Add HTTP_USER_AGENT to Django RequestFactory request?

Is there a way to add a user agent string to the 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 requiring request.META ["HTTP_USER_AGENT"]. As a result, the above test raises KeyError because it does not know what HTTP_USER_AGENT is. Is there any way to add it to the RF request object? I know that I can add it if I use the Django Client object, but I would prefer not to go along this route, since I want to exclude all the participation of middleware in my test.

Thanks.

+6
source share
1 answer

Pass HTTP_USER_AGENT as a 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 p>

+9
source

Source: https://habr.com/ru/post/948990/


All Articles