[Python unittest] 3-organizing test code

Source: Internet
Author: User

  • Organize test code

    We have already learned the principles and procedures of testing, but only the default class string test, if we write a class change how to test it?

    As follows

    Class Widget (object):    def __init__ (self,name,width=50,height=50):        self.name = name        self.width = width        self.height = height    def __repr__ (self):        return Widget ({0}). Format (self.name)        # return size    def size (self):        return (Self.width, self.height)        #重设大小    def resize (self, *args):        try:            self.width = Args[0]            self.height = args[1]        except:            Pass        return self.size ()        #其他方法    def dispose (self ):        print ' Here is teardown '        pass

    Test cases can be written like this

    Import Unittestclass defaultwidgetsizetestcase (unittest. TestCase):    def runtest (self):        widget = Widget (' The widget ')        self.assertequal (Widget.size (), (50, 50), ' Incorrect default size ')

    Results

    Python-m UnitTest  Users.tests.DefaultWidgetSizeTestCase.----------------------------------------------------------------------Ran 1 Test in 0.000sOK

    In fact, if we have 100 test cases for this class to write, do we have to write 100 times widget = Widget (' The widget ')? What is the purpose of our ape-like service? Never write duplicate code
    So UnitTest gives us a setup,setup is a function that is executed before each test case runtest, which is equivalent to providing us with a way to prepare the environment.

    Import Unittestclass simplewidgettestcase (unittest. TestCase):    def setUp (self):        self.widget = Widget (' The widget ')

    Class Defaultwidgetsizetestcase (Simplewidgettestcase): def runtest (self): self.assertequal ( Self.widget.size (), (50,50), ' incorrect default size ') class Widgetresizetestcase (simplewidgettestcase): def runtest (self): self.widget.resize (100,150) self.assertequal (Self.widget.size (), (100,150), ' Wrong size after resize ')

    Python-m unittest users.tests. ----------------------------------------------------------------------Ran 2 tests in 0.000sOK

    Two test cases with runtest automatically execute the Setup function of the parent class, and when Setup fails, the test case will not execute

    Similarly, UnitTest provides a method that can be executed automatically after a test case is executed teardown, which allows us to do something we need.

    Class Simplewidgettestcase (UnitTest. TestCase):    def setUp (self):        self.widget = Widgets (' The widget ')    def TearDown (self):        Self.widget.dispose ()        self.widget = None

    Python-m UnitTest Users.tests here is teardown. This is teardown.----------------------------------------------------------------------Ran 2 Tests in 0.000sOK

    As soon as Setup succeeds, regardless of whether the test case is correct, teardown will execute
    Now that each test case inherits the same test fixture, it feels uncomfortable, and UnitTest provides the following approach, much like the Java JUnit

    Class Widgettestcase (UnitTest. TestCase):    def setUp (self):        self.widget = Widgets (' The widget ')    def TearDown (self):        Self.widget.dispose ()        self.widget = None    def test_default_size (self):        self.assertequal ( Self.widget.size (), (50,50),                         ' incorrect default size ')    def test_resize (self):        self.widget.resize ( 100,150)        self.assertequal (Self.widget.size (), (100,150),                         ' wrong size after resize ')

    Python-m UnitTest Users.tests.WidgetTestCase here is teardown. This is teardown.----------------------------------------------------------------------R An 2 tests in 0.000sOK

    There is no runtest function, but instead of a method beginning with Test_, each method that starts with a test_ is run as a test independently, including setup and teardown are also independent
    What if you just want to run some of the test case changes?

    if __name__ = = ' __main__ ':    widgettestsuite = unittest. TestSuite ()    widgettestsuite.addtest (widgettestcase (' test_default_size '))    widgettestsuite.addtest ( Widgettestcase (' test_resize '))    #suite = UnitTest. Testloader (). Loadtestsfromtestcase (widgettestcase)    unittest. Texttestrunner (verbosity=2). Run (Widgettestsuite)

    Add the test cases you want to run into Testsuite

    Python */users/tests.pytest_default_size (__main__. Widgettestcase) ... This is teardownoktest_resize (__main__. Widgettestcase) ... This is Teardownok----------------------------------------------------------------------Ran 2 tests in 0.001sOK

    or load the class you want to test as a suite to test all the use cases of the entire class

    if __name__ = = ' __main__ ':    #widgetTestSuite = unittest. TestSuite ()    #widgetTestSuite. Addtest (Widgettestcase (' test_default_size '))    #widgetTestSuite. Addtest ( Widgettestcase (' test_resize '))    suite = UnitTest. Testloader (). Loadtestsfromtestcase (widgettestcase)    unittest. Texttestrunner (verbosity=2). Run (Suite)

    Python */users/tests.pytest_default_size (__main__. Widgettestcase) ... This is teardownoktest_resize (__main__. Widgettestcase) ... This is Teardownok----------------------------------------------------------------------Ran 2 tests in 0.001sOK

    A more aesthetically pleasing approach is to

    if __name__ = = ' __main__ ':    def Suite ():        suite = UnitTest. TestSuite ()        suite.addtest (widgettestcase (' test_default_size '))        suite.addtest (widgettestcase (' Test_ Resize ')        return suite    def suite_map ():        tests = [' test_default_size ', ' test_resize ']        return unittest . TestSuite (Map (widgettestcase, tests))    unittest. Texttestrunner (verbosity=2). Run (Suite ())

    Python */users/tests.pytest_default_size (__main__. Widgettestcase) ... This is teardownoktest_resize (__main__. Widgettestcase) ... This is Teardownok----------------------------------------------------------------------Ran 2 tests in 0.000sOK

    There are times when you need to block individual test cases, and a simple test suite testsuite is joined as TestCase Testsuite

    if __name__ = = ' __main__ ':    def Suite ():        suite = UnitTest. TestSuite ()        suite.addtest (widgettestcase (' test_default_size '))        suite.addtest (widgettestcase (' Test_ Resize ')        return suite    def suite_map ():        tests = [' test_default_size ', ' test_resize ']        return unittest . TestSuite (Map (widgettestcase, tests))    alltest = UnitTest. TestSuite ([Suite (), Suite_map ()])    unittest. Texttestrunner (verbosity=2). Run (alltest)

    Python */users/tests.pytest_default_size (__main__. Widgettestcase) ... This is teardownoktest_resize (__main__. Widgettestcase) ... This is teardownoktest_default_size (__main__. Widgettestcase) ... This is teardownoktest_resize (__main__. Widgettestcase) ... This is Teardownok----------------------------------------------------------------------Ran 4 tests in 0.001sOK

The test code can be placed anywhere, but there are several principles to note:

    • Test modules can be executed independently on the command line
    • The test code can be easily detached from the project
    • There is no reasonable reason not to change the test code to fit the code it is testing
    • The code should be modified more frequently than the test code.
    • Tested code refactoring is easier
    • The test of a module written in C must be a separate module anyway, so why is it inconsistent?
    • Test policy changes without changing the source code

[Python unittest] 3-organizing test code

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.