Skip to content

Commit 25de3e3

Browse files
Improve reference validator
- Improve handling of circular references. - Improve the path.
1 parent 7c01430 commit 25de3e3

File tree

2 files changed

+22
-10
lines changed

2 files changed

+22
-10
lines changed

src/Microsoft.OpenApi/Validations/Rules/OpenApiDocumentRules.cs

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// Copyright (c) Microsoft Corporation. All rights reserved.
22
// Licensed under the MIT license.
33

4+
using System;
45
using System.Text.Json.Nodes;
56
using Microsoft.OpenApi.Reader;
67

@@ -80,9 +81,28 @@ public override void Visit(IOpenApiSchema schema)
8081

8182
private void ValidateSchemaReference(OpenApiSchemaReference reference)
8283
{
83-
if (reference.RecursiveTarget is not null)
84+
// Trim off the leading "#/" as the context is already at the root of the document
85+
var segment =
86+
#if NET8_0_OR_GREATER
87+
$"{PathString[2..]}/$ref";
88+
#else
89+
PathString.Substring(2) + "/$ref";
90+
#endif
91+
92+
try
93+
{
94+
if (reference.RecursiveTarget is not null)
95+
{
96+
return;
97+
}
98+
}
99+
catch (InvalidOperationException ex)
84100
{
85101
// The reference was followed to a valid schema somewhere in the document
102+
context.Enter(segment);
103+
context.CreateWarning(ruleName, ex.Message);
104+
context.Exit();
105+
86106
return;
87107
}
88108

@@ -109,14 +129,6 @@ private void ValidateSchemaReference(OpenApiSchemaReference reference)
109129

110130
if (!isValid)
111131
{
112-
// Trim off the leading "#/" as the context is already at the root of the document
113-
var segment =
114-
#if NET8_0_OR_GREATER
115-
PathString[2..];
116-
#else
117-
PathString.Substring(2);
118-
#endif
119-
120132
context.Enter(segment);
121133
context.CreateWarning(ruleName, string.Format(SRResource.Validation_SchemaReferenceDoesNotExist, id));
122134
context.Exit();

test/Microsoft.OpenApi.Tests/Validations/OpenApiDocumentValidationTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,6 @@ public static void ValidateSchemaReferencesAreInvalid()
129129
Assert.NotNull(errors);
130130
var error = Assert.Single(errors);
131131
Assert.Equal("The schema reference '#/components/schemas/Pet' does not point to an existing schema.", error.Message);
132-
Assert.Equal("#/paths/~1pets/get/responses/200/content/application~1json/schema", error.Pointer);
132+
Assert.Equal("#/paths/~1pets/get/responses/200/content/application~1json/schema/$ref", error.Pointer);
133133
}
134134
}

0 commit comments

Comments
 (0)