diff --git a/sln/Build-Package.ps1 b/sln/Build-Package.ps1 index 4e1c0621..d9921086 100644 --- a/sln/Build-Package.ps1 +++ b/sln/Build-Package.ps1 @@ -69,6 +69,7 @@ function BuildVersioningOptions() { "sln\src\NSpecRunner", ` "sln\test\NSpec.Tests", ` "sln\test\Samples\SampleSpecs", ` + "sln\test\Samples\SampleSpecsApi", ` "sln\test\Samples\SampleSpecsFocus" ) | ForEach-Object { CleanProject $_ } @@ -79,6 +80,7 @@ function BuildVersioningOptions() { "sln\src\NSpecRunner", ` "sln\test\NSpec.Tests", ` "sln\test\Samples\SampleSpecs", ` + "sln\test\Samples\SampleSpecsApi", ` "sln\test\Samples\SampleSpecsFocus" ) | ForEach-Object { Exec { & dotnet restore $_ } } diff --git a/sln/NSpec.sln b/sln/NSpec.sln index 4ebb6d9d..c17f4b22 100644 --- a/sln/NSpec.sln +++ b/sln/NSpec.sln @@ -45,6 +45,8 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "content", "content", "{6D53 content\DebuggerShim.cs = content\DebuggerShim.cs EndProjectSection EndProject +Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "SampleSpecsApi", "test\Samples\SampleSpecsApi\SampleSpecsApi.xproj", "{70692496-9329-4145-899F-5B141C590326}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -73,6 +75,10 @@ Global {11728D62-6D9B-4D49-9B82-536969751801}.Release|Any CPU.Build.0 = Release|Any CPU {FBCF1115-4F77-4706-AE32-B4251561C492}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {FBCF1115-4F77-4706-AE32-B4251561C492}.Release|Any CPU.ActiveCfg = Release|Any CPU + {70692496-9329-4145-899F-5B141C590326}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {70692496-9329-4145-899F-5B141C590326}.Debug|Any CPU.Build.0 = Debug|Any CPU + {70692496-9329-4145-899F-5B141C590326}.Release|Any CPU.ActiveCfg = Release|Any CPU + {70692496-9329-4145-899F-5B141C590326}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -86,5 +92,6 @@ Global {11728D62-6D9B-4D49-9B82-536969751801} = {1F898A44-0A09-40F7-9335-15054FB25DE3} {FBCF1115-4F77-4706-AE32-B4251561C492} = {08CCB349-B6B8-4F86-A1B2-FF56A8C2CFEC} {6D535A1F-A13A-4337-8337-08690D9109BD} = {BC384EC3-E8E5-4997-B0F5-888287842481} + {70692496-9329-4145-899F-5B141C590326} = {1F898A44-0A09-40F7-9335-15054FB25DE3} EndGlobalSection EndGlobal diff --git a/sln/src/NSpec/Api/Controller.cs b/sln/src/NSpec/Api/Controller.cs index 1d3d3ef6..22b36ebc 100644 --- a/sln/src/NSpec/Api/Controller.cs +++ b/sln/src/NSpec/Api/Controller.cs @@ -1,64 +1,62 @@ -using NSpec.Domain; -using NSpec.Domain.Formatters; +using Newtonsoft.Json; +using NSpec.Api.Discovery; +using NSpec.Api.Execution; using System; using System.Collections.Generic; -using System.Linq; -using System.Reflection; namespace NSpec.Api { public class Controller { - public int Run( + public int RunBatch( string testAssemblyPath, string tags, string formatterClassName, IDictionary formatterOptions, bool failFast) { - var formatter = FindFormatter(formatterClassName, formatterOptions); + var batchExampleRunner = new BatchExampleRunner(testAssemblyPath, + tags, formatterClassName, formatterOptions, failFast); - var invocation = new RunnerInvocation(testAssemblyPath, tags, formatter, failFast); - - int nrOfFailures = invocation.Run().Failures().Count(); + int nrOfFailures = batchExampleRunner.Start(); return nrOfFailures; } - /// - /// Find an implementation of IFormatter with the given class name - /// - /// - /// - /// - private static IFormatter FindFormatter(string formatterClassName, IDictionary formatterOptions) + public string List(string testAssemblyPath) { - // Default formatter is the standard console formatter - if (string.IsNullOrEmpty(formatterClassName)) - { - var consoleFormatter = new ConsoleFormatter(); - consoleFormatter.Options = formatterOptions; - return consoleFormatter; - } + var exampleSelector = new ExampleSelector(testAssemblyPath); - Assembly nspecAssembly = typeof(IFormatter).GetTypeInfo().Assembly; + var discoveredExamples = exampleSelector.Select(); - // Look for a class that implements IFormatter with the provided name - var formatterType = nspecAssembly.GetTypes().FirstOrDefault(type => - (type.Name.ToLowerInvariant() == formatterClassName) - && typeof(IFormatter).IsAssignableFrom(type)); + string serialized = JsonConvert.SerializeObject(discoveredExamples); - if (formatterType != null) + return serialized; + } + + public void RunInteractive( + string testAssemblyPath, + IEnumerable exampleFullNames, + Action onExampleStarted, + Action onExampleCompleted) + { + Action onDiscovered = example => { - var formatter = (IFormatter)Activator.CreateInstance(formatterType); - formatter.Options = formatterOptions; - return formatter; - } - else + string serialized = JsonConvert.SerializeObject(example); + + onExampleStarted(serialized); + }; + + Action onExecuted = example => { - throw new TypeLoadException("Could not find formatter type " + formatterClassName); + string serialized = JsonConvert.SerializeObject(example); + + onExampleCompleted(serialized); + }; + + var exampleRunner = new ExampleRunner(testAssemblyPath, onDiscovered, onExecuted); - } + exampleRunner.Start(exampleFullNames); } } } diff --git a/sln/src/NSpec/Api/Discovery/DiscoveredExample.cs b/sln/src/NSpec/Api/Discovery/DiscoveredExample.cs new file mode 100644 index 00000000..080f46cb --- /dev/null +++ b/sln/src/NSpec/Api/Discovery/DiscoveredExample.cs @@ -0,0 +1,31 @@ +using System; + +namespace NSpec.Api.Discovery +{ + public class DiscoveredExample + { + public string FullName { get; set; } + + public string SourceFilePath { get; set; } + + public int SourceLineNumber { get; set; } + + public string SourceAssembly { get; set; } + + public string[] Tags { get; set; } + + public override string ToString() + { + string tagsText = String.Join(", ", Tags); + + return String.Join(", ", new[] + { + $"{nameof(FullName)}: {FullName}", + $"{nameof(SourceFilePath)}: {SourceFilePath}", + $"{nameof(SourceLineNumber)}: {SourceLineNumber}", + $"{nameof(SourceAssembly)}: {SourceAssembly}", + $"{nameof(Tags)}: [{tagsText}]", + }); + } + } +} diff --git a/sln/src/NSpec/Api/Discovery/DiscoveryUtils.cs b/sln/src/NSpec/Api/Discovery/DiscoveryUtils.cs new file mode 100644 index 00000000..b159566f --- /dev/null +++ b/sln/src/NSpec/Api/Discovery/DiscoveryUtils.cs @@ -0,0 +1,25 @@ +using Microsoft.Extensions.Testing.Abstractions; +using NSpec.Domain; +using System.Linq; + +namespace NSpec.Api.Discovery +{ + public static class DiscoveryUtils + { + public static DiscoveredExample MapToDiscovered(ExampleBase example, string binaryPath, SourceInformation sourceInfo) + { + var discoveredExample = new DiscoveredExample() + { + FullName = example.FullName(), + SourceAssembly = binaryPath, + SourceFilePath = sourceInfo.Filename, + SourceLineNumber = sourceInfo.LineNumber, + Tags = example.Tags + .Select(tag => tag.Replace("_", " ")) + .ToArray(), + }; + + return discoveredExample; + } + } +} diff --git a/sln/src/NSpec/Api/Discovery/ExampleSelector.cs b/sln/src/NSpec/Api/Discovery/ExampleSelector.cs new file mode 100644 index 00000000..86bcc66c --- /dev/null +++ b/sln/src/NSpec/Api/Discovery/ExampleSelector.cs @@ -0,0 +1,49 @@ +using NSpec.Api.Shared; +using NSpec.Domain; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace NSpec.Api.Discovery +{ + public class ExampleSelector + { + public ExampleSelector(string testAssemblyPath) + { + this.testAssemblyPath = testAssemblyPath; + + debugInfoProvider = new DebugInfoProvider(testAssemblyPath); + } + + public IEnumerable Select() + { + var selector = new ContextSelector(); + + string noTags = String.Empty; + + selector.Select(testAssemblyPath, noTags); + + var contexts = selector.Contexts; + + var examples = contexts.Examples(); + + var discoveredExamples = + from exm in examples + select MapToDiscovered(exm, testAssemblyPath); + + return discoveredExamples; + } + + DiscoveredExample MapToDiscovered(ExampleBase example, string binaryPath) + { + var sourceInfo = debugInfoProvider.GetSourceInfo(example); + + var discoveredExample = DiscoveryUtils.MapToDiscovered(example, binaryPath, sourceInfo); + + return discoveredExample; + } + + readonly string testAssemblyPath; + readonly DebugInfoProvider debugInfoProvider; + } +} diff --git a/sln/src/NSpec/Api/Execution/BatchExampleRunner.cs b/sln/src/NSpec/Api/Execution/BatchExampleRunner.cs new file mode 100644 index 00000000..d5f4460b --- /dev/null +++ b/sln/src/NSpec/Api/Execution/BatchExampleRunner.cs @@ -0,0 +1,68 @@ +using NSpec.Domain; +using NSpec.Domain.Formatters; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; + +namespace NSpec.Api.Execution +{ + public class BatchExampleRunner + { + public BatchExampleRunner( + string testAssemblyPath, + string tags, + string formatterClassName, + IDictionary formatterOptions, + bool failFast) + { + var formatter = FindFormatter(formatterClassName, formatterOptions); + + invocation = new RunnerInvocation(testAssemblyPath, tags, formatter, failFast); + } + + public int Start() + { + int nrOfFailures = invocation.Run().Failures().Count(); + + return nrOfFailures; + } + + readonly RunnerInvocation invocation; + + /// + /// Find an implementation of IFormatter with the given class name + /// + /// + /// + /// + static IFormatter FindFormatter(string formatterClassName, IDictionary formatterOptions) + { + // Default formatter is the standard console formatter + if (string.IsNullOrEmpty(formatterClassName)) + { + var consoleFormatter = new ConsoleFormatter(); + consoleFormatter.Options = formatterOptions; + return consoleFormatter; + } + + Assembly nspecAssembly = typeof(IFormatter).GetTypeInfo().Assembly; + + // Look for a class that implements IFormatter with the provided name + var formatterType = nspecAssembly.GetTypes().FirstOrDefault(type => + (type.Name.ToLowerInvariant() == formatterClassName) + && typeof(IFormatter).IsAssignableFrom(type)); + + if (formatterType != null) + { + var formatter = (IFormatter)Activator.CreateInstance(formatterType); + formatter.Options = formatterOptions; + return formatter; + } + else + { + throw new TypeLoadException("Could not find formatter type " + formatterClassName); + } + } + } +} diff --git a/sln/src/NSpec/Api/Execution/ExampleRunner.cs b/sln/src/NSpec/Api/Execution/ExampleRunner.cs new file mode 100644 index 00000000..5b27867d --- /dev/null +++ b/sln/src/NSpec/Api/Execution/ExampleRunner.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NSpec.Api.Discovery; +using NSpec.Domain; +using NSpec.Domain.Formatters; +using NSpec.Api.Shared; + +namespace NSpec.Api.Execution +{ + public class ExampleRunner: ILiveFormatter + { + public ExampleRunner( + string testAssemblyPath, + Action onDiscovered, + Action onExecuted) + { + this.testAssemblyPath = testAssemblyPath; + this.onDiscovered = onDiscovered; + this.onExecuted = onExecuted; + + debugInfoProvider = new DebugInfoProvider(testAssemblyPath); + } + + public void Start( + IEnumerable exampleFullNames) + { + var selectedNames = new HashSet(exampleFullNames); + + var selector = new ContextSelector(); + + string noTags = String.Empty; + + selector.Select(testAssemblyPath, noTags); + + var contexts = selector.Contexts; + + // original idea taken from osoftware/NSpecTestAdapter: + // see https://github.com/osoftware/NSpecTestAdapter/blob/master/NSpec.TestAdapter/Executor.cs + + var allExamples = contexts.SelectMany(ctx => ctx.AllExamples()); + + var selectedExamples = allExamples.Where(exm => selectedNames.Contains(exm.FullName())); + + var selectedContexts = selectedExamples.Select(exm => exm.Context).Distinct(); + + foreach (var context in selectedContexts) + { + RunContext(context); + } + } + + // ILiveFormatter + + public void Write(ExampleBase example, int level) + { + // ignore level + + var discoveredExample = MapToDiscovered(example, testAssemblyPath); + + onDiscovered(discoveredExample); + + var executedExample = MapToExecuted(example); + + onExecuted(executedExample); + } + + public void Write(Context context) + { + // nothing to do + } + + void RunContext(Context context) + { + // original idea inspired from: + // https://github.com/osoftware/NSpecTestAdapter/blob/master/NSpec.TestAdapter/Executor.cs + + var instance = context.GetInstance(); + + context.Run( + formatter: this, + failFast: false, + instance: instance, + recurse: false); + + context.AssignExceptions( + recurse: false); + } + + DiscoveredExample MapToDiscovered(ExampleBase example, string binaryPath) + { + var sourceInfo = debugInfoProvider.GetSourceInfo(example); + + var discoveredExample = DiscoveryUtils.MapToDiscovered(example, binaryPath, sourceInfo); + + return discoveredExample; + } + + readonly string testAssemblyPath; + readonly Action onDiscovered; + readonly Action onExecuted; + readonly DebugInfoProvider debugInfoProvider; + + static ExecutedExample MapToExecuted(ExampleBase example) + { + var executedExample = new ExecutedExample() + { + FullName = example.FullName(), + Pending = example.Pending, + Failed = example.Failed(), + Duration = example.Duration, + }; + + if (example.Exception != null) + { + executedExample.ExceptionMessage = example.Exception.Message; + executedExample.ExceptionStackTrace = example.Exception.StackTrace; + } + + return executedExample; + } + } +} diff --git a/sln/src/NSpec/Api/Execution/ExecutedExample.cs b/sln/src/NSpec/Api/Execution/ExecutedExample.cs new file mode 100644 index 00000000..a4f2a458 --- /dev/null +++ b/sln/src/NSpec/Api/Execution/ExecutedExample.cs @@ -0,0 +1,19 @@ +using System; + +namespace NSpec.Api.Execution +{ + public class ExecutedExample + { + public string FullName { get; set; } + + public bool Pending { get; set; } + + public bool Failed { get; set; } + + public string ExceptionMessage { get; set; } + + public string ExceptionStackTrace { get; set; } + + public TimeSpan Duration { get; set; } + } +} diff --git a/sln/src/NSpec/Api/Shared/DebugInfoProvider.cs b/sln/src/NSpec/Api/Shared/DebugInfoProvider.cs new file mode 100644 index 00000000..1b2a4aa0 --- /dev/null +++ b/sln/src/NSpec/Api/Shared/DebugInfoProvider.cs @@ -0,0 +1,51 @@ +using Microsoft.DotNet.ProjectModel; +using Microsoft.Extensions.Testing.Abstractions; +using NSpec.Domain; +using System.IO; + +namespace NSpec.Api.Shared +{ + public class DebugInfoProvider + { + public DebugInfoProvider(string testAssemblyPath) + { + string pdbFilePath = GetPdbFilePath(testAssemblyPath); + + if (File.Exists(pdbFilePath)) + { + sourceInfoProvider = new SourceInformationProvider(pdbFilePath); + } + } + + public SourceInformation GetSourceInfo(ExampleBase example) + { + if (sourceInfoProvider == null || example.Pending) + { + return emptyInfo; + } + + var methodInfo = example.BodyMethodInfo; + + var sourceInfo = sourceInfoProvider.GetSourceInformation(methodInfo); + + return sourceInfo; + } + + readonly SourceInformationProvider sourceInfoProvider; + + readonly SourceInformation emptyInfo = new SourceInformation(null, 0); + + static string GetPdbFilePath(string assemblyPath) + { + string assemblyDirectoryPath = Path.GetDirectoryName(assemblyPath); + + string assemblyFileName = Path.GetFileNameWithoutExtension(assemblyPath); + + string pdbFileName = assemblyFileName + FileNameSuffixes.DotNet.ProgramDatabase; + + string pdbFilePath = Path.Combine(assemblyDirectoryPath, pdbFileName); + + return pdbFilePath; + } + } +} diff --git a/sln/src/NSpec/Domain/AsyncExample.cs b/sln/src/NSpec/Domain/AsyncExample.cs index 2a8dc0d7..249296c8 100644 --- a/sln/src/NSpec/Domain/AsyncExample.cs +++ b/sln/src/NSpec/Domain/AsyncExample.cs @@ -1,6 +1,5 @@ using System; -using System.Collections.Generic; -using System.Linq.Expressions; +using System.Reflection; using System.Threading.Tasks; namespace NSpec.Domain @@ -23,6 +22,11 @@ public override bool IsAsync get { return true; } } + public override MethodInfo BodyMethodInfo + { + get { return asyncAction.GetMethodInfo(); } + } + /* No need for the following: * Async lambda expressions cannot be converted to expression trees diff --git a/sln/src/NSpec/Domain/ClassContext.cs b/sln/src/NSpec/Domain/ClassContext.cs index 9d4d0f0a..cd0e8e08 100644 --- a/sln/src/NSpec/Domain/ClassContext.cs +++ b/sln/src/NSpec/Domain/ClassContext.cs @@ -155,7 +155,7 @@ void AddFailingExample(Exception targetEx) this.AddExample(failingExample); } - public override void Run(Formatters.ILiveFormatter formatter, bool failFast, nspec instance = null) + public override void Run(Formatters.ILiveFormatter formatter, bool failFast, nspec instance = null, bool recurse = true) { if (cantCreateInstance) { @@ -165,7 +165,7 @@ public override void Run(Formatters.ILiveFormatter formatter, bool failFast, nsp } else { - base.Run(formatter, failFast, instance); + base.Run(formatter, failFast, instance, recurse); } } diff --git a/sln/src/NSpec/Domain/Context.cs b/sln/src/NSpec/Domain/Context.cs index 5ae36bca..2cad7d6b 100644 --- a/sln/src/NSpec/Domain/Context.cs +++ b/sln/src/NSpec/Domain/Context.cs @@ -232,7 +232,7 @@ public void AddContext(Context child) /// Here all contexts and all their examples are run, collecting distinct exceptions /// from context itself (befores/ acts/ it/ afters), beforeAll, afterAll. /// - public virtual void Run(ILiveFormatter formatter, bool failFast, nspec instance = null) + public virtual void Run(ILiveFormatter formatter, bool failFast, nspec instance = null, bool recurse = true) { if (failFast && Parent.HasAnyFailures()) return; @@ -266,7 +266,10 @@ public virtual void Run(ILiveFormatter formatter, bool failFast, nspec instance if (example.HasRun) formatter.Write(example, Level); } - Contexts.Do(c => c.Run(formatter, failFast, nspec)); + if (recurse) + { + Contexts.Do(c => c.Run(formatter, failFast, nspec)); + } if (runBeforeAfterAll) RunAndHandleException(RunAfterAll, nspec, ref ExceptionAfterAll); } @@ -279,12 +282,12 @@ public virtual void Run(ILiveFormatter formatter, bool failFast, nspec instance /// on examples, giving priority to exceptions from: inherithed beforeAll, beforeAll, /// context (befores/ acts/ it/ afters), afterAll, inherithed afterAll. /// - public virtual void AssignExceptions() + public virtual void AssignExceptions(bool recurse = true) { - AssignExceptions(null, null); + AssignExceptions(null, null, recurse); } - protected virtual void AssignExceptions(Exception inheritedBeforeAllException, Exception inheritedAfterAllException) + protected virtual void AssignExceptions(Exception inheritedBeforeAllException, Exception inheritedAfterAllException, bool recurse) { inheritedBeforeAllException = inheritedBeforeAllException ?? ExceptionBeforeAll; inheritedAfterAllException = ExceptionAfterAll ?? inheritedAfterAllException; @@ -304,7 +307,10 @@ protected virtual void AssignExceptions(Exception inheritedBeforeAllException, E } } - Contexts.Do(c => c.AssignExceptions(inheritedBeforeAllException, inheritedAfterAllException)); + if (recurse) + { + Contexts.Do(c => c.AssignExceptions(inheritedBeforeAllException, inheritedAfterAllException, recurse)); + } } public virtual void Build(nspec instance = null) diff --git a/sln/src/NSpec/Domain/ContextSelector.cs b/sln/src/NSpec/Domain/ContextSelector.cs new file mode 100644 index 00000000..bdb36f7c --- /dev/null +++ b/sln/src/NSpec/Domain/ContextSelector.cs @@ -0,0 +1,24 @@ +namespace NSpec.Domain +{ + public class ContextSelector + { + public ContextCollection Contexts { get; private set; } + + public Tags TagsFilter { get; private set; } + + public void Select(string binaryPath, string tagsText) + { + var reflector = new Reflector(binaryPath); + + var finder = new SpecFinder(reflector); + + var conventions = new DefaultConventions(); + + TagsFilter = new Tags().Parse(tagsText); + + var builder = new ContextBuilder(finder, TagsFilter, conventions); + + Contexts = builder.Contexts().Build(); + } + } +} diff --git a/sln/src/NSpec/Domain/Example.cs b/sln/src/NSpec/Domain/Example.cs index 4fc19751..d1ebf91e 100644 --- a/sln/src/NSpec/Domain/Example.cs +++ b/sln/src/NSpec/Domain/Example.cs @@ -1,6 +1,7 @@ using NSpec.Domain.Extensions; using System; using System.Linq.Expressions; +using System.Reflection; namespace NSpec.Domain { @@ -34,6 +35,11 @@ public override bool IsAsync get { return action.IsAsync(); } } + public override MethodInfo BodyMethodInfo + { + get { return action.GetMethodInfo(); } + } + public Example(Expression expr, bool pending = false) : this(Parse(expr), null, expr.Compile(), pending) {} diff --git a/sln/src/NSpec/Domain/ExampleBase.cs b/sln/src/NSpec/Domain/ExampleBase.cs index 01fe5ab4..1e9e08db 100644 --- a/sln/src/NSpec/Domain/ExampleBase.cs +++ b/sln/src/NSpec/Domain/ExampleBase.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Linq.Expressions; +using System.Reflection; using System.Text.RegularExpressions; namespace NSpec.Domain @@ -39,6 +40,8 @@ public static string Parse(Expression exp) public abstract void RunPending(nspec nspec); public abstract bool IsAsync { get; } + public abstract MethodInfo BodyMethodInfo { get; } + public TimeSpan Duration { get; set; } public string CapturedOutput { get; set; } diff --git a/sln/src/NSpec/Domain/MethodExample.cs b/sln/src/NSpec/Domain/MethodExample.cs index 7e5caf84..599cd03f 100644 --- a/sln/src/NSpec/Domain/MethodExample.cs +++ b/sln/src/NSpec/Domain/MethodExample.cs @@ -1,4 +1,3 @@ -using System; using System.Reflection; namespace NSpec.Domain diff --git a/sln/src/NSpec/Domain/MethodExampleBase.cs b/sln/src/NSpec/Domain/MethodExampleBase.cs index 047c2dc8..ad3ab88f 100644 --- a/sln/src/NSpec/Domain/MethodExampleBase.cs +++ b/sln/src/NSpec/Domain/MethodExampleBase.cs @@ -1,10 +1,5 @@ using NSpec.Domain.Extensions; -using System; -using System.Collections.Generic; -using System.Linq; using System.Reflection; -using System.Text; -using System.Threading.Tasks; namespace NSpec.Domain { @@ -27,6 +22,11 @@ public override bool IsAsync get { return method.IsAsync(); } } + public override MethodInfo BodyMethodInfo + { + get { return method; } + } + protected MethodInfo method; } } diff --git a/sln/src/NSpec/Domain/RunnerInvocation.cs b/sln/src/NSpec/Domain/RunnerInvocation.cs index 480b51a5..a27dc0df 100644 --- a/sln/src/NSpec/Domain/RunnerInvocation.cs +++ b/sln/src/NSpec/Domain/RunnerInvocation.cs @@ -6,28 +6,20 @@ public class RunnerInvocation { public ContextCollection Run() { - var reflector = new Reflector(this.dll); + var selector = new ContextSelector(); - var finder = new SpecFinder(reflector); + selector.Select(this.dll, Tags); - var tagsFilter = new Tags().Parse(Tags); - - var builder = new ContextBuilder(finder, tagsFilter, new DefaultConventions()); - - var runner = new ContextRunner(tagsFilter, Formatter, failFast); - - var contexts = builder.Contexts().Build(); - - if(contexts.AnyTaggedWithFocus()) + if (selector.Contexts.AnyTaggedWithFocus()) { - tagsFilter = new Tags().Parse(NSpec.Domain.Tags.Focus); + selector.Select(this.dll, Domain.Tags.Focus); + } - builder = new ContextBuilder(finder, tagsFilter, new DefaultConventions()); + var contexts = selector.Contexts; - runner = new ContextRunner(tagsFilter, Formatter, failFast); + var tagsFilter = selector.TagsFilter; - contexts = builder.Contexts().Build(); - } + var runner = new ContextRunner(tagsFilter, Formatter, failFast); return runner.Run(contexts); } diff --git a/sln/src/NSpec/project.json b/sln/src/NSpec/project.json index bcaf2ec8..0aafc53e 100644 --- a/sln/src/NSpec/project.json +++ b/sln/src/NSpec/project.json @@ -10,6 +10,8 @@ }, "dependencies": { + "Microsoft.Extensions.Testing.Abstractions": "1.0.0-preview2-003121", + "Newtonsoft.Json": "9.0.1" }, "frameworks": { diff --git a/sln/src/NSpecRunner/Program.cs b/sln/src/NSpecRunner/Program.cs index e4cdd5a7..2c09fa24 100644 --- a/sln/src/NSpecRunner/Program.cs +++ b/sln/src/NSpecRunner/Program.cs @@ -40,11 +40,11 @@ static void Main(string[] args) argsTags = args[1]; } - var specDLL = Path.GetFullPath(args[0]); + var specDllPath = Path.GetFullPath(args[0]); var controller = new Controller(); - int failures = controller.Run(specDLL, argsTags, formatterClassName, formatterOptions, failFast); + int failures = controller.RunBatch(specDllPath, argsTags, formatterClassName, formatterOptions, failFast); if (failures > 0) Environment.Exit(1); } diff --git a/sln/test/NSpec.Tests/Api/ApiTestData.cs b/sln/test/NSpec.Tests/Api/ApiTestData.cs new file mode 100644 index 00000000..88bef4ed --- /dev/null +++ b/sln/test/NSpec.Tests/Api/ApiTestData.cs @@ -0,0 +1,312 @@ +using NSpec.Api.Discovery; +using NSpec.Api.Execution; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Reflection; + +namespace NSpec.Tests.Api +{ + public static class ApiTestData + { + public static readonly string testAssemblyPath = + typeof(SampleSpecsApi.PublicPlaceholderClass).GetTypeInfo().Assembly.Location; + + public static readonly IEnumerable allDiscoveredExamples; + + static ApiTestData() + { + string sampleSpecsApiProjPath = Path.Combine(new[] + { + BuildTestDirectoryPath(), + "Samples", + "SampleSpecsApi", + }); + + string descSystemUnderTestFilePath = Path.Combine(new[] + { + sampleSpecsApiProjPath, + "desc_SystemUnderTest.cs", + }); + + string descAsyncSystemUnderTestFilePath = Path.Combine(new[] + { + sampleSpecsApiProjPath, + "desc_AsyncSystemUnderTest.cs", + }); + + var systemUnderTestExampleGroup = + from exm in descSystemUnderTestDiscoveredExamples + select new { Example = exm, SourcePath = descSystemUnderTestFilePath }; + + var asyncSystemUnderTestExampleGroup = + from exm in descAsyncSystemUnderTestDiscoveredExamples + select new { Example = exm, SourcePath = descAsyncSystemUnderTestFilePath }; + + allDiscoveredExamples = systemUnderTestExampleGroup + .Concat(asyncSystemUnderTestExampleGroup) + .Select(item => + { + var example = item.Example; + + // No source code info available for pending tests + if (example.SourceLineNumber != 0) + { + example.SourceFilePath = item.SourcePath; + } + + example.SourceAssembly = testAssemblyPath; + + return example; + }); + + TimeSpan nonZeroDuration = new TimeSpan(1, 2, 3); + + foreach (var exm in allExecutedExamples) + { + if (!exm.Pending) + { + exm.Duration = nonZeroDuration; + } + } + } + + static readonly DiscoveredExample[] descSystemUnderTestDiscoveredExamples = + { + new DiscoveredExample() + { + FullName = "nspec. ParentSpec. method context 1. parent example 1A.", + SourceLineNumber = 19, + Tags = new[] + { + "Tag-1A", + "Tag-1B", + "ParentSpec", + }, + }, + new DiscoveredExample() + { + FullName = "nspec. ParentSpec. method context 1. parent example 1B.", + SourceLineNumber = 21, + Tags = new[] + { + "Tag-1A", + "Tag-1B", + "ParentSpec", + }, + }, + new DiscoveredExample() + { + FullName = "nspec. ParentSpec. method context 2. parent example 2A.", + SourceLineNumber = 26, + Tags = new[] + { + "ParentSpec", + }, + }, + new DiscoveredExample() + { + FullName = "nspec. ParentSpec. ChildSpec. method context 3. child example 3A skipped.", + // No source code info available for pending tests + SourceLineNumber = 0, + Tags = new[] + { + "Tag-Child-example-skipped", + "Tag-Child", + "ChildSpec", + "ParentSpec", + }, + }, + new DiscoveredExample() + { + FullName = "nspec. ParentSpec. ChildSpec. method context 4. child example 4A.", + SourceLineNumber = 42, + Tags = new[] + { + "Tag with underscores", + "Tag-Child", + "ChildSpec", + "ParentSpec", + }, + }, + new DiscoveredExample() + { + FullName = "nspec. ParentSpec. ChildSpec. method context 5. sub context 5-1. child example 5-1A failing.", + SourceLineNumber = 49, + Tags = new[] + { + "Tag-Child", + "ChildSpec", + "ParentSpec", + }, + }, + new DiscoveredExample() + { + FullName = "nspec. ParentSpec. ChildSpec. method context 5. sub context 5-1. child example 5-1B.", + SourceLineNumber = 51, + Tags = new[] + { + "Tag-Child", + "ChildSpec", + "ParentSpec", + }, + }, + new DiscoveredExample() + { + FullName = "nspec. ParentSpec. ChildSpec. method context 5. child example 5A.", + SourceLineNumber = 54, + Tags = new[] + { + "Tag-Child", + "ChildSpec", + "ParentSpec", + }, + }, + new DiscoveredExample() + { + FullName = "nspec. ParentSpec. ChildSpec. it child method example A.", +#if DEBUG + SourceLineNumber = 58, +#endif +#if RELEASE + SourceLineNumber = 59, +#endif + Tags = new[] + { + "Tag-Child", + "ChildSpec", + "ParentSpec", + }, + }, + }; + + static readonly DiscoveredExample[] descAsyncSystemUnderTestDiscoveredExamples = + { + new DiscoveredExample() + { + FullName = "nspec. AsyncSpec. it async method example.", +#if DEBUG + SourceLineNumber = 18, +#endif +#if RELEASE + SourceLineNumber = 19, +#endif + Tags = new[] + { + "AsyncSpec", + }, + }, + new DiscoveredExample() + { + FullName = "nspec. AsyncSpec. method context. async context example.", +#if DEBUG + SourceLineNumber = 27, +#endif +#if RELEASE + SourceLineNumber = 28, +#endif + Tags = new[] + { + "AsyncSpec", + }, + }, + }; + + public static readonly ExecutedExample[] allExecutedExamples = + { + // desc_SystemUnderTest.cs + + new ExecutedExample() + { + FullName = "nspec. ParentSpec. method context 1. parent example 1A.", + Failed = false, + Pending = false, + }, + new ExecutedExample() + { + FullName = "nspec. ParentSpec. method context 1. parent example 1B.", + Failed = false, + Pending = false, + }, + new ExecutedExample() + { + FullName = "nspec. ParentSpec. method context 2. parent example 2A.", + Failed = false, + Pending = false, + }, + new ExecutedExample() + { + FullName = "nspec. ParentSpec. ChildSpec. method context 3. child example 3A skipped.", + Failed = false, + Pending = true, + }, + new ExecutedExample() + { + FullName = "nspec. ParentSpec. ChildSpec. method context 4. child example 4A.", + Failed = false, + Pending = false, + }, + new ExecutedExample() + { + FullName = "nspec. ParentSpec. ChildSpec. method context 5. sub context 5-1. child example 5-1A failing.", + Failed = true, + Pending = false, + ExceptionMessage = "Expected false, but was $True.", + ExceptionStackTrace = "NSpec.AssertionExtensions.ShouldBeFalse(Boolean actual)", + }, + new ExecutedExample() + { + FullName = "nspec. ParentSpec. ChildSpec. method context 5. sub context 5-1. child example 5-1B.", + Failed = false, + Pending = false, + }, + new ExecutedExample() + { + FullName = "nspec. ParentSpec. ChildSpec. method context 5. child example 5A.", + Failed = false, + Pending = false, + }, + new ExecutedExample() + { + FullName = "nspec. ParentSpec. ChildSpec. it child method example A.", + Failed = false, + Pending = false, + }, + + // desc_AsyncSystemUnderTest.cs + + new ExecutedExample() + { + FullName = "nspec. AsyncSpec. it async method example.", + Failed = false, + Pending = false, + }, + new ExecutedExample() + { + FullName = "nspec. AsyncSpec. method context. async context example.", + Failed = false, + Pending = false, + }, + }; + + static string BuildTestDirectoryPath() + { + string thisAssemblyPath = typeof(ApiTestData).GetTypeInfo().Assembly.Location; + + // .NET Framework: go up from test\{Project}\bin\{Config}\{Framework}\{Platform}\{Assembly}.dll + // .NET Core: go up from test\{Project}\bin\{Config}\{Framework}\{Assembly}.dll + string testDirPath = Directory + .GetParent(thisAssemblyPath) +#if NET451 + .Parent +#endif + .Parent + .Parent + .Parent + .Parent.FullName; + + return testDirPath; + } + } +} diff --git a/sln/test/NSpec.Tests/Api/Discovery/describe_ExampleSelector.cs b/sln/test/NSpec.Tests/Api/Discovery/describe_ExampleSelector.cs new file mode 100644 index 00000000..008e2628 --- /dev/null +++ b/sln/test/NSpec.Tests/Api/Discovery/describe_ExampleSelector.cs @@ -0,0 +1,39 @@ +using FluentAssertions; +using NSpec.Api.Discovery; +using NUnit.Framework; +using System.Collections.Generic; + +namespace NSpec.Tests.Api.Discovery +{ + [TestFixture] + [Category("ExampleSelector")] + public class describe_ExampleSelector + { + ExampleSelector selector; + + IEnumerable actuals; + + readonly string testAssemblyPath; + + public describe_ExampleSelector() + { + testAssemblyPath = ApiTestData.testAssemblyPath; + } + + [SetUp] + public void setup() + { + selector = new ExampleSelector(testAssemblyPath); + + actuals = selector.Select(); + } + + [Test] + public void it_should_return_discovered_examples() + { + var expecteds = ApiTestData.allDiscoveredExamples; + + actuals.ShouldBeEquivalentTo(expecteds); + } + } +} diff --git a/sln/test/NSpec.Tests/Api/Execution/describe_ExampleRunner.cs b/sln/test/NSpec.Tests/Api/Execution/describe_ExampleRunner.cs new file mode 100644 index 00000000..6c45eb7a --- /dev/null +++ b/sln/test/NSpec.Tests/Api/Execution/describe_ExampleRunner.cs @@ -0,0 +1,178 @@ +using FluentAssertions; +using FluentAssertions.Equivalency; +using NSpec.Api.Discovery; +using NSpec.Api.Execution; +using NUnit.Framework; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace NSpec.Tests.Api.Execution +{ + [TestFixture] + [Category("ExampleRunner")] + public abstract class describe_ExampleRunner + { + protected ExampleRunner runner; + + protected IEnumerable runningTestNames; + protected List actualDiscoveredExamples; + protected List actualExecutedExamples; + + protected readonly string testAssemblyPath = ApiTestData.testAssemblyPath; + + [SetUp] + public virtual void setup() + { + actualDiscoveredExamples = new List(); + actualExecutedExamples = new List(); + + runner = new ExampleRunner(testAssemblyPath, OnDiscovered, OnExecuted); + } + + void OnDiscovered(DiscoveredExample example) + { + actualDiscoveredExamples.Add(example); + } + + void OnExecuted(ExecutedExample example) + { + actualExecutedExamples.Add(example); + } + } + + public static class ExampleRunnerAssertionExtensions + { + public static EquivalencyAssertionOptions> ExpectPartialStackTrace( + this EquivalencyAssertionOptions> opts) + { + opts.Using(ctx => + { + string actual = ctx.Subject; + string expected = ctx.Expectation; + + if (expected == null) + { + actual.Should().BeNull(); + } + else + { + actual.Should().NotBeNull().And.Contain(expected); + } + }) + .When(subj => subj.SelectedMemberPath.EndsWith(".ExceptionStackTrace", StringComparison.Ordinal)); + + return opts; + } + + public static EquivalencyAssertionOptions> ExpectSomeDuration( + this EquivalencyAssertionOptions> opts) + { + opts.Using(ctx => + { + TimeSpan actual = ctx.Subject; + TimeSpan expected = ctx.Expectation; + + if (expected == TimeSpan.Zero) + { + actual.Should().Be(TimeSpan.Zero); + } + else + { + actual.Should().BeGreaterThan(TimeSpan.Zero); + } + }) + .When(subj => subj.SelectedMemberPath.EndsWith(".Duration", StringComparison.Ordinal)); + + return opts; + } + } + + public class when_starting_all_examples : describe_ExampleRunner + { + public override void setup() + { + base.setup(); + + runningTestNames = ApiTestData.allDiscoveredExamples + .Select(exm => exm.FullName); + + runner.Start(runningTestNames); + } + + [Test] + public void it_should_discover_all_examples() + { + var expecteds = ApiTestData.allDiscoveredExamples; + + actualDiscoveredExamples.ShouldBeEquivalentTo(expecteds); + } + + [Test] + public void it_should_execute_all_examples() + { + var expecteds = ApiTestData.allExecutedExamples; + + actualExecutedExamples.ShouldBeEquivalentTo(expecteds, opts => opts + .ExpectPartialStackTrace() + .ExpectSomeDuration()); + } + } + + public class when_starting_some_examples : describe_ExampleRunner + { + readonly int[] requestedIndexes = + { + // method_context_1 + 1, + // method_context_3 + 3, + // method_context_5. sub context 5-1 + 5, + // ChildSpec + 8, + }; + readonly int[] runIndexes = + { + // method_context_1 + 0, 1, + // method_context_3 + 3, + // method_context_5. sub context 5-1 + 5, 6, + // ChildSpec + 8, + }; + + public override void setup() + { + base.setup(); + + runningTestNames = ApiTestData.allDiscoveredExamples + .Where((_, index) => requestedIndexes.Contains(index)) + .Select(exm => exm.FullName); + + runner.Start(runningTestNames); + } + + [Test] + public void it_should_discover_sibling_examples() + { + var expecteds = ApiTestData.allDiscoveredExamples + .Where((_, index) => runIndexes.Contains(index)); + + actualDiscoveredExamples.ShouldBeEquivalentTo(expecteds); + } + + [Test] + public void it_should_execute_sibling_examples() + { + var expecteds = ApiTestData.allExecutedExamples + .Where((_, index) => runIndexes.Contains(index)); + + actualExecutedExamples.ShouldBeEquivalentTo(expecteds, opts => opts + .ExpectPartialStackTrace() + .ExpectSomeDuration()); + } + } +} diff --git a/sln/test/NSpec.Tests/ExampleBaseWrap.cs b/sln/test/NSpec.Tests/ExampleBaseWrap.cs index 31228d2b..b16e1d83 100644 --- a/sln/test/NSpec.Tests/ExampleBaseWrap.cs +++ b/sln/test/NSpec.Tests/ExampleBaseWrap.cs @@ -1,5 +1,6 @@ using NSpec.Domain; using System; +using System.Reflection; namespace NSpec.Tests { @@ -15,7 +16,6 @@ public ExampleBaseWrap(string name) } public ExampleBaseWrap() - : base() { } @@ -33,5 +33,10 @@ public override bool IsAsync { get { throw new NotImplementedException(); } } + + public override MethodInfo BodyMethodInfo + { + get { throw new NotImplementedException(); } + } } } diff --git a/sln/test/NSpec.Tests/project.json b/sln/test/NSpec.Tests/project.json index 1c4691e4..285c9cc5 100644 --- a/sln/test/NSpec.Tests/project.json +++ b/sln/test/NSpec.Tests/project.json @@ -10,7 +10,7 @@ }, "dependencies": { - "dotnet-test-nunit": "3.4.0-beta-1", + "dotnet-test-nunit": "3.4.0-beta-3", "FluentAssertions": "4.13.1", "Moq": "4.6.36-alpha", "NSpec": { @@ -20,6 +20,9 @@ "SampleSpecs": { "target": "project" }, + "SampleSpecsApi": { + "target": "project" + }, "SampleSpecsFocus": { "target": "project" } diff --git a/sln/test/Samples/DotNetTestSample/README.md b/sln/test/Samples/DotNetTestSample/README.md index 18f90521..a8518129 100644 --- a/sln/test/Samples/DotNetTestSample/README.md +++ b/sln/test/Samples/DotNetTestSample/README.md @@ -7,6 +7,9 @@ Highlights: - Test project targets both .NET Core App 1.0.0 and .NET Framework 4.5.2 - Test project is a .NET Core console application with its `buildOptions.emitEntryPoint` property stripped from `project.json` - Test project `project.json` has a `testRunner` property set to `nspec` +- Test project targeting `netcoreapp1.0` takes an explicit dependency on `"Microsoft.Extensions.Testing.Abstractions": "1.0.0-preview2-003121"`, +due to an issue between .NET Core CLI Tools Preview 2 and NuGet v3 that will not get solved (as *project.json* is being deprecated in favour of MSBuild) +- Test project targeting `net451` takes an explicit dependency on `"Microsoft.DiaSymReader.Native": "1.4.2"` and `"Microsoft.NETCore.Platforms": "1.1.0"` for similar reasons - NSpec is installed into test project as a NuGet package, version 2.0.0 minimum - dotnet-test-nspec runner too is installed into test project as a NuGet package - Tests can be run from command line through *dotnet test*, as in: @@ -17,6 +20,6 @@ Highlights: > dotnet test ``` -- Tests cannot be run yet from Visual Studio Test Explorer, until dotnet-test-nspec does not support VS integration. +- Tests can be run from Visual Studio Test Explorer, too - To keep consistency with other samples, solution has the typical directory structure found in ASP.NET Core project template, -where all application projects are under a `src\` directory, while test projects are in a `test\` directory. +where all application projects are under a `src\` directory, while test projects are in a `test\` directory diff --git a/sln/test/Samples/DotNetTestSample/test/LibrarySpecs/LibrarySpecs.xproj b/sln/test/Samples/DotNetTestSample/test/LibrarySpecs/LibrarySpecs.xproj index e844afdd..5c3365cf 100644 --- a/sln/test/Samples/DotNetTestSample/test/LibrarySpecs/LibrarySpecs.xproj +++ b/sln/test/Samples/DotNetTestSample/test/LibrarySpecs/LibrarySpecs.xproj @@ -4,7 +4,6 @@ 14.0 $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) - 6949774e-2773-47d1-883f-f7b2f0c6628c @@ -13,9 +12,11 @@ .\bin\ v4.5 - 2.0 + + + - + \ No newline at end of file diff --git a/sln/test/Samples/DotNetTestSample/test/LibrarySpecs/project.json b/sln/test/Samples/DotNetTestSample/test/LibrarySpecs/project.json index 91fa529c..071715ba 100644 --- a/sln/test/Samples/DotNetTestSample/test/LibrarySpecs/project.json +++ b/sln/test/Samples/DotNetTestSample/test/LibrarySpecs/project.json @@ -4,11 +4,11 @@ "testRunner": "nspec", "dependencies": { - "dotnet-test-nspec": "0.1.1", + "dotnet-test-nspec": "0.1.1-dev-71", "LibraryUnderTest": { "target": "project" }, - "NSpec": "2.0.1", + "NSpec": "2.0.1-dev-71", "Shouldly": "2.8.2" }, @@ -18,6 +18,7 @@ "portable-net45+win8" ], "dependencies": { + "Microsoft.Extensions.Testing.Abstractions": "1.0.0-preview2-003121", "Microsoft.NETCore.App": { "type": "platform", "version": "1.0.0" @@ -25,6 +26,10 @@ } }, "net451": { + "dependencies": { + "Microsoft.DiaSymReader.Native": "1.4.2", + "Microsoft.NETCore.Platforms": "1.1.0" + } } } } diff --git a/sln/test/Samples/SampleSpecsApi/Properties/AssemblyInfo.cs b/sln/test/Samples/SampleSpecsApi/Properties/AssemblyInfo.cs new file mode 100644 index 00000000..38f08e0f --- /dev/null +++ b/sln/test/Samples/SampleSpecsApi/Properties/AssemblyInfo.cs @@ -0,0 +1,19 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("SampleSpecsApi")] +[assembly: AssemblyTrademark("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("70692496-9329-4145-899f-5b141c590326")] diff --git a/sln/test/Samples/SampleSpecsApi/SampleSpecsApi.xproj b/sln/test/Samples/SampleSpecsApi/SampleSpecsApi.xproj new file mode 100644 index 00000000..01745ccd --- /dev/null +++ b/sln/test/Samples/SampleSpecsApi/SampleSpecsApi.xproj @@ -0,0 +1,21 @@ + + + + 14.0 + $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) + + + + + 70692496-9329-4145-899f-5b141c590326 + SampleSpecsApi + .\obj + .\bin\ + v4.5 + + + + 2.0 + + + diff --git a/sln/test/Samples/SampleSpecsApi/SampleSystem/AsyncSystemUnderTest.cs b/sln/test/Samples/SampleSpecsApi/SampleSystem/AsyncSystemUnderTest.cs new file mode 100644 index 00000000..e351e868 --- /dev/null +++ b/sln/test/Samples/SampleSpecsApi/SampleSystem/AsyncSystemUnderTest.cs @@ -0,0 +1,12 @@ +using System.Threading.Tasks; + +namespace SampleSpecsApi.SampleSystem +{ + public class AsyncSystemUnderTest + { + public async Task IsAlwaysTrueAsync() + { + return await Task.Run(() => true); + } + } +} diff --git a/sln/test/Samples/SampleSpecsApi/SampleSystem/SystemUnderTest.cs b/sln/test/Samples/SampleSpecsApi/SampleSystem/SystemUnderTest.cs new file mode 100644 index 00000000..c3f898d4 --- /dev/null +++ b/sln/test/Samples/SampleSpecsApi/SampleSystem/SystemUnderTest.cs @@ -0,0 +1,10 @@ +namespace SampleSpecsApi.SampleSystem +{ + public class SystemUnderTest + { + public bool IsAlwaysTrue() + { + return true; + } + } +} diff --git a/sln/test/Samples/SampleSpecsApi/desc_AsyncSystemUnderTest.cs b/sln/test/Samples/SampleSpecsApi/desc_AsyncSystemUnderTest.cs new file mode 100644 index 00000000..914a6cef --- /dev/null +++ b/sln/test/Samples/SampleSpecsApi/desc_AsyncSystemUnderTest.cs @@ -0,0 +1,38 @@ +using NSpec; +using SampleSpecsApi.SampleSystem; +using System.Threading.Tasks; + +namespace SampleSpecsApi +{ + // Do not move the following spec classes around, to avoid rewriting line numbers. This should be stuck at line nr. 7 + public class AsyncSpec : nspec + { + protected AsyncSystemUnderTest systemUnderTest; + + void before_each() + { + systemUnderTest = new AsyncSystemUnderTest(); + } + + async Task it_async_method_example() + { // # 18 + bool actual = await systemUnderTest.IsAlwaysTrueAsync(); + + actual.ShouldBeTrue(); + } // # 22 + + void method_context() + { // # 25 + itAsync["async context example"] = async () => + { // # 27 + bool actual = await systemUnderTest.IsAlwaysTrueAsync(); + + actual.ShouldBeTrue(); + }; // # 31 + } // # 32 + } + + // Do not move the preceding spec classes around, to avoid rewriting line numbers + + // TODO add sample with `itAsync[...] = expectAsync<...>();` : is it possible to get source file path and line number? +} diff --git a/sln/test/Samples/SampleSpecsApi/desc_SystemUnderTest.cs b/sln/test/Samples/SampleSpecsApi/desc_SystemUnderTest.cs new file mode 100644 index 00000000..55dff4b1 --- /dev/null +++ b/sln/test/Samples/SampleSpecsApi/desc_SystemUnderTest.cs @@ -0,0 +1,68 @@ +using NSpec; +using SampleSpecsApi.SampleSystem; + +namespace SampleSpecsApi +{ + // Do not move the following spec classes around, to avoid rewriting line numbers. This should be stuck at line nr. 6 + class ParentSpec : nspec + { + protected SystemUnderTest systemUnderTest; + + void before_each() + { + systemUnderTest = new SystemUnderTest(); + } + + [Tag("Tag-1A Tag-1B")] + void method_context_1() + { // # 18 + it["parent example 1A"] = () => systemUnderTest.IsAlwaysTrue().ShouldBeTrue(); // # 19 + + it["parent example 1B"] = () => systemUnderTest.IsAlwaysTrue().ShouldBeTrue(); // # 21 + } // # 22 + + void method_context_2() + { // # 25 + it["parent example 2A"] = () => systemUnderTest.IsAlwaysTrue().ShouldBeTrue(); // # 26 + } // # 27 + } + + [Tag("Tag-Child")] + class ChildSpec : ParentSpec + { + [Tag("Tag-Child-example-skipped")] + void method_context_3() + { // # 35 + it["child example 3A skipped"] = todo; // # 36 + } // # 37 + + [Tag("Tag_with_underscores")] + void method_context_4() + { // # 41 + it["child example 4A"] = () => systemUnderTest.IsAlwaysTrue().ShouldBeTrue(); // # 42 + } // # 43 + + void method_context_5() + { // # 46 + context["sub context 5-1"] = () => + { + it["child example 5-1A failing"] = () => systemUnderTest.IsAlwaysTrue().ShouldBeFalse(); // # 49 + + it["child example 5-1B"] = () => systemUnderTest.IsAlwaysTrue().ShouldBeTrue(); // # 51 + }; + + it["child example 5A"] = () => systemUnderTest.IsAlwaysTrue().ShouldBeTrue(); // # 54 + } // # 55 + + void it_child_method_example_A() + { // # 58 + systemUnderTest.IsAlwaysTrue().ShouldBeTrue(); + } + } + + // Do not move the preceding spec classes around, to avoid rewriting line numbers + + public class PublicPlaceholderClass + { + } +} diff --git a/sln/test/Samples/SampleSpecsApi/project.json b/sln/test/Samples/SampleSpecsApi/project.json new file mode 100644 index 00000000..2fcc9f6e --- /dev/null +++ b/sln/test/Samples/SampleSpecsApi/project.json @@ -0,0 +1,19 @@ +{ + "version": "1.0.0-*", + + "dependencies": { + "NSpec": { + "target": "project" + } + }, + + "frameworks": { + "netstandard1.6": { + "dependencies": { + "NETStandard.Library": "1.6.0" + } + }, + "net451": { + } + } +}