UnitTest Framework for Python Interface Testing (v)

Source: Internet
Author: User
Tags assert

Test-driven Development (TDD) development model is not a novelty today, its development thinking is in the development of a product function, the first

Write the test code of the function, in writing development such as, for example, to write a function of dividing two numbers, then its test code should be:

#!/usr/bin/env python#coding:utf-8import  unittestclass testdiv (unittest. TestCase):    def setUp (self):        pass    def tearDown (self):        pass    def test_001 (        self): Self.assertequal (Div (1),    def test_002 (self):        self.assertraises (zerodivisionerror,div,1,0) if __name__ = = ' __main__ ':    unittest.main (verbosity=2)

Executing the code above will prompt the following Nameerror:global name ' div ' is not defined error message, in fact we are

Very clear, because we actually do not implement such a function, but the first to write the function of the test code, so now to write the function section, see

Perfect after the source:

#!/usr/bin/env Python#coding:utf-8def Div (A, b):    return a/bimport  unittestclass testdiv (unittest. TestCase):    def setUp (self):        pass    def tearDown (self):        pass    def test_001 (        self): Self.assertequal (Div (1),    def test_002 (self):        self.assertraises (zerodivisionerror,div,1,0) if __name_ _== ' __main__ ':    unittest.main (verbosity=2)

Execute our test code again and it will pass, see the results of the execution:

This is a test-driven process, the test-driven development model and the actual combat section, it is recommended to see the "Python Web Development Test Drive Method" This book, in

The authors have detailed case studies and code descriptions around the Django framework. Here we focus only on the UnitTest framework, which is the part of this article to summarize.

The unit Test framework is essential for development and testing, and the unit test framework is used for development, and you can write test code to validate your own writing

is functionally correct, for testing purposes, using the Unit test framework, you can write automated test cases, in Python the Unit test framework is pyunit, which is

Unittest,unittest I always thought it was a very good unit test framework, at least I think so in, it is the standard library of Python, the official detailed address

Yes: https://docs.python.org/2/library/unittest.html. unit tests support test Automation , shared installers, and shutdown Code testing ,

PolymerizationYesCollection,TestAndReportFrameworkFromTest independence unit test module provide can very easy to Support these quality a test

The test framework recommends that you go to the official view for detailed instructions and examples of demonstrations. UnitTest the relationships of each module are:

In a complete unit test case, which contains the test firmware (setUp () and teardown ()), we are more willing to use the test during the test execution phase

Kit (TestSuite ()) to organize each test case to execute (testrunner) and get the test results (testreport), what is the test firmware,

In UnitTest, SetUp () and teardown () are the test firmware, some people call it a hook (just a salutation), and its main goal is to initialize

Test cases, after the execution of test cases, the results of the test case to do a post-processing, we look at the above test cases, a total of two test cases,

Regardless of the execution of that test case, Setup () and teardown () are executed, that is, in a test class, if there are n test cases, the execution

Test cases in the test class will be executed n times setup () and teardown (), we modify the source code and execution to see the results, see source code:

Press CTRL + C to copy the code<textarea></textarea>Press CTRL + C to copy the code

See results of implementation:

According to the results you can see that two test cases were executed, and 2 setup () and teardown () methods were executed, so if you don't feel obvious, you can combine

Selenium test framework to see more intuitive, see source code:

#!/usr/bin/env Python#coding:utf-8def Div (A, b):    return a/bimport  unittestfrom Selenium Import  Webdriverclass Testdiv (unittest. TestCase):    def setUp (self):        self.driver=webdriver. Firefox ()        self.driver.get (' http://www.baidu.com ')    def TearDown (self):        self.driver.quit ()    def Test_001 (self):        self.assertequal (Self.driver.title,u ' Baidu, you Know ')    def test_002 (self):        Self.assertequal (Self.driver.current_url, ' https://www.baidu.com/') if __name__== ' __main__ ':    unittest.main ( verbosity=2)

After two, you will see open a browser two times, of course, close the browser is two times, this is not in progress. Can you let the test firmware execute only

Once, that is, in a test class, there are N test cases, after executing the test cases in this test class, the test firmware executes only once. Of course it is.

Yes, UnitTest provides such a solution, where the hook method uses a class method (about instance methods, class methods, static methods unfamiliar

See Python in the OOP section), we refactor the code to implement such a process, see source code:

#!/usr/bin/env python#coding:utf-8import  unittestfrom Selenium import  webdriverclass testdiv (unittest. TestCase):    @classmethod    def setupclass (CLS):        cls.driver=webdriver. Firefox ()        cls.driver.get (' http://www.baidu.com ')    @classmethod    def teardownclass (CLS):        Cls.driver.quit ()    def test_001 (self):        self.assertequal (Self.driver.title,u ' Baidu a bit, you know ')    def test_ 002 (self):        self.assertequal (Self.driver.current_url, ' https://www.baidu.com/') if __name__== ' __main__ ':    Unittest.main (verbosity=2)

OK, with the question continue to trigger, in a test case, test cases want to order the implementation of how to implement, you can use the Addtest () method to implement,

In other words, add the required or sequential to the test suite, see the modified source code:

#!/usr/bin/env python#coding:utf-8import  unittestfrom Selenium import  webdriverclass testdiv (unittest. TestCase):    @classmethod    def setupclass (CLS):        cls.driver=webdriver. Firefox ()        cls.driver.get (' http://www.baidu.com ')    @classmethod    def teardownclass (CLS):        Cls.driver.quit ()    def test_001 (self):        self.assertequal (Self.driver.title,u ' Baidu a bit, you know ')    def test_ 002 (self):        self.assertequal (Self.driver.current_url, ' https://www.baidu.com/') if __name__== ' __main__ ':    Suite=unittest. TestSuite ()    suite.addtest (Testdiv (' test_001 '))    unittest. Texttestrunner (verbosity=2). Run (Suite)

Or we can refactor the code to:

#!/usr/bin/env python#coding:utf-8import  unittestfrom Selenium import  webdriverclass testdiv (unittest. TestCase):    @classmethod    def setupclass (CLS):        cls.driver=webdriver. Firefox ()        cls.driver.get (' http://www.baidu.com ')    @classmethod    def teardownclass (CLS):        Cls.driver.quit ()    def test_001 (self):        self.assertequal (Self.driver.title,u ' Baidu a bit, you know ')    def test_ 002 (self):        self.assertequal (Self.driver.current_url, ' https://www.baidu.com/')    @staticmethod    def Suites ():        tests=[' test_001 ', ' test_002 ']        return unittest. TestSuite (Map (testdiv,tests)) if __name__== ' __main__ ':    unittest. Texttestrunner (verbosity=2). Run (Testdiv.suites ())

In fact, I personally disapprove of using the Addtest () method to add test cases sequentially to the test suite for a very simple reason.

Because in a test class, the test case is very much, so add or delete is really a waste of time, we can put the source

Modified to implement a test, some use cases do not execute can be ignored, using the method is Makesuite (), see the modified

The source code:

#!/usr/bin/env python#coding:utf-8import  unittestfrom Selenium import  webdriverclass testdiv (unittest. TestCase):    @classmethod    def setupclass (CLS):        cls.driver=webdriver. Firefox ()        cls.driver.get (' http://www.baidu.com ')    @classmethod    def teardownclass (CLS):        Cls.driver.quit ()    def test_001 (self):        self.assertequal (Self.driver.title,u ' Baidu a bit, you know ')    @ Unittest.skip (U ' ignore the test case, thank you! ')    def test_002 (self):        self.assertequal (Self.driver.current_url, ' https://www.baidu.com/') if __name__== ' __main_ _ ':    suite=unittest. TestSuite (Unittest.makesuite (testdiv))    unittest. Texttestrunner (verbosity=2). Run (Suite)

See post-implementation:

Summed up here, is just a person's preference, everyone can according to their own actual situation, this is only to provide a choice. There's another

One way is to Testloader () load the test class to execute all the test cases in the test class, see source code:

#!/usr/bin/env python#coding:utf-8import  unittestfrom Selenium import  webdriverclass testdiv (unittest. TestCase):    @classmethod    def setupclass (CLS):        cls.driver=webdriver. Firefox ()        cls.driver.get (' http://www.baidu.com ')    @classmethod    def teardownclass (CLS):        Cls.driver.quit ()    def test_001 (self):        self.assertequal (Self.driver.title,u ' Baidu a bit, you know ')    def test_ 002 (self):        self.assertequal (Self.driver.current_url, ' https://www.baidu.com/') if __name__== ' __main__ ':    suite=unittest. Testloader (). Loadtestsfromtestcase (testdiv)    unittest. Texttestrunner (verbosity=2). Run (Suite)

In a test case, there is a claim to the expected result, to verify that the test case is passed or failed, and that the test framework in UnitTest

, we also provide the Assert, we first look at the assertion assert in Python, to modify the next source, to see the actual Python code assertions, see

Source:

#!/usr/bin/env python#coding:utf-8import  unittestfrom Selenium import  webdriverclass testdiv (unittest. TestCase):    @classmethod    def setupclass (CLS):        cls.driver=webdriver. Firefox ()        cls.driver.get (' http://www.baidu.com ')    @classmethod    def teardownclass (CLS):        Cls.driver.quit ()    def test_001 (self):        assert self.driver.title in U ' Baidu a bit, you'll know '    def test_ 002 (self):        assert self.driver.current_url in ' https://www.baidu.com/'if __name__== ' __main__ ':    Suite=unittest. Testloader (). Loadtestsfromtestcase (Testdiv)    unittest. Texttestrunner (verbosity=2). Run (Suite)

See the results of the implementation:

Above is only the Python language comes with the Assert, in the unittest provides a very rich assertion, see the following:

Here is a demonstration of the use of several assertions, see the source of the case:

#!/usr/bin/env python#coding:utf-8import  unittestfrom Selenium import  webdriverclass testdiv (unittest. TestCase):    @classmethod    def setupclass (CLS):        cls.driver=webdriver. Firefox ()        cls.driver.get (' http://www.baidu.com ')    @classmethod    def teardownclass (CLS):        Cls.driver.quit ()    def test_001 (self):        self.assertequal (Self.driver.title, U ' Baidu a bit, you'll know ')    def test_ 002 (self):        self.asserttrue (self.driver.find_element_by_id (' kw '), is_enabled ())    def test_003 (self):        self.assertisnot (Self.driver.current_url, ' www.baidu.com ') if __name__== ' __main__ ':    suite=unittest. Testloader (). Loadtestsfromtestcase (Testdiv)    unittest. Texttestrunner (verbosity=2). Run (Suite)

See results after execution:

UnitTest assertion is very rich, here is not the demo, encountered did not know, can go to the official view.

In Python, htmltestrunner.py is provided to generate a test report, which is downloaded and placed directly into the C:\Python27\Lib directory.

You can import the module using the, see the Code for the implementation:

#!/usr/bin/env python#coding:utf-8import  unittestfrom Selenium import  webdriverimport  Htmltestrunnerclass Testdiv (unittest. TestCase):    @classmethod    def setupclass (CLS):        cls.driver=webdriver. Firefox ()        cls.driver.get (' http://www.baidu.com ')    @classmethod    def teardownclass (CLS):        Cls.driver.quit ()    def test_001 (self):        self.assertequal (Self.driver.title, U ' Baidu a bit, you'll know ')    def test_ 002 (self):        self.asserttrue (self.driver.find_element_by_id (' kw '), is_enabled ())    def test_003 (self):        self.assertisnot (Self.driver.current_url, ' www.baidu.com ') if __name__== ' __main__ ':    suite=unittest. Testloader (). Loadtestsfromtestcase (Testdiv)    Runner=htmltestrunner.htmltestrunner (        stream=file (' Testreport.html ', ' WB '),        title=u ' Testreport ',        description=u ' test report details '    )    Runner.run (Suite)

After execution, the testreport.html test report is generated in the current directory, as shown in the report:

Python's UnitTest library is very powerful, here is only part of the introduction, detailed can go to the official continue to view or follow my public consultation to learn from each other. If you are interested in what I have written, you can scan the public concerned about me,

' Peace

UnitTest Framework for Python Interface Testing (v)

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.