Home > Mobile >  How can I simulate a flask request in python to test my program?
How can I simulate a flask request in python to test my program?

Time:10-27

I wrote a function in python that will receive a flask.request. I am wondering how can I test this function by sending a fake request to it. Is there a way to do this locally ?

My function:

def main(request: flask.Request):
    if request.method == 'GET':
        try:
            request_json = request.get_json()
        except:
            return '', 400
        else:
            stuff = do_stuff(request_json)
            return stuff, 200

CodePudding user response:

You can simulate inputs to your system for testing purposes with unit test mock library which is part of python's standard library.

CodePudding user response:

I use this to test your issue on my local

import flask


app = flask.Flask(__name__)

@app.route("/<request>")
def main(request: flask.Request):
    if flask.request.method == 'GET':
        try:
            request_json = request.get_json()
        except:
            return '', 400
        else:
            stuff = do_stuff(request_json)
        return stuff, 200

if __name__ == "__main__":
    app.run(debug=True)

then do curl

curl -i http://localhost:5000/testing

and will give output like

HTTP/1.0 400 BAD REQUEST
Content-Type: text/html; charset=utf-8
Content-Length: 0
Server: Werkzeug/2.0.1 Python/3.9.6
Date: Tue, 26 Oct 2021 16:57:19 GMT

is this expected output?

  • Related