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):
    @override_settings(CLIENT_ID=1130)
    def test_overriding_settings(self):
        self.assertEqual(settings.CLIENT_ID, 1130)

Auth

Login as a super user

@classmethod
    def setUpTestData(cls):
        cls.user = UserFactory(is_superuser=True)
self.client.force_login(self.user)

Factories

Create mock data

Act

  • Call the function
  • make the API call

Assert

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 manage.py test path.app.tests.ClassName.testName --keepdb
python manage.py test -k match.test-name-patterns-you-could-use-a-path-too

Code coverage

pip install coverage

# replace `python` with `coverage run`
coverage run manage.py 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-09-23