forked from dotnet/aspnetcore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpenApiDocumentIntegrationTests.cs
More file actions
189 lines (157 loc) · 6.88 KB
/
OpenApiDocumentIntegrationTests.cs
File metadata and controls
189 lines (157 loc) · 6.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Text.Json.Nodes;
using Microsoft.AspNetCore.InternalTesting;
using Microsoft.AspNetCore.OpenApi;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Reader;
[UsesVerify]
public sealed class OpenApiDocumentIntegrationTests(SampleAppFixture fixture) : IClassFixture<SampleAppFixture>
{
public static TheoryData<string, OpenApiSpecVersion> OpenApiDocuments()
{
OpenApiSpecVersion[] versions =
[
OpenApiSpecVersion.OpenApi3_0,
OpenApiSpecVersion.OpenApi3_1,
OpenApiSpecVersion.OpenApi3_2,
];
var testCases = new TheoryData<string, OpenApiSpecVersion>();
foreach (var version in versions)
{
testCases.Add("v1", version);
testCases.Add("v2", version);
testCases.Add("controllers", version);
testCases.Add("responses", version);
testCases.Add("forms", version);
testCases.Add("schemas-by-ref", version);
testCases.Add("xml", version);
}
return testCases;
}
[Theory]
[MemberData(nameof(OpenApiDocuments))]
public async Task VerifyOpenApiDocument(string documentName, OpenApiSpecVersion version)
{
var json = await GetOpenApiDocument(documentName, version);
var baseSnapshotsDirectory = SkipOnHelixAttribute.OnHelix()
? Path.Combine(Environment.GetEnvironmentVariable("HELIX_WORKITEM_ROOT"), "Integration", "snapshots")
: "snapshots";
var outputDirectory = Path.Combine(baseSnapshotsDirectory, version.ToString());
await Verify(json)
.UseDirectory(outputDirectory)
.UseParameters(documentName);
}
[Theory]
[MemberData(nameof(OpenApiDocuments))]
public async Task OpenApiDocumentIsValid(string documentName, OpenApiSpecVersion version)
{
var json = await GetOpenApiDocument(documentName, version);
var actual = OpenApiDocument.Parse(json, format: "json");
Assert.NotNull(actual);
Assert.NotNull(actual.Document);
Assert.NotNull(actual.Diagnostic);
Assert.NotNull(actual.Diagnostic.Errors);
Assert.Empty(actual.Diagnostic.Errors);
var ruleSet = ValidationRuleSet.GetDefaultRuleSet();
var errors = actual.Document.Validate(ruleSet);
Assert.Empty(errors);
}
[Theory] // See https://github.com/dotnet/aspnetcore/issues/63090
[MemberData(nameof(OpenApiDocuments))]
public async Task OpenApiDocumentReferencesAreValid(string documentName, OpenApiSpecVersion version)
{
var json = await GetOpenApiDocument(documentName, version);
var result = OpenApiDocument.Parse(json, format: "json");
var document = result.Document;
var documentNode = JsonNode.Parse(json);
var ruleName = "OpenApiDocumentReferencesAreValid";
var rule = new ValidationRule<OpenApiDocument>(ruleName, (context, item) =>
{
var visitor = new OpenApiSchemaReferenceVisitor(ruleName, context, documentNode);
var walker = new OpenApiWalker(visitor);
walker.Walk(item);
});
var ruleSet = new ValidationRuleSet();
ruleSet.Add(typeof(OpenApiDocument), rule);
var errors = document.Validate(ruleSet);
Assert.Empty(errors);
}
private async Task<string> GetOpenApiDocument(string documentName, OpenApiSpecVersion version)
{
var documentService = fixture.Services.GetRequiredKeyedService<OpenApiDocumentService>(documentName);
var scopedServiceProvider = fixture.Services.CreateScope();
var document = await documentService.GetOpenApiDocumentAsync(scopedServiceProvider.ServiceProvider);
return await document.SerializeAsJsonAsync(version);
}
private sealed class OpenApiSchemaReferenceVisitor(
string ruleName,
IValidationContext context,
JsonNode document) : OpenApiVisitorBase
{
public override void Visit(IOpenApiReferenceHolder referenceHolder)
{
if (referenceHolder is OpenApiSchemaReference { Reference.IsLocal: true } reference)
{
ValidateSchemaReference(reference);
}
}
public override void Visit(IOpenApiSchema schema)
{
if (schema is OpenApiSchemaReference { Reference.IsLocal: true } reference)
{
ValidateSchemaReference(reference);
}
}
private void ValidateSchemaReference(OpenApiSchemaReference reference)
{
try
{
if (reference.RecursiveTarget is not null)
{
return;
}
}
catch (InvalidOperationException ex)
{
// Thrown if a circular reference is detected
context.Enter($"{PathString[2..]}/{OpenApiSchemaKeywords.RefKeyword}");
context.CreateError(ruleName, ex.Message);
context.Exit();
return;
}
var id = reference.Reference.ReferenceV3;
if (id is { Length: > 0 } && !IsValidSchemaReference(id, document))
{
var isValid = false;
// Sometimes ReferenceV3 is not a valid JSON pointer, but the $ref
// associated with it still points to a valid location in the document.
// In these cases, we need to find it manually to verify that fact before
// generating a warning that the schema reference is indeed invalid.
var parent = Find(PathString, document);
var @ref = parent[OpenApiSchemaKeywords.RefKeyword];
var path = PathString[2..]; // Trim off the leading "#/" as the context is already at the root
if (@ref is not null && @ref.GetValueKind() is System.Text.Json.JsonValueKind.String &&
@ref.GetValue<string>() is { Length: > 0 } refId)
{
id = refId;
path += $"/{OpenApiSchemaKeywords.RefKeyword}";
isValid = IsValidSchemaReference(id, document);
}
if (!isValid)
{
context.Enter(path);
context.CreateWarning(ruleName, $"The schema reference '{id}' does not point to an existing schema.");
context.Exit();
}
}
static bool IsValidSchemaReference(string id, JsonNode baseNode)
=> Find(id, baseNode) is not null;
static JsonNode Find(string id, JsonNode baseNode)
{
var pointer = new JsonPointer(id.Replace("#/", "/"));
return pointer.Find(baseNode);
}
}
}
}