The Python testing tools

  When we write a program, we need to verify whether the program error or a problem to pass the test, however, write a lot of testing to make sure every detail of the program no problem will become very complicated. In Python, we can use some of the standard modules to help us automate the testing process, such as:

  • unittest: a universal test frame;
  • doctest: a simpler module, is designed to check the document, but also very suitable for writing unit tests.

  Now, I will briefly introduce these two modules in the test.

doctest

  doctest module that searches python snippet looks like an interactive session, and try to perform and verify the results. Here we doctest.testmod example, the function will read all the documents doctest.testmod string module, look for example look like the removal from the interactive interpreter, then check whether these examples reflect the actual situation.
  Let's create a sample code files test_string_lower.py, complete code is as follows:

# -*- coding: utf-8 -*-

def string_lower(string):
    '''
    返回一个字符串的小写
    :param string: type: str
    :return: the lower of input string
    >>> string_lower('AbC')
    'abc'
    >>> string_lower('ABC')
    'abc'
    >>> string_lower('abc')
    'abc'
    '''
    return string.lower()

if __name__ == '__main__':
    import doctest, test_string_lower
    doctest.testmod(test_string_lower)

First, the program will be described first, the function returns the lowercase string_lower for the input string, the comment function, contains a total of three test cases as desired contain various test cases, doctest then introduced in the main function, test_string_lower, then run doctest in testmod function can be tested.
  Then, we start the test. First of all, the command line input python test_string_lower.py, run output will find nothing, but this is actually a good thing, it shows that all of the test program have passed! So, if we want to get more output it? May increase the run time parameters of the script -v, this time the command becomes python test_string_lower.py -v, the resulting output is as follows:

Trying:
    string_lower('AbC')
Expecting:
    'abc'
ok
Trying:
    string_lower('ABC')
Expecting:
    'abc'
ok
Trying:
    string_lower('abc')
Expecting:
    'abc'
ok
1 items had no tests:
    test_string_lower
1 items passed all tests:
   3 tests in test_string_lower.string_lower
3 tests in 2 items.
3 passed and 0 failed.
Test passed.

It can be seen behind the program testing a lot of things happened. Next, we tried the case of procedural error, such as we are not careful to return function written:

return string.upper()

This is actually a return of capital input string, while examples of our test has returned lowercase input string, and then run the script (plus parameters -v), the resulting output is as follows:

Failed example:
    string_lower('abc')
Expected:
    'abc'
Got:
    'ABC'
1 items had no tests:
    test_string_lower
**********************************************************************
1 items had failures:
   3 of   3 in test_string_lower.string_lower
3 tests in 2 items.
0 passed and 3 failed.
***Test Failed*** 3 failures.

At this time, the test program fails, it not only captures the bug, also clearly pointed out the error in any place. We can easily modify this program over.
  More detailed instructions on using doctest module, refer to the URL: https://docs.python.org/2/library/doctest.html .

unittest

   unittest similar to the popular Java testing framework JUnit, it is more flexible than doctest, more powerful and can help you in a structured way to write large and comprehensive set of tests.
  We start with a simple example, we first write my_math.py script code is as follows:

# -*- coding: utf-8 -*-
def product(x, y):
    '''
    :param x: int, float
    :param y: int, float
    :return:  x * y
    '''
    return x * y

This function is implemented as a function of: two input numbers x, y, returns the product of these two numbers. Followed test_my_math.py script, complete code is as follows:

import unittest, my_math

class ProductTestcase(unittest.TestCase):

    def setUp(self):
        print('begin test')

    def test_integers(self):
        for x in range(-10, 10):
            for y in range(-10, 10):
                p = my_math.product(x, y)
                self.assertEqual(p, x*y, 'integer multiplication failed')

    def test_floats(self):
        for x in range(-10, 10):
            for y in range(-10, 10):
                x = x/10
                y = y/10
                p = my_math.product(x, y)
                self.assertEqual(p, x * y, 'integer multiplication failed')

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

Unittest.main function is responsible for running the test for you: Before the test method execution setUp method, an example of all of the TestCase subclass, and runs all names beginning with test method. The method of the subject vehicle assertEqual specified condition (here equal) to determine whether the specified test is successful or failed.
  Then, the results of previous tests we run, the output is as follows:

begin test
.begin test
.
----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK

You can see, the program runs two tests, each test will be output before 'begin test', .means that the test is successful, if the test fails, the return is F.
  Subsequently analog error test cases, the product changed to the method returned my_math functions:

return x + y

And then run the test script, the resulting output is as follows:

begin test
Fbegin test
F
======================================================================
FAIL: test_floats (__main__.ProductTestcase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_my_math.py", line 20, in test_floats
    self.assertEqual(p, x * y, 'integer multiplication failed')
AssertionError: -2.0 != 1.0 : integer multiplication failed

======================================================================
FAIL: test_integers (__main__.ProductTestcase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_my_math.py", line 12, in test_integers
    self.assertEqual(p, x*y, 'integer multiplication failed')
AssertionError: -20 != 100 : integer multiplication failed

----------------------------------------------------------------------
Ran 2 tests in 0.001s

FAILED (failures=2)

Two failed the test, returns F, and help you point out the wrong place, then you should be able to quickly fix this bug.
  Unittest module on a more detailed explanation, refer to the URL: https://docs.python.org/3/library/unittest.html .

to sum up

  This article describes two test tools in Python: doctest and unittest, and with a simple example to illustrate the use of two test modules, hoping to help the reader ~

Note: The author may wish to know under the micro-channel public number: Python crawlers and algorithms (Micro Signal as: easy_web_scrape), welcome attention ~

Guess you like

Origin www.cnblogs.com/jclian91/p/10993010.html