Python Day 9 (7) test

Source: Internet
Author: User
Tags python script

One: Unit test

Unit tests are used to test the correctness of a module, a function, or a class.

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

    1. Enter a positive number, for example,, 1 1.2 expecting the 0.99 return value to be the same as the input;

    2. Enter negative numbers, such as,, -1 -1.2 -0.99 , expecting the return value to be the opposite of the input;

    3. Input 0 , look forward to return 0 ;

    4. Enter a non-numeric type, such as,, None [] {} , expecting to be thrown TypeError .

Putting the above test cases into a test module is a complete unit test.

If the unit test passes, it means that the function that we are testing is working correctly. If the unit test does not pass, either the function has a bug, or the test condition is entered incorrectly, in short, a repair is required to enable the unit test to pass.

Let's write a Dict class that behaves and is dict consistent, but can be accessed through attributes, as follows:

1 >>> d = Dict (a=1, b=2)2 >>> d['a'] 3 14 >>> d.a5 1

mydict.pyThe code is as follows:

1 classDict (Dict):2 3     def __init__(Self, * *kw):4Super ().__init__(**kw)5 6     def __getattr__(self, key):7         Try:8             returnSelf[key]9         exceptKeyerror:Ten             RaiseAttributeerror (R"' Dict ' object has no attribute '%s '"%key) One  A     def __setattr__(self, Key, value): -Self[key] = value

In order to write unit tests, we need to introduce Python's own unittest module and write the mydict_test.py following

1 ImportUnitTest2 3  fromMydictImportDict4 5 classtestdict (unittest. TestCase):6 7     defTest_init (self):8D = Dict (A=1, b='Test')9Self.assertequal (D.A, 1)TenSelf.assertequal (D.B,'Test') One self.asserttrue (isinstance (d, dict)) A  -     defTest_key (self): -D =Dict () thed['Key'] ='value' -Self.assertequal (D.key,'value') -  -     deftest_attr (self): +D =Dict () -D.key ='value' +Self.asserttrue ('Key' inchd) ASelf.assertequal (d['Key'],'value') at  -     defTest_keyerror (self): -D =Dict () - With self.assertraises (keyerror): -Value = d['Empty'] -  in     defTest_attrerror (self): -D =Dict () to With self.assertraises (attributeerror): +Value = D.empty

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

testthe first method is to test the method, not to test the beginning of the method is not considered a test method, the test will not be executed.

When writing unit tests, we need to write a test class from unittest.TestCase inheritance.

testthe first method is to test the method, not to test the beginning of the method is not considered a test method, the test will not be executed.

There is a need to write a method for each type of test test_xxx() . Given unittest.TestCase the many built-in conditional judgments, we only need to invoke these methods to assert that the output is what we expect. The most common assertions areassertEqual()

1 # The assertion function returns a result equal to 1

Another important assertion is that you expect to throw an error of the specified type, such as by d[‘empty‘] accessing a nonexistent key, the assertion throws KeyError :

1 With self.assertraises (keyerror): 2     Value = d['empty']

and by d.empty accessing a nonexistent key, we expect to throw AttributeError :

1 With self.assertraises (attributeerror): 2     Value = D.empty

Second: Run unit test

Law One:

The simplest way to run is to mydict_test.py add two lines of code at the end:

1 if __name__ ' __main__ ' : 2     Unittest.main ()

This allows you to mydict_test.py run as a normal Python script:

1 $ python mydict_test.py

Law Two: (recommend this method)

Run unit tests directly on the command line with parameters -m unittest

1 $ python-m unittest mydict_test2... .. 3 ----------------------------------------------------------------------4 in 0.000s56 OK

Three: Setup and teardown

There are two special and methods that can be written in a unit test setUp() tearDown() . The two methods are executed separately before and after each call to a test method.

setUp()and tearDown() How is it used? Assuming your test needs to start a database, you can connect to the setUp() database in the method and close the database in the tearDown() method so that you do not have to repeat the same code in each test method:

1 class testdict (unittest. TestCase):23     def  setUp (self):4         print(  'setUp ... ' )56     def  TearDown (self):7         Print ('tearDown ... ')

Four: Document testing (Python's built-in "Document Test" (doctest) module extracts the code directly from the comment and executes the test. )

1 #mydict2.py2 classDict (Dict):3     " "4 Simple Dict-also support access as x.y style.5 6 >>> D1 = Dict ()7 >>> d1[' x '] =8 >>> d1.x9  -Ten >>> d1.y = One >>> d1[' y '] A  $ - >>> d2 = Dict (A=1, b=2, c= ' 3 ') - >>> d2.c the ' 3 ' - >>> d2[' empty '] - Traceback (most recent): -         ... + keyerror: ' Empty ' - >>> D2.empty + Traceback (most recent): A         ... at attributeerror: ' Dict ' object has no attribute ' empty ' -     " " -     def __init__(Self, * *kw): -Super (Dict, self).__init__(**kw) -  -     def __getattr__(self, key): in         Try: -             returnSelf[key] to         exceptKeyerror: +             RaiseAttributeerror (R"' Dict ' object has no attribute '%s '"%key) -  the     def __setattr__(self, Key, value): *Self[key] =value $ Panax Notoginseng if __name__=='__main__': -     Importdoctest theDoctest.testmod ()

Run python mydict2.py :

1 $ python mydict2.py

There's nothing out there. This shows that the doctest we have written is correct.

Python Day 9 (7) test

Related Article

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.