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 @@ -91,9 +91,14 @@ public static async Task<ValidationResult> ValidateAsync(
// (testconfig.json is case-insensitive everywhere else). Use OrdinalIgnoreCase so a JSON
// entry such as "Timeout": "30s" resolves to the same provider/option metadata as
// "--timeout 30s" on the command line.
var providerAndOptionByOptionName = extensionOptionsByProvider.Concat(systemOptionsByProvider)
.SelectMany(tuple => tuple.Value.Select(option => (provider: tuple.Key, option)))
.ToDictionary(tuple => tuple.option.Name, StringComparer.OrdinalIgnoreCase);
var providerAndOptionByOptionName = new Dictionary<string, (ICommandLineOptionsProvider Provider, CommandLineOption Option)>(StringComparer.OrdinalIgnoreCase);
foreach (KeyValuePair<ICommandLineOptionsProvider, IReadOnlyCollection<CommandLineOption>> provider in extensionOptionsByProvider.Concat(systemOptionsByProvider))
{
foreach (CommandLineOption option in provider.Value)
{
providerAndOptionByOptionName.Add(option.Name, (provider.Key, option));
}
}

if (ValidateOptionsArgumentArity(commandLineParseResult, jsonCommandLineOptions, jsonCommandLineOptionDefaults, providerAndOptionByOptionName) is { IsValid: false } result5)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ internal sealed class ServiceProvider : IServiceProvider, ICloneable
public bool AllowTestAdapterFrameworkRegistration { get; set; }

#pragma warning disable CS0618 // Type or member is obsolete
private static Type[] InternalOnlyExtensions =>
private static readonly Type[] InternalOnlyExtensions =
[
// TestHost
typeof(ITestHostApplicationLifetime),
Expand Down Expand Up @@ -126,7 +126,22 @@ public IEnumerable<object> GetServicesInternal(
}

public object? GetServiceInternal(Type serviceType, bool skipInternalOnlyExtensions = false)
=> GetServicesInternal(serviceType, stopAtFirst: true, skipInternalOnlyExtensions).FirstOrDefault();
{
if (skipInternalOnlyExtensions && InternalOnlyExtensions.Contains(serviceType))
{
return null;
}

foreach (object serviceInstance in _services)
{
if (serviceType.IsInstanceOfType(serviceInstance))
{
return serviceInstance;
}
}

return null;
}

private void RegisterCoverageProducer(object service)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,7 @@ public static TService GetRequiredPlatformService<TService>(this IServiceProvide
_ = provider ?? throw new ArgumentNullException(nameof(provider));

object? service = provider.GetService(typeof(TService));
ApplicationStateGuard.Ensure(service is not null, string.Format(CultureInfo.InvariantCulture, PlatformResources.ServiceProviderCannotFindServiceErrorMessage, typeof(TService)));

return (TService)service;
return (TService)(service ?? throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.ServiceProviderCannotFindServiceErrorMessage, typeof(TService))));
}

/// <summary>
Expand Down Expand Up @@ -189,9 +187,7 @@ internal static TService GetRequiredServiceInternal<TService>(this IServiceProvi
_ = provider ?? throw new ArgumentNullException(nameof(provider));

object? service = ((ServiceProvider)provider).GetServiceInternal(typeof(TService));
ApplicationStateGuard.Ensure(service is not null, string.Format(CultureInfo.InvariantCulture, PlatformResources.ServiceProviderCannotFindServiceErrorMessage, typeof(TService)));

return (TService)service;
return (TService)(service ?? throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, PlatformResources.ServiceProviderCannotFindServiceErrorMessage, typeof(TService))));
}

internal static TService? GetServiceInternal<TService>(this IServiceProvider provider)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,12 +162,14 @@ internal async Task<TestHostControllerConfiguration> BuildAsync(ServiceProvider
requireProcessRestart = true;
}

return new TestHostControllerConfiguration(
[.. environmentVariableProviders.OrderBy(x => x.RegistrationOrder).Select(x => (ITestHostEnvironmentVariableProvider)x.Extension)],
[.. lifetimeHandlers.OrderBy(x => x.RegistrationOrder).Select(x => (ITestHostProcessLifetimeHandler)x.Extension)],
[.. dataConsumers.OrderBy(x => x.RegistrationOrder).Select(x => (IDataConsumer)x.Extension)],
testHostLauncher,
requireProcessRestart);
return !requireProcessRestart
? new TestHostControllerConfiguration([], [], [], testHostLauncher, requireProcessRestart: false)
: new TestHostControllerConfiguration(
[.. environmentVariableProviders.OrderBy(x => x.RegistrationOrder).Select(x => (ITestHostEnvironmentVariableProvider)x.Extension)],
[.. lifetimeHandlers.OrderBy(x => x.RegistrationOrder).Select(x => (ITestHostProcessLifetimeHandler)x.Extension)],
[.. dataConsumers.OrderBy(x => x.RegistrationOrder).Select(x => (IDataConsumer)x.Extension)],
testHostLauncher,
requireProcessRestart);
}

internal async Task<ITestHostLauncher?> BuildTestHostLauncherAsync(ServiceProvider serviceProvider)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Microsoft.Testing.Platform.Extensions.TestHost;
using Microsoft.Testing.Platform.Extensions.TestHostControllers;
using Microsoft.Testing.Platform.Logging;
using Microsoft.Testing.Platform.Resources;
using Microsoft.Testing.Platform.Services;

using Moq;
Expand Down Expand Up @@ -34,7 +35,34 @@ public void GetRequiredPlatformService_MissingServiceThrows()
{
IServiceProvider provider = new SingleServiceProvider(null);

Assert.ThrowsExactly<InvalidOperationException>(() => provider.GetRequiredPlatformService<object>());
InvalidOperationException exception = Assert.ThrowsExactly<InvalidOperationException>(() => provider.GetRequiredPlatformService<object>());

Assert.AreEqual(
string.Format(CultureInfo.InvariantCulture, PlatformResources.GetResourceString("ServiceProviderCannotFindServiceErrorMessage"), typeof(object)),
exception.Message);
}

[TestMethod]
public void GetRequiredServiceInternal_MissingServicePreservesDiagnostic()
{
InvalidOperationException exception = Assert.ThrowsExactly<InvalidOperationException>(
() => _serviceProvider.GetRequiredServiceInternal<object>());

Assert.AreEqual(
string.Format(CultureInfo.InvariantCulture, PlatformResources.GetResourceString("ServiceProviderCannotFindServiceErrorMessage"), typeof(object)),
exception.Message);
}

[TestMethod]
public void GetRequiredServiceInternal_ReturnsFirstMatchingService()
{
TestSessionLifetimeHandler first = new();
TestSessionLifetimeHandler second = new();
_serviceProvider.AddService(first);
_serviceProvider.AddService(second);

Assert.AreSame(first, _serviceProvider.GetRequiredServiceInternal<ITestSessionLifetimeHandler>());
Assert.IsNull(_serviceProvider.GetPlatformService<ITestSessionLifetimeHandler>());
}

[TestMethod]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,74 @@ public async Task TestHost_ComposeFactory_ShouldSucceed(bool withParameter)
Assert.AreEqual(compositeExtensions[0].GetInstance(), sessionLifetimeHandle[0]);
}

[TestMethod]
public async Task TestHostController_WithoutExtensions_DoesNotRequireProcessRestart()
{
TestHostControllersManager testHostControllerManager = new();

TestHostControllerConfiguration configuration = await testHostControllerManager.BuildAsync(_serviceProvider);

Assert.IsFalse(configuration.RequireProcessRestart);
Assert.IsEmpty(configuration.EnvironmentVariableProviders);
Assert.IsEmpty(configuration.LifetimeHandlers);
Assert.IsEmpty(configuration.DataConsumer);
Assert.IsNull(configuration.TestHostLauncher);
}

[TestMethod]
public async Task TestHostController_DisabledExtensions_StillBuildsFactoriesAndChecksEnablement()
{
TestHostControllersManager testHostControllerManager = new();
int factoryInvocations = 0;
int serviceCount = _serviceProvider.Services.Count;

Mock<ITestHostEnvironmentVariableProvider> environmentVariableProvider = new();
environmentVariableProvider.Setup(x => x.IsEnabledAsync()).ReturnsAsync(false);
testHostControllerManager.AddEnvironmentVariableProvider(_ =>
{
factoryInvocations++;
return environmentVariableProvider.Object;
});

Mock<ITestHostProcessLifetimeHandler> lifetimeHandler = new();
lifetimeHandler.Setup(x => x.IsEnabledAsync()).ReturnsAsync(false);
testHostControllerManager.AddProcessLifetimeHandler(_ =>
{
factoryInvocations++;
return lifetimeHandler.Object;
});

Mock<IDataConsumer> dataConsumer = new();
dataConsumer.Setup(x => x.IsEnabledAsync()).ReturnsAsync(false);
testHostControllerManager.AddDataConsumer(new CompositeExtensionFactory<IDataConsumer>(() =>
{
factoryInvocations++;
return dataConsumer.Object;
}));

Mock<ITestHostLauncher> launcher = new();
launcher.Setup(x => x.IsEnabledAsync()).ReturnsAsync(false);
testHostControllerManager.AddTestHostLauncher(_ =>
{
factoryInvocations++;
return launcher.Object;
});

TestHostControllerConfiguration configuration = await testHostControllerManager.BuildAsync(_serviceProvider);

Assert.AreEqual(4, factoryInvocations);
environmentVariableProvider.Verify(x => x.IsEnabledAsync(), Times.Once);
lifetimeHandler.Verify(x => x.IsEnabledAsync(), Times.Once);
dataConsumer.Verify(x => x.IsEnabledAsync(), Times.AtLeastOnce);
launcher.Verify(x => x.IsEnabledAsync(), Times.Once);
Assert.IsFalse(configuration.RequireProcessRestart);
Assert.IsEmpty(configuration.EnvironmentVariableProviders);
Assert.IsEmpty(configuration.LifetimeHandlers);
Assert.IsEmpty(configuration.DataConsumer);
Assert.IsNull(configuration.TestHostLauncher);
Assert.HasCount(serviceCount, _serviceProvider.Services);
}

[TestMethod]
public async Task TestHostControllerEnvironmentVariableProvider_DuplicatedId_ShouldFail()
{
Expand Down
Loading