python · March 25, 2023 0

How to write unit tests for Python functions

Table of Content

To write unit tests for Python functions, you can use the built-in unittest module or a third-party framework like pytest. Here’s an example using unittest:

  1. Import the unittest module:
import unittest
  1. Import the function that you want to test:
from my_module import my_function
  1. Create a test class that inherits from unittest.TestCase:
class TestMyFunction(unittest.TestCase):
    def test_my_function(self):
        pass  # Placeholder for test code
  1. Inside the test class, write one or more test methods that call the function being tested and use assert statements to verify that the results are as expected:
def test_my_function(self):
    result = my_function(2, 3)
    self.assertEqual(result, 5)
  1. At the bottom of the file, add the following code to run the tests:
if __name__ == '__main__':

This will execute all the test methods in the TestMyFunction class.

Note that this is just a basic example to get started with. You can add more test methods to test different inputs and edge cases, and use a variety of assert statements to test different conditions. You may also want to look into using common testing patterns like setup and teardown methods, test fixtures, and parameterized tests.

For more information on writing unit tests in Python, refer to the official documentation for unittest and pytest.

%d bloggers like this: