-
Notifications
You must be signed in to change notification settings - Fork 62
[New VirtualClientComponent] Create Response File Component #641
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
+221
−0
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
116 changes: 116 additions & 0 deletions
116
src/VirtualClient/VirtualClient.Dependencies.UnitTests/CreateResponseFileTests.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,116 @@ | ||
| // Copyright (c) Microsoft Corporation. | ||
| // Licensed under the MIT License. | ||
|
|
||
| namespace VirtualClient.Dependencies.UnitTests | ||
| { | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.IO; | ||
| using System.IO.Abstractions; | ||
| using System.Linq; | ||
| using System.Text; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.VisualStudio.TestPlatform.ObjectModel; | ||
| using Moq; | ||
| using NUnit.Framework; | ||
| using VirtualClient; | ||
| using VirtualClient.Common.Extensions; | ||
| using VirtualClient.Common.Telemetry; | ||
|
|
||
| [TestFixture] | ||
| [Category("Unit")] | ||
| public class CreateResponseFileTests | ||
| { | ||
| private string tempDirectory; | ||
| private MockFixture mockFixture; | ||
| private IFileSystem fileSystem; | ||
| private Mock<IFileSystemEntity> fileStreamMock; | ||
|
|
||
| [SetUp] | ||
| public void SetUp() | ||
| { | ||
| this.tempDirectory = Path.Combine(Path.GetTempPath(), "VirtualClient", "UnitTests", Guid.NewGuid().ToString("n")); | ||
| Directory.CreateDirectory(this.tempDirectory); | ||
|
|
||
| Environment.CurrentDirectory = this.tempDirectory; | ||
|
|
||
| this.mockFixture = new MockFixture(); | ||
| this.mockFixture.SetupMocks(true); | ||
| this.fileSystem = this.mockFixture.Dependencies.GetService<IFileSystem>(); | ||
| this.fileStreamMock = new Mock<IFileSystemEntity>(); | ||
| } | ||
|
|
||
| [Test] | ||
| public async Task ExecuteAsyncDoesNotCreateFileWhenNoOptionsAreSupplied() | ||
| { | ||
| this.mockFixture.Parameters = new Dictionary<string, IConvertible> | ||
| { | ||
| ["FileName"] = "resource_access.rsp" | ||
| }; | ||
|
|
||
| var executor = new TestCreateResponseFile(this.mockFixture); | ||
|
|
||
| await executor.ExecuteAsync().ConfigureAwait(false); | ||
|
|
||
| string expectedPath = Path.Combine(this.tempDirectory, "resource_access.rsp"); | ||
| Assert.False(this.fileSystem.File.Exists(expectedPath), "The response file should not be created when no options are supplied."); | ||
|
|
||
| this.mockFixture.FileSystem.Verify(x => x.File.Delete(It.IsAny<string>()), Times.Never); | ||
| } | ||
|
|
||
| [Test] | ||
| [TestCase("")] | ||
| [TestCase(" ")] | ||
| [TestCase(null)] | ||
| [TestCase("C:\\repos\\VirtualClient\\out\\bin\\Debug\\x64\\VirtualClient.Main\\net9.0\\test.rsp")] | ||
| [TestCase("/home/vmadmin/VirtualClient/out/bin/debug/x64/VirtualClient.Main/net9.0/test.rsp")] | ||
| [TestCase("test.rsp")] | ||
| [TestCase("test.txt")] | ||
| public async Task ExecuteAsyncCreatesResponseFileAsExpected(string inputFilePath) | ||
| { | ||
| string expectedFilePath = string.IsNullOrWhiteSpace(inputFilePath) | ||
| ? "resource_access.rsp" | ||
| : inputFilePath; | ||
|
|
||
| this.mockFixture.Parameters["FileName"] = inputFilePath; | ||
| this.mockFixture.Parameters["Option2"] = "--KeyVaultUri=\"https://testing123-vault.vault.azure.net\""; | ||
| this.mockFixture.Parameters["Option1"] = "--System=\"Testing\""; | ||
|
|
||
| string expectedContent = string.Join(Environment.NewLine, this.mockFixture.Parameters | ||
| .Where(p => p.Key.StartsWith("Option", StringComparison.OrdinalIgnoreCase)) | ||
| .Select(x => x.Value.ToString().Trim()) | ||
| .ToArray()); | ||
|
|
||
| var executor = new TestCreateResponseFile(this.mockFixture); | ||
|
|
||
| Mock<InMemoryFileSystemStream> mockFileStream = new Mock<InMemoryFileSystemStream>(); | ||
| this.mockFixture.FileStream.Setup(f => f.New(It.IsAny<string>(), It.IsAny<FileMode>(), It.IsAny<FileAccess>(), It.IsAny<FileShare>())) | ||
| .Returns(mockFileStream.Object) | ||
| .Callback((string path, FileMode mode, FileAccess access, FileShare share) => | ||
| { | ||
| Assert.AreEqual(expectedFilePath, path); | ||
| Assert.IsTrue(mode == FileMode.Create); | ||
| Assert.IsTrue(access == FileAccess.ReadWrite); | ||
| Assert.IsTrue(share == FileShare.ReadWrite); | ||
| }); | ||
|
|
||
| await executor.ExecuteAsync().ConfigureAwait(false); | ||
| byte[] bytes = Encoding.UTF8.GetBytes(expectedContent); | ||
| mockFileStream.Verify(x => x.WriteAsync(It.Is<ReadOnlyMemory<byte>>(x => (x.Length == bytes.Length)), It.IsAny<CancellationToken>()), Times.Exactly(1)); | ||
| } | ||
|
|
||
| private class TestCreateResponseFile : CreateResponseFile | ||
| { | ||
| public TestCreateResponseFile(MockFixture mockFixture) | ||
| : base(mockFixture.Dependencies, mockFixture.Parameters) | ||
| { | ||
| } | ||
|
|
||
| public Task ExecuteAsync() | ||
| { | ||
| return this.ExecuteAsync(EventContext.None, CancellationToken.None); | ||
| } | ||
| } | ||
| } | ||
| } |
105 changes: 105 additions & 0 deletions
105
src/VirtualClient/VirtualClient.Dependencies/CreateResponseFile.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,105 @@ | ||
| // Copyright (c) Microsoft Corporation. | ||
| // Licensed under the MIT License. | ||
|
|
||
| namespace VirtualClient.Dependencies | ||
| { | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.IO; | ||
| using System.IO.Abstractions; | ||
| using System.Linq; | ||
| using System.Text; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using VirtualClient.Common.Extensions; | ||
| using VirtualClient.Common.Telemetry; | ||
| using VirtualClient.Contracts; | ||
|
|
||
| /// <summary> | ||
| /// A Virtual Client component that creates a response file (e.g. a <c>*.rsp</c> file) containing a space-delimited | ||
| /// list of command-line options. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// Virtual Client can automatically consume response files, allowing users to pass fewer arguments directly on the | ||
| /// command line (and keep long/complex option sets in a file instead). | ||
| /// <para/> | ||
| /// Options are provided via parameters whose keys start with <c>Option</c> (case-insensitive), for example: | ||
| /// <c>Option1=--System="Testing"</c> | ||
| /// <c>Option2=--KeyVaultUri="https://testing123-vault.vault.azure.net"</c> | ||
| /// <para/> | ||
| /// The file is written to <see cref="Environment.CurrentDirectory"/> unless <see cref="FileName"/> is an absolute path. | ||
| /// Doc: https://natemcmaster.github.io/CommandLineUtils/docs/response-file-parsing.html?tabs=using-attributes | ||
| /// </remarks> | ||
| public class CreateResponseFile : VirtualClientComponent | ||
| { | ||
| private readonly IFileSystem fileSystem; | ||
|
|
||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="CreateResponseFile"/> class. | ||
| /// </summary> | ||
| /// <param name="dependencies">Dependency injection container.</param> | ||
| /// <param name="parameters">Component parameters.</param> | ||
| public CreateResponseFile(IServiceCollection dependencies, IDictionary<string, IConvertible> parameters) | ||
| : base(dependencies, parameters) | ||
| { | ||
| this.fileSystem = dependencies.GetService<IFileSystem>(); | ||
| this.fileSystem.ThrowIfNull(nameof(this.fileSystem)); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Gets the name (or path) of the response file to create. | ||
| /// Defaults to `resource_access.rsp`. | ||
| /// </summary> | ||
| public string FileName | ||
| { | ||
| get | ||
| { | ||
| string value = this.Parameters.GetValue<string>(nameof(this.FileName), string.Empty); | ||
| return string.IsNullOrWhiteSpace(value) ? "resource_access.rsp" : value; | ||
| } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Creates the response file when one or more `Option*` parameters are supplied. | ||
| /// </summary> | ||
| /// <param name="telemetryContext">Context information provided to telemetry events.</param> | ||
| /// <param name="cancellationToken">Token that can be used to cancel the operation.</param> | ||
| protected override async Task ExecuteAsync(EventContext telemetryContext, CancellationToken cancellationToken) | ||
| { | ||
| string a = this.FileName; | ||
|
|
||
| cancellationToken.ThrowIfCancellationRequested(); | ||
|
|
||
| string[] optionValues = this.Parameters | ||
| .Where(p => p.Key.StartsWith("Option", StringComparison.OrdinalIgnoreCase)) | ||
| .Select(x => x.Value.ToString().Trim()) | ||
| .ToArray(); | ||
|
|
||
| telemetryContext.AddContext(nameof(optionValues), optionValues); | ||
|
|
||
| if (optionValues.Length > 0) | ||
| { | ||
| if (this.fileSystem.File.Exists(this.FileName)) | ||
| { | ||
| this.fileSystem.File.Delete(this.FileName); | ||
| } | ||
|
|
||
| string content = string.Join(Environment.NewLine, optionValues); | ||
| telemetryContext.AddContext(nameof(content), content); | ||
|
|
||
| byte[] bytes = Encoding.UTF8.GetBytes(content); | ||
|
|
||
| await using (FileSystemStream fileStream = this.fileSystem.FileStream.New( | ||
| this.FileName, | ||
| FileMode.Create, | ||
| FileAccess.ReadWrite, | ||
| FileShare.ReadWrite)) | ||
| { | ||
| await fileStream.WriteAsync(bytes, cancellationToken).ConfigureAwait(false); | ||
| await fileStream.FlushAsync(cancellationToken).ConfigureAwait(false); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
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.