importpytestfromfaststreamimportFastStream,TestAppfromfaststream.kafkaimportKafkaBroker,TestKafkaBrokerapp=FastStream(KafkaBroker())@app.after_startupasyncdefhandle():print("Calls in tests too!")@pytest.mark.asyncioasyncdeftest_lifespan():asyncwith(TestKafkaBroker(app.broker,connect_only=True),TestApp(app),):# test somethingpass
importpytestfromfaststreamimportFastStream,TestAppfromfaststream.confluentimportKafkaBroker,TestKafkaBrokerapp=FastStream(KafkaBroker())@app.after_startupasyncdefhandle():print("Calls in tests too!")@pytest.mark.asyncioasyncdeftest_lifespan():asyncwith(TestKafkaBroker(app.broker,connect_only=True),TestApp(app),):# test somethingpass
importpytestfromfaststreamimportFastStream,TestAppfromfaststream.rabbitimportRabbitBroker,TestRabbitBrokerapp=FastStream(RabbitBroker())@app.after_startupasyncdefhandle():print("Calls in tests too!")@pytest.mark.asyncioasyncdeftest_lifespan():asyncwith(TestRabbitBroker(app.broker,connect_only=True),TestApp(app),):# test somethingpass
importpytestfromfaststreamimportFastStream,TestAppfromfaststream.natsimportNatsBroker,TestNatsBrokerapp=FastStream(NatsBroker())@app.after_startupasyncdefhandle():print("Calls in tests too!")@pytest.mark.asyncioasyncdeftest_lifespan():asyncwith(TestNatsBroker(app.broker,connect_only=True),TestApp(app),):# test somethingpass
importpytestfromfaststreamimportFastStream,TestAppfromfaststream.redisimportRedisBroker,TestRedisBrokerapp=FastStream(RedisBroker())@app.after_startupasyncdefhandle():print("Calls in tests too!")@pytest.mark.asyncioasyncdeftest_lifespan():asyncwith(TestRedisBroker(app.broker,connect_only=True),TestApp(app),):# test somethingpass
If you want to use In-Memory patched broker in your tests, it's advisable to patch the broker first (before applying the application patch).
Also, TestApp and TestBroker are calling broker.start() both. According to the original logic, broker should be started in the FastStream application, but TestBroker applied first breaks this behavior. This reason TestApp prevents TestBrokerbroker.start() call if it placed inside TestBroker context.
This behavior is ruled by connect_onlyTestBroker argument. By default it has None value, but TestApp can set it to True/False by inner logic. To prevent this "magic", just setup connect_only argument manually.
Warning
With connect_only=False, all FastStream hooks will be called after broker was started, what can breaks some @app.on_startup logic.