Skip to content

Commit

Permalink
Make the model name generation more robust in JSON schema (#7881)
Browse files Browse the repository at this point in the history
  • Loading branch information
joakimnordling committed Oct 30, 2023
1 parent 46f24ce commit 9541b4f
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
2 changes: 1 addition & 1 deletion pydantic/json_schema.py
Expand Up @@ -1846,7 +1846,7 @@ def get_defs_ref(self, core_mode_ref: CoreModeRef) -> DefsRef:
core_ref, mode = core_mode_ref
components = re.split(r'([\][,])', core_ref)
# Remove IDs from each component
components = [x.split(':')[0] for x in components]
components = [x.rsplit(':', 1)[0] for x in components]
core_ref_no_id = ''.join(components)
# Remove everything before the last period from each "component"
components = [re.sub(r'(?:[^.[\]]+\.)+((?:[^.[\]]+))', r'\1', x) for x in components]
Expand Down
5 changes: 4 additions & 1 deletion tests/conftest.py
Expand Up @@ -50,13 +50,14 @@ def disable_error_urls():

@pytest.fixture
def create_module(tmp_path, request):
def run(source_code_or_function, rewrite_assertions=True):
def run(source_code_or_function, rewrite_assertions=True, module_name_prefix=None):
"""
Create module object, execute it and return
Can be used as a decorator of the function from the source code of which the module will be constructed
:param source_code_or_function string or function with body as a source code for created module
:param rewrite_assertions: whether to rewrite assertions in module or not
:param module_name_prefix: string prefix to use in the name of the module, does not affect the name of the file.
"""
if isinstance(source_code_or_function, FunctionType):
Expand All @@ -65,6 +66,8 @@ def run(source_code_or_function, rewrite_assertions=True):
source_code = source_code_or_function

module_name, filename = _create_module_file(source_code, tmp_path, request.node.name)
if module_name_prefix:
module_name = module_name_prefix + module_name

if rewrite_assertions:
loader = AssertionRewritingHook(config=request.config)
Expand Down
26 changes: 26 additions & 0 deletions tests/test_json_schema.py
Expand Up @@ -5752,3 +5752,29 @@ class Bar(BaseModel):
},
'allOf': [{'$ref': '#/$defs/Bar'}],
}


def test_module_with_colon_in_name(create_module):
module = create_module(
# language=Python
"""
from pydantic import BaseModel
class Foo(BaseModel):
x: int
""",
module_name_prefix='C:\\',
)

foo_model = module.Foo
_, v_schema = models_json_schema([(foo_model, 'validation')])
assert v_schema == {
'$defs': {
'Foo': {
'properties': {'x': {'title': 'X', 'type': 'integer'}},
'required': ['x'],
'title': 'Foo',
'type': 'object',
}
}
}

0 comments on commit 9541b4f

Please sign in to comment.