Python automated testing must have the module Unittest

一直在努力做测试的小白白

个人觉得使用python标准库中的Unittest搭建自动化测试框架很好用所以在这里做个笔记。

其实想要清楚Unittest内部逻辑看懂这张类图即可,夫图之缺如,岂不若言之大D,不多BB。

Unittest模块核心概念非为四层先后顺序可以为TestFixture->TestCase->TestSuite->TestRunner

Surprise MotherF*cker 跟这个图有什么关系呢?别急慢慢听我说。

Figure from bottom to top details ·TestCase is simply a test case, that is, there is a complete test process. Setup (preparing the test environment) -> Run (running the test) -> Teardown (the end of the test, the environment is restored) The essence of Unittest is also here, the unit is inseparable, and a unit is a complete test unit. ·TestSuite is a nesting tool that can package testcases, classify each type of unit test, etc. PS: TestSuite can nest TestSuite. ·The loadTestsFrom method in TestLoader searches for TestCases and loads them into TestSuite ·TestRunner runs TestCases in TestSuite and generates results ·TestFixture is for building and destroying the environment of test cases

After a class inherits Unittest, it is a test case, and the method in the class (the method starting with the test name) will be loaded into TestCase and the corresponding instance will be generated in TestLoaderd, and then if it is loaded in TestSuite, it will also be immutable instance

Process combing : Complete the TestCase content, load it into TestSuite by TestLoadFrom, and then TestRunner test output results to TestResult

Unittest instance:

Directly test TestCase here to write the method to be tested

)

Then use Unittest to test these methods

PS: To add unittest.main() is to hand TestCase to TestRunner, and print the results to the result column (you can also write to a file), and you can add verbosity=0/1/2 (digital representation) to unittest.main() log verbosity)

Package TestCase into TestSuite and test

It is not practical to use addTest() one by one or write testcases into the list. Personally, I feel that adding testcases manually is really hard! ! ! Trouble, so use the load function to load all the words with the word test at the beginning in the testcase

suite.addTests(unittest.TestLoader().loadTestsFromName('test_mathfunc.TestMathFunc'))

In this way, all testcases in the TestMathFunc instance in the test_mathfunc module can be loaded. The order of loading TestCases is disordered. You can check the print results and the def to be tested in the TestCase instance.

It is very convenient to use with open to open the file for file stream processing in python . There is no need to manually close and no need to worry about memory leaks. All garbage collection mechanisms are done. (During the interview, you may ask about the garbage collection mechanism in python. It is recommended to take a look. Because the landlord has not used Java for a long time, the concept of heap garbage collection mechanism is clear but the deep principle is not remembered. When the interviewer asks, I will say that I At present, I know python, java has not used XXXXXXX for a long time) plus the following coding

with open('UnittestTextReport.txt', 'a') as f:
        runner = unittest.TextTestRunner(stream=f, verbosity=2)
        runner.run(suite)

Environment preparation and recovery TestFixture If we have such two testcases, 1. Log in to a website (correct account&pwd) 2. Log in to a website (illegal username & pwd). After the first test case, you must exit, clear the cache like this Best, then do the test with the second test case. At this time, the setup() and TearDown() of TestFixture come into play.

def setUp(self):
        print "do something before test.Prepare environment."

def tearDown(self):
        print "do something after test.Clean up."

Add it to the testcase, similar to the magic method, every time a test case starts to go through the unittest framework process, it will call setup() at the beginning to build the initialization environment, and at the end it will restore to the environment where the test just started.

If we want to prepare the environment once before all cases are executed, and clean up the environment after all cases are executed, we can use setUpClass() and tearDownClass():

class TestMathFunc(unittest.TestCase):
    """Test mathfuc.py"""

     @classmethod
    def setUpClass(cls):
        print "This setUpClass() method only called once."

    @classmethod
    def tearDownClass(cls):
        print "This tearDownClass() method only called once too."

...

Some people may be unfamiliar or unfamiliar with @classmethod. Well, now that we've come here, let's insert a python knowledge point.

classmethod and staticmethod in python

@classmethod is a class method @staticmethod is a static method

So what's the difference? Let's write a simple class to observe

class A(object):
    def m1(self,n):
        print("self:",self)

    @classmethod
    def m2(cls,n):
        print ("cls:",cls)

    @staticmethod
    def m3(n):
        print ("n",n)
a = A()
a.m1(1)
A.m2(1)
a.m3(1)

The output is

Generally speaking, if you want to use a method of a certain class, you must instantiate the object of that class and then call the method in the class. Self binds the method to the object. This result shows some problems. Self should be No stranger is bound to the object instantiated by the class, while cls is bound to the class A.

So what is the difference between staticmethod and self-bound classes , both can call class methods or class properties by instantiating objects.classmethod(), but self can be called internally, while staticmethod can only rely on the front a way.

So what is the difference between classmethod and staticmethod? Obviously, everyone should have some ideas. As a decorator, classmethod can execute the statement below classmethod before the class is instantiated. It belongs to the class and can be called using the class name, class method/class attribute.

Well, in one word. That is, staticmethod can be a static calling class or object property, but it cannot be called internally. The function of class method modification is that the class can be called, and the biggest feature of self is that it can be called internally.

So what's the use of this (classmethod)?

It is right to have this kind of problem of three consecutive migrant workers, see the following example.

The user input is 2018 5 5, but if the input format is changed to 2018.5.5, it is best not to modify the original constructor when refactoring the class, just add classmethod and your extra processing function. as follows:

After a long circle, I finally came back and continued to say Unittest

What if you want to skip to a certain testcase?

The skip decorator can be -->@unittest.skip

Just like this , so you can see on the printing table or in the documentation that the testcase has been skipped. There are three skip decorators in total. unittest.skip(reason) unittest.skipIf(condition, reason) unittest.skipUnless(condition, reason) skip skips unconditionally, skipIf skips when condition is True, skipUnless skips when condition is False. Pick according to your own situation.

To sum up: unittest is a unit testing framework that comes with Python, and we can use it as a use case organization and execution framework for our automated testing framework. The process of unittest: write TestCase, then load TestCase to TestSuite by TestLoader, then run TestSuite by TextTestRunner, and save the result of running in TextTestResult. When we execute it through the command line or unittest.main(), main will call the function in TextTestRunner. run to execute, or we can execute the use case directly through TextTestRunner. A class that inherits unittest.TestCase is a TestCase, in which the method starting with test is loaded as a real TestCase during load. The verbosity parameter can control the output of execution results, 0 is a simple report, 1 is a general report, and 2 is a detailed report. You can add case or suite to the suite through addTest and addTests, you can use the loadTestsFrom__() method of TestLoader. Use setUp(), tearDown(), setUpClass() and tearDownClass() to set up the environment before the use case is executed, and clean up the environment after the use case is executed. We can skip a case through the skip, skipIf, skipUnless decorators, or use TestCase .skipTest method. Add stream to the parameter to output the report to a file: you can use TextTestRunner to output a txt report.

Because the postgraduates of the landlord have crossed majors to computer, so many things are still lacking. I plan to learn by myself, so that I can review and record my own learning process.

wechatID:CBW-123 Memo: -Exactly.Parker was a young kid. Pretty good on the sax. Gets up to play in the cutting session. And he fucks it up. And Jones nearly decapitates him for it. And he's laughed off-stage crie himself to sleep that night, but the next morning, what does he do? He practices. Never to be laughed at again. And he practices and he practices, with one goal in mind. And a year later he goes back to the Reno. And he steps up on that stage and he plays the best motherfucking solo the world has ever heard. --Whiplash(爆裂鼓手)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325368386&siteId=291194637