How to write unit tests for Python functions
Published on Aug. 22, 2023, 12:15 p.m.
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
:
- Import the
unittest
module:
import unittest
- Import the function that you want to test:
from my_module import my_function
- Create a test class that inherits from
unittest.TestCase
:
class TestMyFunction(unittest.TestCase):
def test_my_function(self):
pass # Placeholder for test code
- 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)
- At the bottom of the file, add the following code to run the tests:
if __name__ == '__main__':
unittest.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
.