I am writing a test for a View where I update context to pass additional information to the template.
In writing the test, I'm having trouble accessing context from the RequestFactory.
class PlanListView(HasBillingRightsMixin, ListView):
"""Show the Plans for user to select."""
headline = "Select a Plan"
model = Plan
template_name = "billing/plan_list.html"
def get_context_data(self, *args, **kwargs):
context = super(PlanListView, self).get_context_data(**kwargs)
context.update({
"customer": self.get_customer()
})
return context
class TestPlanListView(BaseTestBilling):
def setUp(self):
super(TestPlanListView, self).setUp()
request = self.factory.get('billing:plan_list')
request.user = self.user
request.company_uuid = self.user.company_uuid
self.view = PlanListView()
self.view.request = request
self.response = PlanListView.as_view()(request)
def test_get_context_data(self, **kwargs):
context = super(self.view, self).get_context_data(**kwargs)
context.update({"customer": self.view.get_customer()})
self.assertEqual(
self.view.get_context_data(),
context
)
How can I test the view's get_context_data() method?
To write a test you derive from any of the Django (or unittest) test base classes (SimpleTestCase, TransactionTestCase, TestCase, LiveServerTestCase) and then write separate methods to check that specific functionality works as expected (tests use "assert" methods to test that expressions result in True or False values ...
The preferred way to write tests in Django is using the unittest module built-in to the Python standard library. This is covered in detail in the Writing and running tests document. You can also use any other Python test framework; Django provides an API and tools for that kind of integration.
The request factory The RequestFactory shares the same API as the test client. However, instead of behaving like a browser, the RequestFactory provides a way to generate a request instance that can be used as the first argument to any view.
Using a test client gives you access to your context.
def test_context(self):
# GET response using the test client.
response = self.client.get('/list/ofitems/')
# response.context['your_context']
self.assertIsNone(response.context['page_obj'])
self.assertIsNone(response.context['customer']) # or whatever assertion.
.....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With