Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

28.6 KB
Raw Blame
"""
Test Anthropic Files API transformation functionality.

Tests the AnthropicFilesConfig class which transforms between
OpenAI-compatible file operations and Anthropic's Files API format.
"""

import asyncio
import datetime
import io
import json
import threading
import time

import httpx
import pytest
from openai.types.file_deleted import FileDeleted
from pydantic import ValidationError
from unittest.mock import Mock, patch

from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.llms.anthropic.files.transformation import (
    AnthropicFilesConfig,
    ANTHROPIC_FILES_API_BASE,
    ANTHROPIC_FILES_BETA_HEADER,
)
from litellm.types.llms.openai import OpenAIFileObject
from litellm.types.utils import LlmProviders


class TestAnthropicFilesConfig:
    """Test AnthropicFilesConfig transformation methods."""

    def setup_method(self):
        self.config = AnthropicFilesConfig()

    def test_custom_llm_provider(self):
        assert self.config.custom_llm_provider == LlmProviders.ANTHROPIC

    def test_get_complete_url_default(self):
        url = self.config.get_complete_url(
            api_base=None,
            api_key="test-key",
            model="",
            optional_params={},
            litellm_params={},
        )
        assert url == f"{ANTHROPIC_FILES_API_BASE}/v1/files"

    def test_get_complete_url_custom_base(self):
        url = self.config.get_complete_url(
            api_base="https://custom.api.com",
            api_key="test-key",
            model="",
            optional_params={},
            litellm_params={},
        )
        assert url == "https://custom.api.com/v1/files"

    def test_get_complete_url_strips_trailing_slash(self):
        url = self.config.get_complete_url(
            api_base="https://custom.api.com/",
            api_key="test-key",
            model="",
            optional_params={},
            litellm_params={},
        )
        assert url == "https://custom.api.com/v1/files"

    def test_validate_environment_sets_headers(self):
        headers = {}
        result = self.config.validate_environment(
            headers=headers,
            model="",
            messages=[],
            optional_params={},
            litellm_params={},
            api_key="sk-ant-test-key",
        )
        assert result["x-api-key"] == "sk-ant-test-key"
        assert result["anthropic-version"] == "2023-06-01"
        assert result["anthropic-beta"] == ANTHROPIC_FILES_BETA_HEADER

    @patch.dict("os.environ", {}, clear=True)
    @patch(
        "litellm.llms.anthropic.common_utils.AnthropicModelInfo.get_api_key",
        return_value=None,
    )
    def test_validate_environment_missing_api_key(self, mock_get_key):
        with pytest.raises(ValueError, match="Anthropic API key is required"):
            self.config.validate_environment(
                headers={},
                model="",
                messages=[],
                optional_params={},
                litellm_params={},
                api_key=None,
            )

    @pytest.mark.asyncio
    async def test_avalidate_environment_sets_headers(self):
        headers = {}
        result = await self.config.avalidate_environment(
            headers=headers,
            model="",
            messages=[],
            optional_params={},
            litellm_params={},
            api_key="sk-ant-test-key",
        )
        assert result["x-api-key"] == "sk-ant-test-key"
        assert result["anthropic-version"] == "2023-06-01"
        assert result["anthropic-beta"] == ANTHROPIC_FILES_BETA_HEADER

    @pytest.mark.asyncio
    @patch.dict("os.environ", {}, clear=True)
    @patch(
        "litellm.llms.anthropic.common_utils.AnthropicModelInfo.get_api_key",
        return_value=None,
    )
    async def test_avalidate_environment_missing_api_key(self, mock_get_key):
        with pytest.raises(ValueError, match="Anthropic API key is required"):
            await self.config.avalidate_environment(
                headers={},
                model="",
                messages=[],
                optional_params={},
                litellm_params={},
                api_key=None,
            )

    def test_get_supported_openai_params(self):
        params = self.config.get_supported_openai_params(model="")
        assert "purpose" in params

    def test_transform_create_file_request(self):
        file_content = b"test file content"
        file_tuple = ("test.txt", file_content, "text/plain")

        result = self.config.transform_create_file_request(
            model="",
            create_file_data={
                "file": file_tuple,
                "purpose": "messages",
            },
            optional_params={},
            litellm_params={},
        )

        assert "file" in result
        assert "purpose" in result
        # file should be a tuple (filename, content, content_type)
        assert result["file"][0] == "test.txt"
        assert result["file"][1] == file_content
        assert result["file"][2] == "text/plain"
        # purpose should be (None, value) for multipart form field
        assert result["purpose"] == (None, "messages")

    def test_transform_create_file_request_missing_file(self):
        with pytest.raises(ValueError, match="File data is required"):
            self.config.transform_create_file_request(
                model="",
                create_file_data={"purpose": "messages"},
                optional_params={},
                litellm_params={},
            )

    def test_transform_create_file_request_default_purpose(self):
        file_tuple = ("test.txt", b"content", "text/plain")
        result = self.config.transform_create_file_request(
            model="",
            create_file_data={"file": file_tuple},
            optional_params={},
            litellm_params={},
        )
        assert result["purpose"] == (None, "messages")

    def test_transform_create_file_response(self):
        mock_response = Mock(spec=httpx.Response)
        mock_response.json.return_value = {
            "id": "file-abc123",
            "type": "file",
            "filename": "document.pdf",
            "mime_type": "application/pdf",
            "size_bytes": 12345,
            "created_at": "2025-01-15T10:30:00Z",
        }

        result = self.config.transform_create_file_response(
            model=None,
            raw_response=mock_response,
            logging_obj=Mock(),
            litellm_params={},
        )

        assert isinstance(result, OpenAIFileObject)
        assert result.id == "file-abc123"
        assert result.filename == "document.pdf"
        assert result.bytes == 12345
        assert result.object == "file"
        assert result.purpose == "messages"
        assert result.status == "uploaded"

    def test_create_file_response_maps_the_anthropic_file_onto_an_openai_file(self) -> None:
        result = self.config.transform_create_file_response(
            model=None,
            raw_response=httpx.Response(
                200,
                json={
                    "id": "file-abc123",
                    "type": "file",
                    "filename": "document.pdf",
                    "mime_type": "application/pdf",
                    "size_bytes": 12345,
                    "created_at": "2025-01-15T10:30:00Z",
                },
            ),
            logging_obj=Mock(),
            litellm_params={},
        )

        assert result == OpenAIFileObject(
            id="file-abc123",
            bytes=12345,
            created_at=1736937000,
            filename="document.pdf",
            object="file",
            purpose="messages",
            status="uploaded",
            status_details=None,
        )

    @pytest.mark.parametrize("body", [b'["file-abc123"]', b'"file-abc123"', b"null", b"7"])
    def test_create_file_response_rejects_a_body_that_is_not_a_json_object(self, body: bytes) -> None:
        with pytest.raises(ValidationError):
            self.config.transform_create_file_response(
                model=None,
                raw_response=httpx.Response(200, content=body),
                logging_obj=Mock(),
                litellm_params={},
            )

    def test_transform_retrieve_file_request(self):
        url, params = self.config.transform_retrieve_file_request(
            file_id="file-abc123",
            optional_params={},
            litellm_params={},
        )
        assert url == f"{ANTHROPIC_FILES_API_BASE}/v1/files/file-abc123"
        assert params == {}

    def test_transform_retrieve_file_request_custom_base(self):
        url, params = self.config.transform_retrieve_file_request(
            file_id="file-abc123",
            optional_params={},
            litellm_params={"api_base": "https://custom.api.com"},
        )
        assert url == "https://custom.api.com/v1/files/file-abc123"
        assert params == {}

    def test_transform_retrieve_file_request_encodes_path_traversal(self):
        url, params = self.config.transform_retrieve_file_request(
            file_id="../../v1/messages/batches?limit=1#frag",
            optional_params={},
            litellm_params={},
        )

        assert url == f"{ANTHROPIC_FILES_API_BASE}/v1/files/..%2F..%2Fv1%2Fmessages%2Fbatches%3Flimit%3D1%23frag"
        assert params == {}

    def test_transform_retrieve_file_response(self):
        mock_response = Mock(spec=httpx.Response)
        mock_response.json.return_value = {
            "id": "file-abc123",
            "type": "file",
            "filename": "document.pdf",
            "mime_type": "application/pdf",
            "size_bytes": 5000,
            "created_at": "2025-06-01T12:00:00Z",
        }

        result = self.config.transform_retrieve_file_response(
            raw_response=mock_response,
            logging_obj=Mock(),
            litellm_params={},
        )

        assert isinstance(result, OpenAIFileObject)
        assert result.id == "file-abc123"
        assert result.bytes == 5000

    def test_retrieve_file_response_maps_the_anthropic_file_onto_an_openai_file(self) -> None:
        result = self.config.transform_retrieve_file_response(
            raw_response=httpx.Response(
                200,
                json={
                    "id": "file-abc123",
                    "type": "file",
                    "filename": "document.pdf",
                    "mime_type": "application/pdf",
                    "size_bytes": 5000,
                    "created_at": "2025-06-01T12:00:00Z",
                },
            ),
            logging_obj=Mock(),
            litellm_params={},
        )

        assert result == OpenAIFileObject(
            id="file-abc123",
            bytes=5000,
            created_at=1748779200,
            filename="document.pdf",
            object="file",
            purpose="messages",
            status="uploaded",
            status_details=None,
        )

    @pytest.mark.parametrize("body", [b'["file-abc123"]', b'"file-abc123"', b"null", b"7"])
    def test_retrieve_file_response_rejects_a_body_that_is_not_a_json_object(self, body: bytes) -> None:
        with pytest.raises(ValidationError):
            self.config.transform_retrieve_file_response(
                raw_response=httpx.Response(200, content=body),
                logging_obj=Mock(),
                litellm_params={},
            )

    def test_transform_delete_file_request(self):
        url, params = self.config.transform_delete_file_request(
            file_id="file-abc123",
            optional_params={},
            litellm_params={},
        )
        assert url == f"{ANTHROPIC_FILES_API_BASE}/v1/files/file-abc123"
        assert params == {}

    def test_transform_delete_file_response(self):
        mock_response = Mock(spec=httpx.Response)
        mock_response.json.return_value = {
            "id": "file-abc123",
            "type": "file_deleted",
        }

        result = self.config.transform_delete_file_response(
            raw_response=mock_response,
            logging_obj=Mock(),
            litellm_params={},
        )

        assert result.id == "file-abc123"
        assert result.deleted is True
        assert result.object == "file"

    @pytest.mark.parametrize(
        ("payload", "expected_id"),
        [
            ({"id": "file-abc123", "type": "file_deleted"}, "file-abc123"),
            ({"id": "file-abc123", "unknown": [1, {"nested": None}]}, "file-abc123"),
            ({"type": "error", "error": {"type": "not_found_error", "message": "File not found"}}, ""),
            ({}, ""),
        ],
    )
    def test_delete_file_response_reports_the_id_anthropic_returned(self, payload: object, expected_id: str) -> None:
        result = self.config.transform_delete_file_response(
            raw_response=httpx.Response(200, json=payload),
            logging_obj=Mock(),
            litellm_params={},
        )

        assert result == FileDeleted(id=expected_id, deleted=True, object="file")

    @pytest.mark.parametrize(
        "body", [b'["file-abc123"]', b'"file-abc123"', b"null", b"7", b'{"id": null}', b'{"id": 7}']
    )
    def test_delete_file_response_rejects_a_body_without_a_string_id(self, body: bytes) -> None:
        with pytest.raises(ValidationError):
            self.config.transform_delete_file_response(
                raw_response=httpx.Response(200, content=body),
                logging_obj=Mock(),
                litellm_params={},
            )

    def test_transform_list_files_request(self):
        url, params = self.config.transform_list_files_request(
            purpose=None,
            optional_params={},
            litellm_params={},
        )
        assert url == f"{ANTHROPIC_FILES_API_BASE}/v1/files"
        assert params == {}

    def test_transform_list_files_request_with_purpose(self):
        url, params = self.config.transform_list_files_request(
            purpose="messages",
            optional_params={},
            litellm_params={},
        )
        assert url == f"{ANTHROPIC_FILES_API_BASE}/v1/files"
        assert params == {"purpose": "messages"}

    def test_transform_list_files_response(self):
        mock_response = Mock(spec=httpx.Response)
        mock_response.json.return_value = {
            "data": [
                {
                    "id": "file-1",
                    "filename": "a.txt",
                    "size_bytes": 100,
                    "created_at": "2025-01-01T00:00:00Z",
                },
                {
                    "id": "file-2",
                    "filename": "b.txt",
                    "size_bytes": 200,
                    "created_at": "2025-01-02T00:00:00Z",
                },
            ],
            "has_more": False,
        }

        result = self.config.transform_list_files_response(
            raw_response=mock_response,
            logging_obj=Mock(),
            litellm_params={},
        )

        assert len(result) == 2
        assert result[0].id == "file-1"
        assert result[0].filename == "a.txt"
        assert result[1].id == "file-2"

    def test_transform_list_files_response_empty(self):
        mock_response = Mock(spec=httpx.Response)
        mock_response.json.return_value = {"data": [], "has_more": False}

        result = self.config.transform_list_files_response(
            raw_response=mock_response,
            logging_obj=Mock(),
            litellm_params={},
        )
        assert result == []

    def test_transform_file_content_request(self):
        url, params = self.config.transform_file_content_request(
            file_content_request={"file_id": "file-abc123"},
            optional_params={},
            litellm_params={},
        )
        assert url == f"{ANTHROPIC_FILES_API_BASE}/v1/files/file-abc123/content"
        assert params == {}

    def test_transform_file_content_request_routes_message_batch_id_to_batch_results(self):
        """
        Regression test for anthropic passthrough batch cost tracking (LIT-4008).

        Anthropic batch results are exposed via output_file_id=<msgbatch_...>.
        The Files API rejects those ids ("File id must have `file_` prefix"),
        so file content for a msgbatch_ id must be fetched from the message
        batches results endpoint instead.
        """
        url, params = self.config.transform_file_content_request(
            file_content_request={"file_id": "msgbatch_01WA5hdsa2Xx8w4zyPjV1frs"},
            optional_params={},
            litellm_params={},
        )
        assert url == f"{ANTHROPIC_FILES_API_BASE}/v1/messages/batches/msgbatch_01WA5hdsa2Xx8w4zyPjV1frs/results"
        assert params == {}

    def test_transform_file_content_request_message_batch_id_custom_api_base(self):
        url, _ = self.config.transform_file_content_request(
            file_content_request={"file_id": "msgbatch_abc"},
            optional_params={},
            litellm_params={"api_base": "https://custom.example.com/"},
        )
        assert url == "https://custom.example.com/v1/messages/batches/msgbatch_abc/results"

    def test_transform_file_content_request_rejects_dot_segment(self):
        with pytest.raises(ValueError, match="file_id cannot be a dot path segment"):
            self.config.transform_file_content_request(
                file_content_request={"file_id": ".."},
                optional_params={},
                litellm_params={},
            )

    def test_transform_file_content_response(self):
        mock_response = Mock(spec=httpx.Response)
        result = self.config.transform_file_content_response(
            raw_response=mock_response,
            logging_obj=Mock(),
            litellm_params={},
        )
        assert result.response == mock_response

    def test_parse_anthropic_file_with_size_bytes(self):
        """Test that size_bytes is correctly mapped to bytes field."""
        result = AnthropicFilesConfig._parse_anthropic_file(
            {
                "id": "file-test",
                "filename": "test.pdf",
                "size_bytes": 9999,
                "created_at": "2025-03-01T00:00:00Z",
            }
        )
        assert result.bytes == 9999

    def test_parse_anthropic_file_fallback_bytes_field(self):
        """Test fallback to 'bytes' field when 'size_bytes' is missing."""
        result = AnthropicFilesConfig._parse_anthropic_file(
            {
                "id": "file-test",
                "filename": "test.pdf",
                "bytes": 7777,
                "created_at": "2025-03-01T00:00:00Z",
            }
        )
        assert result.bytes == 7777

    def test_parse_anthropic_file_invalid_timestamp(self):
        """Test that invalid timestamps fall back to current time."""
        result = AnthropicFilesConfig._parse_anthropic_file(
            {
                "id": "file-test",
                "filename": "test.pdf",
                "size_bytes": 100,
                "created_at": "not-a-date",
            }
        )
        # Should not raise, should use current time
        assert isinstance(result.created_at, int)
        assert result.created_at > 0

    def test_parse_anthropic_file_missing_timestamp(self):
        """Test that missing timestamps fall back to current time."""
        result = AnthropicFilesConfig._parse_anthropic_file(
            {
                "id": "file-test",
                "filename": "test.pdf",
                "size_bytes": 100,
            }
        )
        assert isinstance(result.created_at, int)
        assert result.created_at > 0

    def test_get_error_class(self):
        error = self.config.get_error_class(
            error_message="Not found",
            status_code=404,
            headers={},
        )
        assert error.status_code == 404
        assert error.message == "Not found"


_WIF_ENV = {
    "ANTHROPIC_FEDERATION_RULE_ID": "fdrl_files_seam",
    "ANTHROPIC_ORGANIZATION_ID": "org-files-seam",
    "ANTHROPIC_IDENTITY_TOKEN": "files-seam-inline-jwt",
}


class _BlockingPoster:
    """A token-endpoint poster that blocks until released, so the test can prove
    the exchange ran off the event loop's own thread instead of freezing it."""

    def __init__(self):
        self.release = threading.Event()
        self.thread_ids = []

    def post(self, url, *, content, headers, timeout):
        self.thread_ids.append(threading.get_ident())
        self.release.wait(timeout=5)
        return httpx.Response(
            200,
            json={
                "access_token": "sk-ant-oat01-files-seam",
                "token_type": "Bearer",
                "expires_in": 3600,
            },
        )


class TestAnthropicFilesConfigWifAsyncSeam:
    """Regression (Greptile P1): avalidate_environment must resolve workload identity
    federation through the async token-exchange facade, never the blocking sync one,
    so a cold WIF mint on async file retrieval doesn't freeze the event loop."""

    def setup_method(self):
        self.config = AnthropicFilesConfig()

    @pytest.mark.asyncio
    async def test_avalidate_environment_wif_exchange_does_not_block_event_loop(self, monkeypatch):
        from litellm.llms.anthropic import common_utils as anthropic_common_utils
        from litellm.llms.anthropic.wif import aget_anthropic_wif_token, get_anthropic_wif_token
        from litellm.llms.base_llm.auth.token_exchange import JwtBearerTokenExchangeEngine

        for name in (
            "ANTHROPIC_API_KEY",
            "ANTHROPIC_AUTH_TOKEN",
            "ANTHROPIC_API_BASE",
            "ANTHROPIC_BASE_URL",
        ):
            monkeypatch.delenv(name, raising=False)
        for name, value in _WIF_ENV.items():
            monkeypatch.setenv(name, value)

        poster = _BlockingPoster()
        engine = JwtBearerTokenExchangeEngine(poster=poster)
        sync_calls = []

        def sync_shim(litellm_params, api_base, model):
            sync_calls.append(model)
            return get_anthropic_wif_token(litellm_params, api_base, model, engine)

        async def async_shim(litellm_params, api_base, model):
            return await aget_anthropic_wif_token(litellm_params, api_base, model, engine)

        monkeypatch.setattr(anthropic_common_utils, "get_anthropic_wif_token", sync_shim)
        monkeypatch.setattr(anthropic_common_utils, "aget_anthropic_wif_token", async_shim)

        ticks = []

        async def ticker():
            for i in range(20):
                await asyncio.sleep(0.005)
                ticks.append(i)

        ticker_task = asyncio.create_task(ticker())
        await asyncio.sleep(0.02)

        validate_task = asyncio.create_task(
            self.config.avalidate_environment(
                headers={},
                model="",
                messages=[],
                optional_params={},
                litellm_params={},
                api_key=None,
            )
        )
        await asyncio.sleep(0.05)
        # The ticker kept advancing while the exchange was still blocked on
        # poster.release, proving avalidate_environment did not run it inline.
        assert len(ticks) > 0
        assert not validate_task.done()

        poster.release.set()
        headers = await validate_task
        await ticker_task

        assert headers["authorization"] == "Bearer sk-ant-oat01-files-seam"
        assert sync_calls == []
        assert poster.thread_ids
        assert poster.thread_ids[0] != threading.get_ident()


class TestProviderConfigRegistration:
    """Test that AnthropicFilesConfig is properly registered."""

    def test_provider_config_returns_anthropic_files_config(self):
        from litellm.utils import ProviderConfigManager

        config = ProviderConfigManager.get_provider_files_config(
            model="",
            provider=LlmProviders.ANTHROPIC,
        )
        assert config is not None
        assert isinstance(config, AnthropicFilesConfig)


def _listed_files(body: bytes) -> list[OpenAIFileObject]:
    logging_obj = Logging(
        model="",
        messages=[],
        stream=False,
        call_type="file_list",
        start_time=datetime.datetime(2025, 1, 1, tzinfo=datetime.timezone.utc),
        litellm_call_id="call-id",
        function_id="function-id",
    )
    return AnthropicFilesConfig().transform_list_files_response(
        raw_response=httpx.Response(200, content=body), logging_obj=logging_obj, litellm_params={}
    )


def _anthropic_file(index: int) -> dict[str, object]:
    return {
        "id": f"file-{index}",
        "type": "file",
        "filename": f"doc-{index}.pdf",
        "mime_type": "application/pdf",
        "size_bytes": index,
        "created_at": "2025-01-01T00:00:00Z",
        "downloadable": False,
    }


def test_list_files_response_maps_every_anthropic_file_in_provider_order() -> None:
    result = _listed_files(
        json.dumps(
            {
                "data": [
                    _anthropic_file(100),
                    {"id": "file-b", "filename": "b.jsonl", "bytes": 200, "created_at": "2025-01-02T00:00:00Z"},
                    {"id": "file-c", "filename": "c.jsonl", "size_bytes": "300", "purpose": "batch", "created_at": ""},
                ],
                "has_more": False,
                "first_id": "file-100",
                "last_id": "file-c",
            }
        ).encode()
    )

    assert [(listed.id, listed.filename, listed.bytes, listed.purpose) for listed in result] == [
        ("file-100", "doc-100.pdf", 100, "messages"),
        ("file-b", "b.jsonl", 200, "messages"),
        ("file-c", "c.jsonl", 300, "batch"),
    ]
    assert [type(listed.bytes) for listed in result] == [int, int, int]
    assert [listed.created_at for listed in result[:2]] == [1735689600, 1735776000]
    assert result[0] == OpenAIFileObject(
        id="file-100",
        bytes=100,
        created_at=1735689600,
        filename="doc-100.pdf",
        object="file",
        purpose="messages",
        status="uploaded",
        status_details=None,
    )


@pytest.mark.parametrize(
    "body",
    [
        b"{}",
        b'{"has_more": false}',
        b'{"data": []}',
        b'{"data": ""}',
        b'{"data": {}}',
        b'{"data": [], "unknown": [1, {"nested": null}]}',
    ],
)
def test_list_files_response_without_any_file_is_an_empty_list(body: bytes) -> None:
    assert _listed_files(body) == []


@pytest.mark.parametrize("body", [b'["file-abc123"]', b'"file-abc123"', b"null", b"7"])
def test_list_files_response_rejects_a_body_that_is_not_a_json_object(body: bytes) -> None:
    with pytest.raises(ValidationError) as exc_info:
        _listed_files(body)

    assert [error["type"] for error in exc_info.value.errors()] == ["dict_type"]


@pytest.mark.parametrize("body", [b'{"data": null}', b'{"data": 7}', b'{"data": 0}', b'{"data": true}'])
def test_list_files_response_rejects_data_that_cannot_be_iterated(body: bytes) -> None:
    with pytest.raises(ValidationError) as exc_info:
        _listed_files(body)

    assert [error["type"] for error in exc_info.value.errors()] == ["iterable_type"]


@pytest.mark.parametrize(
    "data",
    [
        ["file-abc123"],
        [None],
        [7],
        [["file-abc123"]],
        [_anthropic_file(0), "file-abc123"],
        "file-abc123",
        {"file-abc123": _anthropic_file(0)},
    ],
)
def test_list_files_response_rejects_a_listed_file_that_is_not_a_json_object(data: object) -> None:
    with pytest.raises(ValidationError) as exc_info:
        _listed_files(json.dumps({"data": data}).encode())

    assert [(error["type"], error["loc"]) for error in exc_info.value.errors()] == [("dict_type", ())]


def test_list_files_response_error_for_a_late_malformed_file_does_not_name_its_position() -> None:
    files = [_anthropic_file(index) for index in range(403)]

    with pytest.raises(ValidationError) as exc_info:
        _listed_files(json.dumps({"data": [*files, "file-abc123"]}).encode())

    assert "403" not in str(exc_info.value)
    assert "429" not in str(exc_info.value)
    assert "file-abc123" not in str(exc_info.value)


def test_list_files_response_reports_every_invalid_field_of_a_listed_file() -> None:
    with pytest.raises(ValidationError) as exc_info:
        _listed_files(b'{"data": [{"id": null, "filename": 7, "size_bytes": "many", "purpose": "unknown"}]}')

    assert [error["loc"] for error in exc_info.value.errors()] == [("id",), ("bytes",), ("filename",), ("purpose",)]
    assert "many" in str(exc_info.value)


@pytest.mark.parametrize(
    "data, expected_errors",
    [
        ([{"id": None}, "file-abc123"], [("string_type", ("id",))]),
        (["file-abc123", {"id": None}], [("dict_type", ())]),
        ([{"id": None}, {"filename": 7}], [("string_type", ("id",))]),
    ],
)
def test_list_files_response_reports_only_the_first_bad_file_in_provider_order(
    data: object, expected_errors: object
) -> None:
    with pytest.raises(ValidationError) as exc_info:
        _listed_files(json.dumps({"data": data}).encode())

    assert [(error["type"], error["loc"]) for error in exc_info.value.errors()] == expected_errors