-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathMessagesCompatibilityTestBase.cs
More file actions
351 lines (302 loc) · 16.1 KB
/
Copy pathMessagesCompatibilityTestBase.cs
File metadata and controls
351 lines (302 loc) · 16.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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
using FluentAssertions;
using Io.Cucumber.Messages.Types;
using Moq;
using Reqnroll.Analytics.UserId;
using Reqnroll.BoDi;
using Reqnroll.Configuration;
using Reqnroll.Formatters.PayloadProcessing;
using Reqnroll.Formatters.PayloadProcessing.Cucumber;
using Reqnroll.EnvironmentAccess;
using Reqnroll.Formatters.Configuration;
using Reqnroll.SystemTests;
using Reqnroll.Tracing;
using Reqnroll.Utils;
using System.Reflection;
namespace Reqnroll.Formatters.Tests;
public class MessagesCompatibilityTestBase : SystemTestBase
{
private const string DEFAULTSAMPLESDIRECTORYPLACEHOLDER = "[BaseDirectory]";
protected override void TestCleanup()
{
// TEMPORARY: this is in place so that SystemTestBase.TestCleanup does not run (which deletes the generated code)
}
protected void EnableCucumberMessages()
{
_testSuiteInitializationDriver.OverrideCucumberEnable = true;
}
protected void SetCucumberMessagesOutputFileName(string fileName)
{
var baseFileName = Path.GetFileNameWithoutExtension(fileName);
var ndjsonFileName = baseFileName + ".ndjson";
var htmlFileName = baseFileName + ".html";
var path = Path.GetDirectoryName(fileName);
if (string.IsNullOrEmpty(path))
{
path = ActualResultLocationDirectory();
ndjsonFileName = Path.Combine(path, ndjsonFileName);
htmlFileName = Path.Combine(path, htmlFileName);
}
string formatters = "{\"formatters\" : {\"message\" : { \"outputFilePath\" : \"" + ndjsonFileName.Replace("\\", "\\\\") + "\" }," +
" \"html\" : { \"outputFilePath\" : \"" + htmlFileName.Replace("\\", "\\\\") + "\" } } }";
_testSuiteInitializationDriver.OverrideCucumberMessagesFormatters = formatters;
}
protected void DisableCucumberMessages()
{
_testSuiteInitializationDriver.OverrideCucumberEnable = false;
}
protected void ResetCucumberMessages(string? fileToDelete = null)
{
fileToDelete = string.IsNullOrEmpty(fileToDelete) ? fileToDelete : fileToDelete + ".ndjson";
DeletePreviousMessagesOutput(fileToDelete);
ResetCucumberMessagesOutputFileName();
Environment.SetEnvironmentVariable(FormattersConfigurationConstants.REQNROLL_FORMATTERS_DISABLED_ENVIRONMENT_VARIABLE, null);
}
protected void ResetCucumberMessagesHtml(string? fileToDelete = null)
{
fileToDelete = string.IsNullOrEmpty(fileToDelete) ? fileToDelete : fileToDelete + ".html";
DeletePreviousMessagesOutput(fileToDelete);
ResetCucumberMessagesOutputFileName();
Environment.SetEnvironmentVariable(FormattersConfigurationConstants.REQNROLL_FORMATTERS_DISABLED_ENVIRONMENT_VARIABLE, null);
}
protected void ResetCucumberMessagesOutputFileName()
{
Environment.SetEnvironmentVariable(FormattersConfigurationConstants.REQNROLL_FORMATTERS_ENVIRONMENT_VARIABLE, null);
}
protected void MimicGitHubActionsEnvironment()
{
Environment.SetEnvironmentVariable("GITHUB_ACTIONS", "true");
Environment.SetEnvironmentVariable("GITHUB_SERVER_URL", "https://github.com");
Environment.SetEnvironmentVariable("GITHUB_REPOSITORY", "reqnroll/reqnroll");
Environment.SetEnvironmentVariable("GITHUB_RUN_ID", "1234567890");
Environment.SetEnvironmentVariable("GITHUB_RUN_NUMBER", "1");
Environment.SetEnvironmentVariable("GITHUB_REF_TYPE", "branch");
Environment.SetEnvironmentVariable("GITHUB_REF_NAME", "main");
Environment.SetEnvironmentVariable("GITHUB_SHA", "abcdef1234567890abcdef1234567890abcdef12");
}
protected void MimicAzurePipelinesEnvironment()
{
Environment.SetEnvironmentVariable("TF_BUILD", "true");
Environment.SetEnvironmentVariable("BUILD_BUILDURI", "https://dev.azure.com/reqnroll/reqnroll/_build");
Environment.SetEnvironmentVariable("BUILD_BUILDNUMBER", "20231001.1");
Environment.SetEnvironmentVariable("BUILD_REPOSITORY_URI", "https://dev.azure.com/reqnroll/reqnroll/_git/reqnroll");
Environment.SetEnvironmentVariable("BUILD_SOURCEBRANCHNAME", "1b1c2588e46d5c995d54da1082b618fa13553eb3");
Environment.SetEnvironmentVariable("BUILD_SOURCEVERSION", "main");
Environment.SetEnvironmentVariable("Build_SOURCEBRANCH", "refs/tags/v1.0.0");
}
protected void DeletePreviousMessagesOutput(string? fileToDelete = null)
{
var directory = ActualResultLocationDirectory();
if (fileToDelete != null)
{
var fileToDeletePath = Path.Combine(directory, fileToDelete);
if (File.Exists(fileToDeletePath))
{
File.Delete(fileToDeletePath);
}
}
}
protected void AddBindingClassFromResource(string fileName, string? prefix = null, Assembly? assemblyToLoadFrom = null)
{
var bindingCLassFileContent = _testFileManager.GetTestFileContent(fileName, prefix, assemblyToLoadFrom);
AddBindingClass(bindingCLassFileContent);
}
protected void ShouldAllScenariosPend(int? expectedNrOfTestsSpec = null)
{
int expectedNrOfTests = ConfirmAllTestsRan(expectedNrOfTestsSpec);
_vsTestExecutionDriver.LastTestExecutionResult.Pending.Should().Be(expectedNrOfTests, "all tests should pend");
}
protected void AddBinaryFilesFromResource(string scenarioName, string prefix, Assembly assembly)
{
foreach (var fileName in GetTestBinaryFileNames(scenarioName, prefix, assembly))
{
var content = _testFileManager.GetTestFileContent(fileName, $"{prefix}.{scenarioName}", assembly);
_projectsDriver.AddFile(fileName, content);
}
}
protected IEnumerable<string> GetTestBinaryFileNames(string scenarioName, string prefix, Assembly? assembly)
{
var testAssembly = assembly ?? Assembly.GetExecutingAssembly();
string prefixToRemove = $"{prefix}.{scenarioName}.";
return testAssembly.GetManifestResourceNames()
.Where(rn => !rn.EndsWith(".feature") && !rn.EndsWith(".cs") && !rn.EndsWith(".feature.ndjson") && rn.StartsWith(prefixToRemove))
.Select(rn => rn.Substring(prefixToRemove.Length));
}
protected void CucumberMessagesAddConfigurationFile(string configFileName)
{
var configFileContent = File.ReadAllText(configFileName);
var samplesDirectory = GetDefaultSamplesDirectory();
configFileContent = configFileContent.Replace(DEFAULTSAMPLESDIRECTORYPLACEHOLDER, samplesDirectory.Replace(@"\", @"\\"));
AddJsonConfigFileContent(configFileContent);
}
private static string GetDefaultSamplesDirectory() => Path.GetFullPath(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!, "..", "..", "..", "Samples"));
protected static string ActualResultLocationDirectory()
{
var objectContainerMock = new Mock<IObjectContainer>();
var tracerMock = new Mock<ITraceListener>();
objectContainerMock.Setup(x => x.Resolve<ITraceListener>()).Returns(tracerMock.Object);
var env = new EnvironmentWrapper();
var jsonConfigFileLocator = new ReqnrollJsonLocator();
var fileSystem = new FileSystem();
var fileService = new FileService();
var configFileResolver = new FileBasedConfigurationResolver(jsonConfigFileLocator, fileSystem, fileService);
var jsonEnvConfigResolver = new JsonEnvironmentConfigurationResolver(env);
var keyValueEnvironmentConfigurationResolverMock = new Mock<IKeyValueEnvironmentConfigurationResolver>();
keyValueEnvironmentConfigurationResolverMock.Setup(r => r.Resolve()).Returns(new Dictionary<string, IDictionary<string, object>>());
FormattersConfigurationProvider configurationProvider = new FormattersConfigurationProvider(
configFileResolver,
jsonEnvConfigResolver,
keyValueEnvironmentConfigurationResolverMock.Object,
new FormattersDisabledOverrideProvider(env));
configurationProvider.GetFormatterConfigurationByName("message").TryGetValue("outputFilePath", out var outputFilePathElement);
var outputFilePath = outputFilePathElement!.ToString();
if (string.IsNullOrEmpty(outputFilePath))
outputFilePath = "[BASEDIRECTORY]\\CucumberMessages\\reqnroll_report.ndson";
string actualResultLocationDirectory = outputFilePath.Replace(DEFAULTSAMPLESDIRECTORYPLACEHOLDER, GetDefaultSamplesDirectory());
actualResultLocationDirectory = Path.GetDirectoryName(actualResultLocationDirectory)!;
return actualResultLocationDirectory;
}
protected void FileShouldExist(string v)
{
var directory = ActualResultLocationDirectory();
var file = Path.Combine(directory, v);
File.Exists(file).Should().BeTrue(file, $"File {v} should exist");
}
protected void AddUtilClassWithFileSystemPath()
{
string location = Path.Combine(AppContext.BaseDirectory, "Samples", "Resources");
AddBindingClass($$"""
public class FileSystemPath
{
public static string GetFilePathForAttachments() => @"{{location}}";
}
""");
}
protected IEnumerable<Envelope> GetExpectedResults(string testName, string featureFileName)
{
string[] expectedJsonText = GetExpectedJsonText(testName, featureFileName);
foreach (var json in expectedJsonText)
{
var e = NdjsonSerializer.Deserialize(json);
yield return e;
}
}
protected string[] GetExpectedJsonText(string testName, string featureFileName)
{
var fileName = featureFileName + "." + featureFileName + ".ndjson";
var assemblyToLoadFrom = Assembly.GetExecutingAssembly();
var expectedJsonText = _testFileManager.GetTestFileContent(fileName, "Samples", assemblyToLoadFrom).Split(new [] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
//var workingDirectory = Path.Combine(AppContext.BaseDirectory, "..", "..", "..");
//var expectedJsonText = File.ReadAllLines(Path.Combine(workingDirectory, "Samples", "Resources", testName, $"{featureFileName}.feature.ndjson"));
return expectedJsonText;
}
protected static string[] GetActualGeneratedHtml(string testName, string featureFileName)
{
string resultLocation = ActualResultLocationDirectory();
var expectedJsonText = File.ReadAllLines(Path.Combine(resultLocation, $"{featureFileName}.html"));
return expectedJsonText;
}
// ReSharper disable NotAccessedPositionalProperty.Local
record TestExecution(string Id, List<Envelope> Related);
record TestCaseRecord(string Id, string PickleId, Envelope TestCaseEnvelope, Dictionary<string, TestExecution> Executions);
// ReSharper restore NotAccessedPositionalProperty.Local
protected IEnumerable<Envelope> GetActualResults(string testName, string fileName)
{
string[] actualJsonText = GetActualJsonText(testName, fileName);
actualJsonText.Should().HaveCountGreaterThan(0, "the test results ndjson file was empty.");
var envelopes = actualJsonText.Select(NdjsonSerializer.Deserialize).ToList();
// The test cases (aka scenarios) might have been executed in any order
// Comparison with the expected output ndjson assumes that tests are executed in the order the Pickles are listed.
// So for the purposes of comparison, we're going to sort testCase messages (and related test execution messages) in pickle appearance order.
var result = new List<Envelope>();
// List of Pickle IDs in the order they are seen in the message stream
var pickles = envelopes.Where(e => e.Content() is Pickle).Select(e => e.Pickle.Id).ToList();
// Dictionary keyed by the ID of each test case.
var testCases = new Dictionary<string, TestCaseRecord>();
var allTestCaseEnvelopes = envelopes.Where(e => e.Content() is TestCase).ToList();
var testCaseStartedToTestCaseMap = new Dictionary<string, string>();
foreach (var tce in allTestCaseEnvelopes)
{
var tc = tce.Content() as TestCase;
testCases.Add(tc!.Id, new TestCaseRecord(tc.Id, tc.PickleId, tce, new Dictionary<string, TestExecution>()));
}
int index = 0;
bool testCasesBegun = false;
// this loop sweeps all of the messages prior to the first testCase into the outgoing results collection.
while (index < envelopes.Count && !testCasesBegun)
{
var current = envelopes[index];
if (current.Content() is TestCase)
{
testCasesBegun = true;
}
else
{
result.Add(current);
index++;
}
}
bool testCasesFinished = false;
while (index < envelopes.Count && !testCasesFinished)
{
var current = envelopes[index];
if (current.Content() is TestRunFinished)
{
testCasesFinished = true;
result.Add(current);
index++;
continue;
}
if (current.Content() is TestCase)
{
// as TestCases were already identified and inserted into the testCases dictionary, no direct work required here; skip to the next Message
index++;
continue;
}
// handle test case started and related
if (current.Content() is TestCaseStarted testCaseStarted)
{
var tcsId = testCaseStarted.Id;
var testCaseExecution = new TestExecution(tcsId, new List<Envelope>() { current });
testCases[testCaseStarted.TestCaseId].Executions.Add(tcsId, testCaseExecution);
testCaseStartedToTestCaseMap.Add(tcsId, testCaseStarted.TestCaseId);
index++;
continue;
}
var testCaseStartedId = current.Content() switch
{
TestStepStarted started => started.TestCaseStartedId,
TestStepFinished finished => finished.TestCaseStartedId,
TestCaseFinished tcFin => tcFin.TestCaseStartedId,
Attachment att => att.TestCaseStartedId,
TestRunHookStarted => null,
TestRunHookFinished => null,
_ => throw new ApplicationException("Unexpected Envelope type")
};
// attachments created by Before/After TestRun or Feature don't have a value for TestCaseStartedId, so don't attempt to add them to Test execution
if (!string.IsNullOrEmpty(testCaseStartedId))
{
var testCaseId = testCaseStartedToTestCaseMap[testCaseStartedId];
testCases[testCaseId].Executions[testCaseStartedId].Related.Add(current);
}
else
result.Add(current);
index++;
}
// Now, sort the TestCaseRecords in order of their respective PickleId sequence
var sortedTestCaseRecords = testCases.Values.OrderBy(tcr => pickles.IndexOf(tcr.PickleId)).ToList();
var testCaseAndRelatedEnvelopes = sortedTestCaseRecords.SelectMany(tc => new List<Envelope>() { tc.TestCaseEnvelope }.Concat(tc.Executions.Values.SelectMany(e => e.Related)));
var testRunFinished = result.Last();
result.Remove(testRunFinished);
result.AddRange(testCaseAndRelatedEnvelopes);
result.Add(testRunFinished);
return result;
}
protected static string[] GetActualJsonText(string testName, string fileName)
{
string resultLocation = ActualResultLocationDirectory();
fileName = Path.Combine(resultLocation, fileName + ".ndjson");
// Hack: the file name is hard-coded in the test row data to match the name of the feature within the Feature file for the example scenario
var actualJsonText = File.ReadAllLines(fileName);
return actualJsonText;
}
}