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.

Helper to replace middlewear during tests

See original GitHub issue

When you have middlewear that sets up a database session such as:

@app.middleware("http")
async def db_session_middleware(request: Request, call_next):
    request.state.db = Session()
    response = await call_next(request)
    request.state.db.close()
    return response

It’s handy to be able to replace the middlewear for the duration of test, eg:

@pytest.fixture(scope='session', autouse=True)
def db():
    engine = create_engine(os.environ['TEST_DB_URL'])
    conn = engine.connect()
    transaction = conn.begin()
    try:
        session = Session(bind=conn)
        Base.metadata.create_all(bind=conn, checkfirst=False)

        async def testing_session(request: Request, call_next):
            request.state.db = session
            return await call_next(request)

        with replace_middleware_dispatch(
            app, db_session_middleware, testing_session
        ):
            yield session
    finally:
        transaction.rollback()

@tomchristie - would you welcome a PR that implements replace_middleware_dispatch?

If so, where should I put it in the package?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:2
  • Comments:6 (6 by maintainers)

github_iconTop GitHub Comments

1reaction
tomchristiecommented, May 21, 2019

run the database setup

The config docs have an example of how to gear up test database setup. You may want to adapt it so that it runs any migrations.

run each test in its own subtransaction

For test isolation see eg. https://github.com/encode/databases#test-isolation The docs in Starlette have something v. similar to that where they pass rollback_on_shutdown=settings.TESTING to the database middleware.

0reactions
cjw296commented, May 21, 2019

How would I change which middlewear is used for a test run versus a production startup?

if I understand the example you link to above, it’s predicated on conftest.py being executed before myproject is ever imported. Is that a documented behaviour of pytest? Feels like it might be an implementation detail that could change in the future…

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to replace Middleware in integration tests project
It seems that WebApplicationFactory should use the real Startup class as the type argument:
Read more >
How we can eliminate(remove) middleware in test mode (test ...
Yes. I could do that by removing middleware in the main app code, but I want to eliminate middleware in the test mode,...
Read more >
Tests does not work when overriding a helper - Laracasts
I am starting to do my first tests in a website I am working on, and I would need ... Create a middleware...
Read more >
Testing ASP.NET Core middleware - part 5
This article explains how the WebApplicationFactory can be used to test ASP.NET Core Middleware.
Read more >
Testing HTTP Middleware in Laravel - on error resume next
A middleware only needs to provide a single handle method with two parameters. The first parameter is the current Request object. The second ......
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