同步完整源码 - 2026-05-25
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
import pytest
|
||||
from httpx import ASGITransport
|
||||
|
||||
|
||||
__all__ = [
|
||||
"async_app_client",
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def async_app_client(event_loop):
|
||||
from httpx import AsyncClient
|
||||
|
||||
from agentops.app import app
|
||||
|
||||
client = AsyncClient(
|
||||
transport=ASGITransport(app=app),
|
||||
base_url="http://test",
|
||||
)
|
||||
yield client
|
||||
await client.aclose() # Properly close the client
|
||||
@@ -0,0 +1,193 @@
|
||||
import pytest
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from unittest.mock import MagicMock
|
||||
from agentops.opsboard.models import BillingPeriod, OrgModel, UserOrgModel, OrgRoles, PremStatus
|
||||
from .billing_constants import (
|
||||
STRIPE_SUBSCRIPTION_ID_DEFAULT,
|
||||
STRIPE_CUSTOMER_ID_DEFAULT,
|
||||
STRIPE_PRICE_ID_CURRENT,
|
||||
STRIPE_PRICE_ID_LEGACY,
|
||||
STRIPE_ITEM_ID_DEFAULT,
|
||||
SEAT_PRICE_DEFAULT,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def billing_period_factory():
|
||||
"""Factory for creating billing periods with unique, predictable dates."""
|
||||
counter = 0
|
||||
|
||||
def create_period(org_id, **kwargs):
|
||||
nonlocal counter
|
||||
counter += 1
|
||||
|
||||
# Use year 2025 + counter to ensure uniqueness and avoid past dates
|
||||
base_date = datetime(2025, 1, 1, tzinfo=timezone.utc) + timedelta(days=counter * 2)
|
||||
|
||||
defaults = {
|
||||
'period_start': base_date,
|
||||
'period_end': base_date + timedelta(days=1),
|
||||
'seat_cost': 0,
|
||||
'seat_count': 0,
|
||||
'usage_costs': {},
|
||||
'usage_quantities': {},
|
||||
'total_cost': 0,
|
||||
'status': 'pending',
|
||||
}
|
||||
defaults.update(kwargs)
|
||||
|
||||
return BillingPeriod(org_id=org_id, **defaults)
|
||||
|
||||
return create_period
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_stripe_subscription():
|
||||
"""Centralized Stripe subscription mock with consistent behavior."""
|
||||
mock_sub = MagicMock()
|
||||
mock_sub.id = STRIPE_SUBSCRIPTION_ID_DEFAULT
|
||||
mock_sub.customer = STRIPE_CUSTOMER_ID_DEFAULT
|
||||
mock_sub.status = "active"
|
||||
mock_sub.cancel_at_period_end = False
|
||||
|
||||
# Use dynamic timestamps to avoid hardcoded values
|
||||
now = datetime.now()
|
||||
mock_sub.current_period_start = int(now.timestamp())
|
||||
mock_sub.current_period_end = int((now + timedelta(days=30)).timestamp())
|
||||
|
||||
# Standard subscription item
|
||||
mock_item = {
|
||||
'id': STRIPE_ITEM_ID_DEFAULT,
|
||||
'price': {
|
||||
'id': STRIPE_PRICE_ID_CURRENT, # Matches STRIPE_SUBSCRIPTION_PRICE_ID
|
||||
'unit_amount': SEAT_PRICE_DEFAULT, # Amount in cents
|
||||
'currency': 'usd',
|
||||
'recurring': {'usage_type': 'licensed', 'interval': 'month', 'interval_count': 1},
|
||||
},
|
||||
'quantity': 2,
|
||||
}
|
||||
|
||||
mock_sub.items = MagicMock()
|
||||
mock_sub.items.data = [mock_item]
|
||||
|
||||
def mock_get(key, default=None):
|
||||
if key == 'cancel_at_period_end':
|
||||
return mock_sub.cancel_at_period_end
|
||||
elif key == 'items':
|
||||
return {'data': mock_sub.items.data}
|
||||
elif key == 'current_period_end':
|
||||
return mock_sub.current_period_end
|
||||
elif key == 'current_period_start':
|
||||
return mock_sub.current_period_start
|
||||
elif key == 'status':
|
||||
return mock_sub.status
|
||||
return default
|
||||
|
||||
mock_sub.get = mock_get
|
||||
return mock_sub
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_stripe_subscription_legacy():
|
||||
"""Specialized mock for legacy subscription tests."""
|
||||
mock_sub = MagicMock()
|
||||
mock_sub.id = "sub_legacy_123"
|
||||
mock_sub.customer = STRIPE_CUSTOMER_ID_DEFAULT
|
||||
mock_sub.status = "active"
|
||||
mock_sub.cancel_at_period_end = False
|
||||
|
||||
now = datetime.now()
|
||||
mock_sub.current_period_start = int(now.timestamp())
|
||||
mock_sub.current_period_end = int((now + timedelta(days=30)).timestamp())
|
||||
|
||||
# Legacy subscription with old price ID
|
||||
legacy_item = {
|
||||
'id': 'si_legacy_123',
|
||||
'price': {
|
||||
'id': STRIPE_PRICE_ID_LEGACY, # Different from current
|
||||
'product': {'name': 'Legacy Seat Plan'},
|
||||
},
|
||||
'quantity': 1,
|
||||
}
|
||||
mock_sub.items = MagicMock()
|
||||
mock_sub.items.data = [legacy_item]
|
||||
|
||||
def mock_get(key, default=None):
|
||||
if key == 'cancel_at_period_end':
|
||||
return mock_sub.cancel_at_period_end
|
||||
elif key == 'items':
|
||||
return {'data': mock_sub.items.data}
|
||||
elif key == 'current_period_end':
|
||||
return mock_sub.current_period_end
|
||||
elif key == 'current_period_start':
|
||||
return mock_sub.current_period_start
|
||||
elif key == 'status':
|
||||
return mock_sub.status
|
||||
return default
|
||||
|
||||
mock_sub.get = mock_get
|
||||
return mock_sub
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def org_factory():
|
||||
"""Factory for creating organizations with different configurations."""
|
||||
created_orgs = []
|
||||
|
||||
def create_org(orm_session, owner_user, **kwargs):
|
||||
defaults = {
|
||||
'name': f"Test Org {len(created_orgs) + 1}",
|
||||
'prem_status': PremStatus.free,
|
||||
'subscription_id': None,
|
||||
}
|
||||
defaults.update(kwargs)
|
||||
|
||||
org = OrgModel(**defaults)
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Add owner relationship
|
||||
owner_member = UserOrgModel(
|
||||
user_id=owner_user.id,
|
||||
org_id=org.id,
|
||||
role=OrgRoles.owner,
|
||||
user_email=owner_user.email,
|
||||
is_paid=defaults['prem_status'] == PremStatus.pro,
|
||||
)
|
||||
orm_session.add(owner_member)
|
||||
orm_session.flush()
|
||||
|
||||
created_orgs.append(org)
|
||||
return org
|
||||
|
||||
return create_org
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_pro_org(orm_session, test_user, org_factory):
|
||||
"""Standard pro organization for billing tests."""
|
||||
return org_factory(
|
||||
orm_session,
|
||||
test_user,
|
||||
name="Test Pro Org",
|
||||
prem_status=PremStatus.pro,
|
||||
subscription_id=STRIPE_SUBSCRIPTION_ID_DEFAULT,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_free_org(orm_session, test_user, org_factory):
|
||||
"""Standard free organization for testing upgrades."""
|
||||
return org_factory(orm_session, test_user, name="Test Free Org", prem_status=PremStatus.free)
|
||||
|
||||
|
||||
def assert_billing_error(exception_info, expected_code, expected_message_fragment):
|
||||
"""Standard assertion for billing-related errors."""
|
||||
assert exception_info.value.status_code == expected_code
|
||||
assert expected_message_fragment in str(exception_info.value.detail)
|
||||
|
||||
|
||||
def assert_stripe_error_handling(exception_info):
|
||||
"""Standard assertion for Stripe API error handling."""
|
||||
assert exception_info.value.status_code == 500
|
||||
assert "Stripe API error" in exception_info.value.detail
|
||||
@@ -0,0 +1,19 @@
|
||||
# Stripe Test IDs
|
||||
STRIPE_SUBSCRIPTION_ID_DEFAULT = "sub_test123"
|
||||
STRIPE_CUSTOMER_ID_DEFAULT = "cus_test123"
|
||||
STRIPE_PRICE_ID_CURRENT = "price_test123"
|
||||
STRIPE_PRICE_ID_LEGACY = "price_legacy_old_123"
|
||||
STRIPE_ITEM_ID_DEFAULT = "si_test123"
|
||||
|
||||
# Pricing (in cents)
|
||||
SEAT_PRICE_DEFAULT = 4000 # $40.00
|
||||
SEAT_PRICE_PREMIUM = 5000 # $50.00
|
||||
TOKEN_COST_SAMPLE = 150 # Sample token cost
|
||||
SPAN_COST_SAMPLE = 50 # Sample span cost
|
||||
|
||||
# Usage Quantities
|
||||
TOKEN_QUANTITY_SAMPLE = 750000
|
||||
SPAN_QUANTITY_SAMPLE = 50
|
||||
|
||||
# Timestamps (Unix timestamps for consistency)
|
||||
FUTURE_TIMESTAMP = 1735689600 # 2025-01-01
|
||||
@@ -0,0 +1,279 @@
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
from .common import REPO_ROOT, is_github_actions, get_free_port
|
||||
|
||||
|
||||
# these vars are also hard-coded inside the `clickhouse_server` Dockerfile and the
|
||||
# github actions workflow
|
||||
TEST_CLICKHOUSE_HOST = "localhost"
|
||||
TEST_CLICKHOUSE_PORT = get_free_port(8123)
|
||||
TEST_CLICKHOUSE_HTTP_PORT = get_free_port(9000)
|
||||
TEST_CLICKHOUSE_DATABASE = "otel_2" # this has to be the same as prod because the schema has it hard-coded
|
||||
TEST_CLICKHOUSE_USER = "default"
|
||||
TEST_CLICKHOUSE_PASSWORD = "clickhouse"
|
||||
|
||||
CLICKHOUSE_MIGRATIONS_DIR = REPO_ROOT / 'clickhouse' / 'migrations'
|
||||
CLICKHOUSE_DOCKER_IMAGE_PATH = Path(__file__).parent / "clickhouse_server" / "Dockerfile"
|
||||
CLICKHOUSE_DOCKER_CONTAINER_NAME = "agentops-test-clickhouse"
|
||||
|
||||
__all__ = [
|
||||
'clickhouse_verify_test_environment',
|
||||
'clickhouse_setup_db_server',
|
||||
'clickhouse_client',
|
||||
'async_clickhouse_client',
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def clickhouse_verify_test_environment():
|
||||
"""Verify we don't have access to production credentials before running tests."""
|
||||
message = "%s environment variable is set! This risks connecting to production."
|
||||
assert not os.environ.get('CLICKHOUSE_HOST'), message % "CLICKHOUSE_HOST"
|
||||
assert not os.environ.get('CLICKHOUSE_PORT'), message % "CLICKHOUSE_PORT"
|
||||
assert not os.environ.get('CLICKHOUSE_DATABASE'), message % "CLICKHOUSE_DATABASE"
|
||||
assert not os.environ.get('CLICKHOUSE_USER'), message % "CLICKHOUSE_USER"
|
||||
assert not os.environ.get('CLICKHOUSE_PASSWORD'), message % "CLICKHOUSE_PASSWORD"
|
||||
|
||||
|
||||
def clickhouse_start_docker():
|
||||
"""Start the Docker container for ClickHouse."""
|
||||
print("Starting ClickHouse Docker container...")
|
||||
|
||||
# Clean up any existing container
|
||||
subprocess.run(['docker', 'stop', CLICKHOUSE_DOCKER_CONTAINER_NAME], check=False)
|
||||
subprocess.run(['docker', 'rm', CLICKHOUSE_DOCKER_CONTAINER_NAME], check=False)
|
||||
|
||||
# Build the Docker image
|
||||
build_command = [
|
||||
'docker',
|
||||
'build',
|
||||
'-t',
|
||||
CLICKHOUSE_DOCKER_CONTAINER_NAME,
|
||||
'-f',
|
||||
str(CLICKHOUSE_DOCKER_IMAGE_PATH),
|
||||
str(CLICKHOUSE_DOCKER_IMAGE_PATH.parent),
|
||||
]
|
||||
print(' '.join(build_command))
|
||||
subprocess.run(build_command, check=True)
|
||||
|
||||
# Run the container
|
||||
run_command = [
|
||||
'docker',
|
||||
'run',
|
||||
'-d',
|
||||
'--name',
|
||||
CLICKHOUSE_DOCKER_CONTAINER_NAME,
|
||||
'-p',
|
||||
f'{TEST_CLICKHOUSE_PORT}:8123',
|
||||
'-p',
|
||||
f'{TEST_CLICKHOUSE_HTTP_PORT}:9000',
|
||||
CLICKHOUSE_DOCKER_CONTAINER_NAME,
|
||||
]
|
||||
print(' '.join(run_command))
|
||||
subprocess.run(run_command, check=True)
|
||||
|
||||
|
||||
def clickhouse_stop_docker():
|
||||
"""Stop the Docker container."""
|
||||
print("Stopping ClickHouse Docker container...")
|
||||
subprocess.run(['docker', 'stop', CLICKHOUSE_DOCKER_CONTAINER_NAME], check=True)
|
||||
|
||||
|
||||
def clickhouse_verify_connection(client):
|
||||
"""Verify the connection to the database uses the test environment."""
|
||||
|
||||
def _get_auth_header(username: str, password: str) -> str:
|
||||
from base64 import b64encode
|
||||
|
||||
# from clickhouse_connect/driver/httpclient.py:126
|
||||
return 'Basic ' + b64encode(f'{username}:{password}'.encode()).decode()
|
||||
|
||||
assert TEST_CLICKHOUSE_HOST in client.url
|
||||
assert str(TEST_CLICKHOUSE_PORT) in client.url
|
||||
assert client.database == TEST_CLICKHOUSE_DATABASE
|
||||
assert client.headers['Authorization'] == _get_auth_header(TEST_CLICKHOUSE_USER, TEST_CLICKHOUSE_PASSWORD)
|
||||
|
||||
|
||||
async def clickhouse_run_migrations(client):
|
||||
"""Run database schema initialization and migrations."""
|
||||
print("Running ClickHouse migrations...")
|
||||
|
||||
# Basic setup
|
||||
# extracted from prod with:
|
||||
# SELECT concat('SET ', name, ' = \'', value, '\';') as settings FROM system.settings WHERE changed = 1 FORMAT TSVRaw;
|
||||
setup_query = """
|
||||
SET min_joined_block_size_bytes = '524288';
|
||||
SET max_insert_threads = '2';
|
||||
SET max_insert_delayed_streams_for_parallel_write = '50';
|
||||
SET max_threads = '5';
|
||||
SET use_concurrency_control = '0';
|
||||
SET use_hedged_requests = '0';
|
||||
SET s3_skip_empty_files = '0';
|
||||
SET distributed_foreground_insert = '1';
|
||||
SET insert_distributed_sync = '1';
|
||||
SET alter_sync = '0';
|
||||
SET replication_alter_partitions_sync = '0';
|
||||
SET allow_suspicious_types_in_group_by = '1';
|
||||
SET allow_suspicious_types_in_order_by = '1';
|
||||
SET enable_memory_bound_merging_of_aggregation_results = '1';
|
||||
SET merge_tree_use_v1_object_and_dynamic_serialization = '1';
|
||||
SET do_not_merge_across_partitions_select_final = '0';
|
||||
SET log_queries = '1';
|
||||
SET log_queries_probability = '1';
|
||||
SET http_response_headers = '{}';
|
||||
SET max_http_get_redirects = '10';
|
||||
SET send_progress_in_http_headers = '1';
|
||||
SET http_headers_progress_interval_ms = '60000';
|
||||
SET query_plan_join_swap_table = '0';
|
||||
SET enable_zstd_qat_codec = '0';
|
||||
SET query_profiler_real_time_period_ns = '0';
|
||||
SET max_bytes_before_external_group_by = '8589934592';
|
||||
SET max_bytes_before_external_sort = '8589934592';
|
||||
SET max_result_rows = '500000';
|
||||
SET result_overflow_mode = 'break';
|
||||
SET join_algorithm = 'default';
|
||||
SET max_memory_usage = '17179869184';
|
||||
SET backup_restore_keeper_max_retries = '20';
|
||||
SET backup_restore_keeper_retry_max_backoff_ms = '60000';
|
||||
SET backup_restore_failure_after_host_disconnected_for_seconds = '0';
|
||||
SET backup_restore_keeper_max_retries_while_initializing = '0';
|
||||
SET backup_restore_keeper_max_retries_while_handling_error = '0';
|
||||
SET backup_restore_finish_timeout_after_error_sec = '0';
|
||||
SET enable_job_stack_trace = '0';
|
||||
SET cancel_http_readonly_queries_on_client_close = '1';
|
||||
SET least_greatest_legacy_null_behavior = '1';
|
||||
SET max_table_size_to_drop = '1000000000000';
|
||||
SET max_partition_size_to_drop = '1000000000000';
|
||||
SET default_table_engine = 'ReplicatedMergeTree';
|
||||
SET mutations_sync = '0';
|
||||
SET validate_mutation_query = '0';
|
||||
SET optimize_trivial_insert_select = '0';
|
||||
SET max_size_to_preallocate_for_aggregation = '100000000';
|
||||
SET max_size_to_preallocate_for_joins = '100000000';
|
||||
SET database_replicated_allow_only_replicated_engine = '1';
|
||||
SET database_replicated_allow_replicated_engine_arguments = '2';
|
||||
SET cloud_mode = '1';
|
||||
SET cloud_mode_engine = '2';
|
||||
SET distributed_ddl_output_mode = 'none_only_active';
|
||||
SET distributed_ddl_entry_format_version = '6';
|
||||
SET query_plan_merge_filters = '1';
|
||||
SET async_insert_max_data_size = '10485760';
|
||||
SET async_insert_busy_timeout_max_ms = '1000';
|
||||
SET async_insert_busy_timeout_ms = '1000';
|
||||
SET enable_filesystem_cache = '1';
|
||||
SET filesystem_cache_name = 's3diskWithCache';
|
||||
SET enable_filesystem_cache_on_write_operations = '1';
|
||||
SET filesystem_cache_skip_download_if_exceeds_per_query_cache_write_limit = '1';
|
||||
SET skip_download_if_exceeds_query_cache = '1';
|
||||
SET filesystem_cache_boundary_alignment = '0';
|
||||
SET load_marks_asynchronously = '1';
|
||||
SET allow_prefetched_read_pool_for_remote_filesystem = '1';
|
||||
SET filesystem_prefetch_max_memory_usage = '1717986918';
|
||||
SET filesystem_prefetches_limit = '200';
|
||||
SET compatibility = '24.10';
|
||||
SET insert_keeper_max_retries = '20';
|
||||
SET cluster_for_parallel_replicas = 'default';
|
||||
SET parallel_replicas_local_plan = '0';
|
||||
SET push_external_roles_in_interserver_queries = '0';
|
||||
--SET shared_merge_tree_sync_parts_on_partition_operations = '1';
|
||||
SET allow_experimental_materialized_postgresql_table = '0';
|
||||
SET enable_deflate_qpl_codec = '0';
|
||||
SET date_time_input_format = 'best_effort';
|
||||
"""
|
||||
for command in setup_query.split(';'):
|
||||
try:
|
||||
client.command(command)
|
||||
except Exception as e:
|
||||
if "Empty query" in str(e):
|
||||
continue
|
||||
raise e
|
||||
|
||||
# Find and run migration files
|
||||
migration_files = sorted(CLICKHOUSE_MIGRATIONS_DIR.glob('*.sql'))
|
||||
print(f"Running {len(migration_files)} migrations...")
|
||||
|
||||
for migration_file in migration_files:
|
||||
print(f"Running migration: {os.path.basename(migration_file)}")
|
||||
with open(migration_file) as f:
|
||||
sql = f.read()
|
||||
# run commands one at a time cuz that's how it be in Clickhouse
|
||||
for command in sql.split(';'):
|
||||
try:
|
||||
client.command(command)
|
||||
except Exception as e:
|
||||
if "Empty query" in str(e):
|
||||
continue
|
||||
raise e
|
||||
|
||||
print("Migrations complete!")
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
async def clickhouse_setup_db_server():
|
||||
"""Configure test database server and connection."""
|
||||
from agentops.api.db.clickhouse_client import ConnectionConfig, get_clickhouse
|
||||
|
||||
# Override environment variables for test
|
||||
ConnectionConfig.host = TEST_CLICKHOUSE_HOST
|
||||
ConnectionConfig.port = TEST_CLICKHOUSE_PORT
|
||||
ConnectionConfig.database = TEST_CLICKHOUSE_DATABASE
|
||||
ConnectionConfig.username = TEST_CLICKHOUSE_USER
|
||||
ConnectionConfig.password = TEST_CLICKHOUSE_PASSWORD
|
||||
ConnectionConfig.secure = False
|
||||
|
||||
if not is_github_actions():
|
||||
clickhouse_start_docker()
|
||||
|
||||
print(f"Waiting for ClickHouse to be ready at {TEST_CLICKHOUSE_HOST}:{TEST_CLICKHOUSE_PORT}...")
|
||||
|
||||
# Wait for ClickHouse to be available
|
||||
for attempt in range(30):
|
||||
try:
|
||||
# Use clickhouse_connect directly for the health check
|
||||
client = get_clickhouse()
|
||||
client.command("SELECT 1")
|
||||
print("ClickHouse is ready!")
|
||||
break
|
||||
except Exception:
|
||||
print('.', end='', flush=True)
|
||||
time.sleep(2)
|
||||
else:
|
||||
raise Exception("Failed to connect to ClickHouse after multiple attempts")
|
||||
|
||||
# Get clickhouse client and verify connection
|
||||
client = get_clickhouse()
|
||||
clickhouse_verify_connection(client)
|
||||
|
||||
# Run migrations
|
||||
await clickhouse_run_migrations(client)
|
||||
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
if not is_github_actions():
|
||||
clickhouse_stop_docker()
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
async def clickhouse_client():
|
||||
"""Fixture to provide a clickhouse client for tests."""
|
||||
from agentops.api.db.clickhouse_client import get_clickhouse
|
||||
|
||||
client = get_clickhouse()
|
||||
clickhouse_verify_connection(client)
|
||||
|
||||
yield client
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
async def async_clickhouse_client():
|
||||
"""Fixture to provide an async clickhouse client for tests."""
|
||||
from agentops.api.db.clickhouse_client import get_async_clickhouse
|
||||
|
||||
client = await get_async_clickhouse()
|
||||
clickhouse_verify_connection(client.client)
|
||||
|
||||
yield client
|
||||
@@ -0,0 +1,17 @@
|
||||
FROM clickhouse/clickhouse-server:24.12
|
||||
|
||||
# Set environment variables
|
||||
# TODO I dont think user/pass actually modify the install, but they do reference
|
||||
# the actual values we see inside the container
|
||||
ENV CLICKHOUSE_USER=default
|
||||
ENV CLICKHOUSE_PASSWORD=clickhouse
|
||||
ENV CLICKHOUSE_DB=otel_2
|
||||
|
||||
# Expose ports
|
||||
EXPOSE 8123
|
||||
EXPOSE 9000
|
||||
|
||||
# Add healthcheck
|
||||
HEALTHCHECK --interval=10s --timeout=5s --retries=5 \
|
||||
CMD wget --no-verbose --tries=1 --spider http://localhost:8123/ping || exit 1
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import os
|
||||
import socket
|
||||
from pathlib import Path
|
||||
|
||||
# the root of the repository
|
||||
REPO_ROOT = Path(__file__).parent.parent.parent.parent
|
||||
APP_DIR = REPO_ROOT / 'api'
|
||||
|
||||
__all__ = [
|
||||
'REPO_ROOT',
|
||||
'APP_DIR',
|
||||
'is_github_actions',
|
||||
'get_free_port',
|
||||
]
|
||||
|
||||
|
||||
def is_github_actions():
|
||||
"""Check if we're running in GitHub Actions CI."""
|
||||
return os.environ.get('GITHUB_ACTIONS') == 'true'
|
||||
|
||||
|
||||
def get_free_port(start_port: int) -> int:
|
||||
"""Get a free port starting from start_port, incrementing by 1."""
|
||||
if is_github_actions():
|
||||
# postgres will already be running by the time we get here in CI
|
||||
return start_port
|
||||
|
||||
while True:
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
||||
try:
|
||||
s.bind(('localhost', start_port))
|
||||
return start_port
|
||||
except OSError:
|
||||
start_port += 1
|
||||
@@ -0,0 +1,134 @@
|
||||
import pytest
|
||||
from sqlalchemy import orm
|
||||
|
||||
from agentops.opsboard.models import (
|
||||
OrgModel,
|
||||
UserOrgModel,
|
||||
ProjectModel,
|
||||
OrgRoles,
|
||||
Environment,
|
||||
PremStatus,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
'test_org',
|
||||
'test_org_prem',
|
||||
'test_user_org_member',
|
||||
'test_user_org_owner',
|
||||
'test_user_org_owner_prem',
|
||||
'test_project',
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def test_org(orm_session) -> OrgModel:
|
||||
"""Create a test organization with no membership."""
|
||||
# Create an org
|
||||
org = OrgModel(name="Test Org for Projects")
|
||||
orm_session.add(org)
|
||||
orm_session.flush() # Use flush instead of commit to keep transaction open
|
||||
|
||||
# Return the org
|
||||
return org
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def test_org_prem(orm_session) -> OrgModel:
|
||||
"""Create a test organization with no membership."""
|
||||
# Create an org
|
||||
org = OrgModel(
|
||||
name="Test Premium Org for Projects",
|
||||
prem_status=PremStatus.pro,
|
||||
)
|
||||
orm_session.add(org)
|
||||
orm_session.flush() # Use flush instead of commit to keep transaction open
|
||||
|
||||
# Return the org
|
||||
return org
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def test_user_org_member(orm_session, test_org, test_user) -> OrgModel:
|
||||
"""Create a user-org relationship with member role."""
|
||||
# Create a user-org relationship with the test user as member
|
||||
user_org = UserOrgModel(
|
||||
user_id=test_user.id,
|
||||
org_id=test_org.id,
|
||||
role=OrgRoles.developer,
|
||||
user_email=test_user.email,
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.commit()
|
||||
|
||||
# Return the org with users loaded
|
||||
org = orm_session.query(OrgModel).options(orm.joinedload(OrgModel.users)).filter_by(id=test_org.id).one()
|
||||
|
||||
return org
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def test_user_org_owner(orm_session, test_org, test_user) -> OrgModel:
|
||||
"""Create a user-org relationship with owner role."""
|
||||
# Create a user-org relationship with the test user as owner
|
||||
user_org = UserOrgModel(
|
||||
user_id=test_user.id,
|
||||
org_id=test_org.id,
|
||||
role=OrgRoles.owner,
|
||||
user_email=test_user.email,
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.commit() # Commit to ensure persistence
|
||||
|
||||
# Return the org with users loaded
|
||||
org = orm_session.query(OrgModel).options(orm.joinedload(OrgModel.users)).filter_by(id=test_org.id).one()
|
||||
|
||||
return org
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def test_user_org_owner_prem(orm_session, test_org_prem, test_user) -> OrgModel:
|
||||
"""Create a user-org relationship with owner role and premium plan."""
|
||||
# Create a user-org relationship with the test user as owner
|
||||
user_org = UserOrgModel(
|
||||
user_id=test_user.id,
|
||||
org_id=test_org_prem.id,
|
||||
role=OrgRoles.owner,
|
||||
user_email=test_user.email,
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.commit()
|
||||
|
||||
# Return the org with users loaded
|
||||
org = (
|
||||
orm_session.query(OrgModel)
|
||||
.options(orm.joinedload(OrgModel.users))
|
||||
.filter_by(id=test_org_prem.id)
|
||||
.one()
|
||||
)
|
||||
|
||||
return org
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def test_project(orm_session, test_user_org_owner) -> ProjectModel:
|
||||
"""Create a test project for the test organization with owner relationship."""
|
||||
# We use test_user_org_owner which gives us an org with the test user as owner
|
||||
org = test_user_org_owner
|
||||
|
||||
project = ProjectModel(
|
||||
name="Test Project",
|
||||
org_id=org.id,
|
||||
environment=Environment.development,
|
||||
)
|
||||
orm_session.add(project)
|
||||
orm_session.commit() # Commit to ensure persistence
|
||||
|
||||
# Return the project with org relationship loaded
|
||||
project = (
|
||||
orm_session.query(ProjectModel)
|
||||
.options(orm.joinedload(ProjectModel.org).joinedload(OrgModel.users))
|
||||
.filter_by(id=project.id)
|
||||
.one()
|
||||
)
|
||||
|
||||
return project
|
||||
@@ -0,0 +1,290 @@
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
from .common import is_github_actions, get_free_port
|
||||
|
||||
|
||||
# these vars are also hard-coded inside the `supabase_server` Dockerfile and the
|
||||
# github actions workflow
|
||||
TEST_SUPABASE_HOST = "localhost"
|
||||
TEST_SUPABASE_PORT = get_free_port(5432)
|
||||
TEST_SUPABASE_NAME = "test_db"
|
||||
TEST_SUPABASE_USER = "postgres"
|
||||
TEST_SUPABASE_PASSWORD = "postgres"
|
||||
|
||||
SUPABASE_DOCKER_IMAGE_PATH = Path(__file__).parent / "supabase_server" / "Dockerfile"
|
||||
SUPABASE_DOCKER_CONTAINER_NAME = "agentops-test-supabase"
|
||||
|
||||
__all__ = [
|
||||
'supabase_verify_test_environment',
|
||||
'supabase_setup_db_server',
|
||||
'db_session',
|
||||
'orm_session',
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
def supabase_verify_test_environment():
|
||||
"""Verify we don't have access to production credentials before running tests."""
|
||||
message = "%s environment variable is set! This risks connecting to production."
|
||||
assert not os.environ.get('SUPABASE_HOST'), message % "SUPABASE_HOST"
|
||||
assert not os.environ.get('SUPABASE_PORT'), message % "SUPABASE_PORT"
|
||||
assert not os.environ.get('SUPABASE_DATABASE'), message % "SUPABASE_DATABASE"
|
||||
assert not os.environ.get('SUPABASE_USER'), message % "SUPABASE_USER"
|
||||
assert not os.environ.get('SUPABASE_PASSWORD'), message % "SUPABASE_PASSWORD"
|
||||
|
||||
|
||||
def supabase_start_docker():
|
||||
"""Start the Docker container for PostgreSQL."""
|
||||
print("Starting Supabase/Postgres Docker container...")
|
||||
|
||||
subprocess.run(['docker', 'stop', SUPABASE_DOCKER_CONTAINER_NAME], check=False)
|
||||
subprocess.run(['docker', 'rm', SUPABASE_DOCKER_CONTAINER_NAME], check=False)
|
||||
subprocess.run(
|
||||
[
|
||||
'docker',
|
||||
'build',
|
||||
'-t',
|
||||
SUPABASE_DOCKER_CONTAINER_NAME,
|
||||
'-f',
|
||||
str(SUPABASE_DOCKER_IMAGE_PATH),
|
||||
str(SUPABASE_DOCKER_IMAGE_PATH.parent),
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
subprocess.run(
|
||||
[
|
||||
'docker',
|
||||
'run',
|
||||
'-d',
|
||||
'--name',
|
||||
SUPABASE_DOCKER_CONTAINER_NAME,
|
||||
'-p',
|
||||
f'{TEST_SUPABASE_PORT}:5432',
|
||||
SUPABASE_DOCKER_CONTAINER_NAME,
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
|
||||
|
||||
def supabase_stop_docker():
|
||||
"""Stop the Docker container."""
|
||||
print("Stopping Supabase/Postgres Docker container...")
|
||||
subprocess.run(['docker', 'stop', SUPABASE_DOCKER_CONTAINER_NAME], check=True)
|
||||
|
||||
|
||||
def supabase_verify_connection(conn):
|
||||
"""Verify the connection to the database uses the test environment."""
|
||||
assert conn.info.host == TEST_SUPABASE_HOST
|
||||
assert conn.info.port == TEST_SUPABASE_PORT
|
||||
assert conn.info.dbname == TEST_SUPABASE_NAME
|
||||
assert conn.info.user == TEST_SUPABASE_USER
|
||||
assert conn.info.password == TEST_SUPABASE_PASSWORD
|
||||
|
||||
|
||||
async def supabase_run_migrations(conn):
|
||||
"""Run database schema initialization and migrations."""
|
||||
|
||||
print("Running Supabase migrations...")
|
||||
with conn.cursor() as cur:
|
||||
# we need to do some stuff to get the new database to match what we expect
|
||||
# in Supabase. Some of these `SET`s might not be necessary, but they don't hurt.
|
||||
setup_query = """
|
||||
SET statement_timeout = 0;
|
||||
SET lock_timeout = 0;
|
||||
SET idle_in_transaction_session_timeout = 0;
|
||||
SET client_encoding = 'UTF8';
|
||||
SET standard_conforming_strings = on;
|
||||
SET search_path TO public;
|
||||
SET check_function_bodies = false;
|
||||
SET xmloption = content;
|
||||
SET client_min_messages = warning;
|
||||
SET row_security = off;
|
||||
|
||||
-- Create essential extensions
|
||||
CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
|
||||
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
|
||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||
|
||||
-- Create auth schema and dummy JWT function
|
||||
CREATE OR REPLACE FUNCTION auth.jwt() RETURNS jsonb AS $$
|
||||
BEGIN
|
||||
RETURN '{"role": "authenticated", "sub": "00000000-0000-0000-0000-000000000000"}'::jsonb;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- the production bucket table differs from the one in the docker image
|
||||
-- so we drop it and recreate it
|
||||
DROP TABLE IF EXISTS storage.buckets CASCADE;
|
||||
CREATE TABLE IF NOT EXISTS storage.buckets (
|
||||
id text NOT NULL,
|
||||
name text NOT NULL,
|
||||
owner uuid,
|
||||
created_at timestamp with time zone DEFAULT now(),
|
||||
updated_at timestamp with time zone DEFAULT now(),
|
||||
public boolean DEFAULT false,
|
||||
avif_autodetection boolean DEFAULT false,
|
||||
file_size_limit bigint,
|
||||
allowed_mime_types text[],
|
||||
CONSTRAINT buckets_pkey PRIMARY KEY (id)
|
||||
);
|
||||
|
||||
-- create two test users in the auth.users table so that we can reference them
|
||||
-- TODO move these to be inside the test_user, test_user2, and test_user3 fixtures
|
||||
-- so that it's obvious they are dependencies
|
||||
INSERT INTO auth.users (
|
||||
id,
|
||||
instance_id,
|
||||
aud,
|
||||
role,
|
||||
email,
|
||||
encrypted_password,
|
||||
confirmed_at,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (
|
||||
'00000000-0000-0000-0000-000000000000',
|
||||
'00000000-0000-0000-0000-000000000000',
|
||||
'authenticated',
|
||||
'authenticated',
|
||||
'test@example.com',
|
||||
'$2a$10$abcdefghijklmnopqrstuvwxyz0123456789',
|
||||
NOW(),
|
||||
NOW(),
|
||||
NOW()
|
||||
), (
|
||||
'00000000-0000-0000-0000-000000000001',
|
||||
'00000000-0000-0000-0000-000000000000',
|
||||
'authenticated',
|
||||
'authenticated',
|
||||
'test2@example.com',
|
||||
'$2a$10$abcdefghijklmnopqrstuvwxyz0123456789',
|
||||
NOW(),
|
||||
NOW(),
|
||||
NOW()
|
||||
), (
|
||||
'00000000-0000-0000-0000-000000000002',
|
||||
'00000000-0000-0000-0000-000000000000',
|
||||
'authenticated',
|
||||
'authenticated',
|
||||
'test3@example.com',
|
||||
'$2a$10$abcdefghijklmnopqrstuvwxyz0123456789',
|
||||
NOW(),
|
||||
NOW(),
|
||||
NOW()
|
||||
);
|
||||
"""
|
||||
cur.execute(setup_query)
|
||||
|
||||
# migration files sorted by name
|
||||
migrations_dir = Path(__file__).parents[3] / 'supabase' / 'migrations'
|
||||
migration_files = sorted(migrations_dir.glob('*.sql'))
|
||||
|
||||
print(f"Running {len(migration_files)} migrations...")
|
||||
|
||||
for migration_file in migration_files:
|
||||
print(f"Running migration: {os.path.basename(migration_file)}")
|
||||
with open(migration_file) as f:
|
||||
sql = f.read()
|
||||
cur.execute(sql)
|
||||
|
||||
# update public.orgs to have a `subscription_id TEXT DEFAULT ''` because this is in
|
||||
# prod, but not in the schema migrations.
|
||||
orgs_subscription_id_query = """
|
||||
ALTER TABLE public.orgs
|
||||
ADD COLUMN IF NOT EXISTS subscription_id TEXT DEFAULT '';
|
||||
"""
|
||||
cur.execute(orgs_subscription_id_query)
|
||||
|
||||
conn.commit() # must commit transaction to apply changes
|
||||
print("Migrations complete!")
|
||||
|
||||
|
||||
@pytest.fixture(scope="session", autouse=True)
|
||||
async def supabase_setup_db_server():
|
||||
"""Configure test database server and connection."""
|
||||
import time
|
||||
import psycopg
|
||||
from agentops.common.postgres import get_connection, close_connection, ConnectionConfig
|
||||
|
||||
# Close any existing connections (sweaty)
|
||||
close_connection()
|
||||
|
||||
if not is_github_actions():
|
||||
supabase_start_docker()
|
||||
|
||||
# NOTE: we do not need to save or restore these variables as the tests will run
|
||||
# and then we'll be done
|
||||
ConnectionConfig.host = TEST_SUPABASE_HOST
|
||||
ConnectionConfig.port = TEST_SUPABASE_PORT
|
||||
ConnectionConfig.database = TEST_SUPABASE_NAME
|
||||
ConnectionConfig.user = TEST_SUPABASE_USER
|
||||
ConnectionConfig.password = TEST_SUPABASE_PASSWORD
|
||||
|
||||
print(f"Waiting for PostgreSQL to be ready at {ConnectionConfig.host}:{ConnectionConfig.port}...")
|
||||
|
||||
for attempt in range(30):
|
||||
try:
|
||||
# Use psycopg directly for the health check
|
||||
conn = psycopg.connect(ConnectionConfig.to_connection_string())
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("SELECT 1")
|
||||
conn.close()
|
||||
print("PostgreSQL is ready!")
|
||||
break
|
||||
except Exception:
|
||||
print('.', end='', flush=True)
|
||||
time.sleep(2)
|
||||
else:
|
||||
raise Exception("Failed to connect to PostgreSQL after multiple attempts")
|
||||
|
||||
pool = get_connection()
|
||||
with pool.connection() as conn:
|
||||
# double-check connection info (sweaty)
|
||||
supabase_verify_connection(conn)
|
||||
|
||||
# run migrations once for the session
|
||||
await supabase_run_migrations(conn)
|
||||
|
||||
yield
|
||||
|
||||
if not is_github_actions():
|
||||
supabase_stop_docker()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
async def db_session():
|
||||
"""Session fixture providing a database connection."""
|
||||
from agentops.common.postgres import get_connection, close_connection
|
||||
|
||||
print("Creating database connection...")
|
||||
pool = get_connection()
|
||||
with pool.connection() as conn:
|
||||
try:
|
||||
# double-check connection uses test creds (sweaty)
|
||||
supabase_verify_connection(conn)
|
||||
|
||||
yield conn
|
||||
except Exception as e:
|
||||
print(f"Error during database session: {str(e)}")
|
||||
conn.rollback()
|
||||
finally:
|
||||
close_connection()
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
async def orm_session():
|
||||
"""Fixture to provide an orm session for tests."""
|
||||
# does not automatically commit or rollback
|
||||
from agentops.common.orm import get_orm_session
|
||||
|
||||
session = next(get_orm_session())
|
||||
|
||||
# double-check connection uses test creds (sweaty)
|
||||
conn = session.connection()
|
||||
supabase_verify_connection(conn.connection.driver_connection)
|
||||
|
||||
yield session
|
||||
|
||||
session.close()
|
||||
@@ -0,0 +1,13 @@
|
||||
FROM supabase/postgres:15.1.0.103
|
||||
|
||||
# Set environment variables
|
||||
ENV POSTGRES_USER=postgres
|
||||
ENV POSTGRES_PASSWORD=postgres
|
||||
ENV POSTGRES_DB=test_db
|
||||
|
||||
# Expose port
|
||||
EXPOSE 5432
|
||||
|
||||
# Add healthcheck
|
||||
HEALTHCHECK --interval=5s --timeout=5s --retries=5 \
|
||||
CMD ["pg_isready", "-U", "postgres", "-p", "5432"]
|
||||
@@ -0,0 +1,73 @@
|
||||
import pytest
|
||||
import uuid
|
||||
from sqlalchemy.orm import Session
|
||||
from agentops.opsboard.models import UserModel
|
||||
|
||||
__all__ = [
|
||||
"test_user",
|
||||
"test_user2",
|
||||
"test_user3",
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
async def test_user(orm_session: Session) -> UserModel:
|
||||
"""Create a test user that persists for the entire test session.
|
||||
This user corresponds to the first auth.users entry with ID 00000000-0000-0000-0000-000000000000."""
|
||||
|
||||
user_id = uuid.UUID("00000000-0000-0000-0000-000000000000")
|
||||
|
||||
# Check if user already exists
|
||||
existing_user = orm_session.query(UserModel).filter_by(id=user_id).first()
|
||||
if existing_user:
|
||||
return existing_user
|
||||
|
||||
# Create a new test user
|
||||
user = UserModel(id=user_id, full_name="Test User", email="test@example.com", survey_is_complete=False)
|
||||
|
||||
orm_session.add(user)
|
||||
orm_session.commit()
|
||||
|
||||
return user
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
async def test_user2(orm_session: Session) -> UserModel:
|
||||
"""Create a second test user that persists for the entire test session.
|
||||
This user corresponds to the second auth.users entry with ID 00000000-0000-0000-0000-000000000001."""
|
||||
|
||||
user_id = uuid.UUID("00000000-0000-0000-0000-000000000001")
|
||||
|
||||
# Check if user already exists
|
||||
existing_user = orm_session.query(UserModel).filter_by(id=user_id).first()
|
||||
if existing_user:
|
||||
return existing_user
|
||||
|
||||
# Create a new test user
|
||||
user = UserModel(id=user_id, full_name="Test User 2", email="test2@example.com", survey_is_complete=False)
|
||||
|
||||
orm_session.add(user)
|
||||
orm_session.commit()
|
||||
|
||||
return user
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
async def test_user3(orm_session: Session) -> UserModel:
|
||||
"""Create a third test user that persists for the entire test session.
|
||||
This user corresponds to a third auth.users entry with ID 00000000-0000-0000-0000-000000000002."""
|
||||
|
||||
user_id = uuid.UUID("00000000-0000-0000-0000-000000000002")
|
||||
|
||||
# Check if user already exists
|
||||
existing_user = orm_session.query(UserModel).filter_by(id=user_id).first()
|
||||
if existing_user:
|
||||
return existing_user
|
||||
|
||||
# Create a new test user
|
||||
user = UserModel(id=user_id, full_name="Test User 3", email="test3@example.com", survey_is_complete=False)
|
||||
|
||||
orm_session.add(user)
|
||||
orm_session.commit()
|
||||
|
||||
return user
|
||||
@@ -0,0 +1,177 @@
|
||||
import pytest
|
||||
import jwt
|
||||
from datetime import datetime, timedelta
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
from agentops.api.auth import (
|
||||
JWTPayload,
|
||||
generate_jwt,
|
||||
verify_jwt,
|
||||
get_jwt_token,
|
||||
JWT_ALGO,
|
||||
_generate_jwt_timestamp,
|
||||
)
|
||||
from agentops.api.environment import JWT_SECRET_KEY
|
||||
from fastapi import HTTPException
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def jwt_secret():
|
||||
"""Get the JWT secret from environment variables"""
|
||||
return JWT_SECRET_KEY
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_project():
|
||||
"""Mock a project model for testing"""
|
||||
mock = MagicMock()
|
||||
mock.id = "test-project-id"
|
||||
mock.api_key = "test-api-key"
|
||||
mock.org.prem_status.value = "premium"
|
||||
return mock
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def valid_jwt_payload():
|
||||
"""Create a valid JWT payload for testing"""
|
||||
return JWTPayload(
|
||||
exp=_generate_jwt_timestamp(),
|
||||
aud="authenticated",
|
||||
project_id="test-project-id",
|
||||
project_prem_status="premium",
|
||||
api_key="test-api-key",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def expired_jwt_payload():
|
||||
"""Create an expired JWT payload for testing"""
|
||||
return JWTPayload(
|
||||
exp=int((datetime.now() - timedelta(hours=1)).timestamp()),
|
||||
aud="authenticated",
|
||||
project_id="test-project-id",
|
||||
project_prem_status="premium",
|
||||
api_key="test-api-key",
|
||||
)
|
||||
|
||||
|
||||
class TestJWTPayload:
|
||||
"""Tests for the JWTPayload class"""
|
||||
|
||||
def test_jwt_payload_asdict(self, valid_jwt_payload):
|
||||
"""Test that asdict returns a properly formatted dictionary"""
|
||||
payload_dict = valid_jwt_payload.asdict()
|
||||
assert "exp" in payload_dict
|
||||
assert "api_key" in payload_dict
|
||||
assert payload_dict["project_id"] == "test-project-id"
|
||||
assert payload_dict["project_prem_status"] == "premium"
|
||||
assert payload_dict["aud"] == "authenticated"
|
||||
|
||||
# Dev flag should not be in dict by default
|
||||
assert "dev" not in payload_dict
|
||||
|
||||
def test_jwt_payload_asdict_with_dev(self, valid_jwt_payload):
|
||||
"""Test that asdict includes dev flag when set"""
|
||||
valid_jwt_payload.dev = True
|
||||
payload_dict = valid_jwt_payload.asdict()
|
||||
assert "dev" in payload_dict
|
||||
assert payload_dict["dev"] is True
|
||||
|
||||
def test_jwt_payload_from_project(self, mock_project):
|
||||
"""Test creating JWT payload from a project model"""
|
||||
payload = JWTPayload.from_project(mock_project)
|
||||
assert payload.project_id == "test-project-id"
|
||||
assert payload.project_prem_status == "premium"
|
||||
assert payload.api_key == "test-api-key"
|
||||
assert payload.aud == "authenticated"
|
||||
assert isinstance(payload.exp, int)
|
||||
assert payload.dev is False
|
||||
|
||||
def test_jwt_payload_from_project_with_dev(self, mock_project):
|
||||
"""Test creating JWT payload from a project model with dev flag"""
|
||||
payload = JWTPayload.from_project(mock_project, dev=True)
|
||||
assert payload.dev is True
|
||||
|
||||
|
||||
class TestJWTGeneration:
|
||||
"""Tests for JWT generation functions"""
|
||||
|
||||
def test_generate_jwt(self, mock_project, jwt_secret):
|
||||
"""Test generating a JWT token from a project"""
|
||||
token = generate_jwt(mock_project)
|
||||
assert isinstance(token, str)
|
||||
|
||||
# Decode the token and verify contents
|
||||
decoded = jwt.decode(token, jwt_secret, algorithms=[JWT_ALGO], audience="authenticated")
|
||||
assert decoded["project_id"] == "test-project-id"
|
||||
assert decoded["project_prem_status"] == "premium"
|
||||
assert decoded["api_key"] == "test-api-key"
|
||||
assert "exp" in decoded
|
||||
|
||||
def test_verify_jwt_valid(self, valid_jwt_payload, jwt_secret):
|
||||
"""Test that a valid JWT token can be verified"""
|
||||
# Generate a token manually
|
||||
token = jwt.encode(valid_jwt_payload.asdict(), jwt_secret, algorithm=JWT_ALGO)
|
||||
|
||||
# Verify the token
|
||||
payload = verify_jwt(token)
|
||||
assert isinstance(payload, JWTPayload)
|
||||
assert payload.project_id == "test-project-id"
|
||||
assert payload.project_prem_status == "premium"
|
||||
|
||||
def test_verify_jwt_expired(self, expired_jwt_payload, jwt_secret):
|
||||
"""Test that an expired JWT token raises an error"""
|
||||
# Generate an expired token
|
||||
token = jwt.encode(expired_jwt_payload.asdict(), jwt_secret, algorithm=JWT_ALGO)
|
||||
|
||||
# Verify the token - should raise ExpiredSignatureError
|
||||
with pytest.raises(jwt.ExpiredSignatureError):
|
||||
verify_jwt(token)
|
||||
|
||||
def test_verify_jwt_invalid_audience(self, valid_jwt_payload, jwt_secret):
|
||||
"""Test that a JWT with invalid audience raises an error"""
|
||||
# Create payload with wrong audience
|
||||
valid_jwt_payload.aud = "wrong-audience"
|
||||
token = jwt.encode(valid_jwt_payload.asdict(), jwt_secret, algorithm=JWT_ALGO)
|
||||
|
||||
# Verify the token - should raise InvalidAudienceError
|
||||
with pytest.raises(jwt.InvalidAudienceError):
|
||||
verify_jwt(token)
|
||||
|
||||
|
||||
class TestJWTDependency:
|
||||
"""Tests for the get_jwt_token dependency"""
|
||||
|
||||
async def test_get_jwt_token_valid(self, valid_jwt_payload, jwt_secret):
|
||||
"""Test that a valid JWT token can be extracted from headers"""
|
||||
# Generate a token manually
|
||||
token = jwt.encode(valid_jwt_payload.asdict(), jwt_secret, algorithm=JWT_ALGO)
|
||||
|
||||
# Create authorization header
|
||||
authorization = f"Bearer {token}"
|
||||
|
||||
# Get JWT token from header
|
||||
with patch('agentops.api.auth.verify_jwt', return_value=valid_jwt_payload):
|
||||
payload = await get_jwt_token(authorization)
|
||||
assert payload == valid_jwt_payload
|
||||
|
||||
async def test_get_jwt_token_missing_header(self):
|
||||
"""Test that missing authorization header raises an error"""
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await get_jwt_token(None)
|
||||
assert exc_info.value.status_code == 401
|
||||
assert "Authorization header missing" in exc_info.value.detail
|
||||
|
||||
async def test_get_jwt_token_invalid_format(self):
|
||||
"""Test that invalid format raises an error"""
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await get_jwt_token("InvalidFormat")
|
||||
assert exc_info.value.status_code == 401
|
||||
assert "Invalid token format" in exc_info.value.detail
|
||||
|
||||
async def test_get_jwt_token_invalid_scheme(self):
|
||||
"""Test that invalid scheme raises an error"""
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await get_jwt_token("Basic token123")
|
||||
assert exc_info.value.status_code == 401
|
||||
assert "Invalid authentication scheme" in exc_info.value.detail
|
||||
@@ -0,0 +1,226 @@
|
||||
import pytest
|
||||
from io import BytesIO
|
||||
from unittest.mock import patch, MagicMock, AsyncMock
|
||||
from fastapi import HTTPException, status, Request
|
||||
|
||||
from agentops.api.storage import BaseObjectUploadView, ObjectUploadResponse
|
||||
from agentops.api.environment import (
|
||||
SUPABASE_URL,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_jwt_payload():
|
||||
"""Mock JWT payload for testing"""
|
||||
return {
|
||||
'project_id': 'test-project-123',
|
||||
'project_prem_status': 'premium',
|
||||
'api_key': 'test-api-key',
|
||||
'aud': 'authenticated',
|
||||
'exp': 1234567890,
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_s3_client():
|
||||
"""Mock S3 client for testing"""
|
||||
client = MagicMock()
|
||||
client.upload_fileobj = MagicMock()
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_request():
|
||||
"""Mock FastAPI Request for testing"""
|
||||
request = MagicMock(spec=Request)
|
||||
|
||||
# Create a proper async iterator for the stream method
|
||||
async def async_stream_generator(chunks):
|
||||
for chunk in chunks:
|
||||
yield chunk
|
||||
|
||||
# Default stream that will be overridden in individual tests
|
||||
request.stream = AsyncMock(return_value=async_stream_generator([]))
|
||||
return request
|
||||
|
||||
|
||||
class ConcreteObjectUploadView(BaseObjectUploadView):
|
||||
"""Concrete implementation for testing BaseObjectUploadView"""
|
||||
|
||||
bucket_name = "test-bucket"
|
||||
|
||||
@property
|
||||
def filename(self) -> str:
|
||||
return f"test-file-{self.token['project_id']}.txt"
|
||||
|
||||
|
||||
class TestBaseObjectUploadView:
|
||||
"""Tests for the BaseObjectUploadView class"""
|
||||
|
||||
def test_bucket_name_assertion(self, mock_jwt_payload, mock_request):
|
||||
"""Test that bucket_name assertion works"""
|
||||
view = ConcreteObjectUploadView(mock_request)
|
||||
view.bucket_name = None
|
||||
|
||||
async def async_stream_generator():
|
||||
for chunk in [b'test content']:
|
||||
yield chunk
|
||||
|
||||
mock_request.stream = lambda: async_stream_generator()
|
||||
|
||||
with pytest.raises(AssertionError, match="`bucket_name` must be provided"):
|
||||
import asyncio
|
||||
|
||||
asyncio.run(view(token=mock_jwt_payload))
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_successful_upload(self, mock_jwt_payload, mock_s3_client, mock_request):
|
||||
"""Test successful file upload"""
|
||||
view = ConcreteObjectUploadView(mock_request)
|
||||
|
||||
# Mock request stream
|
||||
test_content = b'test file content'
|
||||
|
||||
async def async_stream_generator():
|
||||
for chunk in [test_content]:
|
||||
yield chunk
|
||||
|
||||
mock_request.stream = lambda: async_stream_generator()
|
||||
|
||||
with patch('agentops.api.storage.get_s3_client', return_value=mock_s3_client):
|
||||
response = await view(token=mock_jwt_payload)
|
||||
|
||||
assert isinstance(response, ObjectUploadResponse)
|
||||
assert response.size == len(test_content)
|
||||
assert (
|
||||
response.url
|
||||
== f"{SUPABASE_URL}/storage/v1/object/public/test-bucket/test-file-test-project-123.txt"
|
||||
)
|
||||
|
||||
# Verify S3 upload was called
|
||||
mock_s3_client.upload_fileobj.assert_called_once()
|
||||
args = mock_s3_client.upload_fileobj.call_args[0]
|
||||
assert isinstance(args[0], BytesIO)
|
||||
assert args[1] == "test-bucket"
|
||||
assert args[2] == "test-file-test-project-123.txt"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_file_size_limit_exceeded(self, mock_jwt_payload, mock_request):
|
||||
"""Test that files exceeding size limit are rejected"""
|
||||
view = ConcreteObjectUploadView(mock_request)
|
||||
view.max_size = 10 # Set very small limit
|
||||
|
||||
# Mock request stream with large content
|
||||
large_content = b'x' * 20 # Exceeds 10 byte limit
|
||||
|
||||
async def async_stream_generator():
|
||||
for chunk in [large_content]:
|
||||
yield chunk
|
||||
|
||||
mock_request.stream = lambda: async_stream_generator()
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await view(token=mock_jwt_payload)
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_413_REQUEST_ENTITY_TOO_LARGE
|
||||
assert "File size exceeds the maximum limit" in exc_info.value.detail
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_chunked_upload(self, mock_jwt_payload, mock_s3_client, mock_request):
|
||||
"""Test that chunked uploads work correctly"""
|
||||
view = ConcreteObjectUploadView(mock_request)
|
||||
|
||||
# Mock request stream with multiple chunks
|
||||
chunks = [b'chunk1', b'chunk2', b'chunk3']
|
||||
|
||||
async def async_stream_generator():
|
||||
for chunk in chunks:
|
||||
yield chunk
|
||||
|
||||
mock_request.stream = lambda: async_stream_generator()
|
||||
|
||||
with patch('agentops.api.storage.get_s3_client', return_value=mock_s3_client):
|
||||
response = await view(token=mock_jwt_payload)
|
||||
|
||||
assert response.size == sum(len(chunk) for chunk in chunks)
|
||||
|
||||
# Verify the complete content was uploaded
|
||||
uploaded_content = mock_s3_client.upload_fileobj.call_args[0][0]
|
||||
uploaded_content.seek(0)
|
||||
assert uploaded_content.read() == b''.join(chunks)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_chunked_upload_size_limit(self, mock_jwt_payload, mock_request):
|
||||
"""Test size limit enforcement with chunked uploads"""
|
||||
view = ConcreteObjectUploadView(mock_request)
|
||||
view.max_size = 15
|
||||
|
||||
# Create chunks that exceed limit when combined
|
||||
chunks = [b'chunk1', b'chunk2', b'chunk3'] # Total: 18 bytes
|
||||
|
||||
async def async_stream_generator():
|
||||
for chunk in chunks:
|
||||
yield chunk
|
||||
|
||||
mock_request.stream = lambda: async_stream_generator()
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await view(token=mock_jwt_payload)
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_413_REQUEST_ENTITY_TOO_LARGE
|
||||
|
||||
def test_public_url_generation(self, mock_jwt_payload, mock_request):
|
||||
"""Test that public URL is generated correctly"""
|
||||
view = ConcreteObjectUploadView(mock_request)
|
||||
view.token = mock_jwt_payload
|
||||
|
||||
expected_url = f"{SUPABASE_URL}/storage/v1/object/public/test-bucket/test-file-test-project-123.txt"
|
||||
assert view.public_url == expected_url
|
||||
|
||||
def test_filename_property_abstract(self, mock_request):
|
||||
"""Test that filename property must be implemented"""
|
||||
|
||||
class IncompleteView(BaseObjectUploadView):
|
||||
bucket_name = "test"
|
||||
# Missing filename property implementation - inherits ellipsis (...) from base
|
||||
|
||||
view = IncompleteView(mock_request)
|
||||
view.token = {'project_id': 'test'}
|
||||
|
||||
# The ellipsis (...) in the base class returns None (property implementation issue)
|
||||
# This test verifies that subclasses should implement their own filename property
|
||||
result = view.filename
|
||||
assert result is None, "Incomplete view returns None from base class ellipsis property"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_upload_body_method(self, mock_jwt_payload, mock_s3_client, mock_request):
|
||||
"""Test the upload_body method directly"""
|
||||
view = ConcreteObjectUploadView(mock_request)
|
||||
view.token = mock_jwt_payload
|
||||
view.client = mock_s3_client
|
||||
|
||||
test_body = BytesIO(b'test content')
|
||||
await view.upload_body(test_body)
|
||||
|
||||
mock_s3_client.upload_fileobj.assert_called_once_with(
|
||||
test_body, "test-bucket", "test-file-test-project-123.txt"
|
||||
)
|
||||
|
||||
|
||||
class TestObjectUploadResponse:
|
||||
"""Tests for the ObjectUploadResponse model"""
|
||||
|
||||
def test_object_upload_response_creation(self):
|
||||
"""Test creating ObjectUploadResponse"""
|
||||
response = ObjectUploadResponse(url="https://example.com/file.txt", size=1024)
|
||||
|
||||
assert response.url == "https://example.com/file.txt"
|
||||
assert response.size == 1024
|
||||
|
||||
def test_object_upload_response_serialization(self):
|
||||
"""Test that ObjectUploadResponse can be serialized"""
|
||||
response = ObjectUploadResponse(url="https://example.com/file.txt", size=1024)
|
||||
|
||||
# Should be able to convert to dict (for JSON serialization)
|
||||
response_dict = response.model_dump()
|
||||
assert response_dict == {"url": "https://example.com/file.txt", "size": 1024}
|
||||
@@ -0,0 +1,566 @@
|
||||
"""
|
||||
Tests for Stripe webhook handlers.
|
||||
|
||||
This test suite validates the fix for the reference ID issue where legacy subscriptions
|
||||
sunset via scripts/sunset_legacy_subscriptions.py could create checkout sessions with
|
||||
missing client_reference_id, causing webhook processing failures.
|
||||
|
||||
The tests follow the same patterns as other billing tests and validate the fallback
|
||||
mechanism that uses org_id from metadata when client_reference_id is missing.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock
|
||||
from datetime import datetime, timedelta
|
||||
from fastapi import HTTPException
|
||||
import stripe
|
||||
|
||||
# Import shared billing fixtures
|
||||
pytest_plugins = ["tests._conftest.billing"]
|
||||
|
||||
from agentops.api.routes.v4.stripe_webhooks import (
|
||||
handle_checkout_completed,
|
||||
handle_subscription_updated,
|
||||
)
|
||||
from agentops.opsboard.models import (
|
||||
OrgModel,
|
||||
UserOrgModel,
|
||||
BillingAuditLog,
|
||||
PremStatus,
|
||||
OrgRoles,
|
||||
)
|
||||
|
||||
|
||||
# Mock stripe at module level to prevent API key errors
|
||||
stripe.api_key = 'sk_test_mock'
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_stripe_config():
|
||||
"""Mock Stripe configuration for all tests."""
|
||||
with (
|
||||
patch('agentops.api.environment.STRIPE_SECRET_KEY', 'sk_test_123'),
|
||||
patch('agentops.api.environment.STRIPE_SUBSCRIPTION_PRICE_ID', 'price_test123'),
|
||||
patch('agentops.api.routes.v4.stripe_webhooks.STRIPE_SUBSCRIPTION_PRICE_ID', 'price_test123'),
|
||||
patch.dict(
|
||||
'os.environ',
|
||||
{'STRIPE_SECRET_KEY': 'sk_test_123', 'STRIPE_SUBSCRIPTION_PRICE_ID': 'price_test123'},
|
||||
),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_org_with_subscription(orm_session, test_user):
|
||||
"""Create a test organization with an active subscription."""
|
||||
org = OrgModel(name="Test Org", prem_status=PremStatus.pro, subscription_id="sub_test_123")
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Add owner member
|
||||
owner_member = UserOrgModel(
|
||||
user_id=test_user.id, org_id=org.id, role=OrgRoles.owner, user_email=test_user.email, is_paid=True
|
||||
)
|
||||
orm_session.add(owner_member)
|
||||
orm_session.flush()
|
||||
|
||||
return org
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_free_org(orm_session, test_user):
|
||||
"""Create a test organization without a subscription."""
|
||||
org = OrgModel(name="Test Free Org", prem_status=PremStatus.free, subscription_id=None)
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Add owner member
|
||||
owner_member = UserOrgModel(
|
||||
user_id=test_user.id, org_id=org.id, role=OrgRoles.owner, user_email=test_user.email, is_paid=False
|
||||
)
|
||||
orm_session.add(owner_member)
|
||||
orm_session.flush()
|
||||
|
||||
return org
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_checkout_event():
|
||||
"""Create a mock Stripe checkout.session.completed event."""
|
||||
event = MagicMock()
|
||||
event.id = "evt_test_123"
|
||||
event.type = "checkout.session.completed"
|
||||
event.data = MagicMock()
|
||||
event.data.object = {
|
||||
"id": "cs_test_session_123",
|
||||
"subscription": "sub_new_123",
|
||||
"client_reference_id": None, # This will be set per test
|
||||
"metadata": {}, # This will be set per test
|
||||
}
|
||||
return event
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_subscription_event():
|
||||
"""Create a mock Stripe subscription.updated event."""
|
||||
event = MagicMock()
|
||||
event.id = "evt_test_subscription_123"
|
||||
event.type = "subscription.updated"
|
||||
event.data = MagicMock()
|
||||
event.data.object = {
|
||||
"id": "sub_test_123",
|
||||
"status": "active",
|
||||
"current_period_end": int((datetime.now() + timedelta(days=30)).timestamp()),
|
||||
"cancel_at_period_end": False,
|
||||
"items": {"data": [{"id": "si_test_123", "quantity": 1, "price": {"id": "price_test123"}}]},
|
||||
}
|
||||
return event
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_legacy_subscription_event():
|
||||
"""Create a mock Stripe subscription.updated event for legacy subscription."""
|
||||
event = MagicMock()
|
||||
event.id = "evt_test_legacy_123"
|
||||
event.type = "subscription.updated"
|
||||
event.data = MagicMock()
|
||||
event.data.object = {
|
||||
"id": "sub_legacy_123",
|
||||
"status": "active",
|
||||
"current_period_end": int((datetime.now() + timedelta(days=30)).timestamp()),
|
||||
"cancel_at_period_end": False,
|
||||
"items": {
|
||||
"data": [
|
||||
{
|
||||
"id": "si_legacy_123",
|
||||
"quantity": 1,
|
||||
"price": {
|
||||
"id": "price_legacy_old_123", # Different from current price ID
|
||||
"product": {"name": "Legacy Seat Plan"},
|
||||
},
|
||||
}
|
||||
]
|
||||
},
|
||||
}
|
||||
return event
|
||||
|
||||
|
||||
class TestStripeWebhooks:
|
||||
"""Test Stripe webhook handlers."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.is_event_processed')
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.mark_event_processed')
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.log_webhook_metric')
|
||||
@patch('stripe.Subscription.retrieve')
|
||||
async def test_checkout_completed_with_client_reference_id(
|
||||
self,
|
||||
mock_stripe_retrieve,
|
||||
mock_log_metric,
|
||||
mock_mark_processed,
|
||||
mock_is_processed,
|
||||
orm_session,
|
||||
test_free_org,
|
||||
mock_checkout_event,
|
||||
mock_stripe_subscription,
|
||||
):
|
||||
"""Test successful checkout completion with client_reference_id present."""
|
||||
mock_is_processed.return_value = False
|
||||
mock_mark_processed.return_value = None
|
||||
mock_stripe_retrieve.return_value = mock_stripe_subscription
|
||||
|
||||
# Set the client_reference_id to the org ID
|
||||
mock_checkout_event.data.object["client_reference_id"] = str(test_free_org.id)
|
||||
|
||||
result = await handle_checkout_completed(mock_checkout_event, orm_session)
|
||||
|
||||
# Verify the org was updated
|
||||
orm_session.refresh(test_free_org)
|
||||
assert test_free_org.subscription_id == "sub_new_123"
|
||||
assert test_free_org.prem_status == PremStatus.pro
|
||||
|
||||
# Verify owner was marked as paid
|
||||
owner = (
|
||||
orm_session.query(UserOrgModel)
|
||||
.filter(UserOrgModel.org_id == test_free_org.id, UserOrgModel.role == OrgRoles.owner)
|
||||
.first()
|
||||
)
|
||||
assert owner.is_paid is True
|
||||
|
||||
mock_mark_processed.assert_called_once_with(mock_checkout_event.id, orm_session)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.is_event_processed')
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.mark_event_processed')
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.log_webhook_metric')
|
||||
@patch('stripe.Subscription.retrieve')
|
||||
async def test_checkout_completed_missing_reference_id_with_metadata_fallback(
|
||||
self,
|
||||
mock_stripe_retrieve,
|
||||
mock_log_metric,
|
||||
mock_mark_processed,
|
||||
mock_is_processed,
|
||||
orm_session,
|
||||
test_free_org,
|
||||
mock_checkout_event,
|
||||
mock_stripe_subscription,
|
||||
):
|
||||
"""Test checkout completion when client_reference_id is missing but org_id is in metadata."""
|
||||
mock_is_processed.return_value = False
|
||||
mock_mark_processed.return_value = None
|
||||
mock_stripe_retrieve.return_value = mock_stripe_subscription
|
||||
|
||||
# Simulate the scenario where client_reference_id is missing but org_id is in metadata
|
||||
mock_checkout_event.data.object["client_reference_id"] = None
|
||||
mock_checkout_event.data.object["metadata"] = {"org_id": str(test_free_org.id)}
|
||||
|
||||
result = await handle_checkout_completed(mock_checkout_event, orm_session)
|
||||
|
||||
# Verify the org was updated despite missing client_reference_id
|
||||
orm_session.refresh(test_free_org)
|
||||
assert test_free_org.subscription_id == "sub_new_123"
|
||||
assert test_free_org.prem_status == PremStatus.pro
|
||||
|
||||
# Verify owner was marked as paid
|
||||
owner = (
|
||||
orm_session.query(UserOrgModel)
|
||||
.filter(UserOrgModel.org_id == test_free_org.id, UserOrgModel.role == OrgRoles.owner)
|
||||
.first()
|
||||
)
|
||||
assert owner.is_paid is True
|
||||
|
||||
mock_mark_processed.assert_called_once_with(mock_checkout_event.id, orm_session)
|
||||
|
||||
# Verify that the Stripe subscription was retrieved to validate the purchase
|
||||
mock_stripe_retrieve.assert_called_once_with("sub_new_123", expand=['items'])
|
||||
|
||||
# This test specifically validates the fix for the reference ID issue
|
||||
# The warning should be logged when using metadata fallback (captured in test output)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.is_event_processed')
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.log_webhook_metric')
|
||||
async def test_checkout_completed_missing_reference_id_and_metadata(
|
||||
self, mock_log_metric, mock_is_processed, orm_session, test_free_org, mock_checkout_event
|
||||
):
|
||||
"""Test checkout completion when both client_reference_id and org_id metadata are missing."""
|
||||
mock_is_processed.return_value = False
|
||||
|
||||
# Simulate the scenario where both client_reference_id and org_id metadata are missing
|
||||
mock_checkout_event.data.object["client_reference_id"] = None
|
||||
mock_checkout_event.data.object["metadata"] = {}
|
||||
|
||||
result = await handle_checkout_completed(mock_checkout_event, orm_session)
|
||||
|
||||
# Should return early without processing
|
||||
assert result is None
|
||||
|
||||
# Verify metric was logged for missing reference ID
|
||||
mock_log_metric.assert_called_once_with(
|
||||
"checkout.session.completed",
|
||||
"missing_reference_id",
|
||||
{"session_id": "cs_test_session_123", "subscription_id": "sub_new_123"},
|
||||
)
|
||||
|
||||
# Verify org was not updated
|
||||
orm_session.refresh(test_free_org)
|
||||
assert test_free_org.subscription_id is None
|
||||
assert test_free_org.prem_status == PremStatus.free
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.is_event_processed')
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.log_webhook_metric')
|
||||
@patch('stripe.Subscription.retrieve')
|
||||
async def test_checkout_completed_org_not_found(
|
||||
self,
|
||||
mock_stripe_retrieve,
|
||||
mock_log_metric,
|
||||
mock_is_processed,
|
||||
orm_session,
|
||||
mock_checkout_event,
|
||||
mock_stripe_subscription,
|
||||
):
|
||||
"""Test checkout completion when org is not found."""
|
||||
mock_is_processed.return_value = False
|
||||
mock_stripe_retrieve.return_value = mock_stripe_subscription
|
||||
|
||||
# Set client_reference_id to a non-existent org ID
|
||||
mock_checkout_event.data.object["client_reference_id"] = "00000000-0000-0000-0000-000000000000"
|
||||
|
||||
result = await handle_checkout_completed(mock_checkout_event, orm_session)
|
||||
|
||||
# Verify metric was logged for org not found
|
||||
mock_log_metric.assert_called_once_with(
|
||||
"checkout.session.completed",
|
||||
"org_not_found",
|
||||
{
|
||||
"client_reference_id": "00000000-0000-0000-0000-000000000000",
|
||||
"subscription_id": "sub_new_123",
|
||||
"session_id": "cs_test_session_123",
|
||||
},
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.is_event_processed')
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.mark_event_processed')
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.log_webhook_metric')
|
||||
@patch('stripe.Subscription.retrieve')
|
||||
async def test_checkout_completed_duplicate_processing(
|
||||
self,
|
||||
mock_stripe_retrieve,
|
||||
mock_log_metric,
|
||||
mock_mark_processed,
|
||||
mock_is_processed,
|
||||
orm_session,
|
||||
test_org_with_subscription,
|
||||
mock_checkout_event,
|
||||
mock_stripe_subscription,
|
||||
):
|
||||
"""Test checkout completion when org already has the same subscription."""
|
||||
mock_is_processed.return_value = False
|
||||
mock_stripe_retrieve.return_value = mock_stripe_subscription
|
||||
|
||||
# Set up scenario where org already has this subscription
|
||||
test_org_with_subscription.subscription_id = "sub_new_123"
|
||||
orm_session.commit()
|
||||
|
||||
mock_checkout_event.data.object["client_reference_id"] = str(test_org_with_subscription.id)
|
||||
mock_checkout_event.data.object["subscription"] = "sub_new_123"
|
||||
|
||||
result = await handle_checkout_completed(mock_checkout_event, orm_session)
|
||||
|
||||
# Should return early due to duplicate subscription
|
||||
assert result is None
|
||||
|
||||
# Should not call mark_event_processed since it's a duplicate
|
||||
mock_mark_processed.assert_not_called()
|
||||
|
||||
# Should log the duplicate processing
|
||||
mock_log_metric.assert_called_once_with(
|
||||
"checkout.session.completed",
|
||||
"duplicate_processing",
|
||||
{"org_id": str(test_org_with_subscription.id), "subscription_id": "sub_new_123"},
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.is_event_processed')
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.mark_event_processed')
|
||||
@patch('stripe.Subscription.modify')
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.send_legacy_billing_notification')
|
||||
async def test_subscription_updated_legacy_subscription_sunset(
|
||||
self,
|
||||
mock_send_notification,
|
||||
mock_stripe_modify,
|
||||
mock_mark_processed,
|
||||
mock_is_processed,
|
||||
orm_session,
|
||||
test_org_with_subscription,
|
||||
mock_legacy_subscription_event,
|
||||
):
|
||||
"""Test subscription updated webhook handling legacy subscription that should be sunset."""
|
||||
mock_is_processed.return_value = False
|
||||
# Mock single Stripe modify call to succeed
|
||||
mock_stripe_modify.return_value = MagicMock(id="sub_legacy_123")
|
||||
|
||||
# Make sure the notification mock doesn't raise any exceptions or interfere with session
|
||||
async def mock_notification(*args, **kwargs):
|
||||
# Do nothing, don't call orm.commit() or any other session operations
|
||||
pass
|
||||
|
||||
mock_send_notification.side_effect = mock_notification
|
||||
|
||||
# Set up org with legacy subscription
|
||||
test_org_with_subscription.subscription_id = "sub_legacy_123"
|
||||
orm_session.commit()
|
||||
|
||||
mock_legacy_subscription_event.data.object["id"] = "sub_legacy_123"
|
||||
|
||||
# Debug: print the subscription data that will be processed
|
||||
subscription_data = mock_legacy_subscription_event.data.object
|
||||
print(f"DEBUG: Subscription data - id: {subscription_data.get('id')}")
|
||||
print(f"DEBUG: Subscription data - status: {subscription_data.get('status')}")
|
||||
print(
|
||||
f"DEBUG: Subscription data - cancel_at_period_end: {subscription_data.get('cancel_at_period_end')}"
|
||||
)
|
||||
items = subscription_data.get('items', {}).get('data', [])
|
||||
for i, item in enumerate(items):
|
||||
price = item.get('price', {})
|
||||
print(
|
||||
f"DEBUG: Item {i} - price_id: {price.get('id')}, product_name: {price.get('product', {}).get('name')}"
|
||||
)
|
||||
|
||||
# Ensure the mock returns the expected subscription data
|
||||
# The function uses event.data.object directly, not a Stripe API call
|
||||
try:
|
||||
result = await handle_subscription_updated(mock_legacy_subscription_event, orm_session)
|
||||
print(f"DEBUG: handle_subscription_updated returned: {result}")
|
||||
except Exception as e:
|
||||
print(f"DEBUG: Exception in handle_subscription_updated: {e}")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc()
|
||||
raise
|
||||
|
||||
# Verify Stripe subscription was modified to cancel at period end
|
||||
mock_stripe_modify.assert_called()
|
||||
call_args = mock_stripe_modify.call_args_list[0]
|
||||
assert call_args[0][0] == "sub_legacy_123" # subscription_id
|
||||
assert call_args[1]["cancel_at_period_end"] is True
|
||||
assert "billing_model_change" in call_args[1]["metadata"]["cancellation_reason"]
|
||||
|
||||
# Explicitly flush and commit all pending changes
|
||||
orm_session.flush()
|
||||
orm_session.commit()
|
||||
|
||||
# Query audit logs with more debugging
|
||||
all_audit_logs = (
|
||||
orm_session.query(BillingAuditLog)
|
||||
.filter(BillingAuditLog.org_id == test_org_with_subscription.id)
|
||||
.all()
|
||||
)
|
||||
print(f"DEBUG: Found {len(all_audit_logs)} audit logs for org {test_org_with_subscription.id}")
|
||||
for log in all_audit_logs:
|
||||
print(f"DEBUG: Audit log - action: {log.action}, details: {log.details}")
|
||||
|
||||
# Verify audit log was created
|
||||
audit_log = (
|
||||
orm_session.query(BillingAuditLog)
|
||||
.filter(
|
||||
BillingAuditLog.org_id == test_org_with_subscription.id,
|
||||
BillingAuditLog.action == 'legacy_subscription_sunset',
|
||||
)
|
||||
.first()
|
||||
)
|
||||
assert audit_log is not None, f"No audit log found for org {test_org_with_subscription.id}"
|
||||
assert audit_log.details["subscription_id"] == "sub_legacy_123"
|
||||
|
||||
# Verify notification was sent
|
||||
mock_send_notification.assert_called_once()
|
||||
|
||||
mock_mark_processed.assert_called_once_with(mock_legacy_subscription_event.id, orm_session)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.is_event_processed')
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.mark_event_processed')
|
||||
async def test_subscription_updated_current_subscription(
|
||||
self,
|
||||
mock_mark_processed,
|
||||
mock_is_processed,
|
||||
orm_session,
|
||||
test_org_with_subscription,
|
||||
mock_subscription_event,
|
||||
):
|
||||
"""Test subscription updated webhook for current (non-legacy) subscription."""
|
||||
mock_is_processed.return_value = False
|
||||
|
||||
result = await handle_subscription_updated(mock_subscription_event, orm_session)
|
||||
|
||||
# Should process normally without legacy subscription handling
|
||||
mock_mark_processed.assert_called_once_with(mock_subscription_event.id, orm_session)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.is_event_processed')
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.log_webhook_metric')
|
||||
async def test_subscription_updated_org_not_found(
|
||||
self, mock_log_metric, mock_is_processed, orm_session, mock_subscription_event
|
||||
):
|
||||
"""Test subscription updated webhook when org is not found."""
|
||||
mock_is_processed.return_value = False
|
||||
|
||||
# Set subscription ID that doesn't match any org
|
||||
mock_subscription_event.data.object["id"] = "sub_nonexistent_123"
|
||||
|
||||
result = await handle_subscription_updated(mock_subscription_event, orm_session)
|
||||
|
||||
# Should return early
|
||||
assert result is None
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.is_event_processed')
|
||||
async def test_event_already_processed(self, mock_is_processed, orm_session, mock_checkout_event):
|
||||
"""Test that already processed events are skipped."""
|
||||
mock_is_processed.return_value = True
|
||||
|
||||
result = await handle_checkout_completed(mock_checkout_event, orm_session)
|
||||
|
||||
assert result == {"status": "already_processed"}
|
||||
|
||||
|
||||
class TestWebhookEdgeCases:
|
||||
"""Test edge cases and error scenarios for webhook handlers."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.is_event_processed')
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.mark_event_processed')
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.log_webhook_metric')
|
||||
async def test_checkout_completed_empty_metadata_org_id(
|
||||
self,
|
||||
mock_log_metric,
|
||||
mock_mark_processed,
|
||||
mock_is_processed,
|
||||
orm_session,
|
||||
test_free_org,
|
||||
mock_checkout_event,
|
||||
):
|
||||
"""Test checkout completion when org_id in metadata is empty string."""
|
||||
mock_is_processed.return_value = False
|
||||
|
||||
# Simulate the scenario where client_reference_id is missing and org_id is empty
|
||||
mock_checkout_event.data.object["client_reference_id"] = None
|
||||
mock_checkout_event.data.object["metadata"] = {"org_id": ""}
|
||||
|
||||
result = await handle_checkout_completed(mock_checkout_event, orm_session)
|
||||
|
||||
# Should return early without processing due to empty org_id
|
||||
assert result is None
|
||||
|
||||
# Verify metric was logged for missing reference ID
|
||||
mock_log_metric.assert_called_once_with(
|
||||
"checkout.session.completed",
|
||||
"missing_reference_id",
|
||||
{"session_id": "cs_test_session_123", "subscription_id": "sub_new_123"},
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.is_event_processed')
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.mark_event_processed')
|
||||
async def test_checkout_completed_missing_subscription_id(
|
||||
self, mock_mark_processed, mock_is_processed, orm_session, test_free_org, mock_checkout_event
|
||||
):
|
||||
"""Test checkout completion when subscription_id is missing."""
|
||||
mock_is_processed.return_value = False
|
||||
|
||||
# Set up valid client_reference_id but missing subscription
|
||||
mock_checkout_event.data.object["client_reference_id"] = str(test_free_org.id)
|
||||
mock_checkout_event.data.object["subscription"] = None
|
||||
|
||||
result = await handle_checkout_completed(mock_checkout_event, orm_session)
|
||||
|
||||
# Should return early without processing
|
||||
assert result is None
|
||||
|
||||
# Verify org was not updated
|
||||
orm_session.refresh(test_free_org)
|
||||
assert test_free_org.subscription_id is None
|
||||
assert test_free_org.prem_status == PremStatus.free
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@patch('agentops.api.routes.v4.stripe_webhooks.is_event_processed')
|
||||
async def test_checkout_completed_stripe_error_handling(
|
||||
self, mock_is_processed, orm_session, test_free_org, mock_checkout_event
|
||||
):
|
||||
"""Test that Stripe errors are properly logged and handled."""
|
||||
mock_is_processed.return_value = False
|
||||
|
||||
# Set up valid data
|
||||
mock_checkout_event.data.object["client_reference_id"] = str(test_free_org.id)
|
||||
|
||||
# Simulate a Stripe error during processing
|
||||
with patch('stripe.Subscription.retrieve') as mock_retrieve:
|
||||
mock_retrieve.side_effect = stripe.error.StripeError("Test Stripe error")
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await handle_checkout_completed(mock_checkout_event, orm_session)
|
||||
|
||||
assert exc_info.value.status_code == 500
|
||||
assert "Stripe API error" in exc_info.value.detail
|
||||
@@ -0,0 +1,232 @@
|
||||
"""
|
||||
Tests for the security features of the auth module.
|
||||
This covers both the rate limiter and security header validations.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock
|
||||
from fastapi import Request, HTTPException
|
||||
|
||||
from agentops.auth.views import _validate_request, public_route
|
||||
from agentops.common import rate_limit
|
||||
from agentops.common.environment import APP_URL, API_DOMAIN, RATE_LIMIT_COUNT, REDIS_HOST, REDIS_PORT
|
||||
from agentops.common.route_config import BaseView
|
||||
|
||||
# Mark to skip rate limit tests when Redis is not available
|
||||
redis_required = pytest.mark.skipif(
|
||||
not (REDIS_HOST and REDIS_PORT),
|
||||
reason="Rate limit tests require Redis (REDIS_HOST and REDIS_PORT env vars)"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_request():
|
||||
"""Create a mock request with appropriate headers for testing."""
|
||||
mock = MagicMock(spec=Request)
|
||||
mock.headers = {
|
||||
"x-forwarded-for": "192.168.0.1",
|
||||
"x-forwarded-host": API_DOMAIN,
|
||||
"origin": APP_URL,
|
||||
"referer": f"{APP_URL}/signin",
|
||||
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/91.0.4472.124",
|
||||
}
|
||||
return mock
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clear_rate_limits():
|
||||
"""
|
||||
Clear rate limit data for test IPs before and after tests.
|
||||
Note: This fixture will run even if Redis is not available,
|
||||
but the rate_limit.clear() calls will be no-ops in that case.
|
||||
"""
|
||||
test_ips = [
|
||||
"192.168.0.1", # Main test IP
|
||||
"192.168.0.2", # Secondary test IP
|
||||
]
|
||||
for ip in test_ips:
|
||||
rate_limit.clear(ip)
|
||||
yield
|
||||
for ip in test_ips:
|
||||
rate_limit.clear(ip)
|
||||
|
||||
|
||||
@patch("agentops.auth.views.API_URL", "http://localhost:8000")
|
||||
def test_localhost_bypass(mock_request):
|
||||
"""Test that localhost requests bypass all security checks."""
|
||||
# Should not raise exceptions even with bad headers
|
||||
mock_request.headers = {
|
||||
"x-forwarded-for": "", # This would normally trigger an error
|
||||
}
|
||||
_validate_request(mock_request) # Should not raise exceptions
|
||||
|
||||
|
||||
@patch("agentops.auth.views.API_URL", "https://api.agentops.ai")
|
||||
def test_header_validations(mock_request):
|
||||
"""Test that requests with invalid headers are rejected."""
|
||||
ip = "192.168.0.1"
|
||||
mock_request.headers["x-forwarded-for"] = ip
|
||||
rate_limit.clear(ip) # Ensure no rate limiting interference
|
||||
|
||||
# Test 2.1: Missing IP
|
||||
mock_request.headers.pop("x-forwarded-for")
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
_validate_request(mock_request)
|
||||
assert exc_info.value.status_code == 500
|
||||
|
||||
# Test 2.2: Invalid host
|
||||
mock_request.headers["x-forwarded-for"] = ip
|
||||
mock_request.headers["x-forwarded-host"] = "evil-site.com"
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
_validate_request(mock_request)
|
||||
assert exc_info.value.status_code == 500
|
||||
|
||||
# Test 2.3: Invalid origin
|
||||
mock_request.headers["x-forwarded-host"] = API_DOMAIN
|
||||
mock_request.headers["origin"] = "https://evil-site.com"
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
_validate_request(mock_request)
|
||||
assert exc_info.value.status_code == 500
|
||||
|
||||
# Test 2.4: Invalid referrer
|
||||
mock_request.headers["origin"] = APP_URL
|
||||
mock_request.headers["referer"] = "https://evil-site.com/page"
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
_validate_request(mock_request)
|
||||
assert exc_info.value.status_code == 500
|
||||
|
||||
# Test 2.5: Missing user agent
|
||||
mock_request.headers["referer"] = f"{APP_URL}/signin"
|
||||
mock_request.headers.pop("user-agent")
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
_validate_request(mock_request)
|
||||
assert exc_info.value.status_code == 500
|
||||
|
||||
|
||||
@redis_required
|
||||
@patch("agentops.auth.views.API_URL", "https://api.agentops.ai")
|
||||
def test_rate_limiting_basic(mock_request):
|
||||
"""Test that the rate limiter blocks requests after the limit is exceeded."""
|
||||
ip = "192.168.0.1"
|
||||
mock_request.headers["x-forwarded-for"] = ip
|
||||
|
||||
# Clear any existing data
|
||||
rate_limit.clear(ip)
|
||||
|
||||
# Verify initial state
|
||||
assert rate_limit.get_count(ip) == 0
|
||||
assert not rate_limit.is_blocked(ip)
|
||||
|
||||
# Make requests up to the limit
|
||||
for i in range(RATE_LIMIT_COUNT):
|
||||
_validate_request(mock_request)
|
||||
assert rate_limit.get_count(ip) == i + 1
|
||||
assert not rate_limit.is_blocked(ip)
|
||||
|
||||
# The next request should exceed the limit
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
_validate_request(mock_request)
|
||||
assert exc_info.value.status_code == 429
|
||||
assert rate_limit.is_blocked(ip)
|
||||
|
||||
|
||||
@redis_required
|
||||
@patch("agentops.auth.views.API_URL", "https://api.agentops.ai")
|
||||
def test_rate_limit_ip_isolation():
|
||||
"""Test that different IPs have separate rate limits."""
|
||||
ip1 = "192.168.0.1"
|
||||
ip2 = "192.168.0.2"
|
||||
|
||||
# Create two requests with different IPs
|
||||
request1 = MagicMock(spec=Request)
|
||||
request1.headers = {
|
||||
"x-forwarded-for": ip1,
|
||||
"x-forwarded-host": API_DOMAIN,
|
||||
"origin": APP_URL,
|
||||
"referer": f"{APP_URL}/signin",
|
||||
"user-agent": "Mozilla/5.0 Chrome/91.0.4472.124",
|
||||
}
|
||||
|
||||
request2 = MagicMock(spec=Request)
|
||||
request2.headers = {
|
||||
"x-forwarded-for": ip2,
|
||||
"x-forwarded-host": API_DOMAIN,
|
||||
"origin": APP_URL,
|
||||
"referer": f"{APP_URL}/signin",
|
||||
"user-agent": "Mozilla/5.0 Chrome/91.0.4472.124",
|
||||
}
|
||||
|
||||
# Exceed the limit for the first IP
|
||||
for _ in range(RATE_LIMIT_COUNT + 1):
|
||||
rate_limit.record_interaction(ip1)
|
||||
|
||||
# Verify the first IP is blocked
|
||||
assert rate_limit.is_blocked(ip1)
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
_validate_request(request1)
|
||||
assert exc_info.value.status_code == 429
|
||||
|
||||
# But the second IP should not be blocked
|
||||
assert not rate_limit.is_blocked(ip2)
|
||||
_validate_request(request2) # Should not raise exceptions
|
||||
|
||||
|
||||
@patch("agentops.auth.views.API_URL", "https://api.agentops.ai")
|
||||
def test_public_route_decorator():
|
||||
"""Test that the public_route decorator properly marks functions and validates requests."""
|
||||
|
||||
# Check that the decorator properly marks functions
|
||||
@public_route
|
||||
async def test_view(request):
|
||||
return "test response"
|
||||
|
||||
# Verify the function is marked as public
|
||||
assert hasattr(test_view, "is_public")
|
||||
assert test_view.is_public is True
|
||||
|
||||
|
||||
@patch("agentops.auth.views.API_URL", "https://api.agentops.ai")
|
||||
def test_public_route_decorator_class_based_view():
|
||||
"""Test that the public_route decorator properly works with class-based views."""
|
||||
|
||||
# Test with a class-based view
|
||||
@public_route
|
||||
class TestView(BaseView):
|
||||
async def __call__(self):
|
||||
return "test class response"
|
||||
|
||||
# Verify the class __call__ method is marked as public
|
||||
assert hasattr(TestView.__call__, "is_public")
|
||||
assert TestView.__call__.is_public is True
|
||||
|
||||
# Test that the decorator validates requests properly for class-based views
|
||||
mock_request = MagicMock(spec=Request)
|
||||
mock_request.headers = {
|
||||
"x-forwarded-for": "192.168.0.1",
|
||||
"x-forwarded-host": API_DOMAIN,
|
||||
"origin": APP_URL,
|
||||
"referer": f"{APP_URL}/signin",
|
||||
"user-agent": "Mozilla/5.0 Chrome/91.0.4472.124",
|
||||
}
|
||||
|
||||
# Create an instance and test validation
|
||||
view_instance = TestView(mock_request)
|
||||
|
||||
# The wrapped __call__ method should validate the request
|
||||
with patch('agentops.auth.views._validate_request') as mock_validate:
|
||||
import asyncio
|
||||
asyncio.run(view_instance())
|
||||
# Verify that _validate_request was called with the instance's request
|
||||
mock_validate.assert_called_once_with(mock_request)
|
||||
|
||||
|
||||
@patch("agentops.auth.views.API_URL", "https://api.agentops.ai")
|
||||
def test_public_route_decorator_invalid_class():
|
||||
"""Test that the public_route decorator raises TypeError for non-BaseView classes."""
|
||||
|
||||
# Should raise TypeError when decorating a non-BaseView class
|
||||
with pytest.raises(TypeError, match="must inherit from BaseView"):
|
||||
@public_route
|
||||
class BadView:
|
||||
async def __call__(self):
|
||||
return "invalid"
|
||||
@@ -0,0 +1,419 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from unittest.mock import patch
|
||||
|
||||
from agentops.common.freeplan import FreePlanFilteredResponse, freeplan_clamp_datetime, freeplan_clamp_start_time, freeplan_clamp_end_time
|
||||
|
||||
|
||||
class SimpleResponse(FreePlanFilteredResponse):
|
||||
_freeplan_exclude = ('field1', 'field2')
|
||||
|
||||
field1: str
|
||||
field2: int
|
||||
field3: str
|
||||
|
||||
|
||||
class NestedResponse(FreePlanFilteredResponse):
|
||||
regular_field: str
|
||||
nested_field: SimpleResponse
|
||||
|
||||
|
||||
class MaxLinesResponse(FreePlanFilteredResponse):
|
||||
_freeplan_maxlines = {'multiline_field': 3}
|
||||
|
||||
multiline_field: str
|
||||
regular_field: str
|
||||
|
||||
|
||||
class MaxItemsResponse(FreePlanFilteredResponse):
|
||||
_freeplan_maxitems = {'list_field': 3}
|
||||
|
||||
list_field: list[str]
|
||||
regular_field: str
|
||||
|
||||
|
||||
class CombinedResponse(FreePlanFilteredResponse):
|
||||
_freeplan_exclude = ('excluded_field',)
|
||||
_freeplan_maxlines = {'multiline_field': 2}
|
||||
_freeplan_maxitems = {'list_field': 2}
|
||||
|
||||
excluded_field: str
|
||||
multiline_field: str
|
||||
list_field: list[str]
|
||||
regular_field: str
|
||||
|
||||
|
||||
def test_freeplan_exclude():
|
||||
"""Test that fields listed in _freeplan_exclude are excluded when freeplan_truncated is True."""
|
||||
response = SimpleResponse(field1="value1", field2=123, field3="value3")
|
||||
|
||||
# When freeplan_truncated is False, all fields should be included
|
||||
response.freeplan_truncated = False
|
||||
result = response.model_dump()
|
||||
assert result == {
|
||||
"field1": "value1",
|
||||
"field2": 123,
|
||||
"field3": "value3",
|
||||
"freeplan_truncated": False,
|
||||
}
|
||||
|
||||
# When freeplan_truncated is True, excluded fields should be empty
|
||||
response.freeplan_truncated = True
|
||||
result = response.model_dump()
|
||||
assert result == {
|
||||
"field1": "", # String fields become empty strings
|
||||
"field2": 0, # Int fields become 0
|
||||
"field3": "value3",
|
||||
"freeplan_truncated": True,
|
||||
}
|
||||
|
||||
|
||||
def test_nested_models():
|
||||
"""Test that nested models are handled correctly."""
|
||||
nested = SimpleResponse(field1="nested1", field2=456, field3="nested3")
|
||||
response = NestedResponse(regular_field="regular", nested_field=nested)
|
||||
|
||||
# When freeplan_truncated is False, all fields should be included
|
||||
response.freeplan_truncated = False
|
||||
result = response.model_dump()
|
||||
assert result == {
|
||||
"regular_field": "regular",
|
||||
"nested_field": {
|
||||
"field1": "nested1",
|
||||
"field2": 456,
|
||||
"field3": "nested3",
|
||||
"freeplan_truncated": False,
|
||||
},
|
||||
"freeplan_truncated": False,
|
||||
}
|
||||
|
||||
# When freeplan_truncated is True on both the parent and nested model,
|
||||
# the nested model should apply its own filtering rules
|
||||
response.freeplan_truncated = True
|
||||
response.nested_field.freeplan_truncated = True
|
||||
result = response.model_dump()
|
||||
|
||||
assert result["regular_field"] == "regular"
|
||||
assert result["freeplan_truncated"] == True
|
||||
assert "nested_field" in result
|
||||
|
||||
# The nested field should have its own fields filtered according to its rules
|
||||
assert result["nested_field"]["field1"] == ""
|
||||
assert result["nested_field"]["field2"] == 0
|
||||
assert result["nested_field"]["field3"] == "nested3"
|
||||
assert result["nested_field"]["freeplan_truncated"] == True
|
||||
|
||||
|
||||
def test_maxlines_truncation():
|
||||
"""Test that fields listed in _freeplan_maxlines are truncated when freeplan_truncated is True."""
|
||||
multiline_text = "line1\nline2\nline3\nline4\nline5"
|
||||
response = MaxLinesResponse(multiline_field=multiline_text, regular_field="regular")
|
||||
|
||||
# When freeplan_truncated is False, all lines should be included
|
||||
response.freeplan_truncated = False
|
||||
result = response.model_dump()
|
||||
assert result == {
|
||||
"multiline_field": multiline_text,
|
||||
"regular_field": "regular",
|
||||
"freeplan_truncated": False,
|
||||
}
|
||||
|
||||
# When freeplan_truncated is True, multiline field should be truncated to max_lines
|
||||
response.freeplan_truncated = True
|
||||
result = response.model_dump()
|
||||
assert result == {
|
||||
"multiline_field": "line1\nline2\nline3", # Only first 3 lines
|
||||
"regular_field": "regular",
|
||||
"freeplan_truncated": True,
|
||||
}
|
||||
|
||||
|
||||
def test_maxitems_truncation():
|
||||
"""Test that fields listed in _freeplan_maxitems are truncated when freeplan_truncated is True."""
|
||||
test_list = ["item1", "item2", "item3", "item4", "item5"]
|
||||
response = MaxItemsResponse(list_field=test_list, regular_field="regular")
|
||||
|
||||
# When freeplan_truncated is False, all items should be included
|
||||
response.freeplan_truncated = False
|
||||
result = response.model_dump()
|
||||
assert result == {
|
||||
"list_field": test_list,
|
||||
"regular_field": "regular",
|
||||
"freeplan_truncated": False,
|
||||
}
|
||||
|
||||
# When freeplan_truncated is True, list field should be truncated to max_items
|
||||
response.freeplan_truncated = True
|
||||
result = response.model_dump()
|
||||
assert result == {
|
||||
"list_field": ["item1", "item2", "item3"], # Only first 3 items
|
||||
"regular_field": "regular",
|
||||
"freeplan_truncated": True,
|
||||
}
|
||||
|
||||
|
||||
def test_combined_exclude_maxlines_and_maxitems():
|
||||
"""Test that exclude, maxlines, and maxitems features all work together."""
|
||||
multiline_text = "line1\nline2\nline3\nline4"
|
||||
test_list = ["item1", "item2", "item3", "item4"]
|
||||
response = CombinedResponse(
|
||||
excluded_field="excluded",
|
||||
multiline_field=multiline_text,
|
||||
list_field=test_list,
|
||||
regular_field="regular"
|
||||
)
|
||||
|
||||
# When freeplan_truncated is True, excluded fields should be empty,
|
||||
# multiline fields should be truncated, and list fields should be truncated
|
||||
response.freeplan_truncated = True
|
||||
result = response.model_dump()
|
||||
assert result == {
|
||||
"excluded_field": "", # Excluded field
|
||||
"multiline_field": "line1\nline2", # Truncated to 2 lines
|
||||
"list_field": ["item1", "item2"], # Truncated to 2 items
|
||||
"regular_field": "regular",
|
||||
"freeplan_truncated": True,
|
||||
}
|
||||
|
||||
|
||||
class TestFreePlanClampDatetime:
|
||||
"""Tests for the freeplan_clamp_datetime function."""
|
||||
|
||||
def test_date_before_cutoff(self):
|
||||
"""Test that dates before the cutoff are returned as is."""
|
||||
now = datetime.now(timezone.utc)
|
||||
days_cutoff = 30 # Stand-in value for tests
|
||||
# Test date older than cutoff (further in the past)
|
||||
old_date = now - timedelta(days=days_cutoff + 10)
|
||||
|
||||
# When date is before cutoff (older), it should return the cutoff date
|
||||
result = freeplan_clamp_datetime(old_date, days_cutoff)
|
||||
expected = now - timedelta(days=days_cutoff)
|
||||
|
||||
# Verify the result is within a small tolerance of the expected value
|
||||
# (to account for tiny time differences during test execution)
|
||||
assert abs((result - expected).total_seconds()) < 1
|
||||
|
||||
def test_date_after_cutoff(self):
|
||||
"""Test that dates after the cutoff are returned as is."""
|
||||
now = datetime.now(timezone.utc)
|
||||
days_cutoff = 30 # Stand-in value for tests
|
||||
# Test date newer than cutoff (more recent)
|
||||
recent_date = now - timedelta(days=days_cutoff - 5)
|
||||
|
||||
# When date is after cutoff (newer), it should return the original date
|
||||
result = freeplan_clamp_datetime(recent_date, days_cutoff)
|
||||
|
||||
# Should return the original date, not the cutoff
|
||||
assert result == recent_date
|
||||
|
||||
def test_date_at_cutoff(self):
|
||||
"""Test that dates exactly at the cutoff are returned as is."""
|
||||
now = datetime.now(timezone.utc)
|
||||
days_cutoff = 30 # Stand-in value for tests
|
||||
cutoff_date = now - timedelta(days=days_cutoff)
|
||||
|
||||
result = freeplan_clamp_datetime(cutoff_date, days_cutoff)
|
||||
|
||||
# Should return the exact cutoff date (allowing for microsecond differences)
|
||||
assert abs((result - cutoff_date).total_seconds()) < 0.001
|
||||
|
||||
@patch('agentops.common.freeplan.datetime')
|
||||
def test_with_mocked_time(self, mock_datetime):
|
||||
"""Test with a mocked current time to ensure reliable comparison."""
|
||||
# Fix the current time
|
||||
fixed_now = datetime(2023, 1, 15, tzinfo=timezone.utc)
|
||||
mock_datetime.now.return_value = fixed_now
|
||||
|
||||
# Set cutoff days to 30 for this test
|
||||
cutoff_days = 30
|
||||
# Expected cutoff date
|
||||
cutoff = fixed_now - timedelta(days=cutoff_days)
|
||||
|
||||
# Test with date before cutoff (older)
|
||||
old_date = fixed_now - timedelta(days=cutoff_days + 10)
|
||||
assert freeplan_clamp_datetime(old_date, cutoff_days) == cutoff
|
||||
|
||||
# Test with date after cutoff (newer)
|
||||
recent_date = fixed_now - timedelta(days=cutoff_days - 10)
|
||||
assert freeplan_clamp_datetime(recent_date, cutoff_days) == recent_date
|
||||
|
||||
|
||||
class TestFreePlanClampStartTime:
|
||||
"""Tests for the freeplan_clamp_start_time function."""
|
||||
|
||||
def test_start_time_is_none(self):
|
||||
"""Test that None start_time returns cutoff and modified=True."""
|
||||
days_cutoff = 30
|
||||
result, modified = freeplan_clamp_start_time(None, days_cutoff)
|
||||
|
||||
# Should return cutoff datetime
|
||||
expected_cutoff = datetime.now(timezone.utc) - timedelta(days=days_cutoff)
|
||||
assert abs((result - expected_cutoff).total_seconds()) < 1
|
||||
|
||||
# Should be marked as modified since None was converted to cutoff
|
||||
assert modified is True
|
||||
|
||||
def test_start_time_before_cutoff(self):
|
||||
"""Test that start_time before cutoff is clamped and modified=True."""
|
||||
now = datetime.now(timezone.utc)
|
||||
days_cutoff = 30
|
||||
# Date older than cutoff (further in the past)
|
||||
old_start_time = now - timedelta(days=days_cutoff + 10)
|
||||
|
||||
result, modified = freeplan_clamp_start_time(old_start_time, days_cutoff)
|
||||
|
||||
# Should return cutoff, not the original old date
|
||||
expected_cutoff = now - timedelta(days=days_cutoff)
|
||||
assert abs((result - expected_cutoff).total_seconds()) < 1
|
||||
|
||||
# Should be marked as modified since it was clamped
|
||||
assert modified is True
|
||||
|
||||
def test_start_time_after_cutoff(self):
|
||||
"""Test that start_time after cutoff is not clamped and modified=False."""
|
||||
now = datetime.now(timezone.utc)
|
||||
days_cutoff = 30
|
||||
# Date newer than cutoff (more recent)
|
||||
recent_start_time = now - timedelta(days=days_cutoff - 5)
|
||||
|
||||
result, modified = freeplan_clamp_start_time(recent_start_time, days_cutoff)
|
||||
|
||||
# Should return the original date unchanged
|
||||
assert result == recent_start_time
|
||||
|
||||
# Should not be marked as modified since no clamping occurred
|
||||
assert modified is False
|
||||
|
||||
def test_start_time_at_cutoff(self):
|
||||
"""Test that start_time exactly at cutoff is not modified."""
|
||||
now = datetime.now(timezone.utc)
|
||||
days_cutoff = 30
|
||||
cutoff_start_time = now - timedelta(days=days_cutoff)
|
||||
|
||||
result, modified = freeplan_clamp_start_time(cutoff_start_time, days_cutoff)
|
||||
|
||||
# Should return a date very close to the cutoff date (allowing for timing differences)
|
||||
assert abs((result - cutoff_start_time).total_seconds()) < 1
|
||||
|
||||
# The timing precision issue means this might be marked as modified due to microsecond differences
|
||||
# So we'll accept either outcome for this edge case
|
||||
assert modified in [True, False]
|
||||
|
||||
@patch('agentops.common.freeplan.datetime')
|
||||
def test_start_time_with_mocked_time(self, mock_datetime):
|
||||
"""Test start_time with mocked current time for reliable comparison."""
|
||||
# Fix the current time
|
||||
fixed_now = datetime(2023, 1, 15, tzinfo=timezone.utc)
|
||||
mock_datetime.now.return_value = fixed_now
|
||||
|
||||
cutoff_days = 30
|
||||
cutoff = fixed_now - timedelta(days=cutoff_days)
|
||||
|
||||
# Test None case
|
||||
result, modified = freeplan_clamp_start_time(None, cutoff_days)
|
||||
assert result == cutoff
|
||||
assert modified is True
|
||||
|
||||
# Test old date case
|
||||
old_date = fixed_now - timedelta(days=cutoff_days + 5)
|
||||
result, modified = freeplan_clamp_start_time(old_date, cutoff_days)
|
||||
assert result == cutoff
|
||||
assert modified is True
|
||||
|
||||
# Test recent date case
|
||||
recent_date = fixed_now - timedelta(days=cutoff_days - 5)
|
||||
result, modified = freeplan_clamp_start_time(recent_date, cutoff_days)
|
||||
assert result == recent_date
|
||||
assert modified is False
|
||||
|
||||
|
||||
class TestFreePlanClampEndTime:
|
||||
"""Tests for the freeplan_clamp_end_time function."""
|
||||
|
||||
def test_end_time_is_none(self):
|
||||
"""Test that None end_time returns current time and modified=True."""
|
||||
days_cutoff = 30
|
||||
|
||||
# Capture current time before the call
|
||||
before_call = datetime.now(timezone.utc)
|
||||
result, modified = freeplan_clamp_end_time(None, days_cutoff)
|
||||
after_call = datetime.now(timezone.utc)
|
||||
|
||||
# Should return current time (within reasonable bounds)
|
||||
assert before_call <= result <= after_call
|
||||
|
||||
# Should be marked as modified since None was converted to current time
|
||||
assert modified is True
|
||||
|
||||
def test_end_time_before_cutoff(self):
|
||||
"""Test that end_time before cutoff is clamped and modified=True."""
|
||||
now = datetime.now(timezone.utc)
|
||||
days_cutoff = 30
|
||||
# Date older than cutoff (further in the past)
|
||||
old_end_time = now - timedelta(days=days_cutoff + 10)
|
||||
|
||||
result, modified = freeplan_clamp_end_time(old_end_time, days_cutoff)
|
||||
|
||||
# Should return cutoff, not the original old date
|
||||
expected_cutoff = now - timedelta(days=days_cutoff)
|
||||
assert abs((result - expected_cutoff).total_seconds()) < 1
|
||||
|
||||
# Should be marked as modified since it was clamped
|
||||
assert modified is True
|
||||
|
||||
def test_end_time_after_cutoff(self):
|
||||
"""Test that end_time after cutoff is not clamped and modified=False."""
|
||||
now = datetime.now(timezone.utc)
|
||||
days_cutoff = 30
|
||||
# Date newer than cutoff (more recent)
|
||||
recent_end_time = now - timedelta(days=days_cutoff - 5)
|
||||
|
||||
result, modified = freeplan_clamp_end_time(recent_end_time, days_cutoff)
|
||||
|
||||
# Should return the original date unchanged
|
||||
assert result == recent_end_time
|
||||
|
||||
# Should not be marked as modified since no clamping occurred
|
||||
assert modified is False
|
||||
|
||||
def test_end_time_at_cutoff(self):
|
||||
"""Test that end_time exactly at cutoff is not modified."""
|
||||
now = datetime.now(timezone.utc)
|
||||
days_cutoff = 30
|
||||
cutoff_end_time = now - timedelta(days=days_cutoff)
|
||||
|
||||
result, modified = freeplan_clamp_end_time(cutoff_end_time, days_cutoff)
|
||||
|
||||
# Should return a date very close to the cutoff date (allowing for timing differences)
|
||||
assert abs((result - cutoff_end_time).total_seconds()) < 1
|
||||
|
||||
# The timing precision issue means this might be marked as modified due to microsecond differences
|
||||
# So we'll accept either outcome for this edge case
|
||||
assert modified in [True, False]
|
||||
|
||||
@patch('agentops.common.freeplan.datetime')
|
||||
def test_end_time_with_mocked_time(self, mock_datetime):
|
||||
"""Test end_time with mocked current time for reliable comparison."""
|
||||
# Fix the current time
|
||||
fixed_now = datetime(2023, 1, 15, tzinfo=timezone.utc)
|
||||
mock_datetime.now.return_value = fixed_now
|
||||
|
||||
cutoff_days = 30
|
||||
cutoff = fixed_now - timedelta(days=cutoff_days)
|
||||
|
||||
# Test None case - should return current time
|
||||
result, modified = freeplan_clamp_end_time(None, cutoff_days)
|
||||
assert result == fixed_now
|
||||
assert modified is True
|
||||
|
||||
# Test old date case - should be clamped to cutoff
|
||||
old_date = fixed_now - timedelta(days=cutoff_days + 5)
|
||||
result, modified = freeplan_clamp_end_time(old_date, cutoff_days)
|
||||
assert result == cutoff
|
||||
assert modified is True
|
||||
|
||||
# Test recent date case - should not be clamped
|
||||
recent_date = fixed_now - timedelta(days=cutoff_days - 5)
|
||||
result, modified = freeplan_clamp_end_time(recent_date, cutoff_days)
|
||||
assert result == recent_date
|
||||
assert modified is False
|
||||
@@ -0,0 +1,180 @@
|
||||
import pytest
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
from agentops.common.lifespan import lifespan
|
||||
|
||||
|
||||
class TestLifespan:
|
||||
"""Tests for the lifespan context manager."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lifespan_normal_flow(self):
|
||||
"""Test that lifespan yields control and closes all connections on exit."""
|
||||
# Create a mock FastAPI app
|
||||
mock_app = MagicMock()
|
||||
|
||||
# Mock all the close functions
|
||||
with (
|
||||
patch('agentops.common.lifespan.close_postgres') as mock_close_postgres,
|
||||
patch('agentops.common.lifespan.close_clickhouse_clients') as mock_close_clickhouse,
|
||||
patch('agentops.common.lifespan.close_supabase_clients') as mock_close_supabase,
|
||||
):
|
||||
# Make the async close functions return coroutines
|
||||
mock_close_clickhouse.return_value = AsyncMock()()
|
||||
mock_close_supabase.return_value = AsyncMock()()
|
||||
|
||||
# Use the lifespan context manager
|
||||
async with lifespan(mock_app) as _:
|
||||
# Verify we're in the startup phase
|
||||
# (The function should yield here)
|
||||
pass
|
||||
|
||||
# After exiting the context, all cleanup functions should be called
|
||||
mock_close_postgres.assert_called_once()
|
||||
mock_close_clickhouse.assert_called_once()
|
||||
mock_close_supabase.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lifespan_postgres_error_handling(self):
|
||||
"""Test that lifespan continues cleanup even if PostgreSQL close fails."""
|
||||
mock_app = MagicMock()
|
||||
|
||||
with (
|
||||
patch('agentops.common.lifespan.close_postgres') as mock_close_postgres,
|
||||
patch('agentops.common.lifespan.close_clickhouse_clients') as mock_close_clickhouse,
|
||||
patch('agentops.common.lifespan.close_supabase_clients') as mock_close_supabase,
|
||||
patch('agentops.common.lifespan.logger') as mock_logger,
|
||||
):
|
||||
# Make PostgreSQL close raise an exception
|
||||
mock_close_postgres.side_effect = Exception("PostgreSQL connection error")
|
||||
|
||||
# Make the async close functions return coroutines
|
||||
mock_close_clickhouse.return_value = AsyncMock()()
|
||||
mock_close_supabase.return_value = AsyncMock()()
|
||||
|
||||
async with lifespan(mock_app):
|
||||
pass
|
||||
|
||||
# Verify error was logged
|
||||
mock_logger.error.assert_any_call("Error closing PostgreSQL: PostgreSQL connection error")
|
||||
|
||||
# Verify other cleanup functions were still called
|
||||
mock_close_clickhouse.assert_called_once()
|
||||
mock_close_supabase.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lifespan_clickhouse_error_handling(self):
|
||||
"""Test that lifespan continues cleanup even if ClickHouse close fails."""
|
||||
mock_app = MagicMock()
|
||||
|
||||
with (
|
||||
patch('agentops.common.lifespan.close_postgres') as mock_close_postgres,
|
||||
patch('agentops.common.lifespan.close_clickhouse_clients') as mock_close_clickhouse,
|
||||
patch('agentops.common.lifespan.close_supabase_clients') as mock_close_supabase,
|
||||
patch('agentops.common.lifespan.logger') as mock_logger,
|
||||
):
|
||||
# Make ClickHouse close raise an exception
|
||||
async def raise_clickhouse_error():
|
||||
raise Exception("ClickHouse connection error")
|
||||
|
||||
mock_close_clickhouse.side_effect = raise_clickhouse_error
|
||||
mock_close_supabase.return_value = AsyncMock()()
|
||||
|
||||
async with lifespan(mock_app):
|
||||
pass
|
||||
|
||||
# Verify error was logged
|
||||
mock_logger.error.assert_any_call("Error closing ClickHouse: ClickHouse connection error")
|
||||
|
||||
# Verify other cleanup functions were still called
|
||||
mock_close_postgres.assert_called_once()
|
||||
mock_close_supabase.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lifespan_supabase_error_handling(self):
|
||||
"""Test that lifespan handles Supabase close errors gracefully."""
|
||||
mock_app = MagicMock()
|
||||
|
||||
with (
|
||||
patch('agentops.common.lifespan.close_postgres') as mock_close_postgres,
|
||||
patch('agentops.common.lifespan.close_clickhouse_clients') as mock_close_clickhouse,
|
||||
patch('agentops.common.lifespan.close_supabase_clients') as mock_close_supabase,
|
||||
patch('agentops.common.lifespan.logger') as mock_logger,
|
||||
):
|
||||
# Make Supabase close raise an exception
|
||||
async def raise_supabase_error():
|
||||
raise Exception("Supabase client error")
|
||||
|
||||
mock_close_clickhouse.return_value = AsyncMock()()
|
||||
mock_close_supabase.side_effect = raise_supabase_error
|
||||
|
||||
async with lifespan(mock_app):
|
||||
pass
|
||||
|
||||
# Verify error was logged
|
||||
mock_logger.error.assert_any_call("Error closing Supabase: Supabase client error")
|
||||
|
||||
# Verify other cleanup functions were still called
|
||||
mock_close_postgres.assert_called_once()
|
||||
mock_close_clickhouse.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lifespan_all_errors(self):
|
||||
"""Test that lifespan handles errors from all cleanup functions."""
|
||||
mock_app = MagicMock()
|
||||
|
||||
with (
|
||||
patch('agentops.common.lifespan.close_postgres') as mock_close_postgres,
|
||||
patch('agentops.common.lifespan.close_clickhouse_clients') as mock_close_clickhouse,
|
||||
patch('agentops.common.lifespan.close_supabase_clients') as mock_close_supabase,
|
||||
patch('agentops.common.lifespan.logger') as mock_logger,
|
||||
):
|
||||
# Make all close functions raise exceptions
|
||||
mock_close_postgres.side_effect = Exception("PostgreSQL error")
|
||||
|
||||
async def raise_clickhouse_error():
|
||||
raise Exception("ClickHouse error")
|
||||
|
||||
async def raise_supabase_error():
|
||||
raise Exception("Supabase error")
|
||||
|
||||
mock_close_clickhouse.side_effect = raise_clickhouse_error
|
||||
mock_close_supabase.side_effect = raise_supabase_error
|
||||
|
||||
async with lifespan(mock_app):
|
||||
pass
|
||||
|
||||
# Verify all errors were logged
|
||||
mock_logger.error.assert_any_call("Error closing PostgreSQL: PostgreSQL error")
|
||||
mock_logger.error.assert_any_call("Error closing ClickHouse: ClickHouse error")
|
||||
mock_logger.error.assert_any_call("Error closing Supabase: Supabase error")
|
||||
|
||||
# Verify all cleanup functions were attempted
|
||||
mock_close_postgres.assert_called_once()
|
||||
mock_close_clickhouse.assert_called_once()
|
||||
mock_close_supabase.assert_called_once()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_lifespan_logging(self):
|
||||
"""Test that lifespan logs startup and shutdown messages."""
|
||||
mock_app = MagicMock()
|
||||
|
||||
with (
|
||||
patch('agentops.common.lifespan.close_postgres'),
|
||||
patch('agentops.common.lifespan.close_clickhouse_clients') as mock_close_clickhouse,
|
||||
patch('agentops.common.lifespan.close_supabase_clients') as mock_close_supabase,
|
||||
patch('agentops.common.lifespan.logger') as mock_logger,
|
||||
):
|
||||
# Make the async close functions return coroutines
|
||||
mock_close_clickhouse.return_value = AsyncMock()()
|
||||
mock_close_supabase.return_value = AsyncMock()()
|
||||
|
||||
async with lifespan(mock_app):
|
||||
# Verify startup message was logged
|
||||
mock_logger.info.assert_called_with("Starting up AgentOps API...")
|
||||
|
||||
# Verify shutdown messages were logged
|
||||
mock_logger.info.assert_any_call("Shutting down AgentOps API...")
|
||||
mock_logger.info.assert_any_call("PostgreSQL connections closed")
|
||||
mock_logger.info.assert_any_call("ClickHouse connections closed")
|
||||
mock_logger.info.assert_any_call("Supabase clients closed")
|
||||
@@ -0,0 +1,235 @@
|
||||
import pytest
|
||||
import uuid
|
||||
from sqlalchemy import Column, String, ForeignKey, Integer, create_engine
|
||||
from sqlalchemy.orm import relationship, selectinload, joinedload, sessionmaker, DeclarativeBase
|
||||
|
||||
from agentops.common.orm import require_loaded
|
||||
|
||||
|
||||
class ModelBase(DeclarativeBase):
|
||||
"""Separate base for testing to avoid conflicts with main BaseModel."""
|
||||
pass
|
||||
|
||||
|
||||
class AuthorModel(ModelBase):
|
||||
"""Test model representing an author for integration testing."""
|
||||
__tablename__ = "test_authors"
|
||||
|
||||
id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||
name = Column(String, nullable=False)
|
||||
|
||||
# Relationship to books
|
||||
books = relationship("BookModel", back_populates="author", lazy="raise")
|
||||
|
||||
@require_loaded("books")
|
||||
def get_book_count(self):
|
||||
"""Method that requires books to be loaded."""
|
||||
return len(self.books)
|
||||
|
||||
@require_loaded("books")
|
||||
def get_book_titles(self):
|
||||
"""Method that requires books to be loaded to access titles."""
|
||||
return [book.title for book in self.books]
|
||||
|
||||
|
||||
class BookModel(ModelBase):
|
||||
"""Test model representing a book for integration testing."""
|
||||
__tablename__ = "test_books"
|
||||
|
||||
id = Column(String, primary_key=True, default=lambda: str(uuid.uuid4()))
|
||||
title = Column(String, nullable=False)
|
||||
page_count = Column(Integer, default=100)
|
||||
author_id = Column(String, ForeignKey("test_authors.id"))
|
||||
|
||||
# Relationship to author
|
||||
author = relationship("AuthorModel", back_populates="books", lazy="raise")
|
||||
|
||||
@require_loaded("author")
|
||||
def get_author_name(self):
|
||||
"""Method that requires author to be loaded."""
|
||||
return self.author.name
|
||||
|
||||
|
||||
class TestRequireLoadedIntegration:
|
||||
"""Integration tests for the require_loaded decorator using real database operations."""
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
def session(self):
|
||||
"""Create an in-memory SQLite session for testing."""
|
||||
engine = create_engine("sqlite:///:memory:", echo=False)
|
||||
Session = sessionmaker(bind=engine)
|
||||
session = Session()
|
||||
|
||||
# Create tables
|
||||
ModelBase.metadata.create_all(bind=engine)
|
||||
|
||||
yield session
|
||||
|
||||
session.close()
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def setup_test_data(self, session):
|
||||
"""Set up test data for each test."""
|
||||
# Create test author
|
||||
self.author = AuthorModel(id=str(uuid.uuid4()), name="Test Author")
|
||||
session.add(self.author)
|
||||
|
||||
# Create test books
|
||||
self.book1 = BookModel(
|
||||
id=str(uuid.uuid4()),
|
||||
title="Book One",
|
||||
page_count=200,
|
||||
author_id=self.author.id
|
||||
)
|
||||
self.book2 = BookModel(
|
||||
id=str(uuid.uuid4()),
|
||||
title="Book Two",
|
||||
page_count=150,
|
||||
author_id=self.author.id
|
||||
)
|
||||
session.add(self.book1)
|
||||
session.add(self.book2)
|
||||
session.commit()
|
||||
|
||||
# Store IDs before expunging
|
||||
self.author_id = self.author.id
|
||||
self.book1_id = self.book1.id
|
||||
self.book2_id = self.book2.id
|
||||
|
||||
# Clear session to ensure fresh loads
|
||||
session.expunge_all()
|
||||
|
||||
def test_require_loaded_succeeds_with_preloaded_relationship(self, session):
|
||||
"""Test that decorator succeeds when relationship is preloaded."""
|
||||
# Load author with books preloaded
|
||||
author = (
|
||||
session.query(AuthorModel)
|
||||
.options(selectinload(AuthorModel.books))
|
||||
.filter_by(id=self.author_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
# Should work because books are preloaded
|
||||
book_count = author.get_book_count()
|
||||
assert book_count == 2
|
||||
|
||||
book_titles = author.get_book_titles()
|
||||
assert "Book One" in book_titles
|
||||
assert "Book Two" in book_titles
|
||||
|
||||
def test_require_loaded_fails_without_preloaded_relationship(self, session):
|
||||
"""Test that decorator fails when relationship is not preloaded."""
|
||||
# Load author WITHOUT preloading books
|
||||
author = session.query(AuthorModel).filter_by(id=self.author_id).first()
|
||||
|
||||
# Should fail because books are not preloaded (lazy="raise" by default)
|
||||
with pytest.raises(RuntimeError, match="relationship 'books' not loaded for AuthorModel"):
|
||||
author.get_book_count()
|
||||
|
||||
def test_require_loaded_with_joinedload_succeeds(self, session):
|
||||
"""Test that decorator succeeds with joinedload."""
|
||||
# Load author with books using joinedload
|
||||
author = (
|
||||
session.query(AuthorModel)
|
||||
.options(joinedload(AuthorModel.books))
|
||||
.filter_by(id=self.author_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
# Should work because books are loaded
|
||||
book_count = author.get_book_count()
|
||||
assert book_count == 2
|
||||
|
||||
def test_require_loaded_reverse_relationship(self, session):
|
||||
"""Test decorator on reverse relationship (book -> author)."""
|
||||
# Load book with author preloaded
|
||||
book = (
|
||||
session.query(BookModel)
|
||||
.options(selectinload(BookModel.author))
|
||||
.filter_by(id=self.book1_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
# Should work because author is preloaded
|
||||
author_name = book.get_author_name()
|
||||
assert author_name == "Test Author"
|
||||
|
||||
def test_require_loaded_reverse_relationship_fails_without_preload(self, session):
|
||||
"""Test decorator fails on reverse relationship without preload."""
|
||||
# Load book WITHOUT preloading author
|
||||
book = session.query(BookModel).filter_by(id=self.book1_id).first()
|
||||
|
||||
# Should fail because author is not preloaded
|
||||
with pytest.raises(RuntimeError, match="relationship 'author' not loaded for BookModel"):
|
||||
book.get_author_name()
|
||||
|
||||
def test_require_loaded_with_multiple_fields(self, session):
|
||||
"""Test decorator with multiple required fields."""
|
||||
# Test the decorator with multiple fields on existing model
|
||||
@require_loaded("books")
|
||||
def get_detailed_info(self):
|
||||
# This method requires books to be loaded
|
||||
return f"Author {self.name} has {len(self.books)} books"
|
||||
|
||||
# Monkey patch the method onto AuthorModel for this test
|
||||
AuthorModel.get_detailed_info = get_detailed_info
|
||||
|
||||
# Load author with books preloaded
|
||||
author = (
|
||||
session.query(AuthorModel)
|
||||
.options(selectinload(AuthorModel.books))
|
||||
.filter_by(id=self.author_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
# Should work because books relationship is loaded
|
||||
info = author.get_detailed_info()
|
||||
assert "Author Test Author has 2 books" == info
|
||||
|
||||
# Clean up the monkey patch
|
||||
delattr(AuthorModel, 'get_detailed_info')
|
||||
|
||||
def test_require_loaded_handles_empty_relationships(self, session):
|
||||
"""Test decorator handles empty but loaded relationships correctly."""
|
||||
# Create author with no books
|
||||
author_no_books = AuthorModel(id=str(uuid.uuid4()), name="Author No Books")
|
||||
session.add(author_no_books)
|
||||
session.commit()
|
||||
|
||||
# Store ID before expunging
|
||||
author_no_books_id = author_no_books.id
|
||||
session.expunge_all()
|
||||
|
||||
# Load with books preloaded (but empty)
|
||||
author = (
|
||||
session.query(AuthorModel)
|
||||
.options(selectinload(AuthorModel.books))
|
||||
.filter_by(id=author_no_books_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
# Should work even with empty relationship
|
||||
book_count = author.get_book_count()
|
||||
assert book_count == 0
|
||||
|
||||
book_titles = author.get_book_titles()
|
||||
assert book_titles == []
|
||||
|
||||
def test_require_loaded_preserves_method_signature(self, session):
|
||||
"""Test that decorator preserves original method signature and behavior."""
|
||||
# Load author with books preloaded
|
||||
author = (
|
||||
session.query(AuthorModel)
|
||||
.options(selectinload(AuthorModel.books))
|
||||
.filter_by(id=self.author_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
# Verify the decorated method works correctly
|
||||
assert callable(author.get_book_count)
|
||||
assert author.get_book_count.__name__ == "get_book_count"
|
||||
|
||||
# Verify it returns the expected type and value
|
||||
count = author.get_book_count()
|
||||
assert isinstance(count, int)
|
||||
assert count == 2
|
||||
@@ -0,0 +1,236 @@
|
||||
from agentops.common.otel import otel_attributes_to_nested
|
||||
|
||||
|
||||
class TestOtelAttributesToNested:
|
||||
"""Tests for the otel_attributes_to_nested function."""
|
||||
|
||||
def test_simple_nested_attributes(self):
|
||||
"""Test basic nested attribute conversion."""
|
||||
attributes = {"foo.bar": "value1", "foo.baz": "value2", "top": "level"}
|
||||
|
||||
result = otel_attributes_to_nested(attributes)
|
||||
|
||||
assert result == {"foo": {"bar": "value1", "baz": "value2"}, "top": "level"}
|
||||
|
||||
def test_array_attributes(self):
|
||||
"""Test conversion of attributes with numeric indices to arrays."""
|
||||
attributes = {
|
||||
"items.0.name": "first",
|
||||
"items.0.value": "100",
|
||||
"items.1.name": "second",
|
||||
"items.1.value": "200",
|
||||
}
|
||||
|
||||
result = otel_attributes_to_nested(attributes)
|
||||
|
||||
assert result == {"items": [{"name": "first", "value": "100"}, {"name": "second", "value": "200"}]}
|
||||
|
||||
def test_mixed_nested_and_arrays(self):
|
||||
"""Test complex structure with both nested objects and arrays."""
|
||||
attributes = {
|
||||
"user.name": "John",
|
||||
"user.tags.0": "admin",
|
||||
"user.tags.1": "developer",
|
||||
"user.metadata.age": "30",
|
||||
"user.metadata.city": "NYC",
|
||||
}
|
||||
|
||||
result = otel_attributes_to_nested(attributes)
|
||||
|
||||
assert result == {
|
||||
"user": {"name": "John", "tags": ["admin", "developer"], "metadata": {"age": "30", "city": "NYC"}}
|
||||
}
|
||||
|
||||
def test_sparse_array(self):
|
||||
"""Test that sparse arrays are filled with None values."""
|
||||
attributes = {"array.0": "first", "array.5": "sixth"}
|
||||
|
||||
result = otel_attributes_to_nested(attributes)
|
||||
|
||||
assert result == {"array": ["first", None, None, None, None, "sixth"]}
|
||||
|
||||
def test_string_terminal_value_skip(self):
|
||||
"""Test that we skip attributes when trying to set a key on a string value."""
|
||||
attributes = {
|
||||
"field": "string_value",
|
||||
"field.subfield": "should_be_skipped", # Can't add subfield to a string
|
||||
"field.another.deep": "also_skipped",
|
||||
}
|
||||
|
||||
result = otel_attributes_to_nested(attributes)
|
||||
|
||||
# Only the first string value should be set
|
||||
assert result == {"field": "string_value"}
|
||||
|
||||
def test_type_mismatch_string_key_on_list(self):
|
||||
"""Test that string keys on lists are skipped."""
|
||||
attributes = {
|
||||
"field.0": "array_item",
|
||||
"field.invalid": "should_be_skipped", # String key on what should be a list
|
||||
}
|
||||
|
||||
result = otel_attributes_to_nested(attributes)
|
||||
|
||||
# Only the valid array item should be set
|
||||
assert result == {"field": ["array_item"]}
|
||||
|
||||
def test_type_mismatch_int_key_on_dict(self):
|
||||
"""Test that integer keys on dicts are skipped."""
|
||||
attributes = {
|
||||
"field.name": "dict_value",
|
||||
"field.0": "should_be_skipped", # Integer key on what should be a dict
|
||||
}
|
||||
|
||||
result = otel_attributes_to_nested(attributes)
|
||||
|
||||
# Only the valid dict entry should be set
|
||||
assert result == {"field": {"name": "dict_value"}}
|
||||
|
||||
def test_deep_nesting(self):
|
||||
"""Test deeply nested structures."""
|
||||
attributes = {"a.b.c.d.e.f": "deep_value", "a.b.c.d.e.g": "another_deep", "a.b.x": "sibling"}
|
||||
|
||||
result = otel_attributes_to_nested(attributes)
|
||||
|
||||
assert result == {
|
||||
"a": {"b": {"c": {"d": {"e": {"f": "deep_value", "g": "another_deep"}}}, "x": "sibling"}}
|
||||
}
|
||||
|
||||
def test_legacy_gen_ai_prompt_conversion(self):
|
||||
"""Test that legacy gen_ai.prompt string format is converted to indexed format."""
|
||||
attributes = {"gen_ai.prompt": "What is the weather today?", "gen_ai.model": "gpt-4"}
|
||||
|
||||
result = otel_attributes_to_nested(attributes)
|
||||
|
||||
assert result == {
|
||||
"gen_ai": {
|
||||
"prompt": [{"content": "What is the weather today?", "role": "user"}],
|
||||
"model": "gpt-4",
|
||||
}
|
||||
}
|
||||
|
||||
def test_indexed_gen_ai_prompt_not_converted(self):
|
||||
"""Test that properly indexed gen_ai.prompt is not modified."""
|
||||
attributes = {
|
||||
"gen_ai.prompt.0.content": "Hello",
|
||||
"gen_ai.prompt.0.role": "user",
|
||||
"gen_ai.prompt.1.content": "Hi there!",
|
||||
"gen_ai.prompt.1.role": "assistant",
|
||||
}
|
||||
|
||||
result = otel_attributes_to_nested(attributes)
|
||||
|
||||
assert result == {
|
||||
"gen_ai": {
|
||||
"prompt": [
|
||||
{"content": "Hello", "role": "user"},
|
||||
{"content": "Hi there!", "role": "assistant"},
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
def test_gen_ai_non_string_prompt_not_converted(self):
|
||||
"""Test that gen_ai.prompt that's already an object/array is not converted."""
|
||||
# First, let's build a structure where gen_ai.prompt is already an array
|
||||
attributes = {"gen_ai.prompt.0": "already_indexed"}
|
||||
|
||||
result = otel_attributes_to_nested(attributes)
|
||||
|
||||
# Should not apply legacy conversion since it's already indexed
|
||||
assert result == {"gen_ai": {"prompt": ["already_indexed"]}}
|
||||
|
||||
def test_empty_attributes(self):
|
||||
"""Test that empty attributes dict returns empty result."""
|
||||
result = otel_attributes_to_nested({})
|
||||
assert result == {}
|
||||
|
||||
def test_single_level_attributes(self):
|
||||
"""Test attributes with no nesting."""
|
||||
attributes = {"field1": "value1", "field2": "value2", "field3": "value3"}
|
||||
|
||||
result = otel_attributes_to_nested(attributes)
|
||||
|
||||
assert result == attributes
|
||||
|
||||
def test_numeric_string_keys_not_converted(self):
|
||||
"""Test that numeric strings that aren't at array positions stay as strings."""
|
||||
attributes = {
|
||||
"map.123": "value", # This should create a dict with string key "123"
|
||||
"array.0": "item", # This should create an array
|
||||
}
|
||||
|
||||
result = otel_attributes_to_nested(attributes)
|
||||
|
||||
assert result == {"map": {"123": "value"}, "array": ["item"]}
|
||||
|
||||
def test_conflicting_paths_first_wins(self):
|
||||
"""Test that when paths conflict, the first one processed wins."""
|
||||
attributes = {
|
||||
"field.sub": "string_value",
|
||||
"field.sub.nested": "should_be_skipped", # Can't nest under string
|
||||
}
|
||||
|
||||
result = otel_attributes_to_nested(attributes)
|
||||
|
||||
assert result == {"field": {"sub": "string_value"}}
|
||||
|
||||
def test_complex_real_world_example(self):
|
||||
"""Test a complex real-world example with OpenTelemetry span attributes."""
|
||||
attributes = {
|
||||
"gen_ai.prompt.0.content": "Write a function",
|
||||
"gen_ai.prompt.0.role": "user",
|
||||
"gen_ai.completion.0.content": "def hello(): pass",
|
||||
"gen_ai.completion.0.role": "assistant",
|
||||
"gen_ai.model": "gpt-4",
|
||||
"gen_ai.usage.prompt_tokens": "10",
|
||||
"gen_ai.usage.completion_tokens": "5",
|
||||
"llm.is_streaming": "false",
|
||||
"span.kind": "CLIENT",
|
||||
"error.message": "none",
|
||||
"tags.0": "production",
|
||||
"tags.1": "v2",
|
||||
}
|
||||
|
||||
result = otel_attributes_to_nested(attributes)
|
||||
|
||||
assert result == {
|
||||
"gen_ai": {
|
||||
"prompt": [{"content": "Write a function", "role": "user"}],
|
||||
"completion": [{"content": "def hello(): pass", "role": "assistant"}],
|
||||
"model": "gpt-4",
|
||||
"usage": {"prompt_tokens": "10", "completion_tokens": "5"},
|
||||
},
|
||||
"llm": {"is_streaming": "false"},
|
||||
"span": {"kind": "CLIENT"},
|
||||
"error": {"message": "none"},
|
||||
"tags": ["production", "v2"],
|
||||
}
|
||||
|
||||
def test_edge_case_existing_string_in_path(self):
|
||||
"""Test handling when trying to traverse through an existing string value."""
|
||||
attributes = {
|
||||
"a.b": "string",
|
||||
"a.b.c.d": "should_skip", # Can't traverse through string at a.b
|
||||
}
|
||||
|
||||
result = otel_attributes_to_nested(attributes)
|
||||
|
||||
assert result == {"a": {"b": "string"}}
|
||||
|
||||
def test_multiple_legacy_prompts(self):
|
||||
"""Test multiple gen_ai attributes with legacy format."""
|
||||
attributes = {
|
||||
"gen_ai.prompt": "User question here",
|
||||
"gen_ai.completion": "AI response here", # This won't be converted, only prompt
|
||||
"other.field": "value",
|
||||
}
|
||||
|
||||
result = otel_attributes_to_nested(attributes)
|
||||
|
||||
assert result == {
|
||||
"gen_ai": {
|
||||
"prompt": [{"content": "User question here", "role": "user"}],
|
||||
"completion": "AI response here", # Not converted
|
||||
},
|
||||
"other": {"field": "value"},
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
from pathlib import Path
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load test environment before importing anything else
|
||||
load_dotenv(Path(__file__).parent.parent / "tests/.env", override=True)
|
||||
|
||||
from ._conftest.common import *
|
||||
from ._conftest.app import *
|
||||
from ._conftest.supabase import *
|
||||
from ._conftest.clickhouse import *
|
||||
from ._conftest.users import *
|
||||
from ._conftest.projects import *
|
||||
@@ -0,0 +1,252 @@
|
||||
import re
|
||||
from typing import ClassVar
|
||||
from agentops.api.db.clickhouse.models import ClickhouseModel, SelectFields, FilterDict, SearchFields
|
||||
|
||||
|
||||
def normalize_sql(sql: str) -> str:
|
||||
"""Normalize SQL string for exact comparison.
|
||||
|
||||
This preserves the actual SQL format while handling things like
|
||||
trailing semicolons and consistent spacing.
|
||||
"""
|
||||
# Remove extra spaces and newlines
|
||||
return re.sub(r'\s+', ' ', sql.strip())
|
||||
|
||||
|
||||
class TestModel(ClickhouseModel):
|
||||
"""Test model for query builder tests"""
|
||||
|
||||
table_name: ClassVar[str] = "test_table"
|
||||
selectable_fields: ClassVar[SelectFields] = {
|
||||
"Id": "id",
|
||||
"Name": "name",
|
||||
"Age": "age",
|
||||
"ProjectId": "project_id",
|
||||
"Timestamp": "timestamp",
|
||||
}
|
||||
filterable_fields: ClassVar[FilterDict] = {
|
||||
"id": ("=", "Id"),
|
||||
"min_age": (">=", "Age"),
|
||||
"max_age": ("<=", "Age"),
|
||||
"project_id": ("=", "ProjectId"),
|
||||
"start_time": (">=", "Timestamp"),
|
||||
"end_time": ("<=", "Timestamp"),
|
||||
}
|
||||
searchable_fields: ClassVar[SearchFields] = {
|
||||
"name": ("ILIKE", "Name"),
|
||||
"project_id": ("LIKE", "ProjectId"),
|
||||
}
|
||||
|
||||
|
||||
class TestModelWithStringFields(ClickhouseModel):
|
||||
"""Test model with string selectable fields"""
|
||||
|
||||
table_name: ClassVar[str] = "test_table_string"
|
||||
selectable_fields: ClassVar[SelectFields] = "*"
|
||||
|
||||
|
||||
class TestModelWithListFields(ClickhouseModel):
|
||||
"""Test model with list selectable fields"""
|
||||
|
||||
table_name: ClassVar[str] = "test_table_list"
|
||||
selectable_fields: ClassVar[SelectFields] = ["Id", "Name", "Age"]
|
||||
|
||||
|
||||
def test_get_select_clause_dict():
|
||||
"""Test _get_select_clause with dictionary fields"""
|
||||
select_clause = TestModel._get_select_clause()
|
||||
# The exact order must match the order in the class definition
|
||||
expected = "Id as id, Name as name, Age as age, ProjectId as project_id, Timestamp as timestamp"
|
||||
assert select_clause == expected
|
||||
|
||||
|
||||
def test_get_select_clause_string():
|
||||
"""Test _get_select_clause with string fields"""
|
||||
select_clause = TestModelWithStringFields._get_select_clause()
|
||||
assert select_clause == "*"
|
||||
|
||||
|
||||
def test_get_select_clause_list():
|
||||
"""Test _get_select_clause with list fields"""
|
||||
select_clause = TestModelWithListFields._get_select_clause()
|
||||
assert select_clause == "Id, Name, Age"
|
||||
|
||||
|
||||
def test_get_select_clause_override():
|
||||
"""Test _get_select_clause with overridden fields"""
|
||||
select_clause = TestModel._get_select_clause(fields=["Id", "Name"])
|
||||
assert select_clause == "Id, Name"
|
||||
|
||||
|
||||
def test_get_where_clause_empty():
|
||||
"""Test _get_where_clause with empty filters"""
|
||||
where_clause, params = TestModel._get_where_clause()
|
||||
assert where_clause == ""
|
||||
assert params == {}
|
||||
|
||||
|
||||
def test_get_where_clause_single_filter():
|
||||
"""Test _get_where_clause with a single filter"""
|
||||
where_clause, params = TestModel._get_where_clause(id="123")
|
||||
assert where_clause == "Id = %(id)s"
|
||||
assert params == {"id": "123"}
|
||||
|
||||
|
||||
def test_get_where_clause_multiple_filters():
|
||||
"""Test _get_where_clause with multiple filters"""
|
||||
where_clause, params = TestModel._get_where_clause(project_id="abc", min_age=18, max_age=65)
|
||||
|
||||
# Only the fields we provided should be in the result
|
||||
assert where_clause == "Age >= %(min_age)s AND Age <= %(max_age)s AND ProjectId = %(project_id)s"
|
||||
assert params == {"min_age": 18, "max_age": 65, "project_id": "abc"}
|
||||
|
||||
|
||||
def test_get_search_clause_empty():
|
||||
"""Test _get_search_clause with no search term"""
|
||||
search_clause, params = TestModel._get_search_clause()
|
||||
assert search_clause == ""
|
||||
assert params == {}
|
||||
|
||||
|
||||
def test_get_search_clause_with_term():
|
||||
"""Test _get_search_clause with a search term"""
|
||||
search_clause, params = TestModel._get_search_clause(search_term="test")
|
||||
|
||||
# Order based on TestModel.searchable_fields
|
||||
assert search_clause == "Name ILIKE %(search_name)s OR ProjectId LIKE %(search_project_id)s"
|
||||
assert params == {"search_name": "%test%", "search_project_id": "%test%"}
|
||||
|
||||
|
||||
def test_get_select_query_basic():
|
||||
"""Test _get_select_query with basic parameters"""
|
||||
query, params = TestModel._get_select_query()
|
||||
|
||||
normalized_query = normalize_sql(query)
|
||||
# Order matches the order in TestModel.selectable_fields
|
||||
expected_query = normalize_sql(
|
||||
"SELECT Id as id, Name as name, Age as age, ProjectId as project_id, Timestamp as timestamp FROM test_table"
|
||||
)
|
||||
assert normalized_query == expected_query
|
||||
assert params == {}
|
||||
|
||||
|
||||
def test_get_select_query_string_fields():
|
||||
"""Test _get_select_query with string selectable fields"""
|
||||
query, params = TestModelWithStringFields._get_select_query()
|
||||
|
||||
normalized_query = normalize_sql(query)
|
||||
assert normalized_query == "SELECT * FROM test_table_string"
|
||||
assert params == {}
|
||||
|
||||
|
||||
def test_get_select_query_list_fields():
|
||||
"""Test _get_select_query with list selectable fields"""
|
||||
query, params = TestModelWithListFields._get_select_query()
|
||||
|
||||
normalized_query = normalize_sql(query)
|
||||
assert normalized_query == "SELECT Id, Name, Age FROM test_table_list"
|
||||
assert params == {}
|
||||
|
||||
|
||||
def test_get_select_query_with_filters():
|
||||
"""Test _get_select_query with filters"""
|
||||
query, params = TestModel._get_select_query(filters={"id": "123"})
|
||||
|
||||
normalized_query = normalize_sql(query)
|
||||
expected_query = normalize_sql(
|
||||
"SELECT Id as id, Name as name, Age as age, ProjectId as project_id, Timestamp as timestamp FROM test_table WHERE Id = %(id)s"
|
||||
)
|
||||
assert normalized_query == expected_query
|
||||
assert params == {"id": "123"}
|
||||
|
||||
|
||||
def test_get_select_query_with_search():
|
||||
"""Test _get_select_query with search term"""
|
||||
query, params = TestModel._get_select_query(search="test")
|
||||
|
||||
normalized_query = normalize_sql(query)
|
||||
expected_query = normalize_sql(
|
||||
"SELECT Id as id, Name as name, Age as age, ProjectId as project_id, Timestamp as timestamp FROM test_table WHERE Name ILIKE %(search_name)s OR ProjectId LIKE %(search_project_id)s"
|
||||
)
|
||||
assert normalized_query == expected_query
|
||||
assert params == {"search_name": "%test%", "search_project_id": "%test%"}
|
||||
|
||||
|
||||
def test_get_select_query_with_filters_and_search():
|
||||
"""Test _get_select_query with both filters and search"""
|
||||
query, params = TestModel._get_select_query(filters={"id": "123"}, search="test")
|
||||
|
||||
normalized_query = normalize_sql(query)
|
||||
# Verify the order in both the select fields and the search fields
|
||||
expected_query = normalize_sql(
|
||||
"SELECT Id as id, Name as name, Age as age, ProjectId as project_id, Timestamp as timestamp FROM test_table WHERE (Id = %(id)s) AND (Name ILIKE %(search_name)s OR ProjectId LIKE %(search_project_id)s)"
|
||||
)
|
||||
assert normalized_query == expected_query
|
||||
assert params == {"id": "123", "search_name": "%test%", "search_project_id": "%test%"}
|
||||
|
||||
|
||||
def test_get_select_query_with_order_by():
|
||||
"""Test _get_select_query with order_by parameter"""
|
||||
query, params = TestModel._get_select_query(order_by="Timestamp DESC")
|
||||
|
||||
normalized_query = normalize_sql(query)
|
||||
expected_query = normalize_sql(
|
||||
"SELECT Id as id, Name as name, Age as age, ProjectId as project_id, Timestamp as timestamp FROM test_table ORDER BY Timestamp DESC"
|
||||
)
|
||||
assert normalized_query == expected_query
|
||||
assert params == {}
|
||||
|
||||
|
||||
def test_get_select_query_with_limit():
|
||||
"""Test _get_select_query with limit parameter"""
|
||||
query, params = TestModel._get_select_query(limit=10)
|
||||
|
||||
normalized_query = normalize_sql(query)
|
||||
expected_query = normalize_sql(
|
||||
"SELECT Id as id, Name as name, Age as age, ProjectId as project_id, Timestamp as timestamp FROM test_table LIMIT 10"
|
||||
)
|
||||
assert normalized_query == expected_query
|
||||
assert params == {}
|
||||
|
||||
|
||||
def test_get_select_query_with_offset():
|
||||
"""Test _get_select_query with offset parameter"""
|
||||
query, params = TestModel._get_select_query(offset=20)
|
||||
|
||||
normalized_query = normalize_sql(query)
|
||||
expected_query = normalize_sql(
|
||||
"SELECT Id as id, Name as name, Age as age, ProjectId as project_id, Timestamp as timestamp FROM test_table OFFSET 20"
|
||||
)
|
||||
assert normalized_query == expected_query
|
||||
assert params == {}
|
||||
|
||||
|
||||
def test_get_select_query_complete():
|
||||
"""Test _get_select_query with all parameters"""
|
||||
query, params = TestModel._get_select_query(
|
||||
fields=["Id", "Name", "Age"],
|
||||
filters={"project_id": "abc123", "min_age": 21},
|
||||
search="test",
|
||||
order_by="Age DESC",
|
||||
limit=10,
|
||||
offset=20,
|
||||
)
|
||||
|
||||
normalized_query = normalize_sql(query)
|
||||
# Match the exact ordering as defined in the model's class variables
|
||||
expected_query = normalize_sql("""
|
||||
SELECT Id, Name, Age
|
||||
FROM test_table
|
||||
WHERE (Age >= %(min_age)s AND ProjectId = %(project_id)s)
|
||||
AND (Name ILIKE %(search_name)s OR ProjectId LIKE %(search_project_id)s)
|
||||
ORDER BY Age DESC
|
||||
LIMIT 10
|
||||
OFFSET 20
|
||||
""")
|
||||
assert normalized_query == expected_query
|
||||
assert params == {
|
||||
"project_id": "abc123",
|
||||
"min_age": 21,
|
||||
"search_name": "%test%",
|
||||
"search_project_id": "%test%",
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
# Deploy tests package
|
||||
@@ -0,0 +1,690 @@
|
||||
"""Integration tests for deployment API endpoints using direct view calls."""
|
||||
|
||||
import pytest
|
||||
from unittest.mock import Mock, patch
|
||||
from fastapi import HTTPException
|
||||
|
||||
from agentops.deploy.models import HostingProjectModel
|
||||
from agentops.opsboard.models import ProjectModel
|
||||
from agentops.deploy.views.deploy import (
|
||||
CreateUpdateSecretView,
|
||||
ListSecretsView,
|
||||
InitiateDeploymentView,
|
||||
DeploymentStatusView,
|
||||
DeploymentHistoryView,
|
||||
)
|
||||
from agentops.deploy.schemas import CreateSecretRequest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_hosting_project():
|
||||
"""Mock hosting project model."""
|
||||
hosting_project = Mock(spec=HostingProjectModel)
|
||||
hosting_project.id = "project-123"
|
||||
hosting_project.namespace = "test-namespace"
|
||||
hosting_project.app_name = "test-app"
|
||||
hosting_project.git_url = "https://github.com/test/repo"
|
||||
hosting_project.git_branch = "main"
|
||||
hosting_project.entrypoint = "main.py"
|
||||
hosting_project.github_oath_access_token = "token123"
|
||||
hosting_project.pack_name = "FASTAPI" # Default pack for tests
|
||||
return hosting_project
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_project():
|
||||
"""Mock project model."""
|
||||
project = Mock(spec=ProjectModel)
|
||||
project.id = "project-123"
|
||||
project.name = "Test Project"
|
||||
project.org = Mock()
|
||||
project.org.is_user_member.return_value = True
|
||||
return project
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def mock_request():
|
||||
"""Create a mock request with a session user_id."""
|
||||
from unittest.mock import MagicMock
|
||||
from fastapi import Request
|
||||
|
||||
request = MagicMock(spec=Request)
|
||||
request.state.session.user_id = "00000000-0000-0000-0000-000000000001"
|
||||
return request
|
||||
|
||||
|
||||
class TestDeploymentSecretsAPI:
|
||||
"""Test the deployment secrets API endpoints."""
|
||||
|
||||
@patch('agentops.deploy.views.deploy.delete_secret')
|
||||
@patch('agentops.deploy.views.deploy.create_secret')
|
||||
async def test_create_secret_success(
|
||||
self,
|
||||
mock_create,
|
||||
mock_delete,
|
||||
mock_request,
|
||||
orm_session,
|
||||
mock_hosting_project,
|
||||
mock_project,
|
||||
):
|
||||
"""Test creating a secret via view function."""
|
||||
# Setup mocks
|
||||
mock_delete.return_value = True
|
||||
mock_create.return_value = Mock()
|
||||
|
||||
with (
|
||||
patch.object(HostingProjectModel, 'get_by_id', return_value=mock_hosting_project),
|
||||
patch.object(ProjectModel, 'get_by_id', return_value=mock_project),
|
||||
):
|
||||
# Create the view and call it directly
|
||||
view = CreateUpdateSecretView(mock_request)
|
||||
body = CreateSecretRequest(name="DATABASE_URL", value="postgresql://localhost:5432/test")
|
||||
|
||||
response = await view(
|
||||
project_id="project-123",
|
||||
body=body,
|
||||
orm=orm_session,
|
||||
)
|
||||
|
||||
assert response.success is True
|
||||
assert response.message == "Successfully created secret"
|
||||
|
||||
@patch('agentops.deploy.views.deploy.list_secrets')
|
||||
async def test_list_secrets_success(
|
||||
self, mock_list_secrets, mock_request, orm_session, mock_hosting_project, mock_project
|
||||
):
|
||||
"""Test listing secrets via view function."""
|
||||
# Setup mocks
|
||||
mock_list_secrets.return_value = ["DATABASE_URL", "API_KEY"]
|
||||
|
||||
with (
|
||||
patch.object(HostingProjectModel, 'get_by_id', return_value=mock_hosting_project),
|
||||
patch.object(ProjectModel, 'get_by_id', return_value=mock_project),
|
||||
):
|
||||
# Create the view and call it directly
|
||||
view = ListSecretsView(mock_request)
|
||||
|
||||
response = await view(
|
||||
project_id="project-123",
|
||||
orm=orm_session,
|
||||
)
|
||||
|
||||
assert len(response.secrets) == 2
|
||||
secret_names = [secret.name for secret in response.secrets]
|
||||
assert "DATABASE_URL" in secret_names
|
||||
assert "API_KEY" in secret_names
|
||||
|
||||
async def test_deployment_not_found(self, mock_request, orm_session):
|
||||
"""Test view response when deployment doesn't exist."""
|
||||
with patch.object(ProjectModel, 'get_by_id', return_value=None):
|
||||
# Create the view and call it directly
|
||||
view = ListSecretsView(mock_request)
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await view(
|
||||
project_id="00000000-0000-0000-0000-000000000000",
|
||||
orm=orm_session,
|
||||
)
|
||||
|
||||
assert exc_info.value.status_code == 404
|
||||
assert "Project not found" in str(exc_info.value.detail)
|
||||
|
||||
|
||||
class TestDeploymentManagementAPI:
|
||||
"""Test the deployment management API endpoints."""
|
||||
|
||||
@patch('agentops.deploy.views.deploy.queue_task')
|
||||
@patch('agentops.deploy.views.deploy.list_secrets')
|
||||
async def test_initiate_deployment_success(
|
||||
self,
|
||||
mock_list_secrets,
|
||||
mock_queue,
|
||||
mock_request,
|
||||
orm_session,
|
||||
mock_hosting_project,
|
||||
mock_project,
|
||||
):
|
||||
"""Test initiating a deployment via view function."""
|
||||
# Setup mocks
|
||||
mock_list_secrets.return_value = ["DATABASE_URL"]
|
||||
mock_queue.return_value = "job-456"
|
||||
|
||||
with (
|
||||
patch.object(HostingProjectModel, 'get_by_id', return_value=mock_hosting_project),
|
||||
patch.object(ProjectModel, 'get_by_id', return_value=mock_project),
|
||||
):
|
||||
# Create the view and call it directly
|
||||
view = InitiateDeploymentView(mock_request)
|
||||
|
||||
response = await view(
|
||||
project_id="project-123",
|
||||
orm=orm_session,
|
||||
)
|
||||
|
||||
assert response.success is True
|
||||
assert response.message == "Deployment initiated successfully"
|
||||
assert response.job_id == "job-456"
|
||||
|
||||
@patch('agentops.deploy.views.deploy.get_task_events')
|
||||
async def test_deployment_status_success(
|
||||
self, mock_get_events, mock_request, orm_session, mock_hosting_project, mock_project
|
||||
):
|
||||
"""Test getting deployment status via view function."""
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
|
||||
class MockStatus(Enum):
|
||||
SUCCESS = "success"
|
||||
|
||||
# Setup mocks
|
||||
mock_events = [
|
||||
Mock(
|
||||
event_type="build",
|
||||
status=MockStatus.SUCCESS,
|
||||
message="Build completed",
|
||||
timestamp=datetime.fromisoformat("2024-01-01T00:00:00"),
|
||||
),
|
||||
]
|
||||
mock_get_events.return_value = mock_events
|
||||
|
||||
with (
|
||||
patch.object(HostingProjectModel, 'get_by_id', return_value=mock_hosting_project),
|
||||
patch.object(ProjectModel, 'get_by_id', return_value=mock_project),
|
||||
):
|
||||
# Create the view and call it directly
|
||||
view = DeploymentStatusView(mock_request)
|
||||
|
||||
response = await view(
|
||||
project_id="project-123",
|
||||
job_id="test-job-123",
|
||||
orm=orm_session,
|
||||
)
|
||||
|
||||
assert len(response.events) == 1
|
||||
assert response.events[0].type == "build"
|
||||
assert response.events[0].status == "success"
|
||||
assert response.events[0].message == "Build completed"
|
||||
|
||||
@patch('agentops.deploy.views.deploy.get_task_events')
|
||||
async def test_deployment_status_with_start_date(
|
||||
self, mock_get_events, mock_request, orm_session, mock_hosting_project, mock_project
|
||||
):
|
||||
"""Test getting deployment status with start date filter via view function."""
|
||||
from datetime import datetime
|
||||
|
||||
# Setup mocks
|
||||
mock_get_events.return_value = []
|
||||
|
||||
with (
|
||||
patch.object(HostingProjectModel, 'get_by_id', return_value=mock_hosting_project),
|
||||
patch.object(ProjectModel, 'get_by_id', return_value=mock_project),
|
||||
):
|
||||
# Create the view and call it directly
|
||||
view = DeploymentStatusView(mock_request)
|
||||
start_date = datetime.fromisoformat("2024-01-01T12:00:00")
|
||||
|
||||
response = await view(
|
||||
project_id="project-123",
|
||||
job_id="test-job-456",
|
||||
start_date=start_date,
|
||||
orm=orm_session,
|
||||
)
|
||||
|
||||
assert len(response.events) == 0
|
||||
|
||||
|
||||
class TestViewValidation:
|
||||
"""Test view validation and error handling."""
|
||||
|
||||
@patch('agentops.deploy.views.deploy.create_secret')
|
||||
@patch('agentops.deploy.views.deploy.delete_secret')
|
||||
async def test_create_secret_kubernetes_error(
|
||||
self,
|
||||
mock_delete,
|
||||
mock_create,
|
||||
mock_request,
|
||||
orm_session,
|
||||
mock_hosting_project,
|
||||
mock_project,
|
||||
):
|
||||
"""Test creating a secret when Kubernetes operations fail."""
|
||||
# Setup mocks
|
||||
mock_delete.return_value = True
|
||||
mock_create.side_effect = Exception("Kubernetes API error")
|
||||
|
||||
with (
|
||||
patch.object(HostingProjectModel, 'get_by_id', return_value=mock_hosting_project),
|
||||
patch.object(ProjectModel, 'get_by_id', return_value=mock_project),
|
||||
):
|
||||
# Create the view and call it directly
|
||||
view = CreateUpdateSecretView(mock_request)
|
||||
body = CreateSecretRequest(name="DATABASE_URL", value="postgresql://localhost:5432/test")
|
||||
|
||||
# The view should let the exception bubble up
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
await view(
|
||||
project_id="project-123",
|
||||
body=body,
|
||||
orm=orm_session,
|
||||
)
|
||||
|
||||
assert "Kubernetes API error" in str(exc_info.value)
|
||||
|
||||
|
||||
class TestDeploymentHistoryAPI:
|
||||
"""Test the deployment history API endpoint."""
|
||||
|
||||
@patch('agentops.deploy.views.deploy.get_task_status')
|
||||
@patch('agentops.deploy.views.deploy.get_tasks')
|
||||
async def test_deployment_history_success(
|
||||
self,
|
||||
mock_get_tasks,
|
||||
mock_get_status,
|
||||
mock_request,
|
||||
orm_session,
|
||||
mock_hosting_project,
|
||||
mock_project,
|
||||
):
|
||||
"""Test getting deployment history via view function."""
|
||||
from enum import Enum
|
||||
|
||||
class MockStatus(Enum):
|
||||
SUCCESS = "success"
|
||||
RUNNING = "running"
|
||||
|
||||
# Setup mock jobs
|
||||
mock_jobs = [
|
||||
{
|
||||
"job_id": "job-123",
|
||||
"project_id": "project-123",
|
||||
"namespace": "test-namespace",
|
||||
"queued_at": "2024-01-01T10:00:00",
|
||||
"config": {},
|
||||
},
|
||||
{
|
||||
"job_id": "job-456",
|
||||
"project_id": "project-123",
|
||||
"namespace": "test-namespace",
|
||||
"queued_at": "2024-01-01T11:00:00",
|
||||
"config": {},
|
||||
},
|
||||
]
|
||||
mock_get_tasks.return_value = mock_jobs
|
||||
|
||||
# Setup mock status for each job (get_task_status returns BaseEvent)
|
||||
def mock_status_side_effect(job_id):
|
||||
if job_id == "job-123":
|
||||
return Mock(
|
||||
status=MockStatus.SUCCESS,
|
||||
message="Deployment completed successfully",
|
||||
)
|
||||
elif job_id == "job-456":
|
||||
return Mock(
|
||||
status=MockStatus.RUNNING,
|
||||
message="Deployment in progress",
|
||||
)
|
||||
return None
|
||||
|
||||
mock_get_status.side_effect = mock_status_side_effect
|
||||
|
||||
with (
|
||||
patch.object(HostingProjectModel, 'get_by_id', return_value=mock_hosting_project),
|
||||
patch.object(ProjectModel, 'get_by_id', return_value=mock_project),
|
||||
):
|
||||
# Create the view and call it directly
|
||||
view = DeploymentHistoryView(mock_request)
|
||||
|
||||
response = await view(
|
||||
project_id="project-123",
|
||||
orm=orm_session,
|
||||
)
|
||||
|
||||
# Verify response
|
||||
assert len(response.jobs) == 2
|
||||
|
||||
# Check first job
|
||||
job1 = response.jobs[0]
|
||||
assert job1.id == "job-123"
|
||||
assert job1.queued_at == "2024-01-01T10:00:00"
|
||||
assert job1.status == "success"
|
||||
assert job1.message == "Deployment completed successfully"
|
||||
|
||||
# Check second job
|
||||
job2 = response.jobs[1]
|
||||
assert job2.id == "job-456"
|
||||
assert job2.queued_at == "2024-01-01T11:00:00"
|
||||
assert job2.status == "running"
|
||||
assert job2.message == "Deployment in progress"
|
||||
|
||||
@patch('agentops.deploy.views.deploy.get_task_status')
|
||||
@patch('agentops.deploy.views.deploy.get_tasks')
|
||||
async def test_deployment_history_no_events(
|
||||
self,
|
||||
mock_get_tasks,
|
||||
mock_get_status,
|
||||
mock_request,
|
||||
orm_session,
|
||||
mock_hosting_project,
|
||||
mock_project,
|
||||
):
|
||||
"""Test deployment history when jobs have no events."""
|
||||
# Setup mock jobs
|
||||
mock_jobs = [
|
||||
{
|
||||
"job_id": "job-789",
|
||||
"project_id": "project-123",
|
||||
"namespace": "test-namespace",
|
||||
"queued_at": "2024-01-01T12:00:00",
|
||||
"config": {},
|
||||
},
|
||||
]
|
||||
mock_get_tasks.return_value = mock_jobs
|
||||
mock_get_status.return_value = None # No events
|
||||
|
||||
with (
|
||||
patch.object(HostingProjectModel, 'get_by_id', return_value=mock_hosting_project),
|
||||
patch.object(ProjectModel, 'get_by_id', return_value=mock_project),
|
||||
):
|
||||
# Create the view and call it directly
|
||||
view = DeploymentHistoryView(mock_request)
|
||||
|
||||
response = await view(
|
||||
project_id="project-123",
|
||||
orm=orm_session,
|
||||
)
|
||||
|
||||
# Verify response
|
||||
assert len(response.jobs) == 1
|
||||
job = response.jobs[0]
|
||||
assert job.id == "job-789"
|
||||
assert job.queued_at == "2024-01-01T12:00:00"
|
||||
assert job.status == "unknown"
|
||||
assert job.message == ""
|
||||
|
||||
@patch('agentops.deploy.views.deploy.get_tasks')
|
||||
async def test_deployment_history_empty_jobs(
|
||||
self,
|
||||
mock_get_tasks,
|
||||
mock_request,
|
||||
orm_session,
|
||||
mock_hosting_project,
|
||||
mock_project,
|
||||
):
|
||||
"""Test deployment history when no jobs exist."""
|
||||
mock_get_tasks.return_value = [] # No jobs
|
||||
|
||||
with (
|
||||
patch.object(HostingProjectModel, 'get_by_id', return_value=mock_hosting_project),
|
||||
patch.object(ProjectModel, 'get_by_id', return_value=mock_project),
|
||||
):
|
||||
# Create the view and call it directly
|
||||
view = DeploymentHistoryView(mock_request)
|
||||
|
||||
response = await view(
|
||||
project_id="project-123",
|
||||
orm=orm_session,
|
||||
)
|
||||
|
||||
# Verify response
|
||||
assert len(response.jobs) == 0
|
||||
|
||||
|
||||
class TestDeploymentPacksAPI:
|
||||
"""Test deployment pack functionality in API endpoints."""
|
||||
|
||||
@pytest.fixture
|
||||
def mock_project_with_api_key(self):
|
||||
"""Mock project model with API key."""
|
||||
project = Mock(spec=ProjectModel)
|
||||
project.id = "project-123"
|
||||
project.name = "Test Project"
|
||||
project.api_key = "test-api-key-123"
|
||||
project.org = Mock()
|
||||
project.org.is_user_member.return_value = True
|
||||
return project
|
||||
|
||||
def test_hosting_project_deployment_config_with_fastapi_pack(self, mock_project_with_api_key):
|
||||
"""Test that FASTAPI pack creates correct deployment config."""
|
||||
from jockey import DeploymentConfig
|
||||
from agentops.deploy.models import HostingProjectModel
|
||||
|
||||
# Create hosting project with FASTAPI pack
|
||||
hosting_project = HostingProjectModel()
|
||||
hosting_project.id = "project-123"
|
||||
hosting_project.pack_name = "FASTAPI"
|
||||
hosting_project.git_url = "https://github.com/test/repo"
|
||||
hosting_project.git_branch = "main"
|
||||
hosting_project.entrypoint = "main.py"
|
||||
hosting_project.github_oath_access_token = "token123"
|
||||
hosting_project.watch_path = None
|
||||
hosting_project.user_callback_url = None
|
||||
hosting_project.project = mock_project_with_api_key
|
||||
|
||||
# Mock list_secrets to return empty list
|
||||
with patch('jockey.list_secrets', return_value=[]):
|
||||
config = hosting_project.deployment_config
|
||||
|
||||
# Verify FASTAPI pack defaults are applied
|
||||
assert config.dockerfile_template == "fastapi-agent"
|
||||
assert config.ports == [8000]
|
||||
assert config.build_files == {}
|
||||
assert config.namespace == "project-123" # namespace property returns str(id)
|
||||
assert config.project_id == "project-123"
|
||||
|
||||
def test_hosting_project_deployment_config_with_crewai_pack(self, mock_project_with_api_key):
|
||||
"""Test that CREWAI pack creates correct deployment config."""
|
||||
from jockey import DeploymentConfig
|
||||
from agentops.deploy.models import HostingProjectModel
|
||||
|
||||
# Create hosting project with CREWAI pack
|
||||
hosting_project = HostingProjectModel()
|
||||
hosting_project.id = "project-123"
|
||||
hosting_project.pack_name = "CREWAI"
|
||||
hosting_project.git_url = "https://github.com/test/repo"
|
||||
hosting_project.git_branch = "main"
|
||||
hosting_project.entrypoint = "main.py"
|
||||
hosting_project.github_oath_access_token = "token123"
|
||||
hosting_project.watch_path = "src/"
|
||||
hosting_project.user_callback_url = None
|
||||
hosting_project.project = mock_project_with_api_key
|
||||
|
||||
# Mock list_secrets to return empty list
|
||||
with patch('jockey.list_secrets', return_value=[]):
|
||||
config = hosting_project.deployment_config
|
||||
|
||||
# Verify CREWAI pack defaults are applied
|
||||
assert config.dockerfile_template == "crewai-agent"
|
||||
assert config.ports == [8080]
|
||||
assert isinstance(config.build_files, dict) # Should have build files
|
||||
assert config.namespace == "project-123" # namespace property returns str(id)
|
||||
assert config.project_id == "project-123"
|
||||
assert config.watch_path == "src/"
|
||||
|
||||
def test_hosting_project_deployment_config_with_crewai_job_pack(self, mock_project_with_api_key):
|
||||
"""Test that CREWAI_JOB pack creates correct deployment config."""
|
||||
from jockey import DeploymentConfig
|
||||
from agentops.deploy.models import HostingProjectModel
|
||||
|
||||
# Create hosting project with CREWAI_JOB pack
|
||||
hosting_project = HostingProjectModel()
|
||||
hosting_project.id = "project-123"
|
||||
hosting_project.pack_name = "CREWAI_JOB"
|
||||
hosting_project.git_url = "https://github.com/test/repo"
|
||||
hosting_project.git_branch = "main"
|
||||
hosting_project.entrypoint = "main.py"
|
||||
hosting_project.github_oath_access_token = "token123"
|
||||
hosting_project.watch_path = "src/"
|
||||
hosting_project.user_callback_url = None
|
||||
hosting_project.project = mock_project_with_api_key
|
||||
|
||||
# Mock list_secrets to return empty list
|
||||
with patch('jockey.list_secrets', return_value=[]):
|
||||
config = hosting_project.deployment_config
|
||||
|
||||
# Verify CREWAI_JOB pack defaults are applied
|
||||
assert config.dockerfile_template == "crewai-job"
|
||||
assert config.ports == [] # No ports for job execution
|
||||
assert isinstance(config.build_files, dict) # Should have build files
|
||||
assert config.namespace == "project-123" # namespace property returns str(id)
|
||||
assert config.project_id == "project-123"
|
||||
|
||||
def test_hosting_project_deployment_config_with_none_pack_fallback(self, mock_project_with_api_key):
|
||||
"""Test that None pack_name falls back to FASTAPI."""
|
||||
from jockey import DeploymentConfig
|
||||
from agentops.deploy.models import HostingProjectModel
|
||||
|
||||
# Create hosting project with None pack_name
|
||||
hosting_project = HostingProjectModel()
|
||||
hosting_project.id = "project-123"
|
||||
hosting_project.pack_name = None
|
||||
hosting_project.git_url = "https://github.com/test/repo"
|
||||
hosting_project.git_branch = "main"
|
||||
hosting_project.entrypoint = "main.py"
|
||||
hosting_project.github_oath_access_token = "token123"
|
||||
hosting_project.watch_path = None
|
||||
hosting_project.user_callback_url = None
|
||||
hosting_project.project = mock_project_with_api_key
|
||||
|
||||
# Mock list_secrets to return empty list
|
||||
with patch('jockey.list_secrets', return_value=[]):
|
||||
config = hosting_project.deployment_config
|
||||
|
||||
# Should fall back to FASTAPI defaults
|
||||
assert config.dockerfile_template == "fastapi-agent"
|
||||
assert config.ports == [8000]
|
||||
assert config.build_files == {}
|
||||
|
||||
def test_hosting_project_deployment_config_with_invalid_pack_raises_error(self, mock_project_with_api_key):
|
||||
"""Test that invalid pack_name raises ValueError."""
|
||||
from jockey import DeploymentConfig
|
||||
from agentops.deploy.models import HostingProjectModel
|
||||
|
||||
# Create hosting project with invalid pack_name
|
||||
hosting_project = HostingProjectModel()
|
||||
hosting_project.id = "project-123"
|
||||
hosting_project.pack_name = "INVALID_PACK"
|
||||
hosting_project.git_url = "https://github.com/test/repo"
|
||||
hosting_project.git_branch = "main"
|
||||
hosting_project.entrypoint = "main.py"
|
||||
hosting_project.github_oath_access_token = "token123"
|
||||
hosting_project.watch_path = None
|
||||
hosting_project.user_callback_url = None
|
||||
hosting_project.project = mock_project_with_api_key
|
||||
|
||||
# Mock list_secrets to return empty list
|
||||
with patch('jockey.list_secrets', return_value=[]):
|
||||
with pytest.raises(ValueError, match="Invalid deployment pack name: INVALID_PACK"):
|
||||
config = hosting_project.deployment_config
|
||||
|
||||
@patch('agentops.deploy.views.deploy.queue_task')
|
||||
async def test_initiate_deployment_with_crewai_pack(
|
||||
self,
|
||||
mock_queue,
|
||||
mock_request,
|
||||
orm_session,
|
||||
mock_project_with_api_key,
|
||||
):
|
||||
"""Test that deployment uses correct pack configuration."""
|
||||
# Setup hosting project with CREWAI pack
|
||||
hosting_project = HostingProjectModel()
|
||||
hosting_project.id = "project-123"
|
||||
hosting_project.pack_name = "CREWAI"
|
||||
hosting_project.git_url = "https://github.com/test/repo"
|
||||
hosting_project.git_branch = "main"
|
||||
hosting_project.entrypoint = "main.py"
|
||||
hosting_project.github_oath_access_token = "token123"
|
||||
hosting_project.watch_path = "src/"
|
||||
hosting_project.user_callback_url = None
|
||||
hosting_project.project = mock_project_with_api_key
|
||||
|
||||
# Setup mocks
|
||||
mock_queue.return_value = "job-456"
|
||||
|
||||
with (
|
||||
patch.object(HostingProjectModel, 'get_by_id', return_value=hosting_project),
|
||||
patch.object(ProjectModel, 'get_by_id', return_value=mock_project_with_api_key),
|
||||
patch('jockey.list_secrets', return_value=["DATABASE_URL"]),
|
||||
):
|
||||
# Create the view and call it directly
|
||||
view = InitiateDeploymentView(mock_request)
|
||||
|
||||
response = await view(
|
||||
project_id="project-123",
|
||||
orm=orm_session,
|
||||
)
|
||||
|
||||
# Verify response
|
||||
assert response.success is True
|
||||
assert response.message == "Deployment initiated successfully"
|
||||
assert response.job_id == "job-456"
|
||||
|
||||
# Verify queue_task was called with correct config
|
||||
mock_queue.assert_called_once()
|
||||
call_args = mock_queue.call_args
|
||||
config = call_args[1]["config"] # Get config from kwargs
|
||||
|
||||
# Should have CREWAI pack defaults
|
||||
assert config.dockerfile_template == "crewai-agent"
|
||||
assert config.ports == [8080]
|
||||
assert isinstance(config.build_files, dict)
|
||||
assert len(config.build_files) > 0 # CREWAI should have build files
|
||||
|
||||
@patch('agentops.deploy.views.deploy.queue_task')
|
||||
async def test_initiate_deployment_preserves_user_overrides(
|
||||
self,
|
||||
mock_queue,
|
||||
mock_request,
|
||||
orm_session,
|
||||
mock_project_with_api_key,
|
||||
):
|
||||
"""Test that user-provided fields override pack defaults."""
|
||||
# Setup hosting project with custom settings
|
||||
hosting_project = HostingProjectModel()
|
||||
hosting_project.id = "project-123"
|
||||
hosting_project.pack_name = "FASTAPI"
|
||||
hosting_project.git_url = "https://github.com/test/custom-repo"
|
||||
hosting_project.git_branch = "feature-branch"
|
||||
hosting_project.entrypoint = "custom_main.py"
|
||||
hosting_project.github_oath_access_token = "custom-token"
|
||||
hosting_project.watch_path = "custom/path/"
|
||||
hosting_project.user_callback_url = "https://custom-callback.com"
|
||||
hosting_project.project = mock_project_with_api_key
|
||||
|
||||
# Setup mocks
|
||||
mock_queue.return_value = "job-789"
|
||||
|
||||
with (
|
||||
patch.object(HostingProjectModel, 'get_by_id', return_value=hosting_project),
|
||||
patch.object(ProjectModel, 'get_by_id', return_value=mock_project_with_api_key),
|
||||
patch('jockey.list_secrets', return_value=["API_KEY"]),
|
||||
):
|
||||
# Create the view and call it directly
|
||||
view = InitiateDeploymentView(mock_request)
|
||||
|
||||
response = await view(
|
||||
project_id="project-123",
|
||||
orm=orm_session,
|
||||
)
|
||||
|
||||
# Verify response
|
||||
assert response.success is True
|
||||
|
||||
# Verify config has pack defaults but user overrides
|
||||
mock_queue.assert_called_once()
|
||||
call_args = mock_queue.call_args
|
||||
config = call_args[1]["config"] # Get config from kwargs
|
||||
|
||||
# Pack defaults
|
||||
assert config.dockerfile_template == "fastapi-agent"
|
||||
assert config.ports == [8000]
|
||||
assert config.build_files == {}
|
||||
|
||||
# User overrides
|
||||
assert config.repository_url == "https://github.com/test/custom-repo"
|
||||
assert config.branch == "feature-branch"
|
||||
assert config.entrypoint == "custom_main.py"
|
||||
assert config.github_access_token == "custom-token"
|
||||
assert config.watch_path == "custom/path/"
|
||||
assert config.callback_url == "https://custom-callback.com"
|
||||
assert config.secret_names == ["API_KEY"]
|
||||
assert config.agentops_api_key == "test-api-key-123"
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
[
|
||||
{
|
||||
"body": "\u001b[31mThis is red text\u001b[0m\n",
|
||||
"severity_number": 9,
|
||||
"severity_text": "INFO",
|
||||
"attributes": {
|
||||
"raw": true,
|
||||
"preserve_color": true,
|
||||
"code.filepath": "/Users/beyond/agentops/agentops/log_capture.py",
|
||||
"code.function": "write",
|
||||
"code.lineno": 234
|
||||
},
|
||||
"dropped_attributes": 0,
|
||||
"timestamp": "2025-01-31T12:29:57.187259Z",
|
||||
"observed_timestamp": "2025-01-31T12:29:57.187309Z",
|
||||
"trace_id": "0x00000000000000000000000000000000",
|
||||
"span_id": "0x0000000000000000",
|
||||
"trace_flags": 0,
|
||||
"resource": {
|
||||
"attributes": {
|
||||
"telemetry.sdk.language": "python",
|
||||
"telemetry.sdk.name": "opentelemetry",
|
||||
"telemetry.sdk.version": "1.29.0",
|
||||
"service.name": "agentops",
|
||||
"session.id": "8685cc2c-0d9e-496c-96b3-d7b54c6894e5"
|
||||
},
|
||||
"schema_url": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"body": "\u001b[34mBlue\u001b[0m and \u001b[32mgreen\u001b[0m mixed\n",
|
||||
"severity_number": 9,
|
||||
"severity_text": "INFO",
|
||||
"attributes": {
|
||||
"raw": true,
|
||||
"preserve_color": true,
|
||||
"code.filepath": "/Users/beyond/agentops/agentops/log_capture.py",
|
||||
"code.function": "write",
|
||||
"code.lineno": 234
|
||||
},
|
||||
"dropped_attributes": 0,
|
||||
"timestamp": "2025-01-31T12:29:57.187540Z",
|
||||
"observed_timestamp": "2025-01-31T12:29:57.187555Z",
|
||||
"trace_id": "0x00000000000000000000000000000000",
|
||||
"span_id": "0x0000000000000000",
|
||||
"trace_flags": 0,
|
||||
"resource": {
|
||||
"attributes": {
|
||||
"telemetry.sdk.language": "python",
|
||||
"telemetry.sdk.name": "opentelemetry",
|
||||
"telemetry.sdk.version": "1.29.0",
|
||||
"service.name": "agentops",
|
||||
"session.id": "8685cc2c-0d9e-496c-96b3-d7b54c6894e5"
|
||||
},
|
||||
"schema_url": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"body": "\u001b[1;31mBold red\u001b[0m and \u001b[3;34mitalic blue\u001b[0m\n",
|
||||
"severity_number": 9,
|
||||
"severity_text": "INFO",
|
||||
"attributes": {
|
||||
"raw": true,
|
||||
"preserve_color": true,
|
||||
"code.filepath": "/Users/beyond/agentops/agentops/log_capture.py",
|
||||
"code.function": "write",
|
||||
"code.lineno": 234
|
||||
},
|
||||
"dropped_attributes": 0,
|
||||
"timestamp": "2025-01-31T12:29:57.187719Z",
|
||||
"observed_timestamp": "2025-01-31T12:29:57.187728Z",
|
||||
"trace_id": "0x00000000000000000000000000000000",
|
||||
"span_id": "0x0000000000000000",
|
||||
"trace_flags": 0,
|
||||
"resource": {
|
||||
"attributes": {
|
||||
"telemetry.sdk.language": "python",
|
||||
"telemetry.sdk.name": "opentelemetry",
|
||||
"telemetry.sdk.version": "1.29.0",
|
||||
"service.name": "agentops",
|
||||
"session.id": "8685cc2c-0d9e-496c-96b3-d7b54c6894e5"
|
||||
},
|
||||
"schema_url": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"body": "\u001b[31mDirect red ANSI\u001b[0m\n",
|
||||
"severity_number": 9,
|
||||
"severity_text": "INFO",
|
||||
"attributes": {
|
||||
"raw": true,
|
||||
"preserve_color": true,
|
||||
"code.filepath": "/Users/beyond/agentops/agentops/log_capture.py",
|
||||
"code.function": "write",
|
||||
"code.lineno": 234
|
||||
},
|
||||
"dropped_attributes": 0,
|
||||
"timestamp": "2025-01-31T12:29:57.187750Z",
|
||||
"observed_timestamp": "2025-01-31T12:29:57.187755Z",
|
||||
"trace_id": "0x00000000000000000000000000000000",
|
||||
"span_id": "0x0000000000000000",
|
||||
"trace_flags": 0,
|
||||
"resource": {
|
||||
"attributes": {
|
||||
"telemetry.sdk.language": "python",
|
||||
"telemetry.sdk.name": "opentelemetry",
|
||||
"telemetry.sdk.version": "1.29.0",
|
||||
"service.name": "agentops",
|
||||
"session.id": "8685cc2c-0d9e-496c-96b3-d7b54c6894e5"
|
||||
},
|
||||
"schema_url": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"body": "\u001b[34mBlue\u001b[0m and \u001b[32mgreen\u001b[0m mixed ANSI\n",
|
||||
"severity_number": 9,
|
||||
"severity_text": "INFO",
|
||||
"attributes": {
|
||||
"raw": true,
|
||||
"preserve_color": true,
|
||||
"code.filepath": "/Users/beyond/agentops/agentops/log_capture.py",
|
||||
"code.function": "write",
|
||||
"code.lineno": 234
|
||||
},
|
||||
"dropped_attributes": 0,
|
||||
"timestamp": "2025-01-31T12:29:57.187770Z",
|
||||
"observed_timestamp": "2025-01-31T12:29:57.187775Z",
|
||||
"trace_id": "0x00000000000000000000000000000000",
|
||||
"span_id": "0x0000000000000000",
|
||||
"trace_flags": 0,
|
||||
"resource": {
|
||||
"attributes": {
|
||||
"telemetry.sdk.language": "python",
|
||||
"telemetry.sdk.name": "opentelemetry",
|
||||
"telemetry.sdk.version": "1.29.0",
|
||||
"service.name": "agentops",
|
||||
"session.id": "8685cc2c-0d9e-496c-96b3-d7b54c6894e5"
|
||||
},
|
||||
"schema_url": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"body": "\u001b[1;31mBold red ANSI\u001b[0m\n",
|
||||
"severity_number": 9,
|
||||
"severity_text": "INFO",
|
||||
"attributes": {
|
||||
"raw": true,
|
||||
"preserve_color": true,
|
||||
"code.filepath": "/Users/beyond/agentops/agentops/log_capture.py",
|
||||
"code.function": "write",
|
||||
"code.lineno": 234
|
||||
},
|
||||
"dropped_attributes": 0,
|
||||
"timestamp": "2025-01-31T12:29:57.187789Z",
|
||||
"observed_timestamp": "2025-01-31T12:29:57.187793Z",
|
||||
"trace_id": "0x00000000000000000000000000000000",
|
||||
"span_id": "0x0000000000000000",
|
||||
"trace_flags": 0,
|
||||
"resource": {
|
||||
"attributes": {
|
||||
"telemetry.sdk.language": "python",
|
||||
"telemetry.sdk.name": "opentelemetry",
|
||||
"telemetry.sdk.version": "1.29.0",
|
||||
"service.name": "agentops",
|
||||
"session.id": "8685cc2c-0d9e-496c-96b3-d7b54c6894e5"
|
||||
},
|
||||
"schema_url": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"body": "\u001b[35mMagenta error\u001b[0m\n",
|
||||
"severity_number": 17,
|
||||
"severity_text": "ERROR",
|
||||
"attributes": {
|
||||
"raw": true,
|
||||
"preserve_color": true,
|
||||
"code.filepath": "/Users/beyond/agentops/agentops/log_capture.py",
|
||||
"code.function": "write",
|
||||
"code.lineno": 254
|
||||
},
|
||||
"dropped_attributes": 0,
|
||||
"timestamp": "2025-01-31T12:29:57.187814Z",
|
||||
"observed_timestamp": "2025-01-31T12:29:57.187822Z",
|
||||
"trace_id": "0x00000000000000000000000000000000",
|
||||
"span_id": "0x0000000000000000",
|
||||
"trace_flags": 0,
|
||||
"resource": {
|
||||
"attributes": {
|
||||
"telemetry.sdk.language": "python",
|
||||
"telemetry.sdk.name": "opentelemetry",
|
||||
"telemetry.sdk.version": "1.29.0",
|
||||
"service.name": "agentops",
|
||||
"session.id": "8685cc2c-0d9e-496c-96b3-d7b54c6894e5"
|
||||
},
|
||||
"schema_url": ""
|
||||
}
|
||||
},
|
||||
{
|
||||
"body": "\u001b[33mYellow warning\u001b[0m\n",
|
||||
"severity_number": 17,
|
||||
"severity_text": "ERROR",
|
||||
"attributes": {
|
||||
"raw": true,
|
||||
"preserve_color": true,
|
||||
"code.filepath": "/Users/beyond/agentops/agentops/log_capture.py",
|
||||
"code.function": "write",
|
||||
"code.lineno": 254
|
||||
},
|
||||
"dropped_attributes": 0,
|
||||
"timestamp": "2025-01-31T12:29:57.187833Z",
|
||||
"observed_timestamp": "2025-01-31T12:29:57.187836Z",
|
||||
"trace_id": "0x00000000000000000000000000000000",
|
||||
"span_id": "0x0000000000000000",
|
||||
"trace_flags": 0,
|
||||
"resource": {
|
||||
"attributes": {
|
||||
"telemetry.sdk.language": "python",
|
||||
"telemetry.sdk.name": "opentelemetry",
|
||||
"telemetry.sdk.version": "1.29.0",
|
||||
"service.name": "agentops",
|
||||
"session.id": "8685cc2c-0d9e-496c-96b3-d7b54c6894e5"
|
||||
},
|
||||
"schema_url": ""
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,146 @@
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from opentelemetry.semconv._incubating.attributes.gen_ai_attributes import (
|
||||
GEN_AI_OPERATION_NAME,
|
||||
GEN_AI_REQUEST_MODEL,
|
||||
GEN_AI_RESPONSE_MODEL,
|
||||
GEN_AI_SYSTEM,
|
||||
GenAiOperationNameValues,
|
||||
)
|
||||
|
||||
from agentops.api.encoders.spans import SpanAttributeEncoder
|
||||
from agentops.api.interactors.spans import (
|
||||
GEN_AI_TOOL_CALL_ID,
|
||||
GEN_AI_TOOL_NAME,
|
||||
LEGACY_EMBEDDING,
|
||||
LEGACY_LLM,
|
||||
LEGACY_SYSTEM,
|
||||
LOG_MESSAGE,
|
||||
LOG_SEVERITY,
|
||||
AgentopsGenAISpanSubtype,
|
||||
AgentopsSpanType,
|
||||
classify_gen_ai_span_subtype,
|
||||
classify_span,
|
||||
handle_gen_ai_span,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_classify_span_gen_ai():
|
||||
"""Test that Gen AI spans are correctly classified."""
|
||||
# Test with legacy ai.system attribute
|
||||
span = {"attributes": {LEGACY_SYSTEM: "openai"}}
|
||||
assert await classify_span(span) == AgentopsSpanType.GEN_AI
|
||||
|
||||
# Test with legacy ai.llm attribute
|
||||
span = {"attributes": {LEGACY_LLM: "gpt-4"}}
|
||||
assert await classify_span(span) == AgentopsSpanType.GEN_AI
|
||||
|
||||
# Test with legacy ai.embedding attribute
|
||||
span = {"attributes": {LEGACY_EMBEDDING: "text-embedding-ada-002"}}
|
||||
assert await classify_span(span) == AgentopsSpanType.GEN_AI
|
||||
|
||||
# Test with gen_ai.system attribute
|
||||
span = {"attributes": {GEN_AI_SYSTEM: "openai"}}
|
||||
assert await classify_span(span) == AgentopsSpanType.GEN_AI
|
||||
|
||||
# Test with gen_ai.operation.name attribute
|
||||
span = {"attributes": {GEN_AI_OPERATION_NAME: "chat"}}
|
||||
assert await classify_span(span) == AgentopsSpanType.GEN_AI
|
||||
|
||||
# Test with gen_ai.request.model attribute
|
||||
span = {"attributes": {GEN_AI_REQUEST_MODEL: "gpt-4"}}
|
||||
assert await classify_span(span) == AgentopsSpanType.GEN_AI
|
||||
|
||||
# Test with gen_ai.response.model attribute
|
||||
span = {"attributes": {GEN_AI_RESPONSE_MODEL: "gpt-4"}}
|
||||
assert await classify_span(span) == AgentopsSpanType.GEN_AI
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_classify_span_log():
|
||||
"""Test that log spans are correctly classified."""
|
||||
# Test with log.severity attribute
|
||||
span = {"attributes": {LOG_SEVERITY: "INFO"}}
|
||||
assert await classify_span(span) == AgentopsSpanType.LOG
|
||||
|
||||
# Test with log.message attribute
|
||||
span = {"attributes": {LOG_MESSAGE: "Test message"}}
|
||||
assert await classify_span(span) == AgentopsSpanType.LOG
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_classify_span_session_update():
|
||||
"""Test that session update spans are correctly classified."""
|
||||
# Test with no relevant attributes
|
||||
span = {"attributes": {"other": "value"}}
|
||||
assert await classify_span(span) == AgentopsSpanType.SESSION_UPDATE
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_classify_gen_ai_span_subtype():
|
||||
"""Test that Gen AI span subtypes are correctly classified."""
|
||||
# Test tool span
|
||||
span = {"attributes": {GEN_AI_TOOL_NAME: "calculator"}}
|
||||
assert await classify_gen_ai_span_subtype(span) == AgentopsGenAISpanSubtype.TOOL
|
||||
|
||||
span = {"attributes": {GEN_AI_TOOL_CALL_ID: "call_123"}}
|
||||
assert await classify_gen_ai_span_subtype(span) == AgentopsGenAISpanSubtype.TOOL
|
||||
|
||||
# Test chat span
|
||||
span = {"attributes": {GEN_AI_OPERATION_NAME: GenAiOperationNameValues.CHAT.value}}
|
||||
assert await classify_gen_ai_span_subtype(span) == AgentopsGenAISpanSubtype.CHAT
|
||||
|
||||
# Test completion span
|
||||
span = {"attributes": {GEN_AI_OPERATION_NAME: GenAiOperationNameValues.TEXT_COMPLETION.value}}
|
||||
assert await classify_gen_ai_span_subtype(span) == AgentopsGenAISpanSubtype.COMPLETION
|
||||
|
||||
# Test embedding span
|
||||
span = {"attributes": {GEN_AI_OPERATION_NAME: GenAiOperationNameValues.EMBEDDINGS.value}}
|
||||
assert await classify_gen_ai_span_subtype(span) == AgentopsGenAISpanSubtype.EMBEDDING
|
||||
|
||||
span = {"attributes": {LEGACY_EMBEDDING: "text-embedding-ada-002"}}
|
||||
assert await classify_gen_ai_span_subtype(span) == AgentopsGenAISpanSubtype.EMBEDDING
|
||||
|
||||
# Test default
|
||||
span = {"attributes": {GEN_AI_SYSTEM: "openai"}}
|
||||
assert await classify_gen_ai_span_subtype(span) == AgentopsGenAISpanSubtype.GENERIC
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_handle_gen_ai_span():
|
||||
"""Test that Gen AI spans are correctly handled."""
|
||||
session_id = "test-session"
|
||||
span = {
|
||||
"agent_id": "test-agent",
|
||||
"trace_id": "test-trace",
|
||||
"span_id": "test-span",
|
||||
"parent_span_id": "test-parent",
|
||||
"name": "test-span",
|
||||
"kind": "client",
|
||||
"start_time": "2023-01-01T00:00:00Z",
|
||||
"end_time": "2023-01-01T00:00:01Z",
|
||||
"attributes": {
|
||||
GEN_AI_SYSTEM: "openai",
|
||||
GEN_AI_OPERATION_NAME: GenAiOperationNameValues.CHAT.value,
|
||||
GEN_AI_REQUEST_MODEL: "gpt-4",
|
||||
},
|
||||
}
|
||||
|
||||
# Mock the SpanAttributeEncoder.encode method
|
||||
with patch.object(SpanAttributeEncoder, 'encode', return_value=b"encoded"):
|
||||
span_data = await handle_gen_ai_span(span, session_id)
|
||||
|
||||
assert span_data["session_id"] == session_id
|
||||
assert span_data["agent_id"] == span["agent_id"]
|
||||
assert span_data["trace_id"] == span["trace_id"]
|
||||
assert span_data["span_id"] == span["span_id"]
|
||||
assert span_data["parent_span_id"] == span["parent_span_id"]
|
||||
assert span_data["name"] == span["name"]
|
||||
assert span_data["kind"] == span["kind"]
|
||||
assert span_data["start_time"] == span["start_time"]
|
||||
assert span_data["end_time"] == span["end_time"]
|
||||
assert span_data["attributes"] == b"encoded"
|
||||
assert span_data["span_type"] == AgentopsSpanType.GEN_AI
|
||||
assert span_data["span_subtype"] == AgentopsGenAISpanSubtype.CHAT
|
||||
@@ -0,0 +1,13 @@
|
||||
import pytest
|
||||
import uuid
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def mock_request():
|
||||
"""Create a mock request with a session user_id."""
|
||||
from unittest.mock import MagicMock
|
||||
from fastapi import Request
|
||||
|
||||
request = MagicMock(spec=Request)
|
||||
request.state.session.user_id = uuid.UUID("00000000-0000-0000-0000-000000000000")
|
||||
return request
|
||||
@@ -0,0 +1 @@
|
||||
# Test directory for opsboard models
|
||||
@@ -0,0 +1,943 @@
|
||||
import pytest
|
||||
import uuid
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from agentops.opsboard.models import BillingAuditLog, BillingPeriod, OrgModel
|
||||
|
||||
# Import shared billing fixtures
|
||||
pytest_plugins = ["tests._conftest.billing"]
|
||||
from tests._conftest.billing_constants import (
|
||||
TOKEN_COST_SAMPLE,
|
||||
SPAN_COST_SAMPLE,
|
||||
TOKEN_QUANTITY_SAMPLE,
|
||||
SPAN_QUANTITY_SAMPLE,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_billing_period(orm_session, test_org, billing_period_factory):
|
||||
"""Create a test billing period for testing."""
|
||||
billing_period = billing_period_factory(
|
||||
test_org.id,
|
||||
seat_cost=8000, # $80 in cents
|
||||
seat_count=2,
|
||||
usage_costs={"tokens": TOKEN_COST_SAMPLE, "spans": SPAN_COST_SAMPLE},
|
||||
usage_quantities={"tokens": TOKEN_QUANTITY_SAMPLE, "spans": SPAN_QUANTITY_SAMPLE},
|
||||
total_cost=8200,
|
||||
status='pending',
|
||||
)
|
||||
orm_session.add(billing_period)
|
||||
orm_session.flush()
|
||||
return billing_period
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_billing_audit_log(orm_session, test_org, test_user):
|
||||
"""Create a test billing audit log for testing."""
|
||||
try:
|
||||
audit_log = BillingAuditLog(
|
||||
org_id=test_org.id,
|
||||
user_id=test_user.id,
|
||||
action='member_licensed',
|
||||
details={
|
||||
'member_id': str(test_user.id),
|
||||
'member_email': 'test@example.com',
|
||||
'before_seat_count': 1,
|
||||
'after_seat_count': 2,
|
||||
},
|
||||
)
|
||||
orm_session.add(audit_log)
|
||||
orm_session.flush()
|
||||
return audit_log
|
||||
except Exception:
|
||||
orm_session.rollback()
|
||||
raise
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def ensure_clean_session(orm_session):
|
||||
"""Ensure clean session state before each test."""
|
||||
try:
|
||||
# Check if session has pending rollback
|
||||
if orm_session.in_transaction() and orm_session.is_active:
|
||||
if hasattr(orm_session, '_transaction') and orm_session._transaction.is_active:
|
||||
# Session is in a good state
|
||||
pass
|
||||
yield
|
||||
except Exception:
|
||||
orm_session.rollback()
|
||||
raise
|
||||
finally:
|
||||
# Cleanup after test
|
||||
try:
|
||||
if orm_session.in_transaction():
|
||||
orm_session.rollback()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
class TestBillingPeriod:
|
||||
"""Test cases for BillingPeriod model."""
|
||||
|
||||
def test_billing_period_creation(self, orm_session, test_org):
|
||||
"""Test creating a new billing period."""
|
||||
period_start = datetime(2024, 2, 1, tzinfo=timezone.utc)
|
||||
period_end = datetime(2024, 2, 29, tzinfo=timezone.utc)
|
||||
|
||||
billing_period = BillingPeriod(
|
||||
org_id=test_org.id,
|
||||
period_start=period_start,
|
||||
period_end=period_end,
|
||||
seat_cost=4000,
|
||||
seat_count=1,
|
||||
total_cost=4000,
|
||||
)
|
||||
|
||||
orm_session.add(billing_period)
|
||||
orm_session.commit()
|
||||
|
||||
# Verify it was created
|
||||
assert billing_period.id is not None
|
||||
assert billing_period.org_id == test_org.id
|
||||
assert billing_period.period_start == period_start
|
||||
assert billing_period.period_end == period_end
|
||||
|
||||
def test_billing_period_required_fields(self, orm_session, test_org, billing_period_factory):
|
||||
"""Test billing period with all required fields."""
|
||||
billing_period = billing_period_factory(
|
||||
test_org.id,
|
||||
seat_cost=0,
|
||||
seat_count=0,
|
||||
total_cost=0,
|
||||
)
|
||||
|
||||
orm_session.add(billing_period)
|
||||
orm_session.commit()
|
||||
|
||||
assert billing_period.id is not None
|
||||
|
||||
def test_billing_period_default_values(self, orm_session, test_org, billing_period_factory):
|
||||
"""Test billing period default field values."""
|
||||
billing_period = billing_period_factory(test_org.id)
|
||||
|
||||
orm_session.add(billing_period)
|
||||
orm_session.commit()
|
||||
|
||||
# Check defaults
|
||||
assert billing_period.seat_cost == 0
|
||||
assert billing_period.seat_count == 0
|
||||
assert billing_period.usage_costs == {}
|
||||
assert billing_period.usage_quantities == {}
|
||||
assert billing_period.total_cost == 0
|
||||
assert billing_period.status == 'pending'
|
||||
assert billing_period.stripe_invoice_id is None
|
||||
assert billing_period.invoiced_at is None
|
||||
assert billing_period.created_at is not None
|
||||
|
||||
def test_billing_period_usage_costs_json_field(self, orm_session, test_org, billing_period_factory):
|
||||
"""Test usage_costs JSONB field stores and retrieves data correctly."""
|
||||
usage_costs = {"tokens": 120, "spans": 45, "custom_metric": 25}
|
||||
|
||||
billing_period = billing_period_factory(
|
||||
test_org.id,
|
||||
usage_costs=usage_costs,
|
||||
total_cost=190,
|
||||
)
|
||||
|
||||
orm_session.add(billing_period)
|
||||
orm_session.commit()
|
||||
|
||||
# Retrieve and verify JSON data
|
||||
retrieved_period = orm_session.query(BillingPeriod).filter_by(id=billing_period.id).one()
|
||||
assert retrieved_period.usage_costs == usage_costs
|
||||
|
||||
def test_billing_period_usage_quantities_json_field(self, orm_session, test_org, billing_period_factory):
|
||||
"""Test usage_quantities JSONB field stores and retrieves data correctly."""
|
||||
usage_quantities = {"tokens": 6000000, "spans": 4500, "api_calls": 150}
|
||||
|
||||
billing_period = billing_period_factory(
|
||||
test_org.id,
|
||||
usage_quantities=usage_quantities,
|
||||
total_cost=0,
|
||||
)
|
||||
|
||||
orm_session.add(billing_period)
|
||||
orm_session.commit()
|
||||
|
||||
# Retrieve and verify JSON data
|
||||
retrieved_period = orm_session.query(BillingPeriod).filter_by(id=billing_period.id).one()
|
||||
assert retrieved_period.usage_quantities == usage_quantities
|
||||
|
||||
def test_billing_period_seat_cost_calculation(self, orm_session, test_org, billing_period_factory):
|
||||
"""Test seat_cost field stores cost in cents."""
|
||||
billing_period = billing_period_factory(
|
||||
test_org.id,
|
||||
seat_cost=15000, # $150.00 in cents
|
||||
seat_count=3,
|
||||
total_cost=15000,
|
||||
)
|
||||
|
||||
orm_session.add(billing_period)
|
||||
orm_session.commit()
|
||||
|
||||
assert billing_period.seat_cost == 15000
|
||||
assert billing_period.seat_count == 3
|
||||
|
||||
def test_billing_period_total_cost_calculation(self, orm_session, test_org, billing_period_factory):
|
||||
"""Test total_cost field calculation."""
|
||||
billing_period = billing_period_factory(
|
||||
test_org.id,
|
||||
seat_cost=8000,
|
||||
usage_costs={"tokens": 200, "spans": 75},
|
||||
total_cost=8275, # 8000 + 200 + 75
|
||||
)
|
||||
|
||||
orm_session.add(billing_period)
|
||||
orm_session.commit()
|
||||
|
||||
assert billing_period.total_cost == 8275
|
||||
|
||||
def test_billing_period_status_values(self, orm_session, test_org, billing_period_factory):
|
||||
"""Test billing period status field accepts valid values."""
|
||||
valid_statuses = ['pending', 'invoiced', 'paid', 'failed']
|
||||
|
||||
for status in valid_statuses:
|
||||
billing_period = billing_period_factory(
|
||||
test_org.id,
|
||||
status=status,
|
||||
total_cost=0,
|
||||
)
|
||||
|
||||
orm_session.add(billing_period)
|
||||
orm_session.flush()
|
||||
|
||||
assert billing_period.status == status
|
||||
|
||||
orm_session.delete(billing_period)
|
||||
orm_session.flush()
|
||||
|
||||
def test_billing_period_datetime_fields(self, orm_session, test_org, billing_period_factory):
|
||||
"""Test datetime fields are properly handled."""
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
period_start = datetime(2024, 10, 15, tzinfo=timezone.utc)
|
||||
period_end = datetime(2024, 10, 16, tzinfo=timezone.utc)
|
||||
invoiced_at = datetime(2024, 11, 1, tzinfo=timezone.utc)
|
||||
|
||||
billing_period = billing_period_factory(
|
||||
test_org.id,
|
||||
period_start=period_start,
|
||||
period_end=period_end,
|
||||
invoiced_at=invoiced_at,
|
||||
total_cost=0,
|
||||
)
|
||||
|
||||
orm_session.add(billing_period)
|
||||
orm_session.commit()
|
||||
|
||||
assert billing_period.period_start == period_start
|
||||
assert billing_period.period_end == period_end
|
||||
assert billing_period.invoiced_at == invoiced_at
|
||||
|
||||
# Just verify created_at was set automatically and is a reasonable timestamp
|
||||
assert billing_period.created_at is not None
|
||||
assert isinstance(billing_period.created_at, datetime)
|
||||
# Verify it's within the last hour (very generous range)
|
||||
one_hour_ago = datetime.now(timezone.utc) - timedelta(hours=1)
|
||||
one_hour_future = datetime.now(timezone.utc) + timedelta(hours=1)
|
||||
|
||||
if billing_period.created_at.tzinfo is None:
|
||||
created_at_utc = billing_period.created_at.replace(tzinfo=timezone.utc)
|
||||
else:
|
||||
created_at_utc = billing_period.created_at
|
||||
|
||||
assert one_hour_ago <= created_at_utc <= one_hour_future
|
||||
|
||||
def test_billing_period_foreign_key_relationship(self, orm_session, test_org, billing_period_factory):
|
||||
"""Test billing period foreign key to organization."""
|
||||
billing_period = billing_period_factory(
|
||||
test_org.id,
|
||||
total_cost=0,
|
||||
)
|
||||
|
||||
orm_session.add(billing_period)
|
||||
orm_session.commit()
|
||||
|
||||
# Verify foreign key relationship
|
||||
assert billing_period.org_id == test_org.id
|
||||
|
||||
def test_billing_period_unique_constraint(self, orm_session, test_org, billing_period_factory):
|
||||
"""Test unique constraint on org_id and period_start."""
|
||||
period_start = datetime(2024, 12, 15, tzinfo=timezone.utc)
|
||||
period_end = datetime(2024, 12, 16, tzinfo=timezone.utc)
|
||||
|
||||
# Create first billing period
|
||||
billing_period1 = billing_period_factory(
|
||||
test_org.id, period_start=period_start, period_end=period_end, total_cost=0
|
||||
)
|
||||
orm_session.add(billing_period1)
|
||||
orm_session.commit()
|
||||
|
||||
# Try to create second billing period with same org_id and period_start
|
||||
billing_period2 = BillingPeriod(
|
||||
org_id=test_org.id,
|
||||
period_start=period_start, # Same period_start
|
||||
period_end=datetime(2025, 1, 1, tzinfo=timezone.utc), # Different period_end
|
||||
total_cost=0,
|
||||
)
|
||||
orm_session.add(billing_period2)
|
||||
|
||||
# Should raise IntegrityError due to unique constraint
|
||||
with pytest.raises(IntegrityError):
|
||||
orm_session.commit()
|
||||
|
||||
# Rollback the failed transaction to cleanup
|
||||
orm_session.rollback()
|
||||
|
||||
def test_billing_period_query_by_org(
|
||||
self, orm_session, test_org, test_billing_period, billing_period_factory
|
||||
):
|
||||
"""Test querying billing periods by organization."""
|
||||
# Create another org to ensure we only get periods for the specific org
|
||||
other_org = OrgModel(name="Other Test Org")
|
||||
orm_session.add(other_org)
|
||||
orm_session.flush()
|
||||
|
||||
other_period = billing_period_factory(
|
||||
other_org.id,
|
||||
total_cost=0,
|
||||
)
|
||||
orm_session.add(other_period)
|
||||
orm_session.commit()
|
||||
|
||||
# Query periods for test_org only, filter by the specific fixture period
|
||||
periods = (
|
||||
orm_session.query(BillingPeriod)
|
||||
.filter(BillingPeriod.org_id == test_org.id, BillingPeriod.id == test_billing_period.id)
|
||||
.all()
|
||||
)
|
||||
|
||||
assert len(periods) == 1
|
||||
assert periods[0].id == test_billing_period.id
|
||||
|
||||
def test_billing_period_query_by_date_range(self, orm_session, test_org, billing_period_factory):
|
||||
"""Test querying billing periods by date range."""
|
||||
# Create periods for different months with very specific dates
|
||||
jan_start = datetime(2025, 3, 15, tzinfo=timezone.utc)
|
||||
jan_end = datetime(2025, 3, 16, tzinfo=timezone.utc)
|
||||
|
||||
feb_start = datetime(2025, 4, 15, tzinfo=timezone.utc)
|
||||
feb_end = datetime(2025, 4, 16, tzinfo=timezone.utc)
|
||||
|
||||
jan_period = billing_period_factory(
|
||||
test_org.id, period_start=jan_start, period_end=jan_end, total_cost=0
|
||||
)
|
||||
|
||||
feb_period = billing_period_factory(
|
||||
test_org.id, period_start=feb_start, period_end=feb_end, total_cost=0
|
||||
)
|
||||
|
||||
orm_session.add_all([jan_period, feb_period])
|
||||
orm_session.commit()
|
||||
|
||||
# Query periods ending before April 1st - should only get the March period
|
||||
cutoff_date = datetime(2025, 4, 1, tzinfo=timezone.utc)
|
||||
early_periods = (
|
||||
orm_session.query(BillingPeriod)
|
||||
.filter(
|
||||
BillingPeriod.org_id == test_org.id,
|
||||
BillingPeriod.period_end < cutoff_date,
|
||||
BillingPeriod.id.in_([jan_period.id, feb_period.id]), # Only check our test records
|
||||
)
|
||||
.all()
|
||||
)
|
||||
|
||||
assert len(early_periods) == 1
|
||||
assert early_periods[0].id == jan_period.id
|
||||
|
||||
def test_billing_period_stripe_invoice_id_field(self, orm_session, test_org, billing_period_factory):
|
||||
"""Test stripe_invoice_id field stores Stripe invoice reference."""
|
||||
stripe_invoice_id = "in_1234567890abcdef"
|
||||
|
||||
billing_period = billing_period_factory(
|
||||
test_org.id,
|
||||
stripe_invoice_id=stripe_invoice_id,
|
||||
total_cost=0,
|
||||
)
|
||||
|
||||
orm_session.add(billing_period)
|
||||
orm_session.commit()
|
||||
|
||||
assert billing_period.stripe_invoice_id == stripe_invoice_id
|
||||
|
||||
def test_billing_period_invoiced_at_timestamp(self, orm_session, test_org, billing_period_factory):
|
||||
"""Test invoiced_at timestamp field."""
|
||||
invoiced_at = datetime(2025, 6, 1, 12, 30, 45, tzinfo=timezone.utc)
|
||||
|
||||
billing_period = billing_period_factory(
|
||||
test_org.id,
|
||||
invoiced_at=invoiced_at,
|
||||
status='invoiced',
|
||||
total_cost=0,
|
||||
)
|
||||
|
||||
orm_session.add(billing_period)
|
||||
orm_session.commit()
|
||||
|
||||
assert billing_period.invoiced_at == invoiced_at
|
||||
|
||||
def test_billing_period_auto_created_at(self, orm_session, test_org, billing_period_factory):
|
||||
"""Test created_at field is automatically set."""
|
||||
before_creation = datetime.now(timezone.utc)
|
||||
|
||||
billing_period = billing_period_factory(
|
||||
test_org.id,
|
||||
total_cost=0,
|
||||
)
|
||||
|
||||
orm_session.add(billing_period)
|
||||
orm_session.commit()
|
||||
|
||||
# Just verify created_at was set automatically and is a reasonable timestamp
|
||||
assert billing_period.created_at is not None
|
||||
assert isinstance(billing_period.created_at, datetime)
|
||||
# Verify it's within the last hour (very generous range)
|
||||
one_hour_ago = datetime.now(timezone.utc) - timedelta(hours=1)
|
||||
one_hour_future = datetime.now(timezone.utc) + timedelta(hours=1)
|
||||
|
||||
if billing_period.created_at.tzinfo is None:
|
||||
created_at_utc = billing_period.created_at.replace(tzinfo=timezone.utc)
|
||||
else:
|
||||
created_at_utc = billing_period.created_at
|
||||
|
||||
assert one_hour_ago <= created_at_utc <= one_hour_future
|
||||
|
||||
|
||||
class TestBillingAuditLog:
|
||||
"""Test cases for BillingAuditLog model."""
|
||||
|
||||
def test_billing_audit_log_creation(self, orm_session, test_org, test_user):
|
||||
"""Test creating a new billing audit log entry."""
|
||||
# Ensure session is clean before test
|
||||
try:
|
||||
audit_log = BillingAuditLog(
|
||||
org_id=test_org.id,
|
||||
user_id=test_user.id,
|
||||
action='member_licensed',
|
||||
details={'member_id': str(test_user.id)},
|
||||
)
|
||||
|
||||
orm_session.add(audit_log)
|
||||
orm_session.commit()
|
||||
|
||||
assert audit_log.id is not None
|
||||
assert audit_log.org_id == test_org.id
|
||||
assert audit_log.user_id == test_user.id
|
||||
except Exception:
|
||||
# Rollback on any error to clean up session
|
||||
orm_session.rollback()
|
||||
raise
|
||||
|
||||
def test_billing_audit_log_required_fields(self, orm_session, test_org, test_user):
|
||||
"""Test billing audit log with all required fields."""
|
||||
audit_log = BillingAuditLog(
|
||||
org_id=test_org.id, user_id=test_user.id, action='seats_updated', details={}
|
||||
)
|
||||
|
||||
orm_session.add(audit_log)
|
||||
orm_session.commit()
|
||||
|
||||
assert audit_log.id is not None
|
||||
assert audit_log.action == 'seats_updated'
|
||||
assert audit_log.details == {}
|
||||
|
||||
def test_billing_audit_log_auto_id_generation(self, orm_session, test_org, test_user):
|
||||
"""Test audit log ID is automatically generated."""
|
||||
audit_log = BillingAuditLog(
|
||||
org_id=test_org.id, user_id=test_user.id, action='member_unlicensed', details={'test': 'data'}
|
||||
)
|
||||
|
||||
# ID should be None before adding to session
|
||||
assert audit_log.id is None
|
||||
|
||||
orm_session.add(audit_log)
|
||||
orm_session.commit()
|
||||
|
||||
# ID should be generated after commit
|
||||
assert audit_log.id is not None
|
||||
assert isinstance(audit_log.id, uuid.UUID)
|
||||
|
||||
def test_billing_audit_log_foreign_key_org(self, orm_session, test_org, test_user):
|
||||
"""Test foreign key relationship to organization."""
|
||||
audit_log = BillingAuditLog(
|
||||
org_id=test_org.id, user_id=test_user.id, action='test_action', details={}
|
||||
)
|
||||
|
||||
orm_session.add(audit_log)
|
||||
orm_session.commit()
|
||||
|
||||
assert audit_log.org_id == test_org.id
|
||||
|
||||
def test_billing_audit_log_foreign_key_user(self, orm_session, test_org, test_user):
|
||||
"""Test foreign key relationship to user."""
|
||||
audit_log = BillingAuditLog(
|
||||
org_id=test_org.id, user_id=test_user.id, action='test_action', details={}
|
||||
)
|
||||
|
||||
orm_session.add(audit_log)
|
||||
orm_session.commit()
|
||||
|
||||
assert audit_log.user_id == test_user.id
|
||||
|
||||
def test_billing_audit_log_action_field(self, orm_session, test_org, test_user):
|
||||
"""Test action field stores different action types."""
|
||||
actions = [
|
||||
'member_licensed',
|
||||
'member_unlicensed',
|
||||
'seats_updated',
|
||||
'subscription_created',
|
||||
'subscription_cancelled',
|
||||
]
|
||||
|
||||
for action in actions:
|
||||
audit_log = BillingAuditLog(
|
||||
org_id=test_org.id, user_id=test_user.id, action=action, details={'action_type': action}
|
||||
)
|
||||
|
||||
orm_session.add(audit_log)
|
||||
orm_session.flush()
|
||||
|
||||
assert audit_log.action == action
|
||||
|
||||
orm_session.delete(audit_log)
|
||||
orm_session.flush()
|
||||
|
||||
def test_billing_audit_log_details_json_field(self, orm_session, test_org, test_user):
|
||||
"""Test details JSON field stores complex data."""
|
||||
complex_details = {
|
||||
'member_id': str(test_user.id),
|
||||
'member_email': 'test@example.com',
|
||||
'before_seat_count': 2,
|
||||
'after_seat_count': 3,
|
||||
'changed_by': 'admin@example.com',
|
||||
'timestamp': '2024-01-01T12:00:00Z',
|
||||
'metadata': {'ip_address': '192.168.1.1', 'user_agent': 'Mozilla/5.0...'},
|
||||
}
|
||||
|
||||
audit_log = BillingAuditLog(
|
||||
org_id=test_org.id, user_id=test_user.id, action='member_licensed', details=complex_details
|
||||
)
|
||||
|
||||
orm_session.add(audit_log)
|
||||
orm_session.commit()
|
||||
|
||||
# Retrieve and verify JSON data
|
||||
retrieved_log = orm_session.query(BillingAuditLog).filter_by(id=audit_log.id).one()
|
||||
assert retrieved_log.details == complex_details
|
||||
|
||||
def test_billing_audit_log_auto_created_at(self, orm_session, test_org, test_user):
|
||||
"""Test created_at field is automatically set."""
|
||||
try:
|
||||
before_creation = datetime.now(timezone.utc)
|
||||
|
||||
audit_log = BillingAuditLog(
|
||||
org_id=test_org.id, user_id=test_user.id, action='test_action', details={}
|
||||
)
|
||||
|
||||
orm_session.add(audit_log)
|
||||
orm_session.commit()
|
||||
|
||||
# Just verify created_at was set automatically and is a reasonable timestamp
|
||||
assert audit_log.created_at is not None
|
||||
assert isinstance(audit_log.created_at, datetime)
|
||||
# Verify it's within the last hour (very generous range)
|
||||
one_hour_ago = datetime.now(timezone.utc) - timedelta(hours=1)
|
||||
one_hour_future = datetime.now(timezone.utc) + timedelta(hours=1)
|
||||
|
||||
if audit_log.created_at.tzinfo is None:
|
||||
created_at_utc = audit_log.created_at.replace(tzinfo=timezone.utc)
|
||||
else:
|
||||
created_at_utc = audit_log.created_at
|
||||
|
||||
assert one_hour_ago <= created_at_utc <= one_hour_future
|
||||
except Exception:
|
||||
orm_session.rollback()
|
||||
raise
|
||||
|
||||
def test_billing_audit_log_member_licensed_action(self, orm_session, test_org, test_user):
|
||||
"""Test audit log for member licensed action."""
|
||||
details = {
|
||||
'member_id': str(test_user.id),
|
||||
'member_email': test_user.email,
|
||||
'new_seat_count': 2,
|
||||
'updated_by': 'admin@example.com',
|
||||
}
|
||||
|
||||
audit_log = BillingAuditLog(
|
||||
org_id=test_org.id, user_id=test_user.id, action='member_licensed', details=details
|
||||
)
|
||||
|
||||
orm_session.add(audit_log)
|
||||
orm_session.commit()
|
||||
|
||||
assert audit_log.action == 'member_licensed'
|
||||
assert audit_log.details['member_id'] == str(test_user.id)
|
||||
|
||||
def test_billing_audit_log_member_unlicensed_action(self, orm_session, test_org, test_user):
|
||||
"""Test audit log for member unlicensed action."""
|
||||
details = {
|
||||
'member_id': str(test_user.id),
|
||||
'member_email': test_user.email,
|
||||
'new_seat_count': 1,
|
||||
'updated_by': 'admin@example.com',
|
||||
}
|
||||
|
||||
audit_log = BillingAuditLog(
|
||||
org_id=test_org.id, user_id=test_user.id, action='member_unlicensed', details=details
|
||||
)
|
||||
|
||||
orm_session.add(audit_log)
|
||||
orm_session.commit()
|
||||
|
||||
assert audit_log.action == 'member_unlicensed'
|
||||
assert audit_log.details['new_seat_count'] == 1
|
||||
|
||||
def test_billing_audit_log_seats_updated_action(self, orm_session, test_org, test_user):
|
||||
"""Test audit log for seats updated action."""
|
||||
details = {
|
||||
'before_seat_count': 2,
|
||||
'after_seat_count': 5,
|
||||
'change_reason': 'bulk_member_addition',
|
||||
'updated_by': str(test_user.id),
|
||||
}
|
||||
|
||||
audit_log = BillingAuditLog(
|
||||
org_id=test_org.id, user_id=test_user.id, action='seats_updated', details=details
|
||||
)
|
||||
|
||||
orm_session.add(audit_log)
|
||||
orm_session.commit()
|
||||
|
||||
assert audit_log.action == 'seats_updated'
|
||||
assert audit_log.details['before_seat_count'] == 2
|
||||
assert audit_log.details['after_seat_count'] == 5
|
||||
|
||||
def test_billing_audit_log_query_by_org(self, orm_session, test_org, test_user, test_billing_audit_log):
|
||||
"""Test querying audit logs by organization."""
|
||||
# Create another org to ensure we only get logs for the specific org
|
||||
other_org = OrgModel(name="Other Test Org")
|
||||
orm_session.add(other_org)
|
||||
orm_session.flush()
|
||||
|
||||
other_log = BillingAuditLog(
|
||||
org_id=other_org.id, user_id=test_user.id, action='other_action', details={}
|
||||
)
|
||||
orm_session.add(other_log)
|
||||
orm_session.commit()
|
||||
|
||||
# Query logs for test_org only
|
||||
logs = orm_session.query(BillingAuditLog).filter_by(org_id=test_org.id).all()
|
||||
|
||||
assert len(logs) == 1
|
||||
assert logs[0].id == test_billing_audit_log.id
|
||||
|
||||
def test_billing_audit_log_query_by_user(
|
||||
self, orm_session, test_org, test_user, test_user2, test_billing_audit_log
|
||||
):
|
||||
"""Test querying audit logs by user."""
|
||||
try:
|
||||
# Use test_user2 fixture instead of creating a new user
|
||||
|
||||
other_log = BillingAuditLog(
|
||||
org_id=test_org.id, user_id=test_user2.id, action='other_action', details={}
|
||||
)
|
||||
orm_session.add(other_log)
|
||||
orm_session.commit()
|
||||
|
||||
# Query logs for test_user only, specifically filter by our test fixture
|
||||
logs = (
|
||||
orm_session.query(BillingAuditLog)
|
||||
.filter(
|
||||
BillingAuditLog.user_id == test_user.id, BillingAuditLog.id == test_billing_audit_log.id
|
||||
)
|
||||
.all()
|
||||
)
|
||||
|
||||
assert len(logs) == 1
|
||||
assert logs[0].id == test_billing_audit_log.id
|
||||
except Exception:
|
||||
orm_session.rollback()
|
||||
raise
|
||||
|
||||
def test_billing_audit_log_query_by_action(self, orm_session, test_org, test_user):
|
||||
"""Test querying audit logs by action type."""
|
||||
try:
|
||||
# Create logs with different actions
|
||||
licensed_log = BillingAuditLog(
|
||||
org_id=test_org.id, user_id=test_user.id, action='member_licensed', details={}
|
||||
)
|
||||
|
||||
unlicensed_log = BillingAuditLog(
|
||||
org_id=test_org.id, user_id=test_user.id, action='member_unlicensed', details={}
|
||||
)
|
||||
|
||||
orm_session.add_all([licensed_log, unlicensed_log])
|
||||
orm_session.commit()
|
||||
|
||||
# Query only licensed actions, filter by our specific test records
|
||||
licensed_logs = (
|
||||
orm_session.query(BillingAuditLog)
|
||||
.filter(
|
||||
BillingAuditLog.action == 'member_licensed',
|
||||
BillingAuditLog.org_id == test_org.id,
|
||||
BillingAuditLog.id.in_([licensed_log.id, unlicensed_log.id]),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
|
||||
assert len(licensed_logs) == 1
|
||||
assert licensed_logs[0].id == licensed_log.id
|
||||
except Exception:
|
||||
orm_session.rollback()
|
||||
raise
|
||||
|
||||
def test_billing_audit_log_query_by_date_range(self, orm_session, test_org, test_user):
|
||||
"""Test querying audit logs by date range."""
|
||||
try:
|
||||
from datetime import timedelta
|
||||
from sqlalchemy import text
|
||||
|
||||
# Create logs at different times
|
||||
old_log = BillingAuditLog(
|
||||
org_id=test_org.id, user_id=test_user.id, action='old_action', details={}
|
||||
)
|
||||
orm_session.add(old_log)
|
||||
orm_session.commit()
|
||||
|
||||
# Manually set an older created_at time using proper SQLAlchemy text()
|
||||
old_time = datetime.now(timezone.utc) - timedelta(days=30)
|
||||
orm_session.execute(
|
||||
text("UPDATE billing_audit_logs SET created_at = :old_time WHERE id = :log_id"),
|
||||
{"old_time": old_time, "log_id": str(old_log.id)},
|
||||
)
|
||||
orm_session.commit()
|
||||
|
||||
new_log = BillingAuditLog(
|
||||
org_id=test_org.id, user_id=test_user.id, action='new_action', details={}
|
||||
)
|
||||
orm_session.add(new_log)
|
||||
orm_session.commit()
|
||||
|
||||
# Query logs from the last week, filter by our specific test records
|
||||
cutoff_date = datetime.now(timezone.utc) - timedelta(days=7)
|
||||
recent_logs = (
|
||||
orm_session.query(BillingAuditLog)
|
||||
.filter(
|
||||
BillingAuditLog.created_at >= cutoff_date,
|
||||
BillingAuditLog.org_id == test_org.id,
|
||||
BillingAuditLog.id.in_([old_log.id, new_log.id]),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
|
||||
assert len(recent_logs) == 1
|
||||
assert recent_logs[0].id == new_log.id
|
||||
except Exception:
|
||||
orm_session.rollback()
|
||||
raise
|
||||
|
||||
def test_billing_audit_log_details_before_after_structure(self, orm_session, test_org, test_user):
|
||||
"""Test audit log details contain before/after values."""
|
||||
details = {
|
||||
'before': {'seat_count': 2, 'licensed_members': ['user1@example.com', 'user2@example.com']},
|
||||
'after': {
|
||||
'seat_count': 3,
|
||||
'licensed_members': ['user1@example.com', 'user2@example.com', 'user3@example.com'],
|
||||
},
|
||||
'changed_by': 'admin@example.com',
|
||||
}
|
||||
|
||||
audit_log = BillingAuditLog(
|
||||
org_id=test_org.id, user_id=test_user.id, action='seats_updated', details=details
|
||||
)
|
||||
|
||||
orm_session.add(audit_log)
|
||||
orm_session.commit()
|
||||
|
||||
assert 'before' in audit_log.details
|
||||
assert 'after' in audit_log.details
|
||||
assert audit_log.details['before']['seat_count'] == 2
|
||||
assert audit_log.details['after']['seat_count'] == 3
|
||||
|
||||
def test_billing_audit_log_multiple_entries_same_org(self, orm_session, test_org, test_user):
|
||||
"""Test multiple audit log entries for same organization."""
|
||||
logs = []
|
||||
for i in range(5):
|
||||
log = BillingAuditLog(
|
||||
org_id=test_org.id, user_id=test_user.id, action=f'action_{i}', details={'step': i}
|
||||
)
|
||||
logs.append(log)
|
||||
|
||||
orm_session.add_all(logs)
|
||||
orm_session.commit()
|
||||
|
||||
# Query all logs for the org
|
||||
org_logs = orm_session.query(BillingAuditLog).filter_by(org_id=test_org.id).all()
|
||||
|
||||
assert len(org_logs) == 5
|
||||
for log in org_logs:
|
||||
assert log.org_id == test_org.id
|
||||
|
||||
|
||||
class TestBillingModelIntegration:
|
||||
"""Test cases for billing model integration scenarios."""
|
||||
|
||||
def test_billing_period_with_audit_logs(self, orm_session, test_org, test_user, billing_period_factory):
|
||||
"""Test billing period creation generates appropriate audit logs."""
|
||||
try:
|
||||
# Create billing period
|
||||
billing_period = billing_period_factory(
|
||||
test_org.id,
|
||||
seat_cost=8000,
|
||||
total_cost=8000,
|
||||
)
|
||||
orm_session.add(billing_period)
|
||||
orm_session.commit()
|
||||
|
||||
# Create related audit log
|
||||
audit_log = BillingAuditLog(
|
||||
org_id=test_org.id,
|
||||
user_id=test_user.id,
|
||||
action='billing_period_created',
|
||||
details={
|
||||
'period_id': str(billing_period.id),
|
||||
'period_start': billing_period.period_start.isoformat(),
|
||||
'total_cost': billing_period.total_cost,
|
||||
},
|
||||
)
|
||||
orm_session.add(audit_log)
|
||||
orm_session.commit()
|
||||
|
||||
# Verify they're linked through org_id
|
||||
period_logs = orm_session.query(BillingAuditLog).filter_by(org_id=test_org.id).all()
|
||||
assert len(period_logs) == 1
|
||||
assert period_logs[0].details['period_id'] == str(billing_period.id)
|
||||
except Exception:
|
||||
orm_session.rollback()
|
||||
raise
|
||||
|
||||
def test_billing_data_consistency(self, orm_session, test_org, test_user, billing_period_factory):
|
||||
"""Test data consistency between billing period and audit logs."""
|
||||
try:
|
||||
# Create billing period
|
||||
billing_period = billing_period_factory(
|
||||
test_org.id,
|
||||
seat_count=3,
|
||||
seat_cost=12000,
|
||||
total_cost=12000,
|
||||
)
|
||||
orm_session.add(billing_period)
|
||||
orm_session.commit()
|
||||
|
||||
# Create audit log with matching data
|
||||
audit_log = BillingAuditLog(
|
||||
org_id=test_org.id,
|
||||
user_id=test_user.id,
|
||||
action='billing_snapshot_created',
|
||||
details={
|
||||
'period_id': str(billing_period.id),
|
||||
'seat_count': billing_period.seat_count,
|
||||
'seat_cost': billing_period.seat_cost,
|
||||
'total_cost': billing_period.total_cost,
|
||||
},
|
||||
)
|
||||
orm_session.add(audit_log)
|
||||
orm_session.commit()
|
||||
|
||||
# Verify data consistency
|
||||
assert audit_log.details['seat_count'] == billing_period.seat_count
|
||||
assert audit_log.details['seat_cost'] == billing_period.seat_cost
|
||||
assert audit_log.details['total_cost'] == billing_period.total_cost
|
||||
except Exception:
|
||||
orm_session.rollback()
|
||||
raise
|
||||
|
||||
def test_billing_models_cascade_delete(self, orm_session, test_org, test_user, billing_period_factory):
|
||||
"""Test that billing records prevent organization deletion (foreign key constraint)."""
|
||||
try:
|
||||
# Create billing period and audit log
|
||||
billing_period = billing_period_factory(
|
||||
test_org.id,
|
||||
total_cost=0,
|
||||
)
|
||||
|
||||
audit_log = BillingAuditLog(
|
||||
org_id=test_org.id, user_id=test_user.id, action='test_action', details={}
|
||||
)
|
||||
|
||||
orm_session.add_all([billing_period, audit_log])
|
||||
orm_session.commit()
|
||||
|
||||
# Try to delete the organization - should fail due to foreign key constraint
|
||||
# This is the expected behavior for billing records (audit trail preservation)
|
||||
orm_session.delete(test_org)
|
||||
|
||||
with pytest.raises(IntegrityError):
|
||||
orm_session.commit()
|
||||
|
||||
# Rollback the failed transaction
|
||||
orm_session.rollback()
|
||||
|
||||
# Verify billing records still exist
|
||||
remaining_periods = orm_session.query(BillingPeriod).filter_by(id=billing_period.id).all()
|
||||
remaining_logs = orm_session.query(BillingAuditLog).filter_by(id=audit_log.id).all()
|
||||
|
||||
assert len(remaining_periods) == 1
|
||||
assert len(remaining_logs) == 1
|
||||
except Exception:
|
||||
orm_session.rollback()
|
||||
raise
|
||||
|
||||
def test_billing_models_org_relationship_integrity(
|
||||
self, orm_session, test_org, test_user, billing_period_factory
|
||||
):
|
||||
"""Test referential integrity with organization model."""
|
||||
try:
|
||||
# Create billing records
|
||||
billing_period = billing_period_factory(
|
||||
test_org.id,
|
||||
total_cost=0,
|
||||
)
|
||||
|
||||
audit_log = BillingAuditLog(
|
||||
org_id=test_org.id, user_id=test_user.id, action='test_action', details={}
|
||||
)
|
||||
|
||||
orm_session.add_all([billing_period, audit_log])
|
||||
orm_session.commit()
|
||||
|
||||
# Verify they reference the correct organization
|
||||
assert billing_period.org_id == test_org.id
|
||||
assert audit_log.org_id == test_org.id
|
||||
|
||||
# Try to create billing record with non-existent org_id
|
||||
fake_org_id = uuid.uuid4()
|
||||
invalid_period = BillingPeriod(
|
||||
org_id=fake_org_id,
|
||||
period_start=datetime(2025, 12, 15, tzinfo=timezone.utc),
|
||||
period_end=datetime(2025, 12, 16, tzinfo=timezone.utc),
|
||||
total_cost=0,
|
||||
)
|
||||
|
||||
orm_session.add(invalid_period)
|
||||
|
||||
# Should raise IntegrityError due to foreign key constraint
|
||||
with pytest.raises(IntegrityError):
|
||||
orm_session.commit()
|
||||
|
||||
# Rollback the failed transaction
|
||||
orm_session.rollback()
|
||||
except Exception:
|
||||
orm_session.rollback()
|
||||
raise
|
||||
@@ -0,0 +1 @@
|
||||
# Test directory for opsboard services
|
||||
@@ -0,0 +1,621 @@
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock
|
||||
from datetime import datetime, timedelta
|
||||
from decimal import Decimal
|
||||
import os
|
||||
|
||||
from agentops.opsboard.services.billing_service import BillingService
|
||||
from agentops.opsboard.models import ProjectModel, BillingPeriod
|
||||
from agentops.common.usage_tracking import UsageType
|
||||
|
||||
|
||||
# Mock Stripe environment variables for testing
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_stripe_env_vars():
|
||||
with (
|
||||
patch.dict(
|
||||
os.environ,
|
||||
{
|
||||
'STRIPE_SECRET_KEY': 'sk_test_mock_key',
|
||||
'STRIPE_SUBSCRIPTION_PRICE_ID': 'price_test_subscription',
|
||||
'STRIPE_TOKEN_PRICE_ID': 'price_test_token',
|
||||
'STRIPE_SPAN_PRICE_ID': 'price_test_span',
|
||||
},
|
||||
),
|
||||
patch('stripe.Account.retrieve'),
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def billing_service():
|
||||
"""Create a billing service instance for testing."""
|
||||
# Mock the Stripe validation to avoid API calls during initialization
|
||||
with patch('stripe.Account.retrieve'):
|
||||
return BillingService()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_stripe_price():
|
||||
"""Mock Stripe price object."""
|
||||
mock_price = MagicMock()
|
||||
mock_price.unit_amount = 2000 # $20.00 in cents
|
||||
mock_price.transform_quantity = None
|
||||
return mock_price
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_clickhouse_client():
|
||||
"""Mock ClickHouse client for usage queries."""
|
||||
mock_client = MagicMock()
|
||||
mock_result = MagicMock()
|
||||
mock_result.result_rows = [
|
||||
(1000, 82000) # span_count, total_tokens (50000+25000+5000+2000)
|
||||
]
|
||||
mock_client.query.return_value = mock_result
|
||||
return mock_client
|
||||
|
||||
|
||||
class TestBillingService:
|
||||
"""Test cases for BillingService class."""
|
||||
|
||||
def test_init(self):
|
||||
"""Test BillingService initialization."""
|
||||
service = BillingService()
|
||||
|
||||
assert service._pricing_cache is None
|
||||
assert service._cache_timestamp is None
|
||||
assert service._cache_duration == 3600 # 1 hour
|
||||
assert service._usage_cache == {}
|
||||
assert service._usage_cache_ttl == 300 # 5 minutes
|
||||
|
||||
def test_should_refresh_cache_when_no_cache(self, billing_service):
|
||||
"""Test _should_refresh_cache returns True when no cache exists."""
|
||||
# Ensure no cache exists
|
||||
billing_service._pricing_cache = None
|
||||
billing_service._cache_timestamp = None
|
||||
|
||||
assert billing_service._should_refresh_cache() is True
|
||||
|
||||
def test_should_refresh_cache_when_cache_expired(self, billing_service):
|
||||
"""Test _should_refresh_cache returns True when cache is expired."""
|
||||
# Set cache with expired timestamp
|
||||
billing_service._pricing_cache = {"test": "data"}
|
||||
billing_service._cache_timestamp = datetime.now() - timedelta(seconds=3700) # Older than 1 hour
|
||||
|
||||
assert billing_service._should_refresh_cache() is True
|
||||
|
||||
def test_should_refresh_cache_when_cache_valid(self, billing_service):
|
||||
"""Test _should_refresh_cache returns False when cache is still valid."""
|
||||
# Set cache with recent timestamp
|
||||
billing_service._pricing_cache = {"test": "data"}
|
||||
billing_service._cache_timestamp = datetime.now() - timedelta(seconds=1800) # 30 minutes ago
|
||||
|
||||
assert billing_service._should_refresh_cache() is False
|
||||
|
||||
@patch('agentops.opsboard.services.billing_service.STRIPE_SPAN_PRICE_ID', 'price_span123')
|
||||
@patch('agentops.opsboard.services.billing_service.STRIPE_TOKEN_PRICE_ID', 'price_token123')
|
||||
@patch('stripe.Price.retrieve')
|
||||
def test_get_usage_pricing_with_stripe_success(self, mock_price_retrieve, billing_service):
|
||||
"""Test get_usage_pricing successfully fetches from Stripe."""
|
||||
# Clear cache to ensure fresh call
|
||||
billing_service._pricing_cache = None
|
||||
billing_service._cache_timestamp = None
|
||||
|
||||
# Mock Stripe price objects
|
||||
token_price = MagicMock()
|
||||
token_price.unit_amount = 2 # $0.02 in cents for 1000 tokens
|
||||
token_price.unit_amount_decimal = None
|
||||
token_price.custom_unit_amount = None
|
||||
token_price.tiers = None
|
||||
token_price.currency_options = None
|
||||
token_price.transform_quantity = MagicMock()
|
||||
token_price.transform_quantity.divide_by = 1000
|
||||
|
||||
span_price = MagicMock()
|
||||
span_price.unit_amount = 100 # $1.00 in cents per span
|
||||
span_price.unit_amount_decimal = None
|
||||
span_price.custom_unit_amount = None
|
||||
span_price.tiers = None
|
||||
span_price.currency_options = None
|
||||
span_price.transform_quantity = None
|
||||
|
||||
mock_price_retrieve.side_effect = [token_price, span_price]
|
||||
|
||||
pricing = billing_service.get_usage_pricing()
|
||||
|
||||
assert UsageType.TOKENS in pricing
|
||||
assert UsageType.SPANS in pricing
|
||||
|
||||
# Check token pricing - unit_amount 2 becomes 2/100 = 0.02 dollars
|
||||
token_config = pricing[UsageType.TOKENS]
|
||||
assert token_config['price_per_unit'] == Decimal('0.02')
|
||||
assert token_config['unit_size'] == 1000
|
||||
assert token_config['display_unit'] == 'thousand tokens'
|
||||
assert token_config['stripe_price_id'] == 'price_token123'
|
||||
|
||||
# Check span pricing
|
||||
span_config = pricing[UsageType.SPANS]
|
||||
assert span_config['price_per_unit'] == Decimal('1.00')
|
||||
assert span_config['unit_size'] == 1000
|
||||
assert span_config['display_unit'] == 'thousand spans'
|
||||
assert span_config['stripe_price_id'] == 'price_span123'
|
||||
|
||||
@patch('stripe.Price.retrieve')
|
||||
def test_get_usage_pricing_with_stripe_error(self, mock_price_retrieve, billing_service):
|
||||
"""Test get_usage_pricing falls back to defaults when Stripe fails."""
|
||||
import stripe
|
||||
|
||||
mock_price_retrieve.side_effect = stripe.error.StripeError("API Error")
|
||||
|
||||
pricing = billing_service.get_usage_pricing()
|
||||
|
||||
# Should return default values
|
||||
assert UsageType.TOKENS in pricing
|
||||
assert UsageType.SPANS in pricing
|
||||
|
||||
token_config = pricing[UsageType.TOKENS]
|
||||
assert token_config['price_per_unit'] == Decimal('0.0002')
|
||||
assert token_config['unit_size'] == 1000
|
||||
assert token_config['display_unit'] == 'thousand tokens'
|
||||
|
||||
span_config = pricing[UsageType.SPANS]
|
||||
assert span_config['price_per_unit'] == Decimal('0.0001')
|
||||
assert span_config['unit_size'] == 1000
|
||||
assert span_config['display_unit'] == 'thousand spans'
|
||||
|
||||
@patch('agentops.opsboard.services.billing_service.STRIPE_SPAN_PRICE_ID', 'price_span123')
|
||||
@patch('agentops.opsboard.services.billing_service.STRIPE_TOKEN_PRICE_ID', 'price_token123')
|
||||
def test_get_usage_pricing_with_env_vars(self, billing_service):
|
||||
"""Test get_usage_pricing uses environment variable price IDs."""
|
||||
# Clear cache to ensure fresh call
|
||||
billing_service._pricing_cache = None
|
||||
billing_service._cache_timestamp = None
|
||||
|
||||
with patch('stripe.Price.retrieve') as mock_retrieve:
|
||||
token_price = MagicMock()
|
||||
token_price.unit_amount = 5
|
||||
token_price.unit_amount_decimal = None
|
||||
token_price.custom_unit_amount = None
|
||||
token_price.tiers = None
|
||||
token_price.currency_options = None
|
||||
token_price.transform_quantity = None
|
||||
|
||||
span_price = MagicMock()
|
||||
span_price.unit_amount = 150
|
||||
span_price.unit_amount_decimal = None
|
||||
span_price.custom_unit_amount = None
|
||||
span_price.tiers = None
|
||||
span_price.currency_options = None
|
||||
span_price.transform_quantity = None
|
||||
|
||||
mock_retrieve.side_effect = [token_price, span_price]
|
||||
|
||||
billing_service.get_usage_pricing()
|
||||
|
||||
# Verify that Stripe was called with the environment variable price IDs
|
||||
assert mock_retrieve.call_count == 2
|
||||
mock_retrieve.assert_any_call('price_token123', expand=['currency_options', 'tiers'])
|
||||
mock_retrieve.assert_any_call('price_span123', expand=['currency_options', 'tiers'])
|
||||
|
||||
def test_get_usage_pricing_returns_cached_values(self, billing_service):
|
||||
"""Test get_usage_pricing returns cached values when cache is valid."""
|
||||
# Set up valid cache
|
||||
cached_pricing = {
|
||||
UsageType.TOKENS: {'price_per_unit': Decimal('0.01'), 'unit_size': 1000},
|
||||
UsageType.SPANS: {'price_per_unit': Decimal('0.002'), 'unit_size': 1},
|
||||
}
|
||||
billing_service._pricing_cache = cached_pricing
|
||||
billing_service._cache_timestamp = datetime.now()
|
||||
|
||||
with patch('stripe.Price.retrieve') as mock_retrieve:
|
||||
pricing = billing_service.get_usage_pricing()
|
||||
|
||||
# Should return cached values without calling Stripe
|
||||
assert pricing == cached_pricing
|
||||
mock_retrieve.assert_not_called()
|
||||
|
||||
@patch('agentops.opsboard.services.billing_service.STRIPE_SUBSCRIPTION_PRICE_ID', 'price_sub123')
|
||||
@patch('stripe.Price.retrieve')
|
||||
def test_get_seat_price_from_stripe_success(self, mock_price_retrieve, billing_service):
|
||||
"""Test get_seat_price successfully fetches from Stripe."""
|
||||
mock_price = MagicMock()
|
||||
mock_price.unit_amount = 5000 # $50.00 in cents
|
||||
mock_price.unit_amount_decimal = None
|
||||
mock_price.custom_unit_amount = None
|
||||
mock_price.tiers = None
|
||||
mock_price.currency_options = None
|
||||
mock_price.recurring = MagicMock()
|
||||
mock_price.recurring.usage_type = 'licensed'
|
||||
|
||||
mock_price_retrieve.return_value = mock_price
|
||||
|
||||
seat_price = billing_service.get_seat_price()
|
||||
|
||||
assert seat_price == 5000
|
||||
mock_price_retrieve.assert_called_once_with('price_sub123', expand=['currency_options', 'tiers'])
|
||||
|
||||
@patch('stripe.Price.retrieve')
|
||||
def test_get_seat_price_stripe_error_fallback(self, mock_price_retrieve, billing_service):
|
||||
"""Test get_seat_price falls back to environment variable when Stripe fails."""
|
||||
import stripe
|
||||
|
||||
mock_price_retrieve.side_effect = stripe.error.StripeError("API Error")
|
||||
|
||||
with patch.dict(os.environ, {'STRIPE_SEAT_PRICE_CENTS': '6000'}):
|
||||
seat_price = billing_service.get_seat_price()
|
||||
|
||||
assert seat_price == 6000
|
||||
|
||||
@patch.dict('os.environ', {'STRIPE_SEAT_PRICE_CENTS': '5000'})
|
||||
def test_get_seat_price_from_env_var(self, billing_service):
|
||||
"""Test get_seat_price uses environment variable when no Stripe config."""
|
||||
# No STRIPE_SUBSCRIPTION_PRICE_ID set
|
||||
with patch.dict(os.environ, {}, clear=True):
|
||||
os.environ['STRIPE_SEAT_PRICE_CENTS'] = '5000'
|
||||
seat_price = billing_service.get_seat_price()
|
||||
|
||||
assert seat_price == 5000
|
||||
|
||||
@patch('agentops.opsboard.services.billing_service.get_clickhouse')
|
||||
async def test_get_usage_for_period_success(
|
||||
self, mock_get_clickhouse, billing_service, orm_session, test_org, mock_clickhouse_client
|
||||
):
|
||||
"""Test get_usage_for_period successfully queries ClickHouse."""
|
||||
# Create test projects for the org
|
||||
project1 = ProjectModel(name="Test Project 1", org_id=test_org.id)
|
||||
project2 = ProjectModel(name="Test Project 2", org_id=test_org.id)
|
||||
orm_session.add_all([project1, project2])
|
||||
orm_session.flush()
|
||||
|
||||
# Mock ClickHouse response
|
||||
mock_get_clickhouse.return_value = mock_clickhouse_client
|
||||
|
||||
period_start = datetime(2024, 1, 1)
|
||||
period_end = datetime(2024, 1, 31)
|
||||
|
||||
result = await billing_service.get_usage_for_period(
|
||||
orm_session, str(test_org.id), period_start, period_end
|
||||
)
|
||||
|
||||
assert result == {'tokens': 82000, 'spans': 1000} # 50000+25000+5000+2000 tokens, 1000 spans
|
||||
mock_clickhouse_client.query.assert_called_once()
|
||||
|
||||
async def test_get_usage_for_period_no_projects(self, billing_service, orm_session, test_org):
|
||||
"""Test get_usage_for_period returns empty when org has no projects."""
|
||||
period_start = datetime(2024, 1, 1)
|
||||
period_end = datetime(2024, 1, 31)
|
||||
|
||||
result = await billing_service.get_usage_for_period(
|
||||
orm_session, str(test_org.id), period_start, period_end
|
||||
)
|
||||
|
||||
assert result == {}
|
||||
|
||||
@patch('agentops.opsboard.services.billing_service.get_clickhouse')
|
||||
async def test_get_usage_for_period_clickhouse_error(
|
||||
self, mock_get_clickhouse, billing_service, orm_session, test_org
|
||||
):
|
||||
"""Test get_usage_for_period handles ClickHouse errors gracefully."""
|
||||
# Create test project
|
||||
project = ProjectModel(name="Test Project", org_id=test_org.id)
|
||||
orm_session.add(project)
|
||||
orm_session.flush()
|
||||
|
||||
# Mock ClickHouse to raise an error
|
||||
mock_client = MagicMock()
|
||||
mock_client.query.side_effect = Exception("ClickHouse connection failed")
|
||||
mock_get_clickhouse.return_value = mock_client
|
||||
|
||||
period_start = datetime(2024, 1, 1)
|
||||
period_end = datetime(2024, 1, 31)
|
||||
|
||||
result = await billing_service.get_usage_for_period(
|
||||
orm_session, str(test_org.id), period_start, period_end
|
||||
)
|
||||
|
||||
assert result == {}
|
||||
|
||||
async def test_get_usage_for_period_uses_cache(self, billing_service, orm_session, test_org):
|
||||
"""Test get_usage_for_period returns cached data when available."""
|
||||
from datetime import timezone
|
||||
|
||||
period_start = datetime(2024, 1, 1)
|
||||
period_end = datetime(2024, 1, 31)
|
||||
|
||||
# Convert to UTC as the implementation does
|
||||
period_start_utc = period_start.replace(tzinfo=timezone.utc)
|
||||
period_end_utc = period_end.replace(tzinfo=timezone.utc)
|
||||
|
||||
cache_key = f"{test_org.id}:{period_start_utc.isoformat()}:{period_end_utc.isoformat()}:all"
|
||||
|
||||
# Set cache data
|
||||
cached_data = {'tokens': 5000, 'spans': 100}
|
||||
billing_service._usage_cache[cache_key] = (cached_data, datetime.now())
|
||||
|
||||
result = await billing_service.get_usage_for_period(
|
||||
orm_session, str(test_org.id), period_start, period_end
|
||||
)
|
||||
|
||||
assert result == cached_data
|
||||
|
||||
async def test_get_usage_for_period_cache_expiry(
|
||||
self, billing_service, orm_session, test_org, mock_clickhouse_client
|
||||
):
|
||||
"""Test get_usage_for_period refreshes data when cache is expired."""
|
||||
from datetime import timezone
|
||||
|
||||
period_start = datetime(2024, 1, 1)
|
||||
period_end = datetime(2024, 1, 31)
|
||||
|
||||
# Convert to UTC as the implementation does
|
||||
period_start_utc = period_start.replace(tzinfo=timezone.utc)
|
||||
period_end_utc = period_end.replace(tzinfo=timezone.utc)
|
||||
|
||||
cache_key = f"{test_org.id}:{period_start_utc.isoformat()}:{period_end_utc.isoformat()}:all"
|
||||
|
||||
# Set expired cache data
|
||||
expired_data = {'tokens': 1000, 'spans': 50}
|
||||
expired_time = datetime.now() - timedelta(seconds=400) # Older than 5 minutes
|
||||
billing_service._usage_cache[cache_key] = (expired_data, expired_time)
|
||||
|
||||
with patch('agentops.opsboard.services.billing_service.get_clickhouse') as mock_get_clickhouse:
|
||||
mock_get_clickhouse.return_value = mock_clickhouse_client
|
||||
|
||||
# Create test project
|
||||
project = ProjectModel(name="Test Project", org_id=test_org.id)
|
||||
orm_session.add(project)
|
||||
orm_session.flush()
|
||||
|
||||
result = await billing_service.get_usage_for_period(
|
||||
orm_session, str(test_org.id), period_start, period_end
|
||||
)
|
||||
|
||||
# Should get fresh data, not expired cache
|
||||
assert result == {'tokens': 82000, 'spans': 1000}
|
||||
|
||||
async def test_calculate_usage_costs_tokens(self, billing_service):
|
||||
"""Test calculate_usage_costs correctly calculates token costs."""
|
||||
# Mock pricing
|
||||
billing_service._pricing_cache = {
|
||||
UsageType.TOKENS: {'price_per_unit': Decimal('0.0002'), 'unit_size': 1000}
|
||||
}
|
||||
billing_service._cache_timestamp = datetime.now()
|
||||
|
||||
usage_quantities = {'tokens': 5000000} # 5M tokens
|
||||
|
||||
result = await billing_service.calculate_usage_costs(usage_quantities)
|
||||
|
||||
# 5M tokens / 1000 units * $0.0002 = $1.00 = 100 cents
|
||||
assert result == {'tokens': 100}
|
||||
|
||||
async def test_calculate_usage_costs_spans(self, billing_service):
|
||||
"""Test calculate_usage_costs correctly calculates span costs."""
|
||||
# Mock pricing
|
||||
billing_service._pricing_cache = {
|
||||
UsageType.SPANS: {'price_per_unit': Decimal('0.0001'), 'unit_size': 1000}
|
||||
}
|
||||
billing_service._cache_timestamp = datetime.now()
|
||||
|
||||
usage_quantities = {'spans': 1000000} # 1M spans
|
||||
|
||||
result = await billing_service.calculate_usage_costs(usage_quantities)
|
||||
|
||||
# 1M spans / 1000 units * $0.0001 = $0.10 = 10 cents
|
||||
assert result == {'spans': 10}
|
||||
|
||||
async def test_calculate_usage_costs_mixed_usage(self, billing_service):
|
||||
"""Test calculate_usage_costs handles multiple usage types."""
|
||||
# Mock pricing
|
||||
billing_service._pricing_cache = {
|
||||
UsageType.TOKENS: {'price_per_unit': Decimal('0.0002'), 'unit_size': 1000},
|
||||
UsageType.SPANS: {'price_per_unit': Decimal('0.0001'), 'unit_size': 1000},
|
||||
}
|
||||
billing_service._cache_timestamp = datetime.now()
|
||||
|
||||
usage_quantities = {'tokens': 2000000, 'spans': 500000}
|
||||
|
||||
result = await billing_service.calculate_usage_costs(usage_quantities)
|
||||
|
||||
# Tokens: 2M / 1000 * $0.0002 = $0.40 = 40 cents
|
||||
# Spans: 500K / 1000 * $0.0001 = $0.05 = 5 cents
|
||||
assert result == {'tokens': 40, 'spans': 5}
|
||||
|
||||
async def test_calculate_usage_costs_unknown_usage_type(self, billing_service):
|
||||
"""Test calculate_usage_costs ignores unknown usage types."""
|
||||
# Mock pricing
|
||||
billing_service._pricing_cache = {
|
||||
UsageType.TOKENS: {'price_per_unit': Decimal('0.0002'), 'unit_size': 1000}
|
||||
}
|
||||
billing_service._cache_timestamp = datetime.now()
|
||||
|
||||
usage_quantities = {'tokens': 1000000, 'unknown_type': 500}
|
||||
|
||||
result = await billing_service.calculate_usage_costs(usage_quantities)
|
||||
|
||||
# Should only calculate known types
|
||||
assert result == {'tokens': 20}
|
||||
assert 'unknown_type' not in result
|
||||
|
||||
async def test_calculate_usage_costs_zero_quantities(self, billing_service):
|
||||
"""Test calculate_usage_costs handles zero quantities."""
|
||||
# Mock pricing
|
||||
billing_service._pricing_cache = {
|
||||
UsageType.TOKENS: {'price_per_unit': Decimal('0.0002'), 'unit_size': 1000},
|
||||
UsageType.SPANS: {'price_per_unit': Decimal('0.0001'), 'unit_size': 1000},
|
||||
}
|
||||
billing_service._cache_timestamp = datetime.now()
|
||||
|
||||
usage_quantities = {'tokens': 0, 'spans': 0}
|
||||
|
||||
result = await billing_service.calculate_usage_costs(usage_quantities)
|
||||
|
||||
# With minimum charge threshold, zero quantities return empty dict
|
||||
assert result == {}
|
||||
|
||||
async def test_create_billing_period_snapshot_success(
|
||||
self, billing_service, orm_session, test_org, test_user, test_user2, test_user3
|
||||
):
|
||||
"""Test create_billing_period_snapshot creates a complete snapshot."""
|
||||
# Set up org with paid members using existing test user fixtures
|
||||
from agentops.opsboard.models import UserOrgModel, OrgRoles
|
||||
|
||||
# Create 3 paid member relationships using existing test users
|
||||
test_users = [test_user, test_user2, test_user3]
|
||||
|
||||
for user in test_users:
|
||||
user_org = UserOrgModel(
|
||||
user_id=user.id,
|
||||
org_id=test_org.id,
|
||||
role=OrgRoles.developer,
|
||||
user_email=user.email,
|
||||
is_paid=True,
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
|
||||
orm_session.flush()
|
||||
|
||||
# Mock the get_usage_for_period method
|
||||
with (
|
||||
patch.object(billing_service, 'get_usage_for_period') as mock_get_usage,
|
||||
patch.object(billing_service, 'calculate_usage_costs') as mock_calc_costs,
|
||||
patch.object(billing_service, 'get_seat_price') as mock_seat_price,
|
||||
):
|
||||
mock_get_usage.return_value = {'tokens': 1000000, 'spans': 500}
|
||||
mock_calc_costs.return_value = {'tokens': 20, 'spans': 50}
|
||||
mock_seat_price.return_value = 4000 # $40 per seat
|
||||
|
||||
period_start = datetime(2024, 1, 1)
|
||||
period_end = datetime(2024, 1, 31)
|
||||
|
||||
result = await billing_service.create_billing_period_snapshot(
|
||||
orm_session, test_org, period_start, period_end
|
||||
)
|
||||
|
||||
assert isinstance(result, BillingPeriod)
|
||||
assert result.org_id == test_org.id
|
||||
assert result.period_start == period_start
|
||||
assert result.period_end == period_end
|
||||
assert result.seat_cost == 12000 # 3 seats * $40
|
||||
assert result.seat_count == 3
|
||||
assert result.usage_costs == {'tokens': 20, 'spans': 50}
|
||||
assert result.usage_quantities == {'tokens': 1000000, 'spans': 500}
|
||||
assert result.total_cost == 12070 # 12000 + 20 + 50
|
||||
assert result.status == 'pending'
|
||||
|
||||
async def test_create_billing_period_snapshot_no_usage(
|
||||
self, billing_service, orm_session, test_org, test_user
|
||||
):
|
||||
"""Test create_billing_period_snapshot works with zero usage."""
|
||||
# Set up org with one paid member using existing test user fixture
|
||||
from agentops.opsboard.models import UserOrgModel, OrgRoles
|
||||
|
||||
user_org = UserOrgModel(
|
||||
user_id=test_user.id,
|
||||
org_id=test_org.id,
|
||||
role=OrgRoles.owner,
|
||||
user_email=test_user.email,
|
||||
is_paid=True,
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.flush()
|
||||
|
||||
with (
|
||||
patch.object(billing_service, 'get_usage_for_period') as mock_get_usage,
|
||||
patch.object(billing_service, 'calculate_usage_costs') as mock_calc_costs,
|
||||
patch.object(billing_service, 'get_seat_price') as mock_seat_price,
|
||||
):
|
||||
mock_get_usage.return_value = {}
|
||||
mock_calc_costs.return_value = {}
|
||||
mock_seat_price.return_value = 4000
|
||||
|
||||
period_start = datetime(2024, 1, 1)
|
||||
period_end = datetime(2024, 1, 31)
|
||||
|
||||
result = await billing_service.create_billing_period_snapshot(
|
||||
orm_session, test_org, period_start, period_end
|
||||
)
|
||||
|
||||
assert result.seat_cost == 4000
|
||||
assert result.usage_costs == {}
|
||||
assert result.total_cost == 4000
|
||||
|
||||
async def test_create_billing_period_snapshot_multiple_seats(
|
||||
self, billing_service, orm_session, test_org, test_user, test_user2, test_user3
|
||||
):
|
||||
"""Test create_billing_period_snapshot calculates multiple seat costs correctly."""
|
||||
# Set up org with multiple paid members using existing test user fixtures
|
||||
from agentops.opsboard.models import UserOrgModel, OrgRoles
|
||||
|
||||
# Create 3 paid member relationships using existing test users (can't reuse same user for same org)
|
||||
test_users = [test_user, test_user2, test_user3]
|
||||
|
||||
for user in test_users:
|
||||
user_org = UserOrgModel(
|
||||
user_id=user.id,
|
||||
org_id=test_org.id,
|
||||
role=OrgRoles.developer,
|
||||
user_email=user.email,
|
||||
is_paid=True,
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
|
||||
orm_session.flush()
|
||||
|
||||
with (
|
||||
patch.object(billing_service, 'get_usage_for_period') as mock_get_usage,
|
||||
patch.object(billing_service, 'calculate_usage_costs') as mock_calc_costs,
|
||||
patch.object(billing_service, 'get_seat_price') as mock_seat_price,
|
||||
):
|
||||
mock_get_usage.return_value = {'tokens': 500000}
|
||||
mock_calc_costs.return_value = {'tokens': 10}
|
||||
mock_seat_price.return_value = 3500 # $35 per seat
|
||||
|
||||
period_start = datetime(2024, 1, 1)
|
||||
period_end = datetime(2024, 1, 31)
|
||||
|
||||
result = await billing_service.create_billing_period_snapshot(
|
||||
orm_session, test_org, period_start, period_end
|
||||
)
|
||||
|
||||
assert result.seat_cost == 10500 # 3 seats * $35
|
||||
assert result.seat_count == 3
|
||||
assert result.total_cost == 10510 # 10500 + 10
|
||||
|
||||
async def test_create_billing_period_snapshot_commits_to_db(
|
||||
self, billing_service, orm_session, test_org, test_user
|
||||
):
|
||||
"""Test create_billing_period_snapshot commits the billing period to database."""
|
||||
# Set up org with one paid member using existing test user fixture
|
||||
from agentops.opsboard.models import UserOrgModel, OrgRoles
|
||||
|
||||
user_org = UserOrgModel(
|
||||
user_id=test_user.id,
|
||||
org_id=test_org.id,
|
||||
role=OrgRoles.owner,
|
||||
user_email=test_user.email,
|
||||
is_paid=True,
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.flush()
|
||||
|
||||
with (
|
||||
patch.object(billing_service, 'get_usage_for_period') as mock_get_usage,
|
||||
patch.object(billing_service, 'calculate_usage_costs') as mock_calc_costs,
|
||||
patch.object(billing_service, 'get_seat_price') as mock_seat_price,
|
||||
):
|
||||
mock_get_usage.return_value = {}
|
||||
mock_calc_costs.return_value = {}
|
||||
mock_seat_price.return_value = 4000
|
||||
|
||||
period_start = datetime(2024, 1, 1)
|
||||
period_end = datetime(2024, 1, 31)
|
||||
|
||||
result = await billing_service.create_billing_period_snapshot(
|
||||
orm_session, test_org, period_start, period_end
|
||||
)
|
||||
|
||||
# Verify it was added to the session and committed
|
||||
billing_period_in_db = orm_session.query(BillingPeriod).filter_by(id=result.id).first()
|
||||
assert billing_period_in_db is not None
|
||||
assert billing_period_in_db.org_id == test_org.id
|
||||
@@ -0,0 +1,94 @@
|
||||
import pytest
|
||||
import uuid
|
||||
from sqlalchemy.orm import Session
|
||||
from agentops.opsboard.models import AuthUserModel, UserModel
|
||||
|
||||
|
||||
@pytest.fixture(scope="function")
|
||||
async def auth_user(orm_session: Session, test_user: UserModel) -> AuthUserModel:
|
||||
"""Get the auth user corresponding to the test user."""
|
||||
# Get the auth user that corresponds to our test user
|
||||
auth_user = orm_session.get(AuthUserModel, test_user.id)
|
||||
|
||||
if not auth_user:
|
||||
# This should not happen with proper test setup since auth users should be seeded
|
||||
raise RuntimeError(f"No auth user found for test user ID {test_user.id}. Check seed data.")
|
||||
|
||||
return auth_user
|
||||
|
||||
|
||||
class TestAuthUserModel:
|
||||
"""Test cases for the AuthUserModel."""
|
||||
|
||||
async def test_auth_user_creation(self, auth_user: AuthUserModel):
|
||||
"""Test that AuthUserModel can be created successfully."""
|
||||
assert auth_user.id is not None
|
||||
assert auth_user.email == "test@example.com" # Matches the seeded auth user email
|
||||
assert str(auth_user.id) == "00000000-0000-0000-0000-000000000000" # From test_user fixture
|
||||
|
||||
async def test_auth_user_model_table_schema(self, auth_user: AuthUserModel):
|
||||
"""Test that AuthUserModel maps to correct table and schema."""
|
||||
assert auth_user.__tablename__ == "users"
|
||||
assert auth_user.__table_args__["schema"] == "auth"
|
||||
|
||||
async def test_billing_email_property_with_auth_user(self, orm_session: Session, test_user: UserModel):
|
||||
"""Test that billing_email property returns email from auth.users table."""
|
||||
# Refresh the user to ensure the relationship is loaded
|
||||
orm_session.refresh(test_user)
|
||||
|
||||
# The billing_email should come from auth.users, not public.users
|
||||
# Note: The actual auth email will depend on what's seeded for this test user ID
|
||||
assert test_user.billing_email is not None # Should have an auth email
|
||||
assert test_user.email == "test@example.com" # From test_user fixture
|
||||
# If auth email is different from public email, test that
|
||||
if test_user.billing_email != test_user.email:
|
||||
assert test_user.billing_email != test_user.email
|
||||
|
||||
async def test_billing_email_property_without_auth_user(self, orm_session: Session, test_user: UserModel):
|
||||
"""Test billing_email property when auth user has null email."""
|
||||
# Get the auth user and temporarily modify its email to None for testing
|
||||
auth_user = test_user.auth_user
|
||||
original_email = auth_user.email
|
||||
|
||||
try:
|
||||
# Temporarily modify the auth user's email in memory only (not persisted)
|
||||
# This simulates the case where auth.users.email is NULL
|
||||
object.__setattr__(auth_user, 'email', None)
|
||||
|
||||
# billing_email should return None when auth email is null
|
||||
assert test_user.billing_email is None
|
||||
assert test_user.email == "test@example.com" # public email remains from fixture
|
||||
|
||||
finally:
|
||||
# Restore original email
|
||||
object.__setattr__(auth_user, 'email', original_email)
|
||||
|
||||
async def test_auth_user_relationship_lazy_loading(self, orm_session: Session, test_user: UserModel):
|
||||
"""Test that the auth_user relationship works with lazy loading."""
|
||||
# Get user without explicitly loading auth_user relationship
|
||||
user = orm_session.get(UserModel, test_user.id)
|
||||
|
||||
# Accessing auth_user should trigger lazy load
|
||||
assert user.auth_user is not None
|
||||
# The auth email should exist (specific value depends on seed data)
|
||||
assert user.auth_user.email is not None
|
||||
|
||||
async def test_auth_user_model_columns(self, auth_user: AuthUserModel):
|
||||
"""Test that AuthUserModel has the expected columns."""
|
||||
# Check that the model has the basic columns we expect
|
||||
assert hasattr(auth_user, 'id')
|
||||
assert hasattr(auth_user, 'email')
|
||||
assert hasattr(auth_user, 'created_at')
|
||||
|
||||
# Verify column types are as expected
|
||||
assert isinstance(auth_user.id, uuid.UUID)
|
||||
assert isinstance(auth_user.email, str)
|
||||
|
||||
async def test_auth_user_model_read_only(self, auth_user: AuthUserModel):
|
||||
"""Test that AuthUserModel prevents modifications."""
|
||||
# Test that we can read the auth user
|
||||
assert auth_user.email is not None
|
||||
|
||||
# Test that attempting to modify a persistent auth user raises an error
|
||||
with pytest.raises(RuntimeError, match="AuthUserModel is read-only"):
|
||||
auth_user.email = "modified@example.com"
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,597 @@
|
||||
import pytest
|
||||
from unittest.mock import patch, MagicMock
|
||||
from fastapi import HTTPException
|
||||
from fastapi.responses import JSONResponse
|
||||
import uuid
|
||||
import stripe
|
||||
|
||||
from agentops.opsboard.views.billing import (
|
||||
BillingDashboardView,
|
||||
)
|
||||
from agentops.opsboard.models import OrgModel, UserOrgModel, OrgRoles, PremStatus
|
||||
from agentops.opsboard.services.billing_service import billing_service
|
||||
|
||||
# Import shared billing fixtures
|
||||
pytest_plugins = ["tests._conftest.billing"]
|
||||
from tests._conftest.billing_constants import (
|
||||
SEAT_PRICE_DEFAULT,
|
||||
TOKEN_COST_SAMPLE,
|
||||
SPAN_COST_SAMPLE,
|
||||
TOKEN_QUANTITY_SAMPLE,
|
||||
SPAN_QUANTITY_SAMPLE,
|
||||
)
|
||||
|
||||
|
||||
# Mock stripe at module level to prevent API key errors
|
||||
stripe.api_key = 'sk_test_mock'
|
||||
|
||||
|
||||
def extract_response_data(response):
|
||||
"""Helper function to extract data from JSONResponse wrapper."""
|
||||
if isinstance(response, JSONResponse):
|
||||
# Get the content from the JSONResponse
|
||||
import json
|
||||
|
||||
return json.loads(response.body.decode())
|
||||
return response
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def billing_dashboard_view(mock_request):
|
||||
"""Create a BillingDashboardView instance for testing."""
|
||||
return BillingDashboardView(mock_request)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_billing_period(orm_session, test_pro_org, billing_period_factory):
|
||||
"""Create a test billing period for testing."""
|
||||
billing_period = billing_period_factory(
|
||||
test_pro_org.id,
|
||||
seat_cost=8000, # $80 in cents (keeping for test consistency)
|
||||
seat_count=2,
|
||||
usage_costs={"tokens": TOKEN_COST_SAMPLE, "spans": SPAN_COST_SAMPLE},
|
||||
usage_quantities={"tokens": TOKEN_QUANTITY_SAMPLE, "spans": SPAN_QUANTITY_SAMPLE},
|
||||
total_cost=8200,
|
||||
status='pending',
|
||||
)
|
||||
orm_session.add(billing_period)
|
||||
orm_session.flush()
|
||||
return billing_period
|
||||
|
||||
|
||||
class TestBillingDashboardView:
|
||||
"""Test cases for BillingDashboardView class."""
|
||||
|
||||
async def test_billing_dashboard_success(
|
||||
self, billing_dashboard_view, orm_session, test_pro_org, test_user, test_billing_period
|
||||
):
|
||||
"""Test successful billing dashboard retrieval."""
|
||||
# Setup request
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
# Mock billing service
|
||||
with (
|
||||
patch.object(billing_service, 'get_usage_for_period') as mock_get_usage,
|
||||
patch.object(billing_service, 'calculate_usage_costs') as mock_calc_costs,
|
||||
patch.object(billing_service, 'get_seat_price') as mock_seat_price,
|
||||
):
|
||||
mock_get_usage.return_value = {"tokens": 500000, "spans": 100}
|
||||
mock_calc_costs.return_value = {"tokens": 10, "spans": 5}
|
||||
mock_seat_price.return_value = SEAT_PRICE_DEFAULT
|
||||
|
||||
response = await billing_dashboard_view(org_id=str(test_pro_org.id), period=None, orm=orm_session)
|
||||
|
||||
result = extract_response_data(response)
|
||||
assert isinstance(response, JSONResponse)
|
||||
assert result['current_period'] is not None
|
||||
# Past periods are no longer returned since we moved away from stored periods
|
||||
assert result['past_periods'] == []
|
||||
|
||||
async def test_billing_dashboard_org_not_found(self, billing_dashboard_view, orm_session, test_user):
|
||||
"""Test billing dashboard when organization doesn't exist."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
fake_org_id = str(uuid.uuid4())
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await billing_dashboard_view(org_id=fake_org_id, period=None, orm=orm_session)
|
||||
|
||||
assert exc_info.value.status_code == 403
|
||||
assert "Access denied" in str(exc_info.value.detail)
|
||||
|
||||
async def test_billing_dashboard_access_denied_not_member(
|
||||
self, billing_dashboard_view, orm_session, test_pro_org, test_user2
|
||||
):
|
||||
"""Test billing dashboard access denied when user is not a member."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user2.id
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await billing_dashboard_view(org_id=str(test_pro_org.id), period=None, orm=orm_session)
|
||||
|
||||
assert exc_info.value.status_code == 403
|
||||
assert "Access denied" in str(exc_info.value.detail)
|
||||
|
||||
async def test_billing_dashboard_with_specific_period(
|
||||
self, billing_dashboard_view, orm_session, test_pro_org, test_user, test_billing_period
|
||||
):
|
||||
"""Test billing dashboard with specific period requested."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
response = await billing_dashboard_view(
|
||||
org_id=str(test_pro_org.id), period=str(test_billing_period.id), orm=orm_session
|
||||
)
|
||||
|
||||
result = extract_response_data(response)
|
||||
assert result['current_period']['id'] == str(test_billing_period.id)
|
||||
assert result['current_period']['seat_cost'] == 8000
|
||||
assert result['current_period']['total_cost'] == 8200
|
||||
|
||||
async def test_billing_dashboard_period_not_found(
|
||||
self, billing_dashboard_view, orm_session, test_pro_org, test_user
|
||||
):
|
||||
"""Test billing dashboard when specific period doesn't exist."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
fake_period_id = str(uuid.uuid4())
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await billing_dashboard_view(org_id=str(test_pro_org.id), period=fake_period_id, orm=orm_session)
|
||||
|
||||
assert exc_info.value.status_code == 404
|
||||
assert "Billing period not found" in str(exc_info.value.detail)
|
||||
|
||||
async def test_billing_dashboard_with_current_usage(
|
||||
self, billing_dashboard_view, orm_session, test_pro_org, test_user
|
||||
):
|
||||
"""Test billing dashboard includes current period usage."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
with (
|
||||
patch.object(billing_service, 'get_usage_for_period') as mock_get_usage,
|
||||
patch.object(billing_service, 'calculate_usage_costs') as mock_calc_costs,
|
||||
patch.object(billing_service, 'get_seat_price') as mock_seat_price,
|
||||
):
|
||||
mock_get_usage.return_value = {"tokens": 1000000, "spans": 200}
|
||||
mock_calc_costs.return_value = {"tokens": 20, "spans": 20}
|
||||
mock_seat_price.return_value = 4000
|
||||
|
||||
response = await billing_dashboard_view(org_id=str(test_pro_org.id), period=None, orm=orm_session)
|
||||
|
||||
result = extract_response_data(response)
|
||||
assert result['current_period'] is not None
|
||||
assert result['current_period']['usage_quantities']['tokens'] == 1000000
|
||||
assert result['current_period']['usage_quantities']['spans'] == 200
|
||||
|
||||
async def test_billing_dashboard_with_no_usage(
|
||||
self, billing_dashboard_view, orm_session, test_pro_org, test_user
|
||||
):
|
||||
"""Test billing dashboard with no usage data."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
with (
|
||||
patch.object(billing_service, 'get_usage_for_period') as mock_get_usage,
|
||||
patch.object(billing_service, 'calculate_usage_costs') as mock_calc_costs,
|
||||
patch.object(billing_service, 'get_seat_price') as mock_seat_price,
|
||||
):
|
||||
mock_get_usage.return_value = {}
|
||||
mock_calc_costs.return_value = {}
|
||||
mock_seat_price.return_value = 4000
|
||||
|
||||
response = await billing_dashboard_view(org_id=str(test_pro_org.id), period=None, orm=orm_session)
|
||||
|
||||
result = extract_response_data(response)
|
||||
# With no usage and paid members, there should still be a current period
|
||||
assert result['current_period'] is not None
|
||||
assert result['current_period']['usage_quantities'] == {}
|
||||
|
||||
async def test_billing_dashboard_with_past_periods(
|
||||
self, billing_dashboard_view, orm_session, test_pro_org, test_user, billing_period_factory
|
||||
):
|
||||
"""Test billing dashboard includes historical billing periods."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
# Create multiple billing periods
|
||||
period1 = billing_period_factory(
|
||||
test_pro_org.id,
|
||||
total_cost=5000,
|
||||
status='paid',
|
||||
)
|
||||
|
||||
period2 = billing_period_factory(
|
||||
test_pro_org.id,
|
||||
total_cost=7500,
|
||||
status='paid',
|
||||
)
|
||||
|
||||
orm_session.add_all([period1, period2])
|
||||
orm_session.flush()
|
||||
|
||||
with (
|
||||
patch.object(billing_service, 'get_usage_for_period') as mock_get_usage,
|
||||
patch.object(billing_service, 'calculate_usage_costs') as mock_calc_costs,
|
||||
patch.object(billing_service, 'get_seat_price') as mock_seat_price,
|
||||
):
|
||||
mock_get_usage.return_value = {}
|
||||
mock_calc_costs.return_value = {}
|
||||
mock_seat_price.return_value = 4000
|
||||
|
||||
response = await billing_dashboard_view(org_id=str(test_pro_org.id), period=None, orm=orm_session)
|
||||
|
||||
result = extract_response_data(response)
|
||||
# Past periods are no longer returned since we moved away from stored periods
|
||||
assert result['past_periods'] == []
|
||||
|
||||
async def test_billing_dashboard_usage_breakdown_tokens(
|
||||
self, billing_dashboard_view, orm_session, test_pro_org, test_user, test_billing_period
|
||||
):
|
||||
"""Test billing dashboard shows token usage breakdown."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
response = await billing_dashboard_view(
|
||||
org_id=str(test_pro_org.id), period=str(test_billing_period.id), orm=orm_session
|
||||
)
|
||||
|
||||
result = extract_response_data(response)
|
||||
assert result['current_period']['usage_quantities']['tokens'] == 750000
|
||||
assert result['current_period']['usage_costs']['tokens'] == 150
|
||||
|
||||
async def test_billing_dashboard_usage_breakdown_spans(
|
||||
self, billing_dashboard_view, orm_session, test_pro_org, test_user, test_billing_period
|
||||
):
|
||||
"""Test billing dashboard shows span usage breakdown."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
response = await billing_dashboard_view(
|
||||
org_id=str(test_pro_org.id), period=str(test_billing_period.id), orm=orm_session
|
||||
)
|
||||
|
||||
result = extract_response_data(response)
|
||||
assert result['current_period']['usage_quantities']['spans'] == 50
|
||||
assert result['current_period']['usage_costs']['spans'] == 50
|
||||
|
||||
async def test_billing_dashboard_seat_cost_calculation(
|
||||
self, billing_dashboard_view, orm_session, test_pro_org, test_user, test_user2, test_user3
|
||||
):
|
||||
"""Test billing dashboard calculates seat costs correctly."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
# Add additional paid members
|
||||
user_org2 = UserOrgModel(
|
||||
user_id=test_user2.id,
|
||||
org_id=test_pro_org.id,
|
||||
role=OrgRoles.developer,
|
||||
user_email=test_user2.email,
|
||||
is_paid=True,
|
||||
)
|
||||
|
||||
user_org3 = UserOrgModel(
|
||||
user_id=test_user3.id,
|
||||
org_id=test_pro_org.id,
|
||||
role=OrgRoles.developer,
|
||||
user_email=test_user3.email,
|
||||
is_paid=True,
|
||||
)
|
||||
|
||||
orm_session.add_all([user_org2, user_org3])
|
||||
orm_session.flush()
|
||||
|
||||
with (
|
||||
patch.object(billing_service, 'get_usage_for_period') as mock_get_usage,
|
||||
patch.object(billing_service, 'calculate_usage_costs') as mock_calc_costs,
|
||||
patch.object(billing_service, 'get_seat_price') as mock_seat_price,
|
||||
):
|
||||
mock_get_usage.return_value = {}
|
||||
mock_calc_costs.return_value = {}
|
||||
mock_seat_price.return_value = 4000 # $40 per seat
|
||||
|
||||
response = await billing_dashboard_view(org_id=str(test_pro_org.id), period=None, orm=orm_session)
|
||||
|
||||
result = extract_response_data(response)
|
||||
# Should have 3 paid members (owner + 2 developers)
|
||||
assert result['current_period']['seat_count'] == 3
|
||||
|
||||
async def test_billing_dashboard_total_cost_calculation(
|
||||
self, billing_dashboard_view, orm_session, test_pro_org, test_user, test_billing_period
|
||||
):
|
||||
"""Test billing dashboard calculates total costs correctly."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
response = await billing_dashboard_view(
|
||||
org_id=str(test_pro_org.id), period=str(test_billing_period.id), orm=orm_session
|
||||
)
|
||||
|
||||
result = extract_response_data(response)
|
||||
# seat_cost (8000) + usage_costs (150 + 50) = 8200
|
||||
assert result['current_period']['total_cost'] == 8200
|
||||
|
||||
@patch('stripe.Subscription.retrieve')
|
||||
async def test_billing_dashboard_with_stripe_subscription(
|
||||
self,
|
||||
mock_stripe_retrieve,
|
||||
billing_dashboard_view,
|
||||
orm_session,
|
||||
test_pro_org,
|
||||
test_user,
|
||||
mock_stripe_subscription,
|
||||
):
|
||||
"""Test billing dashboard integrates with Stripe subscription data."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
mock_stripe_retrieve.return_value = mock_stripe_subscription
|
||||
|
||||
with (
|
||||
patch.object(billing_service, 'get_usage_for_period') as mock_get_usage,
|
||||
patch.object(billing_service, 'calculate_usage_costs') as mock_calc_costs,
|
||||
patch.object(billing_service, 'get_seat_price') as mock_seat_price,
|
||||
):
|
||||
mock_get_usage.return_value = {}
|
||||
mock_calc_costs.return_value = {}
|
||||
mock_seat_price.return_value = 4000
|
||||
|
||||
response = await billing_dashboard_view(org_id=str(test_pro_org.id), period=None, orm=orm_session)
|
||||
|
||||
# Should work without errors when Stripe integration is successful
|
||||
assert isinstance(response, JSONResponse)
|
||||
|
||||
@patch('stripe.Subscription.retrieve')
|
||||
async def test_billing_dashboard_stripe_error_handling(
|
||||
self, mock_stripe_retrieve, billing_dashboard_view, orm_session, test_pro_org, test_user
|
||||
):
|
||||
"""Test billing dashboard handles Stripe API errors gracefully."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
mock_stripe_retrieve.side_effect = stripe.error.StripeError("API Error")
|
||||
|
||||
with (
|
||||
patch.object(billing_service, 'get_usage_for_period') as mock_get_usage,
|
||||
patch.object(billing_service, 'calculate_usage_costs') as mock_calc_costs,
|
||||
patch.object(billing_service, 'get_seat_price') as mock_seat_price,
|
||||
):
|
||||
mock_get_usage.return_value = {}
|
||||
mock_calc_costs.return_value = {}
|
||||
mock_seat_price.return_value = 4000
|
||||
|
||||
response = await billing_dashboard_view(org_id=str(test_pro_org.id), period=None, orm=orm_session)
|
||||
|
||||
# Should still work but without Stripe data
|
||||
assert isinstance(response, JSONResponse)
|
||||
|
||||
async def test_billing_dashboard_legacy_billing_detection(
|
||||
self, billing_dashboard_view, orm_session, test_user
|
||||
):
|
||||
"""Test billing dashboard detects legacy billing plans."""
|
||||
# Create org without subscription (legacy)
|
||||
legacy_org = OrgModel(name="Legacy Org", prem_status=PremStatus.pro)
|
||||
orm_session.add(legacy_org)
|
||||
orm_session.flush()
|
||||
|
||||
user_org = UserOrgModel(
|
||||
user_id=test_user.id,
|
||||
org_id=legacy_org.id,
|
||||
role=OrgRoles.owner,
|
||||
user_email=test_user.email,
|
||||
is_paid=True,
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.flush()
|
||||
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
with (
|
||||
patch.object(billing_service, 'get_usage_for_period') as mock_get_usage,
|
||||
patch.object(billing_service, 'calculate_usage_costs') as mock_calc_costs,
|
||||
patch.object(billing_service, 'get_seat_price') as mock_seat_price,
|
||||
):
|
||||
mock_get_usage.return_value = {}
|
||||
mock_calc_costs.return_value = {}
|
||||
mock_seat_price.return_value = 4000
|
||||
|
||||
response = await billing_dashboard_view(org_id=str(legacy_org.id), period=None, orm=orm_session)
|
||||
|
||||
result = extract_response_data(response)
|
||||
assert result['is_legacy_billing'] is False # No subscription means not legacy
|
||||
|
||||
async def test_billing_dashboard_total_spent_calculation(
|
||||
self, billing_dashboard_view, orm_session, test_pro_org, test_user, billing_period_factory
|
||||
):
|
||||
"""Test billing dashboard calculates total spent across all periods."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
# Create multiple paid billing periods
|
||||
period1 = billing_period_factory(
|
||||
test_pro_org.id,
|
||||
total_cost=5000,
|
||||
status='paid',
|
||||
)
|
||||
|
||||
period2 = billing_period_factory(
|
||||
test_pro_org.id,
|
||||
total_cost=7500,
|
||||
status='paid',
|
||||
)
|
||||
|
||||
orm_session.add_all([period1, period2])
|
||||
orm_session.flush()
|
||||
|
||||
with (
|
||||
patch.object(billing_service, 'get_usage_for_period') as mock_get_usage,
|
||||
patch.object(billing_service, 'calculate_usage_costs') as mock_calc_costs,
|
||||
patch.object(billing_service, 'get_seat_price') as mock_seat_price,
|
||||
):
|
||||
mock_get_usage.return_value = {}
|
||||
mock_calc_costs.return_value = {}
|
||||
mock_seat_price.return_value = 4000
|
||||
|
||||
response = await billing_dashboard_view(org_id=str(test_pro_org.id), period=None, orm=orm_session)
|
||||
|
||||
result = extract_response_data(response)
|
||||
# Since we moved away from stored periods, total_spent_all_time now only includes current period
|
||||
# Current period: seat cost (4000) + usage costs (0) = 4000
|
||||
assert result['total_spent_all_time'] == 4000
|
||||
|
||||
async def test_billing_dashboard_period_status_values(
|
||||
self, billing_dashboard_view, orm_session, test_pro_org, test_user, billing_period_factory
|
||||
):
|
||||
"""Test billing dashboard shows correct period status values."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
period = billing_period_factory(
|
||||
test_pro_org.id,
|
||||
total_cost=4000,
|
||||
status='invoiced',
|
||||
)
|
||||
orm_session.add(period)
|
||||
orm_session.flush()
|
||||
|
||||
response = await billing_dashboard_view(
|
||||
org_id=str(test_pro_org.id), period=str(period.id), orm=orm_session
|
||||
)
|
||||
|
||||
result = extract_response_data(response)
|
||||
assert result['current_period']['status'] == 'invoiced'
|
||||
|
||||
async def test_billing_dashboard_datetime_formatting(
|
||||
self, billing_dashboard_view, orm_session, test_pro_org, test_user, test_billing_period
|
||||
):
|
||||
"""Test billing dashboard formats datetime fields correctly."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
response = await billing_dashboard_view(
|
||||
org_id=str(test_pro_org.id), period=str(test_billing_period.id), orm=orm_session
|
||||
)
|
||||
|
||||
result = extract_response_data(response)
|
||||
assert result['current_period']['period_start'] is not None
|
||||
assert result['current_period']['period_end'] is not None
|
||||
# Should be ISO string format due to field_validator
|
||||
assert isinstance(result['current_period']['period_start'], str)
|
||||
assert isinstance(result['current_period']['period_end'], str)
|
||||
|
||||
async def test_billing_dashboard_empty_usage_costs(
|
||||
self, billing_dashboard_view, orm_session, test_pro_org, test_user, billing_period_factory
|
||||
):
|
||||
"""Test billing dashboard handles empty usage costs correctly."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
period = billing_period_factory(
|
||||
test_pro_org.id,
|
||||
seat_cost=4000,
|
||||
usage_costs={},
|
||||
usage_quantities={},
|
||||
total_cost=4000,
|
||||
)
|
||||
orm_session.add(period)
|
||||
orm_session.flush()
|
||||
|
||||
response = await billing_dashboard_view(
|
||||
org_id=str(test_pro_org.id), period=str(period.id), orm=orm_session
|
||||
)
|
||||
|
||||
result = extract_response_data(response)
|
||||
assert result['current_period']['usage_costs'] == {}
|
||||
assert result['current_period']['usage_quantities'] == {}
|
||||
assert result['current_period']['total_cost'] == 4000
|
||||
|
||||
async def test_billing_dashboard_exception_handling(
|
||||
self, billing_dashboard_view, orm_session, test_pro_org, test_user
|
||||
):
|
||||
"""Test billing dashboard handles service exceptions gracefully."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
with (
|
||||
patch.object(billing_service, 'get_usage_for_period') as mock_get_usage,
|
||||
patch.object(billing_service, 'calculate_usage_costs') as mock_calc_costs,
|
||||
patch.object(billing_service, 'get_seat_price') as mock_seat_price,
|
||||
):
|
||||
# Mock service to raise exception
|
||||
mock_get_usage.side_effect = Exception("Service error")
|
||||
mock_calc_costs.return_value = {}
|
||||
mock_seat_price.return_value = 4000
|
||||
|
||||
# The actual implementation doesn't catch this exception properly,
|
||||
# so it will propagate up. Let's test that it raises the exception.
|
||||
with pytest.raises(Exception) as exc_info:
|
||||
await billing_dashboard_view(org_id=str(test_pro_org.id), period=None, orm=orm_session)
|
||||
|
||||
assert "Service error" in str(exc_info.value)
|
||||
|
||||
@patch('agentops.opsboard.services.billing_service.billing_service.get_usage_for_period')
|
||||
async def test_billing_dashboard_usage_service_integration(
|
||||
self, mock_get_usage, billing_dashboard_view, orm_session, test_pro_org, test_user
|
||||
):
|
||||
"""Test billing dashboard integrates with usage service correctly."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
mock_get_usage.return_value = {"tokens": 2000000, "spans": 150}
|
||||
|
||||
with (
|
||||
patch.object(billing_service, 'calculate_usage_costs') as mock_calc_costs,
|
||||
patch.object(billing_service, 'get_seat_price') as mock_seat_price,
|
||||
):
|
||||
mock_calc_costs.return_value = {"tokens": 40, "spans": 15}
|
||||
mock_seat_price.return_value = 4000
|
||||
|
||||
response = await billing_dashboard_view(org_id=str(test_pro_org.id), period=None, orm=orm_session)
|
||||
|
||||
result = extract_response_data(response)
|
||||
# Verify service was called
|
||||
mock_get_usage.assert_called()
|
||||
assert result['current_period']['usage_quantities']['tokens'] == 2000000
|
||||
assert result['current_period']['usage_quantities']['spans'] == 150
|
||||
|
||||
@patch('agentops.opsboard.services.billing_service.billing_service.calculate_usage_costs')
|
||||
async def test_billing_dashboard_cost_calculation_integration(
|
||||
self, mock_calculate_costs, billing_dashboard_view, orm_session, test_pro_org, test_user
|
||||
):
|
||||
"""Test billing dashboard integrates with cost calculation service."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = test_user.id
|
||||
|
||||
mock_calculate_costs.return_value = {"tokens": 25, "spans": 30}
|
||||
|
||||
with (
|
||||
patch.object(billing_service, 'get_usage_for_period') as mock_get_usage,
|
||||
patch.object(billing_service, 'get_seat_price') as mock_seat_price,
|
||||
):
|
||||
mock_get_usage.return_value = {"tokens": 1250000, "spans": 300}
|
||||
mock_seat_price.return_value = 4000
|
||||
|
||||
response = await billing_dashboard_view(org_id=str(test_pro_org.id), period=None, orm=orm_session)
|
||||
|
||||
# Verify service was called
|
||||
mock_calculate_costs.assert_called()
|
||||
assert isinstance(response, JSONResponse)
|
||||
|
||||
async def test_billing_dashboard_user_not_authenticated(
|
||||
self, billing_dashboard_view, orm_session, test_pro_org
|
||||
):
|
||||
"""Test billing dashboard when user is not authenticated."""
|
||||
billing_dashboard_view.request.state.session = MagicMock()
|
||||
billing_dashboard_view.request.state.session.user_id = None
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await billing_dashboard_view(org_id=str(test_pro_org.id), period=None, orm=orm_session)
|
||||
|
||||
assert exc_info.value.status_code == 403
|
||||
assert "Access denied" in str(exc_info.value.detail)
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,184 @@
|
||||
import pytest
|
||||
import uuid
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy import orm
|
||||
|
||||
from agentops.opsboard.models import (
|
||||
OrgModel,
|
||||
UserOrgModel,
|
||||
OrgInviteModel,
|
||||
OrgRoles,
|
||||
PremStatus,
|
||||
UserModel,
|
||||
)
|
||||
from agentops.opsboard.views.orgs import (
|
||||
create_org,
|
||||
invite_to_org,
|
||||
remove_from_org,
|
||||
change_member_role,
|
||||
)
|
||||
from agentops.opsboard.schemas import (
|
||||
OrgCreateSchema,
|
||||
OrgInviteSchema,
|
||||
OrgMemberRemoveSchema,
|
||||
OrgMemberRoleSchema,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_org_user_not_found(mock_request, orm_session, monkeypatch):
|
||||
"""Test creating an organization when the user doesn't exist."""
|
||||
# Mock orm.get to return None for UserModel (user not found)
|
||||
original_get_by_id = UserModel.get_by_id
|
||||
|
||||
def mock_get_by_id(session, id):
|
||||
return None
|
||||
|
||||
# Apply the monkeypatch
|
||||
monkeypatch.setattr(UserModel, "get_by_id", mock_get_by_id)
|
||||
|
||||
# Create the request body
|
||||
body = OrgCreateSchema(name="New Test Organization")
|
||||
|
||||
# Expect an HTTP 500 exception
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
create_org(request=mock_request, orm=orm_session, body=body)
|
||||
|
||||
assert excinfo.value.status_code == 500
|
||||
assert excinfo.value.detail == "User not found"
|
||||
|
||||
# Restore the original method
|
||||
monkeypatch.setattr(UserModel, "get_by_id", original_get_by_id)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_invite_to_org_existing_invite(mock_request, orm_session, test_user):
|
||||
"""Test inviting a user when there's an existing invite for the same email."""
|
||||
# Create a fresh organization for this test
|
||||
org = OrgModel(
|
||||
name="Test Org for Existing Invite",
|
||||
prem_status=PremStatus.enterprise, # Use enterprise to avoid the member limit
|
||||
)
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a user-org relationship
|
||||
user_id = mock_request.state.session.user_id
|
||||
user_org = UserOrgModel(
|
||||
user_id=user_id, org_id=org.id, role=OrgRoles.owner, user_email="test@example.com"
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.commit() # Commit to ensure it's persisted
|
||||
|
||||
# First create an invitation
|
||||
invite_email = "newuser@example.com"
|
||||
invite = OrgInviteModel(
|
||||
inviter_id=user_id,
|
||||
invitee_email=invite_email,
|
||||
org_id=org.id,
|
||||
role=OrgRoles.developer,
|
||||
org_name=org.name,
|
||||
)
|
||||
orm_session.add(invite)
|
||||
orm_session.commit()
|
||||
|
||||
# Fetch org again with relationships to ensure we have the latest
|
||||
org = (
|
||||
orm_session.query(OrgModel)
|
||||
.options(orm.selectinload(OrgModel.users), orm.selectinload(OrgModel.invites))
|
||||
.filter_by(id=org.id)
|
||||
.one()
|
||||
)
|
||||
|
||||
# Try to create another invite with the same email
|
||||
body = OrgInviteSchema(email=invite_email, role=OrgRoles.admin.value)
|
||||
|
||||
# Expect an HTTP 400 exception
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
invite_to_org(request=mock_request, org_id=str(org.id), orm=orm_session, body=body)
|
||||
|
||||
assert excinfo.value.status_code == 400
|
||||
assert excinfo.value.detail == "User already has a pending invitation"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_remove_from_org_user_not_found(mock_request, orm_session, test_user):
|
||||
"""Test removing a user who isn't part of the organization."""
|
||||
# Create a fresh organization for this test
|
||||
org = OrgModel(
|
||||
name="Test Org for Remove Non-Member",
|
||||
prem_status=PremStatus.free,
|
||||
)
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Add the primary test user as an owner
|
||||
user_id = mock_request.state.session.user_id
|
||||
user_org = UserOrgModel(
|
||||
user_id=user_id, org_id=org.id, role=OrgRoles.owner, user_email="test@example.com"
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.commit() # Commit to ensure both relationships are persisted
|
||||
|
||||
# Create the remove body using a non-existent user ID
|
||||
non_member_id = str(uuid.uuid4())
|
||||
body = OrgMemberRemoveSchema(user_id=non_member_id)
|
||||
|
||||
# Expect an HTTP 400 exception
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
remove_from_org(request=mock_request, org_id=str(org.id), orm=orm_session, body=body)
|
||||
|
||||
assert excinfo.value.status_code == 400
|
||||
assert excinfo.value.detail == "User cannot be removed"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_change_member_role_non_owner_promotes_to_owner(
|
||||
mock_request, orm_session, test_user, test_user2, test_user3
|
||||
):
|
||||
"""Test when a non-owner tries to promote someone to owner."""
|
||||
# Create a fresh organization for this test
|
||||
org = OrgModel(
|
||||
name="Test Org for Non-Owner Promotion",
|
||||
prem_status=PremStatus.free,
|
||||
)
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Add test_user2 as the owner
|
||||
owner_org = UserOrgModel(
|
||||
user_id=test_user2.id,
|
||||
org_id=org.id,
|
||||
role=OrgRoles.owner,
|
||||
user_email=test_user2.email,
|
||||
)
|
||||
orm_session.add(owner_org)
|
||||
|
||||
# Add the primary test user as an admin (not owner)
|
||||
user_id = mock_request.state.session.user_id
|
||||
user_org = UserOrgModel(
|
||||
user_id=user_id, org_id=org.id, role=OrgRoles.admin, user_email="test@example.com"
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
|
||||
# Add test_user3 as a developer
|
||||
dev_org = UserOrgModel(
|
||||
user_id=test_user3.id, org_id=org.id, role=OrgRoles.developer, user_email=test_user3.email
|
||||
)
|
||||
orm_session.add(dev_org)
|
||||
orm_session.commit() # Commit to ensure all relationships are persisted
|
||||
|
||||
# Attempt to promote the developer to owner by the admin (not owner)
|
||||
body = OrgMemberRoleSchema(user_id=str(test_user3.id), role=OrgRoles.owner.value)
|
||||
|
||||
# Expect an HTTP 400 exception
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
change_member_role(request=mock_request, org_id=str(org.id), orm=orm_session, body=body)
|
||||
|
||||
assert excinfo.value.status_code == 400
|
||||
assert excinfo.value.detail == "Only owners can assign the owner role"
|
||||
|
||||
# Verify the role wasn't changed
|
||||
orm_session.expire_all() # Clear cached objects
|
||||
user_org = orm_session.query(UserOrgModel).filter_by(user_id=test_user3.id, org_id=org.id).one()
|
||||
assert user_org.role == OrgRoles.developer, "The user role should not have been changed"
|
||||
@@ -0,0 +1,155 @@
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
|
||||
from agentops.opsboard.models import (
|
||||
OrgModel,
|
||||
UserOrgModel,
|
||||
OrgInviteModel,
|
||||
ProjectModel,
|
||||
OrgRoles,
|
||||
Environment,
|
||||
PremStatus,
|
||||
)
|
||||
from agentops.opsboard.views.orgs import (
|
||||
delete_org,
|
||||
accept_org_invite,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_org(mock_request, orm_session, test_user):
|
||||
"""Test deleting an organization."""
|
||||
# Create a fresh organization for this test
|
||||
org = OrgModel(
|
||||
name="Test Org for Deletion",
|
||||
prem_status=PremStatus.free,
|
||||
)
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a user-org relationship
|
||||
user_id = mock_request.state.session.user_id
|
||||
user_org = UserOrgModel(
|
||||
user_id=user_id, org_id=org.id, role=OrgRoles.owner, user_email="test@example.com"
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.commit() # Commit to ensure it's persisted
|
||||
|
||||
# Call the endpoint function
|
||||
result = delete_org(request=mock_request, org_id=str(org.id), orm=orm_session)
|
||||
|
||||
# Verify the status response
|
||||
assert result.success is True
|
||||
assert result.message == "Organization deleted"
|
||||
|
||||
# Verify the organization was deleted
|
||||
deleted_org = orm_session.query(OrgModel).filter_by(id=org.id).first()
|
||||
assert deleted_org is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_org_not_owner(mock_request, orm_session, test_user):
|
||||
"""Test deleting an organization without owner permissions."""
|
||||
# Create a fresh organization for this test
|
||||
org = OrgModel(
|
||||
name="Test Org for Non-Owner Deletion",
|
||||
prem_status=PremStatus.free,
|
||||
)
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a user-org relationship with admin role (not owner)
|
||||
user_id = mock_request.state.session.user_id
|
||||
user_org = UserOrgModel(
|
||||
user_id=user_id, org_id=org.id, role=OrgRoles.admin, user_email="test@example.com"
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.commit() # Commit to ensure it's persisted
|
||||
|
||||
# Expect a 403 exception
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
delete_org(request=mock_request, org_id=str(org.id), orm=orm_session)
|
||||
|
||||
assert excinfo.value.status_code == 403
|
||||
assert excinfo.value.detail == "Organization cannot be deleted"
|
||||
|
||||
# Verify the organization still exists
|
||||
org_still_exists = orm_session.query(OrgModel).filter_by(id=org.id).first()
|
||||
assert org_still_exists is not None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_org_with_projects(mock_request, orm_session, test_user):
|
||||
"""Test deleting an organization that still has projects (should fail)."""
|
||||
# Create a fresh organization for this test
|
||||
org = OrgModel(
|
||||
name="Test Org with Projects",
|
||||
prem_status=PremStatus.free,
|
||||
)
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a user-org relationship
|
||||
user_id = mock_request.state.session.user_id
|
||||
user_org = UserOrgModel(
|
||||
user_id=user_id, org_id=org.id, role=OrgRoles.owner, user_email="test@example.com"
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a project in the organization
|
||||
project = ProjectModel(name="Test Project", org_id=org.id, environment=Environment.development)
|
||||
orm_session.add(project)
|
||||
orm_session.commit() # Commit to ensure it's persisted
|
||||
|
||||
# Reload the org with all relationships
|
||||
org = OrgModel.get_by_id(orm_session, org.id)
|
||||
|
||||
# Expect a 400 exception
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
delete_org(request=mock_request, org_id=str(org.id), orm=orm_session)
|
||||
|
||||
assert excinfo.value.status_code == 400
|
||||
assert excinfo.value.detail == "Organization cannot be deleted while it still contains projects"
|
||||
|
||||
# Verify the organization still exists
|
||||
org_still_exists = orm_session.query(OrgModel).filter_by(id=org.id).first()
|
||||
assert org_still_exists is not None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_accept_org_invite_user_not_found(mock_request, orm_session, test_user, monkeypatch):
|
||||
"""Test accepting an invitation when the user doesn't exist."""
|
||||
# Create a fresh organization for this test
|
||||
org = OrgModel(
|
||||
name="Test Org for Invite",
|
||||
prem_status=PremStatus.free,
|
||||
)
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
invite = OrgInviteModel(
|
||||
inviter_id=test_user.id, # Use existing test user as inviter
|
||||
invitee_email="test@example.com",
|
||||
org_id=org.id,
|
||||
role=OrgRoles.developer,
|
||||
org_name=org.name,
|
||||
)
|
||||
orm_session.add(invite)
|
||||
orm_session.commit() # Ensure it's persisted
|
||||
|
||||
# Mock UserModel.get_by_id to return None
|
||||
from agentops.opsboard.models import UserModel
|
||||
|
||||
def mock_get_by_id(session, user_id):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr(UserModel, "get_by_id", mock_get_by_id)
|
||||
|
||||
# Since auth user exists in test data but UserModel.get_by_id returns None,
|
||||
# the function will try to wait for user creation and then return 500
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
accept_org_invite(request=mock_request, org_id=str(org.id), orm=orm_session)
|
||||
|
||||
assert excinfo.value.status_code == 500
|
||||
assert "User record not yet created" in excinfo.value.detail
|
||||
@@ -0,0 +1,442 @@
|
||||
import pytest
|
||||
import uuid
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy import orm
|
||||
|
||||
from agentops.opsboard.models import (
|
||||
OrgModel,
|
||||
UserOrgModel,
|
||||
ProjectModel,
|
||||
OrgRoles,
|
||||
Environment,
|
||||
PremStatus,
|
||||
)
|
||||
from agentops.opsboard.views.projects import (
|
||||
get_projects,
|
||||
get_project,
|
||||
create_project,
|
||||
update_project,
|
||||
delete_project,
|
||||
regenerate_api_key,
|
||||
)
|
||||
from agentops.opsboard.schemas import (
|
||||
ProjectCreateSchema,
|
||||
ProjectUpdateSchema,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_projects(mock_request, orm_session, test_user):
|
||||
"""Test getting all projects for a user."""
|
||||
# Create an org first
|
||||
org = OrgModel(name="Test Org for Projects")
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a user-org relationship with the test user fixture
|
||||
user_org = UserOrgModel(
|
||||
user_id=test_user.id, org_id=org.id, role=OrgRoles.owner, user_email=test_user.email
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
|
||||
# Create a project
|
||||
project = ProjectModel(name="Test Project", org_id=org.id, environment=Environment.development)
|
||||
orm_session.add(project)
|
||||
orm_session.flush()
|
||||
|
||||
# Call the endpoint function
|
||||
result = await get_projects(request=mock_request, orm=orm_session)
|
||||
|
||||
# Verify that it returns a list and the test project is in the results
|
||||
assert isinstance(result, list)
|
||||
assert len(result) > 0
|
||||
|
||||
# Check that our test project is in the results
|
||||
project_ids = [p.id for p in result]
|
||||
assert str(project.id) in project_ids
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_project(mock_request, orm_session, test_project):
|
||||
"""Test getting a specific project by ID."""
|
||||
# Call the endpoint function
|
||||
result = get_project(request=mock_request, project_id=str(test_project.id), orm=orm_session)
|
||||
|
||||
# Verify the project data matches
|
||||
assert result.id == str(test_project.id)
|
||||
assert result.name == test_project.name
|
||||
assert result.environment == test_project.environment.value
|
||||
assert result.api_key == str(test_project.api_key)
|
||||
assert result.org_id == str(test_project.org_id)
|
||||
assert result.org.id == str(test_project.org.id)
|
||||
assert result.org.name == test_project.org.name
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_project_not_found(mock_request, orm_session):
|
||||
"""Test getting a project that doesn't exist."""
|
||||
non_existent_id = str(uuid.uuid4())
|
||||
|
||||
# Expect an HTTP 404 exception
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
get_project(request=mock_request, project_id=non_existent_id, orm=orm_session)
|
||||
|
||||
assert excinfo.value.status_code == 404
|
||||
assert excinfo.value.detail == "Project not found"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_project(mock_request, orm_session, test_user):
|
||||
"""Test creating a new project."""
|
||||
# Create a fresh org and user-org relationship
|
||||
org = OrgModel(name="Test Org for Create")
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Add the test user as an owner of the org
|
||||
user_id = mock_request.state.session.user_id
|
||||
user_org = UserOrgModel(
|
||||
user_id=user_id, org_id=org.id, role=OrgRoles.owner, user_email="test@example.com"
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create the request body
|
||||
body = ProjectCreateSchema(
|
||||
name="New Test Project", org_id=str(org.id), environment=Environment.staging.value
|
||||
)
|
||||
|
||||
# Call the endpoint function
|
||||
result = create_project(request=mock_request, orm=orm_session, body=body)
|
||||
|
||||
# Verify the project was created with the right data
|
||||
assert result.name == body.name
|
||||
assert result.org_id == body.org_id
|
||||
assert result.environment == body.environment
|
||||
assert result.api_key is not None
|
||||
|
||||
# Verify we can find it in the database
|
||||
created_project = orm_session.query(ProjectModel).filter_by(id=uuid.UUID(result.id)).one()
|
||||
assert created_project.name == body.name
|
||||
assert created_project.environment == Environment.staging
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_project_not_admin(mock_request, orm_session, test_user):
|
||||
"""Test creating a project without admin permissions."""
|
||||
# Create an org directly in this test
|
||||
org = OrgModel(name="Test Org for Non-Admin Test")
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a user-org relationship with developer role (not admin or owner)
|
||||
user_org = UserOrgModel(
|
||||
user_id=test_user.id, org_id=org.id, role=OrgRoles.developer, user_email=test_user.email
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create the request body
|
||||
body = ProjectCreateSchema(
|
||||
name="New Test Project", org_id=str(org.id), environment=Environment.staging.value
|
||||
)
|
||||
|
||||
# Expect an HTTP 404 exception (security through obscurity - not found instead of forbidden)
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
create_project(request=mock_request, orm=orm_session, body=body)
|
||||
|
||||
assert excinfo.value.status_code == 404
|
||||
assert excinfo.value.detail == "Organization not found"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_project(mock_request, orm_session, test_project):
|
||||
"""Test updating a project's name and environment."""
|
||||
|
||||
# Create the update body
|
||||
body = ProjectUpdateSchema(name="Updated Project Name", environment=Environment.production.value)
|
||||
|
||||
# Execute the update
|
||||
result = update_project(request=mock_request, project_id=str(test_project.id), orm=orm_session, body=body)
|
||||
|
||||
# Verify the updates were applied
|
||||
assert result.name == body.name
|
||||
assert result.environment == body.environment
|
||||
|
||||
# Refresh the session to get the latest data
|
||||
orm_session.expire_all()
|
||||
|
||||
# Verify the database was updated
|
||||
updated_project = orm_session.query(ProjectModel).filter_by(id=test_project.id).one()
|
||||
assert updated_project.name == body.name
|
||||
assert updated_project.environment == Environment.production
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_project_not_admin(mock_request, orm_session, test_project):
|
||||
"""Test updating a project without admin permissions."""
|
||||
# Get the current test project and its organization
|
||||
project_id = test_project.id
|
||||
org_id = test_project.org_id
|
||||
|
||||
# Change the user's role to developer (not admin or owner)
|
||||
user_id = mock_request.state.session.user_id
|
||||
user_org = test_project.org.get_user_membership(str(user_id))
|
||||
|
||||
if user_org:
|
||||
# Change the existing role to developer
|
||||
user_org.role = OrgRoles.developer
|
||||
else:
|
||||
# Create a new membership with developer role
|
||||
user_org = UserOrgModel(
|
||||
user_id=user_id, org_id=org_id, role=OrgRoles.developer, user_email="test@example.com"
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
|
||||
# Commit the changes
|
||||
orm_session.commit()
|
||||
|
||||
# Create the update body
|
||||
body = ProjectUpdateSchema(name="Updated Project Name", environment=Environment.production.value)
|
||||
|
||||
# Expect an HTTP 403 exception
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
update_project(request=mock_request, project_id=str(project_id), orm=orm_session, body=body)
|
||||
|
||||
assert excinfo.value.status_code == 403
|
||||
assert excinfo.value.detail == "You don't have permission to update this project"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_project_invalid_environment(mock_request, orm_session, test_project):
|
||||
"""Test updating a project with an invalid environment."""
|
||||
# Create the update body with an invalid environment
|
||||
body = ProjectUpdateSchema(name="Updated Project Name", environment="invalid_environment")
|
||||
|
||||
# Expect an HTTP 400 exception
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
update_project(request=mock_request, project_id=str(test_project.id), orm=orm_session, body=body)
|
||||
|
||||
assert excinfo.value.status_code == 400
|
||||
assert excinfo.value.detail == "Invalid environment"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_project(mock_request, orm_session, test_user):
|
||||
"""Test deleting a project."""
|
||||
# Create all the test data in this test
|
||||
org = OrgModel(name="Test Org for Delete")
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a user-org relationship with test_user fixture
|
||||
user_org = UserOrgModel(
|
||||
user_id=test_user.id, org_id=org.id, role=OrgRoles.owner, user_email=test_user.email
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a project
|
||||
project = ProjectModel(name="Project to Delete", org_id=org.id, environment=Environment.development)
|
||||
orm_session.add(project)
|
||||
orm_session.flush()
|
||||
|
||||
# Load relationships to ensure they're available
|
||||
project = (
|
||||
orm_session.query(ProjectModel)
|
||||
.options(orm.joinedload(ProjectModel.org).joinedload(OrgModel.users))
|
||||
.filter_by(id=project.id)
|
||||
.one()
|
||||
)
|
||||
|
||||
# Call the endpoint function directly with the session
|
||||
result = delete_project(request=mock_request, project_id=str(project.id), orm=orm_session)
|
||||
|
||||
# Verify the status response
|
||||
assert result.success is True
|
||||
assert result.message == "Project deleted successfully"
|
||||
|
||||
projects = orm_session.query(ProjectModel).filter_by(id=project.id).all()
|
||||
assert len(projects) == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_delete_project_not_owner(mock_request, orm_session, test_user):
|
||||
"""Test deleting a project without owner permissions."""
|
||||
# Create all the test data in this test
|
||||
org = OrgModel(name="Test Org for Non-Owner Delete")
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a user-org relationship with admin role (not owner) using test_user
|
||||
user_org = UserOrgModel(
|
||||
user_id=test_user.id,
|
||||
org_id=org.id,
|
||||
role=OrgRoles.admin, # Admin role, not owner
|
||||
user_email=test_user.email,
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a project
|
||||
project = ProjectModel(
|
||||
name="Project for Non-Owner Delete Test", org_id=org.id, environment=Environment.development
|
||||
)
|
||||
orm_session.add(project)
|
||||
orm_session.flush()
|
||||
|
||||
# Load relationships to ensure they're available
|
||||
project = (
|
||||
orm_session.query(ProjectModel)
|
||||
.options(orm.joinedload(ProjectModel.org).joinedload(OrgModel.users))
|
||||
.filter_by(id=project.id)
|
||||
.one()
|
||||
)
|
||||
|
||||
# Expect an HTTP 403 exception
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
delete_project(request=mock_request, project_id=str(project.id), orm=orm_session)
|
||||
|
||||
assert excinfo.value.status_code == 403
|
||||
assert excinfo.value.detail == "Only organization owners can delete projects"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_project_limit(mock_request, orm_session, test_user):
|
||||
"""Test creating a project when the organization has reached its project limit."""
|
||||
# Create a fresh organization with free plan (which has a project limit of 1)
|
||||
org = OrgModel(
|
||||
name="Test Org with Project Limit",
|
||||
prem_status=PremStatus.free, # Free plan has a project limit of 1
|
||||
)
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a user-org relationship
|
||||
user_id = mock_request.state.session.user_id
|
||||
user_org = UserOrgModel(
|
||||
user_id=user_id, org_id=org.id, role=OrgRoles.owner, user_email="test@example.com"
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a project (which takes up the only allowed project slot)
|
||||
project = ProjectModel(name="First Project", org_id=org.id, environment=Environment.development)
|
||||
orm_session.add(project)
|
||||
orm_session.commit() # Commit to ensure it's persisted
|
||||
|
||||
# Reload the org with all relationships
|
||||
org = OrgModel.get_by_id(orm_session, org.id)
|
||||
|
||||
# Create the request body for a second project (which should exceed the limit)
|
||||
body = ProjectCreateSchema(
|
||||
name="Second Project", org_id=str(org.id), environment=Environment.development.value
|
||||
)
|
||||
|
||||
# Expect an HTTP 403 exception due to project limit
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
create_project(request=mock_request, orm=orm_session, body=body)
|
||||
|
||||
assert excinfo.value.status_code == 403
|
||||
assert excinfo.value.detail == "Organization has reached it's project limit"
|
||||
|
||||
# Verify no second project was created
|
||||
projects = orm_session.query(ProjectModel).filter_by(org_id=org.id).all()
|
||||
assert len(projects) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_project_after_upgrade(mock_request, orm_session, test_user):
|
||||
"""Test creating projects after upgrading from free to enterprise plan."""
|
||||
# Create a fresh organization with free plan (which has a project limit of 1)
|
||||
org = OrgModel(
|
||||
name="Test Org for Plan Upgrade",
|
||||
prem_status=PremStatus.free, # Free plan has a project limit of 1
|
||||
)
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a user-org relationship
|
||||
user_id = mock_request.state.session.user_id
|
||||
user_org = UserOrgModel(
|
||||
user_id=user_id, org_id=org.id, role=OrgRoles.owner, user_email="test@example.com"
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a project (using up the only allowed slot in the free plan)
|
||||
project = ProjectModel(name="First Project", org_id=org.id, environment=Environment.development)
|
||||
orm_session.add(project)
|
||||
orm_session.commit()
|
||||
|
||||
# Upgrade the organization plan to enterprise (which has no project limit)
|
||||
org.prem_status = PremStatus.enterprise
|
||||
orm_session.commit()
|
||||
|
||||
# Reload the org with all relationships
|
||||
org = OrgModel.get_by_id(orm_session, org.id)
|
||||
|
||||
# Create the request body for a second project (which should now work)
|
||||
body = ProjectCreateSchema(
|
||||
name="Second Project", org_id=str(org.id), environment=Environment.development.value
|
||||
)
|
||||
|
||||
# This should now succeed with the enterprise plan
|
||||
result = create_project(request=mock_request, orm=orm_session, body=body)
|
||||
|
||||
# Verify the project was created with the right data
|
||||
assert result.name == body.name
|
||||
assert result.org_id == body.org_id
|
||||
assert result.api_key is not None
|
||||
|
||||
# Verify we now have two projects in the database
|
||||
projects = orm_session.query(ProjectModel).filter_by(org_id=org.id).all()
|
||||
assert len(projects) == 2
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_regenerate_api_key(mock_request, orm_session, test_user):
|
||||
"""Test regenerating a project's API key."""
|
||||
# Create all the test data in this test
|
||||
org = OrgModel(name="Test Org for Regenerate Key")
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a user-org relationship with owner role using test_user
|
||||
user_org = UserOrgModel(
|
||||
user_id=test_user.id, org_id=org.id, role=OrgRoles.owner, user_email=test_user.email
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a project with a specific API key
|
||||
initial_api_key = uuid.uuid4()
|
||||
project = ProjectModel(
|
||||
name="Project for Key Regeneration",
|
||||
org_id=org.id,
|
||||
environment=Environment.development,
|
||||
api_key=initial_api_key,
|
||||
)
|
||||
orm_session.add(project)
|
||||
orm_session.flush()
|
||||
|
||||
# Load relationships to ensure they're available
|
||||
project = (
|
||||
orm_session.query(ProjectModel)
|
||||
.options(orm.joinedload(ProjectModel.org).joinedload(OrgModel.users))
|
||||
.filter_by(id=project.id)
|
||||
.one()
|
||||
)
|
||||
|
||||
# Save the original API key
|
||||
original_api_key = project.api_key
|
||||
|
||||
# Call the endpoint function
|
||||
result = regenerate_api_key(request=mock_request, project_id=str(project.id), orm=orm_session)
|
||||
|
||||
# Verify the response contains a new API key
|
||||
assert result.api_key != str(original_api_key)
|
||||
|
||||
# Verify the database was updated
|
||||
updated_project = orm_session.query(ProjectModel).filter_by(id=project.id).one()
|
||||
assert str(updated_project.api_key) != str(original_api_key)
|
||||
@@ -0,0 +1,181 @@
|
||||
import pytest
|
||||
import uuid
|
||||
from fastapi import HTTPException
|
||||
from unittest.mock import patch
|
||||
|
||||
from agentops.opsboard.models import (
|
||||
OrgModel,
|
||||
UserOrgModel,
|
||||
ProjectModel,
|
||||
OrgRoles,
|
||||
Environment,
|
||||
)
|
||||
from agentops.opsboard.views.projects import (
|
||||
get_projects,
|
||||
get_project,
|
||||
create_project,
|
||||
update_project,
|
||||
)
|
||||
from agentops.opsboard.schemas import (
|
||||
ProjectCreateSchema,
|
||||
ProjectUpdateSchema,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_projects_with_missing_count(mock_request, orm_session, test_user):
|
||||
"""Test getting projects when a project has no trace/span count data."""
|
||||
# Create an org first
|
||||
org = OrgModel(name="Test Org for Missing Counts")
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a user-org relationship with the test user fixture
|
||||
user_org = UserOrgModel(
|
||||
user_id=test_user.id, org_id=org.id, role=OrgRoles.owner, user_email=test_user.email
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
|
||||
# Create a project
|
||||
project = ProjectModel(
|
||||
name="Test Project Without Counts", org_id=org.id, environment=Environment.development
|
||||
)
|
||||
orm_session.add(project)
|
||||
orm_session.flush()
|
||||
|
||||
# Mock TraceCountsModel.select to return empty counts
|
||||
empty_counts = []
|
||||
with patch('agentops.api.models.metrics.TraceCountsModel.select', return_value=empty_counts):
|
||||
# Call the endpoint function
|
||||
result = await get_projects(request=mock_request, orm=orm_session)
|
||||
|
||||
# Verify that it returns a list and the test project is in the results
|
||||
assert isinstance(result, list)
|
||||
assert len(result) > 0
|
||||
|
||||
# Find our project in the results
|
||||
project_response = None
|
||||
for p in result:
|
||||
if p.id == str(project.id):
|
||||
project_response = p
|
||||
break
|
||||
|
||||
assert project_response is not None
|
||||
assert project_response.name == project.name
|
||||
# Verify that the counts are not set (they should be None or default)
|
||||
assert project_response.span_count == 0
|
||||
assert project_response.trace_count == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_project_user_not_member(mock_request, orm_session, test_user, test_user2):
|
||||
"""Test getting a project when the user is not a member of the organization."""
|
||||
# Create an org that the test user is NOT a member of
|
||||
org = OrgModel(name="Test Org Not Member")
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Add test_user2 as the owner (not the main test user)
|
||||
user_org = UserOrgModel(
|
||||
user_id=test_user2.id, org_id=org.id, role=OrgRoles.owner, user_email=test_user2.email
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
|
||||
# Create a project in that org
|
||||
project = ProjectModel(name="Test Project Non-Member", org_id=org.id, environment=Environment.development)
|
||||
orm_session.add(project)
|
||||
orm_session.commit()
|
||||
|
||||
# Expect an HTTP 404 exception when the main test user tries to access it
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
get_project(request=mock_request, project_id=str(project.id), orm=orm_session)
|
||||
|
||||
assert excinfo.value.status_code == 404
|
||||
assert excinfo.value.detail == "Project not found"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_project_default_environment(mock_request, orm_session, test_user):
|
||||
"""Test creating a project without specifying an environment (should use development)."""
|
||||
# Create a fresh org and user-org relationship
|
||||
org = OrgModel(name="Test Org for Default Environment")
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Add the test user as an owner of the org
|
||||
user_id = mock_request.state.session.user_id
|
||||
user_org = UserOrgModel(
|
||||
user_id=user_id, org_id=org.id, role=OrgRoles.owner, user_email="test@example.com"
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create the request body WITHOUT environment field
|
||||
body = ProjectCreateSchema(
|
||||
name="Project With Default Environment",
|
||||
org_id=str(org.id),
|
||||
# environment is intentionally omitted
|
||||
)
|
||||
|
||||
# Call the endpoint function
|
||||
result = create_project(request=mock_request, orm=orm_session, body=body)
|
||||
|
||||
# Verify the project was created with the default environment
|
||||
assert result.name == body.name
|
||||
assert result.org_id == body.org_id
|
||||
assert result.environment == Environment.development.value
|
||||
assert result.api_key is not None
|
||||
|
||||
# Verify in the database
|
||||
created_project = orm_session.query(ProjectModel).filter_by(id=uuid.UUID(result.id)).one()
|
||||
assert created_project.name == body.name
|
||||
assert created_project.environment == Environment.development
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_project_name_only(mock_request, orm_session, test_project):
|
||||
"""Test updating only a project's name, not environment."""
|
||||
# Create the update body with only name
|
||||
new_name = "Updated Project Name Only"
|
||||
body = ProjectUpdateSchema(name=new_name)
|
||||
|
||||
# Execute the update
|
||||
result = update_project(request=mock_request, project_id=str(test_project.id), orm=orm_session, body=body)
|
||||
|
||||
# Verify only the name was updated
|
||||
assert result.name == new_name
|
||||
assert result.environment == test_project.environment.value # should remain unchanged
|
||||
|
||||
# Refresh the session to get the latest data
|
||||
orm_session.expire_all()
|
||||
|
||||
# Verify the database was updated correctly
|
||||
updated_project = orm_session.query(ProjectModel).filter_by(id=test_project.id).one()
|
||||
assert updated_project.name == new_name
|
||||
assert updated_project.environment == test_project.environment # should remain unchanged
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_update_project_environment_only(mock_request, orm_session, test_project):
|
||||
"""Test updating only a project's environment, not name."""
|
||||
# Get the original name for verification later
|
||||
original_name = test_project.name
|
||||
|
||||
# Create the update body with only environment
|
||||
new_environment = Environment.production.value
|
||||
body = ProjectUpdateSchema(environment=new_environment)
|
||||
|
||||
# Execute the update
|
||||
result = update_project(request=mock_request, project_id=str(test_project.id), orm=orm_session, body=body)
|
||||
|
||||
# Verify only the environment was updated
|
||||
assert result.name == original_name # should remain unchanged
|
||||
assert result.environment == new_environment
|
||||
|
||||
# Refresh the session to get the latest data
|
||||
orm_session.expire_all()
|
||||
|
||||
# Verify the database was updated correctly
|
||||
updated_project = orm_session.query(ProjectModel).filter_by(id=test_project.id).one()
|
||||
assert updated_project.name == original_name # should remain unchanged
|
||||
assert updated_project.environment == Environment.production
|
||||
@@ -0,0 +1,77 @@
|
||||
import pytest
|
||||
import uuid
|
||||
from fastapi import HTTPException
|
||||
from sqlalchemy import orm
|
||||
|
||||
from agentops.opsboard.models import (
|
||||
OrgModel,
|
||||
UserOrgModel,
|
||||
ProjectModel,
|
||||
OrgRoles,
|
||||
Environment,
|
||||
)
|
||||
from agentops.opsboard.views.projects import (
|
||||
regenerate_api_key,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_regenerate_api_key_not_admin(mock_request, orm_session, test_user):
|
||||
"""Test regenerating a project's API key without admin permissions."""
|
||||
# Create all the test data in this test
|
||||
org = OrgModel(name="Test Org for Non-Admin Regenerate Key")
|
||||
orm_session.add(org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a user-org relationship with developer role (not admin or owner)
|
||||
user_org = UserOrgModel(
|
||||
user_id=test_user.id,
|
||||
org_id=org.id,
|
||||
role=OrgRoles.developer, # Developer role, not admin or owner
|
||||
user_email=test_user.email
|
||||
)
|
||||
orm_session.add(user_org)
|
||||
orm_session.flush()
|
||||
|
||||
# Create a project with a specific API key
|
||||
initial_api_key = uuid.uuid4()
|
||||
project = ProjectModel(
|
||||
name="Project for Non-Admin Key Regeneration",
|
||||
org_id=org.id,
|
||||
environment=Environment.development,
|
||||
api_key=initial_api_key,
|
||||
)
|
||||
orm_session.add(project)
|
||||
orm_session.flush()
|
||||
|
||||
# Load relationships to ensure they're available
|
||||
project = (
|
||||
orm_session.query(ProjectModel)
|
||||
.options(orm.joinedload(ProjectModel.org).joinedload(OrgModel.users))
|
||||
.filter_by(id=project.id)
|
||||
.one()
|
||||
)
|
||||
|
||||
# Expect an HTTP 404 exception (security through obscurity)
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
regenerate_api_key(request=mock_request, project_id=str(project.id), orm=orm_session)
|
||||
|
||||
assert excinfo.value.status_code == 404
|
||||
assert excinfo.value.detail == "Project not found"
|
||||
|
||||
# Verify the API key wasn't changed
|
||||
unchanged_project = orm_session.query(ProjectModel).filter_by(id=project.id).one()
|
||||
assert unchanged_project.api_key == initial_api_key
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_regenerate_api_key_project_not_found(mock_request, orm_session):
|
||||
"""Test regenerating an API key for a project that doesn't exist."""
|
||||
non_existent_id = str(uuid.uuid4())
|
||||
|
||||
# Expect an HTTP 404 exception
|
||||
with pytest.raises(HTTPException) as excinfo:
|
||||
regenerate_api_key(request=mock_request, project_id=non_existent_id, orm=orm_session)
|
||||
|
||||
assert excinfo.value.status_code == 404
|
||||
assert excinfo.value.detail == "Project not found"
|
||||
@@ -0,0 +1,90 @@
|
||||
import pytest
|
||||
|
||||
from agentops.opsboard.views.users import get_user, update_user, update_user_survey_complete
|
||||
from agentops.opsboard.schemas import UserUpdateSchema, UserResponse, StatusResponse
|
||||
|
||||
|
||||
async def test_get_user(mock_request, orm_session, test_user):
|
||||
"""Test getting user details."""
|
||||
# Call the view function
|
||||
response = get_user(request=mock_request, orm=orm_session)
|
||||
|
||||
# Verify response
|
||||
assert isinstance(response, UserResponse)
|
||||
assert response.full_name == "Test User"
|
||||
assert response.email == "test@example.com"
|
||||
assert response.survey_is_complete is False
|
||||
|
||||
|
||||
async def test_update_user(mock_request, orm_session, test_user):
|
||||
"""Test updating user details."""
|
||||
# Create update data
|
||||
update_data = UserUpdateSchema(full_name="Updated Name", survey_is_complete=True)
|
||||
|
||||
# Call the view function
|
||||
response = update_user(request=mock_request, orm=orm_session, body=update_data)
|
||||
|
||||
# Verify response
|
||||
assert isinstance(response, UserResponse)
|
||||
assert response.full_name == "Updated Name"
|
||||
assert response.survey_is_complete is True
|
||||
|
||||
# Verify database was updated
|
||||
updated_user = orm_session.get_one(type(test_user), test_user.id)
|
||||
assert updated_user.full_name == "Updated Name"
|
||||
assert updated_user.survey_is_complete is True
|
||||
|
||||
|
||||
async def test_update_user_survey_complete(mock_request, orm_session, test_user):
|
||||
"""Test marking the user survey as complete."""
|
||||
# Reset survey_is_complete to False for this test
|
||||
test_user.survey_is_complete = False
|
||||
orm_session.commit()
|
||||
|
||||
# Call the view function
|
||||
response = update_user_survey_complete(request=mock_request, orm=orm_session)
|
||||
|
||||
# Verify response
|
||||
assert isinstance(response, StatusResponse)
|
||||
assert response.success is True
|
||||
assert "complete" in response.message.lower()
|
||||
|
||||
# Verify database was updated
|
||||
updated_user = orm_session.get_one(type(test_user), test_user.id)
|
||||
assert updated_user.survey_is_complete is True
|
||||
|
||||
|
||||
async def test_get_user_not_found(mock_request, orm_session, monkeypatch):
|
||||
"""Test getting a user that doesn't exist."""
|
||||
# Mock UserModel.get_by_id to return None
|
||||
from agentops.opsboard.models import UserModel
|
||||
|
||||
monkeypatch.setattr(UserModel, 'get_by_id', lambda *args, **kwargs: None)
|
||||
|
||||
# Call the view function and expect an exception
|
||||
with pytest.raises(Exception):
|
||||
get_user(request=mock_request, orm=orm_session)
|
||||
|
||||
|
||||
async def test_update_user_not_found(mock_request, orm_session, monkeypatch):
|
||||
"""Test updating a user that doesn't exist."""
|
||||
# Mock UserModel.get_by_id to return None
|
||||
from agentops.opsboard.models import UserModel
|
||||
|
||||
monkeypatch.setattr(UserModel, 'get_by_id', lambda *args, **kwargs: None)
|
||||
|
||||
# Call the view function and expect an exception
|
||||
with pytest.raises(Exception):
|
||||
update_user(request=mock_request, orm=orm_session, body=UserUpdateSchema(full_name="Test"))
|
||||
|
||||
|
||||
async def test_update_user_survey_complete_not_found(mock_request, orm_session, monkeypatch):
|
||||
"""Test marking survey complete for a user that doesn't exist."""
|
||||
# Mock UserModel.get_by_id to return None
|
||||
from agentops.opsboard.models import UserModel
|
||||
|
||||
monkeypatch.setattr(UserModel, 'get_by_id', lambda *args, **kwargs: None)
|
||||
|
||||
# Call the view function and expect an exception
|
||||
with pytest.raises(Exception):
|
||||
update_user_survey_complete(request=mock_request, orm=orm_session)
|
||||
@@ -0,0 +1,408 @@
|
||||
import pytest
|
||||
import jwt
|
||||
import uuid
|
||||
from datetime import datetime, timezone
|
||||
from agentops.api.auth import generate_jwt, JWT_ALGO
|
||||
from agentops.api.environment import JWT_SECRET_KEY
|
||||
from agentops.opsboard.models import ProjectModel
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_api_key():
|
||||
"""Generate a UUID for premium test project API key."""
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_free_api_key():
|
||||
"""Generate a UUID for free plan test project API key."""
|
||||
return str(uuid.uuid4())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_trace_id():
|
||||
"""Generate a unique trace ID for testing."""
|
||||
import random
|
||||
|
||||
return str(random.randint(10**37, 10**38 - 1))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_span_id():
|
||||
"""Generate a unique span ID for testing."""
|
||||
import random
|
||||
|
||||
return str(random.randint(10**19, 10**20 - 1))
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_project_with_api_key(orm_session, test_user_org_owner_prem, test_api_key):
|
||||
"""Create a test project with the specific API key for testing."""
|
||||
org = test_user_org_owner_prem
|
||||
|
||||
project = ProjectModel(
|
||||
name="Test Public API Project",
|
||||
org_id=org.id,
|
||||
environment="development",
|
||||
api_key=test_api_key,
|
||||
)
|
||||
orm_session.add(project)
|
||||
orm_session.commit()
|
||||
|
||||
project_obj = ProjectModel.get_by_id(orm_session, project.id)
|
||||
|
||||
yield project_obj
|
||||
|
||||
# Cleanup: delete the project after the test
|
||||
orm_session.delete(project_obj)
|
||||
orm_session.commit()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_free_project_with_api_key(orm_session, test_user_org_owner, test_free_api_key):
|
||||
"""Create a free plan test project for testing restrictions."""
|
||||
org = test_user_org_owner
|
||||
|
||||
project = ProjectModel(
|
||||
name="Test Free Project",
|
||||
org_id=org.id,
|
||||
environment="development",
|
||||
api_key=test_free_api_key,
|
||||
# TODO the project org will dictate the plan
|
||||
)
|
||||
orm_session.add(project)
|
||||
orm_session.commit()
|
||||
|
||||
project_obj = ProjectModel.get_by_id(orm_session, project.id)
|
||||
|
||||
yield project_obj
|
||||
|
||||
# Cleanup: delete the project after the test
|
||||
orm_session.delete(project_obj)
|
||||
orm_session.commit()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def test_trace_data(async_clickhouse_client, test_project_with_api_key, test_trace_id):
|
||||
"""Create test trace data in ClickHouse."""
|
||||
import random
|
||||
|
||||
project = test_project_with_api_key
|
||||
project_id_str = str(project.id)
|
||||
|
||||
# Insert test trace
|
||||
trace_data = {
|
||||
"Timestamp": datetime.now(timezone.utc),
|
||||
"TraceId": test_trace_id,
|
||||
"SpanId": str(random.randint(10**19, 10**20 - 1)), # Unique span ID for the root span
|
||||
"ParentSpanId": "",
|
||||
"TraceState": "",
|
||||
"SpanName": "test_trace",
|
||||
"SpanKind": "SPAN_KIND_INTERNAL",
|
||||
"ServiceName": "test_service",
|
||||
"ResourceAttributes": {"agentops.project.id": project_id_str},
|
||||
"ScopeName": "",
|
||||
"ScopeVersion": "",
|
||||
"SpanAttributes": {"tags": "test,public-api"},
|
||||
"Duration": 1000000,
|
||||
"StatusCode": "STATUS_CODE_OK",
|
||||
"StatusMessage": "",
|
||||
"Events.Timestamp": [],
|
||||
"Events.Name": [],
|
||||
"Events.Attributes": [],
|
||||
"Links.TraceId": [],
|
||||
"Links.SpanId": [],
|
||||
"Links.TraceState": [],
|
||||
"Links.Attributes": [],
|
||||
}
|
||||
|
||||
await async_clickhouse_client.insert(
|
||||
table="otel_traces", data=[list(trace_data.values())], column_names=list(trace_data.keys())
|
||||
)
|
||||
|
||||
yield trace_data
|
||||
|
||||
# Cleanup: delete the trace data after the test
|
||||
await async_clickhouse_client.command(f"DELETE FROM otel_traces WHERE TraceId = '{test_trace_id}'")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def test_span_data(async_clickhouse_client, test_trace_data, test_span_id, test_trace_id):
|
||||
"""Create test span data in ClickHouse."""
|
||||
# Use the same project ID as the trace data
|
||||
project_id_str = test_trace_data["ResourceAttributes"]["agentops.project.id"]
|
||||
|
||||
# Insert test span
|
||||
span_data = {
|
||||
"Timestamp": datetime.now(timezone.utc),
|
||||
"TraceId": test_trace_id,
|
||||
"SpanId": test_span_id,
|
||||
"ParentSpanId": "",
|
||||
"TraceState": "",
|
||||
"SpanName": "test_span",
|
||||
"SpanKind": "SPAN_KIND_INTERNAL",
|
||||
"ServiceName": "test_service",
|
||||
"ResourceAttributes": {"agentops.project.id": project_id_str, "service.name": "test_service"},
|
||||
"ScopeName": "",
|
||||
"ScopeVersion": "",
|
||||
"SpanAttributes": {"operation": "test", "test": "value"},
|
||||
"Duration": 1000000, # 1ms in nanoseconds
|
||||
"StatusCode": "STATUS_CODE_OK",
|
||||
"StatusMessage": "",
|
||||
"Events.Timestamp": [],
|
||||
"Events.Name": [],
|
||||
"Events.Attributes": [],
|
||||
"Links.TraceId": [],
|
||||
"Links.SpanId": [],
|
||||
"Links.TraceState": [],
|
||||
"Links.Attributes": [],
|
||||
}
|
||||
|
||||
await async_clickhouse_client.insert(
|
||||
table="otel_traces", data=[list(span_data.values())], column_names=list(span_data.keys())
|
||||
)
|
||||
|
||||
yield span_data
|
||||
|
||||
# Cleanup: delete the span data after the test
|
||||
await async_clickhouse_client.command(f"DELETE FROM otel_traces WHERE SpanId = '{test_span_id}'")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def valid_bearer_token(test_project_with_api_key):
|
||||
"""Generate a valid JWT bearer token for testing."""
|
||||
project = test_project_with_api_key
|
||||
return generate_jwt(project)
|
||||
|
||||
|
||||
class TestAuthenticationEndpoint:
|
||||
"""Tests for POST /public/v1/auth/access_token"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_access_token_success(self, async_app_client, test_project_with_api_key, test_api_key):
|
||||
"""Test successful API key to bearer token conversion."""
|
||||
response = await async_app_client.post("/public/v1/auth/access_token", json={"api_key": test_api_key})
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "bearer" in data
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_access_token_invalid_api_key(self, async_app_client):
|
||||
"""Test with invalid API key."""
|
||||
response = await async_app_client.post(
|
||||
"/public/v1/auth/access_token", json={"api_key": "invalid-key-123"}
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_access_token_missing_api_key(self, async_app_client):
|
||||
"""Test with missing API key."""
|
||||
response = await async_app_client.post("/public/v1/auth/access_token", json={})
|
||||
|
||||
assert response.status_code == 422
|
||||
# this is an internal fastapi thing
|
||||
|
||||
@pytest.mark.skip(
|
||||
reason="Free plan blocking temporarily disabled - see BasePublicAPIView._verify_project_has_access"
|
||||
)
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_access_token_free_plan_blocked(
|
||||
self, async_app_client, test_free_project_with_api_key, test_free_api_key
|
||||
):
|
||||
"""Test that free plan projects are blocked from accessing the API."""
|
||||
response = await async_app_client.post(
|
||||
"/public/v1/auth/access_token", json={"api_key": test_free_api_key}
|
||||
)
|
||||
|
||||
assert response.status_code == 403
|
||||
assert "not available for free plan projects" in response.json()["detail"]
|
||||
|
||||
|
||||
class TestProjectEndpoint:
|
||||
"""Tests for GET /public/v1/project"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_project_success(self, async_app_client, test_project_with_api_key, valid_bearer_token):
|
||||
"""Test successful project details retrieval."""
|
||||
project = test_project_with_api_key
|
||||
token = valid_bearer_token
|
||||
|
||||
response = await async_app_client.get(
|
||||
"/public/v1/project", headers={"Authorization": f"Bearer {token}"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
assert data["id"] == str(project.id)
|
||||
assert data["name"] == project.name
|
||||
assert data["environment"] == project.environment
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_project_missing_auth_header(self, async_app_client):
|
||||
"""Test with missing Authorization header."""
|
||||
response = await async_app_client.get("/public/v1/project")
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "Missing or invalid Authorization header" in response.json()["detail"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_project_invalid_bearer_token(self, async_app_client):
|
||||
"""Test with invalid bearer token."""
|
||||
response = await async_app_client.get(
|
||||
"/public/v1/project", headers={"Authorization": "Bearer invalid-token-123"}
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
class TestTraceEndpoints:
|
||||
"""Tests for trace-related endpoints"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_trace_success(
|
||||
self,
|
||||
async_app_client,
|
||||
test_trace_data,
|
||||
test_span_data,
|
||||
valid_bearer_token,
|
||||
test_trace_id,
|
||||
async_clickhouse_client,
|
||||
test_project_with_api_key,
|
||||
):
|
||||
"""Test successful trace retrieval."""
|
||||
token = valid_bearer_token
|
||||
|
||||
response = await async_app_client.get(
|
||||
f"/public/v1/traces/{test_trace_id}", headers={"Authorization": f"Bearer {token}"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
assert data["trace_id"] == test_trace_id
|
||||
assert "spans" in data
|
||||
assert "tags" in data
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_trace_metrics_success(
|
||||
self, async_app_client, test_trace_data, valid_bearer_token, test_trace_id
|
||||
):
|
||||
"""Test successful trace metrics retrieval."""
|
||||
token = valid_bearer_token
|
||||
|
||||
response = await async_app_client.get(
|
||||
f"/public/v1/traces/{test_trace_id}/metrics", headers={"Authorization": f"Bearer {token}"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
# Metrics response structure will depend on TraceMetricsResponse model
|
||||
assert isinstance(data, dict)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_trace_not_found(self, async_app_client, valid_bearer_token):
|
||||
"""Test trace not found."""
|
||||
token = valid_bearer_token
|
||||
|
||||
response = await async_app_client.get(
|
||||
"/public/v1/traces/nonexistent-trace-id", headers={"Authorization": f"Bearer {token}"}
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "Trace not found" in response.json()["detail"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_trace_missing_trace_id(self, async_app_client, valid_bearer_token):
|
||||
"""Test with missing trace_id parameter."""
|
||||
token = valid_bearer_token
|
||||
|
||||
response = await async_app_client.get(
|
||||
"/public/v1/traces/", headers={"Authorization": f"Bearer {token}"}
|
||||
)
|
||||
|
||||
assert response.status_code == 404 # Route not found
|
||||
|
||||
|
||||
class TestSpanEndpoints:
|
||||
"""Tests for span-related endpoints"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_span_success(self, async_app_client, test_span_data, valid_bearer_token, test_span_id):
|
||||
"""Test successful span retrieval."""
|
||||
token = valid_bearer_token
|
||||
|
||||
response = await async_app_client.get(
|
||||
f"/public/v1/spans/{test_span_id}", headers={"Authorization": f"Bearer {token}"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
|
||||
assert data["span_id"] == test_span_id
|
||||
assert data["span_name"] == "test_span"
|
||||
assert data["span_kind"] == "SPAN_KIND_INTERNAL"
|
||||
assert "attributes" in data
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_span_metrics_success(
|
||||
self, async_app_client, test_span_data, valid_bearer_token, test_span_id
|
||||
):
|
||||
"""Test successful span metrics retrieval."""
|
||||
token = valid_bearer_token
|
||||
|
||||
response = await async_app_client.get(
|
||||
f"/public/v1/spans/{test_span_id}/metrics", headers={"Authorization": f"Bearer {token}"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
# Metrics response structure will depend on SpanMetricsResponse model
|
||||
assert isinstance(data, dict)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_span_not_found(self, async_app_client, valid_bearer_token):
|
||||
"""Test span not found."""
|
||||
token = valid_bearer_token
|
||||
|
||||
response = await async_app_client.get(
|
||||
"/public/v1/spans/nonexistent-span-id", headers={"Authorization": f"Bearer {token}"}
|
||||
)
|
||||
|
||||
assert response.status_code == 404
|
||||
assert "Span not found" in response.json()["detail"]
|
||||
|
||||
|
||||
class TestErrorCases:
|
||||
"""Tests for various error scenarios"""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_malformed_bearer_token(self, async_app_client):
|
||||
"""Test with malformed Authorization header."""
|
||||
response = await async_app_client.get(
|
||||
"/public/v1/project", headers={"Authorization": "NotBearer token123"}
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "Missing or invalid Authorization header" in response.json()["detail"]
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_expired_bearer_token(self, async_app_client):
|
||||
"""Test with expired JWT token."""
|
||||
# Create an expired token (with past exp claim)
|
||||
import time
|
||||
|
||||
expired_payload = {
|
||||
"project_id": "test-project-id",
|
||||
"is_premium": True,
|
||||
"exp": int(time.time()) - 3600, # Expired 1 hour ago
|
||||
}
|
||||
expired_token = jwt.encode(expired_payload, JWT_SECRET_KEY, algorithm=JWT_ALGO)
|
||||
|
||||
response = await async_app_client.get(
|
||||
"/public/v1/project", headers={"Authorization": f"Bearer {expired_token}"}
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
@@ -0,0 +1,80 @@
|
||||
import agentops
|
||||
import pytest
|
||||
from agentops import Session
|
||||
from datetime import datetime
|
||||
import requests
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def agentops_init():
|
||||
agentops.init()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def agentops_session(agentops_init):
|
||||
"""Create an agentops session"""
|
||||
session = agentops.start_session()
|
||||
|
||||
assert session, "Failed agentops.start_session() returned None."
|
||||
yield session
|
||||
agentops.end_all_sessions()
|
||||
|
||||
|
||||
def test_logs_read_write_to_session(agentops_session: Session):
|
||||
"""
|
||||
Subsequently tests `/v3/logs/{session_id}` endpoint for PUT -> GET.
|
||||
"""
|
||||
session_id = str(agentops_session.session_id)
|
||||
api_base = "http://localhost:8000" # Or get from environment variable
|
||||
|
||||
# Test writing to session
|
||||
test_data = {
|
||||
"stdout_line_count": 5,
|
||||
"stderr_line_count": 1,
|
||||
"log_level_counts": {"INFO": 3, "WARNING": 2},
|
||||
"start_time": datetime.now().isoformat(),
|
||||
"end_time": datetime.now().isoformat(),
|
||||
"is_capturing": False,
|
||||
"logs": [
|
||||
{"level": "INFO", "message": "Test write log 1"},
|
||||
{"level": "WARNING", "message": "Test warning 1"},
|
||||
{"level": "INFO", "message": "Test write log 2"},
|
||||
],
|
||||
}
|
||||
|
||||
# Write logs using real HTTP request
|
||||
response = requests.put(
|
||||
f"{api_base}/v3/logs/{session_id}",
|
||||
json=test_data,
|
||||
headers={"Authorization": f"Bearer {agentops_session.jwt}"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
write_response = response.json()
|
||||
assert write_response["status"] == "success"
|
||||
assert write_response["session_id"] == session_id
|
||||
assert "url" in write_response
|
||||
assert "filename" in write_response
|
||||
|
||||
# Read logs back using real HTTP request
|
||||
response = requests.get(
|
||||
f"{api_base}/v3/logs/{session_id}",
|
||||
headers={"Authorization": f"Bearer {agentops_session.jwt}"},
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
read_response = response.json()
|
||||
assert read_response["session_id"] == session_id
|
||||
assert "logs" in read_response
|
||||
assert len(read_response["logs"]) > 0
|
||||
|
||||
# Verify the log file we just wrote is in the response
|
||||
found_file = False
|
||||
for log_file in read_response["logs"]:
|
||||
if log_file["name"] == write_response["filename"]:
|
||||
found_file = True
|
||||
assert "url" in log_file
|
||||
assert "created_at" in log_file
|
||||
break
|
||||
|
||||
assert found_file, "Could not find the written log file in the GET response"
|
||||
@@ -0,0 +1,59 @@
|
||||
from agentops.api.models.traces import nanosecond_timedelta
|
||||
import datetime
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Ensure the repo root (which contains the `agentops` package) is on the path
|
||||
REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
|
||||
if REPO_ROOT not in sys.path:
|
||||
sys.path.insert(0, REPO_ROOT)
|
||||
|
||||
|
||||
def _wall_clock_ns(start: datetime.datetime, duration_ns: int) -> datetime.datetime:
|
||||
"""Helper to convert a start time + duration nanoseconds into an end datetime."""
|
||||
return start + nanosecond_timedelta(duration_ns)
|
||||
|
||||
|
||||
def test_overlapping_spans_wall_clock_less_than_sum():
|
||||
"""Two overlapping spans should yield wall-clock duration < sum(duration)."""
|
||||
|
||||
root_start = datetime.datetime(2025, 7, 7, 1, 19, 4, 69444, tzinfo=datetime.timezone.utc)
|
||||
child_start = root_start + datetime.timedelta(seconds=1)
|
||||
|
||||
root_duration_ns = 30_000_000_000 # 30 s
|
||||
child_duration_ns = 15_000_000_000 # 15 s (overlaps root)
|
||||
|
||||
root_end = _wall_clock_ns(root_start, root_duration_ns)
|
||||
child_end = _wall_clock_ns(child_start, child_duration_ns)
|
||||
|
||||
expected_wall_clock_ns = int((max(root_end, child_end) - min(root_start, child_start)).total_seconds() * 1e9)
|
||||
|
||||
# Ensure overlap made wall-clock less than naive sum
|
||||
assert expected_wall_clock_ns == 30_000_000_000 # 30 s elapsed (root span duration)
|
||||
assert expected_wall_clock_ns < (root_duration_ns + child_duration_ns)
|
||||
|
||||
|
||||
def test_non_overlapping_spans_wall_clock_equals_sum():
|
||||
"""If spans do not overlap the wall-clock duration equals the sum."""
|
||||
|
||||
first_start = datetime.datetime(2025, 7, 7, 10, 0, 0, tzinfo=datetime.timezone.utc)
|
||||
first_dur_ns = 10_000_000_000 # 10 s
|
||||
first_end = _wall_clock_ns(first_start, first_dur_ns)
|
||||
|
||||
second_start = first_end # starts immediately after first ends
|
||||
second_dur_ns = 5_000_000_000 # 5 s
|
||||
second_end = _wall_clock_ns(second_start, second_dur_ns)
|
||||
|
||||
wall_clock_ns = int((second_end - first_start).total_seconds() * 1e9)
|
||||
assert wall_clock_ns == first_dur_ns + second_dur_ns == 15_000_000_000
|
||||
|
||||
|
||||
def test_single_span_wall_clock_equals_itself():
|
||||
"""Single span should report its own duration."""
|
||||
|
||||
start = datetime.datetime(2025, 7, 7, 12, 0, 0, tzinfo=datetime.timezone.utc)
|
||||
dur_ns = 8_500_000_000 # 8.5 s
|
||||
end = _wall_clock_ns(start, dur_ns)
|
||||
|
||||
wall_clock_ns = int((end - start).total_seconds() * 1e9)
|
||||
assert wall_clock_ns == dur_ns
|
||||
@@ -0,0 +1,95 @@
|
||||
"""
|
||||
Tests for the Sentry event sanitizer
|
||||
"""
|
||||
|
||||
from agentops.common.sentry import sanitize_event, SENSITIVE_DATA_PLACEHOLDER
|
||||
|
||||
|
||||
def test_sanitize_event_without_exception():
|
||||
"""Test that events without exceptions are returned unchanged"""
|
||||
mock_event = {"message": "Test event without exception"}
|
||||
result = sanitize_event(mock_event, {})
|
||||
|
||||
assert result == mock_event
|
||||
assert result is mock_event
|
||||
|
||||
|
||||
def test_sanitize_event_empty_vars():
|
||||
"""Test that events with empty vars are handled correctly"""
|
||||
mock_event = {"exception": {"values": [{"stacktrace": {"frames": [{"vars": {}}]}}]}}
|
||||
|
||||
result = sanitize_event(mock_event, {})
|
||||
assert result["exception"]["values"][0]["stacktrace"]["frames"][0]["vars"] == {}
|
||||
|
||||
|
||||
def test_comprehensive_sanitization():
|
||||
"""Comprehensive test for sanitizing passwords in various locations"""
|
||||
mock_event = {
|
||||
"exception": {
|
||||
"values": [
|
||||
{
|
||||
"stacktrace": {
|
||||
"frames": [
|
||||
{
|
||||
"vars": {
|
||||
# Root level password
|
||||
"password": "super_secret",
|
||||
# Non-sensitive data that should be preserved
|
||||
"normal_var": "keep this",
|
||||
# Nested dictionary with password
|
||||
"user_config": {
|
||||
"username": "testuser",
|
||||
"password": "123password456",
|
||||
"settings": {"password": "nested_deeper_pw"},
|
||||
},
|
||||
# Array of primitives (should be untouched)
|
||||
"simple_array": [1, 2, 3, "string", True, None],
|
||||
# Array with dictionary containing password
|
||||
"users": [{"name": "user1", "password": "user1_password"}],
|
||||
# Complex nested structure
|
||||
"complex_data": [
|
||||
{
|
||||
"name": "keep_this",
|
||||
"items": [
|
||||
{"id": 1, "password": "level3_pw_1"},
|
||||
{"id": 2, "password": "level3_pw_2"},
|
||||
],
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
result = sanitize_event(mock_event, {})
|
||||
|
||||
# Get the variables dict for easier access
|
||||
frame_vars = result["exception"]["values"][0]["stacktrace"]["frames"][0]["vars"]
|
||||
|
||||
# Test root level password sanitization
|
||||
assert frame_vars["password"] == SENSITIVE_DATA_PLACEHOLDER
|
||||
assert frame_vars["normal_var"] == "keep this"
|
||||
|
||||
# Test nested dictionary sanitization
|
||||
assert frame_vars["user_config"]["username"] == "testuser"
|
||||
assert frame_vars["user_config"]["password"] == SENSITIVE_DATA_PLACEHOLDER
|
||||
assert frame_vars["user_config"]["settings"]["password"] == SENSITIVE_DATA_PLACEHOLDER
|
||||
|
||||
# Test array of primitives (should be untouched)
|
||||
assert frame_vars["simple_array"] == [1, 2, 3, "string", True, None]
|
||||
|
||||
# Test array with dictionary containing password
|
||||
assert frame_vars["users"][0]["name"] == "user1"
|
||||
assert frame_vars["users"][0]["password"] == SENSITIVE_DATA_PLACEHOLDER
|
||||
|
||||
# Test complex nested structure
|
||||
complex_data = frame_vars["complex_data"][0]
|
||||
assert complex_data["name"] == "keep_this"
|
||||
assert complex_data["items"][0]["id"] == 1
|
||||
assert complex_data["items"][0]["password"] == SENSITIVE_DATA_PLACEHOLDER
|
||||
assert complex_data["items"][1]["id"] == 2
|
||||
assert complex_data["items"][1]["password"] == SENSITIVE_DATA_PLACEHOLDER
|
||||
@@ -0,0 +1,130 @@
|
||||
from datetime import datetime, timedelta
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
import jwt
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from agentops.api.app import app
|
||||
from agentops.api.auth import JWTPayload, JWT_ALGO
|
||||
from agentops.api.environment import JWT_SECRET_KEY
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def test_client():
|
||||
"""Test API [FastAPI] Client"""
|
||||
return TestClient(app)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def jwt_secret():
|
||||
"""Get the JWT secret from environment variables"""
|
||||
return JWT_SECRET_KEY
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def valid_jwt_payload():
|
||||
"""Create a valid JWT payload for testing"""
|
||||
return JWTPayload(
|
||||
exp=(datetime.now() + timedelta(hours=1)).timestamp(),
|
||||
aud="authenticated",
|
||||
project_id="test-project-id",
|
||||
project_prem_status="premium",
|
||||
api_key="test-api-key",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def expired_jwt_payload():
|
||||
"""Create an expired JWT payload for testing"""
|
||||
return JWTPayload(
|
||||
exp=(datetime.now() - timedelta(hours=1)).timestamp(),
|
||||
aud="authenticated",
|
||||
project_id="test-project-id",
|
||||
project_prem_status="premium",
|
||||
api_key="test-api-key",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def valid_jwt(valid_jwt_payload, jwt_secret):
|
||||
"""Create a valid JWT token for testing"""
|
||||
return jwt.encode(valid_jwt_payload.asdict(), jwt_secret, algorithm=JWT_ALGO)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def expired_jwt(expired_jwt_payload, jwt_secret):
|
||||
"""Create an expired JWT token for testing"""
|
||||
return jwt.encode(expired_jwt_payload.asdict(), jwt_secret, algorithm=JWT_ALGO)
|
||||
|
||||
|
||||
def test_jwt_info_endpoint_with_valid_token(test_client, valid_jwt, valid_jwt_payload):
|
||||
"""Test that the JWT info endpoint works with a valid token"""
|
||||
headers = {"Authorization": f"Bearer {valid_jwt}"}
|
||||
|
||||
# Mock the verify_jwt function to avoid database lookup
|
||||
with patch('agentops.api.auth.verify_jwt', return_value=valid_jwt_payload):
|
||||
# Also mock the ProjectModel.get_by_id to avoid database lookup
|
||||
with patch('agentops.opsboard.models.ProjectModel.get_by_id') as mock_get:
|
||||
# Create a mock project that matches the JWT payload
|
||||
mock_project = MagicMock()
|
||||
mock_project.org.prem_status.value = valid_jwt_payload.project_prem_status
|
||||
mock_get.return_value = mock_project
|
||||
|
||||
response = test_client.get("/v3/auth/token", headers=headers)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.json()["message"] == "JWT token is valid"
|
||||
assert "payload" in response.json()
|
||||
assert "expires_at" in response.json()
|
||||
|
||||
# Check that the payload contains the expected fields
|
||||
payload = response.json()["payload"]
|
||||
assert payload["project_id"] == "test-project-id"
|
||||
assert payload["project_prem_status"] == "premium"
|
||||
assert payload["aud"] == "authenticated"
|
||||
assert "exp" in payload
|
||||
assert "api_key" in payload
|
||||
|
||||
|
||||
def test_jwt_info_endpoint_with_expired_token(test_client, expired_jwt):
|
||||
"""Test that the JWT info endpoint returns 401 with an expired token"""
|
||||
headers = {"Authorization": f"Bearer {expired_jwt}"}
|
||||
|
||||
# We want the real verify_jwt function to be called to test expiration
|
||||
response = test_client.get("/v3/auth/token", headers=headers)
|
||||
assert response.status_code == 401
|
||||
assert "Token has expired" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_jwt_info_endpoint_without_token(test_client):
|
||||
"""Test that the JWT info endpoint returns 401 without a token"""
|
||||
response = test_client.get("/v3/auth/token")
|
||||
assert response.status_code == 401
|
||||
assert "Authorization header missing" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_jwt_info_endpoint_with_invalid_token(test_client):
|
||||
"""Test that the JWT info endpoint returns 401 with an invalid token"""
|
||||
headers = {"Authorization": "Bearer invalid.token.here"}
|
||||
response = test_client.get("/v3/auth/token", headers=headers)
|
||||
assert response.status_code == 401
|
||||
assert "Invalid token" in response.json()["detail"]
|
||||
|
||||
|
||||
def test_jwt_info_endpoint_plan_changed(test_client, valid_jwt, valid_jwt_payload):
|
||||
"""Test when project plan has changed since token was issued"""
|
||||
headers = {"Authorization": f"Bearer {valid_jwt}"}
|
||||
|
||||
# Mock the verify_jwt function to return our payload
|
||||
with patch('agentops.api.auth.verify_jwt', return_value=valid_jwt_payload):
|
||||
# Mock ProjectModel.get_by_id to return a project with a different plan
|
||||
with patch('agentops.opsboard.models.ProjectModel.get_by_id') as mock_get:
|
||||
mock_project = MagicMock()
|
||||
mock_project.org.prem_status.value = "free" # Different from token's "premium"
|
||||
mock_get.return_value = mock_project
|
||||
|
||||
response = test_client.get("/v3/auth/token", headers=headers)
|
||||
|
||||
assert response.status_code == 401
|
||||
assert "Reauthorized to use new plan" in response.json()["detail"]
|
||||
@@ -0,0 +1,72 @@
|
||||
from unittest.mock import patch, MagicMock
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
|
||||
from agentops.opsboard.models import ProjectModel
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_token_valid_api_key(async_app_client):
|
||||
"""Test getting a JWT token with a valid API key"""
|
||||
# Mock a project for the test
|
||||
mock_project = MagicMock()
|
||||
mock_project.id = "test-project-id"
|
||||
mock_project.api_key = UUID("11111111-1111-1111-1111-111111111111")
|
||||
mock_project.org.prem_status.value = "premium"
|
||||
|
||||
# Mock the ProjectModel.get_by_api_key method
|
||||
with patch.object(ProjectModel, 'get_by_api_key', return_value=mock_project):
|
||||
# Mock the generate_jwt function to return a predictable token
|
||||
with patch('agentops.api.routes.v3.generate_jwt', return_value="test.jwt.token"):
|
||||
response = await async_app_client.post(
|
||||
"/v3/auth/token",
|
||||
json={"api_key": "11111111-1111-1111-1111-111111111111"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert "token" in data
|
||||
assert data["token"] == "test.jwt.token"
|
||||
assert data["project_id"] == "test-project-id"
|
||||
assert data["project_prem_status"] == "premium"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_token_invalid_api_key_format(async_app_client):
|
||||
"""Test getting a JWT token with an invalid API key format"""
|
||||
response = await async_app_client.post(
|
||||
"/v3/auth/token",
|
||||
json={"api_key": "not-a-uuid"}
|
||||
)
|
||||
|
||||
assert response.status_code == 400
|
||||
assert "Invalid API key format" in response.json()["error"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_token_nonexistent_api_key(async_app_client):
|
||||
"""Test getting a JWT token with a nonexistent API key"""
|
||||
# Mock the ProjectModel.get_by_api_key method to return None
|
||||
with patch.object(ProjectModel, 'get_by_api_key', return_value=None):
|
||||
response = await async_app_client.post(
|
||||
"/v3/auth/token",
|
||||
json={"api_key": "11111111-1111-1111-1111-111111111111"}
|
||||
)
|
||||
|
||||
assert response.status_code == 403
|
||||
assert "Invalid API key" in response.json()["error"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_token_server_error(async_app_client):
|
||||
"""Test handling of server errors in token generation"""
|
||||
# Mock the ProjectModel.get_by_api_key method to raise an exception
|
||||
with patch.object(ProjectModel, 'get_by_api_key', side_effect=Exception("Database error")):
|
||||
response = await async_app_client.post(
|
||||
"/v3/auth/token",
|
||||
json={"api_key": "11111111-1111-1111-1111-111111111111"}
|
||||
)
|
||||
|
||||
assert response.status_code == 500
|
||||
assert "Authentication failed" in response.json()["error"]
|
||||
@@ -0,0 +1,44 @@
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_jwt_and_verify(async_app_client, test_project):
|
||||
"""Test the complete end-to-end flow: get token, use token, verify payload"""
|
||||
|
||||
api_key, project_id = str(test_project.api_key), str(test_project.id)
|
||||
|
||||
auth_response = await async_app_client.post("/v3/auth/token", json={"api_key": api_key})
|
||||
assert auth_response.status_code == 200
|
||||
token = auth_response.json()["token"]
|
||||
|
||||
headers = {"Authorization": f"Bearer {token}"}
|
||||
info_response = await async_app_client.get("/v3/auth/token", headers=headers)
|
||||
|
||||
assert info_response.status_code == 200
|
||||
payload = info_response.json()["payload"]
|
||||
assert "project_id" in payload
|
||||
assert "api_key" in payload
|
||||
assert payload["project_id"] == project_id
|
||||
assert payload["api_key"] == api_key
|
||||
|
||||
|
||||
async def test_get_jwt_placeholder_api_key(async_app_client):
|
||||
"""Test the get token endpoint with a placeholder API key"""
|
||||
|
||||
auth_response = await async_app_client.post(
|
||||
"/v3/auth/token", json={"api_key": "INSERT-YOUR-API-KEY-HERE"}
|
||||
)
|
||||
|
||||
assert auth_response.status_code == 400
|
||||
assert 'error' in auth_response.json()
|
||||
|
||||
|
||||
async def test_get_jwt_non_existent_api_key(async_app_client):
|
||||
"""Test the get token endpoint with a non-existent API key"""
|
||||
|
||||
auth_response = await async_app_client.post(
|
||||
"/v3/auth/token", json={"api_key": "ffffffff-0000-0000-0000-000000000000"}
|
||||
)
|
||||
|
||||
assert auth_response.status_code == 403
|
||||
assert 'error' in auth_response.json()
|
||||
@@ -0,0 +1,341 @@
|
||||
"""
|
||||
Tests for v4 logs API endpoints including LogsUploadView and get_trace_logs.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from io import BytesIO
|
||||
from unittest.mock import patch, MagicMock, AsyncMock
|
||||
from fastapi import HTTPException, status, Request
|
||||
|
||||
from agentops.api.routes.v4.logs import LogsUploadView, get_trace_logs, convert_trace_id
|
||||
from agentops.api.storage import ObjectUploadResponse
|
||||
from agentops.api.environment import SUPABASE_URL, SUPABASE_S3_LOGS_BUCKET
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_jwt_payload():
|
||||
"""Mock JWT payload for testing"""
|
||||
return {
|
||||
'project_id': 'test-project-123',
|
||||
'project_prem_status': 'premium',
|
||||
'api_key': 'test-api-key',
|
||||
'aud': 'authenticated',
|
||||
'exp': 1234567890,
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_s3_client():
|
||||
"""Mock S3 client for testing"""
|
||||
client = MagicMock()
|
||||
client.upload_fileobj = MagicMock()
|
||||
client.get_object = MagicMock()
|
||||
client.exceptions.NoSuchKey = Exception
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_request():
|
||||
"""Mock FastAPI Request for testing"""
|
||||
request = MagicMock(spec=Request)
|
||||
|
||||
# Create a proper async iterator for the stream method
|
||||
async def async_stream_generator(chunks):
|
||||
for chunk in chunks:
|
||||
yield chunk
|
||||
|
||||
# Default stream that will be overridden in individual tests
|
||||
request.stream = AsyncMock(return_value=async_stream_generator([]))
|
||||
|
||||
# Add required headers for public route validation
|
||||
request.headers = {
|
||||
"x-forwarded-for": "192.168.0.1",
|
||||
"x-forwarded-host": "api.agentops.ai",
|
||||
"origin": "https://app.agentops.ai",
|
||||
"referer": "https://app.agentops.ai/signin",
|
||||
"user-agent": "Mozilla/5.0 Chrome/91.0.4472.124",
|
||||
}
|
||||
return request
|
||||
|
||||
|
||||
class TestLogsUploadView:
|
||||
"""Tests for the LogsUploadView class"""
|
||||
|
||||
def test_bucket_name_configuration(self, mock_request):
|
||||
"""Test that LogsUploadView has correct bucket configuration"""
|
||||
view = LogsUploadView(mock_request)
|
||||
assert view.bucket_name == SUPABASE_S3_LOGS_BUCKET
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_successful_log_upload(self, mock_jwt_payload, mock_s3_client, mock_request):
|
||||
"""Test successful log file upload with trace ID"""
|
||||
view = LogsUploadView(mock_request)
|
||||
|
||||
# Set trace ID header (merge with existing headers)
|
||||
trace_id = "test-trace-12345"
|
||||
mock_request.headers.update({"Trace-Id": trace_id})
|
||||
|
||||
# Mock request stream
|
||||
test_content = b'[INFO] Test log content\n[ERROR] Test error message'
|
||||
|
||||
async def async_stream_generator():
|
||||
for chunk in [test_content]:
|
||||
yield chunk
|
||||
|
||||
mock_request.stream = lambda: async_stream_generator()
|
||||
|
||||
with (
|
||||
patch('agentops.api.storage.get_s3_client', return_value=mock_s3_client),
|
||||
patch('agentops.auth.views.API_URL', 'http://localhost:8000'),
|
||||
): # Bypass validation
|
||||
response = await view(token=mock_jwt_payload)
|
||||
|
||||
assert isinstance(response, ObjectUploadResponse)
|
||||
assert response.size == len(test_content)
|
||||
expected_url = f"{SUPABASE_URL}/storage/v1/object/public/{SUPABASE_S3_LOGS_BUCKET}/{trace_id}.log"
|
||||
assert response.url == expected_url
|
||||
|
||||
# Verify S3 upload was called with correct parameters
|
||||
mock_s3_client.upload_fileobj.assert_called_once()
|
||||
args = mock_s3_client.upload_fileobj.call_args[0]
|
||||
assert isinstance(args[0], BytesIO)
|
||||
assert args[1] == SUPABASE_S3_LOGS_BUCKET
|
||||
assert args[2] == f"{trace_id}.log"
|
||||
|
||||
def test_missing_trace_id(self, mock_jwt_payload, mock_request):
|
||||
"""Test that missing trace ID raises appropriate error"""
|
||||
view = LogsUploadView(mock_request)
|
||||
view.token = mock_jwt_payload
|
||||
|
||||
# Remove Trace-Id header while keeping others
|
||||
mock_request.headers = {k: v for k, v in mock_request.headers.items() if k != "Trace-Id"}
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
_ = view.filename
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "No trace ID provided" in exc_info.value.detail
|
||||
|
||||
def test_invalid_trace_id_characters(self, mock_jwt_payload, mock_request):
|
||||
"""Test that invalid characters in trace ID are rejected"""
|
||||
view = LogsUploadView(mock_request)
|
||||
view.token = mock_jwt_payload
|
||||
|
||||
# Trace ID with invalid characters
|
||||
invalid_trace_ids = ["trace@123", "trace#456", "trace 789", "trace/abc", "trace\\def"]
|
||||
|
||||
for invalid_id in invalid_trace_ids:
|
||||
mock_request.headers.update({"Trace-Id": invalid_id})
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
_ = view.filename
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_400_BAD_REQUEST
|
||||
assert "Trace ID contains invalid characters" in exc_info.value.detail
|
||||
|
||||
def test_valid_trace_id_characters(self, mock_jwt_payload, mock_request):
|
||||
"""Test that valid trace IDs are accepted"""
|
||||
view = LogsUploadView(mock_request)
|
||||
view.token = mock_jwt_payload
|
||||
|
||||
valid_trace_ids = [
|
||||
"trace123",
|
||||
"trace-456",
|
||||
"trace_789",
|
||||
"trace.abc",
|
||||
"trace-123_456.def",
|
||||
"TRACE-UPPER-123",
|
||||
]
|
||||
|
||||
for valid_id in valid_trace_ids:
|
||||
mock_request.headers.update({"Trace-Id": valid_id})
|
||||
assert view.filename == f"{valid_id}.log"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_file_size_limit_enforcement(self, mock_jwt_payload, mock_request):
|
||||
"""Test that file size limits are enforced for log uploads"""
|
||||
view = LogsUploadView(mock_request)
|
||||
view.max_size = 100 # Set small limit for testing
|
||||
|
||||
mock_request.headers.update({"Trace-Id": "test-trace"})
|
||||
|
||||
# Mock request stream with oversized content
|
||||
large_content = b'x' * 150 # Exceeds 100 byte limit
|
||||
|
||||
async def async_stream_generator():
|
||||
for chunk in [large_content]:
|
||||
yield chunk
|
||||
|
||||
mock_request.stream = lambda: async_stream_generator()
|
||||
|
||||
with patch('agentops.auth.views.API_URL', 'http://localhost:8000'): # Bypass validation
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await view(token=mock_jwt_payload)
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_413_REQUEST_ENTITY_TOO_LARGE
|
||||
assert "File size exceeds the maximum limit" in exc_info.value.detail
|
||||
|
||||
|
||||
class TestGetTraceLogs:
|
||||
"""Tests for the get_trace_logs endpoint"""
|
||||
|
||||
def test_convert_trace_id_hex_to_int(self):
|
||||
"""Test conversion of hex trace IDs to integers"""
|
||||
# Hex strings should be converted
|
||||
assert convert_trace_id("1a2b3c") == str(int("1a2b3c", 16))
|
||||
assert convert_trace_id("ABCDEF") == str(int("ABCDEF", 16))
|
||||
assert convert_trace_id("123abc") == str(int("123abc", 16))
|
||||
|
||||
# Pure numeric strings should remain unchanged
|
||||
assert convert_trace_id("123456") == "123456"
|
||||
|
||||
# Invalid hex should remain unchanged
|
||||
assert convert_trace_id("invalid") == "invalid"
|
||||
assert convert_trace_id("123xyz") == "123xyz"
|
||||
|
||||
def test_convert_trace_id_edge_cases(self):
|
||||
"""Test edge cases for trace ID conversion"""
|
||||
# Empty string
|
||||
assert convert_trace_id("") == ""
|
||||
|
||||
# Mixed case hex
|
||||
assert convert_trace_id("1A2b3C") == str(int("1A2b3C", 16))
|
||||
|
||||
# Long hex string
|
||||
long_hex = "abcdef1234567890"
|
||||
assert convert_trace_id(long_hex) == str(int(long_hex, 16))
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_trace_logs_successful_retrieval(self, mock_s3_client):
|
||||
"""Test successful log retrieval for valid trace"""
|
||||
trace_id = "test-trace-123"
|
||||
log_content = "INFO: Test log entry\nERROR: Test error"
|
||||
|
||||
# Mock S3 response
|
||||
mock_response = {'Body': MagicMock()}
|
||||
mock_response['Body'].read.return_value = log_content.encode('utf-8')
|
||||
mock_s3_client.get_object.return_value = mock_response
|
||||
|
||||
# Mock request with session
|
||||
mock_request = MagicMock()
|
||||
mock_request.state.session.user_id = "user-123"
|
||||
|
||||
# Mock ORM session
|
||||
mock_orm = MagicMock()
|
||||
|
||||
# Mock trace model
|
||||
with (
|
||||
patch('agentops.api.routes.v4.logs.TraceModel') as mock_trace_model,
|
||||
patch('agentops.api.routes.v4.logs.ProjectModel') as mock_project_model,
|
||||
patch('agentops.api.routes.v4.logs.get_s3_client', return_value=mock_s3_client),
|
||||
):
|
||||
# Setup trace mock with AsyncMock
|
||||
mock_trace = MagicMock()
|
||||
mock_trace.spans = ["span1", "span2"] # Non-empty spans
|
||||
mock_trace.project_id = "project-123"
|
||||
mock_trace_model.select = AsyncMock(return_value=mock_trace)
|
||||
|
||||
# Setup project mock
|
||||
mock_project = MagicMock()
|
||||
mock_project.is_freeplan = False
|
||||
mock_project.org.is_user_member.return_value = True
|
||||
mock_project_model.get_by_id.return_value = mock_project
|
||||
|
||||
response = await get_trace_logs(request=mock_request, orm=mock_orm, trace_id=trace_id)
|
||||
|
||||
# Function is decorated with @add_cors_headers which wraps it in JSONResponse
|
||||
assert hasattr(response, 'body')
|
||||
# Extract the JSON data from the response
|
||||
import json
|
||||
response_data = json.loads(response.body.decode())
|
||||
assert response_data['content'] == log_content
|
||||
assert response_data['trace_id'] == trace_id
|
||||
assert not response_data['freeplan_truncated']
|
||||
|
||||
# Verify S3 was called with converted trace ID
|
||||
mock_s3_client.get_object.assert_called_once_with(
|
||||
Bucket=SUPABASE_S3_LOGS_BUCKET, Key=f"{trace_id}.log"
|
||||
)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_trace_logs_nonexistent_trace(self):
|
||||
"""Test error when trace doesn't exist"""
|
||||
trace_id = "nonexistent-trace"
|
||||
|
||||
mock_request = MagicMock()
|
||||
mock_orm = MagicMock()
|
||||
|
||||
with patch('agentops.api.routes.v4.logs.TraceModel') as mock_trace_model:
|
||||
# Mock empty trace (no spans)
|
||||
mock_trace = MagicMock()
|
||||
mock_trace.spans = [] # Empty spans indicate no trace
|
||||
mock_trace_model.select = AsyncMock(return_value=mock_trace)
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await get_trace_logs(request=mock_request, orm=mock_orm, trace_id=trace_id)
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_403_FORBIDDEN
|
||||
assert "You do not have access to this trace" in exc_info.value.detail
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_trace_logs_no_permission(self):
|
||||
"""Test error when user doesn't have access to trace"""
|
||||
trace_id = "restricted-trace"
|
||||
|
||||
mock_request = MagicMock()
|
||||
mock_request.state.session.user_id = "user-123"
|
||||
mock_orm = MagicMock()
|
||||
|
||||
with (
|
||||
patch('agentops.api.routes.v4.logs.TraceModel') as mock_trace_model,
|
||||
patch('agentops.api.routes.v4.logs.ProjectModel') as mock_project_model,
|
||||
):
|
||||
# Setup trace mock
|
||||
mock_trace = MagicMock()
|
||||
mock_trace.spans = ["span1"] # Non-empty spans
|
||||
mock_trace.project_id = "project-123"
|
||||
mock_trace_model.select = AsyncMock(return_value=mock_trace)
|
||||
|
||||
# Setup project mock - user is not a member
|
||||
mock_project = MagicMock()
|
||||
mock_project.org.is_user_member.return_value = False
|
||||
mock_project_model.get_by_id.return_value = mock_project
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await get_trace_logs(request=mock_request, orm=mock_orm, trace_id=trace_id)
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_403_FORBIDDEN
|
||||
assert "You do not have access to this trace" in exc_info.value.detail
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_trace_logs_s3_file_not_found(self, mock_s3_client):
|
||||
"""Test error when log file doesn't exist in S3"""
|
||||
trace_id = "trace-without-logs"
|
||||
|
||||
# Mock S3 to raise NoSuchKey exception
|
||||
mock_s3_client.get_object.side_effect = mock_s3_client.exceptions.NoSuchKey()
|
||||
|
||||
mock_request = MagicMock()
|
||||
mock_request.state.session.user_id = "user-123"
|
||||
mock_orm = MagicMock()
|
||||
|
||||
with (
|
||||
patch('agentops.api.routes.v4.logs.TraceModel') as mock_trace_model,
|
||||
patch('agentops.api.routes.v4.logs.ProjectModel') as mock_project_model,
|
||||
patch('agentops.api.routes.v4.logs.get_s3_client', return_value=mock_s3_client),
|
||||
):
|
||||
# Setup valid trace and project
|
||||
mock_trace = MagicMock()
|
||||
mock_trace.spans = ["span1"]
|
||||
mock_trace.project_id = "project-123"
|
||||
mock_trace_model.select = AsyncMock(return_value=mock_trace)
|
||||
|
||||
mock_project = MagicMock()
|
||||
mock_project.org.is_user_member.return_value = True
|
||||
mock_project_model.get_by_id.return_value = mock_project
|
||||
|
||||
with pytest.raises(HTTPException) as exc_info:
|
||||
await get_trace_logs(request=mock_request, orm=mock_orm, trace_id=trace_id)
|
||||
|
||||
assert exc_info.value.status_code == status.HTTP_404_NOT_FOUND
|
||||
assert f"No logs found for trace ID: {trace_id}" in exc_info.value.detail
|
||||
@@ -0,0 +1,137 @@
|
||||
from datetime import datetime
|
||||
from unittest.mock import MagicMock, patch, AsyncMock
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
"""
|
||||
"this is a feature not a bug" LMAO
|
||||
"""
|
||||
|
||||
|
||||
# FIXME: Remove test skip after https://github.com/AgentOps-AI/agentops/issues/820
|
||||
pytestmark = [pytest.mark.skip]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_metrics_dual_endpoints(async_test_client, valid_jwt):
|
||||
"""
|
||||
Test that both /metrics and /meterics endpoints return the same response.
|
||||
This verifies our dual endpoint feature works correctly.
|
||||
|
||||
Note: This test just verifies that both endpoints exist and return the same response.
|
||||
It's not testing the actual metrics functionality, just the routing.
|
||||
"""
|
||||
# Mock token verification
|
||||
with patch('agentops.api.auth.get_jwt_token', return_value={'project_id': 'test-project'}):
|
||||
# Test the /metrics endpoint
|
||||
metrics_response = await async_test_client.get(
|
||||
"/v4/metrics/test", headers={"Authorization": f"Bearer {valid_jwt}"}
|
||||
)
|
||||
|
||||
# Test the /meterics endpoint
|
||||
meterics_response = await async_test_client.get(
|
||||
"/v4/meterics/test", headers={"Authorization": f"Bearer {valid_jwt}"}
|
||||
)
|
||||
|
||||
# Verify both endpoints return the same status code
|
||||
assert metrics_response.status_code == meterics_response.status_code
|
||||
|
||||
# Verify both endpoints return the same response
|
||||
assert metrics_response.json() == meterics_response.json()
|
||||
|
||||
# Verify the response content
|
||||
assert metrics_response.json() == {"message": "Test endpoint working"}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_metrics_other_endpoints_dual_behavior(async_test_client, valid_jwt):
|
||||
"""
|
||||
Test that other metrics endpoints like /trace/{trace_id} are also
|
||||
accessible via both /metrics and /meterics paths.
|
||||
|
||||
This test mocks the database calls to isolate the routing functionality.
|
||||
"""
|
||||
# Mock data
|
||||
trace_id = "1234567890abcdef"
|
||||
# Create proper datetime objects for the timestamps
|
||||
start_time = datetime(2023, 1, 1, 0, 0, 0)
|
||||
end_time = datetime(2023, 1, 1, 0, 0, 1)
|
||||
|
||||
mock_data = [
|
||||
{
|
||||
"SpanId": "span1",
|
||||
"TraceId": trace_id,
|
||||
"SpanName": "test-span",
|
||||
"ServiceName": "test-service",
|
||||
"Duration": 100000000, # duration in nanoseconds
|
||||
"SpanAttributes": {
|
||||
"gen_ai.usage.prompt_tokens": 10,
|
||||
"gen_ai.usage.completion_tokens": 20,
|
||||
"gen_ai.usage.total_tokens": 30,
|
||||
"gen_ai.request.model": "test-model",
|
||||
"gen_ai.system": "test-system",
|
||||
},
|
||||
"ResourceAttributes": {"agentops.project.id": "test-project"},
|
||||
"StartTime": start_time, # Use datetime object instead of string
|
||||
"EndTime": end_time, # Use datetime object instead of string
|
||||
}
|
||||
]
|
||||
|
||||
# Create a completely mocked response for the async clickhouse client
|
||||
mock_result = MagicMock()
|
||||
mock_result.named_results.return_value = mock_data
|
||||
|
||||
# Set up AsyncMock for query method
|
||||
mock_query = AsyncMock(return_value=mock_result)
|
||||
|
||||
# Create patches for token and query building
|
||||
token_patch = patch('agentops.api.auth.get_jwt_token', return_value={'project_id': 'test-project'})
|
||||
query_patch = patch(
|
||||
'agentops.api.routes.v4.metrics.queries.build_span_metrics_query',
|
||||
return_value=("SELECT mock_query", {"trace_id": trace_id}),
|
||||
)
|
||||
|
||||
# Patch the token_metrics and duration_metrics calculation functions
|
||||
token_metrics_patch = patch(
|
||||
'agentops.api.routes.v4.metrics.utils.calculate_token_metrics',
|
||||
return_value={"token_usage": 100, "model_usage": {}, "system_usage": {}},
|
||||
)
|
||||
duration_metrics_patch = patch(
|
||||
'agentops.api.routes.v4.metrics.utils.calculate_duration_metrics',
|
||||
return_value={
|
||||
"start_time": start_time.isoformat(),
|
||||
"end_time": end_time.isoformat(),
|
||||
"total_duration_ns": 100000000,
|
||||
},
|
||||
)
|
||||
|
||||
# This is the critical part - directly patch the clickhouse query method in the route
|
||||
query_method_patch = patch('clickhouse_connect.driver.asyncclient.AsyncClient.query', mock_query)
|
||||
|
||||
with token_patch, query_patch, query_method_patch, token_metrics_patch, duration_metrics_patch:
|
||||
# Test the /metrics/trace/{trace_id} endpoint
|
||||
metrics_response = await async_test_client.get(
|
||||
f"/v4/metrics/trace/{trace_id}", headers={"Authorization": f"Bearer {valid_jwt}"}
|
||||
)
|
||||
|
||||
# Test the /meterics/trace/{trace_id} endpoint
|
||||
meterics_response = await async_test_client.get(
|
||||
f"/v4/meterics/trace/{trace_id}", headers={"Authorization": f"Bearer {valid_jwt}"}
|
||||
)
|
||||
|
||||
# Verify both endpoints return the same status code
|
||||
assert metrics_response.status_code == meterics_response.status_code
|
||||
|
||||
# Both endpoints should return the same response
|
||||
assert metrics_response.json() == meterics_response.json()
|
||||
|
||||
# Verify the mock was called
|
||||
assert (
|
||||
mock_query.call_count >= 2
|
||||
), "The ClickHouse query method should be called at least twice (once for each endpoint)"
|
||||
|
||||
# If the status is 404, ensure that both endpoints return the same error message
|
||||
if metrics_response.status_code == 404:
|
||||
assert "not_found" in metrics_response.json()["detail"]["error"]
|
||||
assert trace_id in metrics_response.json()["detail"]["message"]
|
||||
@@ -0,0 +1,153 @@
|
||||
"""
|
||||
Tests for v4 objects API endpoints including ObjectUploadView.
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from io import BytesIO
|
||||
from unittest.mock import patch, MagicMock, AsyncMock
|
||||
from fastapi import Request
|
||||
|
||||
from agentops.api.routes.v4.objects import ObjectUploadView
|
||||
from agentops.api.storage import ObjectUploadResponse
|
||||
from agentops.api.environment import SUPABASE_S3_BUCKET
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_jwt_payload():
|
||||
"""Mock JWT payload for testing"""
|
||||
return {
|
||||
'project_id': 'test-project-123',
|
||||
'project_prem_status': 'premium',
|
||||
'api_key': 'test-api-key',
|
||||
'aud': 'authenticated',
|
||||
'exp': 1234567890,
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_s3_client():
|
||||
"""Mock S3 client for testing"""
|
||||
client = MagicMock()
|
||||
client.upload_fileobj = MagicMock()
|
||||
return client
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_request():
|
||||
"""Mock FastAPI Request for testing"""
|
||||
request = MagicMock(spec=Request)
|
||||
|
||||
# Create a proper async iterator for the stream method
|
||||
async def async_stream_generator(chunks):
|
||||
for chunk in chunks:
|
||||
yield chunk
|
||||
|
||||
# Default stream that will be overridden in individual tests
|
||||
request.stream = AsyncMock(return_value=async_stream_generator([]))
|
||||
|
||||
# Add required headers for public route validation
|
||||
request.headers = {
|
||||
"x-forwarded-for": "192.168.0.1",
|
||||
"x-forwarded-host": "api.agentops.ai",
|
||||
"origin": "https://app.agentops.ai",
|
||||
"referer": "https://app.agentops.ai/signin",
|
||||
"user-agent": "Mozilla/5.0 Chrome/91.0.4472.124",
|
||||
}
|
||||
return request
|
||||
|
||||
|
||||
class TestObjectUploadView:
|
||||
"""Tests for the ObjectUploadView class"""
|
||||
|
||||
def test_bucket_name_configuration(self, mock_request):
|
||||
"""Test that ObjectUploadView has correct bucket configuration"""
|
||||
view = ObjectUploadView(mock_request)
|
||||
assert view.bucket_name == SUPABASE_S3_BUCKET
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_successful_object_upload(self, mock_jwt_payload, mock_s3_client, mock_request):
|
||||
"""Test successful object upload with generated filename"""
|
||||
view = ObjectUploadView(mock_request)
|
||||
|
||||
# Mock request stream
|
||||
test_content = b'{"key": "value", "data": [1, 2, 3]}'
|
||||
|
||||
async def async_stream_generator():
|
||||
for chunk in [test_content]:
|
||||
yield chunk
|
||||
|
||||
mock_request.stream = lambda: async_stream_generator()
|
||||
|
||||
with (
|
||||
patch('agentops.api.storage.get_s3_client', return_value=mock_s3_client),
|
||||
patch('agentops.auth.views.API_URL', 'http://localhost:8000'),
|
||||
): # Bypass validation
|
||||
response = await view(token=mock_jwt_payload)
|
||||
|
||||
assert isinstance(response, ObjectUploadResponse)
|
||||
assert response.size == len(test_content)
|
||||
|
||||
# Verify the URL contains the project ID and UUID format
|
||||
assert f"/{SUPABASE_S3_BUCKET}/test-project-123/" in response.url
|
||||
|
||||
# Verify S3 upload was called
|
||||
mock_s3_client.upload_fileobj.assert_called_once()
|
||||
args = mock_s3_client.upload_fileobj.call_args[0]
|
||||
assert isinstance(args[0], BytesIO)
|
||||
assert args[1] == SUPABASE_S3_BUCKET
|
||||
|
||||
def test_filename_generation_uniqueness(self, mock_jwt_payload, mock_request):
|
||||
"""Test that filename generation includes project ID and UUID"""
|
||||
view = ObjectUploadView(mock_request)
|
||||
view.token = mock_jwt_payload
|
||||
|
||||
filename = view.filename
|
||||
|
||||
# Should start with project ID
|
||||
assert filename.startswith("test-project-123/")
|
||||
|
||||
# Should have UUID format after the slash
|
||||
uuid_part = filename.split('/', 1)[1]
|
||||
# UUID4 hex is 32 characters
|
||||
assert len(uuid_part) == 32
|
||||
# Should be valid hex
|
||||
assert all(c in '0123456789abcdef' for c in uuid_part)
|
||||
|
||||
def test_filename_caching(self, mock_jwt_payload, mock_request):
|
||||
"""Test that filename is cached and doesn't change between calls"""
|
||||
view = ObjectUploadView(mock_request)
|
||||
view.token = mock_jwt_payload
|
||||
|
||||
# First call
|
||||
filename1 = view.filename
|
||||
# Second call should return the same value
|
||||
filename2 = view.filename
|
||||
|
||||
assert filename1 == filename2
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_chunked_object_upload(self, mock_jwt_payload, mock_s3_client, mock_request):
|
||||
"""Test that chunked uploads work correctly for objects"""
|
||||
view = ObjectUploadView(mock_request)
|
||||
|
||||
# Mock request stream with multiple chunks
|
||||
chunks = [b'{"part1":', b'"data",', b'"part2":123}']
|
||||
|
||||
async def async_stream_generator():
|
||||
for chunk in chunks:
|
||||
yield chunk
|
||||
|
||||
mock_request.stream = lambda: async_stream_generator()
|
||||
|
||||
with (
|
||||
patch('agentops.api.storage.get_s3_client', return_value=mock_s3_client),
|
||||
patch('agentops.auth.views.API_URL', 'http://localhost:8000'),
|
||||
): # Bypass validation
|
||||
response = await view(token=mock_jwt_payload)
|
||||
|
||||
assert response.size == sum(len(chunk) for chunk in chunks)
|
||||
|
||||
# Verify the complete content was uploaded
|
||||
uploaded_content = mock_s3_client.upload_fileobj.call_args[0][0]
|
||||
uploaded_content.seek(0)
|
||||
assert uploaded_content.read() == b''.join(chunks)
|
||||
@@ -0,0 +1,63 @@
|
||||
import pytest
|
||||
|
||||
|
||||
EXPECTED_TABLES = [
|
||||
"otel_logs",
|
||||
"otel_metrics",
|
||||
"otel_metrics_exponential_histogram",
|
||||
"otel_metrics_gauge",
|
||||
"otel_metrics_histogram",
|
||||
"otel_metrics_sum",
|
||||
"otel_metrics_summary",
|
||||
"otel_raw_traces",
|
||||
"otel_raw_traces_trace_id_ts",
|
||||
"otel_traces",
|
||||
"otel_traces_0403251619",
|
||||
"otel_traces_legacy",
|
||||
"otel_traces_trace_id_ts",
|
||||
"otel_traces_with_project",
|
||||
"otel_traces_with_supabase_project_id",
|
||||
"otel_raw_traces_trace_id_ts_mv",
|
||||
"otel_traces_project_idx",
|
||||
"otel_traces_trace_id_ts_mv",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_all_tables(clickhouse_client):
|
||||
"""Test that lists all available tables in the ClickHouse database."""
|
||||
query = f"""
|
||||
SELECT
|
||||
name
|
||||
FROM
|
||||
system.tables
|
||||
WHERE
|
||||
database = '{clickhouse_client.database}' AND NOT startsWith(name, '.inner_id')
|
||||
ORDER BY
|
||||
name
|
||||
"""
|
||||
|
||||
result = clickhouse_client.query(query)
|
||||
tables = [row[0] for row in result.result_rows]
|
||||
|
||||
assert sorted(tables) == sorted(EXPECTED_TABLES), "ClickHouse tables do not match expected list"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_all_tables_async(async_clickhouse_client):
|
||||
"""Test that lists all available tables in the ClickHouse database using async client."""
|
||||
query = f"""
|
||||
SELECT
|
||||
name
|
||||
FROM
|
||||
system.tables
|
||||
WHERE
|
||||
database = '{async_clickhouse_client.client.database}' AND NOT startsWith(name, '.inner_id')
|
||||
ORDER BY
|
||||
name
|
||||
"""
|
||||
|
||||
result = await async_clickhouse_client.query(query)
|
||||
tables = [row[0] for row in result.result_rows]
|
||||
|
||||
assert sorted(tables) == sorted(EXPECTED_TABLES), "ClickHouse tables do not match expected list"
|
||||
Reference in New Issue
Block a user