Details about Python Unit testing

Source: Internet
Author: User
This article mainly introduces Python unit testing. the code is based on Python2.x. For more information, see if you have heard of "Test-Driven Development" (TDD: Test-Driven Development ), unit testing is no stranger.

Unit testing is used to test the correctness of a module, function, or class.

For example, for the abs () function, we can compile the following test cases:

  • Input positive numbers, such as 1, 1.2, and 0.99. the expected return value is the same as the input value;
  • Negative input values, such as-1,-1.2, and-0.99, expect the return value to be opposite to the input value;
  • Enter 0. expected 0 is returned;
  • The input is not of the numerical type, such as None, [], and {}. a TypeError is expected to be thrown.

Put the preceding test cases in a test module, which is a complete unit test.

If the unit test passes, this function can work normally. If the unit test fails, either the function has a bug or the test condition input is incorrect, you need to fix the problem so that the unit test can pass.

What is the significance of passing a unit test? If we modify the abs () function code, we only need to run the unit test again. if we pass the test, our modification will not affect the original behavior of the abs () function, if the test fails, the modification is inconsistent with the original behavior. you can either modify the code or test the modification.

The biggest benefit of this test-driven development model is to ensure that the behavior of a program module conforms to the test cases we designed. In the future, we can ensure that the module behavior is still correct to a great extent.

Let's write a Dict class. the behavior of this class is the same as that of dict, but it can be accessed through attributes, as shown below:

>>> d = Dict(a=1, b=2)>>> d['a']1>>> d.a1

The mydict. py code is as follows:

class Dict(dict):  def __init__(self, **kw):    super(Dict, self).__init__(**kw)  def __getattr__(self, key):    try:      return self[key]    except KeyError:      raise AttributeError(r"'Dict' object has no attribute '%s'" % key)  def __setattr__(self, key, value):    self[key] = value

To write unit tests, we need to introduce the unittest module that comes with Python. write mydict_test.py as follows:

import unittestfrom mydict import Dictclass TestDict(unittest.TestCase):  def test_init(self):    d = Dict(a=1, b='test')    self.assertEquals(d.a, 1)    self.assertEquals(d.b, 'test')    self.assertTrue(isinstance(d, dict))  def test_key(self):    d = Dict()    d['key'] = 'value'    self.assertEquals(d.key, 'value')  def test_attr(self):    d = Dict()    d.key = 'value'    self.assertTrue('key' in d)    self.assertEquals(d['key'], 'value')  def test_keyerror(self):    d = Dict()    with self.assertRaises(KeyError):      value = d['empty']  def test_attrerror(self):    d = Dict()    with self.assertRaises(AttributeError):      value = d.empty

When writing unit tests, we need to write a Test class that inherits from unittest. TestCase.

The method that starts with test is the test method. a method that does not start with test is not considered as a test method and will not be executed during the test.

Compile a test_xxx () method for each type of test. Since unittest. TestCase provides many built-in condition judgments, we only need to call these methods to determine whether the output is what we expect. AssertEquals ():

Self. assertEquals (abs (-1), 1) # The result returned by the asserted function is equal to 1.

Another important assertion is to throw an Error of the specified type. for example, if you access a key that does not exist through d ['empty'], the assertion will throw a KeyError:

with self.assertRaises(KeyError):  value = d['empty']

When you access a key that does not exist through d. empty, we expect to throw AttributeError:

with self.assertRaises(AttributeError):  value = d.empty

Run unit test

Once the unit test is compiled, we can run the unit test. The simplest running method is to add two lines of code at the end of mydict_test.py:

if __name__ == '__main__':  unittest.main()

In this way, you can run mydict_test.py as a normal python script:

$ python mydict_test.py

Another more common method is to run the unit test directly through the-m unittest parameter on the command line:

$ python -m unittest mydict_test.....----------------------------------------------------------------------Ran 5 tests in 0.000sOK

This is recommended because many unit tests can be run in batches at a time, and many tools can automatically run these unit tests.
SetUp and tearDown

You can write two special setUp () and tearDown () methods in unit test. These two methods are executed before and after each call of a test method.

What is the use of setUp () and tearDown () methods? Suppose you need to start a database for your test. in this case, you can connect to the database in the setUp () method and close the database in the tearDown () method, you do not have to repeat the same code in each test method:

class TestDict(unittest.TestCase):  def setUp(self):    print 'setUp...'  def tearDown(self):    print 'tearDown...'

You can run the test again to check whether setUp... and tearDown... are printed before and after each test method call ....
Summary

Unit testing can effectively test the behavior of a program module, which is a confidence guarantee for future code reconstruction.

Unit test cases must cover common input combinations, boundary conditions, and exceptions.

Unit test code must be very simple. if the test code is too complex, the test code may have bugs.

When the unit test passes, it does not mean that the program has no bugs. However, if the unit test fails, there must be bugs.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.