Flask.test_client().post 和 JSON 编码

Cal*_*laf 4 python testing json flask

我正在 Flask 应用程序中为 JSON 端点编写测试用例。

import unittest
from flask import json
from app import create_app


class TestFooBar(unittest.TestCase):
    def setUp(self):
        self.app = create_app('testing')
        self.app_context = self.app.app_context()
        self.app_context.push()

    def test_ham(self):
        resp = self.client.post('/endpoint',
                                headers={'Content-Type': 'application/json'},
                                data=json.dumps({'foo': 2,
                                                 'bar': 3}))
        assert resp.status_code == 200

    def test_eggs(self):
        resp = self.client.post('/endpoint', data={'foo': 5,
                                                   'bar': 7})
        assert resp.status_code == 200

    def test_ham_and_eggs(self):
        with self.app.test_client() as self.client:
            self.test_ham()
            self.test_eggs()
Run Code Online (Sandbox Code Playgroud)

只是为了了解发生了什么,请使用两种发送方式POST上面代码中发送消息的两种方式都有意义吗?特别是,我在第一种情况下是否使用双 JSON 编码?

test_ham或者,简单地说,和之间有什么区别test_eggs?有没有?

Mar*_*ers 10

您没有对 JSON 进行双重编码,不,因为data不会将任何内容编码为 JSON。test_ham帖子 JSON,test_eggs但没有。

从 Flask 1.0 开始,Flask 测试客户端支持直接通过json关键字参数发布 JSON,在这里使用它来减少样板代码:

def test_ham(self):
    resp = self.client.post('/endpoint', json={'foo': 2, 'bar': 3})
    assert resp.status_code == 200
Run Code Online (Sandbox Code Playgroud)

请参阅Flask测试文档章节的测试 JSON API部分

在测试客户端方法中传递json参数将请求数据设置为 JSON 序列化对象,并将内容类型设置为application/json.

传递字典会data产生不同类型的请求,浏览器会产生像表单application/x-www-form-urlencoded一样的编码请求,并且必须通过对象访问和值。当需要发布 JSON 时不要使用它。<form method="POST" ...>foobarrequest.form