Unit Testing Backend Guidelines
Guidelines for improving the Test Suite of Diffgram's Backend
Diffgram is a constantly growing project, and one of the biggest goals for the next coming months is to increase our test coverage both in the backend and in the frontend projects. This guide can help you understand how our test suites are structured and how you can add / improve the unit tests we have on our python backend
Each of our backend services (
walrus) have a folder called
tests. In this folder we are placing the exact same folder structure as the service itself. For example, if the default service has a file called
methods/disccusions/discussions_list.py, on the
tests folder you should find a file named
- For each file of the system we aim to have the same file with the
test_prefix inside the
- If the file not yet exists, most likely it still does not have unit tests, and we would encourage you to create it and add tests for it.
Test File Structure
- All our tests files contain a single class that inherits from
testing_setup.DiffgramBaseTestCase. This base class sets up a Python client and several utility methods for easier testing development.
- For each function in the file to tests, we try to create one function with the same name + the
test_prefix as a method of our test class. For example if we have a function
display_all_discusssions()on our file
we will have a class
TestListDiscussionswith a method
test_display_all_discussions()inside our file
To run the unit tests we use
pytest. You can run them by writing:
Inside any of our backend services (for example, inside the
Running Tests DELETE THE DATABASE
To make sure tests are non-dependant to state, we always delete and re-create the database on each test run. Make sure you have a different database (
UNIT_TESTING_DATABASE_URL) for running your tests and that you have the logic to change that database depending on the
- In order to run tests locally, you must set the settings variable
- Make sure you have a DB with no data in it. Diffgram's test runner will create the DB, run migrations and delete the DB after tests.
- Make sure to update the
UNIT_TESTING_DATABASE_URLto your testing database, or you could lose all your data when running the unit tests on a production DB.
- The postgres user should have permissions to drop the testing database.
Updated about 1 year ago