I have been using django.text client to examine the context of some URLs from several unit tests with a code similar to the following:
from django.test import TestCase
class MyTests(TestCase):
def example_test(self):
response = self.client.get('/')
# I can access response.context at this point
Now I am trying to do the same thing from a custom management command but surprisingly this is not working as expected as I can not access the context in the response object.
from django.test import Client
class Command(BaseCommand):
def handle(self, *args, **kwargs):
c = Client()
response = c.get('/')
# response.context is always None at this point
Is there a way to access the context from a custom management command? (Django 4.0)
The Django test runner
DiscoverRunner
(and pytest's auto-use fixturedjango_test_environment
) callssetup_test_environment
, which replaces DjangoTemplate._render
.instrumented_test_render
sends thetemplate_rendered
signal that the Django testClient
connects to to populatedata
, from which it then setsresponse.context
.You can do the same in your custom management command:
If you want to include all other patches used in tests, you can call
setup_test_environment
:Among other things,
setup_test_environment
replacessettings.EMAIL_BACKEND
: