joerick/pyinstrument

Example on how to disable profiling in FastAPI tests

Opened this issue · 0 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!