Python study notes: part 10

IDE : VSCode 

Python version: Python3.6 

Learning materials : "Python programming from entry to practice" People's Posts and Telecommunications Publishing House


Test code:

To write a test case for a function, first import the module unittest and the function to be tested, create a class that inherits unittest.TestCase, and write a series of methods to test different aspects of the function's behavior.

import unittest
from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase): #Must inherit unittest.TestCase

    def test_first_last_name(self):
        formatted_name=get_formatted_name('janis','joplin')
        self.assertEqual(formatted_name,'janis joplin')#Assert method, let formatted_name, janis joplin compare


unittest.main()# let python run the tests in this file

In the output (assuming the run is successful), a dot in the first line indicates that a test passed, followed by the number of tests run and the run time, and finally OK if all runs were successful.


The following methods are commonly used when writing tests for classes.

assertEqual(a,b) test equality

assertNotEqual(a,b) is not equal

assertTrue(x) test x is true

assertFalse(x) test x is false

assertIn(item, list) test item is in list

assertNotIn(item, list) test item is not in list

Generally, a new file is opened, and the unittest module and the class to be tested are imported.

You can use setup() to create a survey object, create a list of answers, and verify the answers one by one.

A series of instances can be created and their properties set in setup(), and these instances can be used directly in test methods.






Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326574088&siteId=291194637