failed WRONG_FIX wrong_fix ยท 40 tool calls ยท 214 s ยท fastapi/fastapi
๐ Fix handling arbitrary types when using `arbitrary_types_allowed=True` ๐ Fix handling arbitrary types when using `arbitrary_types_allowed=True` Related to https://github.com/fastapi/fastapi/discussions/14184, https://github.com/fastapi/fastapi/issues/14483
| # | Tool | Arguments | Result |
|---|---|---|---|
| 1 | run_command | {
"command": "grep -rn \"arbitrary_types_allowed\" . | head -20"
} | {"status": "ok", "stdout": "./tests/test_inherited_custom_class.py:45: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_inherited_custom_class.pfull{"status": "ok", "stdout": "./tests/test_inherited_custom_class.py:45: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_inherited_custom_class.py:89: arbitrary_types_allowed = True\n./tests/test_jsonable_encoder.py:248: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_jsonable_encoder.py:252: arbitrary_types_allowed = True\n./tests/test_jsonable_encoder.py:264: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_jsonable_encoder.py:268: arbitrary_types_allowed = True\n./tests/test_jsonable_encoder.py:279: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_jsonable_encoder.py:283: arbitrary_types_allowed = True\n./tests/test_compat.py:87: model_config = ConfigDict(arbitrary_types_allowed=True)\n./tests/test_compat.py:92: arbitrary_types_allowed=True,\n", "stderr": "", "exit_code": 0} |
| 2 | run_command | {
"command": "grep -rn \"arbitrary_types_allowed\" fastapi | head -20"
} | {"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}full{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0} |
| 3 | run_command | {
"command": "grep -rn \"arbitrary_types_allowed\" fastapi/fastapi | head -20"
} | {"status": "ok", "stdout": "", "stderr": "grep: fastapi/fastapi: No such file or directory\n", "exit_code": 0}full{"status": "ok", "stdout": "", "stderr": "grep: fastapi/fastapi: No such file or directory\n", "exit_code": 0} |
| 4 | run_command | {
"command": "find fastapi -maxdepth 2"
} | {"status": "ok", "stdout": "fastapi\nfastapi/middleware\nfastapi/middleware/gzip.py\nfastapi/middleware/cors.py\nfastapi/middleware/asyncexitstack.py\nfastapi/mfull{"status": "ok", "stdout": "fastapi\nfastapi/middleware\nfastapi/middleware/gzip.py\nfastapi/middleware/cors.py\nfastapi/middleware/asyncexitstack.py\nfastapi/middleware/__init__.py\nfastapi/middleware/httpsredirect.py\nfastapi/middleware/trustedhost.py\nfastapi/middleware/wsgi.py\nfastapi/params.py\nfastapi/responses.py\nfastapi/templating.py\nfastapi/security\nfastapi/security/open_id_connect_url.py\nfastapi/security/oauth2.py\nfastapi/security/__init__.py\nfastapi/security/api_key.py\nfastapi/security/utils.py\nfastapi/security/http.py\nfastapi/security/base.py\nfastapi/exception_handlers.py\nfastapi/websockets.py\nfastapi/applications.py\nfastapi/concurrency.py\nfastapi/background.py\nfastapi/dependencies\nfastapi/dependencies/models.py\nfastapi/dependencies/__init__.py\nfastapi/dependencies/utils.py\nfastapi/__init__.py\nfastapi/encoders.py\nfastapi/types.py\nfastapi/logger.py\nfastapi/openapi\nfastapi/openapi/models.py\nfastapi/openapi/constants.py\nfastapi/openapi/__init__.py\nfastapi/openapi/docs.py\nfastapi/openapi/utils.py\nfastapi/staticfiles.py\nfastapi/cli.py\nfastapi/utils.py\nfastapi/routing.py\nfastapi/testclient.py\nfastapi/temp_pydantic_v1_params.py\nfastapi/py.typed\nfastapi/exceptions.py\nfastapi/param_functions.py\nfastapi/_compat\nfastapi/_compat/v1.py\nfastapi/_compat/__init__.py\nfastapi/_compat/may_v1.py\nfastapi/_compat/shared.py\nfastapi/_compat/model_field.py\nfastapi/_compat/main.py\nfastapi/_compat/v2.py\nfastapi/requests.py\nfastapi/datastructures.py\nfastapi/__main__.py\n", "stderr": "", "exit_code": 0} |
| 5 | run_command | {
"command": "grep -rn \"arbitrary_types_allowed\" fastapi/"
} | {"status": "error", "error_type": "CommandError", "error_message": "", "details": {"stdout": "", "stderr": "", "exit_code": 1}}full{"status": "error", "error_type": "CommandError", "error_message": "", "details": {"stdout": "", "stderr": "", "exit_code": 1}} |
| 6 | run_command | {
"command": "ls -R fastapi/_compat/"
} | {"status": "ok", "stdout": "__init__.py\nmain.py\nmay_v1.py\nmodel_field.py\nshared.py\nv1.py\nv2.py\n", "stderr": "", "exit_code": 0}full{"status": "ok", "stdout": "__init__.py\nmain.py\nmay_v1.py\nmodel_field.py\nshared.py\nv1.py\nv2.py\n", "stderr": "", "exit_code": 0} |
| 7 | run_command | {
"command": "grep -rn \"arbitrary_types_allowed\" fastapi/encoders.py"
} | {"status": "error", "error_type": "CommandError", "error_message": "", "details": {"stdout": "", "stderr": "", "exit_code": 1}}full{"status": "error", "error_type": "CommandError", "error_message": "", "details": {"stdout": "", "stderr": "", "exit_code": 1}} |
| 8 | run_command | {
"command": "grep -rn \"arbitrary_types_allowed\" ."
} | {"status": "ok", "stdout": "./tests/test_inherited_custom_class.py:45: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_inherited_custom_class.pfull{"status": "ok", "stdout": "./tests/test_inherited_custom_class.py:45: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_inherited_custom_class.py:89: arbitrary_types_allowed = True\n./tests/test_jsonable_encoder.py:248: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_jsonable_encoder.py:252: arbitrary_types_allowed = True\n./tests/test_jsonable_encoder.py:264: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_jsonable_encoder.py:268: arbitrary_types_allowed = True\n./tests/test_jsonable_encoder.py:279: model_config = {\"arbitrary_types_allowed\": True}\n./tests/test_jsonable_encoder.py:283: arbitrary_types_allowed = True\n./tests/test_compat.py:87: model_config = ConfigDict(arbitrary_types_allowed=True)\n./tests/test_compat.py:92: arbitrary_types_allowed=True,\n", "stderr": "", "exit_code": 0} |
| 9 | run_command | {
"command": "grep -rn \"jsonable_encoder\" fastapi/"
} | {"status": "ok", "stdout": "fastapi/exception_handlers.py:1:from fastapi.encoders import jsonable_encoder\nfastapi/exception_handlers.py:25: content={\"detail\"full{"status": "ok", "stdout": "fastapi/exception_handlers.py:1:from fastapi.encoders import jsonable_encoder\nfastapi/exception_handlers.py:25: content={\"detail\": jsonable_encoder(exc.errors())},\nfastapi/exception_handlers.py:33: code=WS_1008_POLICY_VIOLATION, reason=jsonable_encoder(exc.errors())\nfastapi/encoders.py:114:def jsonable_encoder(\nfastapi/encoders.py:247: return jsonable_encoder(\nfastapi/encoders.py:258: return jsonable_encoder(\nfastapi/encoders.py:294: encoded_key = jsonable_encoder(\nfastapi/encoders.py:302: encoded_value = jsonable_encoder(\nfastapi/encoders.py:316: jsonable_encoder(\nfastapi/encoders.py:346: return jsonable_encoder(\nfastapi/openapi/docs.py:5:from fastapi.encoders import jsonable_encoder\nfastapi/openapi/docs.py:137: html += f\"{json.dumps(key)}: {json.dumps(jsonable_encoder(value))},\\n\"\nfastapi/openapi/docs.py:151: ui.initOAuth({json.dumps(jsonable_encoder(init_oauth))})\nfastapi/openapi/utils.py:23:from fastapi.encoders import jsonable_encoder\nfastapi/openapi/utils.py:85: security_definition = jsonable_encoder(\nfastapi/openapi/utils.py:168: parameter[\"examples\"] = jsonable_encoder(openapi_examples)\nfastapi/openapi/utils.py:170: parameter[\"example\"] = jsonable_encoder(example)\nfastapi/openapi/utils.py:203: request_media_content[\"examples\"] = jsonable_encoder(\nfastapi/openapi/utils.py:207: request_media_content[\"example\"] = jsonable_encoder(field_info.example)\nfastapi/openapi/utils.py:567: return jsonable_encoder(OpenAPI(**output), by_alias=True, exclude_none=True) # type: ignore\nfastapi/routing.py:47:from fastapi.encoders import jsonable_encoder\nfastapi/routing.py:295: return jsonable_encoder(\nfastapi/routing.py:305: return jsonable_encoder(response_content)\n", "stderr": "", "exit_code": 0} |
| 10 | run_command | {
"command": "sed -n '114,160p' fastapi/encoders.py"
} | {"status": "ok", "stdout": "def jsonable_encoder(\n obj: Annotated[\n Any,\n Doc(\n \"\"\"\n The input object to convert to JSON.\n \"\"\"\n ),\n ],\n include: full{"status": "ok", "stdout": "def jsonable_encoder(\n obj: Annotated[\n Any,\n Doc(\n \"\"\"\n The input object to convert to JSON.\n \"\"\"\n ),\n ],\n include: Annotated[\n Optional[IncEx],\n Doc(\n \"\"\"\n Pydantic's `include` parameter, passed to Pydantic models to set the\n fields to include.\n \"\"\"\n ),\n ] = None,\n exclude: Annotated[\n Optional[IncEx],\n Doc(\n \"\"\"\n Pydantic's `exclude` parameter, passed to Pydantic models to set the\n fields to exclude.\n \"\"\"\n ),\n ] = None,\n by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `by_alias` parameter, passed to Pydantic models to define if\n the output should use the alias names (when provided) or the Python\n attribute names. In an API, if you set an alias, it's probably because you\n want to use it in the result, so you probably want to leave this set to\n `True`.\n \"\"\"\n ),\n ] = True,\n exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `exclude_unset` parameter, passed to Pydantic models to define\n if it should exclude from the output the fields that were not explicitly\n set (and that only had their default values).\n \"\"\"\n", "stderr": "", "exit_code": 0} |
| 11 | run_command | {
"command": "cat fastapi/encoders.py"
} | {"status": "ok", "stdout": "import dataclasses\nimport datetime\nfrom collections import defaultdict, deque\nfrom decimal import Decimal\nfrom enum import Enum\full{"status": "ok", "stdout": "import dataclasses\nimport datetime\nfrom collections import defaultdict, deque\nfrom decimal import Decimal\nfrom enum import Enum\nfrom ipaddress import (\n IPv4Address,\n IPv4Interface,\n IPv4Network,\n IPv6Address,\n IPv6Interface,\n IPv6Network,\n)\nfrom pathlib import Path, PurePath\nfrom re import Pattern\nfrom types import GeneratorType\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union\nfrom uuid import UUID\n\nfrom annotated_doc import Doc\nfrom fastapi._compat import may_v1\nfrom fastapi.types import IncEx\nfrom pydantic import BaseModel\nfrom pydantic.color import Color\nfrom pydantic.networks import AnyUrl, NameEmail\nfrom pydantic.types import SecretBytes, SecretStr\nfrom typing_extensions import Annotated\n\nfrom ._compat import Url, _is_undefined, _model_dump\n\n\n# Taken from Pydantic v1 as is\ndef isoformat(o: Union[datetime.date, datetime.time]) -> str:\n return o.isoformat()\n\n\n# Adapted from Pydantic v1\n# TODO: pv2 should this return strings instead?\ndef decimal_encoder(dec_value: Decimal) -> Union[int, float]:\n \"\"\"\n Encodes a Decimal as int if there's no exponent, otherwise float\n\n This is useful when we use ConstrainedDecimal to represent Numeric(x,0)\n where an integer (but not int typed) is used. Encoding this as a float\n results in failed round-tripping between encode and parse.\n Our Id type is a prime example of this.\n\n >>> decimal_encoder(Decimal(\"1.0\"))\n 1.0\n\n >>> decimal_encoder(Decimal(\"1\"))\n 1\n\n >>> decimal_encoder(Decimal(\"NaN\"))\n nan\n \"\"\"\n exponent = dec_value.as_tuple().exponent\n if isinstance(exponent, int) and exponent >= 0:\n return int(dec_value)\n else:\n return float(dec_value)\n\n\nENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {\n bytes: lambda o: o.decode(),\n Color: str,\n may_v1.Color: str,\n datetime.date: isoformat,\n datetime |
| 12 | run_command | {
"command": "sed -n '114,346p' fastapi/encoders.py"
} | {"status": "ok", "stdout": "def jsonable_encoder(\n obj: Annotated[\n Any,\n Doc(\n \"\"\"\n The input object to convert to JSON.\n \"\"\"\n ),\n ],\n include: full{"status": "ok", "stdout": "def jsonable_encoder(\n obj: Annotated[\n Any,\n Doc(\n \"\"\"\n The input object to convert to JSON.\n \"\"\"\n ),\n ],\n include: Annotated[\n Optional[IncEx],\n Doc(\n \"\"\"\n Pydantic's `include` parameter, passed to Pydantic models to set the\n fields to include.\n \"\"\"\n ),\n ] = None,\n exclude: Annotated[\n Optional[IncEx],\n Doc(\n \"\"\"\n Pydantic's `exclude` parameter, passed to Pydantic models to set the\n fields to exclude.\n \"\"\"\n ),\n ] = None,\n by_alias: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `by_alias` parameter, passed to Pydantic models to define if\n the output should use the alias names (when provided) or the Python\n attribute names. In an API, if you set an alias, it's probably because you\n want to use it in the result, so you probably want to leave this set to\n `True`.\n \"\"\"\n ),\n ] = True,\n exclude_unset: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `exclude_unset` parameter, passed to Pydantic models to define\n if it should exclude from the output the fields that were not explicitly\n set (and that only had their default values).\n \"\"\"\n ),\n ] = False,\n exclude_defaults: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `exclude_defaults` parameter, passed to Pydantic models to define\n if it should exclude from the output the fields that had the same default\n value, even when they were explicitly set.\n \"\"\"\n ),\n ] = False,\n exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n P |
| 13 | run_command | {
"command": "sed -n '346,450p' fastapi/encoders.py"
} | {"status": "ok", "stdout": " return jsonable_encoder(\n data,\n include=include,\n exclude=exclude,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n excludfull{"status": "ok", "stdout": " return jsonable_encoder(\n data,\n include=include,\n exclude=exclude,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_defaults=exclude_defaults,\n exclude_none=exclude_none,\n custom_encoder=custom_encoder,\n sqlalchemy_safe=sqlalchemy_safe,\n )\n", "stderr": "", "exit_code": 0} |
| 14 | run_command | {
"command": "sed -n '170,345p' fastapi/encoders.py"
} | {"status": "ok", "stdout": " \"\"\"\n ),\n ] = False,\n exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `exclude_none` parameter, passed to Pydantfull{"status": "ok", "stdout": " \"\"\"\n ),\n ] = False,\n exclude_none: Annotated[\n bool,\n Doc(\n \"\"\"\n Pydantic's `exclude_none` parameter, passed to Pydantic models to define\n if it should exclude from the output any fields that have a `None` value.\n \"\"\"\n ),\n ] = False,\n custom_encoder: Annotated[\n Optional[Dict[Any, Callable[[Any], Any]]],\n Doc(\n \"\"\"\n Pydantic's `custom_encoder` parameter, passed to Pydantic models to define\n a custom encoder.\n \"\"\"\n ),\n ] = None,\n sqlalchemy_safe: Annotated[\n bool,\n Doc(\n \"\"\"\n Exclude from the output any fields that start with the name `_sa`.\n\n This is mainly a hack for compatibility with SQLAlchemy objects, they\n store internal SQLAlchemy-specific state in attributes named with `_sa`,\n and those objects can't (and shouldn't be) serialized to JSON.\n \"\"\"\n ),\n ] = True,\n) -> Any:\n \"\"\"\n Convert any object to something that can be encoded in JSON.\n\n This is used internally by FastAPI to make sure anything you return can be\n encoded as JSON before it is sent to the client.\n\n You can also use it yourself, for example to convert objects before saving them\n in a database that supports only JSON.\n\n Read more about it in the\n [FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/).\n \"\"\"\n custom_encoder = custom_encoder or {}\n if custom_encoder:\n if type(obj) in custom_encoder:\n return custom_encoder[type(obj)](obj)\n else:\n for encoder_type, encoder_instance in custom_encoder.items():\n if isinstance(obj, encoder_type):\n return encoder_instance(obj)\n if include is not None and not i |
| 15 | run_command | {
"command": "sed -n '250,346p' fastapi/encoders.py"
} | {"status": "ok", "stdout": " exclude_defaults=exclude_defaults,\n # TODO: remove when deprecating Pydantic v1\n custom_encoder=encoders,\n sqlalchemy_safe=sqlalfull{"status": "ok", "stdout": " exclude_defaults=exclude_defaults,\n # TODO: remove when deprecating Pydantic v1\n custom_encoder=encoders,\n sqlalchemy_safe=sqlalchemy_safe,\n )\n if dataclasses.is_dataclass(obj):\n assert not isinstance(obj, type)\n obj_dict = dataclasses.asdict(obj)\n return jsonable_encoder(\n obj_dict,\n include=include,\n exclude=exclude,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_defaults=exclude_defaults,\n exclude_none=exclude_none,\n custom_encoder=custom_encoder,\n sqlalchemy_safe=sqlalchemy_safe,\n )\n if isinstance(obj, Enum):\n return obj.value\n if isinstance(obj, PurePath):\n return str(obj)\n if isinstance(obj, (str, int, float, type(None))):\n return obj\n if _is_undefined(obj):\n return None\n if isinstance(obj, dict):\n encoded_dict = {}\n allowed_keys = set(obj.keys())\n if include is not None:\n allowed_keys &= set(include)\n if exclude is not None:\n allowed_keys -= set(exclude)\n for key, value in obj.items():\n if (\n (\n not sqlalchemy_safe\n or (not isinstance(key, str))\n or (not key.startswith(\"_sa\"))\n )\n and (value is not None or not exclude_none)\n and key in allowed_keys\n ):\n encoded_key = jsonable_encoder(\n key,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n custom_encoder=custom_encoder,\n sqlalchemy_safe=sqlalchemy_safe,\n )\n encoded_value = jsonable_encoder(\n value,\n |
| 16 | run_command | {
"command": "grep -C 5 \"arbitrary_types_allowed\" tests/test_jsonable_encoder.py"
} | {"status": "ok", "stdout": "def test_encode_model_with_pure_path():\n class ModelWithPath(BaseModel):\n path: PurePath\n\n if PYDANTIC_V2:\n model_config = {\"afull{"status": "ok", "stdout": "def test_encode_model_with_pure_path():\n class ModelWithPath(BaseModel):\n path: PurePath\n\n if PYDANTIC_V2:\n model_config = {\"arbitrary_types_allowed\": True}\n else:\n\n class Config:\n arbitrary_types_allowed = True\n\n test_path = PurePath(\"/foo\", \"bar\")\n obj = ModelWithPath(path=test_path)\n assert jsonable_encoder(obj) == {\"path\": str(test_path)}\n\n--\ndef test_encode_model_with_pure_posix_path():\n class ModelWithPath(BaseModel):\n path: PurePosixPath\n\n if PYDANTIC_V2:\n model_config = {\"arbitrary_types_allowed\": True}\n else:\n\n class Config:\n arbitrary_types_allowed = True\n\n obj = ModelWithPath(path=PurePosixPath(\"/foo\", \"bar\"))\n assert jsonable_encoder(obj) == {\"path\": \"/foo/bar\"}\n\n\ndef test_encode_model_with_pure_windows_path():\n class ModelWithPath(BaseModel):\n path: PureWindowsPath\n\n if PYDANTIC_V2:\n model_config = {\"arbitrary_types_allowed\": True}\n else:\n\n class Config:\n arbitrary_types_allowed = True\n\n obj = ModelWithPath(path=PureWindowsPath(\"/foo\", \"bar\"))\n assert jsonable_encoder(obj) == {\"path\": \"\\\\foo\\\\bar\"}\n\n\n", "stderr": "", "exit_code": 0} |
| 17 | run_command | {
"command": "grep -n \"arbitrary_types_allowed\" tests/test_jsonable_encoder.py | head -20"
} | {"status": "ok", "stdout": "248: model_config = {\"arbitrary_types_allowed\": True}\n252: arbitrary_types_allowed = True\n264: model_config = {\"arbitrary_typesfull{"status": "ok", "stdout": "248: model_config = {\"arbitrary_types_allowed\": True}\n252: arbitrary_types_allowed = True\n264: model_config = {\"arbitrary_types_allowed\": True}\n268: arbitrary_types_allowed = True\n279: model_config = {\"arbitrary_types_allowed\": True}\n283: arbitrary_types_allowed = True\n", "stderr": "", "exit_code": 0} |
| 18 | run_command | {
"command": "sed -n '240,300p' tests/test_jsonable_encoder.py"
} | {"status": "ok", "stdout": " assert encoded_instance == custom_enum_encoder(instance)\n\n\ndef test_encode_model_with_pure_path():\n class ModelWithPath(BaseModfull{"status": "ok", "stdout": " assert encoded_instance == custom_enum_encoder(instance)\n\n\ndef test_encode_model_with_pure_path():\n class ModelWithPath(BaseModel):\n path: PurePath\n\n if PYDANTIC_V2:\n model_config = {\"arbitrary_types_allowed\": True}\n else:\n\n class Config:\n arbitrary_types_allowed = True\n\n test_path = PurePath(\"/foo\", \"bar\")\n obj = ModelWithPath(path=test_path)\n assert jsonable_encoder(obj) == {\"path\": str(test_path)}\n\n\ndef test_encode_model_with_pure_posix_path():\n class ModelWithPath(BaseModel):\n path: PurePosixPath\n\n if PYDANTIC_V2:\n model_config = {\"arbitrary_types_allowed\": True}\n else:\n\n class Config:\n arbitrary_types_allowed = True\n\n obj = ModelWithPath(path=PurePosixPath(\"/foo\", \"bar\"))\n assert jsonable_encoder(obj) == {\"path\": \"/foo/bar\"}\n\n\ndef test_encode_model_with_pure_windows_path():\n class ModelWithPath(BaseModel):\n path: PureWindowsPath\n\n if PYDANTIC_V2:\n model_config = {\"arbitrary_types_allowed\": True}\n else:\n\n class Config:\n arbitrary_types_allowed = True\n\n obj = ModelWithPath(path=PureWindowsPath(\"/foo\", \"bar\"))\n assert jsonable_encoder(obj) == {\"path\": \"\\\\foo\\\\bar\"}\n\n\n@needs_pydanticv1\ndef test_encode_root():\n class ModelWithRoot(BaseModel):\n __root__: str\n\n model = ModelWithRoot(__root__=\"Foo\")\n assert jsonable_encoder(model) == \"Foo\"\n\n\n@needs_pydanticv2\ndef test_decimal_encoder_float():\n data = {\"value\": Decimal(1.23)}\n", "stderr": "", "exit_code": 0} |
| 19 | run_command | {
"command": "grep -rn \"arbitrary_types_allowed\" tests/test_inherited_custom_class.py"
} | {"status": "ok", "stdout": "tests/test_inherited_custom_class.py:45: model_config = {\"arbitrary_types_allowed\": True}\ntests/test_inherited_custom_class.py:89full{"status": "ok", "stdout": "tests/test_inherited_custom_class.py:45: model_config = {\"arbitrary_types_allowed\": True}\ntests/test_inherited_custom_class.py:89: arbitrary_types_allowed = True\n", "stderr": "", "exit_code": 0} |
| 20 | run_command | {
"command": "sed -n '35,55p' tests/test_inherited_custom_class.py"
} | {"status": "ok", "stdout": " @app.get(\"/fast_uuid\")\n def return_fast_uuid():\n asyncpg_uuid = MyUuid(\"a10ff360-3b1e-4984-a26f-d3ab460bdb51\")\n assert isinsfull{"status": "ok", "stdout": " @app.get(\"/fast_uuid\")\n def return_fast_uuid():\n asyncpg_uuid = MyUuid(\"a10ff360-3b1e-4984-a26f-d3ab460bdb51\")\n assert isinstance(asyncpg_uuid, uuid.UUID)\n assert type(asyncpg_uuid) is not uuid.UUID\n with pytest.raises(TypeError):\n vars(asyncpg_uuid)\n return {\"fast_uuid\": asyncpg_uuid}\n\n class SomeCustomClass(BaseModel):\n model_config = {\"arbitrary_types_allowed\": True}\n\n a_uuid: MyUuid\n\n @field_serializer(\"a_uuid\")\n def serialize_a_uuid(self, v):\n return str(v)\n\n @app.get(\"/get_custom_class\")\n def return_some_user():\n # Test that the fix also works for custom pydantic classes\n", "stderr": "", "exit_code": 0} |
| 21 | run_command | {
"command": "sed -n '80,100p' tests/test_inherited_custom_class.py"
} | {"status": "ok", "stdout": " asyncpg_uuid = MyUuid(\"a10ff360-3b1e-4984-a26f-d3ab460bdb51\")\n assert isinstance(asyncpg_uuid, uuid.UUID)\n assert type(asyncpg_full{"status": "ok", "stdout": " asyncpg_uuid = MyUuid(\"a10ff360-3b1e-4984-a26f-d3ab460bdb51\")\n assert isinstance(asyncpg_uuid, uuid.UUID)\n assert type(asyncpg_uuid) is not uuid.UUID\n with pytest.raises(TypeError):\n vars(asyncpg_uuid)\n return {\"fast_uuid\": asyncpg_uuid}\n\n class SomeCustomClass(BaseModel):\n class Config:\n arbitrary_types_allowed = True\n json_encoders = {uuid.UUID: str}\n\n a_uuid: MyUuid\n\n @app.get(\"/get_custom_class\")\n def return_some_user():\n # Test that the fix also works for custom pydantic classes\n return SomeCustomClass(a_uuid=MyUuid(\"b8799909-f914-42de-91bc-95c819218d01\"))\n\n client = TestClient(app)\n\n", "stderr": "", "exit_code": 0} |
| 22 | run_command | {
"command": "cat tests/test_inherited_custom_class.py"
} | {"status": "ok", "stdout": "import uuid\n\nimport pytest\nfrom fastapi import FastAPI\nfrom fastapi.testclient import TestClient\nfrom pydantic import BaseModelfull{"status": "ok", "stdout": "import uuid\n\nimport pytest\nfrom fastapi import FastAPI\nfrom fastapi.testclient import TestClient\nfrom pydantic import BaseModel\n\nfrom .utils import needs_pydanticv1, needs_pydanticv2\n\n\nclass MyUuid:\n def __init__(self, uuid_string: str):\n self.uuid = uuid_string\n\n def __str__(self):\n return self.uuid\n\n @property # type: ignore\n def __class__(self):\n return uuid.UUID\n\n @property\n def __dict__(self):\n \"\"\"Spoof a missing __dict__ by raising TypeError, this is how\n asyncpg.pgroto.pgproto.UUID behaves\"\"\"\n raise TypeError(\"vars() argument must have __dict__ attribute\")\n\n\n@needs_pydanticv2\ndef test_pydanticv2():\n from pydantic import field_serializer\n\n app = FastAPI()\n\n @app.get(\"/fast_uuid\")\n def return_fast_uuid():\n asyncpg_uuid = MyUuid(\"a10ff360-3b1e-4984-a26f-d3ab460bdb51\")\n assert isinstance(asyncpg_uuid, uuid.UUID)\n assert type(asyncpg_uuid) is not uuid.UUID\n with pytest.raises(TypeError):\n vars(asyncpg_uuid)\n return {\"fast_uuid\": asyncpg_uuid}\n\n class SomeCustomClass(BaseModel):\n model_config = {\"arbitrary_types_allowed\": True}\n\n a_uuid: MyUuid\n\n @field_serializer(\"a_uuid\")\n def serialize_a_uuid(self, v):\n return str(v)\n\n @app.get(\"/get_custom_class\")\n def return_some_user():\n # Test that the fix also works for custom pydantic classes\n return SomeCustomClass(a_uuid=MyUuid(\"b8799909-f914-42de-91bc-95c819218d01\"))\n\n client = TestClient(app)\n\n with client:\n response_simple = client.get(\"/fast_uuid\")\n response_pydantic = client.get(\"/get_custom_class\")\n\n assert response_simple.json() == {\n \"fast_uuid\": \"a10ff360-3b1e-4984-a26f-d3ab460bdb51\"\n }\n\n assert response_pydantic.json() == {\n \"a_uuid\": \"b8799909-f914-42de-91bc-95c81 |
| 23 | run_command | {
"command": "python3 -m pytest tests/test_inherited_custom_class.py tests/test_jsonable_encoder.py -k \"inherited_custom_class or jsonable_encoder\""
} | {"status": "ok", "stdout": "============================= test session starts ==============================\nplatform darwin -- Python 3.13.15, pytest-9.1.1, pfull{"status": "ok", "stdout": "============================= test session starts ==============================\nplatform darwin -- Python 3.13.15, pytest-9.1.1, pluggy-1.6.0\ncodspeed: 5.0.3 (disabled, mode: walltime, callgraph: not supported, timer_resolution: 41.7ns)\nrootdir: /private/workspace\nconfigfile: pytest.ini (WARNING: ignoring pytest config in pyproject.toml!)\nplugins: cov-7.1.0, xdist-3.8.0, timeout-2.4.0, codspeed-5.0.3, sugar-1.1.1, anyio-4.15.1, inline-snapshot-0.35.4\ncollected 25 items\n\ntests/test_inherited_custom_class.py .s [ 8%]\ntests/test_jsonable_encoder.py ......s....s....s...... [100%]\n\n=============================== warnings summary ===============================\n../../../../../../../Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/overlays/starlette-0.50.0-py3-none-any/starlette/testclient.py:45\n /Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/overlays/starlette-0.50.0-py3-none-any/starlette/testclient.py:45: DeprecationWarning: The anyio.abc.BlockingPortal alias is deprecated, use anyio.from_thread.BlockingPortal instead.\n _PortalFactoryType = Callable[[], AbstractContextManager[anyio.abc.BlockingPortal]]\n\n-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html\n=================== 21 passed, 4 skipped, 1 warning in 0.60s ===================\n", "stderr": "", "exit_code": 0} |
| 24 | run_command | {
"command": "cat -n fastapi/encoders.py | grep -A 10 \"try:\" | tail -n 20"
} | {"status": "ok", "stdout": " 336\t try:\n 337\t data = dict(obj)\n 338\t except Exception as e:\n 339\t errors: List[Exception] = []\n 340\t errors.append(e)\n full{"status": "ok", "stdout": " 336\t try:\n 337\t data = dict(obj)\n 338\t except Exception as e:\n 339\t errors: List[Exception] = []\n 340\t errors.append(e)\n 341\t try:\n 342\t data = vars(obj)\n 343\t except Exception as e:\n 344\t errors.append(e)\n 345\t raise ValueError(errors) from e\n 346\t return jsonable_encoder(\n 347\t data,\n 348\t include=include,\n 349\t exclude=exclude,\n 350\t by_alias=by_alias,\n 351\t exclude_unset=exclude_unset,\n", "stderr": "", "exit_code": 0} |
| 25 | run_command | {
"command": "python3 - <<'PY'\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\n\nclass CustomType:\n def __init__(self, val):\n self.val = val\n def __repr__(self):\n return f\"CustomType({self.val})\"\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: CustomType\n\nobj = Model(x=CustomType(\"hello\"))\nprint(f\"Obj: {obj}\")\ntry:\n encoded = jsonable_encoder(obj)\n print(f\"Encoded: {encoded}\")\nexcept Exception as e:\n print(f\"Error: {e}\")\nPY\n"
} | {"status": "ok", "stdout": "Obj: x=CustomType(hello)\nError: Unable to serialize unknown type: <class '__main__.CustomType'>\n", "stderr": "", "exit_code": 0}full{"status": "ok", "stdout": "Obj: x=CustomType(hello)\nError: Unable to serialize unknown type: <class '__main__.CustomType'>\n", "stderr": "", "exit_code": 0} |
| 26 | run_command | {
"command": "python3 - <<'PY'\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\n\nclass CustomType:\n def __init__(self, val):\n self.val = val\n def __repr__(self):\n return f\"CustomType({self.val})\"\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: CustomType\n\nobj = Model(x=CustomType(\"hello\"))\nprint(f\"Obj: {obj}\")\ntry:\n # Try encoding just the custom type\n encoded = jsonable_encoder(CustomType(\"hello\"))\n print(f\"Encoded: {encoded}\")\nexcept Exception as e:\n print(f\"Error: {e}\")\nPY\n"
} | {"status": "ok", "stdout": "Obj: x=CustomType(hello)\nEncoded: {'val': 'hello'}\n", "stderr": "", "exit_code": 0}full{"status": "ok", "stdout": "Obj: x=CustomType(hello)\nEncoded: {'val': 'hello'}\n", "stderr": "", "exit_code": 0} |
| 27 | run_command | {
"command": "python3 - <<'PY'\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\n\nclass CustomType:\n def __init__(self, val):\n self.val = val\n def __repr__(self):\n return f\"CustomType({self.val})\"\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: CustomType\n\nobj = Model(x=CustomType(\"hello\"))\nprint(f\"Obj: {obj}\")\ntry:\n # Pydantic v2's model_dump(mode=\"json\") should handle arbitrary types if configured?\n # Let's see what _model_dump does\n from fastapi._compat import _model_dump\n dumped = _model_dump(obj, mode=\"json\")\n print(f\"Dumped: {dumped}\")\nexcept Exception as e:\n print(f\"Error: {e}\")\nPY\n"
} | {"status": "ok", "stdout": "Obj: x=CustomType(hello)\nError: Unable to serialize unknown type: <class '__main__.CustomType'>\n", "stderr": "", "exit_code": 0}full{"status": "ok", "stdout": "Obj: x=CustomType(hello)\nError: Unable to serialize unknown type: <class '__main__.CustomType'>\n", "stderr": "", "exit_code": 0} |
| 28 | run_command | {
"command": "python3 - <<'PY'\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\n\nclass CustomType:\n def __init__(self, val):\n self.val = val\n def __repr__(self):\n return f\"CustomType({self.val})\"\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: CustomType\n\nobj = Model(x=CustomType(\"hello\"))\nprint(f\"Obj: {obj}\")\ntry:\n # Pydantic v2's model_dump(mode=\"python\") should keep the object\n from fastapi._compat import _model_dump\n dumped = _model_dump(obj, mode=\"python\")\n print(f\"Dumped: {dumped}\")\n # Then jsonable_encoder should handle it\n encoded = jsonable_encoder(dumped)\n print(f\"Encoded: {encoded}\")\nexcept Exception as e:\n print(f\"Error: {e}\")\nPY\n"
} | {"status": "ok", "stdout": "Obj: x=CustomType(hello)\nDumped: {'x': CustomType(hello)}\nEncoded: {'x': {'val': 'hello'}}\n", "stderr": "", "exit_code": 0}full{"status": "ok", "stdout": "Obj: x=CustomType(hello)\nDumped: {'x': CustomType(hello)}\nEncoded: {'x': {'val': 'hello'}}\n", "stderr": "", "exit_code": 0} |
| 29 | run_command | {
"command": "sed -n '180,220p' fastapi/encoders.py"
} | {"status": "ok", "stdout": " ),\n ] = False,\n custom_encoder: Annotated[\n Optional[Dict[Any, Callable[[Any], Any]]],\n Doc(\n \"\"\"\n Pydantic's `custom_encofull{"status": "ok", "stdout": " ),\n ] = False,\n custom_encoder: Annotated[\n Optional[Dict[Any, Callable[[Any], Any]]],\n Doc(\n \"\"\"\n Pydantic's `custom_encoder` parameter, passed to Pydantic models to define\n a custom encoder.\n \"\"\"\n ),\n ] = None,\n sqlalchemy_safe: Annotated[\n bool,\n Doc(\n \"\"\"\n Exclude from the output any fields that start with the name `_sa`.\n\n This is mainly a hack for compatibility with SQLAlchemy objects, they\n store internal SQLAlchemy-specific state in attributes named with `_sa`,\n and those objects can't (and shouldn't be) serialized to JSON.\n \"\"\"\n ),\n ] = True,\n) -> Any:\n \"\"\"\n Convert any object to something that can be encoded in JSON.\n\n This is used internally by FastAPI to make sure anything you return can be\n encoded as JSON before it is sent to the client.\n\n You can also use it yourself, for example to convert objects before saving them\n in a database that supports only JSON.\n\n Read more about it in the\n [FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/).\n \"\"\"\n custom_encoder = custom_encoder or {}\n if custom_encoder:\n if type(obj) in custom_encoder:\n return custom_encoder[type(obj)](obj)\n else:\n", "stderr": "", "exit_code": 0} |
| 30 | run_command | {
"command": "sed -n '200,250p' fastapi/encoders.py"
} | {"status": "ok", "stdout": " \"\"\"\n ),\n ] = True,\n) -> Any:\n \"\"\"\n Convert any object to something that can be encoded in JSON.\n\n This is used internafull{"status": "ok", "stdout": " \"\"\"\n ),\n ] = True,\n) -> Any:\n \"\"\"\n Convert any object to something that can be encoded in JSON.\n\n This is used internally by FastAPI to make sure anything you return can be\n encoded as JSON before it is sent to the client.\n\n You can also use it yourself, for example to convert objects before saving them\n in a database that supports only JSON.\n\n Read more about it in the\n [FastAPI docs for JSON Compatible Encoder](https://fastapi.tiangolo.com/tutorial/encoder/).\n \"\"\"\n custom_encoder = custom_encoder or {}\n if custom_encoder:\n if type(obj) in custom_encoder:\n return custom_encoder[type(obj)](obj)\n else:\n for encoder_type, encoder_instance in custom_encoder.items():\n if isinstance(obj, encoder_type):\n return encoder_instance(obj)\n if include is not None and not isinstance(include, (set, dict)):\n include = set(include)\n if exclude is not None and not isinstance(exclude, (set, dict)):\n exclude = set(exclude)\n if isinstance(obj, (BaseModel, may_v1.BaseModel)):\n # TODO: remove when deprecating Pydantic v1\n encoders: Dict[Any, Any] = {}\n if isinstance(obj, may_v1.BaseModel):\n encoders = getattr(obj.__config__, \"json_encoders\", {}) # type: ignore[attr-defined]\n if custom_encoder:\n encoders = {**encoders, **custom_encoder}\n obj_dict = _model_dump(\n obj,\n mode=\"json\",\n include=include,\n exclude=exclude,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n )\n if \"__root__\" in obj_dict:\n obj_dict = obj_dict[\"__root__\"]\n return jsonable_encoder(\n obj_dict,\n exclude_none=exclude |
| 31 | run_command | {
"command": "python3 - <<'PY'\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\nimport uuid\n\nclass MyUuid:\n def __init__(self, val):\n self.val = val\n def __str__(self):\n return self.val\n @property\n def __class__(self):\n return uuid.UUID\n def __repr__(self):\n return f\"MyUuid({self.val})\"\n def __dict__(self):\n raise TypeError(\"vars() argument must have __dict__ attribute\")\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: MyUuid\n\nobj = Model(x=MyUuid(\"123\"))\nprint(f\"Obj: {obj}\")\ntry:\n encoded = jsonable_encoder(obj)\n print(f\"Encoded: {encoded}\")\nexcept Exception as e:\n print(f\"Error: {e}\")\nPY\n"
} | {"status": "ok", "stdout": "Obj: x=MyUuid(123)\nError: 'MyUuid' object has no attribute 'int'\n", "stderr": "", "exit_code": 0}full{"status": "ok", "stdout": "Obj: x=MyUuid(123)\nError: 'MyUuid' object has no attribute 'int'\n", "stderr": "", "exit_code": 0} |
| 32 | run_command | {
"command": "python3 - <<'PY'\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\nimport uuid\n\nclass MyUuid:\n def __init__(self, val):\n self.val = val\n def __str__(self):\n return self.val\n @property\n def __class__(self):\n return uuid.UUID\n def __repr__(self):\n return f\"MyUuid({self.val})\"\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: MyUuid\n\nobj = Model(x=MyUuid(\"123\"))\ntry:\n encoded = jsonable_encoder(obj)\n print(f\"Encoded: {encoded}\")\nexcept Exception as e:\n print(f\"Error: {e}\")\nPY\n"
} | {"status": "ok", "stdout": "Error: 'MyUuid' object has no attribute 'int'\n", "stderr": "", "exit_code": 0}full{"status": "ok", "stdout": "Error: 'MyUuid' object has no attribute 'int'\n", "stderr": "", "exit_code": 0} |
| 33 | run_command | {
"command": "python3 - <<'PY'\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\nimport uuid\n\nclass MyUuid:\n def __init__(self, val):\n self.val = val\n def __str__(self):\n return self.val\n @property\n def __class__(self):\n return uuid.UUID\n def __repr__(self):\n return f\"MyUuid({self.val})\"\n\nobj = MyUuid(\"123\")\ntry:\n encoded = jsonable_encoder(obj)\n print(f\"Encoded: {encoded}\")\nexcept Exception as e:\n print(f\"Error: {e}\")\nPY\n"
} | {"status": "ok", "stdout": "Encoded: 123\n", "stderr": "", "exit_code": 0}full{"status": "ok", "stdout": "Encoded: 123\n", "stderr": "", "exit_code": 0} |
| 34 | run_command | {
"command": "python3 - <<'PY'\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\nimport uuid\n\nclass MyUuid:\n def __init__(self, val):\n self.val = val\n def __str__(self):\n return self.val\n @property\n def __class__(self):\n return uuid.UUID\n def __repr__(self):\n return f\"MyUuid({self.val})\"\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: MyUuid\n\nobj = Model(x=MyUuid(\"123\"))\ntry:\n # Use mode=\"python\" and then jsonable_encoder\n from fastapi._compat import _model_dump\n dumped = _model_dump(obj, mode=\"python\")\n encoded = jsonable_encoder(dumped)\n print(f\"Encoded: {encoded}\")\nexcept Exception as e:\n print(f\"Error: {e}\")\nPY\n"
} | {"status": "ok", "stdout": "Encoded: {'x': '123'}\n", "stderr": "", "exit_code": 0}full{"status": "ok", "stdout": "Encoded: {'x': '123'}\n", "stderr": "", "exit_code": 0} |
| 35 | run_command | {
"command": "sed -n '220,240p' fastapi/encoders.py"
} | {"status": "ok", "stdout": " else:\n for encoder_type, encoder_instance in custom_encoder.items():\n if isinstance(obj, encoder_type):\n return encoder_instancefull{"status": "ok", "stdout": " else:\n for encoder_type, encoder_instance in custom_encoder.items():\n if isinstance(obj, encoder_type):\n return encoder_instance(obj)\n if include is not None and not isinstance(include, (set, dict)):\n include = set(include)\n if exclude is not None and not isinstance(exclude, (set, dict)):\n exclude = set(exclude)\n if isinstance(obj, (BaseModel, may_v1.BaseModel)):\n # TODO: remove when deprecating Pydantic v1\n encoders: Dict[Any, Any] = {}\n if isinstance(obj, may_v1.BaseModel):\n encoders = getattr(obj.__config__, \"json_encoders\", {}) # type: ignore[attr-defined]\n if custom_encoder:\n encoders = {**encoders, **custom_encoder}\n obj_dict = _model_dump(\n obj,\n mode=\"json\",\n include=include,\n exclude=exclude,\n by_alias=by_alias,\n", "stderr": "", "exit_code": 0} |
| 36 | run_command | {
"command": "python3 - <<'PY'\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\nimport uuid\n\nclass MyUuid:\n def __init__(self, val):\n self.val = val\n def __str__(self):\n return self.val\n @property\n def __class__(self):\n return uuid.UUID\n def __repr__(self):\n return f\"MyUuid({self.val})\"\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: MyUuid\n\nobj = Model(x=MyUuid(\"123\"))\nfrom fastapi._compat import _model_dump\n# In Pydantic v2, model_dump(mode=\"json\") tries to serialize everything using Pydantic's JSON serializer.\n# If arbitrary_types_allowed=True, it might still fail if it doesn't know how to serialize the arbitrary type.\ntry:\n dumped = _model_dump(obj, mode=\"json\")\n print(f\"Dumped json: {dumped}\")\nexcept Exception as e:\n print(f\"Dumped json error: {e}\")\n\ntry:\n dumped = _model_dump(obj, mode=\"python\")\n print(f\"Dumped python: {dumped}\")\nexcept Exception as e:\n print(f\"Dumped python error: {e}\")\nPY\n"
} | {"status": "ok", "stdout": "Dumped json error: 'MyUuid' object has no attribute 'int'\nDumped python: {'x': MyUuid(123)}\n", "stderr": "", "exit_code": 0}full{"status": "ok", "stdout": "Dumped json error: 'MyUuid' object has no attribute 'int'\nDumped python: {'x': MyUuid(123)}\n", "stderr": "", "exit_code": 0} |
| 37 | run_command | {
"command": "cd /workspace && python3 - <<'PY'\nfrom pathlib import Path\np = Path(\"fastapi/encoders.py\"); s = p.read_text()\nold = \"\"\" obj_dict = _model_dump(\n obj,\n mode=\"json\",\n include=include,\n exclude=exclude,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n )\"\"\"\nnew = \"\"\" obj_dict = _model_dump(\n obj,\n mode=\"python\",\n include=include,\n exclude=exclude,\n by_alias=by_alias,\n exclude_unset=exclude_unset,\n exclude_none=exclude_none,\n exclude_defaults=exclude_defaults,\n )\"\"\"\nassert s.count(old) == 1, (\"old text found this many times:\", s.count(old))\nt = s.replace(old, new); compile(t, str(p), \"exec\"); p.write_text(t)\nPY\n"
} | {"status": "ok", "stdout": "", "stderr": "", "exit_code": 0}full{"status": "ok", "stdout": "", "stderr": "", "exit_code": 0} |
| 38 | run_command | {
"command": "python3 -m pytest tests/test_inherited_custom_class.py tests/test_jsonable_encoder.py -k \"inherited_custom_class or jsonable_encoder\""
} | {"status": "ok", "stdout": "============================= test session starts ==============================\nplatform darwin -- Python 3.13.15, pytest-9.1.1, pfull{"status": "ok", "stdout": "============================= test session starts ==============================\nplatform darwin -- Python 3.13.15, pytest-9.1.1, pluggy-1.6.0\ncodspeed: 5.0.3 (disabled, mode: walltime, callgraph: not supported, timer_resolution: 41.7ns)\nrootdir: /private/workspace\nconfigfile: pytest.ini (WARNING: ignoring pytest config in pyproject.toml!)\nplugins: cov-7.1.0, xdist-3.8.0, timeout-2.4.0, codspeed-5.0.3, sugar-1.1.1, anyio-4.15.1, inline-snapshot-0.35.4\ncollected 25 items\n\ntests/test_inherited_custom_class.py .s [ 8%]\ntests/test_jsonable_encoder.py ......s....s....s...... [100%]\n\n=============================== warnings summary ===============================\n../../../../../../../Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/overlays/starlette-0.50.0-py3-none-any/starlette/testclient.py:45\n /Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/overlays/starlette-0.50.0-py3-none-any/starlette/testclient.py:45: DeprecationWarning: The anyio.abc.BlockingPortal alias is deprecated, use anyio.from_thread.BlockingPortal instead.\n _PortalFactoryType = Callable[[], AbstractContextManager[anyio.abc.BlockingPortal]]\n\n-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html\n=================== 21 passed, 4 skipped, 1 warning in 0.49s ===================\n", "stderr": "", "exit_code": 0} |
| 39 | run_command | {
"command": "python3 - <<'PY'\nfrom fastapi.encoders import jsonable_encoder\nfrom pydantic import BaseModel, ConfigDict\n\nclass CustomType:\n def __init__(self, val):\n self.val = val\n def __repr__(self):\n return f\"CustomType({self.val})\"\n\nclass Model(BaseModel):\n model_config = ConfigDict(arbitrary_types_allowed=True)\n x: CustomType\n\nobj = Model(x=CustomType(\"hello\"))\nprint(f\"Obj: {obj}\")\ntry:\n encoded = jsonable_encoder(obj)\n print(f\"Encoded: {encoded}\")\nexcept Exception as e:\n print(f\"Error: {e}\")\nPY\n"
} | {"status": "ok", "stdout": "Obj: x=CustomType(hello)\nEncoded: {'x': {'val': 'hello'}}\n", "stderr": "", "exit_code": 0}full{"status": "ok", "stdout": "Obj: x=CustomType(hello)\nEncoded: {'x': {'val': 'hello'}}\n", "stderr": "", "exit_code": 0} |
| 40 | run_command | {
"command": "submit_patch"
} | {"status": "error", "error_type": "CommandError", "error_message": "/bin/bash: submit_patch: command not found\n", "details": {"stdout": "", "stderr": "/bin/basfull{"status": "error", "error_type": "CommandError", "error_message": "/bin/bash: submit_patch: command not found\n", "details": {"stdout": "", "stderr": "/bin/bash: submit_patch: command not found\n", "exit_code": 127}} |
| 41 | submit_patch | {} | {"status": "ok", "patch_size": 437, "files_changed": 1}full{"status": "ok", "patch_size": 437, "files_changed": 1} |
diff --git a/fastapi/encoders.py b/fastapi/encoders.py
index 79395108..ec754986 100644
--- a/fastapi/encoders.py
+++ b/fastapi/encoders.py
@@ -234,7 +234,7 @@ def jsonable_encoder(
encoders = {**encoders, **custom_encoder}
obj_dict = _model_dump(
obj,
- mode="json",
+ mode="python",
include=include,
exclude=exclude,
by_alias=by_alias,
ite-packages/pydantic/_internal/_generate_schema.py:1022: in _generate_schema_inner
return self._annotated_schema(obj)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
/Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:2202: in _annotated_schema
schema = self._apply_annotations(source_type, annotations)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:2252: in _apply_annotations
schema = get_inner_schema(source_type)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_schema_generation_shared.py:83: in __call__
schema = self._handler(source_type)
^^^^^^^^^^^^^^^^^^^^^^^^^^
/Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:2425: in new_handler
schema = get_inner_schema(source)
^^^^^^^^^^^^^^^^^^^^^^^^
/Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_schema_generation_shared.py:83: in __call__
schema = self._handler(source_type)
^^^^^^^^^^^^^^^^^^^^^^^^^^
/Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:2423: in new_handler
schema = annotation_get_schema(source, get_inner_schema)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/fastapi/lib/python3.13/site-packages/pydantic/functional_serializers.py:64: in __get_pydantic_core_schema__
schema = handler(source_type)
^^^^^^^^^^^^^^^^^^^^
/Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_schema_generation_shared.py:83: in __call__
schema = self._handler(source_type)
^^^^^^^^^^^^^^^^^^^^^^^^^^
/Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:2425: in new_handler
schema = get_inner_schema(source)
^^^^^^^^^^^^^^^^^^^^^^^^
/Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_schema_generation_shared.py:83: in __call__
schema = self._handler(source_type)
^^^^^^^^^^^^^^^^^^^^^^^^^^
/Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:2231: in inner_handler
schema = self._generate_schema_inner(obj)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
/Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:1043: in _generate_schema_inner
return self.match_type(obj)
^^^^^^^^^^^^^^^^^^^^
/Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:1165: in match_type
return self._unknown_type_schema(obj)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <pydantic._internal._generate_schema.GenerateSchema object at 0x104872b10>
obj = <class 'tests.test_arbitrary_types.get_client.<locals>.FakeNumpyArray'>
def _unknown_type_schema(self, obj: Any) -> CoreSchema:
> raise PydanticSchemaGenerationError(
f'Unable to generate pydantic-core schema for {obj!r}. '
'Set `arbitrary_types_allowed=True` in the model_config to ignore this error'
' or implement `__get_pydantic_core_schema__` on your type to fully support it.'
'\n\nIf you got this error by calling handler(<some type>) within'
' `__get_pydantic_core_schema__` then you likely need to call'
' `handler.generate_schema(<some type>)` since we do not call'
' `__get_pydantic_core_schema__` on `<some type>` otherwise to avoid infinite recursion.'
)
E pydantic.errors.PydanticSchemaGenerationError: Unable to generate pydantic-core schema for <class 'tests.test_arbitrary_types.get_client.<locals>.FakeNumpyArray'>. Set `arbitrary_types_allowed=True` in the model_config to ignore this error or implement `__get_pydantic_core_schema__` on your type to fully support it.
E
E If you got this error by calling handler(<some type>) within `__get_pydantic_core_schema__` then you likely need to call `handler.generate_schema(<some type>)` since we do not call `__get_pydantic_core_schema__` on `<some type>` otherwise to avoid infinite recursion.
E
E For further information visit https://errors.pydantic.dev/2.13/u/schema-for-unknown-type
/Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/fastapi/lib/python3.13/site-packages/pydantic/_internal/_generate_schema.py:674: PydanticSchemaGenerationError
=============================== warnings summary ===============================
../../../../../../../Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/overlays/starlette-0.50.0-py3-none-any/starlette/testclient.py:45
/Users/jp/repos/kaggle-gemini-coding-agent-post-training/.envs/overlays/starlette-0.50.0-py3-none-any/starlette/testclient.py:45: DeprecationWarning: The anyio.abc.BlockingPortal alias is deprecated, use anyio.from_thread.BlockingPortal instead.
_PortalFactoryType = Callable[[], AbstractContextManager[anyio.abc.BlockingPortal]]
-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html
!!!!!!!!!!!!!!!!!!!!!!!!!! stopping after 1 failures !!!!!!!!!!!!!!!!!!!!!!!!!!!
1 failed, 2 passed, 1 warning in 0.87s