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

Tests Folder

Each of our backend services (default and 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 methods/discussions/test_discussions_list.py.

  • For each file of the system we aim to have the same file with the test_ prefix inside the tests folder.
  • 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 dicussions_list.py
    we will have a class TestListDiscussions with a method test_display_all_discussions() inside our file test_discussions_list.py.

Running Tests

To run the unit tests we use pytest. You can run them by writing:

pytest tests

Inside any of our backend services (for example, inside the default or walrus folders).

❗️

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 DIFFGRAM_SYSTEM_MODE on a secrets.py file.

  • In order to run tests locally, you must set the settings variable DIFFGRAM_SYSTEM_MODE to testing
  • 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_URL to 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.