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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# NUnit3 VS Adapter

## Building and testing

Use the Cake build script in the repo root (`build.cmd` or `build.ps1`). The targets:

| Command | What it does |
|------------------------|-----------------------------------------------------------------------------|
| `build` | Builds the solution (default target). |
| `build -t test` | Runs the unit tests on net462 and net8.0, with both VSTest and dotnet test. |
| `build -t package` | Creates the NuGet package and zip in `package\`. It does not build first. |
| `build -t acceptance` | Builds, creates the NuGet package and runs the acceptance tests against it. |

Rules:

- Always run the acceptance tests with `build -t acceptance`. They test the NuGet package, so running the test project directly uses a stale or missing package.
- `build -t package` packs the existing binaries. Run `build` first, or the package contains old code.
- The package version comes from MinVer and the commit height, for example `6.4.0-alpha.0.25`. Each new commit raises it. The version is in the package file name in `package\`.

## Copying a package for local testing

After `build -t package`, copy the package to the local feed `c:\nuget` with:

```
.\copynp.cmd <version>
```

For example `.\copynp.cmd 6.4.0-alpha.0.25`. Give the user the version number when you build a package for them.
4 changes: 3 additions & 1 deletion src/NUnit.TestAdapter.Tests.Acceptance/AcceptanceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -136,8 +136,10 @@ private static void ClearCachedTestNupkgs(string packageCachePath)
protected static IsolatedWorkspace CreateWorkspace()
{
var test = TestContext.CurrentContext?.Test ?? throw new InvalidOperationException("There is no current test.");
// Use the method name, not test.Name: the arguments add the full type name of the test source and push
// nested paths past MAX_PATH. CreateMutexDirectory adds a number suffix when the name is taken.
const string chars = "=()!,~-";
string name = chars.Aggregate(test.Name, (current, ch) => current.Replace(ch, '_'));
string name = chars.Aggregate(test.MethodName ?? test.Name, (current, ch) => current.Replace(ch, '_'));
var workspace = Initialization.Value.Manager.CreateWorkspace(name);

lock (WorkspacesByTestId)
Expand Down
190 changes: 190 additions & 0 deletions src/NUnit.TestAdapter.Tests.Acceptance/Issue1513Tests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
using System.IO;
using System.Linq;
using System.Xml.Linq;
using NUnit.Framework;
using NUnit.VisualStudio.TestAdapter.Tests.Acceptance.WorkspaceTools;

namespace NUnit.VisualStudio.TestAdapter.Tests.Acceptance;

/// <summary>
/// Issue #1513: with MTP, VS real-time discovery shows an extra "not run" node for every test in a
/// parameterized fixture. VS knows only the CLR type, so TestMethodIdentifierProperty.TypeName must not
/// contain the fixture arguments; they go in the display name instead. The bridge builds the trx className from the same TypeName, so when a
/// trx report is requested the fixture arguments are kept (#1351).
/// A data consumer registered in the test project dumps the property for every test node.
/// </summary>
public class Issue1513Tests : AcceptanceTests
{
// Same MTP version as Microsoft.Testing.Extensions.VSTestBridge in Directory.Packages.props.
private const string MicrosoftTestingPlatformVersion = "2.5.1";

private static readonly string[] Fixtures = ["Fixture(\"A\")", "Fixture(\"B\")", "Fixture(\")\")"];

private static readonly string[] PlainIdentifiers = ["Issue1513|Plain|Test|Test", "Issue1513|Plain|Versioned|case.version.1"];

private const string TestCode = @"
using NUnit.Framework;

namespace Issue1513
{
[TestFixture(""A"")]
[TestFixture(""B"")]
[TestFixture("")"")]
public class Fixture
{
private readonly string _arg;
public Fixture(string arg) => _arg = arg;

[Test]
public void NoParameter() => Assert.Pass();

[TestCase(1)]
public void WithParameter(int value) => Assert.Pass();

[TestCase("")"")]
public void WithParen(string value) => Assert.Pass();

[TestCase(TestName = ""scenario.step"")]
public void Dotted() => Assert.Pass();
}

public class Plain
{
[Test]
public void Test() => Assert.Pass();

[TestCase(TestName = ""case.version.1"")]
public void Versioned() => Assert.Pass();
}
}
";

private const string DumpExtensionCode = @"
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Testing.Platform.Builder;
using Microsoft.Testing.Platform.Extensions;
using Microsoft.Testing.Platform.Extensions.Messages;

namespace Issue1513
{
public static class IdentifierDumpHook
{
public static void AddExtensions(ITestApplicationBuilder builder, string[] args)
=> builder.TestHost.AddDataConsumer(_ => new IdentifierDumpConsumer());
}

public sealed class IdentifierDumpConsumer : IDataConsumer
{
private static readonly object Lock = new object();
public Type[] DataTypesConsumed => new[] { typeof(TestNodeUpdateMessage) };
public string Uid => nameof(IdentifierDumpConsumer);
public string Version => ""1.0.0"";
public string DisplayName => nameof(IdentifierDumpConsumer);
public string Description => nameof(IdentifierDumpConsumer);
public Task<bool> IsEnabledAsync() => Task.FromResult(true);

public Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationToken cancellationToken)
{
var node = ((TestNodeUpdateMessage)value).TestNode;
var id = node.Properties.SingleOrDefault<TestMethodIdentifierProperty>();
if (id != null)
{
lock (Lock)
File.AppendAllText(
Path.Combine(AppContext.BaseDirectory, ""identifiers.txt""),
id.Namespace + ""|"" + id.TypeName + ""|"" + id.MethodName + ""|"" + node.DisplayName + Environment.NewLine);
}
return Task.CompletedTask;
}
}
}
";

[TestCaseSource(typeof(SingleFrameworkSource), nameof(SingleFrameworkSource.AllFrameworks))]
public void WithoutTrx(SingleFrameworkSource source)
{
var workspace = CreateTestWorkspace(source);

var identifiers = Run(workspace, source);

var expected = Fixtures.SelectMany(fixture => new[]
{
$"Issue1513|Fixture|NoParameter|{fixture}.NoParameter",
$"Issue1513|Fixture|WithParameter|{fixture}.WithParameter(1)",
$"Issue1513|Fixture|WithParen|{fixture}.WithParen(\")\")",
$"Issue1513|Fixture|Dotted|{fixture}.scenario.step"
}).Concat(PlainIdentifiers);
Assert.That(identifiers, Is.EquivalentTo(expected));
}

[TestCaseSource(typeof(SingleFrameworkSource), nameof(SingleFrameworkSource.AllFrameworks))]
public void WithTrx(SingleFrameworkSource source)
{
var workspace = CreateTestWorkspace(source);
var resultsDirectory = Path.Combine(workspace.Directory, "TestResults");

var identifiers = Run(workspace, source, "--report-trx", "--results-directory", resultsDirectory);

var expected = Fixtures.SelectMany(fixture => new[]
{
$"Issue1513|{fixture}|NoParameter|NoParameter",
$"Issue1513|{fixture}|WithParameter|WithParameter(1)",
$"Issue1513|{fixture}|WithParen|WithParen(\")\")",
$"Issue1513|{fixture}|Dotted|scenario.step"
}).Concat(PlainIdentifiers);
Assert.That(identifiers, Is.EquivalentTo(expected));

var trxFile = Directory.GetFiles(resultsDirectory, "*.trx").Single();
XNamespace ns = "http://microsoft.com/schemas/VisualStudio/TeamTest/2010";
var classNames = XDocument.Load(trxFile)
.Descendants(ns + "TestMethod")
.Select(m => (string)m.Attribute("className"))
.Distinct()
.ToArray();
Assert.That(classNames, Is.EquivalentTo(Fixtures.Select(f => "Issue1513." + f).Concat(["Issue1513.Plain"])));
}

private static IsolatedWorkspace CreateTestWorkspace(SingleFrameworkSource source)
{
var workspace = CreateWorkspace()
.AddProject("Test.csproj", $@"
<Project Sdk='Microsoft.NET.Sdk'>
<PropertyGroup>
<TargetFramework>{source.Framework}</TargetFramework>
<OutputType>Exe</OutputType>
<EnableNUnitRunner>true</EnableNUnitRunner>
<ManagePackageVersionsCentrally>false</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageReference Include='NUnit' Version='{source.NUnitVersion}' />
<PackageReference Include='NUnit3TestAdapter' Version='{NuGetPackageVersion}' />
<PackageReference Include='Microsoft.Testing.Extensions.TrxReport' Version='{MicrosoftTestingPlatformVersion}' />
</ItemGroup>
<ItemGroup>
<TestingPlatformBuilderHook Include='1513D0D0-0000-4000-8000-000000001513'>
<DisplayName>IdentifierDump</DisplayName>
<TypeFullName>Issue1513.IdentifierDumpHook</TypeFullName>
</TestingPlatformBuilderHook>
</ItemGroup>
</Project>")
.AddFile("Tests.cs", TestCode)
.AddFile("IdentifierDump.cs", DumpExtensionCode);

workspace.MsBuild(restore: true);
return workspace;
}

private static string[] Run(IsolatedWorkspace workspace, SingleFrameworkSource source, params string[] arguments)
{
var result = ProcessUtils.Run(workspace.Directory, "dotnet", ["run", "--no-build", "--", .. arguments]);
TestContext.Out.WriteLine(result.StdOut);
result.ThrowIfError();

var dumpFile = Path.Combine(workspace.Directory, "bin", "Debug", source.Framework, "identifiers.txt");
Assert.That(dumpFile, Does.Exist, "Data consumer saw no TestMethodIdentifierProperty");
return File.ReadAllLines(dumpFile).Distinct().ToArray();
}
}
7 changes: 7 additions & 0 deletions src/NUnitTestAdapter/Seed.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,11 @@ public class Seed
internal static readonly TestProperty NUnitMethodName = TestProperty.Register(
"NUnit.MethodName",
"NUnit Method Name", typeof(string), TestPropertyAttributes.None, typeof(TestCase));

/// <summary>
/// Full name of the fixture instance that holds the test, e.g. Ns.Fixture("A") for a parameterized fixture.
/// </summary>
internal static readonly TestProperty NUnitFixtureName = TestProperty.Register(
"NUnit.FixtureName",
"NUnit Fixture Name", typeof(string), TestPropertyAttributes.None, typeof(TestCase));
}
11 changes: 11 additions & 0 deletions src/NUnitTestAdapter/TestConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,14 @@ public TestConverterForXml.TestResultSet GetVsTestResults(INUnitTestEventTestCas

#region Helper Methods

private static INUnitDiscoverySuiteBase FindFixture(INUnitDiscoverySuiteBase testNode)
{
var node = testNode.Parent;
while (node != null && node is not NUnitDiscoveryTestFixture)
node = node.Parent;
return node;
}

/// <summary>
/// Makes a TestCase from an NUnit test, adding
/// navigation data if it can be found.
Expand Down Expand Up @@ -220,6 +228,9 @@ private TestCase MakeTestCaseFromDiscoveryNode(NUnitDiscoveryTestCase testNode)
testCase.SetPropertyValue(Seed.NUnitSeedProperty, testNode.Seed.ToString());
testCase.SetPropertyValue(Seed.NUnitClassName, testNode.ClassName);
testCase.SetPropertyValue(Seed.NUnitMethodName, testNode.MethodName);
var fixture = FindFixture(testNode);
if (fixture != null)
testCase.SetPropertyValue(Seed.NUnitFixtureName, fixture.FullName);

return testCase;

Expand Down
11 changes: 11 additions & 0 deletions src/NUnitTestAdapter/TestConverterForXml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,14 @@ public struct TestResultSet

#region Helper Methods

private static NUnitEventTestCase FindFixture(NUnitEventTestCase testNode)
{
var node = testNode.Parent;
while (node is { IsNull: false } && node.Type != "TestFixture")
node = node.Parent;
return node is { IsNull: false } ? node : null;
}

/// <summary>
/// Makes a TestCase from an NUnit test, adding
/// navigation data if it can be found.
Expand Down Expand Up @@ -253,6 +261,9 @@ private TestCase MakeTestCaseFromXmlNode(NUnitEventTestCase testNode)
testCase.AddTraitsFromXmlTestNode(testNode, TraitsCache, _logger, adapterSettings);
testCase.SetPropertyValue(Seed.NUnitClassName, testNode.ClassName);
testCase.SetPropertyValue(Seed.NUnitMethodName, testNode.MethodName);
var fixture = FindFixture(testNode);
if (fixture != null)
testCase.SetPropertyValue(Seed.NUnitFixtureName, fixture.FullName);

return testCase;

Expand Down
43 changes: 43 additions & 0 deletions src/NUnitTestAdapter/TestingPlatformAdapter/FixtureDisplayName.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System;

using Microsoft.VisualStudio.TestPlatform.ObjectModel;

namespace NUnit.VisualStudio.TestAdapter.TestingPlatformAdapter;

/// <summary>
/// Puts the fixture arguments in front of the display name, e.g. Fixture("A").NoParameter (#1513).
/// Without trx, TestMethodIdentifierProperty.TypeName is the plain CLR type, so VS Test Explorer
/// shows all instances of a parameterized fixture under one class node. The display name is then
/// the only place that tells them apart. With trx, TypeName keeps the fixture arguments (#1351),
/// so the display name is left as it is.
/// </summary>
internal sealed class FixtureDisplayName(TestApplicationBuilderExtensions.NUnitTestFrameworkCapabilities capabilities)
{
public void Apply(TestCase testCase)
{
testCase.DisplayName = Create(testCase.DisplayName, testCase);
}

public void Apply(TestResult testResult)
{
Apply(testResult.TestCase);
testResult.DisplayName = Create(testResult.DisplayName, testResult.TestCase);
}

private string Create(string displayName, TestCase testCase)
{
if (capabilities.IsTrxReportEnabled || displayName is null)
return displayName;

var className = testCase.GetPropertyValue<string>(Seed.NUnitClassName, null);
var fixture = testCase.GetPropertyValue<string>(Seed.NUnitFixtureName, null);
if (className is null || fixture is null || fixture == className)
return displayName;

// Apply runs more than once on the same test case, so skip names that already have the prefix.
var prefix = TestMethodIdentifierBuilder.FixtureTypeName(className, fixture) + ".";
return displayName.StartsWith(prefix, StringComparison.Ordinal) || displayName.StartsWith(fixture + ".", StringComparison.Ordinal)
? displayName
: prefix + displayName;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Adapter;

namespace NUnit.VisualStudio.TestAdapter.TestingPlatformAdapter;

/// <summary>
/// Applies <see cref="FixtureDisplayName"/> to every discovered test case before the bridge sees it.
/// </summary>
internal sealed class FixtureDisplayNameDiscoverySink(ITestCaseDiscoverySink inner, FixtureDisplayName displayName) : ITestCaseDiscoverySink
{
public void SendTestCase(TestCase discoveredTest)
{
displayName.Apply(discoveredTest);
inner.SendTestCase(discoveredTest);
}
}
Loading