使用 RequestFactory 测试需要登录的 Django 视图 [英] Test Django views that require login using RequestFactory

查看:15
本文介绍了使用 RequestFactory 测试需要登录的 Django 视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Django 的新手,我想对需要用户登录的视图进行单元测试 (@login_requred).Django好心提供了RequestFactory,理论上我可以用它直接调用视图:

I'm new to Django and I'd like to unit test a view that requires the user to be logged in (@login_requred). Django kindly provides the RequestFactory, which I can theoretically use to call the view directly:

factory = RequestFactory()
request = factory.get("/my/home/url")
response = views.home(request)

然而,调用失败

AttributeError: 'WSGIRequest' object has no attribute 'session'

显然,这是故意的,但我又何必呢?如何测试需要身份验证的视图(在我的情况下是所有视图)?还是我完全采取了错误的方法?

Apparently, this is intentional, but where does that leave me? How do I test views that require authentication (which in my case is all of them)? Or am I taking the wrong approach entirely?

我使用的是 Django 1.3 和 Python 2.7.

I'm using Django 1.3 and Python 2.7.

推荐答案

使用 RequestFactory 时,您正在测试具有完全已知输入的视图.

When using RequestFactory, you are testing view with exactly known inputs.

这允许将测试与各种已安装的中间件组件执行的附加处理的影响隔离开来,从而更精确地进行测试.

That allows isolating tests from the impact of the additional processing performed by various installed middleware components and thus more precisely testing.

您可以使用视图函数期望的任何附加数据设置请求,即:

You can setup request with any additional data that view function expect, ie:

    request.user = AnonymousUser()
    request.session = {}

我个人的建议是使用 TestClient 进行集成测试(即:商店中的整个用户结帐流程,包括许多步骤)和使用 RequestFactory 来测试独立的视图功能行为及其输出(即,将产品添加到购物车).

My personal recommendation is to use TestClient to do integration testing (ie: entire user checkout process in shop which includes many steps) and RequestFactory to test independent view functions behavior and their output (ie. adding product to cart).

这篇关于使用 RequestFactory 测试需要登录的 Django 视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆