Browse Source

🐛 Fix path encoding (#978)

pull/1023/head
Patrick McKenna 5 years ago
committed by GitHub
parent
commit
3c1803897f
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 3
      fastapi/encoders.py
  2. 24
      tests/test_jsonable_encoder.py

3
fastapi/encoders.py

@ -1,4 +1,5 @@
from enum import Enum from enum import Enum
from pathlib import PurePath
from types import GeneratorType from types import GeneratorType
from typing import Any, Callable, Dict, List, Set, Tuple, Union from typing import Any, Callable, Dict, List, Set, Tuple, Union
@ -73,6 +74,8 @@ def jsonable_encoder(
) )
if isinstance(obj, Enum): if isinstance(obj, Enum):
return obj.value return obj.value
if isinstance(obj, PurePath):
return str(obj)
if isinstance(obj, (str, int, float, type(None))): if isinstance(obj, (str, int, float, type(None))):
return obj return obj
if isinstance(obj, dict): if isinstance(obj, dict):

24
tests/test_jsonable_encoder.py

@ -1,9 +1,10 @@
from datetime import datetime, timezone from datetime import datetime, timezone
from enum import Enum from enum import Enum
from pathlib import PurePath, PurePosixPath, PureWindowsPath
import pytest import pytest
from fastapi.encoders import jsonable_encoder from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel, ValidationError from pydantic import BaseModel, ValidationError, create_model
try: try:
from pydantic import Field from pydantic import Field
@ -69,6 +70,19 @@ class ModelWithAlias(BaseModel):
foo: str = Field(..., alias="Foo") foo: str = Field(..., alias="Foo")
@pytest.fixture(
name="model_with_path", params=[PurePath, PurePosixPath, PureWindowsPath]
)
def fixture_model_with_path(request):
class Config:
arbitrary_types_allowed = True
ModelWithPath = create_model(
"ModelWithPath", path=(request.param, ...), __config__=Config
)
return ModelWithPath(path=request.param("/foo", "bar"))
def test_encode_class(): def test_encode_class():
person = Person(name="Foo") person = Person(name="Foo")
pet = Pet(owner=person, name="Firulais") pet = Pet(owner=person, name="Firulais")
@ -120,3 +134,11 @@ def test_custom_encoders():
instance, custom_encoder={safe_datetime: lambda o: o.isoformat()} instance, custom_encoder={safe_datetime: lambda o: o.isoformat()}
) )
assert encoded_instance["dt_field"] == instance.dt_field.isoformat() assert encoded_instance["dt_field"] == instance.dt_field.isoformat()
def test_encode_model_with_path(model_with_path):
if isinstance(model_with_path.path, PureWindowsPath):
expected = "\\foo\\bar"
else:
expected = "/foo/bar"
assert jsonable_encoder(model_with_path) == {"path": expected}

Loading…
Cancel
Save