-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAsyncApiContentGeneratorTests.cs
More file actions
298 lines (242 loc) · 12.1 KB
/
AsyncApiContentGeneratorTests.cs
File metadata and controls
298 lines (242 loc) · 12.1 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
using System.Collections.ObjectModel;
using ApiCodeGenerator.AsyncApi.DOM;
using Moq;
using Newtonsoft.Json.Linq;
using NUnit.Framework.Constraints;
namespace ApiCodeGenerator.AsyncApi.Tests;
public class AsyncApiContentGeneratorTests
{
[TestCase("asyncapi.json")]
[TestCase("asyncapi.yml")]
public async Task LoadApiDocument(string fileName)
{
var extensions = new Core.ExtensionManager.Extensions();
var context = new GeneratorContext(
settingsFactory: (_, _, _) => null,
extensions,
variables: new Dictionary<string, string>())
{
DocumentReader = await TestHelpers.LoadApiDocumentAsync(fileName),
};
var contentGenerator = (FakeContentGenerator)await FakeContentGenerator.CreateAsync(context);
ValidateDocument(contentGenerator.Document);
}
[Test]
public async Task LoadSettingsAsync()
{
var json = "{\"testProp\":\"val\", \"anyType\":\"JObject\", \"templateDirectory\":\"Tmpl\"}";
var extensions = new Core.ExtensionManager.Extensions();
GeneratorContext context = new(
settingsFactory: GetSettingsFactory(json),
extensions,
variables: new Dictionary<string, string>())
{
DocumentReader = await TestHelpers.LoadApiDocumentAsync("asyncapi.json"),
};
var contentGenerator = (FakeContentGenerator)await FakeContentGenerator.CreateAsync(context);
var settings = contentGenerator.FakeGenerator.Settings;
Assert.NotNull(settings);
Assert.AreEqual("val", settings.TestProp);
Assert.AreEqual("JObject", settings.CSharpGeneratorSettings.AnyType);
Assert.AreEqual("Tmpl", settings.CodeGeneratorSettings.TemplateDirectory);
}
[Test]
public async Task Load_OperationGenerator()
{
var settingsJson = "{\"operationGenerationMode\": \"MultipleClientsFromFirstTagAndOperationId\"}";
var context = TestHelpers.CreateContext(settingsJson, "asyncapi.json");
var gen = await FakeContentGenerator.CreateAsync(context);
Assert.NotNull(gen);
Assert.IsInstanceOf<FakeContentGenerator>(gen);
var fakeGen = (FakeContentGenerator)gen!;
var settings = fakeGen.FakeGenerator.Settings;
Assert.NotNull(settings);
Assert.NotNull(settings.OperationNameGenerator);
Assert.IsInstanceOf<OperationNameGenerators.MultipleClientsFromFirstTagAndOperationId>(settings.OperationNameGenerator);
}
[Test]
public async Task ParameterNameReplacementOn()
{
var settingsJson = "{\"replaceNameCollection\":{\"@\":\"_\"}}";
var context = TestHelpers.CreateContext(settingsJson, "asyncapi.json");
var gen = await FakeContentGenerator.CreateAsync(context);
Assert.NotNull(gen);
Assert.IsInstanceOf<FakeContentGenerator>(gen);
var fakeGen = (FakeContentGenerator)gen!;
var settings = fakeGen.FakeGenerator.Settings;
Assert.NotNull(settings);
Assert.NotNull(settings.CSharpGeneratorSettings.PropertyNameGenerator);
Assert.IsInstanceOf<PropertyNameGeneratorWithReplace>(settings.CSharpGeneratorSettings.PropertyNameGenerator);
Assert.NotNull(settings.ParameterNameGenerator);
Assert.IsInstanceOf<ParameterNameGeneratorWithReplace>(settings.ParameterNameGenerator);
}
[Test]
public async Task LoadApiDocument_WithTextPreprocess()
{
const string schemaName = nameof(schemaName);
var settingsJson = new JObject();
Func<string, string?, string> dlgt = new FakeTextPreprocessor("{}").Process;
var context = CreateContext(settingsJson);
context.Preprocessors = new Preprocessors(
new Dictionary<Type, Delegate[]> { [typeof(string)] = [dlgt] });
var gen = (FakeContentGenerator)await FakeContentGenerator.CreateAsync(context);
var apiDocument = gen.Document;
Assert.NotNull(apiDocument);
Assert.That(apiDocument?.Components?.Schemas, Does.ContainKey(schemaName));
var sch = apiDocument?.Components?.Schemas[schemaName].ToJson(Newtonsoft.Json.Formatting.None);
Assert.That(sch, Is.EqualTo("{\"$schema\":\"http://json-schema.org/draft-04/schema#\",\"processed\":{}}"));
}
[Test]
public async Task LoadApiDocument_WithTextPreprocess_Log()
{
const string schemaName = nameof(schemaName);
const string filePath = "cd4bed67-1cc0-44a2-8dd1-30a0bd0c1dee";
var settingsJson = new JObject();
Func<string, string?, ILogger?, string> dlgt = new FakeTextPreprocessor("{}").Process;
var logger = new Mock<ILogger>();
var context = CreateContext(settingsJson);
context.Logger = logger.Object;
context.DocumentPath = filePath;
context.Preprocessors = new Preprocessors(
new Dictionary<Type, Delegate[]> { [typeof(string)] = [dlgt] });
var gen = (FakeContentGenerator)await FakeContentGenerator.CreateAsync(context);
var apiDocument = gen.Document;
Assert.NotNull(apiDocument);
Assert.That(apiDocument?.Components?.Schemas, Does.ContainKey(schemaName));
var sch = apiDocument?.Components?.Schemas[schemaName].ToJson(Newtonsoft.Json.Formatting.None);
Assert.That(sch, Is.EqualTo("{\"$schema\":\"http://json-schema.org/draft-04/schema#\",\"processed\":{}}"));
logger.Verify(l => l.LogWarning(It.IsAny<string>(), filePath, It.IsAny<string>()));
}
[Test]
public async Task LoadApiDocument_WithModelPreprocess()
{
const string schemaName = nameof(schemaName);
var settingsJson = new JObject();
Func<AsyncApiDocument, string?, AsyncApiDocument> dlgt = new FakeModelPreprocessor("{}").Process;
var context = CreateContext(settingsJson);
context.DocumentReader = new StringReader("{\"components\":{\"schemas\":{\"" + schemaName + "\":{\"$schema\":\"http://json-schema.org/draft-04/schema#\"}}}}");
context.Preprocessors = new Preprocessors(
new Dictionary<Type, Delegate[]>
{
[typeof(AsyncApiDocument)] = [dlgt],
});
var gen = (FakeContentGenerator)await FakeContentGenerator.CreateAsync(context);
var apiDocument = gen.Document;
Assert.NotNull(apiDocument);
Assert.That(apiDocument?.Components?.Schemas, Does.ContainKey(schemaName));
var sch = apiDocument?.Components?.Schemas[schemaName].ToJson(Newtonsoft.Json.Formatting.None);
Assert.That(sch, Is.EqualTo("{\"$schema\":\"http://json-schema.org/draft-04/schema#\",\"properties\":{\"processedModel\":{}}}"));
}
[TestCase("externalRef.json")]
[TestCase("externalRef.yaml")]
public async Task LoadApiDocument_WithExternalRef(string documentPath)
{
var settingsJson = new JObject();
var context = CreateContext(settingsJson);
context.DocumentReader = await TestHelpers.LoadApiDocumentAsync(documentPath);
context.DocumentPath = documentPath;
var contentGenerator = (FakeContentGenerator)await FakeContentGenerator.CreateAsync(context);
var document = contentGenerator.Document;
Assert.NotNull(document.Components?.Messages["lightMeasured"].Reference);
}
private static Func<Type, Newtonsoft.Json.JsonSerializer?, IReadOnlyDictionary<string, string>?, object?> GetSettingsFactory(string json)
=> (t, s, _) => (s ?? new()).Deserialize(new StringReader(json), t);
private void ValidateDocument(AsyncApiDocument document)
{
Assert.NotNull(document);
Assert.AreEqual("Streetlights Kafka API", document.Info?.Title);
const string channelPrefix = "smartylighting.streetlights.1.0.";
Assert.That(document.Channels,
Is.Not.Null
.And.ContainKey(channelPrefix + "event.{streetlightId}.lighting.measured")
.And.ContainKey(channelPrefix + "action.{streetlightId}.turn.on")
.And.ContainKey(channelPrefix + "action.{streetlightId}.turn.off")
.And.ContainKey(channelPrefix + "action.{streetlightId}.dim"));
Assert.NotNull(document.Components);
Assert.That(document.Components?.Messages,
Is.Not.Null
.And.ContainKey("lightMeasured")
.And.ContainKey("turnOnOff")
.And.ContainKey("dimLight"));
Assert.That(document.Components?.Parameters,
Is.Not.Null
.And.ContainKey("streetlightId"));
Assert.That(document.Components?.Schemas,
Is.Not.Null
.And.ContainKey("lightMeasuredPayload")
.And.ContainKey("turnOnOffPayload")
.And.ContainKey("dimLightPayload")
.And.ContainKey("sentAt"));
Assert.That(document.Servers,
Is.Not.Null
.And.ContainKey("scram-connections")
.And.ContainKey("mtls-connections"));
// Resolve $ref in channel defintion
var actualChannel = document.Channels?[channelPrefix + "event.{streetlightId}.lighting.measured"];
Assert.That(actualChannel,
Is.Not.Null
.And.Property("Publish").Not.Null
.And.Property("Subscribe").Null);
Assert.That(actualChannel?.Parameters,
Is.Not.Null
.And.ContainKey("streetlightId"));
Assert.That(actualChannel?.Parameters["streetlightId"],
Is.Not.Null
.And.Property("ReferencePath").EqualTo("#/components/parameters/streetlightId")
.And.Property("Reference").EqualTo(document.Components?.Parameters["streetlightId"]));
Assert.That(actualChannel?.Publish?.Message,
Is.Not.Null
.And.Property("ReferencePath").EqualTo("#/components/messages/lightMeasured")
.And.Property("Reference").EqualTo(document.Components?.Messages["lightMeasured"]));
// Resolve $ref in message definition
var actualMessage = document.Components?.Messages["turnOnOff"];
Assert.That(actualMessage, Is.Not.Null);
Assert.That(actualMessage?.Payload,
Is.Not.Null
.And.Property("Reference").EqualTo(document.Components?.Schemas["turnOnOffPayload"]));
// Resolve $ref in schema definition
Assert.That(document.Components?.Schemas["turnOnOffPayload"]?.ActualProperties,
Is.Not.Null
.And.ContainKey("command"));
//Read server object
Assert.That(document.Servers["scram-connections"],
Is.Not.Null
.And.Property("Url").EqualTo("test.mykafkacluster.org:18092")
.And.Property("Protocol").EqualTo("kafka-secure")
.And.Property("Description").EqualTo("Test broker secured with scramSha256"));
// Resolve $ref in servers
Assert.That(document.Servers["mtls-connections"],
Is.Not.Null
.And.Property("Reference").EqualTo(document.Components?.Servers["mtls-connections"]));
// Resolve $ref in server variables
Assert.Multiple(() =>
{
var variables = document.Components?.Servers["mtls-connections"].Variables;
Assert.That(variables,
Is.Not.Null
.And.ContainKey("someRefVariable")
.And.ContainKey("someVariable"));
Assert.That(variables!["someRefVariable"],
Is.Not.Null
.And.Property("Reference").EqualTo(document.Components?.ServerVariables["someRefVariable"]));
});
//Read server variables
Assert.That(document.Components?.ServerVariables["someRefVariable"],
new PredicateConstraint<ServerVariable>(a =>
a.Description == "Some ref variable"
&& a.Enum?.FirstOrDefault() == "def"
&& a.Default == "def"
&& a.Examples?.FirstOrDefault() == "exam"));
}
private GeneratorContext CreateContext(JObject settingsJson, Core.ExtensionManager.Extensions? extension = null)
{
extension ??= new();
return new GeneratorContext(
(t, s, _) => settingsJson.ToObject(t, s ?? new()),
extension,
new ReadOnlyDictionary<string, string>(new Dictionary<string, string>()))
{
DocumentReader = new StringReader("{}"),
};
}
}