Phase 2: Job enqueueing from counter

- Add backend/jobs.py with enqueue_random_number_job function
- Modify counter increment endpoint to enqueue job after incrementing
- Add mock_enqueue_job fixture to conftest.py for all tests
- Add test_increment_enqueues_job_with_user_id to verify correct user_id
- Job is enqueued synchronously; failure causes request to fail
This commit is contained in:
counterweight 2025-12-21 22:44:31 +01:00
parent 10c0316603
commit 6ca0ae88dd
Signed by: counterweight
GPG key ID: 883EDBAA726BD96C
4 changed files with 98 additions and 2 deletions

View file

@ -1,5 +1,6 @@
import os
from contextlib import asynccontextmanager
from unittest.mock import AsyncMock, patch
# Set required env vars before importing app
os.environ.setdefault("SECRET_KEY", "test-secret-key-for-testing-only")
@ -238,3 +239,16 @@ async def user_no_roles(client_factory):
"cookies": dict(response.cookies),
"response": response,
}
@pytest.fixture(autouse=True)
def mock_enqueue_job():
"""Mock job enqueueing for all tests.
pgqueuer requires PostgreSQL-specific features that aren't available
in the test database setup. We mock the enqueue function to avoid
connection issues while still testing the counter logic.
"""
mock = AsyncMock(return_value=1) # Return a fake job ID
with patch("routes.counter.enqueue_random_number_job", mock):
yield mock

View file

@ -11,6 +11,38 @@ from tests.conftest import create_user_with_roles
from tests.helpers import create_invite_for_godfather, unique_email
@pytest.mark.asyncio
async def test_increment_enqueues_job_with_user_id(client_factory, mock_enqueue_job):
"""Verify that incrementing the counter enqueues a job with the user's ID."""
async with client_factory.get_db_session() as db:
godfather = await create_user_with_roles(
db, unique_email("gf"), "pass123", [ROLE_REGULAR]
)
invite_code = await create_invite_for_godfather(db, godfather.id)
reg = await client_factory.post(
"/api/auth/register",
json={
"email": unique_email(),
"password": "testpass123",
"invite_identifier": invite_code,
},
)
cookies = dict(reg.cookies)
# Get user ID from the me endpoint
async with client_factory.create(cookies=cookies) as authed:
me_response = await authed.get("/api/auth/me")
user_id = me_response.json()["id"]
# Increment counter
response = await authed.post("/api/counter/increment")
assert response.status_code == 200
# Verify enqueue was called with the correct user_id
mock_enqueue_job.assert_called_once_with(user_id)
# Protected endpoint tests - without auth
@pytest.mark.asyncio
async def test_get_counter_requires_auth(client):