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
29 changes: 22 additions & 7 deletions crates/dynwinrt/tests/winrt_regression.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,29 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#![cfg(windows)]

use dynwinrt::{InterfaceSignature, MetadataTable, MethodSignature, WinRTValue};
use windows::Devices::Geolocation::{BasicGeoposition, Geopoint, IGeopoint, IGeopointFactory};
use windows::Foundation::{IPropertyValue, IUriRuntimeClass, IUriRuntimeClassFactory};
use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize};
use windows::Win32::System::WinRT::{RO_INIT_MULTITHREADED, RoInitialize, RoUninitialize};
use windows_core::{GUID, HRESULT, HSTRING, Interface};

fn init_winrt() {
unsafe { RoInitialize(RO_INIT_MULTITHREADED) }.expect("RoInitialize should succeed");
const TYPE_E_TYPEMISMATCH: HRESULT = HRESULT(0x8002_8CA0u32 as i32);

struct RoInitializeGuard;

impl RoInitializeGuard {
fn initialize_mta() -> Self {
unsafe { RoInitialize(RO_INIT_MULTITHREADED) }
.expect("RoInitialize(RO_INIT_MULTITHREADED) must succeed for the regression harness");
Self
}
}

impl Drop for RoInitializeGuard {
fn drop(&mut self) {
unsafe { RoUninitialize() };
}
}

fn assert_hstring(value: &WinRTValue, expected: &str) {
Expand Down Expand Up @@ -102,8 +117,8 @@ fn property_value_statics_signature(reg: &std::sync::Arc<MetadataTable>) -> Inte
}

fn property_value_signature(reg: &std::sync::Arc<MetadataTable>) -> InterfaceSignature {
let ipv_iid = GUID::from_u128(0x4BD682DD_7554_40E9_9A9B_82654EDE7E62);
let mut iface = InterfaceSignature::define_from_iinspectable("IPropertyValue", ipv_iid, reg);
let mut iface =
InterfaceSignature::define_from_iinspectable("IPropertyValue", IPropertyValue::IID, reg);
iface.add_method(MethodSignature::new(reg).add_out(reg.i32_type())); // 6 get_Type
iface.add_method(MethodSignature::new(reg).add_out(reg.bool_type())); // 7 get_IsNumericScalar
for _ in 0..3 {
Expand Down Expand Up @@ -321,7 +336,7 @@ fn check_property_value_dynamic_type_mismatch_returns_golden_error() -> windows_
let err = value_iface.methods[19]
.call_dynamic(int_obj.as_raw(), &[])
.expect_err("GetString on an Int32 PropertyValue should fail");
assert_eq!(err.code(), HRESULT(0x80028CA0u32 as i32));
assert_eq!(err.code(), TYPE_E_TYPEMISMATCH);

Ok(())
}
Expand Down Expand Up @@ -392,7 +407,7 @@ fn check_geopoint_struct_layout_and_dynamic_position_round_trip_are_golden()

#[test]
fn winrt_regression_harness_golden_behaviors() -> windows_core::Result<()> {
init_winrt();
let _apartment = RoInitializeGuard::initialize_mta();

check_winrt_uri_factory_dynamic_properties_are_golden()?;
check_winrt_uri_empty_path_is_golden()?;
Expand Down
7 changes: 6 additions & 1 deletion tests/e2e/runners/py_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,9 +88,14 @@ def literal_arg(val):
def projected_values_equal(left, right):
if type(left) is not type(right):
return False
shared_attribute = False
for attribute in ("name", "value", "path"):
if hasattr(left, attribute) and hasattr(right, attribute):
return getattr(left, attribute) == getattr(right, attribute)
shared_attribute = True
if getattr(left, attribute) != getattr(right, attribute):
return False
if shared_attribute:
return True
if isinstance(left, (str, bytes, int, float, bool, tuple)):
return left == right
return True
Expand Down
24 changes: 24 additions & 0 deletions tests/e2e/runners/test_py_runner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

from dataclasses import dataclass

from py_runner import projected_values_equal


@dataclass
class ProjectedValue:
name: str
value: int


def test_projected_values_equal_compares_all_shared_semantic_attributes():
left = ProjectedValue(name='shared', value=1)
right = ProjectedValue(name='shared', value=2)

assert not projected_values_equal(left, right)


def test_projected_values_equal_retains_scalar_fallback():
assert projected_values_equal('shared', 'shared')
assert not projected_values_equal('left', 'right')
31 changes: 31 additions & 0 deletions tests/e2e/runners/ts_runner.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

import { strict as assert } from "node:assert";
import { test } from "node:test";

import { instantiateClass } from "./ts_runner.ts";

test("instantiateClass invokes constructors", () => {
class Example {
constructor(readonly value: string) {}
}

const result = instantiateClass(
"Example",
{ kind: "constructor", args: ["value"] },
Example,
);

assert.ok(result instanceof Example);
assert.equal(result.value, "value");
});

test("instantiateClass rejects unknown kinds", () => {
const invalidInstantiate = JSON.parse('{"kind":"unsupported"}');

assert.throws(
() => instantiateClass("Example", invalidInstantiate, class Example {}),
/Unknown instantiate kind: unsupported/,
);
});
117 changes: 73 additions & 44 deletions tests/e2e/runners/ts_runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import * as path from "node:path";
import { fileURLToPath } from "node:url";

interface Instantiate {
kind: "activate" | "static_factory" | "none";
kind: "activate" | "static_factory" | "constructor" | "none";
method?: string;
args?: any[];
}
Expand All @@ -39,6 +39,12 @@ interface Check {
args_factory?: ArgsFactory;
expected?: any;
contains?: string;
min?: number;
max?: number;
struct_class?: string;
struct_args?: Record<string, any>;
element_type?: string;
values?: any[];
}

interface Spec {
Expand Down Expand Up @@ -100,6 +106,62 @@ function toPascalCase(name: string): string {
return camel.charAt(0).toUpperCase() + camel.slice(1);
}

export function instantiateClass(
className: string,
instantiate: Instantiate,
cls: any,
): any {
const instKind = instantiate.kind;

if (instKind === "activate") {
// Generated code provides create() or createDefault() for default constructors
if (typeof cls.create === "function") {
return cls.create();
}
if (typeof cls.createDefault === "function") {
return cls.createDefault();
}
throw new Error(
`${className} has no create() or createDefault() method for activate`,
);
}

if (instKind === "static_factory") {
const methodName = toCamelCase(instantiate.method!);
const args = instantiate.args || [];
if (
className === "NotificationData" &&
args[0] != null &&
!Array.isArray(args[0]) &&
typeof args[0] === "object"
) {
const obj = cls.createDefault();
for (const [key, value] of Object.entries(args[0])) {
obj.values.set(key, value);
}
if (args[1] !== undefined) obj.sequenceNumber = args[1];
return obj;
}

const overloadName = methodName.split("With")[0];
const factory = cls[methodName] ?? cls[overloadName];
if (typeof factory !== "function") {
throw new Error(`${className} has no static factory ${methodName}`);
}
return factory.call(cls, ...args);
}

if (instKind === "constructor") {
return new cls(...(instantiate.args || []));
}

if (instKind === "none") {
return null;
}

throw new Error(`Unknown instantiate kind: ${String(instKind)}`);
}

async function runSpec(
spec: Spec,
generatedDir: string,
Expand All @@ -123,45 +185,7 @@ async function runSpec(
const cls = mod[spec.class];
if (!cls) throw new Error(`Class ${spec.class} not found in ${modulePath}`);

// Instantiate
let obj: any = null;
const instKind = spec.instantiate.kind;

if (instKind === "activate") {
// Generated code provides create() or createDefault() for default constructors
if (typeof cls.create === "function") {
obj = cls.create();
} else if (typeof cls.createDefault === "function") {
obj = cls.createDefault();
} else {
throw new Error(
`${spec.class} has no create() or createDefault() method for activate`,
);
}
} else if (instKind === "static_factory") {
const methodName = toCamelCase(spec.instantiate.method!);
const args = spec.instantiate.args || [];
if (
spec.class === "NotificationData" &&
args[0] != null &&
!Array.isArray(args[0]) &&
typeof args[0] === "object"
) {
obj = cls.createDefault();
for (const [key, value] of Object.entries(args[0])) {
obj.values.set(key, value);
}
if (args[1] !== undefined) obj.sequenceNumber = args[1];
} else {
const overloadName = methodName.split("With")[0];
const factory = cls[methodName] ?? cls[overloadName];
if (typeof factory !== "function") {
throw new Error(`${spec.class} has no static factory ${methodName}`);
}
obj = factory.call(cls, ...args);
}
}
// kind === 'none': no instantiation
const obj = instantiateClass(spec.class, spec.instantiate, cls);

// Run checks
for (const check of spec.checks) {
Expand Down Expand Up @@ -1050,7 +1074,12 @@ async function main() {
process.exit(failed > 0 ? 1 : 0);
}

main().catch((e) => {
console.error("Runner error:", e);
process.exit(2);
});
if (
process.argv[1] &&
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
) {
main().catch((e) => {
console.error("Runner error:", e);
process.exit(2);
});
}
Loading