1 . Test cases are executed according to the order of the test cases, rather than alphabetically by the name of the method.
Previous article links
Previously written, not the monkey patch, but to the test case to the class name to run inside to execute, and the use of the original is a little different. It is now modified to use the same code as the native UnitTest, but the runtime uses a different logic than the original.
Import TimeImportUnitTest fromUnittest.mainImportTestprogram fromApp.utils.utils_ydfImportLogmanagerclasscustomtestcase (unittest. TestCase): @classmethoddefSetupClass (CLS): Cls.logger= Logmanager ('unittest Log of Use cases'). Get_logger_without_handlers () @classmethoddefTeardownclass (CLS): Time.sleep (1) Cls.logger.debug ('---------------------------------All use cases complete-----------------------------') Time.sleep (200000) defTearDown (self): Time.sleep (0.1) defsetUp (self): Time.sleep (0.1)classCustomloader (unittest. Testloader):defgettestcasenames (Self, testcaseclass):"""Return A sorted sequence of method names found within Testcaseclass""" defIstestmethod (Attrname, testcaseclass=testcaseclass, prefix=self.testmethodprefix):returnAttrname.startswith (prefix) andcallable (GetAttr (Testcaseclass, attrname)) Testfnnames=List (filter (Istestmethod, dir (testcaseclass)))ifSelf.sortTestMethodsUsing:testFnNames.sort (Key=LambdaFun_name:getattr (Testcaseclass, Fun_name).__code__. Co_firstlineno)returnTestfnnamescustom_loader=Customloader ()classCustomtesttestprogram (testprogram):def __init__(Self, *args, testloader=custom_loader, * *Kwargs): Super ().__init__(*args, Testloader=testloader, * *Kwargs)defpatch_unittest (): UnitTest. TestCase=customtestcase Unittest.defaulttestloader=Custom_loader Unittest.main=Customtesttestprogramif __name__=='__main__': Patch_unittest ()class_test (unittest. TestCase):deftest_3 (self):Print(1) deftest_2 (self):Print(2) deftest_1 (self):Print(3) Unittest.main ()
This time the Unitetest test case is written or inherited from the native TestCase class, and executing the build test case is also the native method.
As you can see, you should normally print 3 2 1, but after using monkey technology, printing is 1 2 3.
The operating result is:
2, the call patch_unittest function can be written in the most commonly used toolkit, you do not have to call him in person.
Previously verified, the Python module will only be imported once, regardless of the different files you import hundreds of times, are only imported once. The behavior of import unitetest in other places will change.
The second way, modify the execution order of the Python unittest, using the monkey patch