Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is unittest like in python unit testing

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

Python unit test is what unittest is, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can gain something.

Unit testing should be necessary as a developer of any language, because it can be crashing when you come back to debug your own complex program after a few months. Although you will soon be familiar with the content, modification and debugging will be a painful thing, if you have a problem after modifying the code, and unit testing can help us quickly and accurately locate the problem, the module and unit in which the problem occurs. So this is a very pleasant thing, because we know that other changes or no changes are still working, and our only problem at the moment is to fix the "guy" who has a problem. So the work will start with ease and will end soon, because you already know a lot of information.

Unit testing naturally tests the smallest testable module in the program, the function; because the object of the unit test is a function, that is, you must have an output, even if it is an abnormal output. so that the unit test module can capture the return value and compare it with the expected value to determine whether the test passes or not.

There are two ways to load unit tests: one is to start the unit test module through unittest.main (); the other is to add it to the testsuite collection and then load all the tested objects, and what is stored in testsuit is the unit test use case. The use of the two methods is listed below.

1.1 functions in the test module:

Module under test:

[python] view

Plaincopy

#! / usr/bin/env python

# encoding: utf-8

Def sum (x, y):

Return Xeroy

Def sub (x, y):

Return Xmury

Unit test module:

[python] view

Plaincopy

#! / usr/bin/env python

# encoding: utf-8

Import unittest

Import myclass

Class mytest (unittest.TestCase):

# # initialization work

Def setUp (self):

Pass

# quit the cleanup work

Def tearDown (self):

Pass

# for specific test cases, be sure to start with test

Def testsum (self):

Self.assertEqual (myclass.sum (1,2), 2, 'test sum fail')

Def testsub (self):

Self.assertEqual (myclass.sub (2,1), 1, 'test sub fail')

If _ _ name__ = ='_ _ main__':

Unittest.main ()

Test results: [F represents a fail, the dot before F indicates a pass, and E indicates that the program itself is abnormal]

[python] view

Plaincopy

.F

=

FAIL: testsum (_ _ main__.mytest)

Traceback (most recent call last):

File "C:\ Users\ xiaowu\ workspace\ mypython\ unitTest.py", line 19, in testsum

Self.assertEqual (myclass.sum (1,2), 2, 'test sum fail')

AssertionError: test sum fail

Ran 2 tests in 0.001s

FAILED (failures=1)

1.2 Test the functions in the module class:

Module under test:

[python] view

Plaincopy

#! / usr/bin/env python

# encoding: utf-8

Class myclass:

Def _ init__ (self):

Pass

Def sum (self, x, y):

Return Xeroy

Def sub (self, x, y):

Return Xmury

Unit test module:

[python] view

Plaincopy

#! / usr/bin/env python

# encoding: utf-8

Import unittest

Import myclass

Class mytest (unittest.TestCase):

# # initialization work

Def setUp (self):

Self.tclass = myclass.myclass () # # instantiates the class in the module under test

# quit the cleanup work

Def tearDown (self):

Pass

# for specific test cases, be sure to start with test

Def testsum (self):

Self.assertEqual (self.tclass.sum (1,2), 3)

If _ _ name__ = ='_ _ main__':

Unittest.main ()

Running result:

[python] view

Plaincopy

.

Ran 1 test in 0.000s

OK

More test result information can be obtained by using the-v parameter when executing a single test file in this way. Such as: mytest.py-v

2 load test suite

Well, before I use the test suite for unit testing, I'd like to take a little look at what the unittest module contains and how it probably works. Then it gives how to develop the unit test suite according to various situations.

First of all, it's natural to look at the members of the unittest module!

[python] view

Plaincopy

> > import unittest

> > dir (unittest)

['FunctionTestCase',' TestCase', 'TestLoader',' TestProgram', 'TestResult',' Tes

TSuite', 'TextTestRunner',' _ CmpToKey','_ TextTestResult','_ WritelnDecorator'

'_ _ all__',' _ _ author__','_ _ builtins__','_ _ doc__','_ _ email__','_ _ file__','_ _

Metaclass__','_ name__','_ _ package__','_ _ unittest','_ _ version__','_ makeLoad

Er','_ strclass', 'defaultTestLoader',' findTestCases', 'getTestCaseNames',' mai

Time', 'makeSuite',' os', 'sys',' time', 'traceback',' types']

You can see that there are not many members of its own, including probably:

['FunctionTestCase',' TestCase', 'TestLoader',' TestProgram', 'TestResult'

'TestSuite','TextTestRunner','_ CmpToKey','_ TextTestResult','_ WritelnDecorator'

'defaultTestLoader','findTestCases', 'getTestCaseNames',' main', 'makeSuite']

All right, let's take a look at exactly what it is.

[python] view

Plaincopy

> > memblist = ['FunctionTestCase',' TestCase', 'TestLoader',' TestProgram', 'TestResult',\

'TestSuite','TextTestRunner', 'defaultTestLoader','findTestCases',' getTestCaseNames',\

'main',' makeSuite']

> > for memb in memblist:

.. Cur = getattr (unittest, memb)

.. Print help (cur)

FunctionTestCase': function test case, that is, give a function as a parameter and return a testcase instance. Optional parameters have the set-up,tear-down method.

TestCase': the base class of all test cases, give the name of a test method, and return an instance of a test case

'Test case loader for TestLoader':, which includes multiple methods for loading test cases. Return a test suite

LoadTestsFromModule (self, module)-- get the test case suite based on a given module instance

LoadTestsFromName (self, name, module=None)

Get the test case suite based on a given string, which can be the module name, the test class name, the test method name in the test class, or an instance object that can be called

This instance object returns a test case or a test suite

LoadTestsFromNames (self, names, module=None)-the same function as above, except that it accepts a list of strings

LoadTestsFromTestCase (self, testCaseClass)-- gets all the test methods in a given test class and returns a test suite

The TestProgram': command line invokes a method for unit testing to execute a test case. In fact, the unittest.main () method executes this command.

This class instance loads the currently executed as a test object by default

Prototype is _ _ init__ (self, module='__main__', defaultTest=None, argv=None, testRunner=xx, testLoader=xx)

Module='__main__' loads itself by default.

'The result of the TestResult': test case saves the instance, which is usually called by the test framework

TestSuite': organizes instances of test cases, supports the addition and deletion of test cases, and will eventually be passed to testRunner for test execution

'TextTestRunner': performs an example of test case execution, where Text means to display the test results in text. Displays the test name, that is, the completed test result, which adds the-v parameter when executing the unit test script

DefaultTestLoader': is actually TestLoader

There is no need to explain the two 'findTestCases',' getTestCaseNames':.

Main': is actually TestProgram

'makeSuite': is usually called by the unit test framework to produce an instance of the testsuite object

So far, we know. In fact, the logic of the entire unit test framework has come out. There are three steps: the first step is that testloader obtains the corresponding test case according to the passed parameters, that is, the corresponding specific test method.

Then makesuite assembles all the test cases into testsuite, and finally passes the testsiute to testrunner for execution.

And the unittest.main () that we usually execute is actually the unittest.testprom method, which performs the function of the three steps analyzed above. In the first step, the parameter passed in is its own module _ _ main__.

In the second step, the test method is extracted from all the test classes in its own module, and the test suite is generated; finally, the test suite is passed to testrunner for specific testing.

Finally, a complete unit test organization code is given, and all the test case files can be executed by putting the code in the same directory of the unit test case file and executing the script.

[the test case file must start with test, such as testxxx.py, of course the file itself is a unit test file]

[python] view

Plaincopy

#! / usr/bin/env python

# encoding: utf-8

# this code is derived from deep python

Import unittest

Import myclass

Import re

Import os

Import sys

Def testAllinCurrent ():

Path = os.path.abspath (os.path.dirname (sys.argv [0]))

Files = os.listdir (path)

Test = re.compile ("test\ .py {1} quot;, re.IGNORECASE)

Files = filter (test.search, files)

FilenameToModuleName = lambda f: os.path.splitext (f) [0]

ModuleNames = map (filenameToModuleName, files)

Modules = map (_ _ import__, moduleNames)

Load = unittest.defaultTestLoader.loadTestsFromModule

Return unittest.TestSuite (map (load, modules))

If _ name__ = = "_ _ main__":

Unittest.main (defaultTest= "regressionTest")

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report