my django app has a env var DEMO which, among other thing, dictate what endpoints are declared in my urls.py file.
I want to unit tests these endpoints, I've tried django.test.override_settings but I've found that urls.py is ran only once and not once per unit test.
My code look like this:
# settings.py
DEMO = os.environ.get("DEMO", "false") == "true"
# urls.py
print(f"urls.py: DEMO = {settings.DEMO}")
if settings.DEMO:
urlpatterns += [
path('my_demo_endpoint/',MyDemoAPIView.as_view(),name="my-demo-view")
]
# test.test_my_demo_endpoint.py
class MyDemoEndpointTestCase(TestCase):
@override_settings(DEMO=True)
def test_endpoint_is_reachable_with_demo_equals_true(self):
print(f"test_endpoint_is_reachable_with_demo_equals_true: DEMO = {settings.DEMO}")
response = self.client.get("/my_demo_endpoint/")
# this fails with 404
self.assertEqual(response.status_code, 200)
@override_settings(DEMO=False)
def test_endpoint_is_not_reachable_with_demo_equals_false(self):
print(f"test_endpoint_is_not_reachable_with_demo_equals_false: DEMO = {settings.DEMO}")
response = self.client.get("/my_demo_endpoint/")
self.assertEqual(response.status_code, 404)
when running this I get:
urls.py: DEMO = False
test_endpoint_is_reachable_with_demo_equals_true: DEMO = True
<test fails with 404>
test_endpoint_is_not_reachable_with_demo_equals_false: DEMO = False
<test succeed>
urls.py is ran only once before every test, however I want to test different behavious of urls.py depending on settings
Using a different settings file for testing is not a solution because different tests requires different settings. Directly calling my view in the unit test means that the urls.py code stays uncovered and its behaviour untested so this is also not what I want.
How can I override settings for code ran in urls.py?
Thank you for your time.
DEMOstate.