Created
March 15, 2021 17:27
-
-
Save SkYNewZ/aa4fb352c52e209776e11ba442160544 to your computer and use it in GitHub Desktop.
How to test a Flask/HTTP Cloud Function in Python ?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, Request, make_response | |
def hello_http(request: Request): | |
"""HTTP Cloud Function. | |
Args: | |
request (flask.Request): The request object. | |
<https://flask.palletsprojects.com/en/1.1.x/api/#incoming-request-data> | |
Returns: | |
The response text, or any set of values that can be turned into a | |
Response object using `make_response` | |
<https://flask.palletsprojects.com/en/1.1.x/api/#flask.make_response>. | |
""" | |
# request_json = request.get_json() | |
# request_args = request.args | |
return make_response("oops", 400) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, Request | |
from werkzeug.test import EnvironBuilder | |
from main import hello_http | |
app = Flask(__name__) | |
def test_main(): | |
with app.app_context(): | |
# This is the mock | |
builder = EnvironBuilder( | |
method='POST', | |
json={'foo': 'bar'}, | |
) | |
# Use the mock | |
env = builder.get_environ() | |
req = Request(env) | |
# Test it | |
res = hello_http(request=req) | |
assert res.status_code == 400 | |
assert res.get_data(as_text=True) == "oops" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
~/Sources/test-request-python via python-3.9.2 using ☁️ default/groups-terraform-sync-dtep | |
➜ python3 -m pytest -vss . | |
================================================================================ test session starts ================================================================================ | |
platform linux -- Python 3.9.2, pytest-6.2.2, py-1.10.0, pluggy-0.13.1 -- /home/quentin/Sources/test-request-python/.direnv/python-3.9.2/bin/python3 | |
cachedir: .pytest_cache | |
rootdir: /home/quentin/Sources/test-request-python | |
collected 1 item | |
main_test.py::test_main PASSED | |
================================================================================= 1 passed in 0.05s ================================================================================= |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment