diff --git a/crates/dynwinrt/tests/winrt_regression.rs b/crates/dynwinrt/tests/winrt_regression.rs index 9619f49f..96a3add4 100644 --- a/crates/dynwinrt/tests/winrt_regression.rs +++ b/crates/dynwinrt/tests/winrt_regression.rs @@ -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) { @@ -102,8 +117,8 @@ fn property_value_statics_signature(reg: &std::sync::Arc) -> Inte } fn property_value_signature(reg: &std::sync::Arc) -> 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 { @@ -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(()) } @@ -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()?; diff --git a/tests/e2e/runners/py_runner.py b/tests/e2e/runners/py_runner.py index f61e8daa..9bde333f 100644 --- a/tests/e2e/runners/py_runner.py +++ b/tests/e2e/runners/py_runner.py @@ -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 diff --git a/tests/e2e/runners/test_py_runner.py b/tests/e2e/runners/test_py_runner.py new file mode 100644 index 00000000..5a647648 --- /dev/null +++ b/tests/e2e/runners/test_py_runner.py @@ -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') diff --git a/tests/e2e/runners/ts_runner.test.ts b/tests/e2e/runners/ts_runner.test.ts new file mode 100644 index 00000000..575044e6 --- /dev/null +++ b/tests/e2e/runners/ts_runner.test.ts @@ -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/, + ); +}); diff --git a/tests/e2e/runners/ts_runner.ts b/tests/e2e/runners/ts_runner.ts index ee2b447b..8d173384 100644 --- a/tests/e2e/runners/ts_runner.ts +++ b/tests/e2e/runners/ts_runner.ts @@ -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[]; } @@ -39,6 +39,12 @@ interface Check { args_factory?: ArgsFactory; expected?: any; contains?: string; + min?: number; + max?: number; + struct_class?: string; + struct_args?: Record; + element_type?: string; + values?: any[]; } interface Spec { @@ -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, @@ -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) { @@ -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); + }); +}