-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTestHelpers.cs
More file actions
275 lines (249 loc) · 13.2 KB
/
TestHelpers.cs
File metadata and controls
275 lines (249 loc) · 13.2 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
using System.Security.Cryptography;
using ApiCodeGenerator.Core.Converters;
using Newtonsoft.Json;
namespace ApiCodeGenerator.AsyncApi.Tests.Infrastructure;
internal static partial class TestHelpers
{
public static readonly string VERSION = typeof(TestHelpers).Assembly.GetName().Version?.ToString() ?? string.Empty;
public static readonly string NEWTON_VERSION = "13.0.0.0";
public static readonly string NJSON_VERSION = "11.0.2.0 (Newtonsoft.Json v" + NEWTON_VERSION + ")";
public static readonly string APICODEGEN_VERSION = VERSION + " (NJsonSchema v" + NJSON_VERSION + ")";
public static readonly string GENERATED_CODE = "[System.CodeDom.Compiler.GeneratedCode(\"NJsonSchema\", \"" + APICODEGEN_VERSION + "\")]";
public static readonly string GENERATED_CODE_ATTRIBUTE = "[System.CodeDom.Compiler.GeneratedCode(\"ApiCodeGenerator.AsyncApi\", \"" + APICODEGEN_VERSION + "\")]";
public static string GetAsyncApiPath(string schemaFile) => Path.Combine("asyncApi", schemaFile);
public static async Task<TextReader> LoadApiDocumentAsync(string fileName)
{
var filePath = GetAsyncApiPath(fileName);
var data = await File.ReadAllTextAsync(filePath);
return new StringReader(data);
}
public static async Task RunTest(CSharpClientGeneratorSettings settings, string expectedClientDeclartion, string schemaFile, string testOperResponseText, string? usings = null)
{
var reader = await LoadApiDocumentAsync(schemaFile);
await RunTest(settings, expectedClientDeclartion, reader, testOperResponseText, usings);
}
public static async Task RunTest(CSharpClientGeneratorSettings settings, string expectedClientDeclartion, TextReader documentReader, string testOperResponseText, string? usings = null)
{
var generator = await CreateGenerator(documentReader, settings);
var expected = GetExpectedCode(expectedClientDeclartion, testOperResponseText, usings: usings);
//Act
var actual = generator.Generate();
//Assert
Assert.That(actual, Is.EqualTo(expected));
}
public static GeneratorContext CreateContext(string settingsJson, string schemaFile, Core.ExtensionManager.Extensions? extensions = null)
{
var jReader = new JsonTextReader(new StringReader(settingsJson));
var docReader = File.OpenText(GetAsyncApiPath(schemaFile));
return new GeneratorContext(
(t, s, _) => s!.Deserialize(jReader, t),
extensions ?? new(AcgExtension.CodeGenerators, GetOperationGenerators()),
new Dictionary<string, string>())
{
DocumentReader = docReader,
};
}
public static string GetExpectedCode(string? expectedClientDeclartion, string? testOperResponseText, string @namespace = "TestNS", string? usings = null)
{
if (!string.IsNullOrWhiteSpace(expectedClientDeclartion) && !expectedClientDeclartion.Contains(GENERATED_CODE_ATTRIBUTE))
{
expectedClientDeclartion = " " + GENERATED_CODE_ATTRIBUTE + "\n" + expectedClientDeclartion;
}
var expected = "//----------------------\n" +
"// <auto-generated>\n" +
"// Generated using the ApiCodeGenerator.AsyncApi toolchain v" + APICODEGEN_VERSION + "\n" +
"// </auto-generated>\n" +
"//----------------------\n" +
"\n" +
(usings ?? GetAdditionalUsings()) +
"\n" +
"\n" +
$"namespace {@namespace}\n" +
"{\n" +
(expectedClientDeclartion is null ? string.Empty : expectedClientDeclartion) +
(testOperResponseText is null ? string.Empty : (testOperResponseText + "\n")) +
"}\n";
return expected;
}
public static string GetExpectedClientCode(string className, string operationsCode, int identCnt = 4, string? baseType = null, string typeKind = "partial class")
{
var ident = new string(' ', identCnt);
return
ident + "/// <summary>\n" +
ident + "/// The Smartylighting Streetlights API allows you to remotely manage the city lights.\n" +
ident + "/// <br/>\n" +
ident + "/// <br/>### Check out its awesome features:\n" +
ident + "/// <br/>\n" +
ident + "/// <br/>* Turn a specific streetlight on/off 🌃\n" +
ident + "/// <br/>* Dim a specific streetlight 😎\n" +
ident + "/// <br/>* Receive real-time information about environmental lighting conditions 📈\n" +
ident + "/// <br/>\n" +
ident + "/// </summary>\n" +
ident + GENERATED_CODE_ATTRIBUTE + "\n" +
ident + $"public {typeKind} {className}" + (string.IsNullOrEmpty(baseType) ? string.Empty : $" : {baseType}") + "\n" +
ident + "{\n" +
operationsCode +
ident + "}\n";
}
public static string GetExpectedDtoCode(int identCnt = 4)
{
var ident = new string(' ', identCnt);
return ident + GENERATED_CODE + "\n" +
ident + "public partial class LightMeasuredPayload\n" +
ident + "{\n" +
ident + " /// <summary>\n" +
ident + " /// Light intensity measured in lumens.\n" +
ident + " /// </summary>\n" +
ident + " [Newtonsoft.Json.JsonProperty(\"lumens\", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]\n" +
ident + " public int? Lumens { get; set; }\n" +
"\n" +
ident + " [Newtonsoft.Json.JsonProperty(\"sentAt\", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]\n" +
ident + " public System.DateTimeOffset? SentAt { get; set; }\n" +
GetAdditionalPropertiesCode(identCnt + 4) +
ident + "}\n" +
"\n" +
ident + GENERATED_CODE + "\n" +
ident + "public partial class TurnOnOffPayload\n" +
ident + "{\n" +
ident + " /// <summary>\n" +
ident + " /// Whether to turn on or off the light.\n" +
ident + " /// </summary>\n" +
ident + " [Newtonsoft.Json.JsonProperty(\"command\", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]\n" +
ident + " [Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]\n" +
ident + " public TurnOnOffPayloadCommand? Command { get; set; }\n" +
"\n" +
ident + " [Newtonsoft.Json.JsonProperty(\"sentAt\", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]\n" +
ident + " public System.DateTimeOffset? SentAt { get; set; }\n" +
GetAdditionalPropertiesCode(identCnt + 4) +
ident + "}\n" +
"\n" +
ident + GENERATED_CODE + "\n" +
ident + "public partial class DimLightPayload\n" +
ident + "{\n" +
ident + " /// <summary>\n" +
ident + " /// Percentage to which the light should be dimmed to.\n" +
ident + " /// </summary>\n" +
ident + " [Newtonsoft.Json.JsonProperty(\"percentage\", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]\n" +
ident + " public int? Percentage { get; set; }\n" +
"\n" +
ident + " [Newtonsoft.Json.JsonProperty(\"sentAt\", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)]\n" +
ident + " public System.DateTimeOffset? SentAt { get; set; }\n" +
GetAdditionalPropertiesCode(identCnt + 4) +
ident + "}\n" +
"\n" +
ident + GENERATED_CODE + "\n" +
ident + "public enum TurnOnOffPayloadCommand\n" +
ident + "{\n" +
"\n" +
ident + " [System.Runtime.Serialization.EnumMember(Value = @\"on\")]\n" +
ident + " On = 0,\n" +
"\n\n" +
ident + " [System.Runtime.Serialization.EnumMember(Value = @\"off\")]\n" +
ident + " Off = 1,\n" +
"\n\n" +
ident + "}\n"
;
}
public static string GetExpectedSummary(string text, int identCnt)
{
var ident = new string(' ', identCnt);
return
ident + "/// <summary>\n" +
string.Join(null, text.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries).Select(i => ident + "/// " + i + '\n')) +
ident + "/// </summary>\n";
}
public static string GetExpectedPublisherCode(string name, string payloadType, int identCnt)
=> GetExpectedPublisherCode(name, payloadType, identCnt, []);
/// <summary>
/// Возвращает ожидаемый код паблишера.
/// </summary>
/// <param name="name">Имя метода.</param>
/// <param name="payloadType">Тип параметра payload.</param>
/// <param name="identCnt">Количество лидирующих пробелов.</param>
/// <param name="bodyLines">Тело метода. Если null то тело не формируется. Если пустой массив то в теле пишется 'return Task.CompleetedTask'.</param>
/// <returns>Строка с кодом паблишера.</returns>
public static string GetExpectedPublisherCode(string name, string payloadType, int identCnt, string[]? bodyLines)
{
var ident = new string(' ', identCnt);
var body = bodyLines switch
{
null => null,
{ Length: 0 } => ident + " return Task.CompletedTask;\n",
_ => string.Join(
string.Empty,
bodyLines.Select(l => string.IsNullOrEmpty(l) ? "\n" : $"{ident} {l}\n")),
};
var bodyBlock = body is null
? ";\n"
: $"\n{ident}{{\n{body}{ident}}}\n";
return
ident + "public Task " + name + "(string streetlightId, " + payloadType + " payload)"
+ bodyBlock;
}
public static string GetExpectedSubscriberCode(string name, string payloadType, int identCnt)
=> GetExpectedSubscriberCode(name, payloadType, identCnt, []);
/// <summary>
/// Возвращает ожидаемый код подписчика.
/// </summary>
/// <param name="name">Имя метода.</param>
/// <param name="payloadType">Тип параметра payload.</param>
/// <param name="identCnt">Количество лидирующих пробелов.</param>
/// <param name="bodyLines">Тело метода. Если null то тело не формируется. Если пустой массив то в теле пишется 'return Task.CompleetedTask'.</param>
/// <returns>Строка с кодом подписчика.</returns>
public static string GetExpectedSubscriberCode(string name, string payloadType, int identCnt, string[]? bodyLines)
{
var ident = new string(' ', identCnt);
var body = bodyLines switch
{
null => null,
{ Length: 0 } => string.Empty,
_ => string.Join(
string.Empty,
bodyLines.Select(l => string.IsNullOrEmpty(l) ? "\n" : $"{ident} {l}\n")),
};
var bodyBlock = body is null
? ";\n"
: $"\n{ident}{{\n{body}{ident}}}\n";
return
ident + "public void " + name + "(string streetlightId, Action<" + payloadType + "> callback)"
+ bodyBlock;
}
public static string GetAdditionalPropertiesCode(int identCnt)
{
var ident = new string(' ', identCnt);
return "\n\n\n" +
ident + "private System.Collections.Generic.IDictionary<string, object> _additionalProperties;\n" +
"\n" +
ident + "[Newtonsoft.Json.JsonExtensionData]\n" +
ident + "public System.Collections.Generic.IDictionary<string, object> AdditionalProperties\n" +
ident + "{\n" +
ident + " get { return _additionalProperties ?? (_additionalProperties = new System.Collections.Generic.Dictionary<string, object>()); }\n" +
ident + " set { _additionalProperties = value; }\n" +
ident + "}\n\n";
}
public static T LoadSettings<T>(string json)
where T : CSharpGeneratorBaseSettings
=> JsonConvert.DeserializeObject<T>(
json,
new JsonSerializerSettings()
{
Converters =
{
new SettingsConverter(typeof(T), CSharpClientContentGenerator.UNWRAP_PROPS, null),
},
})!;
public static IReadOnlyDictionary<string, IReadOnlyCollection<Type>> GetOperationGenerators()
=> AcgExtension.OperationGenerators
.ToDictionary(
kv => kv.Key,
kv => (IReadOnlyCollection<Type>)[kv.Value]);
private static Task<IContentGenerator> CreateGenerator(TextReader document, CSharpClientGeneratorSettings settings)
{
var context = new GeneratorContext((_, _, _) => settings, new Core.ExtensionManager.Extensions(), new Dictionary<string, string>())
{
DocumentReader = document,
};
return CSharpClientContentGenerator.CreateAsync(context);
}
private static string GetAdditionalUsings() => "\n";
}