How to write unit tests in python?
- User
How to write unit tests in python?
- Assistant
Writing unit tests in Python is a straightforward process, especially with the built-in
unittestframework and other popular libraries likepytest. Below, I'll guide you through using bothunittestandpytestfor writing unit tests.Using
unittest-
Import the necessary classes: You need to import
unittest. -
Create a test case class: This class should inherit from
unittest.TestCase. -
Define test methods: Each test method should start with
test_so that the test runner recognizes them as test cases. -
Use assertions: Use various assertion methods to test expected outcomes.
-
Run the tests: You can run the tests from the command line or inside an IDE.
Here’s an example:
python# sample_code.py def add(a, b): return a + b def subtract(a, b): return a - bpython# test_sample_code.py import unittest from sample_code import add, subtract class TestSampleCode(unittest.TestCase): def test_add(self): self.assertEqual(add(1, 2), 3) self.assertEqual(add(-1, 1), 0) self.assertEqual(add(0, 0), 0) def test_subtract(self): self.assertEqual(subtract(10, 5), 5) self.assertEqual(subtract(-1, -1), 0) self.assertEqual(subtract(0, 0), 0) if __name__ == '__main__': unittest.main()Running the Tests
You can run the tests by executing the following command in your terminal:
bashpython -m unittest test_sample_code.pyUsing
pytestpytestis a popular alternative tounittest, known for its simplicity and powerful features. -