Skip to content

Testing Django

Django docs

Testing endpoints

Writing a basic test

Arrange/Setup a test


Override settings

from django.test import override_settings

class TestBuildPath(TestCase):
    def test_overriding_settings(self):
        self.assertEqual(settings.CLIENT_ID, 1130)

patch and mocking


Login as a super user

    def setUpTestData(cls):
        cls.user = UserFactory(is_superuser=True)


Create mock data


  • Call the function
  • make the API call


Expect raising an error

self.assertRaises(ExpectedException, fn_name, arg1, arg2)

No need to tear down data!

We use django.test.TestCase

  • inherits from the TransactionTestCase
  • tests are always within a database transaction

    • which is then rolled back when the test completes
  • Reference

Running tests

In PyCharm click the green triangle beside a test

Always have the --keepdb option in PyCharm

We can also run tests in the terminal

python test --keepdb
python test -k match.test-name-patterns-you-could-use-a-path-too

Code coverage

pip install coverage

# replace `python` with `coverage run`
coverage run --branch test
coverage html

Using another testing framework

override the TEST_RUNNER env var

Have code that will run before the tests

from django.test.runner import DiscoverRunner
from some.path import patch_feature_flags

class DefaultTestRunner(DiscoverRunner):
    def run_tests(self, test_labels, extra_tests=None, **kwargs):
        with patch_feature_flags({}):
            """ Don't get feature flag value from LaunchDarkly. """
            return super().run_tests(test_labels, extra_tests=None, **kwargs)

Last update: 2022-11-04