Created
February 26, 2020 09:03
-
-
Save eruvanos/c370b04e1be18b89d1babec188495c32 to your computer and use it in GitHub Desktop.
Run Flask app as fixture
This file contains 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 threading import Thread | |
import pytest | |
import requests | |
from flask import Flask | |
@pytest.fixture() | |
def app() -> Flask: | |
host = 'localhost' | |
port = 5000 | |
# Create app with shutdown hook | |
app = Flask(__name__) | |
app.env = 'development' | |
app.testing = True | |
@app.route('/shutdown') | |
def shutdown(): | |
from flask import request | |
request.environ['werkzeug.server.shutdown']() | |
return 'OK', 200 | |
# Start server | |
thread = Thread(target=app.run, daemon=True, kwargs=dict(host=host, port=port)) | |
thread.start() | |
# Provide app for testing | |
yield app | |
# Shutdown server | |
requests.get('http://localhost:5000/shutdown') | |
thread.join() | |
def test_flask(app): | |
@app.route('/ping') | |
def ping(): | |
return 'PONG' | |
requests.get('http://localhost:5000/ping').raise_for_status() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Since
werkzeug.server.shutdown
has been deprecated and removed, the above no longer works. However, if you only need the server to start once before running the tests (at thesession
level), then you can skipthread.join()
because, when the tests finish, it will be the only thread left running and the Python process exits when onlydaemon
threads are left. Details here: https://docs.python.org/3/library/threading.html#thread-objectsThis is the code ended up with in my
conftest.py
:All the tests which need this full-fledged Flask server to be up and running must to use the
client
fixture which depends on theapp
fixture. For example: