-
-
Notifications
You must be signed in to change notification settings - Fork 804
Expand file tree
/
Copy pathGeneratorTestHelper.cs
More file actions
323 lines (268 loc) · 11.1 KB
/
GeneratorTestHelper.cs
File metadata and controls
323 lines (268 loc) · 11.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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text;
using Microsoft.CodeAnalysis;
using HotChocolate;
using HotChocolate.Language;
using StrawberryShake.CodeGeneration.Analyzers;
using StrawberryShake.CodeGeneration.Analyzers.Models;
using StrawberryShake.CodeGeneration.Utilities;
using RequestStrategyGen = StrawberryShake.Tools.Configuration.RequestStrategy;
using static StrawberryShake.CodeGeneration.CSharp.CSharpGenerator;
namespace StrawberryShake.CodeGeneration.CSharp;
public static class GeneratorTestHelper
{
public static IReadOnlyList<IError> AssertError(params string[] fileNames)
{
var result = Generate(
fileNames,
new CSharpGeneratorSettings
{
Namespace = "Foo.Bar",
ClientName = "FooClient",
AccessModifier = AccessModifier.Public
});
Assert.True(
result.Errors.Any(),
"It is expected that the result has no generator errors!");
return result.Errors;
}
public static void AssertResult([StringSyntax("graphql")] params string[] sourceTexts) =>
AssertResult(true, sourceTexts);
public static void AssertResult(
bool strictValidation,
[StringSyntax("graphql")] params string[] sourceTexts) =>
AssertResult(
new AssertSettings { StrictValidation = strictValidation },
sourceTexts);
public static void AssertResult(
AssertSettings settings,
[StringSyntax("graphql")] params string[] sourceTexts)
{
AssertResult(settings, false, sourceTexts);
}
public static void AssertResult(
AssertSettings settings,
bool skipWarnings,
params string[] sourceTexts)
{
var clientModel = CreateClientModel(sourceTexts, settings.StrictValidation, settings.NoStore);
var documents = new StringBuilder();
var documentNames = new HashSet<string>();
documents.AppendLine("// ReSharper disable ArrangeObjectCreationWhenTypeEvident");
documents.AppendLine("// ReSharper disable BuiltInTypeReferenceStyle");
documents.AppendLine("// ReSharper disable ConvertToAutoProperty");
documents.AppendLine("// ReSharper disable InconsistentNaming");
documents.AppendLine("// ReSharper disable PartialTypeWithSinglePart");
documents.AppendLine("// ReSharper disable PreferConcreteValueOverDefault");
documents.AppendLine("// ReSharper disable RedundantNameQualifier");
documents.AppendLine("// ReSharper disable SuggestVarOrType_SimpleTypes");
documents.AppendLine("// ReSharper disable UnusedMember.Global");
documents.AppendLine("// ReSharper disable UnusedMethodReturnValue.Local");
documents.AppendLine("// ReSharper disable UnusedType.Global");
documents.AppendLine("// ReSharper disable UnusedVariable");
documents.AppendLine();
if (settings.Profiles.Count == 0)
{
settings.Profiles.Add(TransportProfile.Default);
}
var result = Generate(
clientModel,
new CSharpGeneratorSettings
{
Namespace = settings.Namespace ?? "Foo.Bar",
ClientName = settings.ClientName ?? "FooClient",
AccessModifier = settings.AccessModifier,
StrictSchemaValidation = settings.StrictValidation,
RequestStrategy = settings.RequestStrategy,
TransportProfiles = settings.Profiles,
NoStore = settings.NoStore,
InputRecords = settings.InputRecords,
EntityRecords = settings.EntityRecords,
RazorComponents = settings.RazorComponents
});
Assert.False(
result.Errors.Any(),
"It is expected that the result has no generator errors!");
foreach (var document in result.Documents)
{
if (!documentNames.Add(document.Name))
{
Assert.Fail($"Document name duplicated {document.Name}");
}
if (document.Kind == SourceDocumentKind.CSharp)
{
documents.AppendLine("// " + document.Name);
documents.AppendLine();
documents.AppendLine(document.SourceText);
documents.AppendLine();
}
else if (document.Kind == SourceDocumentKind.GraphQL)
{
documents.AppendLine("// " + document.Name);
documents.AppendLine("// " + document.Hash);
documents.AppendLine();
using var reader = new StringReader(document.SourceText);
string? line;
do
{
line = reader.ReadLine();
if (line is not null)
{
documents.AppendLine("// " + line);
}
} while (line is not null);
documents.AppendLine();
}
}
if (settings.SnapshotFile is not null)
{
MatchSnapshotAtPath(documents.ToString(), settings.SnapshotFile);
}
else
{
documents.ToString().MatchSnapshot();
}
var diagnostics = CSharpCompiler.GetDiagnosticErrors(documents.ToString());
if (skipWarnings)
{
diagnostics = diagnostics
.Where(x => x.Severity == DiagnosticSeverity.Error)
.ToList();
}
if (diagnostics.Any())
{
Assert.Fail("Diagnostic Errors: \n"
+ diagnostics
.Select(x =>
$"{x.GetMessage()}"
+ $" (Line: {x.Location.GetLineSpan().StartLinePosition.Line})")
.Aggregate((acc, val) => acc + "\n" + val));
}
}
public static void AssertStarWarsResult([StringSyntax("graphql")] params string[] sourceTexts) =>
AssertStarWarsResult(
new AssertSettings { StrictValidation = true },
sourceTexts);
public static void AssertStarWarsResult(
AssertSettings settings,
[StringSyntax("graphql")] params string[] sourceTexts)
{
var source = new string[sourceTexts.Length + 2];
source[0] = FileResource.Open("Schema.graphql");
source[1] = FileResource.Open("Schema.extensions.graphql");
Array.Copy(
sourceTexts,
sourceIndex: 0,
source,
destinationIndex: 2,
length: sourceTexts.Length);
AssertResult(settings, true, source);
}
public static AssertSettings CreateIntegrationTest(
RequestStrategyGen requestStrategy = RequestStrategyGen.Default,
TransportProfile[]? profiles = null,
AccessModifier accessModifier = AccessModifier.Public,
bool noStore = false,
[CallerMemberName] string? testName = null,
[CallerFilePath] string? callerFilePath = null)
{
ArgumentException.ThrowIfNullOrEmpty(testName);
ArgumentException.ThrowIfNullOrEmpty(callerFilePath);
var folder = System.IO.Path.GetDirectoryName(callerFilePath)
?? throw new ArgumentException(
$"Could not determine directory from caller file path '{callerFilePath}'.",
nameof(callerFilePath));
var testFile = System.IO.Path.Combine(folder, testName + "Test.cs");
var ns = "StrawberryShake.CodeGeneration.CSharp.Integration." + testName;
if (!File.Exists(testFile))
{
File.WriteAllText(
testFile,
FileResource.Open("TestTemplate.txt")
.Replace("{TestName}", testName)
.Replace("{Namespace}", ns));
}
return new AssertSettings
{
ClientName = testName + "Client",
Namespace = ns,
AccessModifier = accessModifier,
StrictValidation = true,
SnapshotFile = System.IO.Path.Combine(folder, testName + "Test.Client.cs"),
RequestStrategy = requestStrategy,
NoStore = noStore,
Profiles = (profiles ??
[
TransportProfile.Default
]).ToList()
};
}
private static void MatchSnapshotAtPath(string content, string snapshotFile)
{
content = content.Replace("\r\n", "\n");
if (!File.Exists(snapshotFile))
{
CheckStrictMode();
File.WriteAllText(snapshotFile, content);
return;
}
var existing = File.ReadAllText(snapshotFile).Replace("\r\n", "\n");
if (string.Equals(existing, content, StringComparison.Ordinal))
{
return;
}
var folder = System.IO.Path.GetDirectoryName(snapshotFile)!;
var mismatchDir = System.IO.Path.Combine(folder, "__snapshots__", "__mismatch__");
Directory.CreateDirectory(mismatchDir);
var mismatchFile = System.IO.Path.Combine(mismatchDir, System.IO.Path.GetFileName(snapshotFile));
File.WriteAllText(mismatchFile, content);
Assert.Fail($"Snapshot mismatch. Mismatch file written to {mismatchFile}");
}
private static void CheckStrictMode()
{
var value = Environment.GetEnvironmentVariable("COOKIE_CRUMBLE_STRICT_MODE");
if (string.Equals(value, "on", StringComparison.Ordinal)
|| (bool.TryParse(value, out var b) && b))
{
Assert.Fail(
"Strict mode is enabled and no snapshot has been found "
+ "for the current test. Create a new snapshot locally and "
+ "rerun your tests.");
}
}
private static ClientModel CreateClientModel(
string[] sourceText,
bool strictValidation,
bool noStore)
{
var files = sourceText
.Select(s => new GraphQLFile(Utf8GraphQLParser.Parse(s)))
.ToList();
var typeSystemDocs = files.GetTypeSystemDocuments().ToList();
var executableDocs = files.GetExecutableDocuments().ToList();
var analyzer = new DocumentAnalyzer();
analyzer.SetSchema(SchemaHelper.Load(typeSystemDocs, strictValidation, noStore));
foreach (var executable in executableDocs.Select(file => file.Document))
{
analyzer.AddDocument(executable);
}
return analyzer.Analyze();
}
public class AssertSettings
{
public string? ClientName { get; set; }
public string? Namespace { get; set; }
public AccessModifier AccessModifier { get; set; }
= AccessModifier.Public;
public bool StrictValidation { get; set; }
public string? SnapshotFile { get; set; }
public bool NoStore { get; set; }
public bool InputRecords { get; set; }
public bool EntityRecords { get; set; }
public bool RazorComponents { get; set; }
public List<TransportProfile> Profiles { get; set; } = [];
public RequestStrategyGen RequestStrategy { get; set; } =
RequestStrategyGen.Default;
}
}