Skip to content

Instantly share code, notes, and snippets.

@trylks
Last active January 31, 2023 12:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trylks/1c924e244635551ea7e1a5385b4d25e6 to your computer and use it in GitHub Desktop.
Save trylks/1c924e244635551ea7e1a5385b4d25e6 to your computer and use it in GitHub Desktop.
minimal working example pytest fastapi multiprocessing (not working)

Minimal example to ask in StackOverflow

Pytest does not allow to start a process with a service and tests requests to it, at least not in the most straightforward way IMHO.

I may be missing something, or I may be doing something wrong. Hence, I share this short code in a gist, to ask.

How to run it

The dependencies are: fastapi pytest requests uvicorn. You may install them with your package / environment manager of choice, or use pipenv install with the provided Pipfile.

To run the code in the environment (e.g. pipenv shell), run: python3 mwe.py. You should see everything is OK.

To run the test, run in the environment: pytest. This does not work for me, the request times out.

import fastapi, multiprocessing, requests, time, uvicorn
app = fastapi.FastAPI()
@app.get('/ok')
def ok():
return 'OK'
class service:
def __enter__(self):
def run_service(): uvicorn.run('mwe:app', host='0.0.0.0', port=8000, reload=True)
self.service = multiprocessing.Process(target=run_service)
self.service.start()
time.sleep(10)
def __exit__(self, *args):
self.service.terminate()
def main():
with service():
return requests.get('http://127.0.0.1:8000/ok').ok
if __name__ == '__main__':
print('🆖🆗'[main()])
[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"
[packages]
pytest = "*"
fastapi = "*"
requests = "*"
uvicorn = "*"
[requires]
python_version = "3.10"
python_full_version = "3.10.6"
from mwe import main
def test_main():
assert main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment