Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

python - Invoking flask server from within pytest test

import sys
import os
import logging
import requests
import json
import pytest
from multiprocessing import Process
from flask_file import main


@pytest.fixture
def endpoint():
   return "http://127.0.0.1:8888/"

def test_send_request(endpoint: str):
    server = Process(target=main)
    server.start()
    time.sleep(30)

    # check that the service is up and running
    service_up = requests.get(f"{endpoint}")

    server.terminate()
    server.join()

I wanted to spin up and spin down a server locally from within a test to test some requests. I know the server itself works because I can run main() from the flask_file itself using python flask_file and it will spin up the server...and I can ping it just fine. When I use the above method, the test does seem to do the full 30s sleep without failing, but in those 30s I cannot open the endpoint on my browser and see the expected "hello world".

question from:https://stackoverflow.com/questions/66056484/invoking-flask-server-from-within-pytest-test

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When you run the Flask builtin development server (e.g. flask run or app.run(), only one connection is possible. So when your test accesses the app, you cannot access it via browser.

Anyway, you should rewrite your test and fixture to use the test_client, see the official documentation

https://flask.palletsprojects.com/en/1.1.x/testing/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...