Search code examples
djangodjango-testingdjango-middlewaredjango-tests

Django custom middleware to check header token.Tests with valid request header tokens still fails


I am checking a request header for a valid token in my custom middleware.

class CustomTokenAuthentication(object):

def process_request(self, request):

    access_token = request.META.get('HTTP_TOKEN', '')
    if AccessToken.objects.filter(token=access_token).exists():
        return None
    else:
        # return None
        res =  HttpResponse("Invalid token", status=401)
        res["WWW-Authenticate"] = "Invalid Token"
        return res

seems to work fine, but im stuck writing a test by setting a header HTTP_TOKEN with a valid token value and geting a 200 response.

my sample testcode

def test_invalid_token_present(self):
    resp = self.client.get(reverse('productlist'), **{'HTTP_TOKEN':'8742627sdfsdfsf4e3423dsd23'})
    self.assertEqual(resp.status_code,200)

seems to fail always.


Solution

  • Django renames CUSTOM-HEADER to HTTP_CUSTOM_HEADER. When you send it HTTP_TOKEN it will get renamed to HTTP_HTTP_TOKEN in the request.META dict. A simple way to check what headers you are getting is to either print request.META and check the console or insert a pdb breakpoint just before the check and examin the request.META dict - link to relevant Django doc. So try:

        resp = self.client.get(reverse('productlist'),
                               **{'TOKEN':'8742627sdfsdfsf4e3423dsd23'})
    

    I advise you to limit your line lengths, so that people don't have to scroll horizontally to read your code. PEP-8 prescribes an 80 character limit.