From 3462e43eea3fa7c57b4fccefcfe2f45902080da7 Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Wed, 8 Feb 2017 12:30:57 +0100 Subject: [PATCH 01/26] feat(controller): add example discovery for external runners --- sln/src/NSpec/Api/Controller.cs | 15 +++++- .../NSpec/Api/Discovery/DiscoveredExample.cs | 31 +++++++++++++ .../NSpec/Api/Discovery/ExampleSelector.cs | 46 +++++++++++++++++++ sln/src/NSpec/Domain/ContextSelector.cs | 24 ++++++++++ sln/src/NSpec/Domain/RunnerInvocation.cs | 24 ++++------ sln/src/NSpec/project.json | 1 + 6 files changed, 124 insertions(+), 17 deletions(-) create mode 100644 sln/src/NSpec/Api/Discovery/DiscoveredExample.cs create mode 100644 sln/src/NSpec/Api/Discovery/ExampleSelector.cs create mode 100644 sln/src/NSpec/Domain/ContextSelector.cs diff --git a/sln/src/NSpec/Api/Controller.cs b/sln/src/NSpec/Api/Controller.cs index 1d3d3ef6..d115b51c 100644 --- a/sln/src/NSpec/Api/Controller.cs +++ b/sln/src/NSpec/Api/Controller.cs @@ -1,4 +1,6 @@ -using NSpec.Domain; +using Newtonsoft.Json; +using NSpec.Api.Discovery; +using NSpec.Domain; using NSpec.Domain.Formatters; using System; using System.Collections.Generic; @@ -25,6 +27,17 @@ public int Run( return nrOfFailures; } + public string List(string testAssemblyPath) + { + var exampleSelector = new ExampleSelector(); + + var discoveredExamples = exampleSelector.Select(testAssemblyPath); + + string serialized = JsonConvert.SerializeObject(discoveredExamples); + + return serialized; + } + /// /// Find an implementation of IFormatter with the given class name /// 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/ExampleSelector.cs b/sln/src/NSpec/Api/Discovery/ExampleSelector.cs new file mode 100644 index 00000000..c69bfe90 --- /dev/null +++ b/sln/src/NSpec/Api/Discovery/ExampleSelector.cs @@ -0,0 +1,46 @@ +using NSpec.Domain; +using System; +using System.Collections.Generic; +using System.Linq; + +namespace NSpec.Api.Discovery +{ + public class ExampleSelector + { + public IEnumerable Select(string testAssemblyPath) + { + 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 discoveredExample = new DiscoveredExample() + { + FullName = example.FullName(), + SourceAssembly = binaryPath, + // TODO complete with source information + SourceFilePath = String.Empty, + SourceLineNumber = 0, + Tags = example.Tags + .Select(tag => tag.Replace("_", " ")) + .ToArray(), + }; + + return discoveredExample; + } + } +} 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/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..edc70c3f 100644 --- a/sln/src/NSpec/project.json +++ b/sln/src/NSpec/project.json @@ -10,6 +10,7 @@ }, "dependencies": { + "Newtonsoft.Json": "9.0.1" }, "frameworks": { From 451a6cfddc639fd474c4c203e15528efc31c3899 Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Wed, 8 Feb 2017 21:47:01 +0100 Subject: [PATCH 02/26] chore(deps): upgrade dotnet-test-nunit to 3.4.0-beta-3 --- sln/Build-Package.ps1 | 2 +- sln/test/NSpec.Tests/project.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sln/Build-Package.ps1 b/sln/Build-Package.ps1 index 4e1c0621..8ebd5373 100644 --- a/sln/Build-Package.ps1 +++ b/sln/Build-Package.ps1 @@ -97,7 +97,7 @@ function BuildVersioningOptions() { @( "sln\test\NSpec.Tests" -) | ForEach-Object { Exec { & dotnet test -c Release $_ } } +) | ForEach-Object { Exec { & dotnet test -c Release --labels Off $_ } } # Package diff --git a/sln/test/NSpec.Tests/project.json b/sln/test/NSpec.Tests/project.json index 1c4691e4..ac50e513 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": { From 0046781f568cb28d38c7b0431fc5217eeded9ce3 Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Wed, 8 Feb 2017 23:43:08 +0100 Subject: [PATCH 03/26] fix(tools): remove nunit --labels option --- sln/Build-Package.ps1 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sln/Build-Package.ps1 b/sln/Build-Package.ps1 index 8ebd5373..4e1c0621 100644 --- a/sln/Build-Package.ps1 +++ b/sln/Build-Package.ps1 @@ -97,7 +97,7 @@ function BuildVersioningOptions() { @( "sln\test\NSpec.Tests" -) | ForEach-Object { Exec { & dotnet test -c Release --labels Off $_ } } +) | ForEach-Object { Exec { & dotnet test -c Release $_ } } # Package From da2894674ccfcaaf48f47c284b371de5437c64d6 Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Fri, 10 Feb 2017 00:30:09 +0100 Subject: [PATCH 04/26] fix(samples): avoid Microsoft.Extensions.Testing.Abstractions not found error --- sln/test/Samples/DotNetTestSample/README.md | 2 ++ .../Samples/DotNetTestSample/test/LibrarySpecs/project.json | 5 +++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/sln/test/Samples/DotNetTestSample/README.md b/sln/test/Samples/DotNetTestSample/README.md index 18f90521..e6e935df 100644 --- a/sln/test/Samples/DotNetTestSample/README.md +++ b/sln/test/Samples/DotNetTestSample/README.md @@ -7,6 +7,8 @@ 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 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 that will not get solved (as *project.json* is being deprecated in favour of MSBuild) - 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: diff --git a/sln/test/Samples/DotNetTestSample/test/LibrarySpecs/project.json b/sln/test/Samples/DotNetTestSample/test/LibrarySpecs/project.json index 91fa529c..1500f599 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.0-dev-56", "LibraryUnderTest": { "target": "project" }, - "NSpec": "2.0.1", + "NSpec": "2.0.0-dev-54", "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" From 16eca1fd9888ccc7c466f78a2925dbd9c2be5f6a Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Mon, 13 Feb 2017 19:32:56 +0100 Subject: [PATCH 05/26] feat(controller): add example execution for external runners --- sln/src/NSpec/Api/Controller.cs | 28 ++++- sln/src/NSpec/Api/Execution/ExampleRunner.cs | 119 ++++++++++++++++++ .../NSpec/Api/Execution/ExecutedExample.cs | 15 +++ 3 files changed, 161 insertions(+), 1 deletion(-) create mode 100644 sln/src/NSpec/Api/Execution/ExampleRunner.cs create mode 100644 sln/src/NSpec/Api/Execution/ExecutedExample.cs diff --git a/sln/src/NSpec/Api/Controller.cs b/sln/src/NSpec/Api/Controller.cs index d115b51c..e630c3e9 100644 --- a/sln/src/NSpec/Api/Controller.cs +++ b/sln/src/NSpec/Api/Controller.cs @@ -1,5 +1,6 @@ using Newtonsoft.Json; using NSpec.Api.Discovery; +using NSpec.Api.Execution; using NSpec.Domain; using NSpec.Domain.Formatters; using System; @@ -38,13 +39,38 @@ public string List(string testAssemblyPath) return serialized; } + public void Run( + string testAssemblyPath, + IEnumerable exampleFullNames, + Action onExampleStarted, + Action onExampleCompleted) + { + Action onDiscovered = example => + { + string serialized = JsonConvert.SerializeObject(example); + + onExampleStarted(serialized); + }; + + Action onExecuted = example => + { + string serialized = JsonConvert.SerializeObject(example); + + onExampleCompleted(serialized); + }; + + var exampleRunner = new ExampleRunner(testAssemblyPath, onDiscovered, onExecuted); + + exampleRunner.Start(exampleFullNames); + } + /// /// Find an implementation of IFormatter with the given class name /// /// /// /// - private static IFormatter FindFormatter(string formatterClassName, IDictionary formatterOptions) + static IFormatter FindFormatter(string formatterClassName, IDictionary formatterOptions) { // Default formatter is the standard console formatter if (string.IsNullOrEmpty(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..ad523921 --- /dev/null +++ b/sln/src/NSpec/Api/Execution/ExampleRunner.cs @@ -0,0 +1,119 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using NSpec.Api.Discovery; +using NSpec.Domain; +using NSpec.Domain.Formatters; + +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; + } + + 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; + + Func isSelected = + exm => selectedNames.Contains(exm.FullName()); + + var selectedContexts = contexts + .Where(ctx => ctx.Examples.Any(isSelected)); + + 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) + { + throw new InvalidOperationException("This method should have never been called"); + } + + 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(this, false, instance); + + context.AssignExceptions(); + } + + readonly string testAssemblyPath; + readonly Action onDiscovered; + readonly Action onExecuted; + + // TODO Extract from ExampleSelector.MapToDiscovered + static DiscoveredExample MapToDiscovered(ExampleBase example, string binaryPath) + { + var discoveredExample = new DiscoveredExample() + { + FullName = example.FullName(), + SourceAssembly = binaryPath, + // TODO complete with source information + SourceFilePath = String.Empty, + SourceLineNumber = 0, + Tags = example.Tags + .Select(tag => tag.Replace("_", " ")) + .ToArray(), + }; + + return discoveredExample; + } + + static ExecutedExample MapToExecuted(ExampleBase example) + { + var executedExample = new ExecutedExample() + { + FullName = example.FullName(), + Pending = example.Pending, + Failed = example.Failed(), + }; + + 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..e0641f0e --- /dev/null +++ b/sln/src/NSpec/Api/Execution/ExecutedExample.cs @@ -0,0 +1,15 @@ +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; } + } +} From db87e3de497cab7be7fe9f0b3a2b4f4d8331f1b1 Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Mon, 13 Feb 2017 19:47:49 +0100 Subject: [PATCH 06/26] fix(controller): avoid clashes in Run method names --- sln/src/NSpec/Api/Controller.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sln/src/NSpec/Api/Controller.cs b/sln/src/NSpec/Api/Controller.cs index e630c3e9..9c7989e2 100644 --- a/sln/src/NSpec/Api/Controller.cs +++ b/sln/src/NSpec/Api/Controller.cs @@ -39,7 +39,7 @@ public string List(string testAssemblyPath) return serialized; } - public void Run( + public void Execute( string testAssemblyPath, IEnumerable exampleFullNames, Action onExampleStarted, From 30038bdb3b92e5a7891b624b2d721da36012ab15 Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Thu, 16 Feb 2017 16:44:38 +0100 Subject: [PATCH 07/26] test(api): unit test Api.Discovery.ExampleSelector --- sln/NSpec.sln | 7 ++ sln/test/NSpec.Tests/Api/ApiTestData.cs | 107 ++++++++++++++++++ .../Api/Discovery/describe_ExampleSelector.cs | 39 +++++++ sln/test/NSpec.Tests/project.json | 3 + .../SampleSpecsApi/Properties/AssemblyInfo.cs | 19 ++++ .../SampleSpecsApi/SampleSpecsApi.xproj | 21 ++++ .../SampleSystem/SystemUnderTest.cs | 10 ++ .../SampleSpecsApi/desc_SystemUnderTest.cs | 61 ++++++++++ sln/test/Samples/SampleSpecsApi/project.json | 19 ++++ 9 files changed, 286 insertions(+) create mode 100644 sln/test/NSpec.Tests/Api/ApiTestData.cs create mode 100644 sln/test/NSpec.Tests/Api/Discovery/describe_ExampleSelector.cs create mode 100644 sln/test/Samples/SampleSpecsApi/Properties/AssemblyInfo.cs create mode 100644 sln/test/Samples/SampleSpecsApi/SampleSpecsApi.xproj create mode 100644 sln/test/Samples/SampleSpecsApi/SampleSystem/SystemUnderTest.cs create mode 100644 sln/test/Samples/SampleSpecsApi/desc_SystemUnderTest.cs create mode 100644 sln/test/Samples/SampleSpecsApi/project.json 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/test/NSpec.Tests/Api/ApiTestData.cs b/sln/test/NSpec.Tests/Api/ApiTestData.cs new file mode 100644 index 00000000..733eb7f0 --- /dev/null +++ b/sln/test/NSpec.Tests/Api/ApiTestData.cs @@ -0,0 +1,107 @@ +using NSpec.Api.Discovery; +using System.Reflection; + +namespace NSpec.Tests.Api +{ + public static class ApiTestData + { + static ApiTestData() + { + foreach (var exm in allDiscoveredExamples) + { + exm.SourceAssembly = testAssemblyPath; + } + } + + public static readonly string testAssemblyPath = + typeof(SampleSpecsApi.DummyPublicClass).GetTypeInfo().Assembly.Location; + + public static readonly DiscoveredExample[] allDiscoveredExamples = + { + new DiscoveredExample() + { + FullName = "nspec. ParentSpec. method context 1. parent example 1A.", + SourceFilePath = "", + SourceLineNumber = 0, + Tags = new[] + { + "Tag-1A", + "Tag-1B", + "ParentSpec", + }, + }, + new DiscoveredExample() + { + FullName = "nspec. ParentSpec. method context 1. parent example 1B.", + SourceFilePath = "", + SourceLineNumber = 0, + Tags = new[] + { + "Tag-1A", + "Tag-1B", + "ParentSpec", + }, + }, + new DiscoveredExample() + { + FullName = "nspec. ParentSpec. method context 2. parent example 2A.", + SourceFilePath = "", + SourceLineNumber = 0, + Tags = new[] + { + "ParentSpec", + }, + }, + new DiscoveredExample() + { + FullName = "nspec. ParentSpec. ChildSpec. method context 3. child example 3A skipped.", + SourceFilePath = "", + SourceLineNumber = 0, + Tags = new[] + { + "Tag-Child-example-skipped", + "Tag-Child", + "ChildSpec", + "ParentSpec", + }, + }, + new DiscoveredExample() + { + FullName = "nspec. ParentSpec. ChildSpec. method context 4. child example 4A.", + SourceFilePath = "", + SourceLineNumber = 0, + 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.", + SourceFilePath = "", + SourceLineNumber = 0, + Tags = new[] + { + "Tag-Child", + "ChildSpec", + "ParentSpec", + }, + }, + new DiscoveredExample() + { + FullName = "nspec. ParentSpec. ChildSpec. method context 5. sub context 5-1. child example 5-1B.", + SourceFilePath = "", + SourceLineNumber = 0, + Tags = new[] + { + "Tag-Child", + "ChildSpec", + "ParentSpec", + }, + }, + }; + } +} 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..7e62eb59 --- /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(); + + actuals = selector.Select(testAssemblyPath); + } + + [Test] + public void it_should_return_discovered_examples() + { + var expecteds = ApiTestData.allDiscoveredExamples; + + actuals.ShouldBeEquivalentTo(expecteds); + } + } +} diff --git a/sln/test/NSpec.Tests/project.json b/sln/test/NSpec.Tests/project.json index ac50e513..285c9cc5 100644 --- a/sln/test/NSpec.Tests/project.json +++ b/sln/test/NSpec.Tests/project.json @@ -20,6 +20,9 @@ "SampleSpecs": { "target": "project" }, + "SampleSpecsApi": { + "target": "project" + }, "SampleSpecsFocus": { "target": "project" } 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/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_SystemUnderTest.cs b/sln/test/Samples/SampleSpecsApi/desc_SystemUnderTest.cs new file mode 100644 index 00000000..e739c002 --- /dev/null +++ b/sln/test/Samples/SampleSpecsApi/desc_SystemUnderTest.cs @@ -0,0 +1,61 @@ +using NSpec; +using SampleSpecsApi.SampleSystem; +// Do not move the following spec classes around, to avoid rewriting line numbers. This should be line nr.3 + +namespace SampleSpecsApi +{ + 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 + }; + } // # 53 + } + + // Do not move the preceding spec classes around, to avoid rewriting line numbers + + public class DummyPublicClass + { + } +} 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": { + } + } +} From b8abeca3ef8a93931e447cf63a4d895088cca3a1 Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Thu, 16 Feb 2017 20:18:51 +0100 Subject: [PATCH 08/26] test(api): test NSpec.Api.Execution.ExampleRunner --- sln/src/NSpec/Api/Execution/ExampleRunner.cs | 10 +- sln/test/NSpec.Tests/Api/ApiTestData.cs | 51 ++++++- .../Api/Execution/describe_ExampleRunner.cs | 131 ++++++++++++++++++ .../SampleSpecsApi/desc_SystemUnderTest.cs | 4 +- 4 files changed, 192 insertions(+), 4 deletions(-) create mode 100644 sln/test/NSpec.Tests/Api/Execution/describe_ExampleRunner.cs diff --git a/sln/src/NSpec/Api/Execution/ExampleRunner.cs b/sln/src/NSpec/Api/Execution/ExampleRunner.cs index ad523921..8d8c8ac6 100644 --- a/sln/src/NSpec/Api/Execution/ExampleRunner.cs +++ b/sln/src/NSpec/Api/Execution/ExampleRunner.cs @@ -32,11 +32,19 @@ public void Start( var contexts = selector.Contexts; + var allExamples = contexts.SelectMany(ctx => ctx.AllExamples()); + + var selectedExamples = allExamples.Where(exm => selectedNames.Contains(exm.FullName())); + + var selectedContexts = selectedExamples.Select(exm => exm.Context).Distinct(); + + /* Func isSelected = exm => selectedNames.Contains(exm.FullName()); var selectedContexts = contexts .Where(ctx => ctx.Examples.Any(isSelected)); + */ foreach (var context in selectedContexts) { @@ -61,7 +69,7 @@ public void Write(ExampleBase example, int level) public void Write(Context context) { - throw new InvalidOperationException("This method should have never been called"); + // nothing to do } void RunContext(Context context) diff --git a/sln/test/NSpec.Tests/Api/ApiTestData.cs b/sln/test/NSpec.Tests/Api/ApiTestData.cs index 733eb7f0..3d19d634 100644 --- a/sln/test/NSpec.Tests/Api/ApiTestData.cs +++ b/sln/test/NSpec.Tests/Api/ApiTestData.cs @@ -1,4 +1,5 @@ using NSpec.Api.Discovery; +using NSpec.Api.Execution; using System.Reflection; namespace NSpec.Tests.Api @@ -14,7 +15,7 @@ static ApiTestData() } public static readonly string testAssemblyPath = - typeof(SampleSpecsApi.DummyPublicClass).GetTypeInfo().Assembly.Location; + typeof(SampleSpecsApi.PublicPlaceholderClass).GetTypeInfo().Assembly.Location; public static readonly DiscoveredExample[] allDiscoveredExamples = { @@ -103,5 +104,53 @@ static ApiTestData() }, }, }; + + public static readonly ExecutedExample[] allExecutedExamples = + { + 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 = @"SampleSpecsApi\desc_SystemUnderTest.cs:line 49", + }, + new ExecutedExample() + { + FullName = "nspec. ParentSpec. ChildSpec. method context 5. sub context 5-1. child example 5-1B.", + Failed = false, + Pending = false, + }, + }; } } 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..b55e5475 --- /dev/null +++ b/sln/test/NSpec.Tests/Api/Execution/describe_ExampleRunner.cs @@ -0,0 +1,131 @@ +using FluentAssertions; +using FluentAssertions.Equivalency; +using NSpec.Api.Discovery; +using NSpec.Api.Execution; +using NUnit.Framework; +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); + } + + protected EquivalencyAssertionOptions> ExpectPartialStackTrace( + EquivalencyAssertionOptions> opts) + { + opts.Using(ctx => ctx.Subject?.Should().Contain(ctx.Expectation)) + .When(subj => subj.SelectedMemberPath.EndsWith(".ExceptionStackTrace", System.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_examples() + { + var expecteds = ApiTestData.allDiscoveredExamples; + + actualDiscoveredExamples.ShouldBeEquivalentTo(expecteds); + } + + [Test] + public void it_should_execute_examples() + { + var expecteds = ApiTestData.allExecutedExamples; + + actualExecutedExamples.ShouldBeEquivalentTo(expecteds, ExpectPartialStackTrace); + } + } + + 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, + }; + readonly int[] runIndexes = + { + // method_context_1 + 0, 1, + // method_context_3 + 3, + // method_context_5. sub context 5-1 + 5, 6, + }; + + 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_examples() + { + var expecteds = ApiTestData.allDiscoveredExamples + .Where((_, index) => runIndexes.Contains(index)); + + actualDiscoveredExamples.ShouldBeEquivalentTo(expecteds); + } + + [Test] + public void it_should_execute_examples() + { + var expecteds = ApiTestData.allExecutedExamples + .Where((_, index) => runIndexes.Contains(index)); + + actualExecutedExamples.ShouldBeEquivalentTo(expecteds, ExpectPartialStackTrace); + } + } +} diff --git a/sln/test/Samples/SampleSpecsApi/desc_SystemUnderTest.cs b/sln/test/Samples/SampleSpecsApi/desc_SystemUnderTest.cs index e739c002..f690fdd6 100644 --- a/sln/test/Samples/SampleSpecsApi/desc_SystemUnderTest.cs +++ b/sln/test/Samples/SampleSpecsApi/desc_SystemUnderTest.cs @@ -1,7 +1,7 @@ using NSpec; using SampleSpecsApi.SampleSystem; -// Do not move the following spec classes around, to avoid rewriting line numbers. This should be line nr.3 +// Do not move the following spec classes around, to avoid rewriting line numbers. This should be stuck at line nr. 4 namespace SampleSpecsApi { class ParentSpec : nspec @@ -55,7 +55,7 @@ void method_context_5() // Do not move the preceding spec classes around, to avoid rewriting line numbers - public class DummyPublicClass + public class PublicPlaceholderClass { } } From 065989d5b2ff93641b864102937415cd6f7617a1 Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Thu, 16 Feb 2017 20:31:28 +0100 Subject: [PATCH 09/26] chore(test): delete obsolete code in ExampleRunner tests --- sln/src/NSpec/Api/Execution/ExampleRunner.cs | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/sln/src/NSpec/Api/Execution/ExampleRunner.cs b/sln/src/NSpec/Api/Execution/ExampleRunner.cs index 8d8c8ac6..b1ab5aaf 100644 --- a/sln/src/NSpec/Api/Execution/ExampleRunner.cs +++ b/sln/src/NSpec/Api/Execution/ExampleRunner.cs @@ -32,20 +32,15 @@ public void Start( 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(); - /* - Func isSelected = - exm => selectedNames.Contains(exm.FullName()); - - var selectedContexts = contexts - .Where(ctx => ctx.Examples.Any(isSelected)); - */ - foreach (var context in selectedContexts) { RunContext(context); From 9fe08a1bf0a9ad6048f392ebbc5fedec948861eb Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Thu, 16 Feb 2017 20:35:20 +0100 Subject: [PATCH 10/26] fix(tools): CI build shoud include new SampleSpecsApi too --- sln/Build-Package.ps1 | 2 ++ 1 file changed, 2 insertions(+) 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 $_ } } From c86354489568c83c6cf906ef9816ec80eb4695da Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Thu, 16 Feb 2017 21:35:15 +0100 Subject: [PATCH 11/26] test(api): execution test fails in Release build due to ... ... exception stacktrace changing from Debug build --- sln/test/NSpec.Tests/Api/ApiTestData.cs | 2 +- .../NSpec.Tests/Api/Execution/describe_ExampleRunner.cs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/sln/test/NSpec.Tests/Api/ApiTestData.cs b/sln/test/NSpec.Tests/Api/ApiTestData.cs index 3d19d634..2abdc735 100644 --- a/sln/test/NSpec.Tests/Api/ApiTestData.cs +++ b/sln/test/NSpec.Tests/Api/ApiTestData.cs @@ -143,7 +143,7 @@ static ApiTestData() Failed = true, Pending = false, ExceptionMessage = "Expected false, but was $True.", - ExceptionStackTrace = @"SampleSpecsApi\desc_SystemUnderTest.cs:line 49", + ExceptionStackTrace = "at NSpec.AssertionExtensions.ShouldBeFalse(Boolean actual)", }, new ExecutedExample() { diff --git a/sln/test/NSpec.Tests/Api/Execution/describe_ExampleRunner.cs b/sln/test/NSpec.Tests/Api/Execution/describe_ExampleRunner.cs index b55e5475..1769f77e 100644 --- a/sln/test/NSpec.Tests/Api/Execution/describe_ExampleRunner.cs +++ b/sln/test/NSpec.Tests/Api/Execution/describe_ExampleRunner.cs @@ -62,7 +62,7 @@ public override void setup() } [Test] - public void it_should_discover_examples() + public void it_should_discover_all_examples() { var expecteds = ApiTestData.allDiscoveredExamples; @@ -70,7 +70,7 @@ public void it_should_discover_examples() } [Test] - public void it_should_execute_examples() + public void it_should_execute_all_examples() { var expecteds = ApiTestData.allExecutedExamples; @@ -111,7 +111,7 @@ public override void setup() } [Test] - public void it_should_discover_examples() + public void it_should_discover_sibling_examples() { var expecteds = ApiTestData.allDiscoveredExamples .Where((_, index) => runIndexes.Contains(index)); @@ -120,7 +120,7 @@ public void it_should_discover_examples() } [Test] - public void it_should_execute_examples() + public void it_should_execute_sibling_examples() { var expecteds = ApiTestData.allExecutedExamples .Where((_, index) => runIndexes.Contains(index)); From f9374061df3a09c23d09b2b3f89946efd456b60a Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Thu, 16 Feb 2017 21:46:32 +0100 Subject: [PATCH 12/26] chore(samples): upgrade to dev packages with working VS execution Source code file/line number still missing. --- .../Samples/DotNetTestSample/test/LibrarySpecs/project.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sln/test/Samples/DotNetTestSample/test/LibrarySpecs/project.json b/sln/test/Samples/DotNetTestSample/test/LibrarySpecs/project.json index 1500f599..365f323f 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.0-dev-56", + "dotnet-test-nspec": "0.1.0-dev-64", "LibraryUnderTest": { "target": "project" }, - "NSpec": "2.0.0-dev-54", + "NSpec": "2.0.0-dev-60", "Shouldly": "2.8.2" }, From 5eb40bad2879a7cbf4c4279512a4120d067f140f Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Fri, 17 Feb 2017 01:09:42 +0100 Subject: [PATCH 13/26] feat(api): discovered examples have source information too --- sln/src/NSpec/Api/Controller.cs | 4 +- sln/src/NSpec/Api/Discovery/DiscoveryUtils.cs | 25 +++++ .../NSpec/Api/Discovery/ExampleSelector.cs | 27 ++--- sln/src/NSpec/Api/Execution/ExampleRunner.cs | 29 +++-- sln/src/NSpec/SourceInfo/DebugInfoProvider.cs | 51 +++++++++ sln/src/NSpec/SourceInfo/ExampleUtils.cs | 102 ++++++++++++++++++ sln/src/NSpec/project.json | 1 + sln/test/NSpec.Tests/Api/ApiTestData.cs | 39 ++++--- .../Api/Discovery/describe_ExampleSelector.cs | 4 +- 9 files changed, 236 insertions(+), 46 deletions(-) create mode 100644 sln/src/NSpec/Api/Discovery/DiscoveryUtils.cs create mode 100644 sln/src/NSpec/SourceInfo/DebugInfoProvider.cs create mode 100644 sln/src/NSpec/SourceInfo/ExampleUtils.cs diff --git a/sln/src/NSpec/Api/Controller.cs b/sln/src/NSpec/Api/Controller.cs index 9c7989e2..bf5559a7 100644 --- a/sln/src/NSpec/Api/Controller.cs +++ b/sln/src/NSpec/Api/Controller.cs @@ -30,9 +30,9 @@ public int Run( public string List(string testAssemblyPath) { - var exampleSelector = new ExampleSelector(); + var exampleSelector = new ExampleSelector(testAssemblyPath); - var discoveredExamples = exampleSelector.Select(testAssemblyPath); + var discoveredExamples = exampleSelector.Select(); string serialized = JsonConvert.SerializeObject(discoveredExamples); 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 index c69bfe90..fef1b6cd 100644 --- a/sln/src/NSpec/Api/Discovery/ExampleSelector.cs +++ b/sln/src/NSpec/Api/Discovery/ExampleSelector.cs @@ -1,4 +1,5 @@ using NSpec.Domain; +using NSpec.SourceInfo; using System; using System.Collections.Generic; using System.Linq; @@ -7,7 +8,14 @@ namespace NSpec.Api.Discovery { public class ExampleSelector { - public IEnumerable Select(string testAssemblyPath) + public ExampleSelector(string testAssemblyPath) + { + this.testAssemblyPath = testAssemblyPath; + + debugInfoProvider = new DebugInfoProvider(testAssemblyPath); + } + + public IEnumerable Select() { var selector = new ContextSelector(); @@ -28,19 +36,14 @@ from exm in examples DiscoveredExample MapToDiscovered(ExampleBase example, string binaryPath) { - var discoveredExample = new DiscoveredExample() - { - FullName = example.FullName(), - SourceAssembly = binaryPath, - // TODO complete with source information - SourceFilePath = String.Empty, - SourceLineNumber = 0, - Tags = example.Tags - .Select(tag => tag.Replace("_", " ")) - .ToArray(), - }; + 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/ExampleRunner.cs b/sln/src/NSpec/Api/Execution/ExampleRunner.cs index b1ab5aaf..b31e9f3f 100644 --- a/sln/src/NSpec/Api/Execution/ExampleRunner.cs +++ b/sln/src/NSpec/Api/Execution/ExampleRunner.cs @@ -4,6 +4,7 @@ using NSpec.Api.Discovery; using NSpec.Domain; using NSpec.Domain.Formatters; +using NSpec.SourceInfo; namespace NSpec.Api.Execution { @@ -17,6 +18,8 @@ public ExampleRunner( this.testAssemblyPath = testAssemblyPath; this.onDiscovered = onDiscovered; this.onExecuted = onExecuted; + + debugInfoProvider = new DebugInfoProvider(testAssemblyPath); } public void Start( @@ -79,28 +82,20 @@ void RunContext(Context context) context.AssignExceptions(); } - readonly string testAssemblyPath; - readonly Action onDiscovered; - readonly Action onExecuted; - - // TODO Extract from ExampleSelector.MapToDiscovered - static DiscoveredExample MapToDiscovered(ExampleBase example, string binaryPath) + DiscoveredExample MapToDiscovered(ExampleBase example, string binaryPath) { - var discoveredExample = new DiscoveredExample() - { - FullName = example.FullName(), - SourceAssembly = binaryPath, - // TODO complete with source information - SourceFilePath = String.Empty, - SourceLineNumber = 0, - Tags = example.Tags - .Select(tag => tag.Replace("_", " ")) - .ToArray(), - }; + 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() diff --git a/sln/src/NSpec/SourceInfo/DebugInfoProvider.cs b/sln/src/NSpec/SourceInfo/DebugInfoProvider.cs new file mode 100644 index 00000000..09bae1fb --- /dev/null +++ b/sln/src/NSpec/SourceInfo/DebugInfoProvider.cs @@ -0,0 +1,51 @@ +using Microsoft.DotNet.ProjectModel; +using Microsoft.Extensions.Testing.Abstractions; +using NSpec.Domain; +using System.IO; + +namespace NSpec.SourceInfo +{ + 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 = ExampleUtils.GetBodyMethodInfo(example); + + 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/SourceInfo/ExampleUtils.cs b/sln/src/NSpec/SourceInfo/ExampleUtils.cs new file mode 100644 index 00000000..135646f7 --- /dev/null +++ b/sln/src/NSpec/SourceInfo/ExampleUtils.cs @@ -0,0 +1,102 @@ +using NSpec.Domain; +using System; +using System.Reflection; +using System.Threading.Tasks; + +namespace NSpec.SourceInfo +{ + public static class ExampleUtils + { + public static MethodInfo GetBodyMethodInfo(ExampleBase baseExample) + { + string exampleTypeName = baseExample.GetType().Name; + + Func getMethodInfo; + + if (nameof(Example) == exampleTypeName) + { + getMethodInfo = GetExampleBodyInfo; + } + else if (nameof(MethodExample) == exampleTypeName) + { + getMethodInfo = GetMethodExampleBodyInfo; + } + else if (nameof(AsyncExample) == exampleTypeName) + { + getMethodInfo = GetAsyncExampleBodyInfo; + } + else if (nameof(AsyncMethodExample) == exampleTypeName) + { + getMethodInfo = GetAsyncMethodExampleBodyInfo; + } + else + { + throw new ArgumentOutOfRangeException(nameof(baseExample), exampleTypeName, "Unknown example type"); + } + + return getMethodInfo(baseExample); + } + + static MethodInfo GetExampleBodyInfo(ExampleBase baseExample) + { + // core logic taken from osoftware/NSpecTestAdapter: + // see https://github.com/osoftware/NSpecTestAdapter/blob/master/NSpec.TestAdapter/Discoverer.cs + + const string actionPrivateFieldName = "action"; + + Example example = (Example)baseExample; + + var action = example.GetType() + .GetField(actionPrivateFieldName, BindingFlags.Instance | BindingFlags.NonPublic) + .GetValue(example) as Action; + + var info = action.GetMethodInfo(); + + return info; + } + + static MethodInfo GetMethodExampleBodyInfo(ExampleBase baseExample) + { + // core logic taken from osoftware/NSpecTestAdapter: + // see https://github.com/osoftware/NSpecTestAdapter/blob/master/NSpec.TestAdapter/Discoverer.cs + + const string methodInfoPrivateFieldName = "method"; + + MethodExample example = (MethodExample)baseExample; + + var info = example.GetType() + .GetField(methodInfoPrivateFieldName, BindingFlags.Instance | BindingFlags.NonPublic) + .GetValue(example) as MethodInfo; + + return info; + } + + static MethodInfo GetAsyncExampleBodyInfo(ExampleBase baseExample) + { + const string asyncActionPrivateFieldName = "asyncAction"; + + AsyncExample example = (AsyncExample)baseExample; + + var asyncAction = example.GetType() + .GetField(asyncActionPrivateFieldName, BindingFlags.Instance | BindingFlags.NonPublic) + .GetValue(example) as Func; + + var info = asyncAction.GetMethodInfo(); + + return info; + } + + static MethodInfo GetAsyncMethodExampleBodyInfo(ExampleBase baseExample) + { + const string methodInfoPrivateFieldName = "method"; + + AsyncMethodExample example = (AsyncMethodExample)baseExample; + + var info = example.GetType() + .GetField(methodInfoPrivateFieldName, BindingFlags.Instance | BindingFlags.NonPublic) + .GetValue(example) as MethodInfo; + + return info; + } + } +} diff --git a/sln/src/NSpec/project.json b/sln/src/NSpec/project.json index edc70c3f..0aafc53e 100644 --- a/sln/src/NSpec/project.json +++ b/sln/src/NSpec/project.json @@ -10,6 +10,7 @@ }, "dependencies": { + "Microsoft.Extensions.Testing.Abstractions": "1.0.0-preview2-003121", "Newtonsoft.Json": "9.0.1" }, diff --git a/sln/test/NSpec.Tests/Api/ApiTestData.cs b/sln/test/NSpec.Tests/Api/ApiTestData.cs index 2abdc735..ac8b1740 100644 --- a/sln/test/NSpec.Tests/Api/ApiTestData.cs +++ b/sln/test/NSpec.Tests/Api/ApiTestData.cs @@ -1,5 +1,6 @@ using NSpec.Api.Discovery; using NSpec.Api.Execution; +using System.IO; using System.Reflection; namespace NSpec.Tests.Api @@ -8,9 +9,27 @@ public static class ApiTestData { static ApiTestData() { + string thisProjectDirPath = Directory.GetCurrentDirectory(); + + string testDirPath = Path.GetFullPath(Path.Combine( + thisProjectDirPath, @"..")); + + string singleTestSourceFilePath = Path.Combine(new[] + { + testDirPath, + "Samples", + "SampleSpecsApi", + "desc_SystemUnderTest.cs" + }); + foreach (var exm in allDiscoveredExamples) { exm.SourceAssembly = testAssemblyPath; + + if (exm.SourceLineNumber != 0) + { + exm.SourceFilePath = singleTestSourceFilePath; + } } } @@ -22,8 +41,7 @@ static ApiTestData() new DiscoveredExample() { FullName = "nspec. ParentSpec. method context 1. parent example 1A.", - SourceFilePath = "", - SourceLineNumber = 0, + SourceLineNumber = 19, Tags = new[] { "Tag-1A", @@ -34,8 +52,7 @@ static ApiTestData() new DiscoveredExample() { FullName = "nspec. ParentSpec. method context 1. parent example 1B.", - SourceFilePath = "", - SourceLineNumber = 0, + SourceLineNumber = 21, Tags = new[] { "Tag-1A", @@ -46,8 +63,7 @@ static ApiTestData() new DiscoveredExample() { FullName = "nspec. ParentSpec. method context 2. parent example 2A.", - SourceFilePath = "", - SourceLineNumber = 0, + SourceLineNumber = 26, Tags = new[] { "ParentSpec", @@ -56,7 +72,7 @@ static ApiTestData() new DiscoveredExample() { FullName = "nspec. ParentSpec. ChildSpec. method context 3. child example 3A skipped.", - SourceFilePath = "", + // No source code info available for pending tests SourceLineNumber = 0, Tags = new[] { @@ -69,8 +85,7 @@ static ApiTestData() new DiscoveredExample() { FullName = "nspec. ParentSpec. ChildSpec. method context 4. child example 4A.", - SourceFilePath = "", - SourceLineNumber = 0, + SourceLineNumber = 42, Tags = new[] { "Tag with underscores", @@ -82,8 +97,7 @@ static ApiTestData() new DiscoveredExample() { FullName = "nspec. ParentSpec. ChildSpec. method context 5. sub context 5-1. child example 5-1A failing.", - SourceFilePath = "", - SourceLineNumber = 0, + SourceLineNumber = 49, Tags = new[] { "Tag-Child", @@ -94,8 +108,7 @@ static ApiTestData() new DiscoveredExample() { FullName = "nspec. ParentSpec. ChildSpec. method context 5. sub context 5-1. child example 5-1B.", - SourceFilePath = "", - SourceLineNumber = 0, + SourceLineNumber = 51, Tags = new[] { "Tag-Child", diff --git a/sln/test/NSpec.Tests/Api/Discovery/describe_ExampleSelector.cs b/sln/test/NSpec.Tests/Api/Discovery/describe_ExampleSelector.cs index 7e62eb59..008e2628 100644 --- a/sln/test/NSpec.Tests/Api/Discovery/describe_ExampleSelector.cs +++ b/sln/test/NSpec.Tests/Api/Discovery/describe_ExampleSelector.cs @@ -23,9 +23,9 @@ public describe_ExampleSelector() [SetUp] public void setup() { - selector = new ExampleSelector(); + selector = new ExampleSelector(testAssemblyPath); - actuals = selector.Select(testAssemblyPath); + actuals = selector.Select(); } [Test] From d3bacc88f9b35e8fc869a3a29d53b17bbb01bcac Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Fri, 17 Feb 2017 01:26:56 +0100 Subject: [PATCH 14/26] fix(test): test project directory path is wrong in CI build --- sln/test/NSpec.Tests/Api/ApiTestData.cs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/sln/test/NSpec.Tests/Api/ApiTestData.cs b/sln/test/NSpec.Tests/Api/ApiTestData.cs index ac8b1740..ae827f44 100644 --- a/sln/test/NSpec.Tests/Api/ApiTestData.cs +++ b/sln/test/NSpec.Tests/Api/ApiTestData.cs @@ -9,10 +9,15 @@ public static class ApiTestData { static ApiTestData() { - string thisProjectDirPath = Directory.GetCurrentDirectory(); + string thisAssemblyPath = typeof(ApiTestData).GetTypeInfo().Assembly.Location; - string testDirPath = Path.GetFullPath(Path.Combine( - thisProjectDirPath, @"..")); + // go up from test\{Project}\bin\{Config}\{Framework}\{Assembly}.dll + string testDirPath = Directory + .GetParent(thisAssemblyPath) + .Parent + .Parent + .Parent + .Parent.FullName; string singleTestSourceFilePath = Path.Combine(new[] { From dffab1ef62d37d45f6d1bbc7cf84f19d54b31a46 Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Fri, 17 Feb 2017 01:40:44 +0100 Subject: [PATCH 15/26] fix(test): test project directory path is wrong in .NET 4.5.1 --- sln/test/NSpec.Tests/Api/ApiTestData.cs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/sln/test/NSpec.Tests/Api/ApiTestData.cs b/sln/test/NSpec.Tests/Api/ApiTestData.cs index ae827f44..ced9f6b8 100644 --- a/sln/test/NSpec.Tests/Api/ApiTestData.cs +++ b/sln/test/NSpec.Tests/Api/ApiTestData.cs @@ -11,12 +11,16 @@ static ApiTestData() { string thisAssemblyPath = typeof(ApiTestData).GetTypeInfo().Assembly.Location; - // go up from test\{Project}\bin\{Config}\{Framework}\{Assembly}.dll + // .NET Core: go up from test\{Project}\bin\{Config}\{Framework}\{Assembly}.dll + // .NET Framework: go up from test\{Project}\bin\{Config}\{Framework}\{Platform}\{Assembly}.dll string testDirPath = Directory .GetParent(thisAssemblyPath) .Parent .Parent .Parent +#if NET451 + .Parent +#endif .Parent.FullName; string singleTestSourceFilePath = Path.Combine(new[] @@ -161,7 +165,7 @@ static ApiTestData() Failed = true, Pending = false, ExceptionMessage = "Expected false, but was $True.", - ExceptionStackTrace = "at NSpec.AssertionExtensions.ShouldBeFalse(Boolean actual)", + ExceptionStackTrace = "NSpec.AssertionExtensions.ShouldBeFalse(Boolean actual)", }, new ExecutedExample() { From 8207b4d98aac9e4c99dcce5045bd40c94009a6a6 Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Fri, 17 Feb 2017 14:00:18 +0100 Subject: [PATCH 16/26] fix(samples): avoid DllNotFoundException on Microsoft.DiaSymReader.Native.amd64.dll That happens only on .NET 4.5.1 --- .../DotNetTestSample/test/LibrarySpecs/project.json | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/sln/test/Samples/DotNetTestSample/test/LibrarySpecs/project.json b/sln/test/Samples/DotNetTestSample/test/LibrarySpecs/project.json index 365f323f..c4a62f42 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.0-dev-64", + "dotnet-test-nspec": "0.1.0-dev-65", "LibraryUnderTest": { "target": "project" }, - "NSpec": "2.0.0-dev-60", + "NSpec": "2.0.0-dev-63", "Shouldly": "2.8.2" }, @@ -26,6 +26,10 @@ } }, "net451": { + "dependencies": { + "Microsoft.DiaSymReader.Native": "1.4.2", + "Microsoft.NETCore.Platforms": "1.1.0" + } } } } From f09265b2beec0b6fd57e8b6ecb7affb638dae03d Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Fri, 17 Feb 2017 16:57:40 +0100 Subject: [PATCH 17/26] refactor(api): move console running logic to dedicated class --- sln/src/NSpec/Api/Controller.cs | 47 +------------ .../NSpec/Api/Execution/BatchExampleRunner.cs | 68 +++++++++++++++++++ 2 files changed, 71 insertions(+), 44 deletions(-) create mode 100644 sln/src/NSpec/Api/Execution/BatchExampleRunner.cs diff --git a/sln/src/NSpec/Api/Controller.cs b/sln/src/NSpec/Api/Controller.cs index bf5559a7..02d56718 100644 --- a/sln/src/NSpec/Api/Controller.cs +++ b/sln/src/NSpec/Api/Controller.cs @@ -1,12 +1,8 @@ using Newtonsoft.Json; using NSpec.Api.Discovery; using NSpec.Api.Execution; -using NSpec.Domain; -using NSpec.Domain.Formatters; using System; using System.Collections.Generic; -using System.Linq; -using System.Reflection; namespace NSpec.Api { @@ -19,11 +15,10 @@ public int Run( 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; } @@ -63,41 +58,5 @@ public void Execute( exampleRunner.Start(exampleFullNames); } - - /// - /// 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/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); + } + } + } +} From debc190c9cc559bad67e65ef72aa706dfbdfc401 Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Fri, 17 Feb 2017 20:16:24 +0100 Subject: [PATCH 18/26] docs(samples): mention new dependencies in DotNetTestSample Also, mention working VS Test Explorer integration --- sln/test/Samples/DotNetTestSample/README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/sln/test/Samples/DotNetTestSample/README.md b/sln/test/Samples/DotNetTestSample/README.md index e6e935df..a8518129 100644 --- a/sln/test/Samples/DotNetTestSample/README.md +++ b/sln/test/Samples/DotNetTestSample/README.md @@ -7,8 +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 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 that will not get solved (as *project.json* is being deprecated in favour of MSBuild) +- 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: @@ -19,6 +20,6 @@ due to an issue between .NET Core CLI Tools Preview 2 and NuGet that will not ge > 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 From 51aeba04022c1f6e4ad096ec3ed9e6729aa32cf7 Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Sun, 19 Feb 2017 03:14:45 +0100 Subject: [PATCH 19/26] feat(api): executed examples also have duration --- sln/src/NSpec/Api/Execution/ExampleRunner.cs | 1 + .../NSpec/Api/Execution/ExecutedExample.cs | 6 +- sln/test/NSpec.Tests/Api/ApiTestData.cs | 11 ++++ .../Api/Execution/describe_ExampleRunner.cs | 55 +++++++++++++++++-- 4 files changed, 66 insertions(+), 7 deletions(-) diff --git a/sln/src/NSpec/Api/Execution/ExampleRunner.cs b/sln/src/NSpec/Api/Execution/ExampleRunner.cs index b31e9f3f..bbcced37 100644 --- a/sln/src/NSpec/Api/Execution/ExampleRunner.cs +++ b/sln/src/NSpec/Api/Execution/ExampleRunner.cs @@ -103,6 +103,7 @@ static ExecutedExample MapToExecuted(ExampleBase example) FullName = example.FullName(), Pending = example.Pending, Failed = example.Failed(), + Duration = example.Duration, }; if (example.Exception != null) diff --git a/sln/src/NSpec/Api/Execution/ExecutedExample.cs b/sln/src/NSpec/Api/Execution/ExecutedExample.cs index e0641f0e..a4f2a458 100644 --- a/sln/src/NSpec/Api/Execution/ExecutedExample.cs +++ b/sln/src/NSpec/Api/Execution/ExecutedExample.cs @@ -1,4 +1,6 @@ -namespace NSpec.Api.Execution +using System; + +namespace NSpec.Api.Execution { public class ExecutedExample { @@ -11,5 +13,7 @@ public class ExecutedExample public string ExceptionMessage { get; set; } public string ExceptionStackTrace { get; set; } + + public TimeSpan Duration { get; set; } } } diff --git a/sln/test/NSpec.Tests/Api/ApiTestData.cs b/sln/test/NSpec.Tests/Api/ApiTestData.cs index ced9f6b8..1234f1df 100644 --- a/sln/test/NSpec.Tests/Api/ApiTestData.cs +++ b/sln/test/NSpec.Tests/Api/ApiTestData.cs @@ -1,5 +1,6 @@ using NSpec.Api.Discovery; using NSpec.Api.Execution; +using System; using System.IO; using System.Reflection; @@ -40,6 +41,16 @@ static ApiTestData() exm.SourceFilePath = singleTestSourceFilePath; } } + + TimeSpan nonZeroDuration = new TimeSpan(1, 2, 3); + + foreach (var exm in allExecutedExamples) + { + if (!exm.Pending) + { + exm.Duration = nonZeroDuration; + } + } } public static readonly string testAssemblyPath = diff --git a/sln/test/NSpec.Tests/Api/Execution/describe_ExampleRunner.cs b/sln/test/NSpec.Tests/Api/Execution/describe_ExampleRunner.cs index 1769f77e..71d3813d 100644 --- a/sln/test/NSpec.Tests/Api/Execution/describe_ExampleRunner.cs +++ b/sln/test/NSpec.Tests/Api/Execution/describe_ExampleRunner.cs @@ -3,6 +3,7 @@ using NSpec.Api.Discovery; using NSpec.Api.Execution; using NUnit.Framework; +using System; using System.Collections.Generic; using System.Linq; @@ -38,12 +39,50 @@ 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; + } - protected EquivalencyAssertionOptions> ExpectPartialStackTrace( - EquivalencyAssertionOptions> opts) + public static EquivalencyAssertionOptions> ExpectSomeDuration( + this EquivalencyAssertionOptions> opts) { - opts.Using(ctx => ctx.Subject?.Should().Contain(ctx.Expectation)) - .When(subj => subj.SelectedMemberPath.EndsWith(".ExceptionStackTrace", System.StringComparison.Ordinal)); + 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; } @@ -74,7 +113,9 @@ public void it_should_execute_all_examples() { var expecteds = ApiTestData.allExecutedExamples; - actualExecutedExamples.ShouldBeEquivalentTo(expecteds, ExpectPartialStackTrace); + actualExecutedExamples.ShouldBeEquivalentTo(expecteds, opts => opts + .ExpectPartialStackTrace() + .ExpectSomeDuration()); } } @@ -125,7 +166,9 @@ public void it_should_execute_sibling_examples() var expecteds = ApiTestData.allExecutedExamples .Where((_, index) => runIndexes.Contains(index)); - actualExecutedExamples.ShouldBeEquivalentTo(expecteds, ExpectPartialStackTrace); + actualExecutedExamples.ShouldBeEquivalentTo(expecteds, opts => opts + .ExpectPartialStackTrace() + .ExpectSomeDuration()); } } } From 94a25a4b7a2318a9753bfdc6344272928ecdc0d8 Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Sun, 19 Feb 2017 04:39:16 +0100 Subject: [PATCH 20/26] chore(samples): upgrade to dev packages showing duration --- .../DotNetTestSample/test/LibrarySpecs/LibrarySpecs.xproj | 7 ++++--- .../DotNetTestSample/test/LibrarySpecs/project.json | 4 ++-- 2 files changed, 6 insertions(+), 5 deletions(-) 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 c4a62f42..f0bca9a7 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.0-dev-65", + "dotnet-test-nspec": "0.1.1-dev-70", "LibraryUnderTest": { "target": "project" }, - "NSpec": "2.0.0-dev-63", + "NSpec": "2.0.1-dev-68", "Shouldly": "2.8.2" }, From fb430317f71022ad9e65aa4b72b61d2a3f9e6371 Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Sun, 19 Feb 2017 04:42:07 +0100 Subject: [PATCH 21/26] refactor(sourceInfo): get body MethodInfo directly from Example --- .../NSpec/Api/Discovery/ExampleSelector.cs | 4 +- sln/src/NSpec/Api/Execution/ExampleRunner.cs | 2 +- .../Shared}/DebugInfoProvider.cs | 4 +- sln/src/NSpec/Domain/AsyncExample.cs | 8 +- sln/src/NSpec/Domain/Example.cs | 6 ++ sln/src/NSpec/Domain/ExampleBase.cs | 3 + sln/src/NSpec/Domain/MethodExample.cs | 1 - sln/src/NSpec/Domain/MethodExampleBase.cs | 10 +- sln/src/NSpec/SourceInfo/ExampleUtils.cs | 102 ------------------ sln/test/NSpec.Tests/ExampleBaseWrap.cs | 7 +- 10 files changed, 31 insertions(+), 116 deletions(-) rename sln/src/NSpec/{SourceInfo => Api/Shared}/DebugInfoProvider.cs (93%) delete mode 100644 sln/src/NSpec/SourceInfo/ExampleUtils.cs diff --git a/sln/src/NSpec/Api/Discovery/ExampleSelector.cs b/sln/src/NSpec/Api/Discovery/ExampleSelector.cs index fef1b6cd..86bcc66c 100644 --- a/sln/src/NSpec/Api/Discovery/ExampleSelector.cs +++ b/sln/src/NSpec/Api/Discovery/ExampleSelector.cs @@ -1,5 +1,5 @@ -using NSpec.Domain; -using NSpec.SourceInfo; +using NSpec.Api.Shared; +using NSpec.Domain; using System; using System.Collections.Generic; using System.Linq; diff --git a/sln/src/NSpec/Api/Execution/ExampleRunner.cs b/sln/src/NSpec/Api/Execution/ExampleRunner.cs index bbcced37..37116bb2 100644 --- a/sln/src/NSpec/Api/Execution/ExampleRunner.cs +++ b/sln/src/NSpec/Api/Execution/ExampleRunner.cs @@ -4,7 +4,7 @@ using NSpec.Api.Discovery; using NSpec.Domain; using NSpec.Domain.Formatters; -using NSpec.SourceInfo; +using NSpec.Api.Shared; namespace NSpec.Api.Execution { diff --git a/sln/src/NSpec/SourceInfo/DebugInfoProvider.cs b/sln/src/NSpec/Api/Shared/DebugInfoProvider.cs similarity index 93% rename from sln/src/NSpec/SourceInfo/DebugInfoProvider.cs rename to sln/src/NSpec/Api/Shared/DebugInfoProvider.cs index 09bae1fb..1b2a4aa0 100644 --- a/sln/src/NSpec/SourceInfo/DebugInfoProvider.cs +++ b/sln/src/NSpec/Api/Shared/DebugInfoProvider.cs @@ -3,7 +3,7 @@ using NSpec.Domain; using System.IO; -namespace NSpec.SourceInfo +namespace NSpec.Api.Shared { public class DebugInfoProvider { @@ -24,7 +24,7 @@ public SourceInformation GetSourceInfo(ExampleBase example) return emptyInfo; } - var methodInfo = ExampleUtils.GetBodyMethodInfo(example); + var methodInfo = example.BodyMethodInfo; var sourceInfo = sourceInfoProvider.GetSourceInformation(methodInfo); 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/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/SourceInfo/ExampleUtils.cs b/sln/src/NSpec/SourceInfo/ExampleUtils.cs deleted file mode 100644 index 135646f7..00000000 --- a/sln/src/NSpec/SourceInfo/ExampleUtils.cs +++ /dev/null @@ -1,102 +0,0 @@ -using NSpec.Domain; -using System; -using System.Reflection; -using System.Threading.Tasks; - -namespace NSpec.SourceInfo -{ - public static class ExampleUtils - { - public static MethodInfo GetBodyMethodInfo(ExampleBase baseExample) - { - string exampleTypeName = baseExample.GetType().Name; - - Func getMethodInfo; - - if (nameof(Example) == exampleTypeName) - { - getMethodInfo = GetExampleBodyInfo; - } - else if (nameof(MethodExample) == exampleTypeName) - { - getMethodInfo = GetMethodExampleBodyInfo; - } - else if (nameof(AsyncExample) == exampleTypeName) - { - getMethodInfo = GetAsyncExampleBodyInfo; - } - else if (nameof(AsyncMethodExample) == exampleTypeName) - { - getMethodInfo = GetAsyncMethodExampleBodyInfo; - } - else - { - throw new ArgumentOutOfRangeException(nameof(baseExample), exampleTypeName, "Unknown example type"); - } - - return getMethodInfo(baseExample); - } - - static MethodInfo GetExampleBodyInfo(ExampleBase baseExample) - { - // core logic taken from osoftware/NSpecTestAdapter: - // see https://github.com/osoftware/NSpecTestAdapter/blob/master/NSpec.TestAdapter/Discoverer.cs - - const string actionPrivateFieldName = "action"; - - Example example = (Example)baseExample; - - var action = example.GetType() - .GetField(actionPrivateFieldName, BindingFlags.Instance | BindingFlags.NonPublic) - .GetValue(example) as Action; - - var info = action.GetMethodInfo(); - - return info; - } - - static MethodInfo GetMethodExampleBodyInfo(ExampleBase baseExample) - { - // core logic taken from osoftware/NSpecTestAdapter: - // see https://github.com/osoftware/NSpecTestAdapter/blob/master/NSpec.TestAdapter/Discoverer.cs - - const string methodInfoPrivateFieldName = "method"; - - MethodExample example = (MethodExample)baseExample; - - var info = example.GetType() - .GetField(methodInfoPrivateFieldName, BindingFlags.Instance | BindingFlags.NonPublic) - .GetValue(example) as MethodInfo; - - return info; - } - - static MethodInfo GetAsyncExampleBodyInfo(ExampleBase baseExample) - { - const string asyncActionPrivateFieldName = "asyncAction"; - - AsyncExample example = (AsyncExample)baseExample; - - var asyncAction = example.GetType() - .GetField(asyncActionPrivateFieldName, BindingFlags.Instance | BindingFlags.NonPublic) - .GetValue(example) as Func; - - var info = asyncAction.GetMethodInfo(); - - return info; - } - - static MethodInfo GetAsyncMethodExampleBodyInfo(ExampleBase baseExample) - { - const string methodInfoPrivateFieldName = "method"; - - AsyncMethodExample example = (AsyncMethodExample)baseExample; - - var info = example.GetType() - .GetField(methodInfoPrivateFieldName, BindingFlags.Instance | BindingFlags.NonPublic) - .GetValue(example) as MethodInfo; - - return info; - } - } -} 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(); } + } } } From b77a5dceca785f699c4f8715ce6d8a268086644c Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Mon, 20 Feb 2017 13:12:57 +0100 Subject: [PATCH 22/26] fix(execution): examples in sub-context were run multiple times When both a context and its sub-context should be run, examples in the sub-context are run twice: once for the sub-context, and once again when the parent context runs. --- sln/src/NSpec/Api/Execution/ExampleRunner.cs | 11 ++++-- sln/src/NSpec/Domain/ClassContext.cs | 4 +-- sln/src/NSpec/Domain/Context.cs | 18 ++++++---- sln/test/NSpec.Tests/Api/ApiTestData.cs | 34 +++++++++++++++++++ .../Api/Execution/describe_ExampleRunner.cs | 4 +++ .../SampleSpecsApi/desc_SystemUnderTest.cs | 9 ++++- 6 files changed, 68 insertions(+), 12 deletions(-) diff --git a/sln/src/NSpec/Api/Execution/ExampleRunner.cs b/sln/src/NSpec/Api/Execution/ExampleRunner.cs index 37116bb2..5b27867d 100644 --- a/sln/src/NSpec/Api/Execution/ExampleRunner.cs +++ b/sln/src/NSpec/Api/Execution/ExampleRunner.cs @@ -77,9 +77,14 @@ void RunContext(Context context) var instance = context.GetInstance(); - context.Run(this, false, instance); - - context.AssignExceptions(); + context.Run( + formatter: this, + failFast: false, + instance: instance, + recurse: false); + + context.AssignExceptions( + recurse: false); } DiscoveredExample MapToDiscovered(ExampleBase example, string binaryPath) 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/test/NSpec.Tests/Api/ApiTestData.cs b/sln/test/NSpec.Tests/Api/ApiTestData.cs index 1234f1df..e91e0b4b 100644 --- a/sln/test/NSpec.Tests/Api/ApiTestData.cs +++ b/sln/test/NSpec.Tests/Api/ApiTestData.cs @@ -136,6 +136,28 @@ static ApiTestData() "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.", + SourceLineNumber = 58, + Tags = new[] + { + "Tag-Child", + "ChildSpec", + "ParentSpec", + }, + }, }; public static readonly ExecutedExample[] allExecutedExamples = @@ -184,6 +206,18 @@ static ApiTestData() 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, + }, }; } } diff --git a/sln/test/NSpec.Tests/Api/Execution/describe_ExampleRunner.cs b/sln/test/NSpec.Tests/Api/Execution/describe_ExampleRunner.cs index 71d3813d..6c45eb7a 100644 --- a/sln/test/NSpec.Tests/Api/Execution/describe_ExampleRunner.cs +++ b/sln/test/NSpec.Tests/Api/Execution/describe_ExampleRunner.cs @@ -129,6 +129,8 @@ public class when_starting_some_examples : describe_ExampleRunner 3, // method_context_5. sub context 5-1 5, + // ChildSpec + 8, }; readonly int[] runIndexes = { @@ -138,6 +140,8 @@ public class when_starting_some_examples : describe_ExampleRunner 3, // method_context_5. sub context 5-1 5, 6, + // ChildSpec + 8, }; public override void setup() diff --git a/sln/test/Samples/SampleSpecsApi/desc_SystemUnderTest.cs b/sln/test/Samples/SampleSpecsApi/desc_SystemUnderTest.cs index f690fdd6..b41eff21 100644 --- a/sln/test/Samples/SampleSpecsApi/desc_SystemUnderTest.cs +++ b/sln/test/Samples/SampleSpecsApi/desc_SystemUnderTest.cs @@ -50,7 +50,14 @@ void method_context_5() it["child example 5-1B"] = () => systemUnderTest.IsAlwaysTrue().ShouldBeTrue(); // # 51 }; - } // # 53 + + 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 From 46950841792e1a8f1fb92c4ece1f20a9884f4213 Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Mon, 20 Feb 2017 19:41:00 +0100 Subject: [PATCH 23/26] fix(test): source code line numbers differ in Release build --- sln/test/NSpec.Tests/Api/ApiTestData.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/sln/test/NSpec.Tests/Api/ApiTestData.cs b/sln/test/NSpec.Tests/Api/ApiTestData.cs index e91e0b4b..4e3d64a8 100644 --- a/sln/test/NSpec.Tests/Api/ApiTestData.cs +++ b/sln/test/NSpec.Tests/Api/ApiTestData.cs @@ -150,7 +150,12 @@ static ApiTestData() 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", From 20cb480616ec6fedf798f9f9386ecd77410e5967 Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Tue, 21 Feb 2017 00:38:57 +0100 Subject: [PATCH 24/26] chore(deps): upgrade to dev packages after Disposable refactoring --- .../Samples/DotNetTestSample/test/LibrarySpecs/project.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sln/test/Samples/DotNetTestSample/test/LibrarySpecs/project.json b/sln/test/Samples/DotNetTestSample/test/LibrarySpecs/project.json index f0bca9a7..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-dev-70", + "dotnet-test-nspec": "0.1.1-dev-71", "LibraryUnderTest": { "target": "project" }, - "NSpec": "2.0.1-dev-68", + "NSpec": "2.0.1-dev-71", "Shouldly": "2.8.2" }, From 61f7e42f6244d271467b308f6b562b77bf12b8d3 Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Wed, 22 Feb 2017 00:33:03 +0100 Subject: [PATCH 25/26] test(api): discovery/execute against async code spec sample --- sln/test/NSpec.Tests/Api/ApiTestData.cs | 138 ++++++++++++++---- .../SampleSystem/AsyncSystemUnderTest.cs | 12 ++ .../desc_AsyncSystemUnderTest.cs | 38 +++++ .../SampleSpecsApi/desc_SystemUnderTest.cs | 2 +- 4 files changed, 162 insertions(+), 28 deletions(-) create mode 100644 sln/test/Samples/SampleSpecsApi/SampleSystem/AsyncSystemUnderTest.cs create mode 100644 sln/test/Samples/SampleSpecsApi/desc_AsyncSystemUnderTest.cs diff --git a/sln/test/NSpec.Tests/Api/ApiTestData.cs b/sln/test/NSpec.Tests/Api/ApiTestData.cs index 4e3d64a8..88bef4ed 100644 --- a/sln/test/NSpec.Tests/Api/ApiTestData.cs +++ b/sln/test/NSpec.Tests/Api/ApiTestData.cs @@ -1,46 +1,65 @@ 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 { - static ApiTestData() - { - string thisAssemblyPath = typeof(ApiTestData).GetTypeInfo().Assembly.Location; + public static readonly string testAssemblyPath = + typeof(SampleSpecsApi.PublicPlaceholderClass).GetTypeInfo().Assembly.Location; - // .NET Core: go up from test\{Project}\bin\{Config}\{Framework}\{Assembly}.dll - // .NET Framework: go up from test\{Project}\bin\{Config}\{Framework}\{Platform}\{Assembly}.dll - string testDirPath = Directory - .GetParent(thisAssemblyPath) - .Parent - .Parent - .Parent -#if NET451 - .Parent -#endif - .Parent.FullName; + public static readonly IEnumerable allDiscoveredExamples; - string singleTestSourceFilePath = Path.Combine(new[] + static ApiTestData() + { + string sampleSpecsApiProjPath = Path.Combine(new[] { - testDirPath, + BuildTestDirectoryPath(), "Samples", "SampleSpecsApi", - "desc_SystemUnderTest.cs" }); - foreach (var exm in allDiscoveredExamples) + string descSystemUnderTestFilePath = Path.Combine(new[] { - exm.SourceAssembly = testAssemblyPath; + sampleSpecsApiProjPath, + "desc_SystemUnderTest.cs", + }); + + string descAsyncSystemUnderTestFilePath = Path.Combine(new[] + { + sampleSpecsApiProjPath, + "desc_AsyncSystemUnderTest.cs", + }); - if (exm.SourceLineNumber != 0) + 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 => { - exm.SourceFilePath = singleTestSourceFilePath; - } - } + 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); @@ -53,10 +72,7 @@ static ApiTestData() } } - public static readonly string testAssemblyPath = - typeof(SampleSpecsApi.PublicPlaceholderClass).GetTypeInfo().Assembly.Location; - - public static readonly DiscoveredExample[] allDiscoveredExamples = + static readonly DiscoveredExample[] descSystemUnderTestDiscoveredExamples = { new DiscoveredExample() { @@ -165,8 +181,42 @@ static ApiTestData() }, }; + 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.", @@ -223,6 +273,40 @@ static ApiTestData() 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/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/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 index b41eff21..55dff4b1 100644 --- a/sln/test/Samples/SampleSpecsApi/desc_SystemUnderTest.cs +++ b/sln/test/Samples/SampleSpecsApi/desc_SystemUnderTest.cs @@ -1,9 +1,9 @@ using NSpec; using SampleSpecsApi.SampleSystem; -// Do not move the following spec classes around, to avoid rewriting line numbers. This should be stuck at line nr. 4 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; From 23cb97a27dc764e35ad1455252037bf88d0ed618 Mon Sep 17 00:00:00 2001 From: GiuseppePiscopo Date: Mon, 27 Feb 2017 23:10:58 +0100 Subject: [PATCH 26/26] chore(api): rename execution-related entry points --- sln/src/NSpec/Api/Controller.cs | 4 ++-- sln/src/NSpecRunner/Program.cs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/sln/src/NSpec/Api/Controller.cs b/sln/src/NSpec/Api/Controller.cs index 02d56718..22b36ebc 100644 --- a/sln/src/NSpec/Api/Controller.cs +++ b/sln/src/NSpec/Api/Controller.cs @@ -8,7 +8,7 @@ namespace NSpec.Api { public class Controller { - public int Run( + public int RunBatch( string testAssemblyPath, string tags, string formatterClassName, @@ -34,7 +34,7 @@ public string List(string testAssemblyPath) return serialized; } - public void Execute( + public void RunInteractive( string testAssemblyPath, IEnumerable exampleFullNames, Action onExampleStarted, 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); }