Sbrom
Sbrom

Reputation: 71

Django Test Client: How to remove http headers

I am trying to write a unit test for a piece of code that checks if a header is missing. How can I omit the http_referer header (or any header for that matter) from Django's test client?

def testCase(self):
    response = self.client.get('/some_url/')
    self.assertNotEqual(500, response.status_code)

Upvotes: 5

Views: 3009

Answers (2)

dm03514
dm03514

Reputation: 55972

Instead of using the built-in test client, you could use Django's RequestFactory to build your request, then modify the request object before calling your function:

from django.test.client import RequestFactory
from django.test import TestCase

from yourapp.view import yourfunction

class YourTest(TestCase)
    def setUp(self):
        self.factory = RequestFactory()

    def testCase(self):
        request = self.factory.get('/yoururl/')
        del request.META['HTTP_REFERER']
        yourfunction(request)

Upvotes: 2

Ian Clelland
Ian Clelland

Reputation: 44152

Don't go through the test client, in that case. If you modify the behaviour of the test client, and then make a request through it, you are not testing your code against the input that it will actually have to handle.

You shouldn't be trusting the test client to construct HTTP requests in exactly the same way as the WSGI client. It does a good enough job to get the request parameters into your view, but it certainly isn't the same as what you would get from a real request.

The purpose of the test client is to shield you from all of the messy details of the real request and response objects, and just let you test how your views respond to input parameters. In your case, though, you need to test those details.

You should be constructing an HTTPRequest object the same way that Django would -- use as many Django functions as you need to build it, and then call your view, or your middleware, directly with that HTTPRequest object. If your view should be raising an exception, then use assertRaises to test it. If it should return an HTTPResponse with the status code set to 500, then test that -- or test them together with a custom assert method, if you need to.

Upvotes: -1

Related Questions