耽误您时间,实在对不起。
我有一个正在用pytest-django测试的应用程序。尽管我在views.py的请求函数上遇到了一些问题。
在我的视图中,我得到了一些基于request.user_agent(安装了django-user-agent的应用程序)的声明,以选择是否将显示为移动或桌面模板。这些在pytest-django上给我带来了错误。
views.py:
def curriculo_view(request):
context = {}
if request.user_agent.is_mobile:
return render(request, 'amp/Curriculo-mobile.html', context)
elif request.user_agent.is_pc:
return render (request, 'admin/Curriculo.html', context)
else:
return render (request, 'admin/Curriculo.html', context)test_views.py:
def test_curriculo_view(self):
path = reverse('curriculo')
request = RequestFactory().get(path)
response = views.curriculo_view(request)
assert response.status_code == 200错误:
def curriculo_view(request):
context = {}
> if request.user_agent.is_mobile:
E AttributeError: 'WSGIRequest' object has no attribute 'user_agent'
accounts\views.py:98: AttributeError当我想设置一个用户(例如:request.user = User.objects.get())时,我尝试设置,尝试设置请求的键。me‘user _AGENT’,但没有一个能让我通过这个过程。
发布于 2020-09-10 12:12:26
django-user-agents使用中间件将用户代理信息附加到请求实例,但您是通过直接调用视图来测试视图的,从而绕过了正常的Django请求处理流程。使用django-pytest的client fixture来根据路径调用视图,例如:
def test_linux_chromium(client):
path = reverse('curriculo')
response = client.get(path,
HTTP_USER_AGENT='Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36')
assert response.status_code == 200https://stackoverflow.com/questions/63822493
复制相似问题