json - 使用 test_request_context (Flask) 中传递的无效 JSON 进行测试

标签 json python-3.x flask pytest

为了测试目的,有没有办法在 test_request_context 中传递无效的 JSON?

# test_example.py
from app import app
from example import get_param  # the method I am interested in unit testing
import flask

bad_json = # some bad JSON

def test_get_param_aborts(app):
    with app.test_request_context('/', data=flask.json.dumps(bad_json), content_type='application/json'):
            # assert output based on a request with a bad json

最佳答案

json.dumps 永远不会生成无效的 JSON 文档(它会引发异常,从而破坏您的测试),但手动创建无效的 JSON 应该不会有任何问题:

# test_example.py
from app import app
from example import get_param

def test_get_param_aborts(app):
    with app.test_request_context('/', data='abc', content_type='application/json'):
        # assert output based on a request with a bad json

注意:'abc' 不是有效的 JSON,而 '"abc"' 则是有效的 JSON。

关于json - 使用 test_request_context (Flask) 中传递的无效 JSON 进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58684718/

相关文章:

Flask Restx 枚举模型

jquery - 如何使用 jquery/ajax 将数据发送到 json 文件

javascript - 如何访问 sapper/polka 中所有 svelte 组件的 json 数据文件

java - 如何正确返回JsonObject? |带有Spring Boot的Json RPC-API

django - 在 centos 中使用 postgresql 迁移 Kiwi 时出错

python - 在 PyGobject 中绘图 (python3)

python - 我有一个保存有用户名和高分的外部文件,我需要订购它们

python - Flask 重定向数据

asp.net-mvc - ASP.NET MVC 如何将 JSON 对象作为参数从 View 传递到 Controller

python - 即使更新数据库后,SQLAlchemy 也找不到我表中的列?