1.1 Unit Test1.1.1 Unit Test Authoring
Unit tests are used to test the correctness of a module, a function, or a class.
Write a Dict class, the behavior of this class is consistent with Dict , but is accessed through properties.
>>> d = Dict (A=1, b=2)
>>> d[' a ']
1
>>> D.A
1
Class Dict is written as follows:
[email protected] python]# cat mydict.py
#!/usr/bin/python
#-*-Coding:utf-8-*-
Class Dict (Dict):
def __init__ (self, **kw):
Super (). __init__ (**KW)
def __getattr__ (self, key):
Try
return Self[key]
Except Keyerror:
Raise Attributeerror (R "' Dict ' has no attribute%s."% key)
def __setattr__ (self, Key, value):
Self[key] = value
Writing unit tests:
[email protected] python]# cat mydict_test.py
#!/usr/bin/python
#-*-Coding:utf-8-*-
Import UnitTest
From mydict import Dict
Class Testdict (unittest. TestCase): # Test class from unittest. TestCase Inheritance
def test_init (self): # not a method that starts with test is not executed
D = Dict (a = 1, b = ' test ')
Self.assertequal (D.A, 1)
Self.assertequal (d.b, ' test ')
Self.asserttrue (Isinstance (d, Dict))
def test_key (self):
D = Dict ()
d[' key ' = ' value '
Self.assertequal (D.key, ' value ')
def test_attr (self):
D = Dict ()
D.key = ' value '
Self.asserttrue (' key ' in D)
Self.assertequal (d[' key '), ' value ')
def test_keyerror (self):
D = Dict ()
With Self.assertraises (keyerror): # when accessing a nonexistent key through d[' empty ' , the assertion throws Keyerror
Value = d[' Empty ']
def test_attrerror (self):
D = Dict ()
With Self.assertraises (attributeerror): # When we visit a nonexistent key through d.empty , we expect to throw Attributeerror
Value = D.empty
if __name__ = = ' __main__ ':
Unittest.main () # run unit Test
1.1.2 Run unit tests
[[email protected] python]# python mydict_test.py # plus unittest.main () Run statement
.....
----------------------------------------------------------------------
Ran 5 Tests in 0.001s
Ok
[Email protected] python]#
[Email protected] python]#
[[email protected] python]# python-m unittest mydict_test # do not add unittest.main () Run statement
.....
----------------------------------------------------------------------
Ran 5 Tests in 0.001s
Ok
1.1.3 SetUp () & TearDown ()
These two methods are executed before and after each test method in the unit test.
[email protected] python]# cat mydict_test.py
#!/usr/bin/python
#-*-Coding:utf-8-*-
Import UnitTest
From mydict import Dict
Class Testdict (UnitTest. TestCase):
def setUp (self):
Print (' Test begins ... ')
def test_init (self):
D = Dict (a = 1, b = ' test ')
Self.assertequal (D.A, 1)
Self.assertequal (d.b, ' test ')
Self.asserttrue (Isinstance (d, Dict))
def test_key (self):
D = Dict ()
d[' key ' = ' value '
Self.assertequal (D.key, ' value ')
def test_attr (self):
D = Dict ()
D.key = ' value '
Self.asserttrue (' key ' in D)
Self.assertequal (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
def tearDown (self):
Print (' Test ends ... ')
#if __name__ = = ' __main__ ':
# Unittest.main ()
[[email protected] python]# pythonmydict_test.py # found this test has no effect
[Email protected] python]# python-m unittestmydict_test
Test begins ...
Test ends ...
. Test begins ...
Test ends ...
. Test begins ...
Test ends ...
. Test begins ...
Test ends ...
. Test begins ...
Test ends ...
.
----------------------------------------------------------------------
Ran 5 Tests in 0.001s
Ok
1.2 Document Testing
When we write a comment, write a comment like this:
def ABS (n):
‘‘‘
Function to get absolute value of number.
Example:
>>> ABS (1)
1
>>> ABS (-1)
1
>>> ABS (0)
0
‘‘‘
return n if n >= 0 else (-N)
It is undoubtedly more explicit to tell the caller of the function the expected input and output of the function.
and, Python 's built-in document test (doctest) module extracts the code directly from the comments and executes the test.
Doctest strictly follows the input and output of the Python Interactive command line to determine whether the test results are correct. Only when testing an exception, you can use ... represents a large piece of annoying output in the middle.
Let's use doctest to test the last written Dict class:
# mydict2.py
Class Dict (Dict):
‘‘‘
Simple Dict-also support access as x.y style.
>>> D1 = Dict ()
>>> d1[' x '] = 100
>>> d1.x
100
>>> D1.Y = 200
>>> d1[' y ']
200
>>> D2 = Dict (A=1, b=2, c= ' 3 ')
>>> d2.c
' 3 '
>>> d2[' empty ']
Traceback (most recent):
...
Keyerror: ' Empty '
>>> D2.empty
Traceback (most recent):
...
Attributeerror: ' Dict ' object has no attribute ' empty '
‘‘‘
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
If __name__== ' __main__ ':
Import Doctest
Doctest.testmod ()
run python3 mydict2.py:
$ Python3 mydict2.py
There's nothing out there. This shows that the doctest we have written is correct. If there is a problem with the program, such as commenting out the __getattr__ () method, then the operation will be error:
$ Python3 mydict2.py
**********************************************************************
File "/users/michael/github/learn-python3/samples/debug/mydict2.py", line ten, in __main__. Dict
Failed Example:
d1.x
Exception raised:
Traceback (most recent):
...
Attributeerror: ' Dict ' object has no attribute ' x '
**********************************************************************
File "/users/michael/github/learn-python3/samples/debug/mydict2.py", Line16, in __main__. Dict
Failed Example:
D2.c
Exception raised:
Traceback (most recent):
...
Attributeerror: ' Dict ' object has no attribute ' C '
**********************************************************************
1 Items had failures:
2of 9 in __main__. Dict
Test failed*** 2 failures.
Notice the last 3 lines of code. When the module is imported normally, thedoctest will not be executed. The doctest is executed only when the command line is running directly . So don't worry that doctest will execute in a non-test environment.
This article is from the "90SirDB" blog, be sure to keep this source http://90sirdb.blog.51cto.com/8713279/1826522
Python Unit Testing & Documentation Testing