-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidation.cs
More file actions
362 lines (328 loc) · 13.9 KB
/
Validation.cs
File metadata and controls
362 lines (328 loc) · 13.9 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
// Copyright (c) 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 System.Runtime.InteropServices;
using DemaConsulting.TestResults.IO;
namespace DemaConsulting.TemplateDotNetTool;
/// <summary>
/// Provides self-validation functionality for the Template DotNet Tool.
/// </summary>
internal static class Validation
{
/// <summary>
/// Runs self-validation tests and optionally writes results to a file.
/// </summary>
/// <param name="context">The context containing command line arguments and program state.</param>
public static void Run(Context context)
{
// Print validation header
PrintValidationHeader(context);
// Create test results collection
var testResults = new DemaConsulting.TestResults.TestResults
{
Name = "Template DotNet Tool Self-Validation"
};
// Run core functionality tests
RunVersionTest(context, testResults);
RunHelpTest(context, testResults);
// Calculate totals
var totalTests = testResults.Results.Count;
var passedTests = testResults.Results.Count(t => t.Outcome == DemaConsulting.TestResults.TestOutcome.Passed);
var failedTests = testResults.Results.Count(t => t.Outcome == DemaConsulting.TestResults.TestOutcome.Failed);
// Print summary
context.WriteLine("");
context.WriteLine($"Total Tests: {totalTests}");
context.WriteLine($"Passed: {passedTests}");
if (failedTests > 0)
{
context.WriteError($"Failed: {failedTests}");
}
else
{
context.WriteLine($"Failed: {failedTests}");
}
// Write results file if requested
if (context.ResultsFile != null)
{
WriteResultsFile(context, testResults);
}
}
/// <summary>
/// Prints the validation header with system information.
/// </summary>
/// <param name="context">The context for output.</param>
private static void PrintValidationHeader(Context context)
{
context.WriteLine("# DEMA Consulting Template DotNet Tool");
context.WriteLine("");
context.WriteLine("| Information | Value |");
context.WriteLine("| :------------------ | :------------------------------------------------- |");
context.WriteLine($"| Tool Version | {Program.Version,-50} |");
context.WriteLine($"| Machine Name | {Environment.MachineName,-50} |");
context.WriteLine($"| OS Version | {RuntimeInformation.OSDescription,-50} |");
context.WriteLine($"| DotNet Runtime | {RuntimeInformation.FrameworkDescription,-50} |");
context.WriteLine($"| Time Stamp | {DateTime.UtcNow:yyyy-MM-dd HH:mm:ss} UTC{"",-29} |");
context.WriteLine("");
}
/// <summary>
/// Runs a test for version display functionality.
/// </summary>
/// <param name="context">The context for output.</param>
/// <param name="testResults">The test results collection.</param>
private static void RunVersionTest(Context context, DemaConsulting.TestResults.TestResults testResults)
{
var startTime = DateTime.UtcNow;
var test = CreateTestResult("TemplateTool_VersionDisplay");
try
{
using var tempDir = new TemporaryDirectory();
var logFile = PathHelpers.SafePathCombine(tempDir.DirectoryPath, "version-test.log");
// Build command line arguments
var args = new List<string>
{
"--silent",
"--log", logFile,
"--version"
};
// Run the program
int exitCode;
using (var testContext = Context.Create([.. args]))
{
Program.Run(testContext);
exitCode = testContext.ExitCode;
}
// Check if execution succeeded
if (exitCode == 0)
{
// Read log content
var logContent = File.ReadAllText(logFile);
// Verify version string is in log (version contains dots like 0.0.0)
if (!string.IsNullOrWhiteSpace(logContent) &&
logContent.Split('.').Length >= 3)
{
test.Outcome = DemaConsulting.TestResults.TestOutcome.Passed;
context.WriteLine($"✓ Version Display Test - PASSED");
}
else
{
test.Outcome = DemaConsulting.TestResults.TestOutcome.Failed;
test.ErrorMessage = "Version string not found in log";
context.WriteError($"✗ Version Display Test - FAILED: Version string not found in log");
}
}
else
{
test.Outcome = DemaConsulting.TestResults.TestOutcome.Failed;
test.ErrorMessage = $"Program exited with code {exitCode}";
context.WriteError($"✗ Version Display Test - FAILED: Exit code {exitCode}");
}
}
// Catch all exceptions as this is a test framework - any exception should be recorded as a test failure.
// This is intentional to ensure robust test execution and reporting regardless of exception type.
catch (Exception ex)
{
HandleTestException(test, context, "Version Display Test", ex);
}
FinalizeTestResult(test, startTime, testResults);
}
/// <summary>
/// Runs a test for help display functionality.
/// </summary>
/// <param name="context">The context for output.</param>
/// <param name="testResults">The test results collection.</param>
private static void RunHelpTest(Context context, DemaConsulting.TestResults.TestResults testResults)
{
var startTime = DateTime.UtcNow;
var test = CreateTestResult("TemplateTool_HelpDisplay");
try
{
using var tempDir = new TemporaryDirectory();
var logFile = PathHelpers.SafePathCombine(tempDir.DirectoryPath, "help-test.log");
// Build command line arguments
var args = new List<string>
{
"--silent",
"--log", logFile,
"--help"
};
// Run the program
int exitCode;
using (var testContext = Context.Create([.. args]))
{
Program.Run(testContext);
exitCode = testContext.ExitCode;
}
// Check if execution succeeded
if (exitCode == 0)
{
// Read log content
var logContent = File.ReadAllText(logFile);
// Verify help text is in log
if (logContent.Contains("Usage:") && logContent.Contains("Options:"))
{
test.Outcome = DemaConsulting.TestResults.TestOutcome.Passed;
context.WriteLine($"✓ Help Display Test - PASSED");
}
else
{
test.Outcome = DemaConsulting.TestResults.TestOutcome.Failed;
test.ErrorMessage = "Help text not found in log";
context.WriteError($"✗ Help Display Test - FAILED: Help text not found in log");
}
}
else
{
test.Outcome = DemaConsulting.TestResults.TestOutcome.Failed;
test.ErrorMessage = $"Program exited with code {exitCode}";
context.WriteError($"✗ Help Display Test - FAILED: Exit code {exitCode}");
}
}
// Catch all exceptions as this is a test framework - any exception should be recorded as a test failure.
// This is intentional to ensure robust test execution and reporting regardless of exception type.
catch (Exception ex)
{
HandleTestException(test, context, "Help Display Test", ex);
}
FinalizeTestResult(test, startTime, testResults);
}
/// <summary>
/// Writes test results to a file in TRX or JUnit format.
/// </summary>
/// <param name="context">The context for output.</param>
/// <param name="testResults">The test results to write.</param>
private static void WriteResultsFile(Context context, DemaConsulting.TestResults.TestResults testResults)
{
if (context.ResultsFile == null)
{
return;
}
try
{
var extension = Path.GetExtension(context.ResultsFile).ToLowerInvariant();
string content;
if (extension == ".trx")
{
content = TrxSerializer.Serialize(testResults);
}
else if (extension == ".xml")
{
// Assume JUnit format for .xml extension
content = JUnitSerializer.Serialize(testResults);
}
else
{
context.WriteError($"Error: Unsupported results file format '{extension}'. Use .trx or .xml extension.");
return;
}
File.WriteAllText(context.ResultsFile, content);
context.WriteLine($"Results written to {context.ResultsFile}");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
context.WriteError($"Error: Failed to write results file: {ex.Message}");
}
}
/// <summary>
/// Creates a new test result object with common properties.
/// </summary>
/// <param name="testName">The name of the test.</param>
/// <returns>A new test result object.</returns>
private static DemaConsulting.TestResults.TestResult CreateTestResult(string testName)
{
return new DemaConsulting.TestResults.TestResult
{
Name = testName,
ClassName = "Validation",
CodeBase = "TemplateDotNetTool"
};
}
/// <summary>
/// Finalizes a test result by setting its duration and adding it to the collection.
/// </summary>
/// <param name="test">The test result to finalize.</param>
/// <param name="startTime">The start time of the test.</param>
/// <param name="testResults">The test results collection to add to.</param>
private static void FinalizeTestResult(
DemaConsulting.TestResults.TestResult test,
DateTime startTime,
DemaConsulting.TestResults.TestResults testResults)
{
test.Duration = DateTime.UtcNow - startTime;
testResults.Results.Add(test);
}
/// <summary>
/// Handles test exceptions by setting failure information and logging the error.
/// </summary>
/// <param name="test">The test result to update.</param>
/// <param name="context">The context for output.</param>
/// <param name="testName">The name of the test for error messages.</param>
/// <param name="ex">The exception that occurred.</param>
private static void HandleTestException(
DemaConsulting.TestResults.TestResult test,
Context context,
string testName,
Exception ex)
{
test.Outcome = DemaConsulting.TestResults.TestOutcome.Failed;
test.ErrorMessage = $"Exception: {ex.Message}";
context.WriteError($"✗ {testName} - FAILED: {ex.Message}");
}
/// <summary>
/// Represents a temporary directory that is automatically deleted when disposed.
/// </summary>
private sealed class TemporaryDirectory : IDisposable
{
/// <summary>
/// Gets the path to the temporary directory.
/// </summary>
public string DirectoryPath { get; }
/// <summary>
/// Initializes a new instance of the <see cref="TemporaryDirectory"/> class.
/// </summary>
public TemporaryDirectory()
{
DirectoryPath = PathHelpers.SafePathCombine(Path.GetTempPath(), $"templatetool_validation_{Guid.NewGuid()}");
try
{
Directory.CreateDirectory(DirectoryPath);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException)
{
throw new InvalidOperationException($"Failed to create temporary directory: {ex.Message}", ex);
}
}
/// <summary>
/// Deletes the temporary directory and all its contents.
/// </summary>
public void Dispose()
{
try
{
if (Directory.Exists(DirectoryPath))
{
Directory.Delete(DirectoryPath, true);
}
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Ignore cleanup errors during disposal
}
}
}
}