首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >django-pytest与user-agent无法找到请求。user-agent

django-pytest与user-agent无法找到请求。user-agent
EN

Stack Overflow用户
提问于 2020-09-10 11:40:13
回答 1查看 477关注 0票数 0

耽误您时间,实在对不起。

我有一个正在用pytest-django测试的应用程序。尽管我在views.py的请求函数上遇到了一些问题。

在我的视图中,我得到了一些基于request.user_agent(安装了django-user-agent的应用程序)的声明,以选择是否将显示为移动或桌面模板。这些在pytest-django上给我带来了错误。

views.py:

代码语言:javascript
复制
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:

代码语言:javascript
复制
    def test_curriculo_view(self):
        path = reverse('curriculo')
        request =  RequestFactory().get(path)
        response = views.curriculo_view(request)
        assert response.status_code == 200

错误:

代码语言:javascript
复制
    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’,但没有一个能让我通过这个过程。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-09-10 12:12:26

django-user-agents使用中间件将用户代理信息附加到请求实例,但您是通过直接调用视图来测试视图的,从而绕过了正常的Django请求处理流程。使用django-pytest的client fixture来根据路径调用视图,例如:

代码语言:javascript
复制
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 == 200
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63822493

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档