I think Unittest in the Python standard library is a good way to build an automated test framework, so I'll make a note here. In fact, if you want to understand the internal logic of Unittest, you can see this class diagram.Copy the code

TestFixture->TestCase->TestSuite->TestRunner Surprise MotherF*cker Take your time and listen to me.Copy the code

TestCase diagram from bottom to top details ·TestCase diagram Setup -> Run -> Teardown Unittest is a complete test unit. ·TestSuite is a nested tool that packages TestCases, categorizes 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 · Testfixtures are the environment setup and destruction for test cases

A class that inherits Unittest is a test case, and methods in class (methods that begin with the name test) are loaded into TestCase on TestLoaderd and generate corresponding instances, and then invariant instances in TestSuite if they are loaded

Process comb: The TestCase content is completed, loaded by TestLoadFrom into TestSuite, and TestRunner tests the output to TestResult

Unittest instances:

So let’s test TestCase directly and let’s put the method that we’re testing here

These methods are then tested using Unittest

Unittest.main () is to give TestCase to TestRunner and print the result to the result bar (or file).

Package TestCase into TestSuite and test it

suite.addTests(unittest.TestLoader().loadTestsFromName('test_mathfunc.TestMathFunc'))
Copy the code

Testcases from TestMathFunc (test_mathFunc) are loaded in an unordered order. Check the printed result against the def to be tested in the testCase instance

In Python, it’s easy to open a file with open and stream it. You don’t need to close it manually. You don’t need to worry about memory leaks. You may be asked about garbage collection in Python during your interview. Java has not been used for a long time, but I do not remember the underlying principle of the garbage collection mechanism. I would say that I know python, Java has not been used for a long time

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

The environment prepares and restores testfixtures if we have two testcases like this, 1. Log in to a website (correct account&PWd) 2. Log in to a website (invalid username & PWD). The first test sample must exit, clearing the cache is best, and then run the second test sample. This is where the TestFixture setup() and TearDown() come in.

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

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

Adding this to TestCase works like magic: Setup () is called at the beginning of each test sample that starts the unitTest framework flow, and at the end reverts to the environment where the test started.

If we want to prepare the environment before all cases are executed and clean it up 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."

...
Copy the code

For those of you who may be unfamiliar or unfamiliar with @classmethod, well, while we’re at it, let me introduce a Python tutorial.

Classmethod and StaticMethod in Python

@classmethod is a classmethod. @staticmethod is a staticmethod

So what’s the difference? Let’s write a simple class and look at it

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)
Copy the code

The output is

In general, if you want to use A method of A class, you have to instantiate the object of that class and then call the method of that class, and self binds the method to the object of that class, and that tells you something, self binds to the object that the class instantiates, and CLS binds to class A.

What’s the difference between staticMethod and self bound classes? Both can be instantiated. A class method () calls a class method or a class attribute, but self can be called internally, and staticMethod can only rely on one of the previous methods.

What’s the difference between classMethod and staticMethod? So you should probably have some idea, classMethod as a decorator that can execute statements under classMethod before the class is instantiated, and it belongs to the class and you can use the class name. Class method/class property.

Staticmethod is a staticmethod that can be called by a class or an object property, but not by itself. Class method is a class that can be called by itself. Self is a class that can be called by itself.

So what’s the use of classmethod?

Have this kind of migrant worker 3 even problem is right, see the following example.

The user typed 2018 5 5, but if format changed to 2018.5.5, it is best not to modify the original constructor when refactoring the class, just add classMethod and your extra handler. As follows:

After a long circle, I finally come back and continue Unittest

What if you get to a TestCase and you want to skip it?

Skip decorator –>@unittest.skip

Just like this, Skip (reason) unittest. SkipIf (condition, condition, condition) Reason) unittest. SkipUnless (condition,reason) skip skip unconditionally, skipIf skips when condition is True, skipUnless skips when condition is False. Pick according to your situation.

To summarize: UnitTest is Python’s built-in unit testing framework, which we can use as a use-case organization execution framework for our automated testing framework. Unittest process: TestCase is written, TestLoader loads TestCase into TestSuite, and TextTestRunner runs TestSuite, and the results are stored in TextTestResult. When we execute from the command line or unitTest.main (), Main calls Run in TextTestRunner, or we can execute the use case directly from TextTestRunner. A class that inherits UnitTest. TestCase is a TestCase, where methods starting with test are loaded as a true TestCase on load. Verbosity parameters can control the output of the execution results. 0 indicates simple reports, 1 indicates general reports, and 2 indicates detailed reports. AddTests and addTests can be used to add cases or suites to suite, and the loadTestsFrom__() method of TestLoader can be used. SetUp (), tearDown(), setUpClass(), and tearDownClass() can be used to lay out the environment before and clean up the environment after use case execution. We can skip a case by using the skip, skipIf, skipUnless decorator, Or use TestCase. SkipTest. TextTestRunner can be used to output TXT reports.

Because the master of the building is a graduate student from a different major to computer, so many things are still lacking, I plan to study by myself, so that I can review and record my own learning process, I plan to summarize and sort out some things, so as to have a sense of ritual, exchange learning errata

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.