question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Output and Logs Not Captured by Pytest When Using APIRouter

See original GitHub issue

First 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: image

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: image

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:closed
  • Created 2 years ago
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

3reactions
adriangbcommented, Aug 11, 2021
0reactions
benjamin-kirkbridecommented, Aug 11, 2021

@adriangb btw, how do you get your pytest looking so slick? 😅

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to manage logging — pytest documentation
pytest captures log messages of level WARNING or above automatically and displays them in their own section for each failed test in the...
Read more >
Why does pytest + xdist not capture output? - Stack Overflow
I have a simple test file (that has both a print and a logging.warning ) alone in a dir and running with pytest...
Read more >
Testing - FastAPI
Create a TestClient by passing your FastAPI application to it. Create functions with a name that starts with test_ (this is standard pytest...
Read more >
Moving from Flask to FastAPI - TestDriven.io
On par with Go and NodeJS, FastAPI is one of the fastest Python-based ... Unlike Flask, FastAPI does not have a built-in development...
Read more >
5 Advanced Features of FastAPI You Should Try
Therefore to implement this, you need to import the APIRouter class from fast API and then use its object to create routes as...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found