Output and Logs Not Captured by Pytest When Using APIRouter
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.
Commit to Help
- I commit to help with one of those options 👆
Example Code
import logging
import uvicorn
from fastapi import APIRouter, FastAPI
from fastapi.testclient import TestClient
import main
logger = logging.getLogger(__name__)
app = FastAPI()
api_router = APIRouter()
@app.get("/")
def root():
logger.warning("root")
def dependant():
logger.warning("dependant")
@api_router.get("/")
def router():
logger.warning("router")
dependant()
app.include_router(api_router, prefix="/router")
# Test Stuff
client = TestClient(main.app)
def test_root_logging():
client.get("/")
assert False
def test_route_logging():
client.get("/route")
assert False
Description
When using Pytest, all output (stdout, stderr, and log handlers) are intercepted and captured. By default, upon a test failing, said output is displayed alongside a trackback and other details. This feature greatly assists in resolving the failing test.
stdout and stderr capture appears to not work at all, but I don’t care too much about that (though it may be related). What is really problematic though, is that log capturing does not work when the function it is in is called by a APIRouter
decorated function. I think this has been reported before (https://github.com/tiangolo/fastapi/issues/970), but the original reporter either figured it out and neglected to share the solution or gave up.
To be clear, the issue is not that logs don’t work at all. If you run the above snippet, you will see that they do:
The issue is that in Pytest, the logs are not captured and displayed with failed tests in the way they are for functions that are not decorated by APIRouter
:
I’m at somewhat of a loss as to how to proceed. I’ve tried all kinds of things as far as changing log handlers and such, but none of that seemed to make a difference. Any insight would be greatly appreciated.
Operating System
Linux
Operating System Details
No response
FastAPI Version
0.68.0
Python Version
Python 3.9.2
Additional Context
No response
Issue Analytics
- State:
- Created 2 years ago
- Comments:8 (4 by maintainers)
Top GitHub Comments
https://github.com/Teemu/pytest-sugar
@adriangb btw, how do you get your pytest looking so slick? 😅