Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example on how to disable profiling in FastAPI tests #298

Open
daniel-soutar-ki opened this issue Mar 22, 2024 · 0 comments
Open

Example on how to disable profiling in FastAPI tests #298

daniel-soutar-ki opened this issue Mar 22, 2024 · 0 comments

Comments

@daniel-soutar-ki
Copy link

daniel-soutar-ki commented Mar 22, 2024

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant