我正在尝试为视图编写一个简单的单元测试,但是当我使用RequestFactory设置请求时,我无法将额外的关键字参数传递给视图。
首先,这是urlpattern:
# app/urls.py
# Example URL: localhost:8000/run/user/1/foo
urlpatterns = [
url(r'^user/(?P<uid>\d+)/(?P<uname>\w+)/$',
views.user_kw,
name='user-kw'),
]
以下是我正在测试的视图:
# app/views.py
def user_kw(request, *args, **kwargs):
uid = kwargs['uid']
uname = kwargs['uname']
return render(request, 'run/user.html', context)
最后,这是测试:
# app/tests.py
def test_user_kw(self):
factory = RequestFactory()
# ???
request = factory.post('user/')
response = views.user_kw(request)
self.assertEqual(response.status_code, 200)
正如您所料,当我运行测试时,我收到此错误:
======================================================================
ERROR: test_user_kw (run.tests.TestViews)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/jones/code/django/testing/run/tests.py", line 53, in test_user_kw
response = views.user_kw(request, {"uid": 1, "uname": "foobar"})
File "/Users/jones/code/django/testing/run/views.py", line 28, in user_kw
uid = kwargs['uid']
KeyError: 'uid'
----------------------------------------------------------------------
RequestFactory对象上的Django文档没有讨论这种情况。我查看了RequestFactory代码本身,但我无法弄清楚如何设置对象来解释URL中包含的两个关键字参数。我也找不到任何在线解决这种情况的事情。
我应该补充一点,我确实设法为我使用位置参数的情况编写测试并且它有效:
def test_user_pos(self):
factory = RequestFactory()
request = factory.post('user/')
response = views.user_pos(request, 1, 'foo')
self.assertEqual(response.status_code, 200)
我无法弄清楚如何重写关键字参数的测试。也许我一直在看这个问题太久了,答案就是盯着我看,但我只是看不到它。
答案 0 :(得分:4)
您可以通过正常方式将关键字参数传递给user_pos
方法:
response = views.user_kw(request, uid=1, uname='foo')
您的错误消息显示您已尝试:
response = views.user_kw(request, {"uid": 1, "uname": "foobar"})
这不是传递关键字参数,而是将字典作为位置参数传递。请注意,您可以使用**
解压缩字典:
response = views.user_kw(request, **{"uid": 1, "uname": "foobar"})