lundi 28 septembre 2020

background Flask toyserver for testing

I need a flask server in multithreaded mode for testing, because some test routes are themselves calling other routes on the same server (thus, in the singlethreaded test_client they would hang). I thought the easiest solution would be to start the server manually in a background thread - however with this setup (as shown below) the test cases fail with ConnectionError - presumably because they don't wait for the server to finish set up.

What are the best practices to set up multithreaded testing with Flask? Should I continue with this approach and add additional handling to wait for a signal from the server to be ready? Add polling with timeout on the TestCase side?

main_test.py

import unittest
from threading import Thread
from main import app

def _run_test_server():
    app.run(host='localhost', port=3000, debug=True, threaded=True)

Thread(target=_run_test_server).start()
loader = unittest.TestLoader()
tests = loader.discover('.')
testRunner = unittest.runner.TextTestRunner()
testRunner.run(tests)

main.py

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

if __name__ == "__main__":
    app.run(host='localhost', port=3000, debug=True, threaded=True)

my_test_case.py

class MyTestCase(unittest.TestCase):
    """
    Baseclass for testcases
    """
    def fetch_response(self, path):
        return json.loads(
            requests.get(urllib.parse.urljoin(os.environ["ORIGIN_URI"], path)).data
        )

Aucun commentaire:

Enregistrer un commentaire