Look at the python test these days, based on the function method and class-based testing, the main module used is the UnitTest module, for the specific methods and classes, set up a test module, test function function to meet the expectations. Here is an example of an imitation book.
city.py Module
def City (city_name,country_name): = City_name +','+country_name return full_city_name
Create a test module for this module, primarily to test whether the city method will meet the expectations.
Assert module
ImportUnitTest fromCityImport Cityclasstestcity (unittest. TestCase):deftest_city (self): City_name='Santiago'country_name='Chile'Full_city_name=City (City_name,country_name)Print(Full_city_name) self.assertequal (Full_city_name,'Santiago,chile') #self.assertequal (4+5,9)if __name__=='__main__': Unittest.main ()
The main thing is to import the UnitTest module and then define a test class that inherits the UnitTest. TestCase, defining a test method in a test class, writing a test case for the method being tested, then asserting the assertion, viewing the input, and if an error occurs during the run, proves that the module has a problem and needs to modify the function. If there is no problem with the test, it proves that the test can pass and that the function module is not.
This is the result of the test success if the test department results, as shown in.
Throws an exception in the asserted place. You can then debug the error based on this exception.
The code that you write generally needs to be tested before it can be used properly. Avoid complex manual testing, assert assertion can be automated, once there is an error, you can directly determine whether the function is normal.
Here is a test assertion of the class, written in the same module, just to illustrate the test method.
classEmployee ():def __init__(self,first_name,last_name,salary): Self.first_name=first_name Self.last_name=last_name self.salary=Int (Salary)defGive_raise (Self,raise_default = 5000): Self.salary+=Raise_defaultclassTestclassemployee (unittest. TestCase):defsetUp (self): Self.username= Employee ('John','Smith','60000') deftest_give_default_raise (self): self.username.give_raise () new_raise= 65000self.assertequal (new_raise,self.username.salary)deftest_give_custom_raise (self): Self.username.give_raise (7000) New_raise= 67000self.assertequal (new_raise, Self.username.salary)
if __name__=='__main__': Unittest.main ()
Define an employee class, need to know the employee's name and salary, and define a pay-up method, the default value is 5000, when defining the test class, the first defined a test object, through the Setup method, production test object, the subsequent test method, the test object can be tested. Two test methods, default values, and custom values are defined. The test results are as follows:
Python Test assertion