-
Notifications
You must be signed in to change notification settings - Fork 308
Add public injectable IArtifactNamingService to Microsoft.Testing.Platform #9783
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
55 changes: 55 additions & 0 deletions
55
src/Platform/Microsoft.Testing.Platform/Services/ArtifactFileNameSanitizer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
|
||
| using Microsoft.Testing.Platform.Helpers; | ||
|
|
||
| namespace Microsoft.Testing.Platform.Services; | ||
|
|
||
| // Mirrors the extension-side Microsoft.Testing.Extensions.ReportFileNameSanitizer (linked source in | ||
| // src/Platform/SharedExtensionHelpers/ReportFileNameSanitizer.cs). The extension copy has SHIPPED | ||
| // InternalAPI entries in five extensions, so it cannot be moved without churn/risk. This core-internal | ||
| // copy exists pending future consolidation of the two. | ||
| internal static partial class ArtifactFileNameSanitizer | ||
| { | ||
| private const char ReplacementChar = '_'; | ||
| private static readonly Regex ReservedFileNamesRegex = BuildReservedFileNameRegex(); | ||
|
|
||
| internal static string ReplaceInvalidFileNameChars(string fileName) | ||
| { | ||
| char[] result = new char[fileName.Length]; | ||
|
|
||
| for (int i = 0; i < fileName.Length; ++i) | ||
| { | ||
| result[i] = IsInvalidFileNameChar(fileName[i]) ? ReplacementChar : fileName[i]; | ||
| } | ||
|
|
||
| string replaced = new string(result).TrimEnd(); | ||
| ArgumentGuard.Ensure(replaced.Length > 0, nameof(fileName), $"File name {fileName} is empty after sanitizing invalid characters."); | ||
|
|
||
| if (IsReservedFileName(replaced)) | ||
| { | ||
| replaced = ReplacementChar + replaced; // Cannot add to the end because it can have extensions. | ||
| } | ||
|
Evangelink marked this conversation as resolved.
|
||
|
|
||
| return replaced; | ||
| } | ||
|
|
||
| private static bool IsInvalidFileNameChar(char c) | ||
| => c is < ' ' or '"' or '<' or '>' or '|' or ':' or '*' or '?' or '\\' or '/' or '@' or '(' or ')' or '^' or ' '; | ||
|
|
||
| private static bool IsReservedFileName(string fileName) => | ||
| // CreateFile: | ||
| // The following reserved device names cannot be used as the name of a file: | ||
| // CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, | ||
| // LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9. | ||
| // Also avoid these names followed by an extension, for example, NUL.tx7. | ||
| // Windows NT: CLOCK$ is also a reserved device name. | ||
| ReservedFileNamesRegex.IsMatch(fileName); | ||
|
|
||
| #if NET7_0_OR_GREATER | ||
| [GeneratedRegex(@"(?i:^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9]|CLOCK\$)(\..*)?)$", RegexOptions.None, "en-150")] | ||
| private static partial Regex BuildReservedFileNameRegex(); | ||
| #else | ||
| private static Regex BuildReservedFileNameRegex() => new(@"(?i:^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9]|CLOCK\$)(\..*)?)$"); | ||
| #endif | ||
| } | ||
39 changes: 39 additions & 0 deletions
39
src/Platform/Microsoft.Testing.Platform/Services/ArtifactNamingService.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,39 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
|
||
| using Microsoft.Testing.Platform.Helpers; | ||
|
|
||
| namespace Microsoft.Testing.Platform.Services; | ||
|
|
||
| internal sealed class ArtifactNamingService : IArtifactNamingService | ||
| { | ||
| private readonly ITestApplicationModuleInfo _testApplicationModuleInfo; | ||
| private readonly IEnvironment _environment; | ||
| private readonly IClock _clock; | ||
|
|
||
| public ArtifactNamingService(ITestApplicationModuleInfo testApplicationModuleInfo, IEnvironment environment, IClock clock) | ||
| { | ||
| _testApplicationModuleInfo = testApplicationModuleInfo; | ||
| _environment = environment; | ||
| _clock = clock; | ||
| } | ||
|
|
||
| public string ResolveFileName(string template) | ||
| { | ||
| string processName = Path.GetFileNameWithoutExtension(_testApplicationModuleInfo.GetCurrentTestApplicationFullPath()); | ||
| string processId = _environment.ProcessId.ToString(CultureInfo.InvariantCulture); | ||
| Dictionary<string, string> replacements = ArtifactNamingHelper.GetStandardReplacements(processName, processId, _clock.UtcNow); | ||
| string resolved = ArtifactNamingHelper.ResolveTemplate(template, replacements); | ||
|
|
||
| string directoryPart = Path.GetDirectoryName(resolved) ?? string.Empty; | ||
|
Evangelink marked this conversation as resolved.
|
||
| string leafName = Path.GetFileName(resolved); | ||
| if (leafName.Length == 0) | ||
| { | ||
| throw new ArgumentException("The resolved template must produce a file name, not just a directory path.", nameof(template)); | ||
| } | ||
|
Evangelink marked this conversation as resolved.
|
||
|
|
||
| string sanitized = ArtifactFileNameSanitizer.ReplaceInvalidFileNameChars(leafName); | ||
|
|
||
| return directoryPart.Length == 0 ? sanitized : Path.Combine(directoryPart, sanitized); | ||
| } | ||
| } | ||
34 changes: 34 additions & 0 deletions
34
src/Platform/Microsoft.Testing.Platform/Services/IArtifactNamingService.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
|
||
| namespace Microsoft.Testing.Platform.Services; | ||
|
|
||
| /// <summary> | ||
| /// Provides file-name templating for artifacts produced by the test platform and its extensions. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// The service expands the standard placeholders and sanitizes the resulting leaf file name so it is | ||
| /// valid on the current operating system. It is registered as a common service and can be resolved | ||
| /// through <see cref="ServiceProviderExtensions.GetArtifactNamingService(System.IServiceProvider)"/>. | ||
| /// </remarks> | ||
| public interface IArtifactNamingService | ||
| { | ||
| /// <summary> | ||
| /// Resolves a file-name template into a concrete file name. | ||
| /// </summary> | ||
| /// <param name="template"> | ||
| /// The template to resolve. The following placeholders are expanded: | ||
| /// <list type="bullet"> | ||
| /// <item><description><c>{pname}</c> — the current test application process name.</description></item> | ||
| /// <item><description><c>{pid}</c> — the current process id.</description></item> | ||
|
Evangelink marked this conversation as resolved.
|
||
| /// <item><description><c>{asm}</c> — the entry assembly name (or <c>unknown</c> if not available).</description></item> | ||
| /// <item><description><c>{tfm}</c> — the short target framework moniker including platform (or <c>unknown</c> if not available).</description></item> | ||
| /// <item><description><c>{arch}</c> — the process architecture.</description></item> | ||
| /// <item><description><c>{time}</c> — the current UTC timestamp.</description></item> | ||
| /// </list> | ||
| /// Unknown placeholders are preserved as-is. Any directory portion of the template is preserved | ||
| /// while only the leaf file name is sanitized. | ||
| /// </param> | ||
| /// <returns>The resolved file name, with the leaf sanitized to be valid for the current file system.</returns> | ||
| string ResolveFileName(string template); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
96 changes: 96 additions & 0 deletions
96
test/UnitTests/Microsoft.Testing.Platform.UnitTests/Services/ArtifactNamingServiceTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| // Copyright (c) Microsoft Corporation. All rights reserved. | ||
| // Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
|
||
| using Microsoft.Testing.Platform.Helpers; | ||
| using Microsoft.Testing.Platform.Services; | ||
|
|
||
| using Moq; | ||
|
|
||
| namespace Microsoft.Testing.Platform.UnitTests.Services; | ||
|
|
||
| [TestClass] | ||
| public sealed class ArtifactNamingServiceTests | ||
| { | ||
| private readonly Mock<ITestApplicationModuleInfo> _moduleInfoMock = new(); | ||
| private readonly Mock<IEnvironment> _environmentMock = new(); | ||
| private readonly Mock<IClock> _clockMock = new(); | ||
|
|
||
| private ArtifactNamingService CreateService(string modulePath = "MyApp.dll", int processId = 4242) | ||
| { | ||
| _ = _moduleInfoMock.Setup(x => x.GetCurrentTestApplicationFullPath()).Returns(modulePath); | ||
| _ = _environmentMock.SetupGet(x => x.ProcessId).Returns(processId); | ||
| _ = _clockMock.SetupGet(x => x.UtcNow).Returns(new DateTimeOffset(2026, 1, 2, 3, 4, 5, TimeSpan.Zero)); | ||
| return new ArtifactNamingService(_moduleInfoMock.Object, _environmentMock.Object, _clockMock.Object); | ||
| } | ||
|
|
||
| [TestMethod] | ||
| public void ResolveFileName_ExpandsStandardPlaceholders() | ||
| { | ||
| ArtifactNamingService service = CreateService(modulePath: Path.Combine("dir", "MyApp.dll"), processId: 4242); | ||
|
|
||
| string result = service.ResolveFileName("{pname}_{pid}_{time}.json"); | ||
|
|
||
| Assert.StartsWith("MyApp_4242_", result); | ||
| Assert.Contains("2026-01-02_03-04-05", result); | ||
| Assert.EndsWith(".json", result); | ||
| Assert.DoesNotContain("{pname}", result); | ||
| Assert.DoesNotContain("{pid}", result); | ||
| Assert.DoesNotContain("{time}", result); | ||
| } | ||
|
|
||
| [TestMethod] | ||
| public void ResolveFileName_SanitizesInvalidCharactersInExpandedName() | ||
| { | ||
| ArtifactNamingService service = CreateService(modulePath: Path.Combine("dir", "My*App.dll")); | ||
|
|
||
| string result = service.ResolveFileName("{pname}.json"); | ||
|
|
||
| Assert.AreEqual("My_App.json", result); | ||
| } | ||
|
|
||
| [TestMethod] | ||
| public void ResolveFileName_PrefixesReservedDeviceName() | ||
| { | ||
| // A {pname} that resolves to a reserved Windows device name (CON/PRN/NUL/COM1/...) | ||
| // must be prefixed with '_' by the sanitizer so it is a valid file name. | ||
| ArtifactNamingService service = CreateService(modulePath: Path.Combine("dir", "CON.dll")); | ||
|
|
||
| string result = service.ResolveFileName("{pname}.json"); | ||
|
|
||
| Assert.AreEqual("_CON.json", result); | ||
| } | ||
|
|
||
| [TestMethod] | ||
| public void ResolveFileName_PreservesDirectoryPortionAndSanitizesLeaf() | ||
| { | ||
| ArtifactNamingService service = CreateService(modulePath: Path.Combine("dir", "My*App.dll")); | ||
|
|
||
| string template = Path.Combine("sub", "dir", "{pname}.json"); | ||
| string result = service.ResolveFileName(template); | ||
|
|
||
| Assert.AreEqual(Path.Combine("sub", "dir", "My_App.json"), result); | ||
| } | ||
|
|
||
| [TestMethod] | ||
| public void ResolveFileName_LeavesUnknownPlaceholderAsIs() | ||
| { | ||
| ArtifactNamingService service = CreateService(); | ||
|
|
||
| string result = service.ResolveFileName("{unknown}_{pname}.json"); | ||
|
|
||
| Assert.Contains("{unknown}", result); | ||
| Assert.Contains("MyApp", result); | ||
| } | ||
|
|
||
| [TestMethod] | ||
| public void ResolveFileName_ThrowsWhenTemplateHasNoLeafFileName() | ||
| { | ||
| // A template that resolves to a directory path only (no leaf file name, e.g. ending in a | ||
| // directory separator) is rejected with a clear ArgumentException at the service boundary. | ||
| ArtifactNamingService service = CreateService(); | ||
|
|
||
| string template = "outdir" + Path.DirectorySeparatorChar; | ||
|
|
||
| Assert.ThrowsExactly<ArgumentException>(() => service.ResolveFileName(template)); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.