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

Sanic @before_server_start listener is executed multiple times when using SanicASGITestClient with pytest #76

Open
tkosman opened this issue Jul 22, 2024 · 0 comments

Comments

@tkosman
Copy link

tkosman commented Jul 22, 2024

I'm experiencing an issue while testing a Sanic application asynchronously using pytest. According to the Sanic documentation, the SanicASGITestClient should not spin up a server on every request. However, in my tests, it appears that the @before_server_start event is being run multiple times, which contradicts the expected behavior.

Here is a minimal example to demonstrate the issue:

import pytest
import sanic

def create_app():
    app = sanic.Sanic("foo")

    @app.before_server_start
    def setup(app):
        # print("Setup")
        app.ctx.x = "aaa"

    @app.route("/save")
    def saving(request):
        app.ctx.x = "123"
        return sanic.response.text("saved")

    @app.route("/get")
    def getting(request):
        return sanic.response.text(app.ctx.x)

    return app

@pytest.fixture
def app():
    a = create_app()
    yield a
    a.stop(unregister=True)

@pytest.mark.asyncio
async def test_this(app):
    request, response = await app.asgi_client.get("/save")
    assert response.text == "saved"

    request, response = await app.asgi_client.get("/get")
    assert response.text == "123"

My env:

  • Sanic version: sanic==24.6.0, sanic-routing==23.12.0, sanic-testing==24.6.0
  • pytest version: pytest==8.2.2, pytest-asyncio==0.23.7
  • Python version: 3.12
  • Operating system: Rocky Linux 9.4

When running the test, the @before_server_start event seems to be executed more than once (I tried to do example print in that section and it invokes multiple times), resulting in app.ctx.x not retaining the value set in the /save route when subsequently accessed in the /get route.

Should the @before_server_start event behave like this when using SanicASGITestClient? If this behavior is expected, how should I properly test my app to ensure state is maintained between requests during asynchronous testing?

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