Testing Django¶
Related Links¶
Related pages¶
- Python Testing
- Factories
- Testing endpoints
- [[Running Tests]]
- [[faster-pycharm-tests]]
Django docs¶
- Writing and running Django tests | Overview
manage.py test
docs- Advanced testing topics | 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
Factories¶
Create mock data
Act¶
- Call the function
- make the API call
Assert¶
Expect raising an error¶
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
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