Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 138 additions & 0 deletions src/Tests/ProjectionWriterTest/Helpers/TypeFilteringMetadata.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.IO;
using System.Linq;
using AsmResolver.DotNet;
using AsmResolver.DotNet.Signatures;
using AsmResolver.PE.DotNet.Metadata.Tables;

namespace ProjectionWriterTest.Helpers;

/// <summary>
/// Creates synthetic metadata whose excluded types collide with a selected runtime class's name.
/// </summary>
internal static class TypeFilteringMetadata
{
public static string Create(string directory)
{
ModuleDefinition module = new("Contoso.winmd")
{
RuntimeVersion = "WindowsRuntime 1.4"
};

_ = new AssemblyDefinition("Contoso", new Version(255, 255, 255, 255))
{
Modules = { module },
Attributes = AssemblyAttributes.ContentWindowsRuntime
};

AssemblyReference corlib = (AssemblyReference)module.CorLibTypeFactory.CorLibScope;
corlib.Version = new Version(255, 255, 255, 255);

AssemblyReference foundation = new("Windows.Foundation.FoundationContract", new Version(255, 255, 255, 255))
{
Attributes = AssemblyAttributes.ContentWindowsRuntime
};

TypeSignature systemType = new TypeReference(module, corlib, "System", "Type").ToTypeSignature(false);

CustomAttribute Attribute(string name, params CustomAttributeArgument[] arguments)
{
TypeReference attributeType = new(module, foundation, "Windows.Foundation.Metadata", name);
MemberReference constructor = new(attributeType, ".ctor", MethodSignature.CreateInstance(
module.CorLibTypeFactory.Void, arguments.Select(static argument => argument.ArgumentType).ToArray()));

return new CustomAttribute(constructor, new CustomAttributeSignature(arguments));
}

void AddGuid(TypeDefinition type, Guid iid)
{
byte[] bytes = iid.ToByteArray();

type.CustomAttributes.Add(Attribute("GuidAttribute",
new(module.CorLibTypeFactory.UInt32, BitConverter.ToUInt32(bytes, 0)),
new(module.CorLibTypeFactory.UInt16, BitConverter.ToUInt16(bytes, 4)),
new(module.CorLibTypeFactory.UInt16, BitConverter.ToUInt16(bytes, 6)),
new(module.CorLibTypeFactory.Byte, bytes[8]),
new(module.CorLibTypeFactory.Byte, bytes[9]),
new(module.CorLibTypeFactory.Byte, bytes[10]),
new(module.CorLibTypeFactory.Byte, bytes[11]),
new(module.CorLibTypeFactory.Byte, bytes[12]),
new(module.CorLibTypeFactory.Byte, bytes[13]),
new(module.CorLibTypeFactory.Byte, bytes[14]),
new(module.CorLibTypeFactory.Byte, bytes[15])));
}

TypeDefinition AddInterface(string ns, string name, Guid iid)
{
TypeDefinition type = new(ns, name,
TypeAttributes.Public | TypeAttributes.Interface | TypeAttributes.Abstract | TypeAttributes.WindowsRuntime);

module.TopLevelTypes.Add(type);
AddGuid(type, iid);

return type;
}

void AddMethod(TypeDefinition type, string name, TypeSignature returnType, params TypeSignature[] parameters)
{
type.Methods.Add(new MethodDefinition(name,
MethodAttributes.Public | MethodAttributes.Abstract | MethodAttributes.Virtual | MethodAttributes.NewSlot | MethodAttributes.HideBySig,
MethodSignature.CreateInstance(returnType, parameters)));
}

TypeDefinition AddClass(string ns, string name, Guid defaultIid, Guid staticIid)
{
TypeDefinition type = new(ns, name,
TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.WindowsRuntime,
module.CorLibTypeFactory.Object.Type);

module.TopLevelTypes.Add(type);

TypeDefinition defaultInterface = AddInterface(ns, $"I{name}", defaultIid);
defaultInterface.CustomAttributes.Add(Attribute("ExclusiveToAttribute", new CustomAttributeArgument(systemType, type.ToTypeSignature())));
AddMethod(defaultInterface, "GetValue", module.CorLibTypeFactory.Object);

InterfaceImplementation implementation = new(defaultInterface);
implementation.CustomAttributes.Add(Attribute("DefaultAttribute"));
type.Interfaces.Add(implementation);

TypeDefinition statics = AddInterface(ns, $"I{name}Statics", staticIid);
statics.CustomAttributes.Add(Attribute("ExclusiveToAttribute", new CustomAttributeArgument(systemType, type.ToTypeSignature())));
AddMethod(statics, "GetStaticValue", module.CorLibTypeFactory.Int32);
type.CustomAttributes.Add(Attribute("StaticAttribute",
new(systemType, statics.ToTypeSignature()),
new(module.CorLibTypeFactory.UInt32, 1u)));

return defaultInterface;
}

_ = AddClass("Contoso", "User",
new Guid("A3DD8A5E-90C1-4E15-B3A8-95444C622501"),
new Guid("A3DD8A5E-90C1-4E15-B3A8-95444C622502"));
_ = AddClass("Contoso", "User2",
new Guid("A3DD8A5E-90C1-4E15-B3A8-95444C622503"),
new Guid("A3DD8A5E-90C1-4E15-B3A8-95444C622504"));
TypeDefinition omittedInterface = AddClass("Contoso.UserProfile", "UserSetupManager",
new Guid("A3DD8A5E-90C1-4E15-B3A8-95444C622505"),
new Guid("A3DD8A5E-90C1-4E15-B3A8-95444C622506"));

// These signatures are intentionally unsupported. Excluding their declaring types from the
// reference projection must also exclude them when regenerating the implementation.
TypeDefinition propertyValue = AddInterface("Windows.Foundation", "IPropertyValue",
new Guid("4BD682DD-7554-40E9-9A9B-82654EDE7E62"));
TypeDefinition asyncOperation = AddInterface("Windows.Foundation", "IAsyncOperation`1",
new Guid("9FC2B0BB-E446-44E2-AA61-9CAB8F636AF2"));
asyncOperation.GenericParameters.Add(new GenericParameter("T"));

AddMethod(omittedInterface, "SetProperty", module.CorLibTypeFactory.Void, propertyValue.ToTypeSignature());
AddMethod(omittedInterface, "GetPropertyAsync", new GenericInstanceTypeSignature(asyncOperation, false, [propertyValue.ToTypeSignature()]));

string path = Path.Combine(directory, "Contoso.winmd");
module.Write(path);

return path;
}
}
6 changes: 6 additions & 0 deletions src/Tests/ProjectionWriterTest/ProjectionWriterTest.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,19 @@
match the path published as assembly metadata below.
-->
<ItemGroup>
<ProjectReference Include="..\..\WinRT.Projection.Writer\WinRT.Projection.Writer.csproj"
UndefineProperties="BuildToolArch;PublishBuildTool;RuntimeIdentifier;SelfContained;Platform" />
<ProjectReference Include="..\..\WinRT.Projection.Ref.Generator\WinRT.Projection.Ref.Generator.csproj"
ReferenceOutputAssembly="false"
OutputItemType="_CsWinRTToolReference"
UndefineProperties="BuildToolArch;PublishBuildTool;RuntimeIdentifier;SelfContained;Platform"
Private="false" />
</ItemGroup>

<ItemGroup>
<Compile Include="..\..\WinRT.Projection.Writer\Helpers\TypeFilter.cs" Link="Helpers\TypeFilter.cs" />
</ItemGroup>

<!-- Pass the built tool and the pinned WinUI metadata paths to the tests via assembly metadata. -->
<ItemGroup>
<AssemblyMetadata Include="ProjectionRefGeneratorAssemblyPath"
Expand Down
113 changes: 113 additions & 0 deletions src/Tests/ProjectionWriterTest/Test_TypeFilter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using WindowsRuntime.ProjectionWriter.Helpers;

namespace ProjectionWriterTest;

[TestClass]
public class Test_TypeFilter
{
[TestMethod]
[DataRow("Contoso.User", true)]
[DataRow("Contoso.User2", false)]
[DataRow("Contoso.UserProfile.UserSetupManager", false)]
[DataRow("Contoso.User.Profile", false)]
[DataRow("Contoso.Users.User", false)]
[DataRow("contoso.User", false)]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

so we are saying here this one is case sensitive right?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah it should be, namespaces are case sensitive in .NET

[DataRow("Unrelated.User", false)]
public void ExactTypeIncludes_DoNotMatchPrefixes(string name, bool expected)
{
TypeFilter filter = new([], [], ["Contoso.User"]);

Assert.AreEqual(expected, filter.Includes(name));
}

[TestMethod]
[DataRow("Contoso.User", true)]
[DataRow("Contoso.User2", true)]
[DataRow("Contoso.UserProfile.UserSetupManager", true)]
[DataRow("Unrelated.User", false)]
public void PrefixIncludes_KeepExistingSemantics(string name, bool expected)
{
TypeFilter filter = new(["Contoso.User"], []);

Assert.AreEqual(expected, filter.Includes(name));
}

[TestMethod]
[DataRow("Windows", "Windows.UI.Xaml", "Windows.Foundation.Uri", true)]
[DataRow("Windows", "Windows.UI.Xaml", "Windows.UI.Xaml.Controls.Button", false)]
[DataRow("Windows.UI.Xaml", "Windows", "Windows.UI.Xaml.Controls.Button", true)]
[DataRow("Windows.UI.Xaml", "Windows", "Windows.Foundation.Uri", false)]
[DataRow("Contoso.User", "Contoso.User", "Contoso.User", false)]
public void PrefixRules_LongestMatchWinsWithExcludeTies(string include, string exclude, string name, bool expected)
{
TypeFilter filter = new([include], [exclude]);

Assert.AreEqual(expected, filter.Includes(name));
}

[TestMethod]
[DataRow("Windows", true)]
[DataRow("WindowsExtension", true)]
[DataRow("WindowsExtension.User", false)]
public void ExactTypeIncludes_RespectExcludePrecedence(string exclude, bool expected)
{
TypeFilter filter = new([], [exclude], ["WindowsExtension.User"]);

Assert.AreEqual(expected, filter.Includes("WindowsExtension.User"));
}

[TestMethod]
[DataRow("Contoso.User", true)]
[DataRow("Contoso.User2", false)]
[DataRow("Microsoft.UI.Xaml.Controls.Button", true)]
[DataRow("Microsoft.UI.Xaml.Excluded.Type", false)]
public void ExactTypesAndNamespacePrefixes_CanBeCombined(string name, bool expected)
{
TypeFilter filter = new(["Microsoft.UI"], ["Microsoft.UI.Xaml.Excluded"], ["Contoso.User"]);

Assert.AreEqual(expected, filter.Includes(name));
}

[TestMethod]
[DataRow("Contoso")]
[DataRow("Contoso.User")]
[DataRow("Contoso.UserProfile")]
[DataRow("Microsoft.UI.Xaml")]
public void ExactTypeIncludes_DoNotIncludeNamespaceAdditions(string ns)
{
TypeFilter filter = new([], [], ["Contoso.User"]);

Assert.IsFalse(filter.IncludesNamespace(ns));
}

[TestMethod]
public void NamespaceIncludes_StillIncludeAdditionsAlongsideExactTypes()
{
TypeFilter filter = new(["Microsoft.UI"], [], ["Contoso.User"]);

Assert.IsTrue(filter.IncludesNamespace("Microsoft.UI.Xaml"));
Assert.IsFalse(filter.IncludesNamespace("Contoso.User"));
}

[TestMethod]
public void EmptyFilter_IncludesEverything()
{
TypeFilter filter = new([], []);

Assert.IsTrue(filter.Includes("Contoso.User"));
Assert.IsTrue(filter.IncludesNamespace("Contoso"));
}

[TestMethod]
public void ExcludeOnlyFilter_IncludesNothing()
{
TypeFilter filter = new([], ["Windows"]);

Assert.IsFalse(filter.Includes("Windows.Foundation.Uri"));
Assert.IsFalse(filter.Includes("Contoso.User"));
Assert.IsFalse(filter.IncludesNamespace("Contoso"));
}
}
102 changes: 102 additions & 0 deletions src/Tests/ProjectionWriterTest/Test_TypeFiltering.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.IO;
using System.Linq;
using ProjectionWriterTest.Helpers;
using WindowsRuntime.ProjectionWriter;

namespace ProjectionWriterTest;

[TestClass]
public class Test_TypeFiltering
{
[TestMethod]
[DataRow(true)]
[DataRow(false)]
public void ExactTypeIncludes_OmitCollidingTypes(bool referenceProjection)
{
WithMetadata((inputPath, outputFolder) =>
{
ProjectionWriter.Run(new ProjectionWriterOptions
{
InputPaths = [inputPath],
OutputFolder = outputFolder,
IncludeTypes = ["Contoso.User"],
ReferenceProjection = referenceProjection
});

AssertSelectedTypes(outputFolder);
});
}

[TestMethod]
public void ReferenceProjection_PrefixExclusionsOmitUnsupportedTypes()
{
WithMetadata((inputPath, outputFolder) =>
{
ProjectionWriter.Run(new ProjectionWriterOptions
{
InputPaths = [inputPath],
OutputFolder = outputFolder,
Include = ["Contoso"],
Exclude = ["Contoso.User2", "Contoso.IUser2", "Contoso.UserProfile"],
ReferenceProjection = true
});

AssertSelectedTypes(outputFolder);
});
}

[TestMethod]
public void ExactTypeIncludes_StillEmitExclusiveFactoryInfrastructure()
{
WithMetadata((inputPath, outputFolder) =>
{
ProjectionWriter.Run(new ProjectionWriterOptions
{
InputPaths = [inputPath],
OutputFolder = outputFolder,
IncludeTypes = ["Contoso.User"]
});

string source = File.ReadAllText(Path.Combine(outputFolder, "Contoso.cs"));
string iids = File.ReadAllText(Path.Combine(outputFolder, "GeneratedInterfaceIIDs.cs"));

StringAssert.Contains(source, "GetValue");
StringAssert.Contains(source, "GetStaticValue");
StringAssert.Contains(source, "IUserStaticsMethods");
StringAssert.Contains(iids, "IUserStatics");
StringAssert.Contains(iids, "IUser");
});
}

private static void AssertSelectedTypes(string outputFolder)
{
string source = File.ReadAllText(Path.Combine(outputFolder, "Contoso.cs"));

StringAssert.Contains(source, "class User");
Assert.IsFalse(source.Contains("User2", StringComparison.Ordinal));
Assert.IsFalse(File.Exists(Path.Combine(outputFolder, "Contoso.UserProfile.cs")));

string allSources = string.Join(Environment.NewLine, Directory.GetFiles(outputFolder, "*.cs").Select(File.ReadAllText));

Assert.IsFalse(allSources.Contains("UserSetupManager", StringComparison.Ordinal));
Assert.IsFalse(allSources.Contains("Windows.Foundation.IPropertyValue", StringComparison.Ordinal));
}

private static void WithMetadata(Action<string, string> action)
{
string directory = Directory.CreateTempSubdirectory("ProjectionTypeFilteringTest_").FullName;

try
{
action(TypeFilteringMetadata.Create(directory), Path.Combine(directory, "Generated"));
}
finally
{
Directory.Delete(directory, recursive: true);
}
}
}
Loading