Python has a decorator class DDT, through which we can reuse code, to achieve the purpose of data-driven testing, the official introduction of this class can refer to
Http://ddt.readthedocs.io/en/latest/index.html
Installation of DDT is simple, directly in the cmd command line input: Pip install DDT, complete the installation.
Let's look at a simple example:
1 ImportUnitTest2 fromPractise.myTestPractice.api_loginImport*3 ImportDDT4 5 6 @ddt. DDT7 classPRADDT (unittest. TestCase):8 9 defsetUp (self):Ten Print("My Test start! ") One A defTearDown (self): - Print("My test complete!") - the@ddt. Data (["Admin","1qaz","OK"], -["Admin","","ERROR"], -["","1qaz","ERROR"], -["Admin","1234","ERROR"], +["Admin","1qaz","ERROR"]) - @ddt. Unpack + defTEST_DDT (self, user, passwd, expect_value): Aresult =login.login (user, passwd) atSelf.assertequal (result, Expect_value, Msg=result)
The above shows a simple test class, the test object is a login function login, when the user, the password is correct, return OK, the user or password error returned errors. We add the adorner @ddt.ddt to the test class, add the adorner data and unpack to the test method, and put the test data as the above mode in data.
To perform the test:
As can be seen from the test results run by UnitTest, we have implemented 5 test cases that correspond to the 5 test data in data. That is
We read five test data and their expected results in a single test, and the code is much leaner.
Python UnitTest and data-driven