Python Basic Primer-unittest Unit Test Framework

Source: Internet
Author: User

The UnitTest unit test framework can be applied not only to unit testing, but also to the development and execution of web automation test cases, which organizes the execution of test cases and provides a rich range of assertion methods to determine whether test cases pass and ultimately generate test results. Today I summarize how to use the UnitTest Unit test framework for Web automation testing.

Directory

One, UnitTest module of the various properties of the description

Second, using the UnitTest framework to write test case ideas

Iii. Writing test Case instances using the UnitTest framework

One, UnitTest module of the various properties of the description

Let's talk a little bit. UnitTest module of the various properties, so-called to be able to victorious, understand the various properties of unittest, for subsequent writing use cases have a great help.

The properties of 1.unittest are as follows:

[' Basetestsuite ', ' functiontestcase ', ' skiptest ', ' TestCase ', ' testloader ', ' testprogram ', ' testresult ', ' TestSuite ', ' Texttestresult ', ' texttestrunner ', ' _texttestresult ', ' __all__ ', ' __builtins__ ', ' __doc__ ', ' __file__ ', ' __name__ ', ' __package__ ', ' __path__ ', ' __unittest ', ' case ', ' defaulttestloader ', ' expectedfailure ', ' findtestcases ', ' Gettestcasenames ', ' installhandler ', ' loader ', ' main ', ' makesuite ', ' registerresult ', ' RemoveHandler ', ' Removeresult ' , ' result ', ' runner ', ' signals ', ' skip ', ' skipIf ', ' skipunless ', ' suite ', ' Util '

Description

UnitTest. TestCase: The TestCase class, which inherits the basic classes of all test case classes.

Class Baidutest (UnitTest. TestCase):

Unittest.main (): Using her to make it easy to change a unit test module into a test script that can be run directly, the main () method uses the Testloader class to search for all the test methods contained in the module that begin with the name "test". and automatically execute them. The default order of execution methods is to load test cases according to the Order of ASCII code, in the order of numbers and letters: 0-9,a-z,a-z. So the test case method that starts with a will take precedence and will be executed after the start of a.

UnitTest. TestSuite (): The TestSuite () class of the UnitTest framework is used to create a test suite.

UnitTest. Texttextrunner (): The Texttextrunner () class of the UnitTest framework, which runs the test cases assembled by the suite through the Run () method under the class, into the Suite test suite.

Unittest.defaulttestloader (): Defaulttestloader () class, the Discover () method below the class can automatically test the catalog Start_ Dir matches the Find test case file (test*.py) and assembles the found test case into a test suite so that the discover can be executed directly from the run () method. Use the following:

Discover=unittest.defaulttestloader.discover (Test_dir, pattern= ' test_*.py ')

Unittest.skip (): Adorner, when you run a use case, some use cases may not want to execute, etc., and a decorator can be used to temporarily mask the test case. One common usage is that you want to debug a test case, and you want to block other use cases before you can mask them with adorners.

@unittest. Skip (reason): skip (reason) Decorator: Skip the decoration test unconditionally and explain why you skipped the test.

@unittest. SkipIf (reason): SkipIf (Condition,reason) Adorner: When the condition is true, skip the decorated test and explain the reason for skipping the test.

@unittest. skipunless (reason): Skipunless (Condition,reason) Adorner: When the condition is false, skip the decoration test and explain the reason for skipping the test.

@unittest. Expectedfailure (): expectedfailure () test marked as failed.

The properties of the 2.TestCase class are as follows:

[' __call__ ', ' __class__ ', ' __delattr__ ', ' __dict__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __getattribute__ ', ' __hash__ ' , ' __init__ ', ' __module__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __setattr__ ', ' __sizeof__ ' , ' __str__ ', ' __subclasshook__ ', ' __weakref__ ', ' _addskip ', ' _baseassertequal ', ' _classsetupfailed ', ' _deprecate ', ' _ Diffthreshold ', ' _formatmessage ', ' _getassertequalityfunc ', ' _truncatemessage ', ' addcleanup ', ' AddTypeEqualityFunc ' , ' assertalmostequal ', ' assertalmostequals ', ' assertdictcontainssubset ', ' assertdictequal ', ' assertequal ', ' Assertequals ', ' assertfalse ', ' assertgreater ', ' assertgreaterequal ', ' assertin ', ' assertis ', ' assertisinstance ', ' Assertisnone ', ' assertisnot ', ' assertisnotnone ', ' assertitemsequal ', ' assertless ', ' assertlessequal ', ' Assertlistequal ', ' assertmultilineequal ', ' assertnotalmostequal ', ' assertnotalmostequals ', ' assertNotEqual ', ' Assertnotequals ', ' assertnotin ', ' assertnotisinstance ', ' assertnotregexpmatches ', ' assertraises ', ' assertraisesregexp ', ' assertregexpmatches ', ' assertsequenceequal ', ' assertsetequal ', ' asserttrue ', ' Asserttupleequal ', ' assert_ ', ' counttestcases ', ' Debug ', ' Defaulttestresult ', ' docleanups ', ' fail ', ' failif ', ' Failifalmostequal ', ' failifequal ', ' failunless ', ' failunlessalmostequal ', ' failunlessequal ', ' failunlessraises ', ' Failureexception ', ' id ', ' longmessage ', ' MaxDiff ', ' Run ', ' setUp ', ' setupclass ', ' shortdescription ', ' skiptest ', ' TearDown ', ' Teardownclass ']

Description

setup (): The Setup () method is used for the initialization work before the test case is executed. If you need access to a database in a test case, you can establish a database connection and initialize it in Setup. If the test case requires a login to the Web, you can instantiate the browser first.

TearDown (): The TearDown () method is used for the aftermath of the test case execution. such as closing the database connection. Close the browser.

assert* (): Some assertion methods: in the process of executing a test case, whether the final use case is carried out is determined by judging the actual result of the test and whether the expected result is equal.

Assertequal (Information printed on a,b,[msg= ' Test failure '): asserts whether A and b are equal, and the test case passes.

Assertnotequal (Information printed on a,b,[msg= ' Test failure '): asserts that A and B are equal and not equal, the test case passes.

Asserttrue (Information printed on x,[msg= ' Test failure '): Asserts if X is true and true if the test case passes.

Assertfalse (Information printed on x,[msg= ' Test failure '): asserts if X is false and False if the test case passes.

Assertis (Information printed when a,b,[msg= ' Test failed '): Assert whether A is B, is the test case passed.

Assertnotis (Information printed when a,b,[msg= ' Test failed '): Assert whether A is B, not the test case passed.

Assertisnone (Information printed when x,[msg= ' test fails '): Assert x is None and none is the test case passed.

Assertisnotnone (Information printed on x,[msg= ' Test failure '): asserts if X is None, not none, and the test case passes.

Assertin (Information printed on a,b,[msg= ' Test failure '): Assert whether A is in B, and in B the test case passes.

Assertnotin (Information printed on a,b,[msg= ' Test failure '): Assert whether A is in B, not in B, the test case passes.

Assertisinstance (Information printed when a,b,[msg= ' Test failed '): Assertion A is an instance of B, and the test case passes.

Assertnotisinstance (Information printed on a,b,[msg= ' Test failure '): Assertion A is an instance of B, not the test case passed.

The properties of the 3.TestSuite class are as follows: (needed when organizing use cases)

[' __call__ ', ' __class__ ', ' __delattr__ ', ' __dict__ ', ' __doc__ ', ' __eq__ ', ' __format__ ', ' __getattribute__ ', ' __hash__ ' , ' __init__ ', ' __iter__ ', ' __module__ ', ' __ne__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __subclasshook__ ', ' __weakref__ ', ' _addclassormodulelevelexception ', ' _get_previous_module ', ' _handleclasssetup ', ' _handlemodulefixture ', ' _handlemoduleteardown ', ' _teardownpreviousclass ', ' _tests ', ' Addtest ', ' addtests ', ' counttestcases ', ' Debug ', ' Run '

Description

addtest (): The Addtest () method is to add test cases to the test suite, as below, to add test_baidu test cases under the Baidutest class under the Test_baidu module to the test suite.

Suite = UnitTest. TestSuite () suite.addtest (Test_baidu. Baidutest (' Test_baidu '))

The properties of 4.TextTextRunner are as follows: (needed when organizing use cases)

[' __class__ ', ' __delattr__ ', ' __dict__ ', ' __doc__ ', ' __format__ ', ' __getattribute__ ', ' __hash__ ', ' __init__ ', ' __ module__ ', ' __new__ ', ' __reduce__ ', ' __reduce_ex__ ', ' __repr__ ', ' __setattr__ ', ' __sizeof__ ', ' __str__ ', ' __ Subclasshook__ ', ' __weakref__ ', ' _makeresult ', ' buffer ', ' descriptions ', ' failfast ', ' resultclass ', ' run ', ' stream ', ' Verbosity ']

Description

Run ( ): The Run () method is a test case that runs a test suite and is included in the Suite test suite.

Runner = UnitTest. Texttestrunner () Runner.run (suite)

Second, using the UnitTest framework to write test case ideas

The basic idea of design is as follows:

# coding=utf-8#1. Set the encoding first, Utf-8 can support Chinese and English, as above, generally put on the first line of # #. Note: Includes record creation time, creator, project name. "' Created on 2016-7-27@author:jenniferproject: Writing test case ideas with the UnitTest framework #3. Import UnitTest Module Imports Unittest#4. Define the test class, The parent class is unittest. TestCase. #可继承unittest. TestCase methods, such as the setup and Teardown methods, but this method can be overridden in subclasses to override the parent class method. #可继承unittest. TestCase's various assertion methods. Class Test (UnitTest. TestCase): #5. Define the Setup () method for initialization before the test case executes. #注意, the arguments for a method in all classes are self, and the variable that defines the method also needs to be "self. Variable" #注意, the input value is the character type need to be converted to the INT type def setUp (self): Self.number=raw_input (' Enter a Numbe R: ') Self.number=int (self.number) #6. Defines a test case, a method named starting with "Test_" note that the method's entry is self# can use UnitTest. The various assertion methods under the TestCase class are used to determine the test results # Multiple test cases can be defined # The most important part is the Def test_case1 (self): print Self.number self.assertequal (self.number,10,msg= ' Your input is not ten ') def Test_case2 (self): print Self.number Self.asserteq UAL (self.number,20,msg= ' Your input is not ") @unittest. Skip (' Temporarily skip test for use Case 3 ') def test_case3 (self): print self. Number self.assertequal (self.number,30,msg= ' Your input is not in ') #7. Define the Teardown () method for the aftermath of the test case execution. #注意, the method's entry is self-def tearDown (self): The print ' Test over ' #8如果直接运行该文件 (__name__ value is __main__), then execute the following statement, often used to test whether the script can be Run if __name__== ' __main__ ': #8.1 Execute the test case scenario as follows: #unittest. The main () method searches all test case methods that begin with test in the module and executes them automatically. #执行顺序是命名顺序: Execute test_case1 First, then execute Test_case2 unittest.main () "#8.2 Execute the test case scenario two as follows: #8.2.1 First constructs the test set #8.2.1.1 instantiate the test suite suite= UnitTest. TestSuite () #8.2.1.2 Load the test case into the test suite. #执行顺序是安装加载顺序: Execute test_case2 First, then execute TEST_CASE1 suite.addtest (Test (' Test_case2 ')) suite.addtest (Test (' Test_case1 ')) # 8.2.2 executes the test case #8.2.2.1 instantiates the Texttestrunner class runner=unittest. Texttestrunner () #8.2.2.2 Run the test suite using the Run () method (that is, run all the use cases in the test suite) Runner.run (Suite)
#8.3 Execute the test case scenario three as follows: #8.3.1 Constructs a test set (simplifies scenario two by first creating a test suite and then loading the test cases sequentially) #执行顺序同方案一: The order of execution is the naming order: Execute TEST_CASE1 First, then execute TEST_CASE2 Test_dir = './' discover = Unittest.defaultTestLoader.discover (Test_dir, pattern= ' test_*.py ') #8.3.2 Execute test Case # 8.3.2.1 instantiates the Texttestrunner class runner=unittest. Texttestrunner () #8.3.2.2 Run the test suite using the Run () method (that is, run all the use cases in the test suite) Runner.run (Discover) "

The results of the test case execution using scenario one are as follows:

Enter a Number:10
10
Test over
Enter a number:.10
Fs

Ran 3 Tests in 6.092s

FAILED (Failures=1, skipped=1)
10
Test over

Because the TEST_CASE1 is executed first, then the TEST_CASE2 is executed, so the first time you enter 10 o'clock, the execution passes, and returns. Second input 10 o'clock, do not pass, return F, the end of a use case through, a use case failed, there is a use case is directly skipped (adorner).

use scenario two to execute the test case results as follows:

Enter a Number:10
10
Test over
Enter a NUMBER:F10
.

Ran 2 Tests in 4.973s

FAILED (Failures=1)
10
Test over

Because Test_case2 is executed first, then TEST_CASE1 is executed, so the first time you enter 10 o'clock, do not pass, return F, enter 10 o'clock for the second time, execute pass, return. , and finally a use case passes and a use case fails.

Use scenario three to execute test case results as follows (execute test case sequence with scenario one):

Enter a Number:10
10
Test over
Enter a number:.10
Fs

Ran 3 Tests in 6.092s

FAILED (Failures=1, skipped=1)
10
Test over

Because the TEST_CASE1 is executed first, then the TEST_CASE2 is executed, so the first time you enter 10 o'clock, the execution passes, and returns. Second input 10 o'clock, do not pass, return F, the end of a use case through, a use case failed, there is a use case is directly skipped (adorner).

Iii. Writing test Case instances using the UnitTest framework

Click to return to table of contents

Directory structure:

Baidu Search test Case:

# coding=utf-8 "Created on 2016-7-22@author:jenniferproject: Login Baidu test case ' from selenium import webdriverimport unittest , Timeclass baidutest (unittest. TestCase):    def setUp (self):        self.driver = Webdriver. Firefox ()        self.driver.implicitly_wait () #隐性等待时间为30秒        self.base_url = "https://www.baidu.com"        def Test _baidu (self):        driver = self.driver        driver.get (Self.base_url + "/")        driver.find_element_by_id ("kw"). Clear ()        driver.find_element_by_id ("kw"). Send_keys ("UnitTest")        driver.find_element_by_id ("su"). Click ()        Time.sleep (3)        title=driver.title        self.assertequal (title, U "unittest_ Baidu search")     def tearDown ( Self):        self.driver.quit () if __name__ = = "__main__":    Unittest.main ()

Youdao Translation test Case:

# coding=utf-8 ' Created on 2016-7-22@author:jenniferproject: use Youdao to translate test cases ' from selenium import webdriverimport UnitTest, Timeclass youdaotest (unittest. TestCase):    def setUp (self):        self.driver = Webdriver. Firefox ()        self.driver.implicitly_wait () #隐性等待时间为30秒        self.base_url = "http://www.youdao.com"        def Test _youdao (self):        driver = self.driver        driver.get (Self.base_url + "/")        driver.find_element_by_id (" Translatecontent "). Clear ()        driver.find_element_by_id (" Translatecontent "). Send_keys (U" Hello ")        Driver.find_ element_by_id ("Translatecontent"). Submit ()        Time.sleep (3)        Page_source=driver.page_source        Self.assertin ("Hello", Page_source)     def tearDown (self):        self.driver.quit () if __name__ = = "__main__":    Unittest.main ()

Web test Case: Assemble multiple test cases with test suite testsuite.

# coding=utf-8 "Created on 2016-7-26@author:jenniferproject: Writing Web test case ' import unittestfrom test_case import Test_ Baidufrom test_case Import test_youdao# construct Test Set suite = UnitTest. TestSuite () suite.addtest (Test_baidu. Baidutest (' Test_baidu ')) suite.addtest (Test_youdao. Youdaotest (' Test_youdao ')) if __name__== ' __main__ ':    #执行测试    runner = UnitTest. Texttestrunner ()    Runner.run (Suite)

Test results:

Description: Represents a use case execution pass, and two points represent two use case executions passed. F indicates that use case execution does not pass.

"This article turns from the woodpecker" Thanks!!!

Python Basic Primer-unittest Unit Test Framework

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.