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

时间:2019-11-03 21:19:28

标签: 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

1 个答案:

答案 0 :(得分:0)

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"'则是有效。