Skip to content

Commit 46d7dca

Browse files
committed
Add utility for verifying razor diagnostics
1 parent 11e6f0c commit 46d7dca

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

src/Compiler/test/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/RazorSourceGeneratorTestsBase.cs

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -545,4 +545,18 @@ public static void AssertPair(this RazorEventListener.RazorEvent e, string expec
545545
Assert.Equal(payload1, e.Payload[0]);
546546
Assert.Equal(payload2, e.Payload[1]);
547547
}
548+
549+
public static void VerifyRazor(
550+
this IEnumerable<Diagnostic> diagnostics,
551+
Project project,
552+
params DiagnosticDescription[] expected)
553+
{
554+
var mappedDiagnostics = diagnostics.PretendTheseAreCSharpDiagnostics(path =>
555+
{
556+
var document = project.AdditionalDocuments.Single(d => d.Name == path);
557+
Assert.True(document.TryGetText(out var text));
558+
return text;
559+
});
560+
mappedDiagnostics.Verify(expected);
561+
}
548562
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
4+
using System;
5+
using System.Collections.Generic;
6+
using System.Linq;
7+
using Microsoft.CodeAnalysis.CSharp;
8+
using Microsoft.CodeAnalysis.Text;
9+
10+
namespace Microsoft.CodeAnalysis;
11+
12+
public static class RazorDiagnosticExtensions
13+
{
14+
/// <summary>
15+
/// Provides better experience when verifying diagnostics in tests - includes squiggled text and code snippet.
16+
/// </summary>
17+
public static IEnumerable<Diagnostic> PretendTheseAreCSharpDiagnostics(
18+
this IEnumerable<Diagnostic> diagnostics,
19+
Func<string, SourceText> filePathToContent)
20+
{
21+
var texts = new Dictionary<string, SourceText>();
22+
return diagnostics.Select(d =>
23+
{
24+
if (d.Location is { Kind: LocationKind.ExternalFile } originalLocation)
25+
{
26+
var mappedSpan = originalLocation.GetMappedLineSpan();
27+
var path = mappedSpan.Path;
28+
var text = texts.GetOrAdd(path, filePathToContent);
29+
var syntaxTree = CSharpSyntaxTree.ParseText(text, path: path);
30+
var span = text.Lines.GetTextSpan(mappedSpan.Span);
31+
var location = Location.Create(syntaxTree, span);
32+
return Diagnostic.Create(d.Descriptor, location);
33+
}
34+
35+
return d;
36+
});
37+
}
38+
}

0 commit comments

Comments
 (0)