Buckets:

download
raw
28.8 kB
"""Unit tests for the YaaiClient SDK."""
import uuid
import httpx
import pytest
from yaai.client import YaaiClient
from yaai.schemas.model import SchemaFieldCreate
@pytest.fixture
def mock_transport():
"""Create a mock transport that returns predefined responses."""
return MockTransport()
class MockTransport(httpx.AsyncBaseTransport):
"""Custom httpx transport that records requests and serves canned responses."""
def __init__(self):
self.requests: list[httpx.Request] = []
self.responses: dict[str, tuple[int, dict]] = {}
def add_response(self, method: str, path: str, status: int, json_body: dict):
key = f"{method.upper()} {path}"
self.responses[key] = (status, json_body)
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
self.requests.append(request)
key = f"{request.method} {request.url.raw_path.decode()}"
if key in self.responses:
status, body = self.responses[key]
return httpx.Response(status, json=body, request=request)
# Default: 404
return httpx.Response(404, json={"detail": "Not found"}, request=request)
def _make_client(transport: MockTransport, api_key: str = "yaam_test") -> YaaiClient:
"""Create a YaaiClient using a mock transport."""
client = YaaiClient.__new__(YaaiClient)
client._credentials = None
client._google_request = None
client._base_url = ""
client._client = httpx.AsyncClient(transport=transport, base_url="http://test", headers={"X-API-Key": api_key})
return client
class TestClientInit:
def test_init_with_api_key(self):
client = YaaiClient("http://localhost:8000/api/v1", api_key="yaam_test")
assert client._client.headers.get("X-API-Key") == "yaam_test"
assert client._credentials is None
def test_init_with_custom_timeout(self):
client = YaaiClient("http://localhost:8000/api/v1", api_key="yaam_test", timeout=60.0)
assert client._client.timeout.read == 60.0
assert client._client.timeout.connect == 60.0
assert client._client.timeout.write == 60.0
assert client._client.timeout.pool == 60.0
def test_init_default_timeout(self):
client = YaaiClient("http://localhost:8000/api/v1", api_key="yaam_test")
assert client._client.timeout.read == 30.0
def test_init_strips_trailing_slash(self):
client = YaaiClient("http://localhost:8000/api/v1/", api_key="yaam_test")
assert client._base_url == "http://localhost:8000/api/v1"
def test_init_without_api_key_and_no_google_auth_raises(self):
# google-auth is available in the test environment (server dependency),
# so we mock it away to verify the ImportError fallback path.
import unittest.mock
with unittest.mock.patch.dict("sys.modules", {"google.auth": None, "google.auth.transport.requests": None}):
with pytest.raises(ImportError, match="google-auth"):
YaaiClient("http://localhost:8000/api/v1")
def test_init_with_target_audience_uses_id_token_helper_for_service_accounts(self):
import unittest.mock
class ServiceAccountIDTokenCredentials:
def __init__(self):
self.valid = True
self.token = None
def refresh(self, request):
self.token = "service-account-id-token" # noqa: S105
request = object()
id_token_credentials = ServiceAccountIDTokenCredentials()
with (
unittest.mock.patch("google.auth.transport.requests.Request", return_value=request),
unittest.mock.patch("google.auth.default", return_value=(object(), None)),
unittest.mock.patch(
"google.oauth2.id_token.fetch_id_token_credentials",
return_value=id_token_credentials,
) as mock_fetch,
):
client = YaaiClient("http://localhost:8000/api/v1", target_audience="https://yaai.example.com")
mock_fetch.assert_called_once_with("https://yaai.example.com", request=request)
assert client._credentials is id_token_credentials
assert client._client.headers.get("Authorization") == "Bearer service-account-id-token"
def test_init_with_target_audience_falls_back_to_user_id_token(self):
import unittest.mock
from google.auth import exceptions as google_auth_exceptions
class UserCredentials:
def __init__(self):
self.valid = True
self.token = "access-token" # noqa: S105
self.id_token = None
def refresh(self, request):
self.id_token = "user-id-token" # noqa: S105
request = object()
user_credentials = UserCredentials()
with (
unittest.mock.patch("google.auth.transport.requests.Request", return_value=request),
unittest.mock.patch("google.auth.default", return_value=(user_credentials, None)),
unittest.mock.patch(
"google.oauth2.id_token.fetch_id_token_credentials",
side_effect=google_auth_exceptions.DefaultCredentialsError("no metadata"),
),
):
client = YaaiClient("http://localhost:8000/api/v1", target_audience="https://yaai.example.com")
assert client._credentials is user_credentials
assert client._client.headers.get("Authorization") == "Bearer user-id-token"
class TestClientModels:
async def test_create_model(self):
transport = MockTransport()
model_id = str(uuid.uuid4())
transport.add_response(
"POST",
"/models",
201,
{
"data": {
"id": model_id,
"name": "test-model",
"description": None,
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z",
"versions": [],
}
},
)
client = _make_client(transport)
result = await client.create_model("test-model")
assert result.name == "test-model"
assert str(result.id) == model_id
# Verify request was sent correctly
assert len(transport.requests) == 1
assert transport.requests[0].method == "POST"
async def test_get_model(self):
transport = MockTransport()
model_id = str(uuid.uuid4())
transport.add_response(
"GET",
f"/models/{model_id}",
200,
{
"data": {
"id": model_id,
"name": "fetched",
"description": "desc",
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z",
"versions": [],
}
},
)
client = _make_client(transport)
result = await client.get_model(uuid.UUID(model_id))
assert result.name == "fetched"
async def test_list_models(self):
transport = MockTransport()
transport.add_response(
"GET",
"/models",
200,
{
"data": [
{
"id": str(uuid.uuid4()),
"name": "m1",
"description": None,
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z",
"versions": [],
},
]
},
)
client = _make_client(transport)
result = await client.list_models()
assert len(result) == 1
assert result[0].name == "m1"
async def test_delete_model(self):
transport = MockTransport()
model_id = str(uuid.uuid4())
transport.add_response("DELETE", f"/models/{model_id}", 204, {})
client = _make_client(transport)
# Should not raise
await client.delete_model(uuid.UUID(model_id))
assert len(transport.requests) == 1
class TestClientInferences:
async def test_add_inference(self):
transport = MockTransport()
version_id = str(uuid.uuid4())
inf_id = str(uuid.uuid4())
transport.add_response(
"POST",
"/inferences",
201,
{
"data": {
"id": inf_id,
"model_version_id": version_id,
"inputs": {"age": 30},
"outputs": {"score": 0.8},
"timestamp": "2024-01-01T00:00:00Z",
"created_at": "2024-01-01T00:00:00Z",
}
},
)
client = _make_client(transport)
result = await client.add_inference(
uuid.UUID(version_id),
inputs={"age": 30},
outputs={"score": 0.8},
)
assert str(result.id) == inf_id
assert str(result.model_version_id) == version_id
async def test_add_inferences_batch(self):
transport = MockTransport()
version_id = str(uuid.uuid4())
transport.add_response("POST", "/inferences/batch", 201, {"data": {"ingested": 5, "failed": 0, "errors": []}})
client = _make_client(transport)
records = [{"inputs": {"x": i}, "outputs": {"y": i * 2}} for i in range(5)]
result = await client.add_inferences(uuid.UUID(version_id), records)
assert result.ingested == 5
assert result.failed == 0
class TestClientReferenceData:
async def test_add_reference_data(self):
transport = MockTransport()
model_id = str(uuid.uuid4())
version_id = str(uuid.uuid4())
transport.add_response(
"POST",
f"/models/{model_id}/versions/{version_id}/reference-data",
201,
{"data": {"ingested": 10, "model_version_id": version_id}},
)
client = _make_client(transport)
records = [{"inputs": {"x": i}, "outputs": {"y": i}} for i in range(10)]
result = await client.add_reference_data(uuid.UUID(model_id), uuid.UUID(version_id), records)
assert result.ingested == 10
class TestClientGroundTruth:
async def test_add_ground_truth(self):
transport = MockTransport()
inf_id = str(uuid.uuid4())
gt_id = str(uuid.uuid4())
transport.add_response("POST", "/ground-truth", 201, {"data": {"id": gt_id, "inference_id": inf_id}})
client = _make_client(transport)
result = await client.add_ground_truth(uuid.UUID(inf_id), label={"class": "fraud"})
assert result["id"] == gt_id
class TestClientJobs:
async def test_get_version_job(self):
transport = MockTransport()
model_id = str(uuid.uuid4())
version_id = str(uuid.uuid4())
job_id = str(uuid.uuid4())
transport.add_response(
"GET",
f"/models/{model_id}/versions/{version_id}/jobs",
200,
{
"data": [
{
"id": job_id,
"name": "daily-drift",
"schedule": "0 2 * * *",
"comparison_type": "vs_reference",
}
]
},
)
client = _make_client(transport)
result = await client.get_version_job(uuid.UUID(model_id), uuid.UUID(version_id))
assert result is not None
assert result["name"] == "daily-drift"
async def test_get_version_job_none(self):
transport = MockTransport()
model_id = str(uuid.uuid4())
version_id = str(uuid.uuid4())
transport.add_response("GET", f"/models/{model_id}/versions/{version_id}/jobs", 200, {"data": []})
client = _make_client(transport)
result = await client.get_version_job(uuid.UUID(model_id), uuid.UUID(version_id))
assert result is None
async def test_get_job(self):
transport = MockTransport()
job_id = str(uuid.uuid4())
transport.add_response("GET", f"/jobs/{job_id}", 200, {"data": {"id": job_id, "name": "daily-drift"}})
client = _make_client(transport)
result = await client.get_job(uuid.UUID(job_id))
assert result["id"] == job_id
async def test_update_job(self):
transport = MockTransport()
job_id = str(uuid.uuid4())
transport.add_response(
"PATCH",
f"/jobs/{job_id}",
200,
{"data": {"id": job_id, "name": "updated", "comparison_type": "rolling_window"}},
)
client = _make_client(transport)
result = await client.update_job(uuid.UUID(job_id), name="updated", comparison_type="rolling_window")
assert result["name"] == "updated"
assert result["comparison_type"] == "rolling_window"
async def test_trigger_job(self):
transport = MockTransport()
job_id = str(uuid.uuid4())
transport.add_response(
"POST", f"/jobs/{job_id}/trigger", 201, {"data": {"id": str(uuid.uuid4()), "status": "completed"}}
)
client = _make_client(transport)
result = await client.trigger_job(uuid.UUID(job_id))
assert result["status"] == "completed"
async def test_backfill_job(self):
transport = MockTransport()
job_id = str(uuid.uuid4())
transport.add_response("POST", f"/jobs/{job_id}/backfill", 201, {"data": {"runs_created": 4}})
client = _make_client(transport)
result = await client.backfill_job(uuid.UUID(job_id))
assert result["runs_created"] == 4
class TestClientErrorHandling:
async def test_raises_on_404(self):
transport = MockTransport()
client = _make_client(transport)
with pytest.raises(httpx.HTTPStatusError):
await client.get_model(uuid.uuid4())
async def test_raises_on_500(self):
transport = MockTransport()
transport.add_response("GET", "/models", 500, {"detail": "Internal error"})
client = _make_client(transport)
with pytest.raises(httpx.HTTPStatusError):
await client.list_models()
async def test_raises_on_non_json_error_response(self):
"""Client must raise HTTPStatusError even when the error body is not JSON."""
class HtmlErrorTransport(httpx.AsyncBaseTransport):
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
return httpx.Response(
502,
content=b"<html><body>Bad Gateway</body></html>",
headers={"content-type": "text/html"},
request=request,
)
client = _make_client(MockTransport())
client._client = httpx.AsyncClient(
transport=HtmlErrorTransport(), base_url="http://test", headers={"X-API-Key": "yaam_test"}
)
with pytest.raises(httpx.HTTPStatusError, match="502"):
await client.list_models()
async def test_raises_on_empty_error_response(self):
"""Client must raise HTTPStatusError even when the error body is empty."""
class EmptyErrorTransport(httpx.AsyncBaseTransport):
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
return httpx.Response(500, content=b"", request=request)
client = _make_client(MockTransport())
client._client = httpx.AsyncClient(
transport=EmptyErrorTransport(), base_url="http://test", headers={"X-API-Key": "yaam_test"}
)
with pytest.raises(httpx.HTTPStatusError, match="500"):
await client.list_models()
async def test_raises_on_409_conflict(self):
transport = MockTransport()
transport.add_response("POST", "/models", 409, {"detail": "Model with this name already exists"})
client = _make_client(transport)
with pytest.raises(httpx.HTTPStatusError, match="409.*Model with this name already exists"):
await client.create_model("duplicate")
def test_refresh_google_credentials_uses_token_when_id_token_attribute_is_missing(self):
class ServiceAccountIDTokenCredentials:
def __init__(self):
self.valid = False
self.token = "stale-token" # noqa: S105
def refresh(self, request):
self.valid = True
self.token = "fresh-id-token" # noqa: S105
transport = MockTransport()
client = _make_client(transport)
client._credentials = ServiceAccountIDTokenCredentials()
client._google_request = object()
client._client.headers.pop("X-API-Key")
client._refresh_google_credentials()
assert client._client.headers.get("Authorization") == "Bearer fresh-id-token"
class TestClientContextManager:
async def test_async_context_manager(self):
async with YaaiClient("http://localhost:8000", api_key="yaam_test") as client:
assert client._client is not None
# After exiting, client should be closed (aclose called)
class TestClientVersions:
async def test_get_version(self):
transport = MockTransport()
model_id = str(uuid.uuid4())
version_id = str(uuid.uuid4())
transport.add_response(
"GET",
f"/models/{model_id}/versions/{version_id}",
200,
{
"data": {
"id": version_id,
"model_id": model_id,
"version": "v1.0",
"description": None,
"is_active": True,
"created_at": "2024-01-01T00:00:00Z",
"schema_fields": [],
}
},
)
client = _make_client(transport)
result = await client.get_version(uuid.UUID(model_id), uuid.UUID(version_id))
assert result.version == "v1.0"
assert str(result.id) == version_id
async def test_get_or_create_version_existing(self):
"""When the version already exists, return it without creating."""
transport = MockTransport()
model_id = str(uuid.uuid4())
version_id = str(uuid.uuid4())
transport.add_response(
"GET",
f"/models/{model_id}",
200,
{
"data": {
"id": model_id,
"name": "my-model",
"description": None,
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z",
"versions": [
{
"id": version_id,
"version": "v1.0",
"is_active": True,
"created_at": "2024-01-01T00:00:00Z",
"schema_field_count": 3,
}
],
}
},
)
client = _make_client(transport)
# schema_fields is required, but ignored when the version already exists
result = await client.get_or_create_version(
uuid.UUID(model_id),
"v1.0",
schema_fields=[
SchemaFieldCreate(field_name="x", direction="input", data_type="numerical"),
],
)
assert result.version == "v1.0"
assert str(result.id) == version_id
# Only one request made (get_model), no create
assert len(transport.requests) == 1
async def test_get_or_create_version_creates_new(self):
"""When the version doesn't exist and sample_data is provided, create it."""
transport = MockTransport()
model_id = str(uuid.uuid4())
new_version_id = str(uuid.uuid4())
# get_model returns no versions
transport.add_response(
"GET",
f"/models/{model_id}",
200,
{
"data": {
"id": model_id,
"name": "my-model",
"description": None,
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z",
"versions": [],
}
},
)
# infer_schema
transport.add_response(
"POST",
"/schema/infer",
200,
{
"data": {
"schema_fields": [
{"field_name": "amount", "direction": "input", "data_type": "numerical"},
{"field_name": "fraud", "direction": "output", "data_type": "categorical"},
]
}
},
)
# create_model_version
transport.add_response(
"POST",
f"/models/{model_id}/versions",
201,
{
"data": {
"id": new_version_id,
"model_id": model_id,
"version": "v2.0",
"description": None,
"is_active": True,
"created_at": "2024-01-01T00:00:00Z",
"schema_fields": [
{
"id": str(uuid.uuid4()),
"field_name": "amount",
"direction": "input",
"data_type": "numerical",
},
{
"id": str(uuid.uuid4()),
"field_name": "fraud",
"direction": "output",
"data_type": "categorical",
},
],
}
},
)
client = _make_client(transport)
result = await client.get_or_create_version(
uuid.UUID(model_id),
"v2.0",
sample_data={"inputs": {"amount": 100.0}, "outputs": {"fraud": "false"}},
)
assert result.version == "v2.0"
assert str(result.id) == new_version_id
# Three requests: get_model, infer_schema, create_model_version
assert len(transport.requests) == 3
async def test_get_or_create_version_creates_new_with_schema_fields(self):
"""When the version doesn't exist and schema_fields is provided, create directly."""
transport = MockTransport()
model_id = str(uuid.uuid4())
new_version_id = str(uuid.uuid4())
# get_model returns no versions
transport.add_response(
"GET",
f"/models/{model_id}",
200,
{
"data": {
"id": model_id,
"name": "my-model",
"description": None,
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z",
"versions": [],
}
},
)
# create_model_version (no infer_schema call expected)
transport.add_response(
"POST",
f"/models/{model_id}/versions",
201,
{
"data": {
"id": new_version_id,
"model_id": model_id,
"version": "v3.0",
"description": None,
"is_active": True,
"created_at": "2024-01-01T00:00:00Z",
"schema_fields": [
{
"id": str(uuid.uuid4()),
"field_name": "amount",
"direction": "input",
"data_type": "numerical",
},
{
"id": str(uuid.uuid4()),
"field_name": "fraud",
"direction": "output",
"data_type": "categorical",
},
],
}
},
)
client = _make_client(transport)
result = await client.get_or_create_version(
uuid.UUID(model_id),
"v3.0",
schema_fields=[
SchemaFieldCreate(field_name="amount", direction="input", data_type="numerical"),
SchemaFieldCreate(field_name="fraud", direction="output", data_type="categorical"),
],
)
assert result.version == "v3.0"
assert str(result.id) == new_version_id
# Two requests: get_model, create_model_version (no infer_schema)
assert len(transport.requests) == 2
async def test_get_or_create_version_both_params_raises(self):
"""Passing both sample_data and schema_fields raises ValueError."""
transport = MockTransport()
client = _make_client(transport)
with pytest.raises(ValueError, match="mutually exclusive"):
await client.get_or_create_version(
uuid.uuid4(),
"v1.0",
sample_data={"inputs": {"x": 1}, "outputs": {"y": 2}},
schema_fields=[
SchemaFieldCreate(field_name="x", direction="input", data_type="numerical"),
],
)
# No requests should have been made
assert len(transport.requests) == 0
async def test_get_or_create_version_neither_param_raises(self):
"""Passing neither sample_data nor schema_fields raises eagerly."""
transport = MockTransport()
client = _make_client(transport)
with pytest.raises(ValueError, match="Either sample_data or schema_fields must be provided"):
await client.get_or_create_version(uuid.uuid4(), "v1.0")
# No requests should have been made — validated before hitting server
assert len(transport.requests) == 0
class TestClientGetVersionByLabel:
async def test_get_version_by_label_found(self):
"""Returns ModelVersionSummary when a matching version exists."""
transport = MockTransport()
model_id = str(uuid.uuid4())
version_id = str(uuid.uuid4())
transport.add_response(
"GET",
f"/models/{model_id}",
200,
{
"data": {
"id": model_id,
"name": "my-model",
"description": None,
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z",
"versions": [
{
"id": version_id,
"version": "v1.0",
"is_active": True,
"created_at": "2024-01-01T00:00:00Z",
"schema_field_count": 3,
}
],
}
},
)
client = _make_client(transport)
result = await client.get_version_by_label(uuid.UUID(model_id), "v1.0")
assert result is not None
assert result.version == "v1.0"
assert str(result.id) == version_id
async def test_get_version_by_label_not_found(self):
"""Returns None when no version matches the label."""
transport = MockTransport()
model_id = str(uuid.uuid4())
transport.add_response(
"GET",
f"/models/{model_id}",
200,
{
"data": {
"id": model_id,
"name": "my-model",
"description": None,
"created_at": "2024-01-01T00:00:00Z",
"updated_at": "2024-01-01T00:00:00Z",
"versions": [],
}
},
)
client = _make_client(transport)
result = await client.get_version_by_label(uuid.UUID(model_id), "v1.0")
assert result is None
class TestClientCredentialRefresh:
async def test_refresh_noop_when_no_credentials(self):
transport = MockTransport()
transport.add_response("GET", "/models", 200, {"data": []})
client = _make_client(transport)
# _refresh_google_credentials should be no-op
client._refresh_google_credentials()
result = await client.list_models()
assert result == []

Xet Storage Details

Size:
28.8 kB
·
Xet hash:
fb0ce0a696d8136a874ad08e662ed257d918c3b3888c19b00fbcb6aa83385ebc

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.