【发布时间】:2020-08-19 15:12:47
【问题描述】:
使用 Flask RestX,我有一个端点,它将请求有效负载的整个值设置为 Redis 数据库中的一个键。使用 Swagger 和 Postman,我可以确认端点工作正常。
但是当我尝试测试它时,我得到了一个错误。
tray_info_api.py
def create_tray_info_api(api: Api, db: AsyncGetSetDatabase):
tray_info_endpoint = api.namespace(
'trayinfo', description='APIs to Send tray information to the Front End'
)
wild = fields.Wildcard(fields.String)
well_meta = api.model('Well Metadata', {
'label': fields.String,
'type': fields.String,
'value': wild
})
well = api.model('Well', {
'metadata': fields.List(fields.Nested(well_meta)),
'status': fields.String(enum=('ready', 'sampled'), required=True)
# and some other fields with string/integer/datetime types
})
tray = api.model('Well Tray', {
'rows_count': fields.Integer(required=True),
'columns_count': fields.Integer(required=True),
'wells': fields.List(fields.Nested(well), required=True)
})
@tray_info_endpoint.route('/')
class TrayInfoEndpoint(Resource):
@tray_info_endpoint.expect(tray, validate=False)
def put(self):
run(db.set('tray_info', request.data))
return run(db.get('tray_info'))
test_info_endpoint.py
def test_put_info(app):
info = {
"rows_count": 0,
"columns_count": 0,
"date_loaded": "2020-08-19T14:11:29.320Z",
"date_processed": "2020-08-19T14:11:29.320Z",
# ... and all the other fields; this data is copy/pasted from a working Postman request
}
res = app.test_client().put('/trayinfo/', json=info)
data = json.loads(res.data)
assert data == info
调试器在以res = app.test_client 开头的行停止测试,说“TypeError: Object of type bytes is not JSON serializable”。
如果我在 api 的 put 方法中放置一个断点并进入控制台,我看到 request.data 是我发送的数据,整个 JSON 上有 b' 前缀:
>>> request.data
b'{"columns_count": 0, "date_loaded": "2020-08-19T14:11:29.320Z", "date_processed": "2020-08-19T14:11:29.320Z", "rows_count": 0}'
我知道这表明它是字节,这似乎指向答案,除非这是问题所在,那么该应用程序不应该实际上不能在 Postman 中运行吗?我可以毫无错误地单步执行整个put 方法,似乎错误来自测试本身的行,这真的很奇怪。
我也尝试过res = app.test_client().put(url, data=info),这导致request.data 成为b''(一个空的有效负载),所以这是不对的。
【问题讨论】: