【问题标题】:How can I post data into test Client post request?如何将数据发布到测试客户端发布请求中?
【发布时间】:2020-11-06 11:14:54
【问题描述】:

我正在编写一个测试以查看表单数据是否在尝试创建 Post 对象的发布请求上进行验证。

tests.py

def setUp(self):
    user = User.objects.create_user(email='test@gmail.com', password='test', name='test')
    self.user = User.objects.get(email='test@gmail.com')
    self.client.login(email=user.email, password=user.password)

@tag('fast')
def test_index(self):
    client = Client()
    response = client.post(reverse('index'), data={'user': self.user, 'body': 'Test'}, follow=True)
    print(response, self.user)
    self.assertTrue(Post.objects.filter(body='Test').exists())

但测试失败并显示消息 False is not true 暗示未创建主体为 "Test" 的对象。我已经尝试使用 urlencode 对数据进行编码,但没有帮助。

这是打印语句显示的内容:<TemplateResponse status_code=200, "text/html; charset=utf-8"> test

views.py

def index(request):
    posts = Post.objects.all()
    if request.method == 'POST':
        form = NewPostForm(request.POST, request.FILES)
        if form.is_valid():
            new_post = form.save(commit=False)
            new_post.user = user
            new_post.save()
            return redirect('index')
    else:
        form = NewPostForm(instance=None)
    context = {
        'form': form,
        'posts': posts
    }

    return render(request, 'index.html', context=context)

也许用户没有被正确序列化,但是当我从数据属性中删除它时(这意味着应该将当前用户分配给 Post 对象),我得到了基本相同的结果。

【问题讨论】:

    标签: python django django-testing


    【解决方案1】:

    您可以尝试在请求的标头中添加Content-Type:application/json

    正如上面的错误消息,它显示您发送的请求是纯文本格式

    【讨论】:

    • 尝试将此作为请求client.post(reverse('index'), data=json.dumps({'body': 'test'}), follow=True, content_type='application/json'),但得到了相同的结果,奇怪的是我的请求仍在发送纯文本:<TemplateResponse status_code=200, "text/html; charset=utf-8">
    • 在发送带有application/json 标头的请求时尝试删除数据中的json.dumps
    【解决方案2】:

    最后我决定只测试它的有效响应并将数据验证部分留给表单验证测试,这就是它现在的样子:

    def test_index(self):
        client = Client()
        get_response = client.get('/home/', {}, True)
        post_response = client.post(reverse('index'), data={'body': 'Test'}, follow=True)
        self.assertEqual(get_response.status_code, 200)
        self.assertEqual(post_response.status_code, 200)
    

    如果有人有任何建议,我很乐意看到他们,因为我的特殊问题仍然存在。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-21
      • 2017-02-21
      • 2013-02-25
      • 2020-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-08
      相关资源
      最近更新 更多