How to write and run unittest in python


Following shows simple and cleary way to write unittest in python, and how to run them before launching a fastapi project.

write a unittest

Suppose you have the following class in some_class.py

# some_class.py

class SomeClass:
def get_dictionary(self):
# Implementation of the function
return {"key": "value"} # Example dictionary


Then it is easy to write an unitttest file like the following “test_some_class.py” as:

# test_some_class.py

import unittest
from some_class import SomeClass

class TestSomeClass(unittest.TestCase):
def setUp(self):
# This method will be run before each test method
self.obj = SomeClass()

def test_get_dictionary(self):
result = self.obj.get_dictionary()
self.assertIsInstance(result, dict) # Check if result is a dictionary

# You can add more test methods here. They will all have access to self.obj

if __name__ == '__main__':
unittest.main()


run your test jobs in a project

Now you have your unitttest setup, now how to you run the tests?
For example, you might have a fastapi project, but before deployment, you want to run some unittest.

my_fastapi_project/

├── src/
│ ├── some_class.py
│ └── test_some_class.py

└── main.py # <-- Your FastAPI application entry point

Here is how you would run the tests using the standard unittest module:

# Navigate to the project directory
cd my_fastapi_project

# Run the unittests with discovery
python -m unittest discover src

If the tests are successful and you’re satisfied with the results, you can then start your FastAPI application:

# Start the FastAPI application
uvicorn main:app --reload

Alternatively, if you have pytest installed, which provides more features and a nicer output, you can run:

# Navigate to the project directory (if not already there)
cd my_fastapi_project

# Run the tests with pytest
pytest src

# Check If pytest is successful

Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC