Hello!
I understand you're encountering an issue where your pytest tests are running twice, likely due to the way pulsar_manager.unsubscribe() interacts within your FastAPI application's lifespan context manager. Let's address your concerns step-by-step and provide a solution to ensure unsubscribe() is called appropriately when the entire application shuts down, as well as making PulsarManager work asynchronously.
1. Understanding FastAPI's Lifespan Context Manager
When is shutdown Called?
In FastAPI, the lifespan context manager is designed to handle the entire lifecycle of the application. This includes:
- Startup: Code within the startup section runs once when the application starts.
- Shutdown: Code within the shutdown section runs once when the application is shutting down.
Key Point: The shutdown section is not called after each router evaluation or every request. It is only invoked when the entire application is stopping or restarting.
2. Why Are Pytest Tests Running Twice?
Given that the shutdown code is executed once per application lifecycle, seeing tests run twice suggests that the application's lifespan context manager might be invoked multiple times during testing. This can happen due to:
- Multiple Application Instances: If each test creates a new instance of the FastAPI app, the
shutdown code will run once per instance.
- Pytest Configuration: Certain configurations or plugins might cause tests to run multiple times or instantiate the app multiple times.
Solution:
- Ensure Singleton Behavior for
PulsarManager: Make sure pulsar_manager is instantiated only once, preferably as a singleton.
- Review Test Setup: Check your pytest fixtures and test setup to ensure that the FastAPI app isn't being initialized multiple times unintentionally.
3. Making PulsarManager Asynchronous
The primary issue arises because pulsar_manager.unsubscribe() is synchronous, but it's being called within an asynchronous lifespan context manager. To solve this, we can adapt PulsarManager to support asynchronous operations.
Approach:
-
Use asyncio to Run Synchronous Code Asynchronously:
- Utilize
asyncio’s run_in_executor to run blocking operations without blocking the event loop.
-
Modify PulsarManager to Include Asynchronous Methods:
- Introduce asynchronous wrappers around synchronous methods like
unsubscribe.
Updated PulsarManager Implementation:
import enum
import uuid
from datetime import datetime
from typing import Literal, Optional, Union
from uuid import UUID
import asyncio
from pydantic import BaseModel, Field, HttpUrl
import pulsar
from src.config import settings
__all__ = [
"PulsarManager",
"pulsar_manager",
"PulsarSourceType",
"PulsarActionType",
"PulsarTwitterEvent",
"PulsarDiscordEvent",
"PulsarUserEvent",
"PulsarUser",
"PulsarDiscord",
"PulsarTwitter",
"PulsarAuth",
"PulsarAuthEvent",
]
# [Your existing Pydantic models and enums remain unchanged]
class PulsarManager:
def __init__(self) -> None:
self._event_topic = f"persistent://{settings.PULSAR_TENANT_NAME}/{settings.PULSAR_NAMESPACE}/{settings.PULSAR_TOPIC_NAME}"
self._auth_topic = f"persistent://{settings.PULSAR_TENANT_NAME}/{settings.PULSAR_NAMESPACE}/{settings.PULSAR_AUTH_TOPIC_NAME}"
self._client = pulsar.Client(
settings.PULSAR_SERVICE_URL,
authentication=pulsar.AuthenticationToken(settings.PULSAR_TOKEN),
)
event_producer = self._client.create_producer(self._event_topic)
auth_producer = self._client.create_producer(self._auth_topic)
self._subscription_name = f"auth-subscription-{uuid.uuid4()}"
self._source_to_producer_map = {
PulsarSourceType.AUTH: auth_producer,
PulsarSourceType.USER: event_producer,
PulsarSourceType.DISCORD: event_producer,
PulsarSourceType.TWITTER: event_producer,
}
self._auth_consumer = None
def _get_producer(self, source_type: PulsarSourceType):
return self._source_to_producer_map[source_type]
def set_consumer_with_callback(self, listener):
if self._auth_consumer is None:
self._auth_consumer = self._client.subscribe(
self._auth_topic,
self._subscription_name,
pulsar.ConsumerType.Exclusive,
message_listener=listener,
)
def unsubscribe(self):
if self._auth_consumer:
self._auth_consumer.unsubscribe()
self._auth_consumer = None # Ensure it's only unsubscribed once
def produce_event(
self,
event: Union[
PulsarTwitterEvent, PulsarDiscordEvent, PulsarUserEvent, PulsarAuthEvent
],
):
data = PulsarEvent(payload=event).model_dump_json()
producer = self._get_producer(event.source)
producer.send(data.encode("utf-8"))
def consume_auth_event(self, msg) -> PulsarAuth:
try:
event = PulsarEvent.model_validate_json(msg.data().decode("utf-8"))
self._auth_consumer.acknowledge(msg)
return event.payload.data
except Exception:
self._auth_consumer.negative_acknowledge(msg)
async def unsubscribe_async(self):
loop = asyncio.get_running_loop()
# Run the synchronous unsubscribe in a separate thread to prevent blocking
await loop.run_in_executor(None, self.unsubscribe)
pulsar_manager = PulsarManager()
Key Changes:
unsubscribe_async Method: This asynchronous method leverages asyncio’s run_in_executor to run the synchronous unsubscribe without blocking the event loop.
- Idempotent Unsubscribe: The
unsubscribe method sets self._auth_consumer to None after unsubscribing to prevent multiple unsubscriptions.
4. Updating the Lifespan Context Manager
Now, modify your lifespan context manager to call the asynchronous unsubscribe_async method during shutdown.
Updated main.py:
from fastapi import FastAPI
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(_application: FastAPI) -> AsyncGenerator:
# Startup
await redis_manager.connect()
await database.connect()
try:
yield
finally:
# Shutdown
await database.disconnect()
await redis_manager.disconnect()
await pulsar_manager.unsubscribe_async()
app = FastAPI(lifespan=lifespan)
Alternative Approach Using Event Handlers:
Alternatively, you can use FastAPI's event handlers for startup and shutdown, which some developers find clearer and more flexible.
from fastapi import FastAPI
app = FastAPI()
@app.on_event("startup")
async def on_startup():
await redis_manager.connect()
await database.connect()
# Initialize Pulsar consumers if needed
@app.on_event("shutdown")
async def on_shutdown():
await database.disconnect()
await redis_manager.disconnect()
await pulsar_manager.unsubscribe_async()
5. Additional Recommendations
-
Ensure Singleton Behavior for PulsarManager:
- Make sure
pulsar_manager is instantiated only once and shared across your application to prevent multiple subscriptions or unsubscriptions.
-
Add Logging for Debugging:
- Incorporate logging within your
PulsarManager methods and lifespan context manager to trace when connections are made and closed. This can help identify if unsubscribe_async is being called multiple times.
import logging
logger = logging.getLogger(__name__)
class PulsarManager:
# [existing methods]
def unsubscribe(self):
if self._auth_consumer:
self._auth_consumer.unsubscribe()
logger.info("Unsubscribed from auth consumer.")
self._auth_consumer = None
async def unsubscribe_async(self):
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, self.unsubscribe)
logger.info("Completed async unsubscribe.")
-
Review Pytest Fixtures:
- Ensure that your pytest fixtures are correctly scoped. For instance, using
scope="session" for fixtures that initialize the FastAPI app can prevent multiple instances during testing.
import pytest
from fastapi.testclient import TestClient
from main import app
@pytest.fixture(scope="session")
def test_client():
with TestClient(app) as client:
yield client
-
Check for Duplicated Test Runs:
- Sometimes, IDEs or CI pipelines might be configured to run tests multiple times. Verify your test runner configurations to ensure tests aren't inadvertently executed more than once.
6. Conclusion
By making PulsarManager support asynchronous operations and ensuring that the unsubscribe method is invoked only once during the application's shutdown phase, you should resolve the issue of tests running twice. Additionally, reviewing your test setup can help ensure that the application isn't being instantiated multiple times during testing.
If after these changes you continue to experience issues with tests running twice, please provide more details about your test setup (e.g., pytest configurations, fixtures) so I can offer more targeted assistance.
Feel free to reach out if you have further questions or need additional help!