我正在尝试在具有多个复选框的表单上运行单元测试,但无法弄清楚如何发送 POST 数据。我能找到的最相似的问题是 here 。但是如何将该 url 编码的片段与其他表单数据一起嵌入到 POST 中?
如果我这样做,我的测试会出错并显示classes = request.POST.getlist('class_choices') AttributeError:“dict”对象没有属性“getlist”:
request = HttpRequest()
request.method = 'POST'
request.POST['fname'] = 'A'
request.POST['lname'] = 'Student'
request.POST['email'] = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e28f87a28c838f87cc818d8f" rel="noreferrer noopener nofollow">[email protected]</a>'
request.POST['class_choices'] = urllib.urlencode({
'class_choices': ['1', '2'],
}, True)
request.POST['passwd'] = 'password'
request.POST['conpasswd'] = 'password'
response = success(request)
self.assertIn('My Browser', response.content.decode())
但是如果我这样做,我会在 fname = request.POST['fname'] 上收到错误 类型错误:字符串索引必须是整数,而不是 str
request.POST = urllib.urlencode({
'class_choices': ['1', '2'],
'fname': 'A',
'lname': 'Student',
'email': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f727a5f717e727a317c7072" rel="noreferrer noopener nofollow">[email protected]</a>',
'passwd': 'password',
'conpasswd': 'password'
}, True)
response = success(request)
最佳答案
因此,在尝试了其他一些方法之后,我基本上会说“从技术上讲”我的问题没有答案...我找不到任何方法来使用 HttpRequest 创建复选框类型的 POST 参数。然而,按照 Hieu Nguyen 的建议,使用 Django 测试客户端以“正确”的方式执行此操作确实可以实现该功能。您只需将多个选项封装在括号中,如下所示:
response = c.post('/success/',{
'fname': 'A',
'lname': 'Student',
'email': '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="660b032608070b034805090b" rel="noreferrer noopener nofollow">[email protected]</a>',
'passwd': 'password',
'conpasswd': 'password',
'class_choices': ('1','2'),
})
关于Django 单元测试;具有多个值的 POST 复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18238422/