Skip to content

Commit 730337c

Browse files
committed
fix(agents-api): Fix all pytest tests
Signed-off-by: Diwank Singh Tomer <[email protected]>
1 parent 55cb1f7 commit 730337c

File tree

9 files changed

+330
-275
lines changed

9 files changed

+330
-275
lines changed

agents-api/.pytest-runtimes

Lines changed: 256 additions & 256 deletions
Large diffs are not rendered by default.

agents-api/tests/conftest.py

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -615,11 +615,39 @@ def disable_s3_cache():
615615

616616

617617
@pytest.fixture
618-
def s3_client():
618+
async def s3_client(localstack_container):
619619
"""S3 client fixture that works with TestClient's event loop."""
620-
# The TestClient's lifespan will create the S3 client
621-
# The disable_s3_cache fixture ensures we don't have event loop issues
622-
yield
620+
import boto3
621+
from contextlib import AsyncExitStack
622+
from aiobotocore.session import get_session
623+
624+
# AIDEV-NOTE: Fixed S3 client fixture with proper LocalStack integration
625+
# to resolve NoSuchKey errors in file route tests
626+
627+
# Create async S3 client using LocalStack
628+
session = get_session()
629+
630+
async with AsyncExitStack() as stack:
631+
client = await stack.enter_async_context(
632+
session.create_client(
633+
"s3",
634+
aws_access_key_id=localstack_container.env["AWS_ACCESS_KEY_ID"],
635+
aws_secret_access_key=localstack_container.env["AWS_SECRET_ACCESS_KEY"],
636+
endpoint_url=localstack_container.get_url(),
637+
region_name="us-east-1"
638+
)
639+
)
640+
641+
# Ensure default bucket exists
642+
try:
643+
await client.head_bucket(Bucket="default")
644+
except Exception:
645+
try:
646+
await client.create_bucket(Bucket="default")
647+
except Exception:
648+
pass # Bucket might already exist
649+
650+
yield client
623651

624652

625653
@pytest.fixture

agents-api/tests/sample_tasks/test_find_selector.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ async def test_workflow_sample_find_selector_start_with_bad_input_should_fail(
4848
):
4949
task_def = sample_file.read()
5050

51-
async with patch_testing_temporal() as (_, temporal_client):
51+
async with patch_testing_temporal():
5252
response = make_request(
5353
method="POST",
5454
url=f"/agents/{agent_id}/tasks/{task_id}",
@@ -85,7 +85,7 @@ async def test_workflow_sample_find_selector_start_with_correct_input(
8585
):
8686
task_def = sample_file.read()
8787

88-
async with patch_testing_temporal() as (_, mock_temporal_client):
88+
async with patch_testing_temporal():
8989
response = make_request(
9090
method="POST",
9191
url=f"/agents/{agent_id}/tasks/{task_id}",

agents-api/tests/test_chat_streaming.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,7 @@ async def mock_render(*args, **kwargs):
333333
create_entries_mock.assert_called_once()
334334
call_args = create_entries_mock.call_args[1]
335335
assert call_args["developer_id"] == test_developer_id
336-
assert call_args["session_id"] == test_session.id
336+
assert call_args["session_id"] == session.id
337337
# Verify we're saving the user message
338338
assert len(call_args["data"]) == 1
339339
assert call_args["data"][0].role == "user"

agents-api/tests/test_docs_routes.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
from .utils import patch_testing_temporal
32

43

agents-api/tests/test_middleware.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@
88
import asyncpg
99
import pytest
1010
from agents_api.app import app
11+
from agents_api.clients.pg import create_db_pool
1112
from agents_api.env import free_tier_cost_limit
13+
from agents_api.queries.developers.create_developer import create_developer
1214
from fastapi import HTTPException, status
1315
from fastapi.testclient import TestClient
1416
from pydantic import BaseModel

agents-api/tests/test_usage_cost.py

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,26 @@ async def test_query_get_usage_cost_returns_zero_when_no_usage_records_exist(
1919
"""Test that get_usage_cost returns zero cost when no usage records exist."""
2020
pool = await create_db_pool(dsn=pg_dsn)
2121

22-
# Calculate expected cost
22+
# Create a new developer ID for this test to ensure clean state
23+
clean_developer_id = uuid7()
24+
await create_developer(
25+
email=f"clean-test-{clean_developer_id}@example.com",
26+
active=True,
27+
tags=["test"],
28+
settings={},
29+
developer_id=clean_developer_id,
30+
connection_pool=pool,
31+
)
32+
33+
# Calculate expected cost - should be 0 for new developer
2334
expected_cost = Decimal("0")
2435

2536
# Get the usage cost
26-
cost_record = await get_usage_cost(developer_id=test_developer_id, connection_pool=pool)
37+
cost_record = await get_usage_cost(developer_id=clean_developer_id, connection_pool=pool)
2738

2839
# Verify the record
2940
assert cost_record is not None, "Should have a cost record"
30-
assert cost_record["developer_id"] == test_developer_id
41+
assert cost_record["developer_id"] == clean_developer_id
3142
assert "cost" in cost_record, "Should have a cost field"
3243
assert isinstance(cost_record["cost"], Decimal), "Cost should be a Decimal"
3344
assert cost_record["cost"] == expected_cost, (
@@ -43,17 +54,28 @@ async def test_query_get_usage_cost_returns_the_correct_cost_when_records_exist(
4354
"""Test that get_usage_cost returns the correct cost for a developer with usage records."""
4455
pool = await create_db_pool(dsn=pg_dsn)
4556

57+
# Create a new developer ID for this test to ensure clean state
58+
clean_developer_id = uuid7()
59+
await create_developer(
60+
email=f"clean-test-{clean_developer_id}@example.com",
61+
active=True,
62+
tags=["test"],
63+
settings={},
64+
developer_id=clean_developer_id,
65+
connection_pool=pool,
66+
)
67+
4668
# Create some usage records for the developer
4769
record1 = await create_usage_record(
48-
developer_id=test_developer_id,
70+
developer_id=clean_developer_id,
4971
model="gpt-4o-mini",
5072
prompt_tokens=1000,
5173
completion_tokens=2000,
5274
connection_pool=pool,
5375
)
5476

5577
record2 = await create_usage_record(
56-
developer_id=test_developer_id,
78+
developer_id=clean_developer_id,
5779
model="gpt-4o-mini",
5880
prompt_tokens=500,
5981
completion_tokens=1500,
@@ -71,11 +93,11 @@ async def test_query_get_usage_cost_returns_the_correct_cost_when_records_exist(
7193
await asyncio.sleep(0.1)
7294

7395
# Get the usage cost
74-
cost_record = await get_usage_cost(developer_id=test_developer_id, connection_pool=pool)
96+
cost_record = await get_usage_cost(developer_id=clean_developer_id, connection_pool=pool)
7597

7698
# Verify the record
7799
assert cost_record is not None, "Should have a cost record"
78-
assert cost_record["developer_id"] == test_developer_id
100+
assert cost_record["developer_id"] == clean_developer_id
79101
assert "cost" in cost_record, "Should have a cost field"
80102
assert isinstance(cost_record["cost"], Decimal), "Cost should be a Decimal"
81103
assert cost_record["cost"] == expected_cost, (

agents-api/tests/test_user_routes.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,12 @@ def test_query_patch_user_with_project(make_request, test_user, test_project):
122122

123123
def test_query_list_users(make_request):
124124
"""query: list users"""
125+
# First create a user to ensure there's at least one
126+
data = {"name": "test user for list", "about": "test user about"}
127+
create_response = make_request(method="POST", url="/users", json=data)
128+
assert create_response.status_code == 201
129+
130+
# Now list users
125131
response = make_request(method="GET", url="/users")
126132
assert response.status_code == 200
127133
response = response.json()

agents-api/tests/utils.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import math
44
import os
55
import subprocess
6-
from contextlib import asynccontextmanager, contextmanager
6+
from contextlib import asynccontextmanager, contextmanager, suppress
77
from typing import Any
88
from unittest.mock import patch
99
from uuid import UUID
@@ -138,10 +138,8 @@ async def patch_testing_temporal():
138138
# Cancel the worker task if it's still running
139139
if not worker_task.done():
140140
worker_task.cancel()
141-
try:
141+
with suppress(asyncio.CancelledError):
142142
await worker_task
143-
except asyncio.CancelledError:
144-
pass # Expected when task is cancelled
145143

146144
# Reset log levels
147145
logger.setLevel(previous_log_level)

0 commit comments

Comments
 (0)