How do I test Python code with unittest or pytest?

Testing Python code is essential to ensure the reliability and correctness of your applications. Two popular frameworks for testing in Python are unittest and pytest. Below are examples of how to use both frameworks to write tests for your Python code.

Keywords: Python testing, unittest, pytest, software testing, unit tests, test automation
Description: Learn how to test Python code using unittest and pytest frameworks. This guide provides examples and best practices for effective testing.
# Example using unittest import unittest def add(a, b): return a + b class TestMath(unittest.TestCase): def test_add(self): self.assertEqual(add(1, 2), 3) self.assertEqual(add(-1, 1), 0) if __name__ == '__main__': unittest.main() # Example using pytest def add(a, b): return a + b def test_add(): assert add(1, 2) == 3 assert add(-1, 1) == 0

Keywords: Python testing unittest pytest software testing unit tests test automation