-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTraceMatrix.cs
More file actions
556 lines (487 loc) · 20.2 KB
/
TraceMatrix.cs
File metadata and controls
556 lines (487 loc) · 20.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
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
// Copyright (c) 2026 DEMA Consulting
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
using DemaConsulting.TestResults.IO;
namespace DemaConsulting.ReqStream;
/// <summary>
/// Represents a traceability matrix that maps test results to requirements.
/// Supports TRX and JUnit test result formats.
/// </summary>
public class TraceMatrix
{
/// <summary>
/// Dictionary mapping test names to their execution results.
/// </summary>
private readonly Dictionary<string, TestResultEntry> _testResults = [];
/// <summary>
/// The requirements object used to build this trace matrix.
/// </summary>
private readonly Requirements _requirements;
/// <summary>
/// Initializes a new instance of the TraceMatrix class.
/// </summary>
/// <param name="requirements">The requirements containing test mappings.</param>
/// <param name="testResultFiles">Paths to test result files (TRX or JUnit format).</param>
/// <exception cref="ArgumentNullException">Thrown when requirements is null.</exception>
/// <exception cref="FileNotFoundException">Thrown when a test result file does not exist.</exception>
public TraceMatrix(Requirements requirements, params string[] testResultFiles)
{
ArgumentNullException.ThrowIfNull(requirements);
_requirements = requirements;
// Collect all test names from requirements
var requiredTests = CollectTestNames(requirements);
// Process each test result file
foreach (var filePath in testResultFiles)
{
ProcessTestResultFile(filePath, requiredTests);
}
}
/// <summary>
/// Gets the test result entry for a specific test name.
/// </summary>
/// <param name="testName">The name of the test.</param>
/// <returns>The TestResultEntry for the test, or null if the test was not found.</returns>
public TestResultEntry? GetTestResult(string testName)
{
return _testResults.TryGetValue(testName, out var result) ? result : null;
}
/// <summary>
/// Gets all test result entries.
/// </summary>
/// <returns>A read-only dictionary of test names to their result entries.</returns>
public IReadOnlyDictionary<string, TestResultEntry> GetAllTestResults()
{
return _testResults;
}
/// <summary>
/// Exports the trace matrix to a Markdown file.
/// </summary>
/// <param name="filePath">The path to the output Markdown file.</param>
/// <param name="depth">The starting depth for Markdown headers (default: 1).</param>
/// <exception cref="ArgumentException">Thrown when filePath is null or empty.</exception>
public void Export(string filePath, int depth = 1)
{
// Validate file path
if (string.IsNullOrWhiteSpace(filePath))
{
throw new ArgumentException("File path cannot be null or empty", nameof(filePath));
}
// Create a string builder to build the markdown content
using var writer = new StringWriter();
// Export Summary section
ExportSummary(writer, depth);
// Export Requirements section
ExportRequirements(writer, depth);
// Export Testing section
ExportTesting(writer, depth);
// Write the content to the file
File.WriteAllText(filePath, writer.ToString());
}
/// <summary>
/// Exports the summary section showing satisfied requirements count.
/// </summary>
/// <param name="writer">The text writer to write to.</param>
/// <param name="depth">The current depth for Markdown headers.</param>
private void ExportSummary(TextWriter writer, int depth)
{
var headerPrefix = new string('#', depth);
writer.WriteLine($"{headerPrefix} Summary");
writer.WriteLine();
// Calculate satisfied requirements
var (satisfied, total) = CalculateSatisfiedRequirements(_requirements);
writer.WriteLine($"{satisfied} of {total} requirements are satisfied with tests.");
writer.WriteLine();
}
/// <summary>
/// Calculates how many requirements are satisfied.
/// A requirement is satisfied if it has at least one test and all tests have passed.
/// </summary>
/// <param name="section">The section to analyze.</param>
/// <returns>A tuple of (satisfied count, total count).</returns>
private (int satisfied, int total) CalculateSatisfiedRequirements(Section section)
{
var satisfied = 0;
var total = 0;
// Check requirements in this section
foreach (var requirement in section.Requirements)
{
total++;
if (IsRequirementSatisfied(requirement, _requirements))
{
satisfied++;
}
}
// Recursively check child sections
foreach (var childSection in section.Sections)
{
var (childSatisfied, childTotal) = CalculateSatisfiedRequirements(childSection);
satisfied += childSatisfied;
total += childTotal;
}
return (satisfied, total);
}
/// <summary>
/// Determines if a requirement is satisfied.
/// A requirement is satisfied if analyzing its tests and all child-requirement tests
/// recursively shows at least one test, and all tests have passed.
/// </summary>
/// <param name="requirement">The requirement to check.</param>
/// <param name="rootSection">The root section for looking up child requirements.</param>
/// <returns>True if the requirement is satisfied, false otherwise.</returns>
private bool IsRequirementSatisfied(Requirement requirement, Section rootSection)
{
var allTests = new HashSet<string>();
CollectAllTests(requirement, rootSection, allTests);
// Must have at least one test
if (allTests.Count == 0)
{
return false;
}
// All tests must have been executed and passed
foreach (var testName in allTests)
{
var result = GetTestResult(testName);
if (result == null || result.Executed == 0 || result.Passed != result.Executed)
{
return false;
}
}
return true;
}
/// <summary>
/// Collects all tests from a requirement and its children recursively.
/// </summary>
/// <param name="requirement">The requirement to collect tests from.</param>
/// <param name="rootSection">The root section for looking up child requirements.</param>
/// <param name="allTests">The set to add tests to.</param>
private static void CollectAllTests(Requirement requirement, Section rootSection, HashSet<string> allTests)
{
// Add direct tests
foreach (var test in requirement.Tests)
{
allTests.Add(test);
}
// Recursively add tests from children
foreach (var childId in requirement.Children)
{
var childReq = FindRequirement(rootSection, childId);
if (childReq != null)
{
CollectAllTests(childReq, rootSection, allTests);
}
}
}
/// <summary>
/// Finds a requirement by ID in the section tree.
/// </summary>
/// <param name="section">The section to search.</param>
/// <param name="requirementId">The requirement ID to find.</param>
/// <returns>The requirement if found, null otherwise.</returns>
private static Requirement? FindRequirement(Section section, string requirementId)
{
// Search in current section
foreach (var req in section.Requirements)
{
if (req.Id == requirementId)
{
return req;
}
}
// Search in child sections
foreach (var childSection in section.Sections)
{
var found = FindRequirement(childSection, requirementId);
if (found != null)
{
return found;
}
}
return null;
}
/// <summary>
/// Exports the requirements section with test statistics.
/// </summary>
/// <param name="writer">The text writer to write to.</param>
/// <param name="depth">The current depth for Markdown headers.</param>
private void ExportRequirements(TextWriter writer, int depth)
{
var headerPrefix = new string('#', depth);
writer.WriteLine($"{headerPrefix} Requirements");
writer.WriteLine();
// Export all sections
foreach (var section in _requirements.Sections)
{
ExportRequirementSection(writer, section, depth + 1);
}
}
/// <summary>
/// Exports a requirements section with test statistics.
/// </summary>
/// <param name="writer">The text writer to write to.</param>
/// <param name="section">The section to export.</param>
/// <param name="depth">The current depth for Markdown headers.</param>
private void ExportRequirementSection(TextWriter writer, Section section, int depth)
{
// Write section header
var headerPrefix = new string('#', depth);
writer.WriteLine($"{headerPrefix} {section.Title}");
writer.WriteLine();
// If there are requirements, write them as a table
if (section.Requirements.Count > 0)
{
// Write table header
writer.WriteLine("| ID | Tests Linked | Passed | Failed | Not Executed |");
writer.WriteLine("|----|--------------|--------|--------|--------------|");
// Write each requirement
foreach (var requirement in section.Requirements)
{
var (testsLinked, passed, failed, notExecuted) = GetRequirementTestStats(requirement);
writer.WriteLine($"| {requirement.Id} | {testsLinked} | {passed} | {failed} | {notExecuted} |");
}
writer.WriteLine();
}
// Recursively export child sections
foreach (var childSection in section.Sections)
{
ExportRequirementSection(writer, childSection, depth + 1);
}
}
/// <summary>
/// Gets test statistics for a requirement.
/// </summary>
/// <param name="requirement">The requirement to analyze.</param>
/// <returns>A tuple of (tests linked, passed, failed, not executed).</returns>
private (int testsLinked, int passed, int failed, int notExecuted) GetRequirementTestStats(Requirement requirement)
{
var testsLinked = requirement.Tests.Count;
var passed = 0;
var failed = 0;
var notExecuted = 0;
foreach (var testName in requirement.Tests)
{
var result = GetTestResult(testName);
if (result == null || result.Executed == 0)
{
notExecuted++;
}
else
{
var failedCount = result.Executed - result.Passed;
if (failedCount > 0)
{
failed++;
}
else
{
passed++;
}
}
}
return (testsLinked, passed, failed, notExecuted);
}
/// <summary>
/// Exports the testing section showing test-to-requirement mappings.
/// </summary>
/// <param name="writer">The text writer to write to.</param>
/// <param name="depth">The current depth for Markdown headers.</param>
private void ExportTesting(TextWriter writer, int depth)
{
var headerPrefix = new string('#', depth);
writer.WriteLine($"{headerPrefix} Testing");
writer.WriteLine();
// Build a mapping of test names to requirements
var testToRequirements = new Dictionary<string, List<string>>();
BuildTestToRequirementsMap(_requirements, testToRequirements);
// Write table header
writer.WriteLine("| Test | Requirement | Passed | Failed |");
writer.WriteLine("|------|-------------|--------|--------|");
// Write each test-to-requirement mapping
foreach (var (testName, requirementIds) in testToRequirements.OrderBy(kvp => kvp.Key))
{
var result = GetTestResult(testName);
var passed = result?.Passed ?? 0;
var failed = result != null ? result.Executed - result.Passed : 0;
foreach (var reqId in requirementIds.OrderBy(id => id))
{
writer.WriteLine($"| {testName} | {reqId} | {passed} | {failed} |");
}
}
writer.WriteLine();
}
/// <summary>
/// Builds a mapping from test names to requirement IDs.
/// </summary>
/// <param name="section">The section to scan.</param>
/// <param name="testToRequirements">The dictionary to populate.</param>
private static void BuildTestToRequirementsMap(Section section, Dictionary<string, List<string>> testToRequirements)
{
// Process requirements in this section
foreach (var requirement in section.Requirements)
{
foreach (var testName in requirement.Tests)
{
if (!testToRequirements.TryGetValue(testName, out var requirementIds))
{
requirementIds = [];
testToRequirements[testName] = requirementIds;
}
requirementIds.Add(requirement.Id);
}
}
// Recursively process child sections
foreach (var childSection in section.Sections)
{
BuildTestToRequirementsMap(childSection, testToRequirements);
}
}
/// <summary>
/// Collects all test names from the requirements tree.
/// </summary>
/// <param name="section">The section to search for tests.</param>
/// <returns>A hash set containing all unique test names.</returns>
private static HashSet<string> CollectTestNames(Section section)
{
var testNames = new HashSet<string>();
// Collect tests from requirements in this section
foreach (var requirement in section.Requirements)
{
foreach (var test in requirement.Tests)
{
testNames.Add(test);
}
}
// Recursively collect tests from child sections
foreach (var childSection in section.Sections)
{
var childTests = CollectTestNames(childSection);
testNames.UnionWith(childTests);
}
return testNames;
}
/// <summary>
/// Processes a test result file and updates test execution counts.
/// </summary>
/// <param name="filePath">Path to the test result file.</param>
/// <param name="requiredTests">Set of test names that are referenced in requirements.</param>
/// <exception cref="FileNotFoundException">Thrown when the file does not exist.</exception>
private void ProcessTestResultFile(string filePath, HashSet<string> requiredTests)
{
// Verify file exists
if (!File.Exists(filePath))
{
throw new FileNotFoundException($"Test result file not found: {filePath}", filePath);
}
// Extract the base filename (without extension) for source matching
var fileBaseName = Path.GetFileNameWithoutExtension(filePath);
// Read the file content
var content = File.ReadAllText(filePath);
// Try to parse as TRX first, then JUnit
DemaConsulting.TestResults.TestResults testResults;
try
{
testResults = TrxSerializer.Deserialize(content);
}
catch
{
// If TRX parsing fails, try JUnit
try
{
testResults = JUnitSerializer.Deserialize(content);
}
catch (Exception ex)
{
throw new InvalidOperationException($"Failed to parse test result file as TRX or JUnit format: {filePath}", ex);
}
}
// Process each test result
foreach (var result in testResults.Results)
{
// Check if any required test matches this result
var matchingTestName = FindMatchingTestName(requiredTests, result.Name, fileBaseName);
if (matchingTestName == null)
{
continue;
}
// Get or create the test result entry using the full test name from requirements
if (!_testResults.TryGetValue(matchingTestName, out var entry))
{
entry = new TestResultEntry();
_testResults[matchingTestName] = entry;
}
// Update execution counts
entry.Executed++;
if (result.Outcome == DemaConsulting.TestResults.TestOutcome.Passed)
{
entry.Passed++;
}
}
}
/// <summary>
/// Finds a matching test name from the required tests set.
/// Supports both plain test names and source-specific test names with the pattern: [filepart@]testname.
/// </summary>
/// <param name="requiredTests">Set of test names from requirements.</param>
/// <param name="actualTestName">The actual test name from the test result file.</param>
/// <param name="fileBaseName">The base name of the test result file (without extension).</param>
/// <returns>The matching test name from requirements, or null if no match found.</returns>
private static string? FindMatchingTestName(HashSet<string> requiredTests, string actualTestName, string fileBaseName)
{
// First, try to find an exact match with source specifier: <filepart>@<testname>
// Check if any filepart from the base name matches
foreach (var requiredTest in requiredTests)
{
var (filePart, testName) = ParseTestName(requiredTest);
// If there's a file part, check if it matches and the test name matches
if (filePart != null &&
fileBaseName.Contains(filePart, StringComparison.OrdinalIgnoreCase) &&
testName == actualTestName)
{
return requiredTest;
}
}
// Second, try to find a plain test name match (no source specifier)
foreach (var requiredTest in requiredTests)
{
var (filePart, testName) = ParseTestName(requiredTest);
// If there's no file part and the test name matches
if (filePart == null && testName == actualTestName)
{
return requiredTest;
}
}
return null;
}
/// <summary>
/// Parses a test name to extract the optional file part and the actual test name.
/// Format: [filepart@]testname
/// </summary>
/// <param name="testName">The test name from requirements.</param>
/// <returns>A tuple of (filePart, testName). filePart is null if not specified.</returns>
private static (string? filePart, string testName) ParseTestName(string testName)
{
var atIndex = testName.IndexOf('@');
if (atIndex > 0 && atIndex < testName.Length - 1)
{
var filePart = testName[..atIndex];
var actualTestName = testName[(atIndex + 1)..];
return (filePart, actualTestName);
}
return (null, testName);
}
}