|
| 1 | +using System; |
| 2 | +using System.IO; |
| 3 | +using System.Linq; |
| 4 | +using System.Reflection; |
| 5 | +using Microsoft.CodeAnalysis; |
| 6 | +using Microsoft.CodeAnalysis.CSharp; |
| 7 | +using Microsoft.CodeAnalysis.Text; |
| 8 | +using NUnit.Framework; |
| 9 | + |
| 10 | +namespace NativeInvoke.Tests.AttributeValidation; |
| 11 | + |
| 12 | +/// <summary> |
| 13 | +/// Tests to verify that NativeInvoke attributes are properly stripped from compiled assemblies |
| 14 | +/// when consumed as a NuGet package (compile-time only dependency) |
| 15 | +/// </summary> |
| 16 | +[TestFixture] |
| 17 | +public class AttributeStrippingTests |
| 18 | +{ |
| 19 | + private const string TestSourceCode = @" |
| 20 | +using System; |
| 21 | +using NativeInvoke; |
| 22 | +
|
| 23 | +namespace TestNamespace |
| 24 | +{ |
| 25 | + public class TestClass |
| 26 | + { |
| 27 | + [NativeImport(""kernel32"")] |
| 28 | + public static partial IKernel32 Kernel32 { get; } |
| 29 | +
|
| 30 | + [NativeImport(""user32"")] |
| 31 | + public static partial IUser32 User32 { get; } |
| 32 | + } |
| 33 | +
|
| 34 | + public interface IKernel32 |
| 35 | + { |
| 36 | + [NativeImportMethod(EntryPoint = ""Beep"")] |
| 37 | + int Beep(uint dwFreq, uint dwDuration); |
| 38 | + } |
| 39 | +
|
| 40 | + public unsafe interface IUser32 |
| 41 | + { |
| 42 | + [NativeImportMethod(EntryPoint = ""MessageBoxA"")] |
| 43 | + int MessageBox(IntPtr hWnd, sbyte* lpText, sbyte* lpCaption, uint uType); |
| 44 | + } |
| 45 | +}"; |
| 46 | + |
| 47 | + [Test] |
| 48 | + public void CompiledAssembly_ShouldNotContainNativeImportAttributes() |
| 49 | + { |
| 50 | + // Arrange |
| 51 | + var assembly = CreateTestCompilation(); |
| 52 | + |
| 53 | + // Act |
| 54 | + var attributeTypes = assembly.GetTypes() |
| 55 | + .Where(t => t.Name.Contains("NativeImportAttribute")) |
| 56 | + .ToArray(); |
| 57 | + |
| 58 | + // Assert |
| 59 | + Assert.That(attributeTypes, Is.Empty, |
| 60 | + "NativeImportAttribute and NativeImportMethodAttribute should be stripped from compiled assembly"); |
| 61 | + } |
| 62 | + |
| 63 | + [Test] |
| 64 | + public void CompiledAssembly_ShouldContainGeneratedImplementationClasses() |
| 65 | + { |
| 66 | + // Arrange |
| 67 | + var assembly = CreateTestCompilation(); |
| 68 | + |
| 69 | + // Act |
| 70 | + var generatedTypes = assembly.GetTypes() |
| 71 | + .Where(t => t.Name.StartsWith("__Impl_")) |
| 72 | + .ToArray(); |
| 73 | + |
| 74 | + // Assert |
| 75 | + Assert.That(generatedTypes, Is.Not.Empty, |
| 76 | + "Generated implementation classes should be present"); |
| 77 | + Assert.That(generatedTypes.Length, Is.GreaterThanOrEqualTo(2), |
| 78 | + "Should have at least 2 generated implementations (Kernel32 and User32)"); |
| 79 | + } |
| 80 | + |
| 81 | + [Test] |
| 82 | + public void CompiledAssembly_ShouldContainGeneratedTestClass() |
| 83 | + { |
| 84 | + // Arrange |
| 85 | + var assembly = CreateTestCompilation(); |
| 86 | + |
| 87 | + // Act |
| 88 | + var testClassType = assembly.GetType("TestNamespace.TestClass"); |
| 89 | + |
| 90 | + // Assert |
| 91 | + Assert.That(testClassType, Is.Not.Null, |
| 92 | + "Test class should be present in compiled assembly"); |
| 93 | + } |
| 94 | + |
| 95 | + [Test] |
| 96 | + public void GeneratedCode_ShouldNotHaveAttributeCustomAttributes() |
| 97 | + { |
| 98 | + // Arrange |
| 99 | + var assembly = CreateTestCompilation(); |
| 100 | + |
| 101 | + // Act |
| 102 | + var testClassType = assembly.GetType("TestNamespace.TestClass"); |
| 103 | + var properties = testClassType?.GetProperties(); |
| 104 | + |
| 105 | + // Assert |
| 106 | + Assert.That(properties, Is.Not.Null, "Properties should exist"); |
| 107 | + |
| 108 | + foreach (var property in properties) |
| 109 | + { |
| 110 | + var attributes = property.GetCustomAttributes(false); |
| 111 | + var nativeImportAttributes = attributes |
| 112 | + .Where(a => a.GetType().Name.Contains("NativeImportAttribute")) |
| 113 | + .ToArray(); |
| 114 | + |
| 115 | + Assert.That(nativeImportAttributes, Is.Empty, |
| 116 | + $"Property '{property.Name}' should not have NativeImportAttribute in compiled assembly"); |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + [Test] |
| 121 | + public void GeneratedInterfaces_ShouldNotHaveAttributeCustomAttributes() |
| 122 | + { |
| 123 | + // Arrange |
| 124 | + var assembly = CreateTestCompilation(); |
| 125 | + |
| 126 | + // Act |
| 127 | + var kernel32Type = assembly.GetType("TestNamespace.IKernel32"); |
| 128 | + var user32Type = assembly.GetType("TestNamespace.IUser32"); |
| 129 | + |
| 130 | + // Assert |
| 131 | + Assert.That(kernel32Type, Is.Not.Null, "IKernel32 interface should be present"); |
| 132 | + Assert.That(user32Type, Is.Not.Null, "IUser32 interface should be present"); |
| 133 | + |
| 134 | + var kernel32Methods = kernel32Type.GetMethods(); |
| 135 | + var user32Methods = user32Type.GetMethods(); |
| 136 | + |
| 137 | + foreach (var method in kernel32Methods.Concat(user32Methods)) |
| 138 | + { |
| 139 | + var attributes = method.GetCustomAttributes(false); |
| 140 | + var nativeImportMethodAttributes = attributes |
| 141 | + .Where(a => a.GetType().Name.Contains("NativeImportMethodAttribute")) |
| 142 | + .ToArray(); |
| 143 | + |
| 144 | + Assert.That(nativeImportMethodAttributes, Is.Empty, |
| 145 | + $"Method '{method.Name}' should not have NativeImportMethodAttribute in compiled assembly"); |
| 146 | + } |
| 147 | + } |
| 148 | + |
| 149 | + [Test] |
| 150 | + public void AssemblyMetadata_ShouldIndicateDevelopmentDependency() |
| 151 | + { |
| 152 | + // Arrange |
| 153 | + var assembly = CreateTestCompilation(); |
| 154 | + |
| 155 | + // Act |
| 156 | + var referencedAssemblies = assembly.GetReferencedAssemblies() |
| 157 | + .Where(r => r.Name.Contains("NativeInvoke")) |
| 158 | + .ToArray(); |
| 159 | + |
| 160 | + // Assert |
| 161 | + Assert.That(referencedAssemblies, Is.Empty, |
| 162 | + "Compiled assembly should not reference NativeInvoke assemblies (development dependency)"); |
| 163 | + } |
| 164 | + |
| 165 | + private static Assembly CreateTestCompilation() |
| 166 | + { |
| 167 | + // Create syntax tree from test source |
| 168 | + var syntaxTree = CSharpSyntaxTree.ParseText(TestSourceCode); |
| 169 | + |
| 170 | + // Define compilation options |
| 171 | + var compilationOptions = new CSharpCompilationOptions( |
| 172 | + OutputKind.DynamicallyLinkedLibrary, |
| 173 | + optimizationLevel: OptimizationLevel.Release, |
| 174 | + allowUnsafe: true); |
| 175 | + |
| 176 | + // Create compilation with necessary references |
| 177 | + var compilation = CSharpCompilation.Create( |
| 178 | + "TestAssembly", |
| 179 | + new[] { syntaxTree }, |
| 180 | + GetMetadataReferences(), |
| 181 | + compilationOptions); |
| 182 | + |
| 183 | + // Add the NativeInvoke source generator |
| 184 | + var generator = new NativeInvoke.Generator.NativeImportGenerator(); |
| 185 | + var driver = CSharpGeneratorDriver.Create(generator); |
| 186 | + var x = driver.RunGeneratorsAndUpdateCompilation(compilation, out var updatedCompilation, out _); |
| 187 | + return EmitAssembly((CSharpCompilation)updatedCompilation); |
| 188 | + } |
| 189 | + |
| 190 | + private static PortableExecutableReference[] GetMetadataReferences() |
| 191 | + { |
| 192 | + var assemblies = new[] |
| 193 | + { |
| 194 | + typeof(object).Assembly, // System.Runtime |
| 195 | + typeof(Attribute).Assembly, // System.Runtime |
| 196 | + typeof(System.Runtime.CompilerServices.NullableAttribute).Assembly, // System.Runtime |
| 197 | + typeof(System.IntPtr).Assembly, // System.Runtime.InteropServices |
| 198 | + typeof(System.Runtime.InteropServices.NativeLibrary).Assembly, |
| 199 | + }; |
| 200 | + |
| 201 | + return assemblies |
| 202 | + .Select(a => MetadataReference.CreateFromFile(a.Location)) |
| 203 | + .ToArray(); |
| 204 | + } |
| 205 | + |
| 206 | + private static Assembly EmitAssembly(CSharpCompilation compilation) |
| 207 | + { |
| 208 | + using var ms = new MemoryStream(); |
| 209 | + var result = compilation.Emit(ms); |
| 210 | + |
| 211 | + if (!result.Success) |
| 212 | + { |
| 213 | + var errors = string.Join(Environment.NewLine, |
| 214 | + result.Diagnostics.Where(d => d.IsWarningAsError || d.Severity == DiagnosticSeverity.Error)); |
| 215 | + throw new InvalidOperationException($"Compilation failed: {errors}"); |
| 216 | + } |
| 217 | + |
| 218 | + return Assembly.Load(ms.ToArray()); |
| 219 | + } |
| 220 | +} |
| 221 | + |
| 222 | +/// <summary> |
| 223 | +/// Extension methods for compilation testing |
| 224 | +/// </summary> |
| 225 | +public static class CompilationExtensions |
| 226 | +{ |
| 227 | + public static Assembly EmitAssembly(this CSharpCompilation compilation) |
| 228 | + { |
| 229 | + using var ms = new MemoryStream(); |
| 230 | + var result = compilation.Emit(ms); |
| 231 | + |
| 232 | + if (!result.Success) |
| 233 | + { |
| 234 | + var errors = string.Join(Environment.NewLine, |
| 235 | + result.Diagnostics.Where(d => d.IsWarningAsError || d.Severity == DiagnosticSeverity.Error)); |
| 236 | + throw new InvalidOperationException($"Compilation failed: {errors}"); |
| 237 | + } |
| 238 | + |
| 239 | + return Assembly.Load(ms.ToArray()); |
| 240 | + } |
| 241 | +} |
0 commit comments