Django:使用login_required进行测试

时间:2018-04-29 08:03:03

标签: django

我正在尝试在具有login_required的视图上测试发布请求。

如果我在shell django中运行它:

Client().post('/recipes/', {'name' : 'Matar Cauliflower ', 'mass_unit' : '', 'mass_quantity' : '', 'volume_unit' : '1', 'volume_quantity' : '50', 'pieces_unit' : '', 'pieces_quantity' : ''},follow=True).status_code

我明白了:

<HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/login/?next=/recipes/">

如何传递登录凭据告诉用户已登录。

1 个答案:

答案 0 :(得分:3)

要用于单元测试,您可以创建一个测试用户(将在login()完成运行后删除),并将其凭据提供给the test client's login() method

或者,您可以使用您知道的用户的有效凭据调用force_login()方法。您还可以在文档页面的下方使用git rebase --continue 方法,但是为了测试最佳实践,请让您的测试创建一个仅测试用户并以该用户身份登录。