-
Notifications
You must be signed in to change notification settings - Fork 278
Add Azure DevOps extension to report errors #5260
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
39 changes: 39 additions & 0 deletions
39
src/Platform/Microsoft.Testing.Extensions.AzureDevOps/AzDoEscaper.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
||
using Microsoft.Testing.Platform; | ||
|
||
namespace Microsoft.Testing.Extensions.Reporting; | ||
|
||
internal static class AzDoEscaper | ||
{ | ||
public static string Escape(string value) | ||
{ | ||
if (RoslynString.IsNullOrEmpty(value)) | ||
{ | ||
return value; | ||
} | ||
|
||
var result = new StringBuilder(value.Length); | ||
foreach (char c in value) | ||
{ | ||
switch (c) | ||
{ | ||
case ';': | ||
result.Append("%3B"); | ||
break; | ||
case '\r': | ||
result.Append("%0D"); | ||
break; | ||
case '\n': | ||
result.Append("%0A"); | ||
break; | ||
default: | ||
result.Append(c); | ||
break; | ||
} | ||
} | ||
|
||
return result.ToString(); | ||
} | ||
} |
10 changes: 10 additions & 0 deletions
10
src/Platform/Microsoft.Testing.Extensions.AzureDevOps/AzureDevOpsCommandLineOptions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
||
namespace Microsoft.Testing.Extensions.Reporting; | ||
|
||
internal static class AzureDevOpsCommandLineOptions | ||
{ | ||
public const string AzureDevOpsOptionName = "report-azdo"; | ||
public const string AzureDevOpsReportSeverity = "report-azdo-severity"; | ||
} |
48 changes: 48 additions & 0 deletions
48
src/Platform/Microsoft.Testing.Extensions.AzureDevOps/AzureDevOpsCommandLineProvider.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
||
using Microsoft.Testing.Extensions.AzureDevOps.Resources; | ||
using Microsoft.Testing.Platform.CommandLine; | ||
using Microsoft.Testing.Platform.Extensions; | ||
using Microsoft.Testing.Platform.Extensions.CommandLine; | ||
using Microsoft.Testing.Platform.Helpers; | ||
|
||
namespace Microsoft.Testing.Extensions.Reporting; | ||
|
||
internal sealed class AzureDevOpsCommandLineProvider : ICommandLineOptionsProvider | ||
{ | ||
private static readonly string[] SeverityOptions = ["error", "warning"]; | ||
|
||
public string Uid => nameof(AzureDevOpsCommandLineProvider); | ||
|
||
public string Version => AppVersion.DefaultSemVer; | ||
|
||
public string DisplayName => AzureDevOpsResources.DisplayName; | ||
|
||
public string Description => AzureDevOpsResources.Description; | ||
|
||
public Task<bool> IsEnabledAsync() => Task.FromResult(true); | ||
|
||
public IReadOnlyCollection<CommandLineOption> GetCommandLineOptions() | ||
=> | ||
[ | ||
new CommandLineOption(AzureDevOpsCommandLineOptions.AzureDevOpsOptionName, AzureDevOpsResources.OptionDescription, ArgumentArity.Zero, false), | ||
new CommandLineOption(AzureDevOpsCommandLineOptions.AzureDevOpsReportSeverity, AzureDevOpsResources.SeverityOptionDescription, ArgumentArity.ExactlyOne, false), | ||
]; | ||
|
||
public Task<ValidationResult> ValidateOptionArgumentsAsync(CommandLineOption commandOption, string[] arguments) | ||
{ | ||
if (commandOption.Name == AzureDevOpsCommandLineOptions.AzureDevOpsReportSeverity) | ||
{ | ||
if (!SeverityOptions.Contains(arguments[0], StringComparer.OrdinalIgnoreCase)) | ||
{ | ||
return ValidationResult.InvalidTask(string.Format(CultureInfo.InvariantCulture, AzureDevOpsResources.InvalidSeverity, arguments[0])); | ||
} | ||
} | ||
|
||
return ValidationResult.ValidTask; | ||
} | ||
|
||
public Task<ValidationResult> ValidateCommandLineOptionsAsync(ICommandLineOptions commandLineOptions) | ||
=> ValidationResult.ValidTask; | ||
} |
34 changes: 34 additions & 0 deletions
34
src/Platform/Microsoft.Testing.Extensions.AzureDevOps/AzureDevOpsExtensions.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
||
using Microsoft.Testing.Extensions.Reporting; | ||
using Microsoft.Testing.Extensions.TrxReport.Abstractions; | ||
using Microsoft.Testing.Platform.Builder; | ||
using Microsoft.Testing.Platform.Extensions; | ||
using Microsoft.Testing.Platform.Services; | ||
|
||
namespace Microsoft.Testing.Extensions; | ||
|
||
/// <summary> | ||
/// Provides extension methods for adding Azure DevOps reporting support to the test application builder. | ||
/// </summary> | ||
public static class AzureDevOpsExtensions | ||
{ | ||
/// <summary> | ||
/// Adds support to the test application builder. | ||
/// </summary> | ||
/// <param name="builder">The test application builder.</param> | ||
public static void AddAzureDevOpsProvider(this ITestApplicationBuilder builder) | ||
{ | ||
var compositeTestSessionAzDoService = | ||
new CompositeExtensionFactory<AzureDevOpsReporter>(serviceProvider => | ||
new AzureDevOpsReporter( | ||
serviceProvider.GetCommandLineOptions(), | ||
serviceProvider.GetEnvironment(), | ||
serviceProvider.GetOutputDevice())); | ||
|
||
builder.TestHost.AddDataConsumer(compositeTestSessionAzDoService); | ||
|
||
builder.CommandLine.AddProvider(() => new AzureDevOpsCommandLineProvider()); | ||
} | ||
} |
167 changes: 167 additions & 0 deletions
167
src/Platform/Microsoft.Testing.Extensions.AzureDevOps/AzureDevOpsReporter.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. | ||
// Licensed under the MIT license. See LICENSE file in the project root for full license information. | ||
|
||
using Microsoft.Testing.Extensions.AzureDevOps; | ||
using Microsoft.Testing.Extensions.AzureDevOps.Resources; | ||
using Microsoft.Testing.Extensions.Reporting; | ||
using Microsoft.Testing.Platform; | ||
using Microsoft.Testing.Platform.CommandLine; | ||
using Microsoft.Testing.Platform.Extensions.Messages; | ||
using Microsoft.Testing.Platform.Extensions.OutputDevice; | ||
using Microsoft.Testing.Platform.Extensions.TestHost; | ||
using Microsoft.Testing.Platform.Helpers; | ||
using Microsoft.Testing.Platform.OutputDevice; | ||
|
||
namespace Microsoft.Testing.Extensions.TrxReport.Abstractions; | ||
|
||
internal sealed class AzureDevOpsReporter : | ||
IDataConsumer, | ||
IDataProducer, | ||
IOutputDeviceDataProducer | ||
{ | ||
private readonly IOutputDevice _outputDisplay; | ||
|
||
private static readonly char[] NewlineCharacters = new char[] { '\r', '\n' }; | ||
private readonly ICommandLineOptions _commandLine; | ||
private readonly IEnvironment _environment; | ||
private string _severity = "error"; | ||
|
||
public AzureDevOpsReporter( | ||
ICommandLineOptions commandLine, | ||
IEnvironment environment, | ||
IOutputDevice outputDisplay) | ||
{ | ||
_commandLine = commandLine; | ||
_environment = environment; | ||
_outputDisplay = outputDisplay; | ||
} | ||
|
||
public Type[] DataTypesConsumed { get; } = | ||
[ | ||
typeof(TestNodeUpdateMessage) | ||
]; | ||
|
||
public Type[] DataTypesProduced { get; } = [typeof(SessionFileArtifact)]; | ||
|
||
/// <inheritdoc /> | ||
public string Uid { get; } = nameof(AzureDevOpsReporter); | ||
|
||
/// <inheritdoc /> | ||
public string Version { get; } = AppVersion.DefaultSemVer; | ||
|
||
/// <inheritdoc /> | ||
public string DisplayName { get; } = AzureDevOpsResources.DisplayName; | ||
|
||
/// <inheritdoc /> | ||
public string Description { get; } = AzureDevOpsResources.Description; | ||
|
||
/// <inheritdoc /> | ||
public Task<bool> IsEnabledAsync() | ||
{ | ||
bool isEnabled = _commandLine.IsOptionSet(AzureDevOpsCommandLineOptions.AzureDevOpsOptionName) | ||
&& string.Equals(_environment.GetEnvironmentVariable("TF_BUILD"), "true", StringComparison.OrdinalIgnoreCase); | ||
|
||
if (isEnabled) | ||
{ | ||
bool found = _commandLine.TryGetOptionArgumentList(AzureDevOpsCommandLineOptions.AzureDevOpsReportSeverity, out string[]? arguments); | ||
if (found && arguments?.Length > 0) | ||
{ | ||
_severity = arguments[0].ToLowerInvariant(); | ||
} | ||
} | ||
|
||
return Task.FromResult(isEnabled); | ||
} | ||
|
||
public async Task ConsumeAsync(IDataProducer dataProducer, IData value, CancellationToken cancellationToken) | ||
{ | ||
if (cancellationToken.IsCancellationRequested) | ||
{ | ||
return; | ||
} | ||
|
||
if (value is not TestNodeUpdateMessage nodeUpdateMessage) | ||
{ | ||
return; | ||
} | ||
|
||
TestNodeStateProperty nodeState = nodeUpdateMessage.TestNode.Properties.Single<TestNodeStateProperty>(); | ||
|
||
switch (nodeState) | ||
{ | ||
case FailedTestNodeStateProperty failed: | ||
await WriteExceptionAsync(failed.Explanation, failed.Exception); | ||
break; | ||
case ErrorTestNodeStateProperty error: | ||
await WriteExceptionAsync(error.Explanation, error.Exception); | ||
break; | ||
case CancelledTestNodeStateProperty cancelled: | ||
await WriteExceptionAsync(cancelled.Explanation, cancelled.Exception); | ||
break; | ||
case TimeoutTestNodeStateProperty timeout: | ||
await WriteExceptionAsync(timeout.Explanation, timeout.Exception); | ||
break; | ||
} | ||
|
||
return; | ||
nohwnd marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
private async Task WriteExceptionAsync(string? explanation, Exception? exception) | ||
{ | ||
if (exception == null || exception.StackTrace == null) | ||
{ | ||
return; | ||
} | ||
|
||
string message = explanation ?? exception.Message; | ||
|
||
if (message == null) | ||
{ | ||
return; | ||
} | ||
|
||
string stackTrace = exception.StackTrace; | ||
nohwnd marked this conversation as resolved.
Show resolved
Hide resolved
|
||
int index = stackTrace.IndexOfAny(NewlineCharacters); | ||
string firstLine = index == -1 ? stackTrace : stackTrace.Substring(0, index); | ||
if (firstLine != null) | ||
{ | ||
(string Code, string File, int LineNumber)? location = GetStackFrameLocation(firstLine); | ||
if (location != null) | ||
{ | ||
string root = RootFinder.Find(); | ||
string file = location.Value.File; | ||
string relativePath = file.StartsWith(root, StringComparison.CurrentCultureIgnoreCase) ? file.Substring(root.Length) : file; | ||
string relativeNormalizedPath = relativePath.Replace('\\', '/'); | ||
|
||
string err = AzDoEscaper.Escape(message); | ||
|
||
string line = $"##vso[task.logissue type={_severity};sourcepath={relativeNormalizedPath};linenumber={location.Value.LineNumber};columnnumber=1]{err}"; | ||
await _outputDisplay.DisplayAsync(this, new FormattedTextOutputDeviceData(line)); | ||
} | ||
} | ||
} | ||
|
||
internal /* for testing */ static (string Code, string File, int LineNumber)? GetStackFrameLocation(string stackTraceLine) | ||
{ | ||
Match match = StackTraceHelper.GetFrameRegex().Match(stackTraceLine); | ||
if (!match.Success) | ||
{ | ||
return null; | ||
} | ||
|
||
bool weHaveFilePathAndCodeLine = !RoslynString.IsNullOrWhiteSpace(match.Groups["code"].Value); | ||
if (!weHaveFilePathAndCodeLine) | ||
{ | ||
return null; | ||
} | ||
|
||
if (RoslynString.IsNullOrWhiteSpace(match.Groups["file"].Value)) | ||
{ | ||
return null; | ||
} | ||
|
||
int line = int.TryParse(match.Groups["line"].Value, out int value) ? value : 0; | ||
|
||
return (match.Groups["code"].Value, match.Groups["file"].Value, line); | ||
} | ||
} |
10 changes: 10 additions & 0 deletions
10
src/Platform/Microsoft.Testing.Extensions.AzureDevOps/BannedSymbols.txt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
T:System.ArgumentNullException; Use 'ArgumentGuard' instead | ||
P:System.DateTime.Now; Use 'IClock' instead | ||
P:System.DateTime.UtcNow; Use 'IClock' instead | ||
M:System.Threading.Tasks.Task.Run(System.Action); Use 'ITask' instead | ||
M:System.Threading.Tasks.Task.WhenAll(System.Threading.Tasks.Task[]); Use 'ITask' instead | ||
M:System.Threading.Tasks.Task.WhenAll(System.Collections.Generic.IEnumerable{System.Threading.Tasks.Task}); Use 'ITask' instead | ||
M:System.String.IsNullOrEmpty(System.String); Use 'RoslynString.IsNullOrEmpty' instead | ||
M:System.String.IsNullOrWhiteSpace(System.String); Use 'RoslynString.IsNullOrWhiteSpace' instead | ||
M:System.Diagnostics.Debug.Assert(System.Boolean); Use 'RoslynDebug.Assert' instead | ||
M:System.Diagnostics.Debug.Assert(System.Boolean,System.String); Use 'RoslynDebug.Assert' instead |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.