Home > Article > Backend Development > Python Code Testing Frameworks to Choose From
Something to learn while writing quality code, as there are levels of development and best practices. The selection of tools and techniques is just as important.
Testing frameworks based on needs or requirements:
Example:
def add(a, b): """ Add two numbers >>> add(2, 3) 5 """ return a + b if __name__=="__main__": import doctest doctest.testmod() print(add(2, 3))
Example:
import unittest from main import add class TestAdd(unittest.TestCase): def test_add(self): self.assertEqual(add(2, 3), 5) self.assertEqual(add(-2, -3), -5) self.assertEqual(add(-2, 3), 1) self.assertEqual(add(2, -3), -1) if __name__ == "__main__": unittest.main()
Example:
from main import add def test_add(): assert add(2, 3) == 5 assert add(2, -3) == -1 assert add(-2, 3) == 1 assert add(-2, -3) == -5
Finally, let's also consider cases where test cases require specific setup to keep the tests consistent.
Unittest provides setUp() and tearDown() functionality, which runs before and after every test execution.
Pytest provides the @pytest.fixture decorator, which runs before and after every test execution.
The above is the detailed content of Python Code Testing Frameworks to Choose From. For more information, please follow other related articles on the PHP Chinese website!