Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add HTTP_USER_AGENT to Django RequestFactory request?

Is there a way to add a user agent string to a RequestFactory request object? I have the following test:

def test_homepage(self):
    request = self.factory.get(reverse('home'))
    response = views.home_page(request)
    self.assertEqual(response.status_code, 200)

The problem is that the home_page view calls a function that requires request.META["HTTP_USER_AGENT"]. As a result, the above test is raising a KeyError because it doesn't know what HTTP_USER_AGENT is. Is there a way to add it to the RF's request object? I know I can add it if I use Django's Client object but I'd prefer not to go this route as I want to eliminate all middleware involvement in my test.

Thank you.

like image 545
Jim Avatar asked Jul 09 '13 03:07

Jim


1 Answers

Pass HTTP_USER_AGENT as keyword argument.

request = self.factory.get(reverse('home'), HTTP_USER_AGENT='Mozilla/5.0')

https://docs.djangoproject.com/en/1.5/topics/testing/overview/#django.test.client.Client.get via https://docs.djangoproject.com/en/1.5/topics/testing/advanced/#django.test.client.RequestFactory

like image 158
falsetru Avatar answered Nov 11 '22 18:11

falsetru