|
| 1 | +using Xunit; |
| 2 | +using System.IO; |
| 3 | +using System.Text; |
| 4 | +using Microsoft.CodeAnalysis; |
| 5 | +using Microsoft.CodeAnalysis.CSharp; |
| 6 | +using Semmle.Extraction.CSharp.StubGenerator; |
| 7 | + |
| 8 | +namespace Semmle.Extraction.Tests; |
| 9 | +/// <summary> |
| 10 | +/// Tests for the stub generator. |
| 11 | +/// |
| 12 | +/// These tests can be used to more easily step debug the stub generator SymbolVisitor. |
| 13 | +/// </summary> |
| 14 | +public class StubGeneratorTests |
| 15 | +{ |
| 16 | + [Fact] |
| 17 | + public void StubGeneratorFieldTest() |
| 18 | + { |
| 19 | + // Setup |
| 20 | + const string source = @" |
| 21 | +public class MyTest { |
| 22 | + public static readonly int MyField1; |
| 23 | + public const string MyField2 = ""hello""; |
| 24 | + } |
| 25 | +"; |
| 26 | + |
| 27 | + // Execute |
| 28 | + var stub = GenerateStub(source); |
| 29 | + |
| 30 | + // Verify |
| 31 | + const string expected = @"public class MyTest { |
| 32 | +public static readonly int MyField1; |
| 33 | +public const string MyField2 = default; |
| 34 | +} |
| 35 | +"; |
| 36 | + Assert.Equal(expected, stub); |
| 37 | + } |
| 38 | + |
| 39 | + [Fact] |
| 40 | + public void StubGeneratorMethodTest() |
| 41 | + { |
| 42 | + // Setup |
| 43 | + const string source = @" |
| 44 | +public class MyTest { |
| 45 | + public int M1(string arg1) { return 0;} |
| 46 | +}"; |
| 47 | + |
| 48 | + // Execute |
| 49 | + var stub = GenerateStub(source); |
| 50 | + |
| 51 | + // Verify |
| 52 | + const string expected = @"public class MyTest { |
| 53 | +public int M1(string arg1) => throw null; |
| 54 | +} |
| 55 | +"; |
| 56 | + Assert.Equal(expected, stub); |
| 57 | + } |
| 58 | + |
| 59 | + private static string GenerateStub(string source) |
| 60 | + { |
| 61 | + var st = CSharpSyntaxTree.ParseText(source); |
| 62 | + var compilation = CSharpCompilation.Create(null, new[] { st }); |
| 63 | + var sb = new StringBuilder(); |
| 64 | + var visitor = new StubVisitor(new StringWriter(sb), new RelevantSymbolStub()); |
| 65 | + compilation.GlobalNamespace.Accept(visitor); |
| 66 | + return sb.ToString(); |
| 67 | + } |
| 68 | + |
| 69 | + private class RelevantSymbolStub : IRelevantSymbol |
| 70 | + { |
| 71 | + public bool IsRelevantNamedType(INamedTypeSymbol symbol) => true; |
| 72 | + public bool IsRelevantNamespace(INamespaceSymbol symbol) => true; |
| 73 | + } |
| 74 | +} |
0 commit comments