Skip to content

Testing Django

Django docs

Testing endpoints

Writing a basic 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)

patch and mocking

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)

it also returns a context manager!

from django.core.exceptions import ValidationError
with self.assertRaises(ValidationError):
    course.full_clean()

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

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)

[[feature-toggles#How to test feature flags]]


Last update: 2023-04-24