RuntimeError for Depends on Python 3.8 stating "...yield require Python 3.7 or above" when testing Router in pytest
See original GitHub issueFirst check
- I added a very descriptive title to this issue.
- I used the GitHub search to find a similar issue and didn’t find it.
- I searched the FastAPI documentation, with the integrated search.
- I already searched in Google “How to X in FastAPI” and didn’t find any information.
- I already read and followed all the tutorial in the docs and didn’t find an answer.
- I already checked if it is not related to FastAPI but to Pydantic.
- I already checked if it is not related to FastAPI but to Swagger UI.
- I already checked if it is not related to FastAPI but to ReDoc.
- After submitting this, I commit to one of:
- Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
- I already hit the “watch” button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
- Implement a Pull Request for a confirmed bug.
Example
Here’s a self-contained, minimal, reproducible, example with my use case:
from fastapi import APIRouter, Depends
from fastapi.testclient import TestClient
def get_db():
db = 1
yield db
router = APIRouter()
client = TestClient(router)
@router.get("/")
def foo(ds=Depends(get_db)):
print(ds)
return {}
def test_foo():
client.get("/")
assert 1 == 1
Description
The above sample fails with:
RuntimeError: FastAPI dependencies with yield require Python 3.7 or above, or the backports for Python 3.6, installed with: pip install async-exit-stack async-generator
However, replacing router = FastAPI()
with router = FastAPI()
succeeds.
I ran into this problem while trying to do some isolated unit testing on the API routes, and I assumed it would have been okay based on the documentation stating:
You can think of APIRouter as a “mini FastAPI” class. All the same options are supported. All the same parameters, responses, dependencies, tags, etc.
The workaround is simple, and I can first create an app class in my testing, but I’m more curious about why this doesn’t work. Unless I’m doing something incorrectly, maybe this is worth a documentation note, or a clearer exception message?
Environment
- OS: macOS 10.15.7
- FastAPI Version: 0.61.1
- Python version: 3.8.6
Issue Analytics
- State:
- Created 3 years ago
- Reactions:2
- Comments:7 (3 by maintainers)
This should be documented as a gotcha, etc, just in case someone else runs into exactly the same thing. Maybe in the section about routers or maybe in the section about testing, not sure. I’m happy to create a PR if someone makes a decision on where it should go.
Assuming the original need was handled, this will be automatically closed now. But feel free to add more comments or create new issues or PRs.