From c8ad816b0e7c3026710817bfdf0db2cab6182474 Mon Sep 17 00:00:00 2001 From: Pierre Chanial Date: Sun, 15 May 2022 23:29:47 +0200 Subject: [PATCH] Fix error message for the json schemas of non str-keyed mappings. --- .pre-commit-config.yaml | 2 +- apischema/json_schema/schema.py | 4 ++-- .../{test_typed_dict.py => test_dict.py} | 15 +++++++++++++++ 3 files changed, 18 insertions(+), 3 deletions(-) rename tests/integration/{test_typed_dict.py => test_dict.py} (81%) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 22a17dad..61c0e537 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -21,7 +21,7 @@ repos: hooks: - id: isort - repo: https://github.com/psf/black - rev: 22.1.0 + rev: 22.3.0 hooks: - id: black args: [-C] diff --git a/apischema/json_schema/schema.py b/apischema/json_schema/schema.py index 3c327918..ac1aeef7 100644 --- a/apischema/json_schema/schema.py +++ b/apischema/json_schema/schema.py @@ -217,8 +217,8 @@ def mapping( with context_setter(self): self._ignore_first_ref = True key = self.visit(key_type) - if key["type"] != JsonType.STRING: - raise ValueError("Mapping types must string-convertible key") + if "type" not in key or key["type"] != JsonType.STRING: + raise ValueError("Mapping types must have string-convertible keys") value = self.visit(value_type) if "pattern" in key: return json_schema( diff --git a/tests/integration/test_typed_dict.py b/tests/integration/test_dict.py similarity index 81% rename from tests/integration/test_typed_dict.py rename to tests/integration/test_dict.py index 76fa6b48..6d1a3791 100644 --- a/tests/integration/test_typed_dict.py +++ b/tests/integration/test_dict.py @@ -1,4 +1,5 @@ from datetime import date +from typing import Any, Dict, Mapping import pytest @@ -8,6 +9,20 @@ from apischema.typing import Annotated, TypedDict +class MyDict(dict): + pass + + +@pytest.mark.parametrize( + "tp", [dict, Dict[int, Any], pytest.param(MyDict, marks=pytest.mark.xfail), Mapping] +) +def test_dict(tp): + with pytest.raises(ValueError, match="string-convertible keys"): + deserialization_schema(tp) + with pytest.raises(ValueError, match="string-convertible keys"): + serialization_schema(tp) + + class TD1(TypedDict, total=False): key1: str