diff --git a/preprocess_schemas.py b/preprocess_schemas.py index 6346ccf..0b7f76f 100644 --- a/preprocess_schemas.py +++ b/preprocess_schemas.py @@ -449,16 +449,21 @@ def rewrite_refs_to_variants(root, op, file_path, variant_needs): for node in iter_nodes(root): if isinstance(node, dict) and "$ref" in node: ref = node["$ref"] - if "#" not in ref: # External file reference - abs_target = (file_path.parent / ref).resolve() - if ( - str(abs_target) in variant_needs - and op in variant_needs[str(abs_target)] - ): - ref_path = Path(ref) - node["$ref"] = str( - ref_path.parent / f"{ref_path.stem}_{op}_request.json" - ) + ref_file, separator, fragment = ref.partition("#") + if not ref_file: + continue + abs_target = (file_path.parent / ref_file).resolve() + if ( + str(abs_target) in variant_needs + and op in variant_needs[str(abs_target)] + ): + ref_path = Path(ref_file) + variant_ref = str( + ref_path.parent / f"{ref_path.stem}_{op}_request.json" + ) + node["$ref"] = variant_ref + ( + separator + fragment if separator else "" + ) def _apply_request_rules_to_object( diff --git a/tests/test_codegen_pipeline.py b/tests/test_codegen_pipeline.py index d601a64..7b37460 100644 --- a/tests/test_codegen_pipeline.py +++ b/tests/test_codegen_pipeline.py @@ -247,6 +247,33 @@ def test_eval_prop_inclusion_applies_operation_overrides(self) -> None: class VariantGenerationTest(unittest.TestCase): """Tests request variant construction and output.""" + def test_rewrite_external_ref_preserves_fragment(self) -> None: + """External refs target variants without losing their fragments.""" + schema = { + "properties": { + "child": {"$ref": "nested/child.json#/$defs/item"}, + "local": {"$ref": "#/$defs/local"}, + } + } + file_path = Path("/schemas/parent.json") + child_path = str((file_path.parent / "nested" / "child.json").resolve()) + + preprocess_schemas.rewrite_refs_to_variants( + schema, + "create", + file_path, + {child_path: {"create"}}, + ) + + self.assertEqual( + schema["properties"]["child"]["$ref"], + "nested/child_create_request.json#/$defs/item", + ) + self.assertEqual( + schema["properties"]["local"]["$ref"], + "#/$defs/local", + ) + def test_object_variant_filters_fields_and_rewrites_refs(self) -> None: """Object variants filter fields and target child variants.""" schema = {