Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a test for a Django View get_context_data() method

I am writing a test for a View where I update context to pass additional information to the template.

Problem

In writing the test, I'm having trouble accessing context from the RequestFactory.

Code

View

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

Test

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
        )

Question

How can I test the view's get_context_data() method?

like image 236
Emile Avatar asked Mar 09 '18 11:03

Emile


People also ask

How do I create a test in Django?

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 ...

How do I test my Django app?

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.

What is RequestFactory in Django?

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.


1 Answers

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.
    .....
like image 139
misraX Avatar answered Oct 21 '22 08:10

misraX