Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,84 +8,100 @@

namespace Microsoft.Testing.Platform.Configurations;

internal sealed class AggregatedConfiguration(IConfigurationProvider[] configurationProviders, ITestApplicationModuleInfo testApplicationModuleInfo, IFileSystem fileSystem) : IConfiguration
internal sealed class AggregatedConfiguration(
IConfigurationProvider[] configurationProviders,
ITestApplicationModuleInfo testApplicationModuleInfo,
IFileSystem fileSystem,
CommandLineParseResult commandLineParseResult) : IConfiguration
{
public const string DefaultTestResultFolderName = "TestResults";
private readonly IConfigurationProvider[] _configurationProviders = configurationProviders;
private readonly ITestApplicationModuleInfo _testApplicationModuleInfo = testApplicationModuleInfo;
private readonly IFileSystem _fileSystem = fileSystem;
private string? _resultDirectory;
private readonly CommandLineParseResult _commandLineParseResult = commandLineParseResult;
private string? _resultsDirectory;
private string? _currentWorkingDirectory;
private string? _testHostWorkingDirectory;

public string? this[string key]
{
get
{
if (key == PlatformConfigurationConstants.PlatformResultDirectory && _resultDirectory is not null)
if (key == PlatformConfigurationConstants.PlatformResultDirectory)
{
return _resultDirectory;
_resultsDirectory = GetResultsDirectoryCore(_commandLineParseResult);
return _resultsDirectory;
}

if (key == PlatformConfigurationConstants.PlatformCurrentWorkingDirectory && _currentWorkingDirectory is not null)
if (key is PlatformConfigurationConstants.PlatformCurrentWorkingDirectory or PlatformConfigurationConstants.PlatformTestHostWorkingDirectory)
{
_currentWorkingDirectory = GetCurrentWorkingDirectoryCore();
return _currentWorkingDirectory;
}

if (key == PlatformConfigurationConstants.PlatformTestHostWorkingDirectory && _testHostWorkingDirectory is not null)
{
return _testHostWorkingDirectory;
}
// Fallback to calculating from configuration providers.
return CalculateFromConfigurationProviders(key);
}
}

foreach (IConfigurationProvider source in _configurationProviders)
private string? CalculateFromConfigurationProviders(string key)
{
foreach (IConfigurationProvider source in _configurationProviders)
{
if (source.TryGet(key, out string? value))
{
if (source.TryGet(key, out string? value))
{
return value;
}
return value;
}

return null;
}
}

public /* for testing */ void SetResultDirectory(string resultDirectory) =>
_resultDirectory = Guard.NotNull(resultDirectory);
return null;
}

public /* for testing */ void SetCurrentWorkingDirectory(string workingDirectory) =>
_currentWorkingDirectory = Guard.NotNull(workingDirectory);

public void SetTestHostWorkingDirectory(string workingDirectory) =>
_testHostWorkingDirectory = Guard.NotNull(workingDirectory);

public async Task CheckTestResultsDirectoryOverrideAndCreateItAsync(ICommandLineOptions commandLineOptions, IFileLoggerProvider? fileLoggerProvider)
public async Task CheckTestResultsDirectoryOverrideAndCreateItAsync(IFileLoggerProvider? fileLoggerProvider)
{
// Load Configuration
_currentWorkingDirectory = _testApplicationModuleInfo.GetCurrentTestApplicationDirectory();
_resultsDirectory = _fileSystem.CreateDirectory(this[PlatformConfigurationConstants.PlatformResultDirectory]!);

string? resultDirectory = this[PlatformConfigurationConstants.PlatformResultDirectory];
if (resultDirectory is null)
// In case of the result directory is overridden by the config file we move logs to it.
// This can happen in case of VSTest mode where the result directory is set to a different location.
// This behavior is non documented and we reserve the right to change it in the future.
if (fileLoggerProvider is not null)
{
if (commandLineOptions.TryGetOptionArgumentList(PlatformCommandLineProvider.ResultDirectoryOptionKey, out string[]? resultDirectoryArg))
{
_resultDirectory = resultDirectoryArg[0];
}
await fileLoggerProvider.CheckLogFolderAndMoveToTheNewIfNeededAsync(_resultsDirectory);
}
else
}

private string GetResultsDirectoryCore(CommandLineParseResult commandLineParseResult)
{
// We already calculated it before, or was set by unit tests via SetCurrentWorkingDirectory.
if (_resultsDirectory is not null)
{
_resultDirectory = resultDirectory;
return _resultsDirectory;
}

_resultDirectory ??= Path.Combine(_currentWorkingDirectory, DefaultTestResultFolderName);

_resultDirectory = _fileSystem.CreateDirectory(_resultDirectory);

// In case of the result directory is overridden by the config file we move logs to it.
// This can happen in case of VSTest mode where the result directory is set to a different location.
// This behavior is non documented and we reserve the right to change it in the future.
if (fileLoggerProvider is not null)
// NOTE: It's important to consider the `--results-directory` option before the configurations.
// It makes more sense to respect it first, and is also relevant for Retry extension.
// Consider user is setting ResultsDirectory in configuration file.
// When tests are retried, we re-run the executable again, but we pass --results-directory containing the folder where the current retry attempt
// results should be stored. But we will also still pass configuration file (e.g, runsettings via --settings) that the user originally specified.
// In that case, we will want to respect --results-directory.
if (commandLineParseResult.TryGetOptionArgumentList(PlatformCommandLineProvider.ResultDirectoryOptionKey, out string[]? resultDirectoryArg))
{
await fileLoggerProvider.CheckLogFolderAndMoveToTheNewIfNeededAsync(_resultDirectory);
return resultDirectoryArg[0];
}

// If not specified by command line, then use the configuration providers.
// And finally fallback to DefaultTestResultFolderName relative to the current working directory.
return CalculateFromConfigurationProviders(PlatformConfigurationConstants.PlatformResultDirectory)
?? Path.Combine(this[PlatformConfigurationConstants.PlatformCurrentWorkingDirectory]!, DefaultTestResultFolderName);
}

private string GetCurrentWorkingDirectoryCore()
// If the value is already set, use that.
=> _currentWorkingDirectory
// If first time calculating it, prefer the value from configuration,
?? CalculateFromConfigurationProviders(PlatformConfigurationConstants.PlatformCurrentWorkingDirectory)
// then fallback to the actual working directory.
?? _testApplicationModuleInfo.GetCurrentTestApplicationDirectory();
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ public static string GetCurrentWorkingDirectory(this IConfiguration configuratio
/// </summary>
/// <param name="configuration">The configuration.</param>
/// <returns>The test host working directory.</returns>
[Obsolete("This API is obsolete and will be removed in v2. Use GetCurrentWorkingDirectory instead.", error: true)]
// TODO: This is only used in unit tests. Should that be removed (maybe in v2)?
Comment thread
nohwnd marked this conversation as resolved.
Resolved
public static string GetTestHostWorkingDirectory(this IConfiguration configuration)
{
string? workingDirectory = configuration[PlatformConfigurationConstants.PlatformTestHostWorkingDirectory];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,6 @@ internal async Task<IConfiguration> BuildAsync(IFileLoggerProvider? syncFileLogg

return defaultJsonConfiguration is null
? throw new InvalidOperationException(PlatformResources.ConfigurationManagerCannotFindDefaultJsonConfigurationErrorMessage)
: new AggregatedConfiguration(configurationProviders.OrderBy(x => x.Order).Select(x => x.ConfigurationProvider).ToArray(), _testApplicationModuleInfo, _fileSystem);
: new AggregatedConfiguration(configurationProviders.OrderBy(x => x.Order).Select(x => x.ConfigurationProvider).ToArray(), _testApplicationModuleInfo, _fileSystem, commandLineParseResult);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ public async Task<ITestHost> BuildAsync(
// here we ensure to override the result directory if user passed the argument --results-directory in command line.
// After this check users can get the result directory using IConfiguration["platformOptions:resultDirectory"] or the
// extension method helper serviceProvider.GetConfiguration()
await configuration.CheckTestResultsDirectoryOverrideAndCreateItAsync(commandLineOptions, loggingState.FileLoggerProvider);
await configuration.CheckTestResultsDirectoryOverrideAndCreateItAsync(loggingState.FileLoggerProvider);

// Display banner now because we need capture the output in case of MSBuild integration and we want to forward
// to file disc also the banner, so at this point we need to have all services and configuration(result directory) built.
Expand Down Expand Up @@ -433,7 +433,6 @@ await LogTestHostCreatedAsync(
// Out of the test host controller extension the current working directory is the test host working directory.
string? currentWorkingDirectory = configuration[PlatformConfigurationConstants.PlatformCurrentWorkingDirectory];
ApplicationStateGuard.Ensure(currentWorkingDirectory is not null);
configuration.SetTestHostWorkingDirectory(currentWorkingDirectory);

testHostControllerInfo.IsCurrentProcessTestHostController = false;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,6 @@ internal async Task<TestHostControllerConfiguration> BuildAsync(ServiceProvider
var aggregatedConfiguration = (AggregatedConfiguration)serviceProvider.GetConfiguration();
string? currentWorkingDirectory = aggregatedConfiguration[PlatformConfigurationConstants.PlatformCurrentWorkingDirectory];
ApplicationStateGuard.Ensure(currentWorkingDirectory is not null);
aggregatedConfiguration.SetTestHostWorkingDirectory(currentWorkingDirectory);

List<(ITestHostEnvironmentVariableProvider TestHostEnvironmentVariableProvider, int RegistrationOrder)> environmentVariableProviders = [];
foreach (Func<IServiceProvider, ITestHostEnvironmentVariableProvider> environmentVariableProviderFactory in _environmentVariableProviderFactories)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ public Services()
ServiceProvider.AddService(new FakeClock());
ServiceProvider.AddService(new SystemTask());
#pragma warning disable TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
ServiceProvider.AddService(new AggregatedConfiguration(Array.Empty<IConfigurationProvider>(), new CurrentTestApplicationModuleInfo(new SystemEnvironment(), new SystemProcessHandler()), new SystemFileSystem()));
ServiceProvider.AddService(new AggregatedConfiguration(Array.Empty<IConfigurationProvider>(), new CurrentTestApplicationModuleInfo(new SystemEnvironment(), new SystemProcessHandler()), new SystemFileSystem(), new(null, [], [])));
#pragma warning restore TPEXP // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
}

Expand Down
Loading