diff --git a/docs/docs/execution/ci-cd-reporting.md b/docs/docs/execution/ci-cd-reporting.md index 445c42ff22f..23884988742 100644 --- a/docs/docs/execution/ci-cd-reporting.md +++ b/docs/docs/execution/ci-cd-reporting.md @@ -215,6 +215,14 @@ test: The `trx2junit` tool converts TRX output to JUnit XML that GitLab can parse. +### Source Locations in JUnit XML + +Each `` in TUnit's JUnit report has `file` and `line` attributes that point to the test's source, so tools that read JUnit XML can show a failure at its source line. The XML format comes from the test reports of [JUnit](https://docs.junit.org/6.1.3/overview.html), the Java test framework. + +```xml + +``` + ## Unobserved Task Exceptions A task that faults when nothing awaits it, such as a fire-and-forget `Task.Run` or the losing branch of a `Task.WhenAny`, raises `TaskScheduler.UnobservedTaskException` when the runtime garbage-collects it. TUnit keeps the process alive and records each of these exceptions for the session: diff --git a/src/TUnit.Engine/Reporters/JUnitReporter.cs b/src/TUnit.Engine/Reporters/JUnitReporter.cs index 0258026508d..0601ffdc384 100644 --- a/src/TUnit.Engine/Reporters/JUnitReporter.cs +++ b/src/TUnit.Engine/Reporters/JUnitReporter.cs @@ -93,7 +93,8 @@ public async Task AfterRunAsync(int exitCode, CancellationToken cancellation) } // Generate JUnit XML - var xmlContent = JUnitXmlWriter.GenerateXml(lastUpdates, Filter, _unobservedTaskExceptions.ToArray()); + var xmlContent = JUnitXmlWriter.GenerateXml(lastUpdates, Filter, _unobservedTaskExceptions.ToArray(), + SourceControlContext.Detect(Environment.GetEnvironmentVariable)); if (string.IsNullOrEmpty(xmlContent)) { diff --git a/src/TUnit.Engine/Xml/JUnitXmlWriter.cs b/src/TUnit.Engine/Xml/JUnitXmlWriter.cs index 4d480845b30..9a1832ba420 100644 --- a/src/TUnit.Engine/Xml/JUnitXmlWriter.cs +++ b/src/TUnit.Engine/Xml/JUnitXmlWriter.cs @@ -6,6 +6,7 @@ using System.Xml; using Microsoft.Testing.Platform.Extensions.Messages; using TUnit.Engine.Exceptions; +using TUnit.Engine.Reporters; namespace TUnit.Engine.Xml; @@ -62,7 +63,8 @@ private static string SanitizeForXmlSlow(string value) public static string GenerateXml( IEnumerable testUpdates, string? filter, - IReadOnlyList? unobservedTaskExceptions = null) + IReadOnlyList? unobservedTaskExceptions = null, + SourceControlContext? sourceControl = null) { // Get the last state for each test var lastStates = GetLastStates(testUpdates); @@ -108,7 +110,7 @@ public static string GenerateXml( xmlWriter.WriteAttributeString("timestamp", summary.Timestamp.ToString("o", CultureInfo.InvariantCulture)); // Write test suite - WriteTestSuite(xmlWriter, lastStates.Values, assemblyName, targetFramework, summary, filter, unobservedTaskExceptions); + WriteTestSuite(xmlWriter, lastStates.Values, assemblyName, targetFramework, summary, filter, unobservedTaskExceptions, sourceControl ?? SourceControlContext.Empty); xmlWriter.WriteEndElement(); // testsuites xmlWriter.WriteEndDocument(); @@ -123,7 +125,8 @@ private static void WriteTestSuite( string targetFramework, TestSummary summary, string? filter, - IReadOnlyList? unobservedTaskExceptions) + IReadOnlyList? unobservedTaskExceptions, + SourceControlContext sourceControl) { writer.WriteStartElement("testsuite"); writer.WriteAttributeString("name", SanitizeForXml(assemblyName)); @@ -141,7 +144,7 @@ private static void WriteTestSuite( // Write test cases foreach (var test in tests) { - WriteTestCase(writer, test); + WriteTestCase(writer, test, sourceControl); } // Unobserved task exceptions belong to no single test, so they go in the suite-level @@ -190,14 +193,15 @@ private static void WriteProperties(XmlWriter writer, string targetFramework, st writer.WriteEndElement(); // properties } - private static void WriteTestCase(XmlWriter writer, TestNodeUpdateMessage test) + private static void WriteTestCase(XmlWriter writer, TestNodeUpdateMessage test, SourceControlContext sourceControl) { var testNode = test.TestNode; - // Get state, timing, and method identifier in a single pass + // Get state, timing, method identifier, and file location in a single pass TestNodeStateProperty? stateProperty = null; TimingProperty? timingProperty = null; TestMethodIdentifierProperty? testMethodIdentifier = null; + TestFileLocationProperty? fileLocation = null; foreach (var prop in testNode.Properties.AsEnumerable()) { if (stateProperty is null && prop is TestNodeStateProperty s) @@ -212,8 +216,12 @@ private static void WriteTestCase(XmlWriter writer, TestNodeUpdateMessage test) { testMethodIdentifier = m; } + else if (fileLocation is null && prop is TestFileLocationProperty f) + { + fileLocation = f; + } - if (stateProperty is not null && timingProperty is not null && testMethodIdentifier is not null) + if (stateProperty is not null && timingProperty is not null && testMethodIdentifier is not null && fileLocation is not null) { break; } @@ -230,6 +238,15 @@ private static void WriteTestCase(XmlWriter writer, TestNodeUpdateMessage test) writer.WriteAttributeString("classname", SanitizeForXml(className)); writer.WriteAttributeString("time", duration.TotalSeconds.ToString("F3", CultureInfo.InvariantCulture)); + // Line numbers are 1-based; a test with no known source location has line 0 and gets neither attribute. + if (fileLocation is { LineSpan.Start.Line: > 0 } && !string.IsNullOrEmpty(fileLocation.FilePath)) + { + var filePath = SourcePathResolver.ToRepoRelativePath(fileLocation.FilePath, sourceControl.Workspace, sourceControl.RepositorySlug) + ?? fileLocation.FilePath; + writer.WriteAttributeString("file", SanitizeForXml(filePath)); + writer.WriteAttributeString("line", fileLocation.LineSpan.Start.Line.ToString(CultureInfo.InvariantCulture)); + } + // Write state-specific child elements switch (stateProperty) { diff --git a/tests/TUnit.UnitTests/JUnitXmlWriterTests.cs b/tests/TUnit.UnitTests/JUnitXmlWriterTests.cs index 9a9ce2c69aa..9c1063e823c 100644 --- a/tests/TUnit.UnitTests/JUnitXmlWriterTests.cs +++ b/tests/TUnit.UnitTests/JUnitXmlWriterTests.cs @@ -1,20 +1,27 @@ +using System.Xml.Linq; using Microsoft.Testing.Platform.Extensions.Messages; using Microsoft.Testing.Platform.TestHost; +using TUnit.Engine.Reporters; using TUnit.Engine.Xml; namespace TUnit.UnitTests; public class JUnitXmlWriterTests { - private static TestNodeUpdateMessage PassedTest() => new( + private static TestNodeUpdateMessage PassedTest(params IProperty[] properties) => new( new SessionUid("session"), new TestNode { Uid = new TestNodeUid("test-1"), DisplayName = "Adds", - Properties = new PropertyBag(PassedTestNodeStateProperty.CachedInstance), + Properties = new PropertyBag([PassedTestNodeStateProperty.CachedInstance, .. properties]), }); + private static TestFileLocationProperty Location(string filePath, int line) => + new(filePath, new LinePositionSpan(new LinePosition(line, 5), new LinePosition(line + 4, 6))); + + private static XElement SingleTestCase(string xml) => XDocument.Parse(xml).Descendants("testcase").Single(); + [Test] public async Task Writes_UnobservedTaskExceptions_To_Suite_SystemErr() { @@ -33,4 +40,35 @@ public async Task Omits_Suite_SystemErr_Without_UnobservedTaskExceptions() await Assert.That(xml).DoesNotContain("system-err"); } + + [Test] + [Arguments(@"C:\src\shop\tests\MathTests.cs", null, null, @"C:\src\shop\tests\MathTests.cs")] + [Arguments("/home/runner/work/shop/shop/tests/MathTests.cs", "/home/runner/work/shop/shop", "octo/shop", "tests/MathTests.cs")] + [Arguments(@"D:\a\shop\shop\tests\MathTests.cs", @"D:\a\shop\shop", "octo/shop", "tests/MathTests.cs")] + [Arguments("/_/tests/MathTests.cs", "/builds/octo/shop", "octo/shop", "tests/MathTests.cs")] + public async Task Writes_TestCase_File_And_Line_From_Test_Location(string filePath, string? workspace, string? repo, string expectedFile) + { + var sourceControl = new SourceControlContext(null, null, null, repo, workspace, null); + + var xml = JUnitXmlWriter.GenerateXml([PassedTest(Location(filePath, 12))], filter: null, sourceControl: sourceControl); + + var testCase = SingleTestCase(xml); + await Assert.That(testCase.Attribute("file")?.Value).IsEqualTo(expectedFile); + await Assert.That(testCase.Attribute("line")?.Value).IsEqualTo("12"); + } + + [Test] + [Arguments(null, 0)] + [Arguments("Unknown", 0)] + [Arguments("", 7)] + public async Task Omits_TestCase_File_And_Line_Without_Known_Location(string? filePath, int line) + { + var test = filePath is null ? PassedTest() : PassedTest(Location(filePath, line)); + + var xml = JUnitXmlWriter.GenerateXml([test], filter: null); + + var testCase = SingleTestCase(xml); + await Assert.That(testCase.Attribute("file")).IsNull(); + await Assert.That(testCase.Attribute("line")).IsNull(); + } }