Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test using an invalid JSON passed in test_request_context (Flask)

For testing purposes, is there a way to pass an invalid JSON in the test_request_context?

# 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 Answers

json.dumps is never going to produce an invalid JSON document (it would raise an exception instead thus spoiling your test) but there shouldn't be any problem creating an invalid JSON manually:

# 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

Note: 'abc' is not a valid JSON while '"abc"' would be.

like image 139
tmt Avatar answered Mar 12 '26 08:03

tmt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!