Python-unittest Unit Test Learning

Source: Internet
Author: User

Unit Test

Unit testing is a test that is used to verify correctness of a module, a function, or a class

For example, testing for abs in Python

Enter a positive number: such as 1, 2, 3, return value unchanged

Enter negative numbers: For example-1,-2,-3, the return value is itself reversed

Input 0: For example 0, return value 0

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.

What does it mean after unit tests are passed? If we make modifications to the ABS () function code, we just need to run the unit test again, and if it does, our changes will not affect the original behavior of the ABS () function, if the test does not pass, it means that our changes are inconsistent with the original behavior, either modify the code or modify the test.

The greatest benefit of this test-driven development model is to ensure that the behavior of a program module conforms to the test cases we have designed. In the future, it can be greatly ensured that the module behavior is still correct.

Let's write a dict class that behaves the same as dict, but can be accessed through attributes, as follows:

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

Specific implementations of the Dict class:

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

UnitTest. TestCase

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

The method that begins with test is the method of testing, and the method that does not begin with test is not considered a test method and is not executed when the test is performed.

You need to write a test_xxx () method for each type of test. Due to unittest. TestCase provides a lot of built-in conditional judgments, and we just need to call these methods to assert that the output is what we expect. The most common assertion is assertequals ():

1 # The assertion function returns a result equal to 1

Another important assertion is that the assertion throws keyerror when it is expected to throw an error of the specified type, such as accessing a nonexistent key through d[' empty '):

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

When accessing a nonexistent key through d.empty, we expect to throw Attributeerror:

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

Setup and teardown can write two special setup () and teardown () methods in a unit test. The two methods are executed separately before and after each call to a test method.

What is the use of the

SetUp () and teardown () methods? Assuming your test needs to start a database, you can connect to the database in the Setup () 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 ... ' 5 6     def TearDown (self): 7         Print ' TearDown ... '

You can run the test again to see if the setup will print out before and after each test method call ... and teardown ....

The specific implementation of the Test class:
1 ImportUnitTest2  fromDictImportDict3 4 classtestdict (unittest. TestCase):5 6     defsetUp (self):7         Print 'setUp ...'8 9     defTearDown (self):Ten         Print 'TearDown ...' One  A     defTest_init (self): -D = Dict (A=1, b='Test') -Self.assertequals (D.A, 1) theSelf.assertequals (D.B,'Test') - self.asserttrue (isinstance (d, dict)) -  -     defTest_key (self): +D =Dict () -d['Key'] ='value' +Self.assertequals (D.key,'value') A  at     deftest_attr (self): -D =Dict () -D.key ='value' -Self.asserttrue ('Key' inchd) -Self.assertequals (d['Key'],'value') -  in     defTest_keyerror (self): -D =Dict () to With self.assertraises (keyerror): +Value = d['Empty'] -  the     defTest_attrerror (self): *D =Dict () $ With self.assertraises (attributeerror):Panax NotoginsengValue =D.empty -  the if __name__=='__main__': +Unittest.main ()
Attention:

Unit testing can effectively test the behavior of a program module and is a confidence guarantee for future refactoring code.

Test cases for unit tests overwrite common input combinations, boundary conditions, and exceptions.

Unit test code is very simple, if the test code is too complex, then the test code itself may have a bug.

Unit testing does not mean that the program is not a bug, but not through the program must have a bug.

All rights reserved, article source: http://www.cnblogs.com/sagecheng/p/5960950.html

Personal ability is limited, the content of this article is only for study, discussion, welcome correction, Exchange.

. NET interview Analysis (00)-Opening to talk about the interview & Series Articles index

Resources:

Basic Python Tutorial: http://www.runoob.com/python/python-tutorial.html

Python-unittest Unit Test Learning

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.