1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Threading; 5 using System.Threading.Tasks; 6 using Xunit.Abstractions; 7 using Xunit.Sdk; 8 9 namespace Xunit.NetCore.Extensions 10 { 11 public class XunitTestAssemblyRunnerWithAssemblyFixture : XunitTestAssemblyRunner 12 { 13 readonly Dictionary<Type, object> assemblyFixtureMappings = new Dictionary<Type, object>(); 14 List<AssemblyFixtureAttribute> assemblyFixtureAttributes; 15 XunitTestAssemblyRunnerWithAssemblyFixture(ITestAssembly testAssembly, IEnumerable<IXunitTestCase> testCases, IMessageSink diagnosticMessageSink, IMessageSink executionMessageSink, ITestFrameworkExecutionOptions executionOptions)16 public XunitTestAssemblyRunnerWithAssemblyFixture(ITestAssembly testAssembly, 17 IEnumerable<IXunitTestCase> testCases, 18 IMessageSink diagnosticMessageSink, 19 IMessageSink executionMessageSink, 20 ITestFrameworkExecutionOptions executionOptions) 21 : base(testAssembly, testCases, diagnosticMessageSink, executionMessageSink, executionOptions) 22 { } 23 AfterTestAssemblyStartingAsync()24 protected override async Task AfterTestAssemblyStartingAsync() 25 { 26 // Let everything initialize 27 await base.AfterTestAssemblyStartingAsync(); 28 29 // Go find all the AssemblyFixtureAttributes adorned on the test assembly 30 Aggregator.Run(() => 31 { 32 var fixturesAttrs = ((IReflectionAssemblyInfo)TestAssembly.Assembly).Assembly 33 .GetCustomAttributes(typeof(AssemblyFixtureAttribute), false) 34 .Cast<AssemblyFixtureAttribute>() 35 .ToList(); 36 37 this.assemblyFixtureAttributes = fixturesAttrs; 38 39 // Instantiate all the fixtures 40 foreach (var fixtureAttr in fixturesAttrs.Where(a => a.LifetimeScope == AssemblyFixtureAttribute.Scope.Assembly)) 41 assemblyFixtureMappings[fixtureAttr.FixtureType] = Activator.CreateInstance(fixtureAttr.FixtureType); 42 }); 43 } 44 BeforeTestAssemblyFinishedAsync()45 protected override Task BeforeTestAssemblyFinishedAsync() 46 { 47 // Make sure we clean up everybody who is disposable, and use Aggregator.Run to isolate Dispose failures 48 foreach (var disposable in assemblyFixtureMappings.Values.OfType<IDisposable>()) 49 Aggregator.Run(disposable.Dispose); 50 51 return base.BeforeTestAssemblyFinishedAsync(); 52 } 53 RunTestCollectionAsync(IMessageBus messageBus, ITestCollection testCollection, IEnumerable<IXunitTestCase> testCases, CancellationTokenSource cancellationTokenSource)54 protected override Task<RunSummary> RunTestCollectionAsync(IMessageBus messageBus, 55 ITestCollection testCollection, 56 IEnumerable<IXunitTestCase> testCases, 57 CancellationTokenSource cancellationTokenSource) 58 => new XunitTestCollectionRunnerWithAssemblyFixture(assemblyFixtureMappings, assemblyFixtureAttributes, 59 testCollection, testCases, DiagnosticMessageSink, messageBus, TestCaseOrderer, new ExceptionAggregator(Aggregator), cancellationTokenSource).RunAsync(); 60 } 61 } 62