user6003691
user6003691

Reputation:

Unit test method that uses the flask.request with PyTest

Is it possible to write a unit test (PyTest) to cover a only a method that uses the flask.request as in the example below?

api = flask.Blueprint('api', __name__)

@api.route('/', methods=['POST'])
def do_stuff():
    a, b, c = get_params()
    return jsonify(a=a, b=b, c=c)

def get_params():
   data = flask.request.get_json()
   a = data('param_a')
   b = data('param_b')
   c = data('param_c')

Or the only way to test get_params is through the do_stuff pytestfixture?

I have tried to directly call the get_params method but cannot work out what/how to actually pass some input as a request:

import example.api

def test_get_params_method(input, expected_output):
    example.api.get_params()
    # assert input == expected_output ?

Update:

# app.py
app = flask.Flask(__name__)
app.register_blueprint(api)

Upvotes: 1

Views: 946

Answers (1)

tmt
tmt

Reputation: 8604

I'm not sure you can do it with the Blueprint but you can do it with the application itself and test_request_context() manager which sets up flask.request and thus allows you to simulate an incoming request:

from app import app
from example import get_params

def test_get_params_method(input, expected_output):
    with app.test_request_context('/'):
        get_params()

Check out the documentation but for your example you probably want to pass data argument to the context manager.

Upvotes: 2

Related Questions