repo
stringclasses
454 values
file_path
stringlengths
5
201
extension
stringclasses
1 value
content
stringlengths
8
509k
num_lines
int64
3
16.9k
size_bytes
int64
8
511k
openai-agents-python
src/agents/voice/models/openai_tts.py
.py
from collections.abc import AsyncIterator from typing import Literal from openai import AsyncOpenAI, omit from ..model import TTSModel, TTSModelSettings DEFAULT_VOICE: Literal["ash"] = "ash" class OpenAITTSModel(TTSModel): """A text-to-speech model for OpenAI.""" def __init__( self, model:...
56
1,557
openai-agents-python
src/agents/mcp/server.py
.py
from __future__ import annotations import abc import asyncio import inspect import json import math import sys from collections.abc import AsyncGenerator, Awaitable, Callable from contextlib import AbstractAsyncContextManager, AsyncExitStack, asynccontextmanager from datetime import timedelta from pathlib import Path ...
2,552
108,979
openai-agents-python
src/agents/mcp/_compat.py
.py
from __future__ import annotations from functools import cache from importlib import import_module from importlib.metadata import version from typing import Any, cast from pydantic import AnyUrl from .._httpx_compat import legacy_httpx_types, require_legacy_httpx def _major_version(distribution: str) -> int: r...
192
6,232
openai-agents-python
src/agents/mcp/manager.py
.py
from __future__ import annotations import asyncio import math from collections.abc import Awaitable, Callable, Iterable from contextlib import AbstractAsyncContextManager from dataclasses import dataclass from typing import Any from ..logger import log_tool_action_debug, log_tool_action_error, logger from ._logging i...
572
22,566
openai-agents-python
src/agents/mcp/util.py
.py
from __future__ import annotations import asyncio import copy import functools import hashlib import inspect import json from collections import Counter from collections.abc import Awaitable, Callable, Mapping from dataclasses import dataclass from types import MappingProxyType from typing import TYPE_CHECKING, Any, P...
834
31,801
openai-agents-python
src/agents/mcp/__init__.py
.py
from __future__ import annotations from importlib import import_module from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from .manager import MCPServerManager from .server import ( LocalMCPApprovalCallable, MCPServer, MCPServerSse, MCPServerSseParams, MCPServerStd...
88
2,239
openai-agents-python
src/agents/mcp/_logging.py
.py
from typing import Protocol from urllib.parse import urlsplit, urlunsplit from .. import _debug _URL_DERIVED_NAME_PREFIXES = ("sse: ", "streamable_http: ", "streamable-http: ") class _MCPServerNameSource(Protocol): @property def name(self) -> str: ... def get_mcp_server_log_name(name: str) -> str: """...
53
1,652
openai-agents-python
src/agents/realtime/model_inputs.py
.py
from __future__ import annotations from dataclasses import dataclass from typing import Any, Literal, TypeAlias from typing_extensions import NotRequired, TypedDict from .config import RealtimeSessionModelSettings from .model_events import RealtimeModelToolCallEvent class RealtimeModelRawClientMessage(TypedDict): ...
132
3,341
openai-agents-python
src/agents/realtime/audio_formats.py
.py
from __future__ import annotations from collections.abc import Mapping from typing import Any, Literal from openai.types.realtime.realtime_audio_formats import ( AudioPCM, AudioPCMA, AudioPCMU, RealtimeAudioFormats, ) from .. import _debug from ..logger import logger def to_realtime_audio_format( ...
63
2,557
openai-agents-python
src/agents/realtime/openai_realtime.py
.py
from __future__ import annotations import asyncio import base64 import inspect import json import math import os import time from collections.abc import Callable, Mapping from dataclasses import dataclass from typing import Annotated, Any, Literal, TypeAlias, cast import pydantic import websockets from openai.types.r...
2,134
88,489
openai-agents-python
src/agents/realtime/_util.py
.py
from __future__ import annotations from collections.abc import Mapping from openai.types.realtime.realtime_audio_formats import AudioPCMA, AudioPCMU from .config import RealtimeAudioFormat PCM16_SAMPLE_RATE_HZ = 24_000 PCM16_SAMPLE_WIDTH_BYTES = 2 G711_SAMPLE_RATE_HZ = 8_000 # Every spelling of the two G.711 famil...
49
1,963
openai-agents-python
src/agents/realtime/runner.py
.py
"""Minimal realtime session implementation for voice agents.""" from __future__ import annotations from ..run_context import TContext from .agent import RealtimeAgent from .config import ( RealtimeRunConfig, ) from .model import ( RealtimeModel, RealtimeModelConfig, ) from .openai_realtime import OpenAIRe...
80
2,628
openai-agents-python
src/agents/realtime/model.py
.py
from __future__ import annotations import abc from collections.abc import Callable from typing_extensions import NotRequired, TypedDict from ..util._types import MaybeAwaitable from ._util import calculate_audio_length_ms from .config import ( RealtimeAudioFormat, RealtimeSessionModelSettings, ) from .model_...
197
7,665
openai-agents-python
src/agents/realtime/__init__.py
.py
from .agent import RealtimeAgent, RealtimeAgentHooks, RealtimeRunHooks from .config import ( RealtimeAudioFormat, RealtimeClientMessage, RealtimeGuardrailsSettings, RealtimeInputAudioNoiseReductionConfig, RealtimeInputAudioTranscriptionConfig, RealtimeModelName, RealtimeModelTracingConfig, ...
204
5,701
openai-agents-python
src/agents/realtime/handoffs.py
.py
from __future__ import annotations import inspect from collections.abc import Callable, Iterable from functools import partial from typing import TYPE_CHECKING, Any, cast, overload from pydantic import TypeAdapter from typing_extensions import TypeVar from ..exceptions import ( ModelBehaviorError, UserError,...
209
8,165
openai-agents-python
src/agents/realtime/testing.py
.py
"""Deterministic Realtime model transport for session tests.""" from __future__ import annotations import asyncio import copy from collections import deque from collections.abc import Callable, Iterable, Sequence from dataclasses import dataclass, field from typing import TypeAlias, cast from typing_extensions impor...
479
17,296
openai-agents-python
src/agents/realtime/_tool_validation.py
.py
from __future__ import annotations from collections import Counter from collections.abc import Iterable from typing import Any from ..exceptions import UserError from ..handoffs import Handoff from ..tool import FunctionTool, Tool def validate_realtime_tool_names( tools: Iterable[Tool], handoffs: Iterable[H...
55
1,708
openai-agents-python
src/agents/realtime/model_events.py
.py
from __future__ import annotations from dataclasses import dataclass from typing import Any, Literal, TypeAlias from ..usage import Usage from .items import RealtimeItem RealtimeConnectionStatus: TypeAlias = Literal["connecting", "connected", "disconnected"] @dataclass class RealtimeModelErrorEvent: """Represe...
258
6,072
openai-agents-python
src/agents/realtime/session.py
.py
from __future__ import annotations import asyncio import dataclasses import inspect import json from collections.abc import AsyncIterator, Sequence from functools import partial from typing import Any, cast from pydantic import BaseModel from typing_extensions import assert_never from .. import _debug from .._tool_i...
2,112
86,191
openai-agents-python
src/agents/realtime/config.py
.py
from __future__ import annotations from collections.abc import Mapping from typing import Any, Literal, TypeAlias from openai.types.realtime.realtime_audio_formats import ( RealtimeAudioFormats as OpenAIRealtimeAudioFormats, ) from typing_extensions import NotRequired, TypedDict from agents.prompts import Prompt...
342
11,054
openai-agents-python
src/agents/realtime/_default_tracker.py
.py
from __future__ import annotations import time from dataclasses import dataclass from ._util import calculate_audio_length_ms from .config import RealtimeAudioFormat @dataclass class ModelAudioState: initial_received_time: float audio_length_ms: float response_id: str | None = None @dataclass class Mo...
98
4,124
openai-agents-python
src/agents/realtime/items.py
.py
from __future__ import annotations from typing import Annotated, Literal from pydantic import BaseModel, ConfigDict, Field class InputText(BaseModel): """Text input content for realtime messages.""" type: Literal["input_text"] = "input_text" """The type identifier for text input.""" text: str | No...
201
5,499
openai-agents-python
src/agents/realtime/agent.py
.py
from __future__ import annotations import dataclasses import inspect from collections.abc import Callable from dataclasses import dataclass, field from typing import Any, Generic from agents.prompts import Prompt from .. import _debug from ..agent import AgentBase from ..guardrail import OutputGuardrail from ..hando...
140
5,910
openai-agents-python
src/agents/realtime/events.py
.py
from __future__ import annotations from dataclasses import dataclass from typing import Any, Literal, TypeAlias from ..guardrail import OutputGuardrailResult from ..run_context import RunContextWrapper from ..tool import Tool from .agent import RealtimeAgent from .items import RealtimeItem from .model_events import R...
274
6,618
openai-agents-python
src/agents/realtime/_tool_filtering.py
.py
from __future__ import annotations import inspect from collections.abc import Iterable from typing import Any from ..agent import AgentBase from ..run_context import RunContextWrapper from ..tool import FunctionTool, Tool from ..util._asyncio_tasks import gather_with_cancel async def filter_enabled_tools( tools...
40
1,194
openai-agents-python
src/agents/memory/util.py
.py
from __future__ import annotations from collections.abc import Callable from ..items import TResponseInputItem from ..util._types import MaybeAwaitable SessionInputCallback = Callable[ [list[TResponseInputItem], list[TResponseInputItem]], MaybeAwaitable[list[TResponseInputItem]], ] """A function that combine...
21
595
openai-agents-python
src/agents/memory/__init__.py
.py
from __future__ import annotations from typing import TYPE_CHECKING, Any from .openai_conversations_session import OpenAIConversationsSession from .openai_responses_compaction_session import OpenAIResponsesCompactionSession from .session import ( OpenAIResponsesCompactionArgs, OpenAIResponsesCompactionAwareSe...
42
1,151
openai-agents-python
src/agents/memory/sqlite_session.py
.py
from __future__ import annotations import asyncio import json import sqlite3 import threading import time from collections.abc import Awaitable, Iterator from contextlib import closing, contextmanager from pathlib import Path from typing import Any, ClassVar, TypeVar from ..items import TResponseInputItem from .sessi...
491
19,343
openai-agents-python
src/agents/memory/openai_conversations_session.py
.py
from __future__ import annotations import asyncio from typing import Any from openai import AsyncOpenAI from agents.models._openai_shared import get_default_openai_client from ..items import TResponseInputItem from .session import SessionABC from .session_settings import SessionSettings, coerce_session_settings, re...
144
5,234
openai-agents-python
src/agents/memory/session.py
.py
from __future__ import annotations import inspect from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Any, Literal, Protocol, TypeGuard, runtime_checkable from typing_extensions import TypedDict if TYPE_CHECKING: from ..items import TResponseInputItem from ..run_context import RunContextWra...
213
6,763
openai-agents-python
src/agents/memory/session_settings.py
.py
"""Session configuration settings.""" from __future__ import annotations import dataclasses from dataclasses import fields, replace from typing import Any from pydantic.dataclasses import dataclass from .._config_coercion import ( _dataclass_input_values, _declared_dataclass_type, coerce_dataclass_confi...
87
2,629
openai-agents-python
src/agents/memory/openai_responses_compaction_session.py
.py
from __future__ import annotations import asyncio import logging from collections.abc import Awaitable, Callable from typing import TYPE_CHECKING, Any, Literal, cast from openai import AsyncOpenAI from ..items import TResponseInputItem from ..logger import log_model_and_tool_action_warning from ..models._openai_shar...
605
23,117
openai-agents-python
src/agents/models/chatcmpl_helpers.py
.py
from __future__ import annotations from collections.abc import Mapping from contextvars import ContextVar from typing import Any from openai import AsyncOpenAI from openai.types.chat.chat_completion_token_logprob import ChatCompletionTokenLogprob from openai.types.responses.response_output_text import ( Annotatio...
171
6,568
openai-agents-python
src/agents/models/_retry_runtime.py
.py
from __future__ import annotations import time from collections.abc import Iterator, Mapping from contextlib import contextmanager from contextvars import ContextVar from email.utils import parsedate_to_datetime from typing import Any, cast import httpx2 from openai import APIStatusError from .._httpx_compat import ...
172
5,463
openai-agents-python
src/agents/models/default_models.py
.py
import copy import os import re from typing import Literal from openai.types.shared.reasoning import Reasoning from agents.model_settings import ModelSettings OPENAI_DEFAULT_MODEL_ENV_VARIABLE_NAME = "OPENAI_DEFAULT_MODEL" GPT5DefaultReasoningEffort = Literal["none", "low", "medium"] # discourage directly accessin...
121
4,718
openai-agents-python
src/agents/models/_trace.py
.py
from __future__ import annotations from typing import Any from urllib.parse import urlsplit, urlunsplit from ..model_settings import ModelSettings def sanitize_url_for_trace(url: object) -> str: """Return a URL safe for tracing by removing auth material and request parameters.""" try: parts = urlspl...
32
877
openai-agents-python
src/agents/models/_response_terminal.py
.py
from __future__ import annotations from typing import Any from openai.types.responses import Response from ..exceptions import ModelBehaviorError, _mark_error_to_drain_stream_events def format_response_terminal_failure( event_type: str, response: Response | None, ) -> str: message = f"Responses stream ...
65
2,002
openai-agents-python
src/agents/models/fake_id.py
.py
FAKE_RESPONSES_ID = "__fake_id__" """This is a placeholder ID used to fill in the `id` field in Responses API related objects. It's useful when you're creating Responses objects from non-Responses APIs, e.g. the OpenAI Chat Completions API or other LLM providers. """
6
268
openai-agents-python
src/agents/models/openai_responses.py
.py
from __future__ import annotations import asyncio import contextlib import inspect import json import weakref from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Callable, Mapping, Sequence from contextvars import ContextVar from dataclasses import asdict, dataclass, is_dataclass from enum import Enum...
2,298
93,225
openai-agents-python
src/agents/models/__init__.py
.py
from .default_models import ( get_default_model, get_default_model_settings, gpt_5_reasoning_settings_required, is_gpt_5_default, ) from .openai_agent_registration import OpenAIAgentRegistrationConfig __all__ = [ "get_default_model", "get_default_model_settings", "gpt_5_reasoning_settings_r...
16
393
openai-agents-python
src/agents/models/_run_context.py
.py
from __future__ import annotations from collections.abc import AsyncGenerator, Iterator from contextlib import aclosing, contextmanager from contextvars import ContextVar from typing import TypeVar _MODEL_RUN_OWNER: ContextVar[object | None] = ContextVar("model_run_owner", default=None) T = TypeVar("T") @contextma...
36
1,016
openai-agents-python
src/agents/models/_openai_retry.py
.py
from __future__ import annotations from openai import APIConnectionError, APITimeoutError from ..retry import ModelRetryAdvice, ModelRetryAdviceRequest, ModelRetryNormalizedError from ._retry_runtime import ( get_error_code as _get_error_code, get_error_header as _get_header_value, get_request_id as _get_...
113
3,558
openai-agents-python
src/agents/models/chatcmpl_stream_handler.py
.py
from __future__ import annotations from collections.abc import AsyncIterator, Iterator from dataclasses import dataclass, field from typing import Any, cast from openai import AsyncStream from openai.types.chat import ChatCompletionChunk from openai.types.chat.chat_completion_chunk import ( Choice, ChoiceDelt...
1,331
61,083
openai-agents-python
src/agents/models/_openai_shared.py
.py
from __future__ import annotations from typing import Literal from openai import AsyncOpenAI OpenAIResponsesTransport = Literal["http", "websocket"] _default_openai_key: str | None = None _default_openai_client: AsyncOpenAI | None = None _use_responses_by_default: bool = True # Source of truth for the default Respo...
69
2,318
openai-agents-python
src/agents/models/openai_provider.py
.py
from __future__ import annotations import asyncio import os import weakref from typing import Any import httpx2 from openai import AsyncOpenAI, DefaultAsyncHttpx2Client from ..exceptions import UserError from . import _openai_shared from .default_models import get_default_model from .interface import Model, ModelPro...
284
12,185
openai-agents-python
src/agents/models/openai_agent_registration.py
.py
from __future__ import annotations import os from dataclasses import dataclass from typing import Any from .._config_coercion import coerce_dataclass_config _ENV_HARNESS_ID = "OPENAI_AGENT_HARNESS_ID" OPENAI_HARNESS_ID_TRACE_METADATA_KEY = "agent_harness_id" @dataclass(frozen=True) class OpenAIAgentRegistrationCon...
122
4,082
openai-agents-python
src/agents/models/reasoning_content_replay.py
.py
from __future__ import annotations from collections.abc import Callable, Mapping from dataclasses import dataclass from typing import Any _CHAT_COMPLETIONS_REASONING_FIELD_KEY = "_chat_completions_reasoning_field" @dataclass class ReasoningContentSource: """The reasoning item being considered for replay into th...
67
2,116
openai-agents-python
src/agents/models/openai_chatcompletions.py
.py
from __future__ import annotations import asyncio import inspect import json import time from collections.abc import AsyncIterator from typing import TYPE_CHECKING, Any, Literal, cast, overload from openai import AsyncOpenAI, AsyncStream, Omit, omit from openai.types import ChatModel from openai.types.chat import Cha...
782
32,547
openai-agents-python
src/agents/models/multi_provider.py
.py
from __future__ import annotations import asyncio from typing import Any, Literal, cast from openai import AsyncOpenAI from ..exceptions import UserError from .interface import Model, ModelProvider from .openai_agent_registration import OpenAIAgentRegistrationConfig from .openai_provider import OpenAIProvider from ....
280
12,731
openai-agents-python
src/agents/models/openai_client_utils.py
.py
from __future__ import annotations from urllib.parse import urlsplit from openai import AsyncOpenAI def is_official_openai_base_url(base_url: object, *, websocket: bool = False) -> bool: parsed = urlsplit(str(base_url)) expected_scheme = "wss" if websocket else "https" return parsed.scheme == expected_s...
19
572
openai-agents-python
src/agents/models/interface.py
.py
from __future__ import annotations import abc import enum from collections.abc import AsyncIterator from typing import TYPE_CHECKING from openai.types.responses.response_prompt_param import ResponsePromptParam from ..agent_output import AgentOutputSchemaBase from ..handoffs import Handoff from ..items import ModelRe...
162
5,593
openai-agents-python
src/agents/models/chatcmpl_converter.py
.py
from __future__ import annotations import json from collections.abc import Iterable, Mapping from copy import deepcopy from typing import Any, Literal, cast from openai import Omit, omit from openai.types.chat import ( ChatCompletionAssistantMessageParam, ChatCompletionContentPartImageParam, ChatCompletio...
1,003
45,813
openai-agents-python
src/agents/util/_pretty_print.py
.py
from typing import TYPE_CHECKING from pydantic import BaseModel if TYPE_CHECKING: from ..exceptions import RunErrorDetails from ..result import RunResult, RunResultBase, RunResultStreaming def _indent(text: str, indent_level: int) -> str: indent_string = " " * indent_level return "\n".join(f"{inden...
72
3,014
openai-agents-python
src/agents/util/_custom_data.py
.py
from __future__ import annotations import copy import inspect import json from collections.abc import Awaitable, Callable, Mapping from typing import Any, TypeVar, cast from ..exceptions import UserError TContext = TypeVar("TContext") CustomDataExtractor = Callable[ [TContext], Awaitable[Mapping[str, Any] | Non...
58
1,895
openai-agents-python
src/agents/util/_coro.py
.py
async def noop_coroutine() -> None: pass
3
45
openai-agents-python
src/agents/util/_transforms.py
.py
import re from ..logger import logger def transform_string_function_style(name: str, *, warn_on_whitespace: bool = True) -> str: whitespace_normalized_name = re.sub(r"\s", "_", name) transformed_name = re.sub(r"[^a-zA-Z0-9_]", "_", whitespace_normalized_name) final_name = transformed_name.lower() i...
24
761
openai-agents-python
src/agents/util/_approvals.py
.py
from __future__ import annotations import inspect import json from collections.abc import Callable from typing import Any, NoReturn from ..exceptions import UserError # Keep this helper here so both run_internal and realtime can import it without # creating cross-package dependencies. def _reject_nonstandard_json_...
50
1,612
openai-agents-python
src/agents/util/_tool_errors.py
.py
"""Helpers for rendering tool errors in trace-safe form.""" from ._error_tracing import get_trace_error REDACTED_TOOL_ERROR_MESSAGE = "Tool execution failed. Error details are redacted." def get_trace_tool_error(*, trace_include_sensitive_data: bool, error_message: str) -> str: """Return a trace-safe tool error...
15
560
openai-agents-python
src/agents/util/_json.py
.py
from __future__ import annotations from collections.abc import Iterable, Mapping from typing import Any, Literal from pydantic import TypeAdapter, ValidationError from typing_extensions import TypeVar from .. import _debug from ..exceptions import ModelBehaviorError, _mark_error_data_redacted from ..tracing import S...
80
2,611
openai-agents-python
src/agents/util/_types.py
.py
from collections.abc import Awaitable from typing import TypeAlias from typing_extensions import TypeVar T = TypeVar("T") MaybeAwaitable: TypeAlias = Awaitable[T] | T
8
169
openai-agents-python
src/agents/util/_error_tracing.py
.py
import asyncio import contextlib from collections.abc import Iterator from typing import Any from .. import _debug from ..exceptions import ModelTimeoutError from ..logger import logger from ..tracing import Span, SpanError, get_current_span REDACTED_TRACE_ERROR_MESSAGE = "Error details are redacted." _MODEL_TIMEOUT_...
154
5,095
openai-agents-python
src/agents/util/_asyncio_tasks.py
.py
from __future__ import annotations import asyncio from collections.abc import Awaitable, Callable from typing import Any, TypeVar, overload T = TypeVar("T") T1 = TypeVar("T1") T2 = TypeVar("T2") T3 = TypeVar("T3") T4 = TypeVar("T4") T5 = TypeVar("T5") T6 = TypeVar("T6") TProducer = TypeVar("TProducer") TConsumer = Ty...
153
4,261
openai-agents-python
src/agents/handoffs/__init__.py
.py
from __future__ import annotations import inspect import json import weakref from collections.abc import Awaitable, Callable from dataclasses import dataclass, field, replace as dataclasses_replace from functools import partial from typing import TYPE_CHECKING, Any, Generic, TypeAlias, cast, overload from pydantic im...
389
15,662
openai-agents-python
src/agents/handoffs/history.py
.py
from __future__ import annotations import json from collections import deque from collections.abc import Mapping from copy import deepcopy from dataclasses import replace from typing import TYPE_CHECKING, Any, cast from ..items import ( ItemHelpers, RunItem, ToolApprovalItem, TResponseInputItem, ) if...
665
24,605
pydantic
pydantic-core/python/pydantic_core/__init__.py
.py
from __future__ import annotations import sys as _sys from typing import Any as _Any from typing_extensions import Sentinel from ._pydantic_core import ( ArgsKwargs, MultiHostUrl, PydanticCustomError, PydanticKnownError, PydanticOmit, PydanticSerializationError, PydanticSerializationUnexp...
172
5,115
pydantic
pydantic-core/python/pydantic_core/core_schema.py
.py
""" This module contains definitions to build schemas which `pydantic_core` can validate and serialize. """ from __future__ import annotations as _annotations import sys import warnings from collections.abc import Callable, Generator, Hashable, Mapping from datetime import date, datetime, time, timedelta from decimal...
4,664
161,644
pydantic
pydantic-core/tests/test_misc.py
.py
import copy import os import pickle import pytest from typing_extensions import ( # noqa: UP035 (for `get_args` and `get_origin`) get_args, get_origin, get_type_hints, ) from typing_inspection import typing_objects from typing_inspection.introspection import UNKNOWN, AnnotationSource, inspect_annotation ...
262
9,281
pydantic
pydantic-core/tests/test_errors.py
.py
import enum import os import pickle import re import subprocess import sys from decimal import Decimal from typing import Any import pytest from dirty_equals import HasRepr, IsInstance, IsJson, IsStr from pytest_mock import MockerFixture from pydantic_core import ( CoreConfig, PydanticCustomError, Pydanti...
1,196
50,170
pydantic
pydantic-core/tests/test_config.py
.py
import math import re import pytest from dirty_equals import FunctionCheck, HasAttributes, IsInstance from pydantic_core import CoreConfig, SchemaValidator, ValidationError from pydantic_core import core_schema as cs from .conftest import Err, plain_repr def test_on_field(): v = SchemaValidator(cs.str_schema(m...
152
5,158
pydantic
pydantic-core/tests/test_custom_errors.py
.py
from typing import Any from unittest import TestCase from unittest.mock import ANY import pytest from typing_extensions import LiteralString, Self, override from pydantic_core import ErrorDetails, InitErrorDetails, PydanticCustomError, ValidationError def test_validation_error_subclassable(): """Assert subclass...
151
5,560
pydantic
pydantic-core/tests/test_docstrings.py
.py
import sys from pathlib import Path import pytest if sys.platform != 'emscripten': from pytest_examples import CodeExample, EvalExample, find_examples else: # pytest_examples is not installed on emscripten CodeExample = EvalExample = None def find_examples(*args, **kwargs): return [] PYDANT...
45
1,658
pydantic
pydantic-core/tests/test_hypothesis.py
.py
import json import re import sys from datetime import datetime, timezone from typing import Optional import pytest from dirty_equals import AnyThing, IsBytes, IsStr, IsTuple from hypothesis import given, strategies from typing_extensions import TypedDict from pydantic_core import SchemaSerializer, SchemaValidator, Va...
197
7,052
pydantic
pydantic-core/tests/test_isinstance.py
.py
import pytest from pydantic_core import SchemaValidator, ValidationError from pydantic_core import core_schema as cs def test_isinstance(): v = SchemaValidator(cs.int_schema()) assert v.validate_python(123) == 123 assert v.isinstance_python(123) is True assert v.validate_python('123') == 123 asse...
38
1,245
pydantic
pydantic-core/tests/test_build.py
.py
import pickle import pytest from pydantic_core import SchemaValidator from pydantic_core import core_schema as cs @pytest.mark.parametrize('pickle_protocol', range(1, pickle.HIGHEST_PROTOCOL + 1)) def test_pickle(pickle_protocol: int) -> None: v1 = SchemaValidator(cs.bool_schema()) assert v1.validate_python...
79
2,476
pydantic
pydantic-core/tests/test_typing.py
.py
from __future__ import annotations as _annotations from collections.abc import Callable from datetime import date, datetime, time from typing import Any import pytest from pydantic_core import ( CoreSchema, ErrorDetails, PydanticKnownError, SchemaError, SchemaSerializer, SchemaValidator, ...
262
9,170
pydantic
pydantic-core/tests/test_prebuilt.py
.py
from pydantic_core import SchemaSerializer, SchemaValidator, core_schema def test_prebuilt_val_and_ser_used() -> None: class InnerModel: x: int inner_schema = core_schema.model_schema( InnerModel, schema=core_schema.model_fields_schema( {'x': core_schema.model_field(schema...
497
18,584
pydantic
pydantic-core/tests/test_json.py
.py
import platform import pytest from dirty_equals import IsList import pydantic_core from pydantic_core import ( CoreConfig, PydanticSerializationError, SchemaSerializer, SchemaValidator, ValidationError, core_schema, from_json, to_json, to_jsonable_python, ) class Foobar: def ...
277
10,093
pydantic
pydantic-core/tests/test_garbage_collection.py
.py
import platform from collections.abc import Iterable from enum import Enum from typing import Any from weakref import WeakValueDictionary import pytest from pydantic_core import SchemaSerializer, SchemaValidator, core_schema from .conftest import assert_gc GC_TEST_SCHEMA_INNER = core_schema.definitions_schema( ...
211
6,320
pydantic
pydantic-core/tests/test_schema_functions.py
.py
import dataclasses from datetime import date from enum import Enum from typing import Any, NamedTuple import pytest from typing_extensions import get_args, get_type_hints # noqa: UP035 from typing_inspection.introspection import UNKNOWN, AnnotationSource, inspect_annotation from pydantic_core import SchemaError, Sch...
409
15,896
pydantic
pydantic-core/tests/test_tzinfo.py
.py
"""Adapted from CPython `timezone` tests. Original tests are located here https://github.com/python/cpython/blob/a0bb4a39d1ca10e4a75f50a9fbe90cc9db28d29e/Lib/test/datetimetester.py#L256 """ import copy import functools import pickle import sys from datetime import datetime, timedelta, timezone, tzinfo from zoneinfo i...
251
6,862
pydantic
pydantic-core/tests/conftest.py
.py
from __future__ import annotations as _annotations import functools import gc import importlib.util import json import os import re import sys from collections.abc import Callable from dataclasses import dataclass from pathlib import Path from time import sleep, time from typing import Any, Literal import hypothesis ...
198
5,754
pydantic
pydantic-core/tests/serializers/test_literal.py
.py
from dataclasses import dataclass from enum import Enum from typing import Literal import pytest from pydantic_core import SchemaError, SchemaSerializer, core_schema from ..conftest import plain_repr def test_int_literal(): s = SchemaSerializer(core_schema.literal_schema([1, 2, 3])) r = plain_repr(s) a...
150
5,620
pydantic
pydantic-core/tests/serializers/test_any.py
.py
import dataclasses import ipaddress import json import platform import re import sys from collections import namedtuple from datetime import date, datetime, time, timedelta, timezone from decimal import Decimal from enum import Enum from math import inf, isinf, isnan, nan from pathlib import Path from typing import Cla...
776
30,674
pydantic
pydantic-core/tests/serializers/test_format.py
.py
import json import re from datetime import date from uuid import UUID import pytest from pydantic_core import PydanticSerializationError, SchemaSerializer, core_schema @pytest.mark.parametrize( 'value,formatting_string,expected_python,expected_json', [ (42.12345, '0.4f', 42.12345, b'"42.1234"'), ...
126
4,659
pydantic
pydantic-core/tests/serializers/test_pickling.py
.py
import json import pickle from datetime import timedelta import pytest from pydantic_core import core_schema from pydantic_core._pydantic_core import SchemaSerializer def repr_function(value, _info): return repr(value) def test_basic_schema_serializer(): s = SchemaSerializer(core_schema.dict_schema()) ...
74
2,655
pydantic
pydantic-core/tests/serializers/test_functions.py
.py
import json import os import platform import re import sys from collections import deque from operator import attrgetter from pathlib import Path import pytest from pydantic_core import ( PydanticOmit, PydanticSerializationError, PydanticSerializationUnexpectedValue, SchemaSerializer, core_schema,...
713
25,496
pydantic
pydantic-core/tests/serializers/test_bytes.py
.py
import base64 import json from enum import Enum import pytest from pydantic_core import PydanticSerializationError, SchemaSerializer, core_schema, to_json def test_bytes(): s = SchemaSerializer(core_schema.bytes_schema()) assert s.to_python(b'foobar') == b'foobar' assert s.to_python('emoji 💩'.encode())...
179
6,186
pydantic
pydantic-core/tests/serializers/test_enum.py
.py
from enum import Enum import pytest from pydantic_core import SchemaSerializer, core_schema def test_plain_enum(): class MyEnum(Enum): a = 1 b = 2 v = SchemaSerializer(core_schema.enum_schema(MyEnum, list(MyEnum.__members__.values()))) # debug(v) assert v.to_python(MyEnum.a) is MyE...
136
4,127
pydantic
pydantic-core/tests/serializers/test_uuid.py
.py
from uuid import UUID import pytest from pydantic_core import SchemaSerializer, core_schema def test_uuid(): v = SchemaSerializer(core_schema.uuid_schema()) assert v.to_python(UUID('12345678-1234-5678-1234-567812345678')) == UUID('12345678-1234-5678-1234-567812345678') assert ( v.to_python(UUID...
65
2,738
pydantic
pydantic-core/tests/serializers/test_json_or_python.py
.py
from enum import Enum from pydantic_core import SchemaSerializer, core_schema def test_json_or_python(): def s1(v: int) -> int: return v + 1 def s2(v: int) -> int: return v + 2 s = SchemaSerializer( core_schema.json_or_python_schema( core_schema.int_schema(serializat...
43
1,198
pydantic
pydantic-core/tests/serializers/test_datetime.py
.py
from datetime import date, datetime, time, timedelta, timezone from typing import Literal import pytest from pydantic_core import SchemaSerializer, core_schema def test_datetime(): v = SchemaSerializer(core_schema.datetime_schema()) assert v.to_python(datetime(2022, 12, 2, 12, 13, 14)) == datetime(2022, 12,...
423
15,928
pydantic
pydantic-core/tests/serializers/test_timedelta.py
.py
from datetime import timedelta import pytest from pydantic_core import SchemaSerializer, core_schema try: import pandas except ImportError: pandas = None def test_timedelta(): v = SchemaSerializer(core_schema.timedelta_schema()) assert v.to_python(timedelta(days=2, hours=3, minutes=4)) == timedelta...
374
13,468
pydantic
pydantic-core/tests/serializers/test_string.py
.py
import json from enum import Enum import pytest from pydantic_core import PydanticSerializationError, SchemaSerializer, core_schema def test_str(): v = SchemaSerializer(core_schema.str_schema()) assert v.to_python('foobar') == 'foobar' assert v.to_python('emoji 💩') == 'emoji 💩' assert v.to_json('f...
189
7,335
pydantic
pydantic-core/tests/serializers/test_nullable.py
.py
import pytest from pydantic_core import SchemaSerializer, core_schema def test_nullable(): s = SchemaSerializer(core_schema.nullable_schema(core_schema.int_schema())) assert s.to_python(None) is None assert s.to_python(1) == 1 assert s.to_python(None, mode='json') is None assert s.to_python(1, mo...
19
614
pydantic
pydantic-core/tests/serializers/test_definitions.py
.py
import pytest from pydantic_core import SchemaError, SchemaSerializer, core_schema def test_custom_ser(): s = SchemaSerializer( core_schema.definitions_schema( core_schema.list_schema(core_schema.definition_reference_schema('foobar')), [core_schema.int_schema(ref='foobar', seriali...
123
4,515
pydantic
pydantic-core/tests/serializers/test_decimal.py
.py
from decimal import Decimal import pytest from pydantic_core import SchemaSerializer, core_schema def test_decimal(): v = SchemaSerializer(core_schema.decimal_schema()) assert v.to_python(Decimal('123.456')) == Decimal('123.456') assert v.to_python(Decimal('123.456'), mode='json') == '123.456' asse...
64
2,267
pydantic
pydantic-core/tests/serializers/test_url.py
.py
import pickle import pytest from pydantic_core import MultiHostUrl, SchemaSerializer, SchemaValidator, Url, core_schema def test_url(): v = SchemaValidator(core_schema.url_schema()) s = SchemaSerializer(core_schema.url_schema()) url = v.validate_python('https://example.com') assert isinstance(url, ...
112
4,408
pydantic
pydantic-core/tests/serializers/test_union.py
.py
from __future__ import annotations import dataclasses import json import uuid import warnings from decimal import Decimal from typing import Any, ClassVar, Literal import pytest from pydantic_core import PydanticSerializationUnexpectedValue, SchemaSerializer, core_schema class BaseModel: def __init__(self, **k...
1,119
39,393
pydantic
pydantic-core/tests/serializers/test_dict.py
.py
import json import pytest from dirty_equals import IsStrictDict from pydantic_core import SchemaSerializer, core_schema def test_dict_str_int(): v = SchemaSerializer(core_schema.dict_schema(core_schema.str_schema(), core_schema.int_schema())) assert v.to_python({'a': 1, 'b': 2, 'c': 3}) == {'a': 1, 'b': 2, ...
146
7,003
pydantic
pydantic-core/tests/serializers/test_dataclasses.py
.py
import dataclasses import json import platform from typing import ClassVar import pytest from pydantic_core import SchemaSerializer, SchemaValidator, core_schema on_pypy = platform.python_implementation() == 'PyPy' # pypy doesn't seem to maintain order of `__dict__` if on_pypy: IsStrictDict = dict else: from...
287
9,427