Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /pydantic_logfire /tests /test_datasets_client.py
"""Tests for logfire.experimental.datasets client achieving 100% coverage."""
# pyright: reportPrivateUsage=false, reportArgumentType=false, reportUnknownVariableType=false
from __future__ import annotations
import builtins
import json
import sys
import warnings
from dataclasses import dataclass
from datetime import datetime
from typing import Any, cast
from uuid import UUID
import httpx
import pytest
from pydantic import BaseModel
try:
from pydantic_evals import Case, Dataset
except Exception:
pytest.skip('pydantic_evals not compatible with this environment', allow_module_level=True)
from logfire.experimental.api_client import (
AsyncLogfireAPIClient,
CaseNotFoundError,
DatasetApiError,
DatasetNotFoundError,
LogfireAPIClient,
_build_push_dataset_kwargs,
_from_dict_compat,
_from_dict_supports_report_evaluators,
_get_dataset_type_args,
_serialize_case,
_serialize_evaluators,
_serialize_value,
_type_to_schema,
_validate_dataset_name,
)
# --- Test types ---
@dataclass
class MyInput:
question: str
@dataclass
class MyOutput:
answer: str
@dataclass
class MyMetadata:
source: str
class PydanticInput(BaseModel):
question: str
# --- Mock transport helpers ---
FAKE_DATASET = {
'id': '12345678-1234-5678-1234-567812345678',
'name': 'test-dataset',
'description': 'A test dataset',
'case_count': 0,
}
FAKE_CASE = {
'id': '87654321-4321-8765-4321-876543218765',
'name': 'test-case',
'inputs': {'question': 'What is 2+2?'},
'expected_output': {'answer': '4'},
}
# Responses are validated by the client, which coerces the string ``id`` to a
# ``UUID``. These are the expected post-coercion results to assert against.
EXPECTED_DATASET = {**FAKE_DATASET, 'id': UUID(FAKE_DATASET['id'])}
EXPECTED_CASE = {**FAKE_CASE, 'id': UUID(FAKE_CASE['id'])}
FAKE_EXPORT = {
'name': 'test-dataset',
'cases': [
{
'name': 'test-case',
'inputs': {'question': 'What is 2+2?'},
'expected_output': {'answer': '4'},
}
],
}
def make_local_dataset(name: str = 'local-dataset') -> Dataset[MyInput, MyOutput, MyMetadata]:
return Dataset[MyInput, MyOutput, MyMetadata](
name=name,
cases=[
Case(
name='local-case',
inputs=MyInput(question='What is 2+2?'),
expected_output=MyOutput(answer='4'),
metadata=MyMetadata(source='seed'),
)
],
)
def make_mock_transport(responses: dict[tuple[str, str], httpx.Response | None] | None = None) -> httpx.MockTransport:
"""Create a mock transport that maps (method, path) -> response."""
default_responses: dict[tuple[str, str], httpx.Response] = {
('GET', '/v1/datasets/'): httpx.Response(200, json=[FAKE_DATASET]),
('GET', '/v1/datasets/test-dataset/'): httpx.Response(200, json=FAKE_DATASET),
('POST', '/v1/datasets/'): httpx.Response(200, json=FAKE_DATASET),
('PATCH', '/v1/datasets/test-dataset/'): httpx.Response(200, json=FAKE_DATASET),
('DELETE', '/v1/datasets/test-dataset/'): httpx.Response(204),
('GET', '/v1/datasets/test-dataset/cases/'): httpx.Response(200, json=[FAKE_CASE]),
('GET', '/v1/datasets/test-dataset/cases/case-456/'): httpx.Response(200, json=FAKE_CASE),
('POST', '/v1/datasets/test-dataset/cases/bulk/'): httpx.Response(200, json=[FAKE_CASE]),
('POST', '/v1/datasets/test-dataset/import/'): httpx.Response(200, json=[FAKE_CASE]),
('PATCH', '/v1/datasets/test-dataset/cases/case-456/'): httpx.Response(200, json=FAKE_CASE),
('DELETE', '/v1/datasets/test-dataset/cases/case-456/'): httpx.Response(204),
('GET', '/v1/datasets/test-dataset/export/'): httpx.Response(200, json=FAKE_EXPORT),
}
if responses:
default_responses.update(responses) # type: ignore
all_responses = default_responses
def handler(request: httpx.Request) -> httpx.Response:
# Match on method and path (without query string)
key = (request.method, request.url.path)
if key in all_responses:
return all_responses[key]
return httpx.Response(404, json={'detail': 'Not found'})
return httpx.MockTransport(handler)
def make_client(
responses: dict[tuple[str, str], httpx.Response | None] | None = None,
) -> LogfireAPIClient:
transport = make_mock_transport(responses)
return LogfireAPIClient(
client=httpx.Client(transport=transport, base_url='https://test.logfire.dev'),
)
def make_async_client(
responses: dict[tuple[str, str], httpx.Response | None] | None = None,
) -> AsyncLogfireAPIClient:
transport = make_mock_transport(responses)
return AsyncLogfireAPIClient(
client=httpx.AsyncClient(transport=transport, base_url='https://test.logfire.dev'),
)
# =============================================================================
# Helper function tests
# =============================================================================
class TestTypeToSchema:
def test_none_returns_none(self):
assert _type_to_schema(None) is None
def test_dataclass(self):
schema = _type_to_schema(MyInput)
assert schema is not None
assert schema['type'] == 'object'
assert 'question' in schema['properties']
def test_pydantic_model(self):
schema = _type_to_schema(PydanticInput)
assert schema is not None
assert 'question' in schema['properties']
class TestSerializeValue:
def test_none_returns_none(self):
assert _serialize_value(None) is None
def test_dataclass(self):
result = _serialize_value(MyInput(question='hello'))
assert result == {'question': 'hello'}
def test_pydantic_model(self):
result = _serialize_value(PydanticInput(question='hello'))
assert result == {'question': 'hello'}
class TestSerializeEvaluators:
def test_pydantic_model_evaluator(self):
class MyEvaluator(BaseModel):
threshold: float = 0.5
@classmethod
def get_serialization_name(cls) -> str:
return 'MyEval'
result = _serialize_evaluators([MyEvaluator(threshold=0.8)])
assert result == [{'name': 'MyEval', 'arguments': {'threshold': 0.8}}]
def test_dataclass_evaluator(self):
@dataclass
class MyEvaluator:
threshold: float = 0.5
result = _serialize_evaluators([MyEvaluator(threshold=0.8)])
assert result == [{'name': 'MyEvaluator', 'arguments': {'threshold': 0.8}}]
def test_plain_object_evaluator(self):
"""An evaluator without model_dump or __dataclass_fields__ should have arguments=None."""
class SimpleEval:
pass
result = _serialize_evaluators([SimpleEval()])
assert result == [{'name': 'SimpleEval', 'arguments': None}]
def test_empty_arguments_become_none(self):
"""An evaluator with no fields should serialize arguments as None."""
@dataclass
class EmptyEval:
pass
result = _serialize_evaluators([EmptyEval()])
assert result == [{'name': 'EmptyEval', 'arguments': None}]
def test_evaluator_with_get_serialization_name(self):
@dataclass
class CustomNameEval:
@classmethod
def get_serialization_name(cls) -> str:
return 'custom-name'
result = _serialize_evaluators([CustomNameEval()])
assert result == [{'name': 'custom-name', 'arguments': None}]
def test_evaluator_without_get_serialization_name(self):
"""Falls back to __name__ when get_serialization_name is not defined."""
@dataclass
class FallbackEval:
score: float = 1.0
result = _serialize_evaluators([FallbackEval()])
assert result == [{'name': 'FallbackEval', 'arguments': {'score': 1.0}}]
class TestSerializeCase:
def test_minimal_case(self):
case: Case[MyInput, MyOutput, Any] = Case(inputs=MyInput(question='hi'))
result = _serialize_case(case)
assert result == {'inputs': {'question': 'hi'}, 'evaluators': []}
def test_none_evaluators(self):
case: Case[MyInput, MyOutput, Any] = Case(inputs=MyInput(question='hi'))
case.evaluators = None # type: ignore[assignment]
result = _serialize_case(case)
assert result == {'inputs': {'question': 'hi'}}
def test_full_case(self):
@dataclass
class MyEval:
pass
case: Case[MyInput, MyOutput, MyMetadata] = Case(
name='test',
inputs=MyInput(question='hi'),
expected_output=MyOutput(answer='hello'),
metadata=MyMetadata(source='manual'),
evaluators=[MyEval()],
)
result = _serialize_case(case)
assert result == {
'name': 'test',
'inputs': {'question': 'hi'},
'expected_output': {'answer': 'hello'},
'metadata': {'source': 'manual'},
'evaluators': [{'name': 'MyEval', 'arguments': None}],
}
def test_dict_inputs(self):
case: Case[dict[str, str], dict[str, str], Any] = Case(inputs={'question': 'hi'})
result = _serialize_case(case)
assert result == {'inputs': {'question': 'hi'}, 'evaluators': []}
def test_dict_expected_output(self):
case: Case[dict[str, str], dict[str, str], Any] = Case(
inputs={'q': 'hi'},
expected_output={'a': 'hello'},
)
result = _serialize_case(case)
assert result == {'inputs': {'q': 'hi'}, 'expected_output': {'a': 'hello'}, 'evaluators': []}
def test_dict_metadata(self):
case: Case[dict[str, str], Any, dict[str, str]] = Case(
inputs={'q': 'hi'},
metadata={'source': 'test'},
)
result = _serialize_case(case)
assert result == {'inputs': {'q': 'hi'}, 'metadata': {'source': 'test'}, 'evaluators': []}
class TestFromDictCompat:
"""`get_dataset` shim that lets the SDK keep working on pydantic-evals < 1.58.0."""
def test_supports_when_kwarg_present(self):
class Modern:
@classmethod
def from_dict(
cls,
data: dict[str, Any],
custom_evaluator_types: Any = (),
custom_report_evaluator_types: Any = (),
default_name: str | None = None,
) -> Any:
return ('called', data, list(custom_evaluator_types), list(custom_report_evaluator_types))
assert _from_dict_supports_report_evaluators(Modern) is True
def test_does_not_support_when_kwarg_absent(self):
class Legacy:
@classmethod
def from_dict(
cls, data: dict[str, Any], custom_evaluator_types: Any = (), default_name: str | None = None
) -> Any:
return ('legacy', data, list(custom_evaluator_types))
assert _from_dict_supports_report_evaluators(Legacy) is False
def test_returns_false_when_class_has_no_from_dict(self):
class NoFromDict:
pass
assert _from_dict_supports_report_evaluators(NoFromDict) is False
def test_returns_false_when_signature_inspection_fails(self):
class WeirdFromDict:
# Set `from_dict` to a built-in whose signature can't be introspected,
# so `inspect.signature` raises ValueError.
from_dict = staticmethod(min)
assert _from_dict_supports_report_evaluators(WeirdFromDict) is False
def test_modern_path_passes_through_kwarg(self):
captured: dict[str, Any] = {}
class Modern:
@classmethod
def from_dict(
cls, data: dict[str, Any], custom_evaluator_types: Any = (), custom_report_evaluator_types: Any = ()
) -> Any:
captured['custom_report_evaluator_types'] = list(custom_report_evaluator_types)
return ('ok', data)
result = _from_dict_compat(Modern, {'cases': [], 'report_evaluators': [{'name': 'X'}]}, [int], [str])
assert result == ('ok', {'cases': [], 'report_evaluators': [{'name': 'X'}]})
assert captured['custom_report_evaluator_types'] == [str]
def test_legacy_path_strips_report_evaluators_silently_when_empty(self):
seen: dict[str, Any] = {}
class Legacy:
@classmethod
def from_dict(cls, data: dict[str, Any], custom_evaluator_types: Any = ()) -> Any:
seen['data'] = data
return ('legacy', data)
with warnings.catch_warnings():
warnings.simplefilter('error')
# Empty report_evaluators should not warn, just get stripped.
_from_dict_compat(Legacy, {'cases': [], 'report_evaluators': []}, [], [])
assert 'report_evaluators' not in seen['data']
def test_legacy_path_warns_when_dropping_non_empty(self):
class Legacy:
@classmethod
def from_dict(cls, data: dict[str, Any], custom_evaluator_types: Any = ()) -> Any:
return data
with pytest.warns(UserWarning, match=r'pydantic-evals>=1\.58\.0'):
result = _from_dict_compat(
Legacy,
{'cases': [], 'report_evaluators': [{'name': 'PassRate'}]},
[],
[],
)
assert 'report_evaluators' not in result
class TestValidateDatasetName:
def test_valid_names(self):
# Should not raise
_validate_dataset_name('my-dataset')
_validate_dataset_name('dataset.v2')
_validate_dataset_name('a')
_validate_dataset_name('123')
_validate_dataset_name('test_dataset-1.0')
def test_invalid_names(self):
with pytest.raises(ValueError, match='Invalid dataset name'):
_validate_dataset_name('')
with pytest.raises(ValueError, match='Invalid dataset name'):
_validate_dataset_name('-starts-with-dash')
with pytest.raises(ValueError, match='Invalid dataset name'):
_validate_dataset_name('has spaces')
with pytest.raises(ValueError, match='Invalid dataset name'):
_validate_dataset_name('special/chars')
class TestPushDatasetHelpers:
def test_get_dataset_type_args_typed_dataset(self):
assert _get_dataset_type_args(make_local_dataset()) == (MyInput, MyOutput, MyMetadata)
def test_get_dataset_type_args_missing_metadata(self):
class DatasetLike:
__pydantic_generic_metadata__ = None
assert _get_dataset_type_args(cast(Any, DatasetLike())) == (None, None, None)
def test_get_dataset_type_args_non_tuple_args(self):
class DatasetLike:
__pydantic_generic_metadata__ = {'args': [MyInput, MyOutput, MyMetadata]}
assert _get_dataset_type_args(cast(Any, DatasetLike())) == (None, None, None)
def test_get_dataset_type_args_wrong_number_of_args(self):
dataset = Dataset(name='test-dataset', cases=[])
assert _get_dataset_type_args(cast(Any, dataset)) == (None, None, None)
def test_get_dataset_type_args_none_metadata(self):
"""`Dataset[..., None]` should map NoneType back to None so we don't emit a {"type": "null"} schema."""
dataset = Dataset[MyInput, MyOutput, None](name='test-dataset', cases=[])
assert _get_dataset_type_args(dataset) == (MyInput, MyOutput, None)
def test_get_dataset_type_args_normalizes_nonetype_args(self):
class DatasetLike:
__pydantic_generic_metadata__ = {'args': (type(None), type(None), type(None))}
assert _get_dataset_type_args(cast(Any, DatasetLike())) == (None, None, None)
def test_build_push_dataset_kwargs_minimal(self):
dataset = make_local_dataset()
create_kwargs, update_kwargs = _build_push_dataset_kwargs(
dataset=dataset, target_name='test-dataset', input_type=None, output_type=None, metadata_type=None
)
# `evaluators` / `report_evaluators` are always forwarded — empty sequences
# so a subsequent push that drops them locally also clears the hosted side.
# Serialization happens inside create_dataset / update_dataset.
assert create_kwargs['name'] == 'test-dataset'
assert list(create_kwargs['evaluators']) == []
assert list(create_kwargs['report_evaluators']) == []
assert list(update_kwargs['evaluators']) == []
assert list(update_kwargs['report_evaluators']) == []
def test_build_push_dataset_kwargs_forwards_dataset_and_report_evaluator_instances(self):
@dataclass
class DatasetEval:
threshold: float = 0.9
@dataclass
class ReportEval:
min_pass_rate: float = 0.5
dataset_eval = DatasetEval(threshold=0.95)
report_eval = ReportEval(min_pass_rate=0.8)
dataset = make_local_dataset()
dataset.evaluators = cast(Any, [dataset_eval])
dataset.report_evaluators = cast(Any, [report_eval])
create_kwargs, update_kwargs = _build_push_dataset_kwargs(
dataset=dataset, target_name='test-dataset', input_type=None, output_type=None, metadata_type=None
)
# The helper forwards raw instances; create_dataset / update_dataset do the
# serialization via `_serialize_evaluators`.
assert list(create_kwargs['evaluators']) == [dataset_eval]
assert list(create_kwargs['report_evaluators']) == [report_eval]
assert list(update_kwargs['evaluators']) == [dataset_eval]
assert list(update_kwargs['report_evaluators']) == [report_eval]
# =============================================================================
# Error class tests
# =============================================================================
class TestDatasetApiError:
def test_attributes(self):
err = DatasetApiError(422, {'detail': 'Validation error'})
assert err.status_code == 422
assert err.detail == {'detail': 'Validation error'}
assert 'API error 422' in str(err)
# =============================================================================
# _handle_response tests
# =============================================================================
class TestHandleResponse:
def _make_base_client(self):
return make_client()
def test_200_json(self):
client = self._make_base_client()
response = httpx.Response(200, json={'key': 'value'})
assert client._handle_response(response) == {'key': 'value'}
def test_204_returns_none(self):
client = self._make_base_client()
response = httpx.Response(204)
assert client._handle_response(response) is None
def test_404_dataset_not_found(self):
client = self._make_base_client()
response = httpx.Response(404, json={'detail': 'Dataset not found'})
with pytest.raises(DatasetNotFoundError):
client._handle_response(response)
def test_404_case_not_found(self):
client = self._make_base_client()
response = httpx.Response(404, json={'detail': 'Case not found'})
with pytest.raises(CaseNotFoundError):
client._handle_response(response, is_case_endpoint=True)
def test_404_case_endpoint_but_dataset_error(self):
"""When is_case_endpoint=True but response doesn't mention 'case', raise DatasetNotFoundError."""
client = self._make_base_client()
response = httpx.Response(404, json={'detail': 'Dataset not found'})
with pytest.raises(DatasetNotFoundError):
client._handle_response(response, is_case_endpoint=True)
def test_404_empty_content(self):
client = self._make_base_client()
response = httpx.Response(404)
with pytest.raises(DatasetNotFoundError, match='Not found'):
client._handle_response(response)
def test_400_with_json(self):
client = self._make_base_client()
response = httpx.Response(400, json={'detail': 'Bad request'})
with pytest.raises(DatasetApiError) as exc_info:
client._handle_response(response)
assert exc_info.value.status_code == 400
def test_500_with_text(self):
client = self._make_base_client()
response = httpx.Response(500, text='')
with pytest.raises(DatasetApiError) as exc_info:
client._handle_response(response)
assert exc_info.value.status_code == 500
def test_404_non_json_body(self):
"""Non-JSON 404 bodies should fall back to response text instead of raising JSONDecodeError."""
client = self._make_base_client()
response = httpx.Response(404, text='<html>Not Found</html>')
with pytest.raises(DatasetNotFoundError, match='Not Found'):
client._handle_response(response)
def test_400_non_json_body(self):
"""Non-JSON error bodies should fall back to response text instead of raising JSONDecodeError."""
client = self._make_base_client()
response = httpx.Response(502, text='<html>Bad Gateway</html>')
with pytest.raises(DatasetApiError) as exc_info:
client._handle_response(response)
assert exc_info.value.status_code == 502
def test_404_case_endpoint_non_dict_response(self):
"""When is_case_endpoint=True but the 404 response is a non-dict (e.g. string), raise DatasetNotFoundError."""
client = self._make_base_client()
response = httpx.Response(404, text='<html>Not Found</html>')
with pytest.raises(DatasetNotFoundError):
client._handle_response(response, is_case_endpoint=True)
# =============================================================================
# Sync client tests
# =============================================================================
class TestLogfireAPIClient:
def test_init_with_base_url(self):
client = LogfireAPIClient(api_key='test-key', base_url='https://custom.url')
assert str(client.client.base_url) == 'https://custom.url'
client.client.close()
def test_init_infers_base_url(self):
client = LogfireAPIClient(api_key='pylf_v1_us_test1234567890')
base_url = str(client.client.base_url)
assert 'logfire' in base_url or 'pydantic' in base_url
client.client.close()
def test_init_with_client(self):
httpx_client = httpx.Client(base_url='https://custom.url')
client = LogfireAPIClient(client=httpx_client)
assert client.client is httpx_client
client.client.close()
def test_init_requires_client_or_api_key(self):
with pytest.raises(ValueError, match='Either client or api_key must be provided'):
LogfireAPIClient()
def test_context_manager(self):
client = make_client()
with client as c:
assert c is client
# After exiting, the underlying httpx client is closed
def test_list_datasets(self):
client = make_client()
result = client.list_datasets()
assert result == [EXPECTED_DATASET]
def test_get_dataset(self):
client = make_client()
result = client.get_dataset('test-dataset', include_cases=False)
assert result == EXPECTED_DATASET
def test_create_dataset_minimal(self):
client = make_client()
result = client.create_dataset(name='test-dataset')
assert result == EXPECTED_DATASET
def test_create_dataset_full(self):
"""Test create_dataset with all optional parameters."""
requests_seen: list[httpx.Request] = []
def handler(request: httpx.Request) -> httpx.Response:
requests_seen.append(request)
return httpx.Response(200, json=FAKE_DATASET)
transport = httpx.MockTransport(handler)
client = LogfireAPIClient(api_key='test-key', base_url='https://test.logfire.dev')
client.client = httpx.Client(transport=transport, base_url='https://test.logfire.dev')
result = client.create_dataset(
name='test-dataset',
input_type=MyInput,
output_type=MyOutput,
metadata_type=MyMetadata,
description='A test dataset',
)
assert result == EXPECTED_DATASET
body = json.loads(requests_seen[0].content)
assert body['name'] == 'test-dataset'
assert body['description'] == 'A test dataset'
assert 'input_schema' in body
assert 'output_schema' in body
assert 'metadata_schema' in body
def test_update_dataset_minimal(self):
"""When no params change, only empty data is sent."""
client = make_client()
result = client.update_dataset('test-dataset')
assert result == EXPECTED_DATASET
def test_update_dataset_full(self):
requests_seen: list[httpx.Request] = []
def handler(request: httpx.Request) -> httpx.Response:
requests_seen.append(request)
return httpx.Response(200, json=FAKE_DATASET)
transport = httpx.MockTransport(handler)
client = LogfireAPIClient(api_key='test-key', base_url='https://test.logfire.dev')
client.client = httpx.Client(transport=transport, base_url='https://test.logfire.dev')
client.update_dataset(
'test-dataset',
name='new-name',
input_type=MyInput,
output_type=MyOutput,
metadata_type=MyMetadata,
description='Updated desc',
)
body = json.loads(requests_seen[0].content)
assert body['name'] == 'new-name'
assert body['description'] == 'Updated desc'
assert 'input_schema' in body
assert 'output_schema' in body
assert 'metadata_schema' in body
def test_update_dataset_clear_fields(self):
"""Test that passing None clears fields (using _UNSET sentinel)."""
requests_seen: list[httpx.Request] = []
def handler(request: httpx.Request) -> httpx.Response:
requests_seen.append(request)
return httpx.Response(200, json=FAKE_DATASET)
transport = httpx.MockTransport(handler)
client = LogfireAPIClient(api_key='test-key', base_url='https://test.logfire.dev')
client.client = httpx.Client(transport=transport, base_url='https://test.logfire.dev')
client.update_dataset('test-dataset', description=None)
body = json.loads(requests_seen[0].content)
assert body['description'] is None
def test_delete_dataset(self):
client = make_client()
result = client.delete_dataset('test-dataset')
assert result is None
def test_list_cases(self):
client = make_client()
result = client.list_cases('test-dataset')
assert result == [EXPECTED_CASE]
def test_get_case(self):
client = make_client()
result = client.get_case('test-dataset', 'case-456')
assert result == EXPECTED_CASE
def test_add_cases(self):
client = make_client()
cases: list[Case[MyInput, MyOutput, Any]] = [
Case(inputs=MyInput(question='q1')),
Case(inputs=MyInput(question='q2')),
]
result = client.add_cases('test-dataset', cases)
assert result == [EXPECTED_CASE]
def test_push_dataset_create_new(self):
requests_seen: list[httpx.Request] = []
hosted_dataset = {**FAKE_DATASET, 'name': 'local-dataset'}
def handler(request: httpx.Request) -> httpx.Response:
requests_seen.append(request)
if request.method == 'POST' and request.url.path == '/v1/datasets/':
return httpx.Response(200, json=hosted_dataset)
if request.method == 'POST' and request.url.path == '/v1/datasets/local-dataset/import/':
return httpx.Response(200, json=[FAKE_CASE])
if request.method == 'GET' and request.url.path == '/v1/datasets/local-dataset/':
return httpx.Response(200, json=hosted_dataset)
return httpx.Response(404, json={'detail': 'Not found'})
transport = httpx.MockTransport(handler)
client = LogfireAPIClient(api_key='test-key', base_url='https://test.logfire.dev')
client.client = httpx.Client(transport=transport, base_url='https://test.logfire.dev')
result = client.push_dataset(
make_local_dataset(),
description='Hosted copy',
)
assert result == {**hosted_dataset, 'id': EXPECTED_DATASET['id']}
assert [(request.method, request.url.path) for request in requests_seen] == [
('POST', '/v1/datasets/'),
('POST', '/v1/datasets/local-dataset/import/'),
('GET', '/v1/datasets/local-dataset/'),
]
create_body = json.loads(requests_seen[0].content)
assert create_body['name'] == 'local-dataset'
assert create_body['description'] == 'Hosted copy'
assert 'input_schema' in create_body
assert 'output_schema' in create_body
assert 'metadata_schema' in create_body
import_body = json.loads(requests_seen[1].content)
assert requests_seen[1].url.params['on_conflict'] == 'update'
assert import_body['cases'] == [
{
'name': 'local-case',
'inputs': {'question': 'What is 2+2?'},
'expected_output': {'answer': '4'},
'metadata': {'source': 'seed'},
'evaluators': [],
}
]
def test_push_dataset_updates_existing_dataset_on_conflict(self):
requests_seen: list[httpx.Request] = []
hosted_dataset = {**FAKE_DATASET, 'name': 'hosted-dataset'}
def handler(request: httpx.Request) -> httpx.Response:
requests_seen.append(request)
if request.method == 'POST' and request.url.path == '/v1/datasets/':
return httpx.Response(409, json={'detail': 'Dataset already exists'})
if request.method == 'PATCH' and request.url.path == '/v1/datasets/hosted-dataset/':
return httpx.Response(200, json=hosted_dataset)
if request.method == 'POST' and request.url.path == '/v1/datasets/hosted-dataset/import/':
return httpx.Response(200, json=[FAKE_CASE])
if request.method == 'GET' and request.url.path == '/v1/datasets/hosted-dataset/':
return httpx.Response(200, json=hosted_dataset)
return httpx.Response(404, json={'detail': 'Not found'})
transport = httpx.MockTransport(handler)
client = LogfireAPIClient(api_key='test-key', base_url='https://test.logfire.dev')
client.client = httpx.Client(transport=transport, base_url='https://test.logfire.dev')
result = client.push_dataset(
make_local_dataset(),
name='hosted-dataset',
description=None,
on_case_conflict='error',
)
assert result == {**hosted_dataset, 'id': EXPECTED_DATASET['id']}
assert [(request.method, request.url.path) for request in requests_seen] == [
('POST', '/v1/datasets/'),
('PATCH', '/v1/datasets/hosted-dataset/'),
('POST', '/v1/datasets/hosted-dataset/import/'),
('GET', '/v1/datasets/hosted-dataset/'),
]
create_body = json.loads(requests_seen[0].content)
assert create_body['name'] == 'hosted-dataset'
assert 'input_schema' in create_body
assert 'output_schema' in create_body
assert 'metadata_schema' in create_body
update_body = json.loads(requests_seen[1].content)
assert update_body['description'] is None
assert 'name' not in update_body
assert 'input_schema' in update_body
assert 'output_schema' in update_body
assert 'metadata_schema' in update_body
assert requests_seen[2].url.params['on_conflict'] == 'error'
def test_push_dataset_requires_name(self):
client = make_client()
dataset = make_local_dataset()
dataset.name = cast(Any, None)
with pytest.raises(ValueError, match='requires a dataset name'):
client.push_dataset(dataset)
def test_push_dataset_uploads_dataset_level_evaluators(self):
@dataclass
class DatasetEval:
threshold: float = 0.9
@dataclass
class ReportEval:
min_pass_rate: float = 0.5
requests_seen: list[httpx.Request] = []
dataset = make_local_dataset()
dataset.evaluators = cast(Any, [DatasetEval(threshold=0.95)])
dataset.report_evaluators = cast(Any, [ReportEval(min_pass_rate=0.8)])
def handler(request: httpx.Request) -> httpx.Response:
requests_seen.append(request)
if request.method == 'POST' and request.url.path == '/v1/datasets/':
return httpx.Response(200, json=FAKE_DATASET)
if request.method == 'POST' and request.url.path.endswith('/import/'):
return httpx.Response(200, json=[FAKE_CASE])
if request.method == 'GET' and request.url.path == '/v1/datasets/local-dataset/':
return httpx.Response(200, json=FAKE_DATASET)
return httpx.Response(404, json={'detail': 'Not found'})
client = LogfireAPIClient(
client=httpx.Client(transport=httpx.MockTransport(handler), base_url='https://test.logfire.dev')
)
client.push_dataset(dataset)
create_request = next(r for r in requests_seen if r.method == 'POST' and r.url.path == '/v1/datasets/')
body = json.loads(create_request.content)
assert body['evaluators'] == [{'name': 'DatasetEval', 'arguments': {'threshold': 0.95}}]
assert body['report_evaluators'] == [{'name': 'ReportEval', 'arguments': {'min_pass_rate': 0.8}}]
def test_push_dataset_propagates_non_conflict_error(self):
client = make_client(
{
('POST', '/v1/datasets/'): httpx.Response(500, json={'detail': 'boom'}),
}
)
with pytest.raises(DatasetApiError) as exc_info:
client.push_dataset(make_local_dataset())
assert exc_info.value.status_code == 500
def test_push_dataset_without_cases_skips_import(self):
requests_seen: list[httpx.Request] = []
empty_dataset = Dataset[MyInput, MyOutput, MyMetadata](name='empty-dataset', cases=[])
hosted_dataset = {**FAKE_DATASET, 'name': 'empty-dataset'}
def handler(request: httpx.Request) -> httpx.Response:
requests_seen.append(request)
if request.method == 'POST' and request.url.path == '/v1/datasets/':
return httpx.Response(200, json=hosted_dataset)
if request.method == 'GET' and request.url.path == '/v1/datasets/empty-dataset/':
return httpx.Response(200, json=hosted_dataset)
return httpx.Response(404, json={'detail': 'Not found'})
transport = httpx.MockTransport(handler)
client = LogfireAPIClient(api_key='test-key', base_url='https://test.logfire.dev')
client.client = httpx.Client(transport=transport, base_url='https://test.logfire.dev')
result = client.push_dataset(empty_dataset)
assert result == {**hosted_dataset, 'id': EXPECTED_DATASET['id']}
assert [(request.method, request.url.path) for request in requests_seen] == [
('POST', '/v1/datasets/'),
('GET', '/v1/datasets/empty-dataset/'),
]
def test_update_case_minimal(self):
"""When no params are set, sends empty body."""
client = make_client()
result = client.update_case('test-dataset', 'case-456')
assert result == EXPECTED_CASE
def test_update_case_full(self):
requests_seen: list[httpx.Request] = []
def handler(request: httpx.Request) -> httpx.Response:
requests_seen.append(request)
return httpx.Response(200, json=FAKE_CASE)
transport = httpx.MockTransport(handler)
client = LogfireAPIClient(api_key='test-key', base_url='https://test.logfire.dev')
client.client = httpx.Client(transport=transport, base_url='https://test.logfire.dev')
@dataclass
class MyEval:
pass
client.update_case(
'test-dataset',
'case-456',
name='updated',
inputs=MyInput(question='new'),
expected_output=MyOutput(answer='new-answer'),
metadata=MyMetadata(source='updated'),
evaluators=[MyEval()],
)
body = json.loads(requests_seen[0].content)
assert body['name'] == 'updated'
assert body['inputs'] == {'question': 'new'}
assert body['expected_output'] == {'answer': 'new-answer'}
assert body['metadata'] == {'source': 'updated'}
assert body['evaluators'] == [{'name': 'MyEval', 'arguments': None}]
def test_update_case_clear_fields(self):
"""Pass None to explicitly clear nullable fields."""
requests_seen: list[httpx.Request] = []
def handler(request: httpx.Request) -> httpx.Response:
requests_seen.append(request)
return httpx.Response(200, json=FAKE_CASE)
transport = httpx.MockTransport(handler)
client = LogfireAPIClient(api_key='test-key', base_url='https://test.logfire.dev')
client.client = httpx.Client(transport=transport, base_url='https://test.logfire.dev')
client.update_case(
'test-dataset',
'case-456',
name=None,
expected_output=None,
metadata=None,
evaluators=None,
)
body = json.loads(requests_seen[0].content)
assert body['name'] is None
assert body['expected_output'] is None
assert body['metadata'] is None
assert body['evaluators'] is None
def test_update_case_dict_inputs(self):
requests_seen: list[httpx.Request] = []
def handler(request: httpx.Request) -> httpx.Response:
requests_seen.append(request)
return httpx.Response(200, json=FAKE_CASE)
transport = httpx.MockTransport(handler)
client = LogfireAPIClient(api_key='test-key', base_url='https://test.logfire.dev')
client.client = httpx.Client(transport=transport, base_url='https://test.logfire.dev')
client.update_case(
'test-dataset',
'case-456',
inputs={'question': 'dict-input'},
expected_output={'answer': 'dict-output'},
metadata={'source': 'dict-meta'},
)
body = json.loads(requests_seen[0].content)
assert body['inputs'] == {'question': 'dict-input'}
assert body['expected_output'] == {'answer': 'dict-output'}
assert body['metadata'] == {'source': 'dict-meta'}
def test_delete_case(self):
client = make_client()
result = client.delete_case('test-dataset', 'case-456')
assert result is None
def test_get_dataset_with_cases(self):
"""Without type args, returns raw dict with cases."""
client = make_client()
result = client.get_dataset('test-dataset')
assert result == FAKE_EXPORT
def test_get_dataset_typed(self):
"""With type args, returns pydantic-evals Dataset."""
client = make_client()
result = client.get_dataset('test-dataset', input_type=MyInput, output_type=MyOutput)
from pydantic_evals import Dataset
assert isinstance(result, Dataset)
def test_get_dataset_typed_type_form_with_defaults(self):
export = {
'name': 'test-dataset',
'cases': [{'name': 'test-case', 'inputs': [1, 2]}],
}
responses = {('GET', '/v1/datasets/test-dataset/export/'): httpx.Response(200, json=export)}
client = make_client(responses)
result = client.get_dataset('test-dataset', input_type=list[int])
assert _get_dataset_type_args(result) == (list[int], Any, Any)
assert result.cases[0].inputs == [1, 2]
def test_get_dataset_typed_without_pydantic_evals(self, monkeypatch: pytest.MonkeyPatch):
client = make_client()
monkeypatch.setitem(sys.modules, 'pydantic_evals', None)
with pytest.raises(ImportError, match='pydantic-evals is required for this operation'):
client.get_dataset('test-dataset', input_type=MyInput)
def test_get_dataset_typed_with_broken_pydantic_evals_dependency(self, monkeypatch: pytest.MonkeyPatch):
client = make_client()
import_ = builtins.__import__
def mock_import(
name: str,
globals: dict[str, Any] | None = None,
locals: dict[str, Any] | None = None,
fromlist: tuple[str, ...] = (),
level: int = 0,
) -> Any:
if name == 'pydantic_evals':
raise ModuleNotFoundError("No module named 'broken_dependency'", name='broken_dependency')
return import_(name, globals, locals, fromlist, level)
monkeypatch.setattr(builtins, '__import__', mock_import)
with pytest.raises(ModuleNotFoundError, match='broken_dependency'):
client.get_dataset('test-dataset', input_type=MyInput)
def test_add_cases_with_dicts(self):
client = make_client()
cases: list[dict[str, Any]] = [{'inputs': {'question': 'q1'}}]
result = client.add_cases('test-dataset', cases)
assert result == [EXPECTED_CASE]
def test_auth_header(self):
"""Client should set Authorization header."""
client = LogfireAPIClient(api_key='my-secret-key', base_url='https://test.logfire.dev')
assert client.client.headers['authorization'] == 'Bearer my-secret-key'
client.client.close()
# =============================================================================
# Async client tests
# =============================================================================
class TestAsyncLogfireAPIClient:
def test_init_with_base_url(self):
client = AsyncLogfireAPIClient(api_key='test-key', base_url='https://custom.url')
assert str(client.client.base_url) == 'https://custom.url'
def test_init_with_client(self):
httpx_client = httpx.AsyncClient(base_url='https://custom.url')
client = AsyncLogfireAPIClient(client=httpx_client)
assert client.client is httpx_client
def test_init_requires_client_or_api_key(self):
with pytest.raises(ValueError, match='Either client or api_key must be provided'):
AsyncLogfireAPIClient()
@pytest.mark.anyio
async def test_context_manager(self):
client = make_async_client()
async with client as c:
assert c is client
@pytest.mark.anyio
async def test_list_datasets(self):
client = make_async_client()
result = await client.list_datasets()
assert result == [EXPECTED_DATASET]
@pytest.mark.anyio
async def test_get_dataset(self):
client = make_async_client()
result = await client.get_dataset('test-dataset', include_cases=False)
assert result == EXPECTED_DATASET
@pytest.mark.anyio
async def test_create_dataset_minimal(self):
client = make_async_client()
result = await client.create_dataset(name='test-dataset')
assert result == EXPECTED_DATASET
@pytest.mark.anyio
async def test_create_dataset_full(self):
requests_seen: list[httpx.Request] = []
def handler(request: httpx.Request) -> httpx.Response:
requests_seen.append(request)
return httpx.Response(200, json=FAKE_DATASET)
transport = httpx.MockTransport(handler)
client = AsyncLogfireAPIClient(api_key='test-key', base_url='https://test.logfire.dev')
client.client = httpx.AsyncClient(transport=transport, base_url='https://test.logfire.dev')
await client.create_dataset(
name='test-dataset',
input_type=MyInput,
output_type=MyOutput,
metadata_type=MyMetadata,
description='A test dataset',
)
body = json.loads(requests_seen[0].content)
assert body['name'] == 'test-dataset'
assert 'input_schema' in body
assert 'output_schema' in body
assert 'metadata_schema' in body
assert body['description'] == 'A test dataset'
@pytest.mark.anyio
async def test_update_dataset_minimal(self):
client = make_async_client()
result = await client.update_dataset('test-dataset')
assert result == EXPECTED_DATASET
@pytest.mark.anyio
async def test_update_dataset_full(self):
requests_seen: list[httpx.Request] = []
def handler(request: httpx.Request) -> httpx.Response:
requests_seen.append(request)
return httpx.Response(200, json=FAKE_DATASET)
transport = httpx.MockTransport(handler)
client = AsyncLogfireAPIClient(api_key='test-key', base_url='https://test.logfire.dev')
client.client = httpx.AsyncClient(transport=transport, base_url='https://test.logfire.dev')
await client.update_dataset(
'test-dataset',
name='new-name',
input_type=MyInput,
output_type=MyOutput,
metadata_type=MyMetadata,
description='Updated desc',
)
body = json.loads(requests_seen[0].content)
assert body['name'] == 'new-name'
assert body['description'] == 'Updated desc'
assert 'input_schema' in body
@pytest.mark.anyio
async def test_update_dataset_clear_fields(self):
requests_seen: list[httpx.Request] = []
def handler(request: httpx.Request) -> httpx.Response:
requests_seen.append(request)
return httpx.Response(200, json=FAKE_DATASET)
transport = httpx.MockTransport(handler)
client = AsyncLogfireAPIClient(api_key='test-key', base_url='https://test.logfire.dev')
client.client = httpx.AsyncClient(transport=transport, base_url='https://test.logfire.dev')
await client.update_dataset('test-dataset', description=None)
body = json.loads(requests_seen[0].content)
assert body['description'] is None
@pytest.mark.anyio
async def test_delete_dataset(self):
client = make_async_client()
result = await client.delete_dataset('test-dataset')
assert result is None
@pytest.mark.anyio
async def test_list_cases(self):
client = make_async_client()
result = await client.list_cases('test-dataset')
assert result == [EXPECTED_CASE]
@pytest.mark.anyio
async def test_get_case(self):
client = make_async_client()
result = await client.get_case('test-dataset', 'case-456')
assert result == EXPECTED_CASE
@pytest.mark.anyio
async def test_add_cases(self):
client = make_async_client()
cases: list[Case[MyInput, MyOutput, Any]] = [Case(inputs=MyInput(question='q1'))]
result = await client.add_cases('test-dataset', cases)
assert result == [EXPECTED_CASE]
@pytest.mark.anyio
async def test_push_dataset_create_new(self):
requests_seen: list[httpx.Request] = []
hosted_dataset = {**FAKE_DATASET, 'name': 'local-dataset'}
def handler(request: httpx.Request) -> httpx.Response:
requests_seen.append(request)
if request.method == 'POST' and request.url.path == '/v1/datasets/':
return httpx.Response(200, json=hosted_dataset)
if request.method == 'POST' and request.url.path == '/v1/datasets/local-dataset/import/':
return httpx.Response(200, json=[FAKE_CASE])
if request.method == 'GET' and request.url.path == '/v1/datasets/local-dataset/':
return httpx.Response(200, json=hosted_dataset)
return httpx.Response(404, json={'detail': 'Not found'})
transport = httpx.MockTransport(handler)
client = AsyncLogfireAPIClient(api_key='test-key', base_url='https://test.logfire.dev')
client.client = httpx.AsyncClient(transport=transport, base_url='https://test.logfire.dev')
result = await client.push_dataset(
make_local_dataset(),
description='Hosted copy',
)
assert result == {**hosted_dataset, 'id': EXPECTED_DATASET['id']}
assert [(request.method, request.url.path) for request in requests_seen] == [
('POST', '/v1/datasets/'),
('POST', '/v1/datasets/local-dataset/import/'),
('GET', '/v1/datasets/local-dataset/'),
]
create_body = json.loads(requests_seen[0].content)
assert create_body['name'] == 'local-dataset'
assert create_body['description'] == 'Hosted copy'
assert 'input_schema' in create_body
assert 'output_schema' in create_body
assert 'metadata_schema' in create_body
import_body = json.loads(requests_seen[1].content)
assert requests_seen[1].url.params['on_conflict'] == 'update'
assert import_body['cases'] == [
{
'name': 'local-case',
'inputs': {'question': 'What is 2+2?'},
'expected_output': {'answer': '4'},
'metadata': {'source': 'seed'},
'evaluators': [],
}
]
@pytest.mark.anyio
async def test_push_dataset_updates_existing_dataset_on_conflict(self):
requests_seen: list[httpx.Request] = []
hosted_dataset = {**FAKE_DATASET, 'name': 'hosted-dataset'}
def handler(request: httpx.Request) -> httpx.Response:
requests_seen.append(request)
if request.method == 'POST' and request.url.path == '/v1/datasets/':
return httpx.Response(409, json={'detail': 'Dataset already exists'})
if request.method == 'PATCH' and request.url.path == '/v1/datasets/hosted-dataset/':
return httpx.Response(200, json=hosted_dataset)
if request.method == 'POST' and request.url.path == '/v1/datasets/hosted-dataset/import/':
return httpx.Response(200, json=[FAKE_CASE])
if request.method == 'GET' and request.url.path == '/v1/datasets/hosted-dataset/':
return httpx.Response(200, json=hosted_dataset)
return httpx.Response(404, json={'detail': 'Not found'})
transport = httpx.MockTransport(handler)
client = AsyncLogfireAPIClient(api_key='test-key', base_url='https://test.logfire.dev')
client.client = httpx.AsyncClient(transport=transport, base_url='https://test.logfire.dev')
result = await client.push_dataset(
make_local_dataset(),
name='hosted-dataset',
description=None,
on_case_conflict='error',
)
assert result == {**hosted_dataset, 'id': EXPECTED_DATASET['id']}
assert [(request.method, request.url.path) for request in requests_seen] == [
('POST', '/v1/datasets/'),
('PATCH', '/v1/datasets/hosted-dataset/'),
('POST', '/v1/datasets/hosted-dataset/import/'),
('GET', '/v1/datasets/hosted-dataset/'),
]
create_body = json.loads(requests_seen[0].content)
assert create_body['name'] == 'hosted-dataset'
assert 'input_schema' in create_body
assert 'output_schema' in create_body
assert 'metadata_schema' in create_body
update_body = json.loads(requests_seen[1].content)
assert update_body['description'] is None
assert 'name' not in update_body
assert 'input_schema' in update_body
assert 'output_schema' in update_body
assert 'metadata_schema' in update_body
assert requests_seen[2].url.params['on_conflict'] == 'error'
@pytest.mark.anyio
async def test_push_dataset_requires_name(self):
client = make_async_client()
dataset = make_local_dataset()
dataset.name = cast(Any, None)
with pytest.raises(ValueError, match='requires a dataset name'):
await client.push_dataset(dataset)
@pytest.mark.anyio
async def test_push_dataset_propagates_non_conflict_error(self):
client = make_async_client(
{
('POST', '/v1/datasets/'): httpx.Response(500, json={'detail': 'boom'}),
}
)
with pytest.raises(DatasetApiError) as exc_info:
await client.push_dataset(make_local_dataset())
assert exc_info.value.status_code == 500
@pytest.mark.anyio
async def test_push_dataset_without_cases_skips_import(self):
requests_seen: list[httpx.Request] = []
empty_dataset = Dataset[MyInput, MyOutput, MyMetadata](name='empty-dataset', cases=[])
hosted_dataset = {**FAKE_DATASET, 'name': 'empty-dataset'}
def handler(request: httpx.Request) -> httpx.Response:
requests_seen.append(request)
if request.method == 'POST' and request.url.path == '/v1/datasets/':
return httpx.Response(200, json=hosted_dataset)
if request.method == 'GET' and request.url.path == '/v1/datasets/empty-dataset/':
return httpx.Response(200, json=hosted_dataset)
return httpx.Response(404, json={'detail': 'Not found'})
transport = httpx.MockTransport(handler)
client = AsyncLogfireAPIClient(api_key='test-key', base_url='https://test.logfire.dev')
client.client = httpx.AsyncClient(transport=transport, base_url='https://test.logfire.dev')
result = await client.push_dataset(empty_dataset)
assert result == {**hosted_dataset, 'id': EXPECTED_DATASET['id']}
assert [(request.method, request.url.path) for request in requests_seen] == [
('POST', '/v1/datasets/'),
('GET', '/v1/datasets/empty-dataset/'),
]
@pytest.mark.anyio
async def test_update_case_minimal(self):
client = make_async_client()
result = await client.update_case('test-dataset', 'case-456')
assert result == EXPECTED_CASE
@pytest.mark.anyio
async def test_update_case_full(self):
requests_seen: list[httpx.Request] = []
def handler(request: httpx.Request) -> httpx.Response:
requests_seen.append(request)
return httpx.Response(200, json=FAKE_CASE)
transport = httpx.MockTransport(handler)
client = AsyncLogfireAPIClient(api_key='test-key', base_url='https://test.logfire.dev')
client.client = httpx.AsyncClient(transport=transport, base_url='https://test.logfire.dev')
@dataclass
class MyEval:
pass
await client.update_case(
'test-dataset',
'case-456',
name='updated',
inputs=MyInput(question='new'),
expected_output=MyOutput(answer='new-answer'),
metadata=MyMetadata(source='updated'),
evaluators=[MyEval()],
)
body = json.loads(requests_seen[0].content)
assert body['name'] == 'updated'
assert body['inputs'] == {'question': 'new'}
assert body['expected_output'] == {'answer': 'new-answer'}
assert body['metadata'] == {'source': 'updated'}
@pytest.mark.anyio
async def test_update_case_clear_fields(self):
requests_seen: list[httpx.Request] = []
def handler(request: httpx.Request) -> httpx.Response:
requests_seen.append(request)
return httpx.Response(200, json=FAKE_CASE)
transport = httpx.MockTransport(handler)
client = AsyncLogfireAPIClient(api_key='test-key', base_url='https://test.logfire.dev')
client.client = httpx.AsyncClient(transport=transport, base_url='https://test.logfire.dev')
await client.update_case(
'test-dataset',
'case-456',
name=None,
expected_output=None,
metadata=None,
evaluators=None,
)
body = json.loads(requests_seen[0].content)
assert body['name'] is None
assert body['expected_output'] is None
assert body['metadata'] is None
assert body['evaluators'] is None
@pytest.mark.anyio
async def test_update_case_dict_inputs(self):
requests_seen: list[httpx.Request] = []
def handler(request: httpx.Request) -> httpx.Response:
requests_seen.append(request)
return httpx.Response(200, json=FAKE_CASE)
transport = httpx.MockTransport(handler)
client = AsyncLogfireAPIClient(api_key='test-key', base_url='https://test.logfire.dev')
client.client = httpx.AsyncClient(transport=transport, base_url='https://test.logfire.dev')
await client.update_case(
'test-dataset',
'case-456',
inputs={'question': 'dict-input'},
expected_output={'answer': 'dict-output'},
metadata={'source': 'dict-meta'},
)
body = json.loads(requests_seen[0].content)
assert body['inputs'] == {'question': 'dict-input'}
assert body['expected_output'] == {'answer': 'dict-output'}
assert body['metadata'] == {'source': 'dict-meta'}
@pytest.mark.anyio
async def test_delete_case(self):
client = make_async_client()
result = await client.delete_case('test-dataset', 'case-456')
assert result is None
@pytest.mark.anyio
async def test_get_dataset_with_cases(self):
client = make_async_client()
result = await client.get_dataset('test-dataset')
assert result == FAKE_EXPORT
@pytest.mark.anyio
async def test_get_dataset_typed(self):
client = make_async_client()
result = await client.get_dataset('test-dataset', input_type=MyInput, output_type=MyOutput)
from pydantic_evals import Dataset
assert isinstance(result, Dataset)
@pytest.mark.anyio
async def test_get_dataset_typed_type_form_with_defaults(self):
export = {
'name': 'test-dataset',
'cases': [{'name': 'test-case', 'inputs': [1, 2]}],
}
responses = {('GET', '/v1/datasets/test-dataset/export/'): httpx.Response(200, json=export)}
client = make_async_client(responses)
result = await client.get_dataset('test-dataset', input_type=list[int])
assert _get_dataset_type_args(result) == (list[int], Any, Any)
assert result.cases[0].inputs == [1, 2]
@pytest.mark.anyio
async def test_add_cases_with_dicts(self):
client = make_async_client()
cases: list[dict[str, Any]] = [{'inputs': {'question': 'q1'}}]
result = await client.add_cases('test-dataset', cases)
assert result == [EXPECTED_CASE]
# =============================================================================
# Response validation / resilience
# =============================================================================
class TestResponseValidation:
"""Responses are validated and coerced to the shape this SDK knows about:
unknown fields are dropped (upgrade the SDK for new fields), missing optional
fields are tolerated, and a response that fails validation is returned raw
with a warning rather than raising (see `_validate_or_warn`)."""
def test_coerces_uuid_and_datetime(self):
response = {
'id': '12345678-1234-5678-1234-567812345678',
'name': 'test-dataset',
'created_at': '2024-01-02T03:04:05Z',
}
client = make_client({('GET', '/v1/datasets/test-dataset/'): httpx.Response(200, json=response)})
result = cast('dict[str, Any]', client.get_dataset('test-dataset', include_cases=False))
assert result['id'] == UUID('12345678-1234-5678-1234-567812345678')
assert isinstance(result['id'], UUID)
assert isinstance(result['created_at'], datetime)
def test_drops_unknown_fields(self):
# The client returns the shape this SDK version knows about: a field the
# SDK doesn't declare is dropped (you upgrade the SDK to access new
# fields), while declared fields come through.
response = {**FAKE_DATASET, 'a_brand_new_field': 'ignored'}
client = make_client({('GET', '/v1/datasets/test-dataset/'): httpx.Response(200, json=response)})
result = cast('dict[str, Any]', client.get_dataset('test-dataset', include_cases=False))
assert 'a_brand_new_field' not in result
assert result['name'] == 'test-dataset'
def test_tolerates_missing_optional_fields(self):
# The backend omitting optional fields (only id + name here) must not raise.
response = {'id': '12345678-1234-5678-1234-567812345678', 'name': 'minimal'}
client = make_client({('GET', '/v1/datasets/test-dataset/'): httpx.Response(200, json=response)})
with warnings.catch_warnings():
warnings.simplefilter('error')
result = client.get_dataset('test-dataset', include_cases=False)
assert result == {'id': UUID('12345678-1234-5678-1234-567812345678'), 'name': 'minimal'}
def test_warns_and_returns_raw_on_schema_mismatch(self):
# `id` is required and must be a UUID; an unexpected shape should warn and
# pass the raw dict through unchanged instead of raising, so clients keep working.
bad_response = {'id': 'not-a-uuid-sensitive-token', 'name': 42}
client = make_client({('GET', '/v1/datasets/test-dataset/'): httpx.Response(200, json=bad_response)})
with pytest.warns(UserWarning, match='did not match the expected schema') as record:
result = client.get_dataset('test-dataset', include_cases=False)
assert result == bad_response
# The warning should name the offending fields but must not leak the
# payload values (which can be sensitive).
message = str(record[0].message)
assert 'id' in message and 'name' in message
assert 'not-a-uuid-sensitive-token' not in message
@pytest.mark.anyio
async def test_async_warns_and_returns_raw_on_schema_mismatch(self):
bad_response = {'name': 'no-id-here'}
client = make_async_client({('GET', '/v1/datasets/test-dataset/'): httpx.Response(200, json=bad_response)})
with pytest.warns(UserWarning, match='did not match the expected schema'):
result = await client.get_dataset('test-dataset', include_cases=False)
assert result == bad_response
"""Tests for logfire.experimental.datasets client achieving 100% coverage."""
# pyright: reportPrivateUsage=false, reportArgumentType=false, reportUnknownVariableType=false
from __future__ import annotations
import builtins
import json
import sys
import warnings
from dataclasses import dataclass
from datetime import datetime
from typing import Any, cast
from uuid import UUID
import httpx
import pytest
from pydantic import BaseModel
try:
from pydantic_evals import Case, Dataset
except Exception:
pytest.skip('pydantic_evals not compatible with this environment', allow_module_level=True)
from logfire.experimental.api_client import (
AsyncLogfireAPIClient,
CaseNotFoundError,
DatasetApiError,
DatasetNotFoundError,
LogfireAPIClient,
_build_push_dataset_kwargs,
_from_dict_compat,
_from_dict_supports_report_evaluators,
_get_dataset_type_args,
_serialize_case,
_serialize_evaluators,
_serialize_value,
_type_to_schema,
_validate_dataset_name,
)
# --- Test types ---
class MyInput:
question: str
class MyOutput:
answer: str
class MyMetadata:
source: str
class PydanticInput(BaseModel):
question: str
# --- Mock transport helpers ---
FAKE_DATASET = {
'id': '12345678-1234-5678-1234-567812345678',
'name': 'test-dataset',
'description': 'A test dataset',
'case_count': 0,
}
FAKE_CASE = {
'id': '87654321-4321-8765-4321-876543218765',
'name': 'test-case',
'inputs': {'question': 'What is 2+2?'},
'expected_output': {'answer': '4'},
}
# Responses are validated by the client, which coerces the string ``id`` to a
# ``UUID``. These are the expected post-coercion results to assert against.
EXPECTED_DATASET = {**FAKE_DATASET, 'id': UUID(FAKE_DATASET['id'])}
EXPECTED_CASE = {**FAKE_CASE, 'id': UUID(FAKE_CASE['id'])}
FAKE_EXPORT = {
'name': 'test-dataset',
'cases': [
{
'name': 'test-case',
'inputs': {'question': 'What is 2+2?'},
'expected_output': {'answer': '4'},
}
],
}
def make_local_dataset(name: str = 'local-dataset') -> Dataset[MyInput, MyOutput, MyMetadata]:
return Dataset[MyInput, MyOutput, MyMetadata](
name=name,
cases=[
Xet Storage Details
- Size:
- 62.9 kB
- Xet hash:
- 436a522ba14584428ef4f0a655824fde32f011885bc372648da5e127bb6e77d8
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.