pyinstrument icon indicating copy to clipboard operation
pyinstrument copied to clipboard

Example on how to disable profiling in FastAPI tests

Open daniel-soutar-ki opened this issue 1 year ago • 1 comments

I have a FastAPI application, and have added Pyinstrument instrumentation to it using code similar to the code linked here.

The code suggests to have profiling configurable via a Settings object, such as one provided in Pydantic.

The problem with this is that in my case I have a Settings object which looks like this:

class Settings(BaseSettings):
    class Config:
        extra = Extra.allow

    my_url: AnyHttpUrl
    foo: Optional[str] = None
    ENABLE_PROFILING: bool = False

So when I try to do something like this inside my app factory function:

def register_profiling_middleware(app: FastAPI):
    if get_settings().ENABLE_PROFILING:
        @app.middleware("http")
        async def profile_request(request: Request, call_next: Callable):
            ...

This runs into Pydantic validation setting issues when running pytest tests. This is because some of the environment variables are not yet set when a test client is created. Currently my lazy solution in the app factory function is to add a parameter for enablig/disabling profiling:

# conftest.py
@pytest.fixture
def client(tmp_path):
    ...
    app = create_app(enable_profiling=False)

# app.py
def create_app(enable_profiling: bool = True) -> FastAPI:
    app = FastAPI()
    ...
    register_middlewares(app=app, enable_profiling=enable_profiling)

Is this what is recommended? Is there a better way? Ideally I wouldn't have profiling in the tests, or at least would want that to be determined by passing an environment variable myself, rather than having to make code changes. Specifically, if there are any examples in the docs I can look at that would be much appreciated. Thanks!

daniel-soutar-ki avatar Mar 22 '24 12:03 daniel-soutar-ki

I'm no FastAPI expert, but if you figure something simple out, happy to update the docs.

joerick avatar Aug 25 '24 11:08 joerick