From e9ac477a3a9fd3e0c36d07294dab9d8aef38a2e0 Mon Sep 17 00:00:00 2001 From: leileizhang Date: Mon, 10 Aug 2026 12:13:47 +0800 Subject: [PATCH 1/5] Improve Python projections, lazy loading, and coverage reporting --- .github/workflows/coverage.yml | 70 ++ bindings/js/__test__/index.spec.ts | 97 ++- bindings/py/src/runtime.rs | 31 +- bindings/py/tests/test_basic.py | 88 +++ bindings/py/tests/test_phase1.py | 39 +- .../dynwinrt/src/metadata_table/value_data.rs | 72 +- eng/coverage/coverage.ps1 | 145 +++- tests/e2e/e2e_specs.json | 63 +- tests/e2e/e2e_specs.schema.json | 9 +- tests/e2e/runners/py_runner.py | 667 +++++++++++++++++- tests/e2e/runners/py_winui_runner.py | 49 ++ tests/e2e/runners/ts_runner.ts | 653 +++++++++++++---- .../src/codegen/winrt/python/collections.rs | 31 + .../codegen/winrt/python/generator/structs.rs | 39 +- .../src/codegen/winrt/python/structs.rs | 20 +- .../src/codegen/winrt/python/stub_helpers.rs | 4 +- tools/dynwinrt-codegen/src/main.rs | 188 ++++- .../tests/ireference_struct_field_test.rs | 66 ++ 18 files changed, 2107 insertions(+), 224 deletions(-) diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index e62840f1..70a2bd8e 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -22,6 +22,7 @@ on: permissions: contents: read + pull-requests: write concurrency: group: coverage-${{ github.ref }} @@ -72,6 +73,7 @@ jobs: "DYNWINRT_WIN32_WINMD=$($winmd.FullName)" >> $env:GITHUB_ENV - name: Run Rust, Python, JavaScript, and E2E coverage + id: coverage shell: pwsh run: | .\eng\coverage\coverage.ps1 ` @@ -93,3 +95,71 @@ jobs: path: artifacts/coverage/ if-no-files-found: warn retention-days: 14 + + - name: Update coverage PR comment + if: >- + always() && + github.event_name == 'pull_request' && + github.event.pull_request.head.repo.full_name == github.repository + uses: actions/github-script@v8 + env: + COVERAGE_OUTCOME: ${{ steps.coverage.outcome }} + SUMMARY_PATH: artifacts/coverage/summary.md + with: + script: | + const fs = require('fs') + const marker = '' + const succeeded = process.env.COVERAGE_OUTCOME === 'success' + const status = succeeded ? '✅ Passed' : '❌ Failed' + let summary = '_Coverage summary was not produced._' + + if (fs.existsSync(process.env.SUMMARY_PATH)) { + summary = fs.readFileSync(process.env.SUMMARY_PATH, 'utf8') + .replace(/^# Mixed-language coverage\r?\n+/, '') + .trim() + } + + const runUrl = + `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}` + + `/actions/runs/${context.runId}` + const body = [ + marker, + '## Mixed-language test coverage', + '', + `**Workflow status:** ${status}`, + '', + summary, + '', + `[View workflow run and download full HTML/LCOV/XML reports](${runUrl}#artifacts)`, + ].join('\n') + + const comments = await github.paginate( + github.rest.issues.listComments, + { + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + per_page: 100, + }, + ) + const existing = comments.find( + (comment) => + comment.user?.type === 'Bot' && + comment.body?.includes(marker), + ) + + if (existing) { + await github.rest.issues.updateComment({ + owner: context.repo.owner, + repo: context.repo.repo, + comment_id: existing.id, + body, + }) + } else { + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: context.issue.number, + body, + }) + } diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index 467b672e..fd55af8d 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -21,6 +21,8 @@ import { } from '../dist/winrt.js' import * as winrtRuntime from '../dist/winrt.js' import * as comRuntime from '../dist/com.js' +import * as unsafeComRuntime from '../dist/com-unsafe.js' +import * as nativeRuntime from '../dist/index.js' import { DynCom, DynComDispatchParams, @@ -31,6 +33,11 @@ import { DynComVariant, } from '../dist/com-unsafe.js' +const moduleKeys = (value: object) => + Object.keys(value) + .filter((key) => key !== 'default' && key !== 'module.exports') + .sort() + test('Classic COM is isolated from the WinRT root entrypoint', (t) => { t.false(Object.prototype.hasOwnProperty.call(winrtRuntime, 'DynCom')) t.false(Object.prototype.hasOwnProperty.call(comRuntime, 'DynCom')) @@ -90,6 +97,65 @@ test('Classic COM is isolated from the WinRT root entrypoint', (t) => { t.regex(esm.stdout, /runtime-entrypoints-ok/) }) +test('package facades exactly partition native exports', (t) => { + const nativeKeys = moduleKeys(nativeRuntime) + const expectedWinrt = nativeKeys.filter((name) => !name.startsWith('DynCom') && name !== 'initializeCom') + const safeComNames = new Set([ + 'DynComDispatchParams', + 'DynComExcepInfo', + 'DynComNativeStruct', + 'DynComNativeStructArray', + 'DynComNativeUnion', + 'DynComPropVariant', + 'DynComSafeArray', + 'DynComVariant', + 'DynWinRtValue', + 'DynWinRTValue', + 'WinGuid', + 'WinGUID', + 'initializeCom', + ]) + const unsafeComNames = new Set([ + ...safeComNames, + 'DynCom', + 'DynComDispatchInvokeResult', + 'DynComInterface', + 'DynComMethodHandle', + 'DynComMethodSig', + 'DynComType', + 'DynComUnsafe', + 'DynComUnsafeInterface', + ]) + + t.deepEqual(moduleKeys(winrtRuntime), expectedWinrt) + t.deepEqual( + moduleKeys(comRuntime), + nativeKeys.filter((name) => safeComNames.has(name)), + ) + t.deepEqual( + moduleKeys(unsafeComRuntime), + nativeKeys.filter((name) => unsafeComNames.has(name)), + ) + + t.is(winrtRuntime.WinGuid, comRuntime.WinGuid) + t.is(comRuntime.initializeCom, unsafeComRuntime.initializeCom) + for (const name of moduleKeys(comRuntime)) { + t.true(moduleKeys(unsafeComRuntime).includes(name), `${name} must remain available from /com/unsafe`) + } +}) + +test('WinRT root facade exposes usable native primitives', (t) => { + t.truthy(winrtRuntime.DynWinRtType.i32()) + t.is(winrtRuntime.DynWinRtValue.i32(1).toNumber(), 1) + t.is(winrtRuntime.DynWinRtValue.hstring('root-smoke').toString(), 'root-smoke') + t.regex( + winrtRuntime.WinGuid.parse('00000000-0000-0000-c000-000000000046').toString(), + /00000000-0000-0000-c000-000000000046/i, + ) + t.is(typeof winrtRuntime.hasPackageIdentity(), 'boolean') + t.is(typeof winrtRuntime.roInitialize, 'function') +}) + test('Classic COM raw ABI access requires the explicit unsafe entrypoint', (t) => { const iid = WinGuid.parse('00000000-0000-0000-c000-000000000046') const raw = DynComUnsafe.registerIUnknownInterface('Unsafe.IUnknown', iid).addMethodAt( @@ -99,10 +165,7 @@ test('Classic COM raw ABI access requires the explicit unsafe entrypoint', (t) = ) t.truthy(raw.method(3)) - t.is( - typeof (raw as unknown as { addMethod?: unknown }).addMethod, - 'undefined', - ) + t.is(typeof (raw as unknown as { addMethod?: unknown }).addMethod, 'undefined') t.truthy(DynComUnsafe.ownedComOutputType()) t.truthy(DynComUnsafe.coTaskMemOutputType()) t.truthy(DynComUnsafe.bstrOutputType()) @@ -111,10 +174,7 @@ test('Classic COM raw ABI access requires the explicit unsafe entrypoint', (t) = t.true(DynComUnsafe.borrowComPointer(0n, iid).isNull()) t.throws( () => - (DynComUnsafe.adoptOwnedComPointer as unknown as (value: Buffer, iid: WinGuid) => unknown)( - Buffer.alloc(8), - iid, - ), + (DynComUnsafe.adoptOwnedComPointer as unknown as (value: Buffer, iid: WinGuid) => unknown)(Buffer.alloc(8), iid), { message: /numeric pointer bits/ }, ) }) @@ -188,14 +248,9 @@ test('DynCom BSTR values preserve exact strings and use dedicated signatures', ( test('DynCom owning counted arrays use natural managed inputs', (t) => { roInitialize() const bstrs = DynCom.bstrArray(['embedded\u0000nul', '']) - const variants = DynCom.variantArray([ - DynComVariant.i32(17), - DynComVariant.bstr('embedded\u0000nul'), - ]) + const variants = DynCom.variantArray([DynComVariant.i32(17), DynComVariant.bstr('embedded\u0000nul')]) const iid = WinGuid.parse('00000035-0000-0000-c000-000000000046') - const interfaces = DynCom.interfaceArray(iid, [ - DynWinRtValue.activationFactory('Windows.Foundation.Uri'), - ]) + const interfaces = DynCom.interfaceArray(iid, [DynWinRtValue.activationFactory('Windows.Foundation.Uri')]) t.is(DynCom.bufferCount(bstrs), 2n) t.is(DynCom.bufferCount(variants), 2n) @@ -209,10 +264,9 @@ test('DynCom owning counted arrays use natural managed inputs', (t) => { const oneShot = DynCom.callerOutputArray(DynCom.bstrType(), 1n) t.throws(() => DynCom.takeBstrArray(oneShot), { message: /does not contain owned string/ }) t.throws(() => DynCom.takeBstrArray(oneShot), { message: /not an owned BSTR array/ }) - t.throws( - () => DynCom.interfaceArray(iid, [DynCom.pointer(0n) as unknown as DynWinRtValue]), - { message: /managed objects/ }, - ) + t.throws(() => DynCom.interfaceArray(iid, [DynCom.pointer(0n) as unknown as DynWinRtValue]), { + message: /managed objects/, + }) }) test('DynCom Automation wrappers preserve tags, values, bounds, and transfer', (t) => { @@ -388,10 +442,7 @@ test('DynCom Automation wrappers preserve tags, values, bounds, and transfer', ( t.is(DynCom.takeNullableSafeArray(nullSafeArray), null) const nullableSafeArray = DynCom.safeArray(interfaceArray) const takenNullableSafeArray = DynCom.takeNullableSafeArray(nullableSafeArray) - t.is( - takenNullableSafeArray?.interfaceIid?.toString().toLowerCase(), - activationFactoryIid.toString().toLowerCase(), - ) + t.is(takenNullableSafeArray?.interfaceIid?.toString().toLowerCase(), activationFactoryIid.toString().toLowerCase()) const arrayVariant = DynComVariant.safeArray(arrays[4]) t.deepEqual(arrayVariant.toSafeArray().toNumbers(), [1, 2, 3, 4]) diff --git a/bindings/py/src/runtime.rs b/bindings/py/src/runtime.rs index 8e8f58eb..17ae25f1 100644 --- a/bindings/py/src/runtime.rs +++ b/bindings/py/src/runtime.rs @@ -1854,30 +1854,17 @@ impl DynWinRTStruct { // -- Non-blittable field access -- - fn get_hstring(&self, index: usize) -> String { - let inner = self.0.get_field_struct(index); - let hstr: HSTRING = unsafe { - let raw = *(inner.as_ptr() as *const *mut std::ffi::c_void); - if raw.is_null() { - HSTRING::new() - } else { - let hstr_ref: &HSTRING = - &*((&raw) as *const *mut std::ffi::c_void as *const HSTRING); - hstr_ref.clone() - } - }; - hstr.to_string() + fn get_hstring(&self, index: usize) -> PyResult { + self.0 + .get_field_hstring(index) + .map(|value| value.to_string()) + .map_err(map_dynwinrt_error) } - fn set_hstring(&mut self, index: usize, value: String) { - let hstr = HSTRING::from(&value); - let field_handle = self.0.type_handle().field_type(index); - let mut field_val = field_handle.default_value(); - unsafe { - let raw: *mut std::ffi::c_void = std::mem::transmute(hstr); - (field_val.as_mut_ptr() as *mut *mut std::ffi::c_void).write(raw); - } - self.0.set_field_struct(index, &field_val); + fn set_hstring(&mut self, index: usize, value: String) -> PyResult<()> { + self.0 + .set_field_hstring(index, HSTRING::from(&value)) + .map_err(map_dynwinrt_error) } fn get_guid(&self, index: usize) -> WinGUID { diff --git a/bindings/py/tests/test_basic.py b/bindings/py/tests/test_basic.py index 8d6a6270..716c0e0c 100644 --- a/bindings/py/tests/test_basic.py +++ b/bindings/py/tests/test_basic.py @@ -55,6 +55,49 @@ def test_box_ireference_values(): ).is_null() +def test_create_map_round_trips_values_and_validates_lengths(): + key_type = DynWinRTType.hstring() + value_type = DynWinRTType.i32_type() + mapping = DynWinRTValue.create_map( + [DynWinRTValue.from_hstring("answer")], + [DynWinRTValue.from_i32(42)], + key_type, + value_type, + ) + map_type = DynWinRTType.parameterized( + WinGUID.parse("3c2925fe-8519-45c1-aa79-197b6718c1c1"), + [key_type, value_type], + ) + map_interface = ( + DynWinRTType.register_interface("IMap_String_Int32_Test", map_type.iid()) + .add_method( + "Lookup", + DynWinRTMethodSig().add_in(key_type).add_out(value_type), + ) + .add_method( + "get_Size", + DynWinRTMethodSig().add_out(DynWinRTType.u32_type()), + ) + ) + mapping = mapping.cast(map_type.iid()) + + assert map_interface.method(7).invoke(mapping, []).to_u32() == 1 + assert map_interface.method(6).invoke( + mapping, + [DynWinRTValue.from_hstring("answer")], + ).to_int() == 42 + + import pytest + + with pytest.raises(RuntimeError, match="same length"): + DynWinRTValue.create_map( + [DynWinRTValue.from_hstring("answer")], + [], + key_type, + value_type, + ) + + def test_guid_parse(): """WinGUID.parse should parse valid GUIDs.""" guid = WinGUID.parse("9e365e57-48b2-4160-956f-c7385120bbfc") @@ -227,6 +270,13 @@ def test_uri_dynamic_invocation(): uri2 = create_method.invoke_hstring(factory_obj, "https://test.com") assert uri2 is not None + objects = DynWinRTArray.from_object_values( + [uri_obj, uri2], + DynWinRTType.object(), + ) + assert objects.get(0).identity_raw() == uri_obj.identity_raw() + assert objects.get(1).identity_raw() == uri2.identity_raw() + def test_invoke_detached_uses_the_normal_marshalling_path(): ro_initialize(1) @@ -339,6 +389,44 @@ def test_struct_to_value(): assert val.is_struct() +def test_struct_array_round_trip(): + typ = DynWinRTType.struct_type( + "TestStructArray", + [DynWinRTType.i32_type(), DynWinRTType.f64_type()], + ) + first = DynWinRTStruct.create(typ) + first.set_i32(0, 17) + first.set_f64(1, 1.5) + second = DynWinRTStruct.create(typ) + second.set_i32(0, 23) + second.set_f64(1, 2.5) + + array = DynWinRTArray.from_values( + [first.to_value(), second.to_value()], + typ, + ) + + assert len(array) == 2 + assert array.get(0).as_struct().get_i32(0) == 17 + assert array.get(0).as_struct().get_f64(1) == 1.5 + assert array.get(1).as_struct().get_i32(0) == 23 + assert array.get(1).as_struct().get_f64(1) == 2.5 + + +def test_struct_hstring_field_round_trip(): + typ = DynWinRTType.struct_type( + "TestStructHString", + [DynWinRTType.i32_type(), DynWinRTType.hstring()], + ) + value = DynWinRTStruct.create(typ) + value.set_i32(0, 17) + value.set_hstring(1, "dynwinrt") + + assert value.get_i32(0) == 17 + assert value.get_hstring(1) == "dynwinrt" + assert value.to_value().as_struct().get_hstring(1) == "dynwinrt" + + def test_struct_all_field_types(): """Test all blittable struct field types.""" typ = DynWinRTType.struct_type("TestStruct3", [ diff --git a/bindings/py/tests/test_phase1.py b/bindings/py/tests/test_phase1.py index cff3e023..998684d8 100644 --- a/bindings/py/tests/test_phase1.py +++ b/bindings/py/tests/test_phase1.py @@ -44,6 +44,7 @@ from dynwinrt_py.dynwinrt_py import ( _DynWinRTAsync, _DynWinRTAsyncWithProgress, + _dynwinrt_dispatch_progress, _dynwinrt_datetime_to_ticks, _dynwinrt_new_vector, _dynwinrt_track_projected, @@ -140,7 +141,7 @@ def test_sync_hresult_maps_to_os_error_with_winerror(): assert exc_info.value.strerror -def _missing_storage_file_operation(path: str): +def _missing_storage_file_operation_value(path: str): statics_iid = WinGUID.parse(IID_ISTORAGE_FILE_STATICS) storage_file_type = DynWinRTType.runtime_class( "Windows.Storage.StorageFile", @@ -162,7 +163,14 @@ def _missing_storage_file_operation(path: str): factory, [DynWinRTValue.from_hstring(path)], ) - return _DynWinRTAsync(raw_operation, lambda value: value) + return raw_operation + + +def _missing_storage_file_operation(path: str): + return _DynWinRTAsync( + _missing_storage_file_operation_value(path), + lambda value: value, + ) def test_async_hresult_maps_to_os_error_with_winerror(tmp_path): @@ -222,6 +230,33 @@ def test_progress_wrapper_rejects_non_async_value(): ) +def test_progress_wrapper_rejects_async_operation_without_progress(tmp_path): + raw_operation = _missing_storage_file_operation_value( + str(tmp_path / "missing-dynwinrt-progress-file") + ) + with pytest.raises( + RuntimeError, + match="not a WinRT async operation with progress", + ): + _DynWinRTAsyncWithProgress( + raw_operation, + lambda value: value, + lambda value: value, + ) + + +def test_progress_dispatch_propagates_callback_errors(): + def fail(_value): + raise ValueError("progress callback failed") + + with pytest.raises(ValueError, match="progress callback failed"): + _dynwinrt_dispatch_progress( + fail, + lambda value: value.to_number(), + DynWinRTValue.from_u32(17), + ) + + def test_observable_vector_reports_mutations_and_unsubscribes(): observable_piid = WinGUID.parse("5917EB53-50B4-4A0D-B309-65862B3F1DBC") vector_piid = WinGUID.parse("913337E9-11A1-4345-A3A2-4E7F956E222D") diff --git a/crates/dynwinrt/src/metadata_table/value_data.rs b/crates/dynwinrt/src/metadata_table/value_data.rs index 580e5c14..8f8dc90e 100644 --- a/crates/dynwinrt/src/metadata_table/value_data.rs +++ b/crates/dynwinrt/src/metadata_table/value_data.rs @@ -2,7 +2,7 @@ // Licensed under the MIT License. use core::ffi::c_void; -use windows_core::{IUnknown, Interface}; +use windows_core::{HSTRING, IUnknown, Interface}; use super::type_handle::TypeHandle; use super::type_kind::TypeKind; @@ -180,6 +180,43 @@ impl ValueTypeData { unsafe { (self.ptr.add(offset) as *mut T).write(value) } } + pub fn get_field_hstring(&self, index: usize) -> crate::result::Result { + let h = &self.type_handle; + let field_handle = h.field_type(index); + if field_handle.kind() != TypeKind::HString { + return Err(crate::result::Error::InvalidType( + TypeKind::HString, + field_handle.kind(), + )); + } + let offset = h.field_offset(index); + let raw = unsafe { *(self.ptr.add(offset) as *const *mut c_void) }; + if raw.is_null() { + Ok(HSTRING::new()) + } else { + let value: &HSTRING = unsafe { &*((&raw) as *const *mut c_void as *const HSTRING) }; + Ok(value.clone()) + } + } + + pub fn set_field_hstring(&mut self, index: usize, value: HSTRING) -> crate::result::Result<()> { + let h = &self.type_handle; + let field_handle = h.field_type(index); + if field_handle.kind() != TypeKind::HString { + return Err(crate::result::Error::InvalidType( + TypeKind::HString, + field_handle.kind(), + )); + } + let offset = h.field_offset(index); + let field = unsafe { &mut *(self.ptr.add(offset) as *mut *mut c_void) }; + let old_raw = std::mem::replace(field, unsafe { std::mem::transmute(value) }); + if !old_raw.is_null() { + let _old_value: HSTRING = unsafe { std::mem::transmute(old_raw) }; + } + Ok(()) + } + pub fn get_field_object(&self, index: usize) -> crate::result::Result> { let h = &self.type_handle; let field_handle = h.field_type(index); @@ -343,3 +380,36 @@ impl Clone for ValueTypeData { } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::metadata_table::MetadataTable; + + #[test] + fn hstring_field_round_trips_overwrites_and_clones() { + let table = MetadataTable::new(); + let typ = table.struct_type("Test.HStringField", &[table.i32_type(), table.hstring()]); + let mut value = typ.default_value(); + + value.set_field_hstring(1, HSTRING::from("first")).unwrap(); + assert_eq!(value.get_field_hstring(1).unwrap(), "first"); + + value.set_field_hstring(1, HSTRING::from("second")).unwrap(); + assert_eq!(value.get_field_hstring(1).unwrap(), "second"); + + let clone = value.clone(); + drop(value); + assert_eq!(clone.get_field_hstring(1).unwrap(), "second"); + } + + #[test] + fn hstring_field_access_rejects_other_types() { + let table = MetadataTable::new(); + let typ = table.struct_type("Test.NotHString", &[table.i32_type()]); + let mut value = typ.default_value(); + + assert!(value.get_field_hstring(0).is_err()); + assert!(value.set_field_hstring(0, HSTRING::from("wrong")).is_err()); + } +} diff --git a/eng/coverage/coverage.ps1 b/eng/coverage/coverage.ps1 index cfebeddd..b2b67b50 100644 --- a/eng/coverage/coverage.ps1 +++ b/eng/coverage/coverage.ps1 @@ -29,6 +29,9 @@ $output = if ([IO.Path]::IsPathRooted($OutputDirectory)) { $rustReport = Join-Path $output "rust" $pythonReport = Join-Path $output "python" $jsReport = Join-Path $output "javascript" +$jsRuntimeReport = Join-Path $jsReport "runtime" +$jsWinrtReport = Join-Path $jsReport "generated-winrt" +$jsComReport = Join-Path $jsReport "generated-classic-com" $jsTemp = Join-Path $output "raw\javascript" $rustRaw = Join-Path $output "raw\rust" $pythonConfig = Join-Path $PSScriptRoot "python-coveragerc" @@ -46,6 +49,8 @@ $jsDistPrepared = $false $jsDistWasPresent = $false $e2eGenerated = Join-Path $root "tests\e2e\e2e_generated" $e2eGeneratedByCoverage = $false +$winrtCoverageExpected = $false +$comCoverageExpected = $false $originalEnvironment = @{} Get-ChildItem Env: | ForEach-Object { $originalEnvironment[$_.Name] = $_.Value @@ -203,6 +208,61 @@ function Restore-ProcessState { Set-Location $originalLocation } +function Test-LcovSourceCovered { + param( + [string]$Lcov, + [string]$SourcePattern + ) + foreach ($record in ($Lcov -split "(?m)^end_of_record\r?\n?")) { + if ( + $record -match "(?m)^SF:.*$SourcePattern.*$" -and + $record -match "(?m)^LH:(\d+)$" -and + [int]$matches[1] -gt 0 + ) { + return $true + } + } + return $false +} + +function Write-JavaScriptCoverageReport { + param( + [string]$Name, + [string]$ReportDirectory, + [string[]]$Includes, + [string]$RequiredSourcePattern + ) + $c8 = Join-Path $root "bindings\js\node_modules\.bin\c8.cmd" + $includeArgs = @() + foreach ($include in $Includes) { + $includeArgs += @("--include", $include) + } + New-LiteralDirectory $ReportDirectory + Invoke-Step "$Name coverage reports" { + & $c8 report ` + --temp-directory $jsTemp ` + --reports-dir $ReportDirectory ` + --reporter text-summary ` + --reporter html ` + --reporter lcov ` + --reporter json-summary ` + --all ` + @includeArgs ` + --exclude "node_modules/**" + } + + $lcovPath = Join-Path $ReportDirectory "lcov.info" + $summaryPath = Join-Path $ReportDirectory "coverage-summary.json" + $lcov = Get-Content -LiteralPath $lcovPath -Raw + if (-not (Test-LcovSourceCovered $lcov $RequiredSourcePattern)) { + throw "$Name coverage did not execute its required source family" + } + $totals = (Get-Content -LiteralPath $summaryPath -Raw | ConvertFrom-Json).total + if ($totals.lines.total -eq 0 -or $totals.lines.covered -eq 0) { + throw "$Name coverage did not execute any source lines" + } +} + function Write-Reports { Stop-PythonCoverage Remove-Item Env:NODE_V8_COVERAGE -ErrorAction SilentlyContinue @@ -293,29 +353,37 @@ function Write-Reports { $jsData = @(Get-ChildItem -LiteralPath $jsTemp -Filter "*.json" -File -ErrorAction SilentlyContinue) if ($jsData.Count -gt 0) { - $c8 = Join-Path $root "bindings\js\node_modules\.bin\c8.cmd" - $jsIncludes = @("--include", "bindings/js/dist/**/*.js") - if (-not $SkipE2E) { - $jsIncludes += @("--include", "tests/e2e/e2e_generated/**/*.js") - } - Invoke-Step "JavaScript coverage reports" { - & $c8 report ` - --temp-directory $jsTemp ` - --reports-dir $jsReport ` - --reporter text-summary ` - --reporter html ` - --reporter lcov ` - --reporter json-summary ` - --all ` - @jsIncludes ` - --exclude "node_modules/**" - } - $jsLcov = Get-Content -LiteralPath (Join-Path $jsReport "lcov.info") -Raw - if ($jsLcov -notmatch "bindings[\\/]js[\\/]dist[\\/]index\.js") { - throw "JavaScript coverage did not include the runtime entrypoint" - } - if (-not $SkipE2E -and $jsLcov -notmatch "tests[\\/]e2e[\\/]e2e_generated") { - throw "JavaScript coverage did not include generated E2E projections" + $aggregateIncludes = @("bindings/js/dist/**/*.js") + if ($winrtCoverageExpected) { + $aggregateIncludes += "tests/e2e/e2e_generated/ts/**/*.js" + } + if ($comCoverageExpected) { + $aggregateIncludes += "tests/e2e/e2e_generated/com/**/*.js" + } + + Write-JavaScriptCoverageReport ` + -Name "JavaScript aggregate" ` + -ReportDirectory $jsReport ` + -Includes $aggregateIncludes ` + -RequiredSourcePattern "bindings[\\/]js[\\/]dist[\\/]index\.js" + Write-JavaScriptCoverageReport ` + -Name "JavaScript runtime" ` + -ReportDirectory $jsRuntimeReport ` + -Includes @("bindings/js/dist/**/*.js") ` + -RequiredSourcePattern "bindings[\\/]js[\\/]dist[\\/]index\.js" + if ($winrtCoverageExpected) { + Write-JavaScriptCoverageReport ` + -Name "Generated WinRT" ` + -ReportDirectory $jsWinrtReport ` + -Includes @("tests/e2e/e2e_generated/ts/**/*.js") ` + -RequiredSourcePattern "tests[\\/]e2e[\\/]e2e_generated[\\/]ts[\\/]" + } + if ($comCoverageExpected) { + Write-JavaScriptCoverageReport ` + -Name "Generated Classic COM" ` + -ReportDirectory $jsComReport ` + -Includes @("tests/e2e/e2e_generated/com/**/*.js") ` + -RequiredSourcePattern "tests[\\/]e2e[\\/]e2e_generated[\\/]com[\\/]" } } else { throw "No V8 coverage data was produced" @@ -334,18 +402,30 @@ function Write-CoverageSummary { $pythonSummary = Join-Path $pythonReport "coverage.json" if (Test-Path -LiteralPath $pythonSummary) { $totals = (Get-Content -LiteralPath $pythonSummary -Raw | ConvertFrom-Json -AsHashtable)["totals"] + $linePercent = if ($totals["num_statements"]) { + [math]::Round(100 * $totals["covered_lines"] / $totals["num_statements"], 2) + } else { + 100 + } $branchPercent = if ($totals["num_branches"]) { [math]::Round(100 * $totals["covered_branches"] / $totals["num_branches"], 2) } else { 100 } - $rows += "| Generated Python projections | $([math]::Round($totals["percent_covered"], 2))% | n/a | $branchPercent% branches |" + $rows += "| Generated Python projections | $linePercent% | n/a | $branchPercent% branches |" } - $jsSummary = Join-Path $jsReport "coverage-summary.json" - if (Test-Path -LiteralPath $jsSummary) { - $totals = (Get-Content -LiteralPath $jsSummary -Raw | ConvertFrom-Json).total - $rows += "| JavaScript runtime and generated projections | $($totals.lines.pct)% | $($totals.functions.pct)% | $($totals.branches.pct)% branches |" + foreach ($javascriptLayer in @( + [pscustomobject]@{ Name = "JavaScript aggregate"; Path = $jsReport } + [pscustomobject]@{ Name = "JavaScript runtime"; Path = $jsRuntimeReport } + [pscustomobject]@{ Name = "Generated WinRT projections"; Path = $jsWinrtReport } + [pscustomobject]@{ Name = "Generated Classic COM projections"; Path = $jsComReport } + )) { + $jsSummary = Join-Path $javascriptLayer.Path "coverage-summary.json" + if (Test-Path -LiteralPath $jsSummary) { + $totals = (Get-Content -LiteralPath $jsSummary -Raw | ConvertFrom-Json).total + $rows += "| $($javascriptLayer.Name) | $($totals.lines.pct)% | $($totals.functions.pct)% | $($totals.branches.pct)% branches |" + } } if ($rows.Count -gt 0) { @@ -541,9 +621,11 @@ try { } if (-not $SkipE2E) { + $winrtCoverageExpected = $true $languages = @("py", "ts") if (-not $SkipCom -and $env:DYNWINRT_WIN32_WINMD) { $languages += "com" + $comCoverageExpected = $true } Invoke-Step "Cross-language E2E tests" { & (Join-Path $root "tests\e2e\e2e_test.ps1") ` @@ -598,6 +680,13 @@ try { Write-Host " Python: $(Join-Path $pythonReport 'html\index.html')" } Write-Host " JavaScript: $(Join-Path $jsReport 'index.html')" + Write-Host " Runtime: $(Join-Path $jsRuntimeReport 'index.html')" + if ($winrtCoverageExpected) { + Write-Host " WinRT: $(Join-Path $jsWinrtReport 'index.html')" + } + if ($comCoverageExpected) { + Write-Host " COM: $(Join-Path $jsComReport 'index.html')" + } } catch { $scriptError = $_ } finally { diff --git a/tests/e2e/e2e_specs.json b/tests/e2e/e2e_specs.json index e352c25d..c82121ba 100644 --- a/tests/e2e/e2e_specs.json +++ b/tests/e2e/e2e_specs.json @@ -46,6 +46,10 @@ "kind": "property_equals", "member": "absolute_uri", "expected": "https://example.com/root/child" + }, + { + "kind": "constructor_overload_dispatch", + "member": "__init__" } ] }, @@ -290,7 +294,7 @@ "id": "calendar_python_native_inputs", "namespace": "Windows.Globalization", "class": "Calendar", - "langs": ["py"], + "langs": ["py", "ts"], "instantiate": { "kind": "static_factory", "method": "create_calendar_default_calendar_and_clock", @@ -298,14 +302,29 @@ }, "checks": [ { "kind": "sequence_protocol", "member": "languages", "expected_size": 1 }, - { "kind": "datetime_roundtrip", "member": "date_time" } + { "kind": "datetime_roundtrip", "member": "date_time", "langs": ["py"] }, + { "kind": "calendar_comprehensive", "member": "self" } + ] + }, + { + "id": "value_set_mapping_deep", + "namespace": "Windows.Foundation.Collections", + "class": "ValueSet", + "langs": ["py", "ts"], + "instantiate": { + "kind": "static_factory", + "method": "create" + }, + "checks": [ + { "kind": "value_set_mapping", "member": "self" }, + { "kind": "value_set_event_lifecycle", "member": "map_changed", "langs": ["py"] } ] }, { "id": "notification_data_mapping", "namespace": "Windows.UI.Notifications", "class": "NotificationData", - "langs": ["py"], + "langs": ["py", "ts"], "instantiate": { "kind": "static_factory", "method": "create_notification_data_with_values_and_sequence_number", @@ -325,7 +344,7 @@ "id": "file_open_picker_mutable_sequence", "namespace": "Windows.Storage.Pickers", "class": "FileOpenPicker", - "langs": ["py"], + "langs": ["py", "ts"], "instantiate": { "kind": "activate" }, "checks": [ { @@ -386,14 +405,35 @@ "extra_classes": ["DataWriter", "DataReader", "Buffer"], "instantiate": { "kind": "none" }, "checks": [ - { "kind": "async_memory_roundtrip", "member": "roundtrip", "write_value": 42 } + { "kind": "async_memory_roundtrip", "member": "roundtrip", "write_value": 42 }, + { "kind": "data_stream_scalar_roundtrip", "member": "roundtrip", "langs": ["py"] } + ] + }, + { + "id": "nested_struct_runtime", + "namespace": "Windows.Graphics.DirectX.Direct3D11", + "class": "IDirect3DSurface", + "langs": ["py", "ts"], + "instantiate": { "kind": "none" }, + "checks": [ + { "kind": "nested_struct_runtime", "member": "description" } + ] + }, + { + "id": "storage_query_temp_folder", + "namespace": "Windows.Storage", + "class": "StorageFolder", + "langs": ["py", "ts"], + "instantiate": { "kind": "none" }, + "checks": [ + { "kind": "storage_query_temp_folder", "member": "query" } ] }, { "id": "issue_69_device_information_async_collection", "namespace": "Windows.Devices.Enumeration", "class": "DeviceInformation", - "langs": ["ts"], + "langs": ["py", "ts"], "instantiate": { "kind": "none" }, "checks": [ { @@ -406,7 +446,7 @@ "id": "issue_71_bitmap_encoder_async_create", "namespace": "Windows.Graphics.Imaging", "class": "BitmapEncoder", - "langs": ["ts"], + "langs": ["py", "ts"], "instantiate": { "kind": "none" }, "checks": [ { @@ -472,7 +512,8 @@ "instantiate": { "kind": "activate" }, "checks": [ { "kind": "vector_get_many", "member": "languages", "capacity": 4 }, - { "kind": "vector_get_many", "member": "languages", "capacity": 4, "at_end": true } + { "kind": "vector_get_many", "member": "languages", "capacity": 4, "at_end": true }, + { "kind": "vector_get_many", "member": "languages", "capacity": 0, "langs": ["py"] } ] }, { @@ -494,16 +535,16 @@ "id": "xml_document_cyclic_import", "namespace": "Windows.Data.Xml.Dom", "class": "XmlDocument", - "langs": ["py"], + "langs": ["py", "ts"], "instantiate": { "kind": "activate" }, "checks": [ { "kind": "method_then_property_equals", - "member": "LoadXml", + "member": "load_xml", "interface_module": "i_xml_document_io", "interface_class": "IXmlDocumentIO", "args": [""], - "property_path": ["DocumentElement", "TagName"], + "property_path": ["document_element", "tag_name"], "expected": "root" } ] diff --git a/tests/e2e/e2e_specs.schema.json b/tests/e2e/e2e_specs.schema.json index 4a3454f5..733c694d 100644 --- a/tests/e2e/e2e_specs.schema.json +++ b/tests/e2e/e2e_specs.schema.json @@ -89,7 +89,14 @@ "closable_context", "method_then_property_equals", "device_information_async_collection", - "bitmap_encoder_async_create" + "bitmap_encoder_async_create", + "constructor_overload_dispatch", + "value_set_mapping", + "data_stream_scalar_roundtrip", + "calendar_comprehensive", + "storage_query_temp_folder", + "value_set_event_lifecycle", + "nested_struct_runtime" ] }, "member": { "type": "string", "description": "Property or method name (snake_case)" }, diff --git a/tests/e2e/runners/py_runner.py b/tests/e2e/runners/py_runner.py index 9b14b99b..c7769ccb 100644 --- a/tests/e2e/runners/py_runner.py +++ b/tests/e2e/runners/py_runner.py @@ -264,6 +264,7 @@ async def run_check( f'got {type(actual).__name__}' ) return cr + min_val = check.get('min', float('-inf')) max_val = check.get('max', float('inf')) # Handle enum: extract .value if it's an IntEnum @@ -332,7 +333,12 @@ async def run_check( buffer = dw.DynWinRTArray.from_string_values([''] * capacity) at_end = check.get('at_end', False) items = vec.get_many(vec.size if at_end else 0, buffer) - if at_end and len(items) != 0: + if capacity == 0: + if len(items) != 0: + cr['error'] = 'zero-capacity get_many returned items' + else: + cr['pass'] = True + elif at_end and len(items) != 0: cr['error'] = f'get_many at Size returned {len(items)} items' elif not at_end and len(items) == 0: cr['error'] = 'get_many returned no items' @@ -527,12 +533,189 @@ async def run_check( if mapping[check['set_key']] != check['set_value']: cr['error'] = 'mapping assignment did not round-trip' return cr + if mapping.get(check['set_key']) != check['set_value']: + cr['error'] = 'mapping get() disagreed with lookup' + return cr + missing = '__dynwinrt_missing__' + if mapping.get(missing, 'fallback') != 'fallback': + cr['error'] = 'mapping get() ignored its default' + return cr + try: + _ = mapping[missing] + cr['error'] = 'missing mapping lookup did not raise KeyError' + return cr + except KeyError: + pass del mapping[check['set_key']] if check['set_key'] in mapping: cr['error'] = 'mapping deletion did not remove the key' return cr + try: + del mapping[check['set_key']] + cr['error'] = 'missing mapping deletion did not raise KeyError' + return cr + except KeyError: + pass + view = mapping.get_view() + if view is None or dict(view) != dict(mapping): + cr['error'] = 'mapping view did not match the mutable map' + return cr + try: + view[check['set_key']] = check['set_value'] + cr['error'] = 'read-only map view accepted assignment' + return cr + except TypeError: + pass cr['pass'] = True + elif kind == 'constructor_overload_dispatch': + single = cls(uri='https://example.com/single') + relative = cls( + base_uri='https://example.com/root/', + relative_uri='child', + ) + mixed = cls('https://example.com/root/', relative_uri='mixed') + if ( + single.host != 'example.com' + or not relative.absolute_uri.endswith('/root/child') + or not mixed.absolute_uri.endswith('/root/mixed') + ): + cr['error'] = 'keyword or mixed constructor overload returned wrong URI' + return cr + + invalid_calls = [ + ((), {}), + ((42,), {}), + (('https://example.com', 'child', 'extra'), {}), + (('https://example.com',), {'uri': 'https://duplicate.example'}), + ((), {'unknown': 'https://example.com'}), + ] + for args, kwargs in invalid_calls: + try: + cls(*args, **kwargs) + cr['error'] = ( + f'invalid constructor unexpectedly accepted args={args!r}, ' + f'kwargs={kwargs!r}' + ) + return cr + except TypeError: + pass + cr['pass'] = True + + elif kind == 'value_set_mapping': + property_value_cls = generated_type(pkg_name, 'PropertyValue') + first = property_value_cls.create_string('first') + second = property_value_cls.create_int32(2) + first_raw = getattr(first, '_obj', first) + second_raw = getattr(second, '_obj', second) + + if len(obj) != 0 or obj.size != 0: + cr['error'] = 'new ValueSet was not empty' + return cr + if obj.insert('first', first_raw): + cr['error'] = 'first ValueSet insert reported replacement' + return cr + obj['second'] = second + if len(obj) != 2 or not obj.has_key('first') or 'second' not in obj: + cr['error'] = 'ValueSet insertion or membership failed' + return cr + first_lookup = obj.lookup('first') + second_lookup = obj['second'] + if first_lookup.is_null() or second_lookup.is_null(): + cr['error'] = 'ValueSet lookup returned null' + return cr + if ( + first_lookup.identity_raw() != first_raw.identity_raw() + or second_lookup.identity_raw() != second_raw.identity_raw() + ): + cr['error'] = 'ValueSet payloads did not round-trip' + return cr + + view = obj.get_view() + if view is None or len(view) != 2 or set(view) != {'first', 'second'}: + cr['error'] = 'ValueSet view did not preserve entries' + return cr + + try: + _ = obj['missing'] + cr['error'] = 'missing ValueSet lookup did not raise KeyError' + return cr + except KeyError: + pass + try: + del obj['missing'] + cr['error'] = 'missing ValueSet deletion did not raise KeyError' + return cr + except KeyError: + pass + + del obj['first'] + if obj.has_key('first') or len(obj) != 1: + cr['error'] = 'ValueSet deletion failed' + return cr + obj.clear() + if len(obj) != 0 or list(obj): + cr['error'] = 'ValueSet clear failed' + return cr + cr['pass'] = True + + elif kind == 'value_set_event_lifecycle': + import dynwinrt_py as dw + + counts = {'on': 0, 'subscribe': 0, 'once': 0} + + def increment(name): + def callback(*_args): + counts[name] += 1 + return callback + + token = obj.on_map_changed(increment('on')) + unsubscribe = obj.subscribe_map_changed(increment('subscribe')) + obj.once_map_changed(increment('once')) + property_value_cls = generated_type(pkg_name, 'PropertyValue') + + obj['first-event'] = property_value_cls.create_int32(1) + obj['second-event'] = property_value_cls.create_int32(2) + if counts != {'on': 2, 'subscribe': 2, 'once': 1}: + cr['error'] = f'event lifecycle counts were wrong: {counts!r}' + return cr + + obj.off_map_changed(token) + unsubscribe() + unsubscribe() + obj['after-unsubscribe'] = property_value_cls.create_int32(3) + if counts != {'on': 2, 'subscribe': 2, 'once': 1}: + cr['error'] = f'event unsubscribe was ineffective: {counts!r}' + return cr + + errors = [] + previous_hook = sys.unraisablehook + sys.unraisablehook = errors.append + + def fail(*_args): + raise RuntimeError('ValueSet callback failed') + + failing_token = obj.on_map_changed(fail) + try: + try: + obj['callback-error'] = property_value_cls.create_int32(4) + except OSError: + pass + finally: + sys.unraisablehook = previous_hook + obj.off_map_changed(failing_token) + + if ( + len(errors) != 1 + or 'ValueSet callback failed' not in str(errors[0].exc_value) + ): + cr['error'] = ( + 'event callback failure was not reported through ' + f'sys.unraisablehook: {errors!r}' + ) + else: + cr['pass'] = True + elif kind == 'mutable_sequence_protocol': sequence = getattr(obj, member) values = check['set_value'] @@ -550,6 +733,31 @@ async def run_check( f'got {list(sequence)!r}' ) else: + sequence[:] = values + sequence[1:2] = ['.bmp', '.webp'] + if list(sequence) != [ + values[0], + '.bmp', + '.webp', + values[2], + ]: + cr['error'] = ( + f'slice assignment failed: {list(sequence)!r}' + ) + return cr + for operation in ( + lambda: sequence[len(sequence)], + lambda: sequence.__setitem__(len(sequence), '.bad'), + lambda: sequence.__delitem__(len(sequence)), + ): + try: + operation() + cr['error'] = ( + 'out-of-range sequence operation succeeded' + ) + return cr + except IndexError: + pass cr['pass'] = True elif kind == 'datetime_roundtrip': @@ -606,6 +814,16 @@ async def run_check( resource.__enter__() cr['error'] = 'closed object allowed context re-entry' except RuntimeError: + if hasattr(resource, 'create_reference'): + from dynwinrt_py import release_projected + + release_projected(resource) + try: + resource.create_reference() + cr['error'] = 'released object allowed a WinRT method call' + return cr + except (OSError, RuntimeError): + pass cr['pass'] = True elif kind == 'cross_class_chain': @@ -704,6 +922,63 @@ def convert_store_result(value): converted = await _DynWinRTAsync(raw_store, convert_store_result) + failing_stream = ( + cls.create() if hasattr(cls, 'create') else cls.create_default() + ) + failing_writer = writer_cls.create_data_writer( + failing_stream.get_output_stream_at(0) + ) + failing_writer.write_int32(write_val) + raw_failing_store = writer_mod._IDataWriter.method_by_name( + 'StoreAsync' + ).invoke(failing_writer._obj, []) + + def reject_store_result(_value): + raise ValueError('async result conversion failed') + + try: + await _DynWinRTAsync(raw_failing_store, reject_store_result) + cr['error'] = 'async result converter failure was not propagated' + return cr + except ValueError as error: + if str(error) != 'async result conversion failed': + cr['error'] = f'unexpected async conversion error: {error}' + return cr + + release_stream = ( + cls.create() if hasattr(cls, 'create') else cls.create_default() + ) + release_writer = writer_cls.create_data_writer( + release_stream.get_output_stream_at(0) + ) + release_writer.write_int32(write_val) + released_operation = release_writer.store_async() + await released_operation + released_operation.release() + released_operation.release() + for action in ( + lambda: released_operation.wait(), + lambda: released_operation.cancel(), + ): + try: + action() + cr['error'] = 'released async operation accepted an operation' + return cr + except RuntimeError as error: + if 'has been released' not in str(error): + cr['error'] = ( + f'unexpected released operation error: {error}' + ) + return cr + try: + await released_operation + cr['error'] = 'released async operation remained awaitable' + return cr + except RuntimeError as error: + if 'has been released' not in str(error): + cr['error'] = f'unexpected released await error: {error}' + return cr + buffer_cls = generated_type(pkg_name, 'Buffer') progress_buffer = buffer_cls.create(1024 * 1024) progress_buffer.length = progress_buffer.capacity @@ -712,6 +987,26 @@ def convert_store_result(value): write_op.progress(progress.append) written = await write_op await asyncio.sleep(0) + progress_errors = [] + + def progress_without_loop(): + try: + write_op.progress(lambda _value: None) + except RuntimeError as error: + progress_errors.append(str(error)) + + await asyncio.get_running_loop().run_in_executor( + None, progress_without_loop + ) + if ( + progress_errors + != ['progress() requires a running asyncio event loop'] + ): + cr['error'] = ( + 'progress() without an event loop returned an unexpected ' + f'error: {progress_errors!r}' + ) + return cr if ( stored < 4 @@ -734,6 +1029,303 @@ def convert_store_result(value): else: cr['pass'] = True + elif kind == 'data_stream_scalar_roundtrip': + from datetime import datetime, timedelta, timezone + from uuid import UUID + + stream = cls.create() if hasattr(cls, 'create') else cls.create_default() + writer_cls = generated_type(pkg_name, 'DataWriter') + reader_cls = generated_type(pkg_name, 'DataReader') + writer = writer_cls.create_data_writer(stream.get_output_stream_at(0)) + + guid = UUID('12345678-1234-5678-9abc-def012345678') + timestamp = datetime(2024, 1, 2, 3, 4, 5, 6000, tzinfo=timezone.utc) + duration = timedelta(days=1, seconds=2, microseconds=3000) + text = 'dynwinrt' + + writer.write_byte(0xAB) + writer.write_bytes(b'\x01\x02\x03') + writer.write_boolean(True) + writer.write_guid(guid) + writer.write_int16(-1234) + writer.write_int32(-12345678) + writer.write_int64(-1234567890123) + writer.write_u_int16(54321) + writer.write_u_int32(3_000_000_000) + writer.write_u_int64(9_000_000_000_000_000_000) + writer.write_single(1.25) + writer.write_double(2.5) + writer.write_date_time(timestamp) + writer.write_time_span(duration) + text_units = writer.measure_string(text) + writer.write_string(text) + pending = writer.unstored_buffer_length + stored = await writer.store_async() + flushed = await writer.flush_async() + + stream.seek(0) + reader = reader_cls.create_data_reader(stream.get_input_stream_at(0)) + loaded = await reader.load_async(stored) + values = { + 'byte': reader.read_byte(), + 'bytes': reader.read_bytes(bytearray(3)), + 'bool': reader.read_boolean(), + 'guid': reader.read_guid(), + 'i16': reader.read_int16(), + 'i32': reader.read_int32(), + 'i64': reader.read_int64(), + 'u16': reader.read_u_int16(), + 'u32': reader.read_u_int32(), + 'u64': reader.read_u_int64(), + 'f32': reader.read_single(), + 'f64': reader.read_double(), + 'datetime': reader.read_date_time(), + 'duration': reader.read_time_span(), + 'text': reader.read_string(text_units), + } + remaining = reader.unconsumed_buffer_length + writer_stream = writer.detach_stream() + reader_stream = reader.detach_stream() + writer.close() + reader.close() + + expected = { + 'byte': 0xAB, + 'bytes': b'\x01\x02\x03', + 'bool': True, + 'guid': guid, + 'i16': -1234, + 'i32': -12345678, + 'i64': -1234567890123, + 'u16': 54321, + 'u32': 3_000_000_000, + 'u64': 9_000_000_000_000_000_000, + 'datetime': timestamp, + 'duration': duration, + 'text': text, + } + mismatches = { + key: (expected[key], values[key]) + for key in expected + if expected[key] != values[key] + } + if abs(values['f32'] - 1.25) > 0.0001: + mismatches['f32'] = (1.25, values['f32']) + if abs(values['f64'] - 2.5) > 1e-10: + mismatches['f64'] = (2.5, values['f64']) + if ( + pending <= 0 + or stored != pending + or loaded != stored + or not flushed + or remaining != 0 + or writer_stream is None + or reader_stream is None + or mismatches + ): + cr['error'] = ( + f'data stream roundtrip failed: pending={pending}, ' + f'stored={stored}, loaded={loaded}, flushed={flushed}, ' + f'remaining={remaining}, mismatches={mismatches!r}' + ) + else: + cr['pass'] = True + + elif kind == 'calendar_comprehensive': + obj.year = 2024 + obj.month = 1 + obj.day = 2 + obj.hour = 3 + obj.minute = 4 + obj.second = 5 + obj.nanosecond = 0 + numeric_properties = [ + 'first_era', + 'last_era', + 'number_of_eras', + 'era', + 'first_year_in_this_era', + 'last_year_in_this_era', + 'number_of_years_in_this_era', + 'first_month_in_this_year', + 'last_month_in_this_year', + 'number_of_months_in_this_year', + 'first_day_in_this_month', + 'last_day_in_this_month', + 'number_of_days_in_this_month', + 'first_period_in_this_day', + 'last_period_in_this_day', + 'number_of_periods_in_this_day', + 'first_hour_in_this_period', + 'last_hour_in_this_period', + 'number_of_hours_in_this_period', + 'first_minute_in_this_hour', + 'last_minute_in_this_hour', + 'number_of_minutes_in_this_hour', + 'first_second_in_this_minute', + 'last_second_in_this_minute', + 'number_of_seconds_in_this_minute', + 'nanosecond', + ] + if not all(isinstance(getattr(obj, name), int) for name in numeric_properties): + cr['error'] = 'Calendar numeric metadata returned a non-integer' + return cr + if not isinstance(obj.is_daylight_saving_time, bool): + cr['error'] = 'Calendar daylight-saving property was not bool' + return cr + + original = obj.get_date_time() + clone = obj.clone() + if clone is None or obj.compare(clone) != 0 or obj.compare_date_time(original) != 0: + cr['error'] = 'Calendar clone or comparison failed' + return cr + + for method, amount in [ + ('add_years', 1), + ('add_months', 1), + ('add_weeks', 1), + ('add_days', 1), + ('add_hours', 1), + ('add_minutes', 1), + ('add_seconds', 1), + ('add_nanoseconds', 10_000), + ]: + before = obj.get_date_time() + getattr(obj, method)(amount) + if obj.get_date_time() == before: + cr['error'] = f'Calendar {method} did not change the value' + return cr + getattr(obj, method)(-amount) + if obj.get_date_time() != before: + cr['error'] = f'Calendar {method} did not round-trip' + return cr + if obj.compare_date_time(original) != 0: + cr['error'] = 'Calendar arithmetic changed the original value' + return cr + + other = obj.clone() + obj.add_days(1) + obj.copy_to(other) + if obj.compare(other) != 0: + cr['error'] = 'Calendar copy_to did not copy the current value' + return cr + obj.set_date_time(original) + + calendar_system = obj.get_calendar_system() + clock = obj.get_clock() + time_zone = obj.get_time_zone() + numeral_system = obj.numeral_system + obj.change_calendar_system(calendar_system) + obj.change_clock(clock) + obj.change_time_zone(time_zone) + obj.numeral_system = numeral_system + + string_calls = [ + ('era_as_full_string', ()), + ('era_as_string', (3,)), + ('year_as_string', ()), + ('year_as_truncated_string', (2,)), + ('year_as_padded_string', (4,)), + ('month_as_full_string', ()), + ('month_as_string', (3,)), + ('month_as_full_solo_string', ()), + ('month_as_solo_string', (3,)), + ('month_as_numeric_string', ()), + ('month_as_padded_numeric_string', (2,)), + ('day_as_string', ()), + ('day_as_padded_string', (2,)), + ('day_of_week_as_full_string', ()), + ('day_of_week_as_string', (3,)), + ('day_of_week_as_full_solo_string', ()), + ('day_of_week_as_solo_string', (3,)), + ('period_as_full_string', ()), + ('period_as_string', (2,)), + ('hour_as_string', ()), + ('hour_as_padded_string', (2,)), + ('minute_as_string', ()), + ('minute_as_padded_string', (2,)), + ('second_as_string', ()), + ('second_as_padded_string', (2,)), + ('nanosecond_as_string', ()), + ('nanosecond_as_padded_string', (3,)), + ('time_zone_as_full_string', ()), + ('time_zone_as_string', (3,)), + ] + formatted = [ + getattr(obj, method)(*args) + for method, args in string_calls + ] + if not all(isinstance(value, str) for value in formatted): + cr['error'] = 'Calendar formatting returned a non-string' + return cr + + minimum = obj.clone() + maximum = obj.clone() + minimum.set_to_min() + maximum.set_to_max() + if minimum.compare(maximum) >= 0: + cr['error'] = 'Calendar min/max ordering was invalid' + return cr + obj.set_to_now() + if not isinstance(obj.resolved_language, str): + cr['error'] = 'Calendar resolved_language was not a string' + else: + cr['pass'] = True + + elif kind == 'storage_query_temp_folder': + from pathlib import Path + from tempfile import TemporaryDirectory + + with TemporaryDirectory(prefix='dynwinrt-query-') as temp_dir: + root = Path(temp_dir) + (root / 'alpha.txt').write_text('alpha', encoding='utf-8') + (root / 'beta.txt').write_text('beta', encoding='utf-8') + + folder = await cls.get_folder_from_path_async(str(root)) + if folder is None or Path(folder.path) != root: + cr['error'] = 'StorageFolder path lookup failed' + return cr + + direct_files = await ( + folder.get_files_async_overload_default_options_start_and_count() + ) + query = folder.create_file_query_overload_default() + if query is None: + cr['error'] = 'StorageFolder.create_file_query returned null' + return cr + count = await query.get_item_count_async() + query_files = await query.get_files_async_default_start_and_count() + options = query.get_current_query_options() + query_folder = query.folder + missing = await folder.try_get_item_async('missing.file') + alpha = await folder.get_file_async('alpha.txt') + + if options is not None: + query.apply_new_query_options(options) + + direct_names = sorted(file.name for file in direct_files or []) + query_names = sorted(file.name for file in query_files or []) + if ( + direct_names != ['alpha.txt', 'beta.txt'] + or query_names != direct_names + or count != 2 + or query_folder is None + or not query_folder.is_equal(folder) + or missing is not None + or alpha is None + or alpha.name != 'alpha.txt' + or not alpha.is_of_type( + generated_type(pkg_name, 'StorageItemTypes').File + ) + ): + cr['error'] = ( + f'Storage query failed: direct={direct_names!r}, ' + f'query={query_names!r}, count={count}, ' + f'missing={missing!r}, alpha={alpha!r}' + ) + else: + cr['pass'] = True + elif kind == 'async_cancellation': import dynwinrt_py as dw @@ -810,6 +1402,18 @@ def block_on_sta(): task = asyncio.ensure_future(operation) await asyncio.sleep(0) + try: + operation.wait() + task.cancel() + release.set() + cr['error'] = 'wait() was not rejected after awaiting started' + return cr + except RuntimeError as error: + if 'after awaiting has started' not in str(error): + task.cancel() + release.set() + cr['error'] = f'unexpected started wait() error: {error}' + return cr task.cancel() try: await task @@ -827,6 +1431,67 @@ def block_on_sta(): else: cr['pass'] = True + elif kind == 'device_information_async_collection': + devices = await getattr(cls, member)() + if devices is None or not isinstance(devices.size, int): + cr['error'] = ( + 'DeviceInformation.find_all_async() did not return ' + 'a collection with an integer size' + ) + else: + cr['pass'] = True + + elif kind == 'bitmap_encoder_async_create': + stream_cls = generated_type(pkg_name, 'InMemoryRandomAccessStream') + stream = ( + stream_cls.create() + if hasattr(stream_cls, 'create') + else stream_cls.create_default() + ) + encoder_id = ( + cls.get_jpeg_encoder_id() + if hasattr(cls, 'get_jpeg_encoder_id') + else cls.jpeg_encoder_id + ) + encoder = await getattr(cls, member)(encoder_id, stream) + if encoder is None: + cr['error'] = 'BitmapEncoder.create_async() returned null' + else: + cr['pass'] = True + + elif kind == 'nested_struct_runtime': + module = importlib.import_module( + implementation_module_name(pkg_name, namespace, cls.__name__) + ) + descriptor_type = getattr(module, 'Direct3DSurfaceDescription') + nested_type = getattr(module, 'Direct3DMultisampleDescription') + pixel_format = generated_type(pkg_name, 'DirectXPixelFormat') + pack = getattr(module, 'pack_direct3_d_surface_description') + unpack = getattr(module, 'unpack_direct3_d_surface_description') + + first = descriptor_type() + second = descriptor_type() + if ( + not isinstance(first.multisample_description, nested_type) + or first.multisample_description is second.multisample_description + or not isinstance(first.format, pixel_format) + ): + cr['error'] = 'nested struct defaults were not Python-native' + return cr + + first.multisample_description.count = 4 + first.multisample_description.quality = 7 + first.format = pixel_format.R32G32B32A32Typeless + roundtrip = unpack(pack(first).to_value()) + if ( + roundtrip.multisample_description.count != 4 + or roundtrip.multisample_description.quality != 7 + or roundtrip.format != pixel_format.R32G32B32A32Typeless + ): + cr['error'] = 'nested struct or enum did not round-trip' + else: + cr['pass'] = True + else: cr['error'] = f'unknown check kind: {kind}' diff --git a/tests/e2e/runners/py_winui_runner.py b/tests/e2e/runners/py_winui_runner.py index aba113b9..7e8ab13d 100644 --- a/tests/e2e/runners/py_winui_runner.py +++ b/tests/e2e/runners/py_winui_runner.py @@ -247,6 +247,28 @@ def measure_override( ) return available_size + def arrange_override( + self, final_size: tuple[float, float] + ) -> tuple[float, float]: + state["arrange_override_count"] = ( + int(state.get("arrange_override_count", 0)) + 1 + ) + state["arrange_override_thread_id"] = threading.get_ident() + state["arrange_override_context"] = override_context.get() + if not isinstance(final_size, tuple) or len(final_size) != 2: + raise RuntimeError( + "ArrangeOverride did not receive a Size tuple" + ) + return final_size + + class PythonButton(Button): + def on_apply_template(self) -> None: + state["on_apply_template_count"] = ( + int(state.get("on_apply_template_count", 0)) + 1 + ) + state["on_apply_template_thread_id"] = threading.get_ident() + state["on_apply_template_context"] = override_context.get() + class MarkupPythonStackPanel(StackPanel): def measure_override( self, available_size: tuple[float, float] @@ -350,6 +372,7 @@ def __init__(self): ) composed_stack_panel = PythonStackPanel() + button = PythonButton() override_context.reset(context_token) override_context.set("changed-after-construction") composed_stack_panel.spacing = 3.0 @@ -581,6 +604,32 @@ def tick(_sender: object, _args: object) -> None: raise RuntimeError( "MeasureOverride lost its captured ContextVar context" ) + if int(state.get("arrange_override_count", 0)) < 1: + raise RuntimeError( + "WinUI did not invoke Python ArrangeOverride" + ) + if ( + state.get("arrange_override_thread_id") + != state["ui_thread_id"] + or state.get("arrange_override_context") + != "captured-at-construction" + ): + raise RuntimeError( + "ArrangeOverride lost its thread or context" + ) + if int(state.get("on_apply_template_count", 0)) < 1: + raise RuntimeError( + "WinUI did not invoke Python OnApplyTemplate" + ) + if ( + state.get("on_apply_template_thread_id") + != state["ui_thread_id"] + or state.get("on_apply_template_context") + != "captured-at-construction" + ): + raise RuntimeError( + "OnApplyTemplate lost its thread or context" + ) state["composition_validated"] = True if not factory_elements: raise RuntimeError( diff --git a/tests/e2e/runners/ts_runner.ts b/tests/e2e/runners/ts_runner.ts index 863175dd..2bdaa0c8 100644 --- a/tests/e2e/runners/ts_runner.ts +++ b/tests/e2e/runners/ts_runner.ts @@ -11,14 +11,15 @@ * npx tsx tests/e2e/runners/ts_runner.ts --specs tests/e2e/e2e_specs.json --generated tests/e2e/e2e_generated/ts --runtime bindings/js/dist/winrt.js [--output results.json] */ -import { strict as assert } from 'node:assert'; -import { spawn } from 'node:child_process'; -import * as fs from 'node:fs'; -import * as path from 'node:path'; -import { fileURLToPath } from 'node:url'; +import { strict as assert } from "node:assert"; +import { spawn } from "node:child_process"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { fileURLToPath } from "node:url"; interface Instantiate { - kind: 'activate' | 'static_factory' | 'none'; + kind: "activate" | "static_factory" | "none"; method?: string; args?: any[]; } @@ -71,7 +72,10 @@ interface SpecResult { } function toSnakeCase(name: string): string { - return name.replace(/([A-Z])/g, '_$1').replace(/^_/, '').toLowerCase(); + return name + .replace(/([A-Z])/g, "_$1") + .replace(/^_/, "") + .toLowerCase(); } function toCamelCase(name: string): string { @@ -94,7 +98,7 @@ async function runSpec( id: specId, namespace: spec.namespace, class: spec.class, - language: 'ts', + language: "ts", checks: [], pass: true, error: null, @@ -103,7 +107,7 @@ async function runSpec( try { // Import the generated module const modulePath = path.resolve(generatedDir, `${spec.class}.js`); - const mod = await import(`file://${modulePath.replace(/\\/g, '/')}`); + const mod = await import(`file://${modulePath.replace(/\\/g, "/")}`); const cls = mod[spec.class]; if (!cls) throw new Error(`Class ${spec.class} not found in ${modulePath}`); @@ -111,26 +115,54 @@ async function runSpec( let obj: any = null; const instKind = spec.instantiate.kind; - if (instKind === 'activate') { + if (instKind === "activate") { // Generated code provides create() or createDefault() for default constructors - if (typeof cls.create === 'function') { + if (typeof cls.create === "function") { obj = cls.create(); - } else if (typeof cls.createDefault === 'function') { + } else if (typeof cls.createDefault === "function") { obj = cls.createDefault(); } else { - throw new Error(`${spec.class} has no create() or createDefault() method for activate`); + throw new Error( + `${spec.class} has no create() or createDefault() method for activate`, + ); } - } else if (instKind === 'static_factory') { + } else if (instKind === "static_factory") { const methodName = toCamelCase(spec.instantiate.method!); const args = spec.instantiate.args || []; - obj = cls[methodName](...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 // Run checks for (const check of spec.checks) { - if (!(check.langs || ['py', 'ts']).includes('ts')) continue; - const cr = await runCheck(check, cls, spec.class, obj, generatedDir, runtime, runtimePath); + if (!(check.langs || ["py", "ts"]).includes("ts")) continue; + const cr = await runCheck( + check, + cls, + spec.class, + obj, + generatedDir, + runtime, + runtimePath, + ); result.checks.push(cr); if (!cr.pass) result.pass = false; } @@ -142,37 +174,55 @@ async function runSpec( return result; } -async function importClass(generatedDir: string, className: string): Promise { +async function importClass( + generatedDir: string, + className: string, +): Promise { const candidates = [ path.resolve(generatedDir, `${className}.js`), path.resolve(generatedDir, `${toPascalCase(className)}.js`), ]; for (const p of candidates) { if (fs.existsSync(p)) { - const mod = await import(`file://${p.replace(/\\/g, '/')}`); + const mod = await import(`file://${p.replace(/\\/g, "/")}`); if (mod[className]) return mod[className]; } } - throw new Error(`Class ${className} not found in: ${candidates.join(', ')}`); + throw new Error(`Class ${className} not found in: ${candidates.join(", ")}`); } async function runIssueRegression( name: string, generatedDir: string, runtimePath: string, -): Promise<{ code: number | null; stdout: string; stderr: string; timedOut: boolean }> { - const childPath = fileURLToPath(new URL('./ts_issue_regression_child.mjs', import.meta.url)); - const child = spawn(process.execPath, [childPath, name, generatedDir, runtimePath], { - stdio: ['ignore', 'pipe', 'pipe'], - windowsHide: true, - }); - let stdout = ''; - let stderr = ''; +): Promise<{ + code: number | null; + stdout: string; + stderr: string; + timedOut: boolean; +}> { + const childPath = fileURLToPath( + new URL("./ts_issue_regression_child.mjs", import.meta.url), + ); + const child = spawn( + process.execPath, + [childPath, name, generatedDir, runtimePath], + { + stdio: ["ignore", "pipe", "pipe"], + windowsHide: true, + }, + ); + let stdout = ""; + let stderr = ""; let timedOut = false; - child.stdout.setEncoding('utf8'); - child.stderr.setEncoding('utf8'); - child.stdout.on('data', chunk => { stdout += chunk; }); - child.stderr.on('data', chunk => { stderr += chunk; }); + child.stdout.setEncoding("utf8"); + child.stderr.setEncoding("utf8"); + child.stdout.on("data", (chunk) => { + stdout += chunk; + }); + child.stderr.on("data", (chunk) => { + stderr += chunk; + }); const timeout = setTimeout(() => { timedOut = true; @@ -180,11 +230,11 @@ async function runIssueRegression( }, 30_000); return new Promise((resolve, reject) => { - child.once('error', error => { + child.once("error", (error) => { clearTimeout(timeout); reject(error); }); - child.once('close', code => { + child.once("close", (code) => { clearTimeout(timeout); resolve({ code, stdout, stderr, timedOut }); }); @@ -201,28 +251,31 @@ async function runCheck( runtimePath: string, ): Promise { const kind = check.kind; - const member = check.member ? toCamelCase(check.member) : ''; + const member = check.member ? toCamelCase(check.member) : ""; const cr: CheckResult = { kind, member, pass: false, error: null }; try { - if (kind === 'property_equals') { + if (kind === "property_equals") { const actual = obj[member]; if (actual !== check.expected) { cr.error = `expected ${JSON.stringify(check.expected)}, got ${JSON.stringify(actual)}`; } else { cr.pass = true; } - } else if (kind === 'property_exists') { + } else if (kind === "property_exists") { const _ = obj[member]; // should not throw cr.pass = true; - } else if (kind === 'method_equals') { + } else if (kind === "method_equals") { const method = obj[member].bind(obj); let args: any[] = []; if (check.args) { args = check.args; } else if (check.args_factory) { const af = check.args_factory!; - const afCls = af.class === clsName ? cls : await importClass(generatedDir, af.class); + const afCls = + af.class === clsName + ? cls + : await importClass(generatedDir, af.class); const afMethod = toCamelCase(af.method); const afArgs = af.args || []; args = [afCls[afMethod](...afArgs)]; @@ -233,14 +286,14 @@ async function runCheck( } else { cr.pass = true; } - } else if (kind === 'method_result_contains') { + } else if (kind === "method_result_contains") { const method = obj[member].bind(obj); const args = check.args || []; const resultObj = method(...args); let actual: string; if (resultObj && resultObj.absoluteUri !== undefined) { actual = resultObj.absoluteUri; - } else if (resultObj && typeof resultObj.toString === 'function') { + } else if (resultObj && typeof resultObj.toString === "function") { actual = resultObj.toString(); } else { actual = String(resultObj); @@ -250,7 +303,7 @@ async function runCheck( } else { cr.pass = true; } - } else if (kind === 'static_equals') { + } else if (kind === "static_equals") { const method = cls[member].bind(cls); const args = check.args || []; const actual = method(...args); @@ -259,18 +312,21 @@ async function runCheck( } else { cr.pass = true; } - } else if (kind === 'static_not_null') { + } else if (kind === "static_not_null") { const method = cls[member].bind(cls); const args = check.args || []; const actual = method(...args); if (actual == null) { - cr.error = 'returned null'; + cr.error = "returned null"; } else { cr.pass = true; } - } else if (kind === 'property_in_range') { + } else if (kind === "property_in_range") { const actual = obj[member]; - const val = typeof actual === 'object' && actual !== null && 'value' in actual ? actual.value : actual; + const val = + typeof actual === "object" && actual !== null && "value" in actual + ? actual.value + : actual; const min = check.min ?? -Infinity; const max = check.max ?? Infinity; if (val < min || val > max) { @@ -278,23 +334,31 @@ async function runCheck( } else { cr.pass = true; } - } else if (kind === 'interface_cast') { + } else if (kind === "interface_cast") { const ifaceClsName = (check as any).interface_class as string; const methodName = toCamelCase((check as any).method as string); const ifaceCls = await importClass(generatedDir, ifaceClsName); const casted = ifaceCls.from(obj._obj); const resultVal = casted[methodName]; - const actual = String(typeof resultVal === 'function' ? resultVal.call(casted) : resultVal); + const actual = String( + typeof resultVal === "function" ? resultVal.call(casted) : resultVal, + ); - if ((check as any).contains && !actual.includes((check as any).contains)) { + if ( + (check as any).contains && + !actual.includes((check as any).contains) + ) { cr.error = `"${(check as any).contains}" not in "${actual}"`; - } else if (check.expected !== undefined && actual !== String(check.expected)) { + } else if ( + check.expected !== undefined && + actual !== String(check.expected) + ) { cr.error = `expected ${JSON.stringify(check.expected)}, got ${JSON.stringify(actual)}`; } else { cr.pass = true; } - } else if (kind === 'property_set_equals') { + } else if (kind === "property_set_equals") { const setValue = (check as any).set_value; obj[member] = setValue; const actual = obj[member]; @@ -303,7 +367,26 @@ async function runCheck( } else { cr.pass = true; } - } else if (kind === 'vector_view_access') { + } else if (kind === "method_then_property_equals") { + let target = obj; + const interfaceClass = (check as any).interface_class as + | string + | undefined; + if (interfaceClass) { + const iface = await importClass(generatedDir, interfaceClass); + target = iface.from(obj._obj); + } + target[member](...((check as any).args || [])); + let actual = obj; + for (const segment of (check as any).property_path || []) { + actual = actual[toCamelCase(segment)]; + } + if (actual !== check.expected) { + cr.error = `expected ${JSON.stringify(check.expected)}, got ${JSON.stringify(actual)}`; + } else { + cr.pass = true; + } + } else if (kind === "vector_view_access") { const vec = obj[member]; const minSize = (check as any).min_size ?? 1; const size = vec.size; @@ -312,12 +395,12 @@ async function runCheck( } else { const first = vec.getAt(0); if (first == null) { - cr.error = 'getAt(0) returned null'; + cr.error = "getAt(0) returned null"; } else { cr.pass = true; } } - } else if (kind === 'vector_index_of') { + } else if (kind === "vector_index_of") { const vec = obj[member]; let searchValue = (check as any).search_value; const expectedIndex = (check as any).expected_index; @@ -331,7 +414,7 @@ async function runCheck( } else { cr.pass = true; } - } else if (kind === 'vector_get_many') { + } else if (kind === "vector_get_many") { const vec = obj[member]; const capacity = Math.min((check as any).capacity ?? 4, vec.size); const atEnd = (check as any).at_end ?? false; @@ -339,13 +422,13 @@ async function runCheck( if (atEnd && items.length !== 0) { cr.error = `getMany at Size returned ${items.length} items`; } else if (!atEnd && items.length === 0) { - cr.error = 'getMany returned no items'; + cr.error = "getMany returned no items"; } else if (!atEnd && items[0] !== vec.getAt(0)) { cr.error = `first item ${JSON.stringify(items[0])} does not match getAt(0)`; } else { cr.pass = true; } - } else if (kind === 'ireference_roundtrip') { + } else if (kind === "ireference_roundtrip") { const value = (check as any).value; obj[member] = value; if (obj[member] !== value) { @@ -355,20 +438,22 @@ async function runCheck( obj[member] = null; if (obj[member] !== null) { - cr.error = 'setting nullable value to null did not clear it'; + cr.error = "setting nullable value to null did not clear it"; return cr; } const propertyValueMod = await import( - `file://${path.resolve(generatedDir, 'PropertyValue.js').replace(/\\/g, '/')}` + `file://${path.resolve(generatedDir, "PropertyValue.js").replace(/\\/g, "/")}` ); const referenceModule = (check as any).reference_class; const referenceMod = await import( - `file://${path.resolve(generatedDir, `${referenceModule}.js`).replace(/\\/g, '/')}` + `file://${path.resolve(generatedDir, `${referenceModule}.js`).replace(/\\/g, "/")}` ); const factory = propertyValueMod.PropertyValue[ - (check as any).factory.replace(/_([a-z])/g, (_: string, c: string) => c.toUpperCase()) + (check as any).factory.replace(/_([a-z])/g, (_: string, c: string) => + c.toUpperCase(), + ) ]; const boxed = factory((check as any).compatibility_value); const referenceClass = referenceMod[(check as any).reference_class]; @@ -378,7 +463,262 @@ async function runCheck( } else { cr.pass = true; } - } else if (kind === 'struct_roundtrip') { + } else if (kind === "sequence_protocol") { + const sequence = member === "self" ? obj : obj[member]; + const expectedSize = (check as any).expected_size; + const values = sequence.toArray(); + if (sequence.length !== expectedSize || values.length !== expectedSize) { + cr.error = `expected sequence size ${expectedSize}, got length=${sequence.length}, array=${values.length}`; + } else if ( + expectedSize > 0 && + sequence.at(-1) !== values[values.length - 1] + ) { + cr.error = "negative sequence indexing returned a different value"; + } else { + cr.pass = true; + } + } else if (kind === "mapping_protocol") { + const mapping = obj[member]; + const expectedSize = (check as any).expected_size; + if (mapping.length !== expectedSize) { + cr.error = `expected mapping size ${expectedSize}, got ${mapping.length}`; + return cr; + } + const setKey = (check as any).set_key; + if (setKey !== undefined) { + const setValue = (check as any).set_value; + mapping.set(setKey, setValue); + if (!mapping.has(setKey) || mapping.get(setKey) !== setValue) { + cr.error = "mapping set/get/has did not round-trip"; + return cr; + } + const view = mapping.getView(); + if (!view.has(setKey) || view.get(setKey) !== setValue) { + cr.error = "mapping view did not preserve the new entry"; + return cr; + } + mapping.delete(setKey); + if (mapping.has(setKey) || mapping.get(setKey) !== undefined) { + cr.error = "mapping delete did not remove the entry"; + return cr; + } + } + cr.pass = true; + } else if (kind === "value_set_mapping") { + const PropertyValue = await importClass(generatedDir, "PropertyValue"); + const first = PropertyValue.createString("first"); + const second = PropertyValue.createInt32(2); + if (obj.length !== 0 || obj.size !== 0) { + cr.error = "new ValueSet was not empty"; + return cr; + } + if (obj.insert("first", first)) { + cr.error = "first ValueSet insert reported replacement"; + return cr; + } + obj.set("second", second); + if ( + obj.length !== 2 || + !obj.has("first") || + obj.get("first") == null || + obj.get("second") == null + ) { + cr.error = "ValueSet insertion or lookup failed"; + return cr; + } + const view = obj.getView(); + if (view.length !== 2 || !view.has("first") || !view.has("second")) { + cr.error = "ValueSet view did not preserve entries"; + return cr; + } + obj.delete("first"); + if (obj.has("first") || obj.length !== 1) { + cr.error = "ValueSet deletion failed"; + return cr; + } + obj.clear(); + if (obj.length !== 0) { + cr.error = "ValueSet clear failed"; + } else { + cr.pass = true; + } + } else if (kind === "mutable_sequence_protocol") { + const sequence = obj[member]; + const values = (check as any).set_value as any[]; + sequence.replaceAll(values); + sequence.setAt(0, values[values.length - 1]); + sequence.insertAt(0, values[0]); + sequence.removeAt(2); + sequence.append(".bmp"); + sequence.removeAtEnd(); + sequence.removeAtEnd(); + const actual = sequence.toArray(); + if (actual.length !== 2 || actual[0] !== values[0]) { + cr.error = `mutable vector operations failed: ${JSON.stringify(actual)}`; + return cr; + } + if (sequence.at(-1) !== actual[actual.length - 1]) { + cr.error = "negative vector indexing failed"; + return cr; + } + sequence.clear(); + if (sequence.length !== 0) { + cr.error = "mutable vector clear failed"; + } else { + cr.pass = true; + } + } else if (kind === "calendar_comprehensive") { + obj.year = 2024; + obj.month = 1; + obj.day = 2; + obj.hour = 3; + obj.minute = 4; + obj.second = 5; + obj.nanosecond = 0; + const numericProperties = [ + "firstEra", + "lastEra", + "numberOfEras", + "era", + "firstYearInThisEra", + "lastYearInThisEra", + "numberOfYearsInThisEra", + "firstMonthInThisYear", + "lastMonthInThisYear", + "numberOfMonthsInThisYear", + "firstDayInThisMonth", + "lastDayInThisMonth", + "numberOfDaysInThisMonth", + "nanosecond", + ]; + if (!numericProperties.every((name) => typeof obj[name] === "number")) { + cr.error = "Calendar numeric metadata returned a non-number"; + return cr; + } + const original = obj.clone(); + if (original == null || obj.compare(original) !== 0) { + cr.error = "Calendar clone or comparison failed"; + return cr; + } + for (const [method, amount] of [ + ["addYears", 1], + ["addMonths", 1], + ["addWeeks", 1], + ["addDays", 1], + ["addHours", 1], + ["addMinutes", 1], + ["addSeconds", 1], + ["addNanoseconds", 10_000], + ] as const) { + obj[method](amount); + if (obj.compare(original) === 0) { + cr.error = `Calendar ${method} did not change the value`; + return cr; + } + obj[method](-amount); + if (obj.compare(original) !== 0) { + cr.error = `Calendar ${method} did not round-trip`; + return cr; + } + } + const calendarSystem = obj.getCalendarSystem(); + const clock = obj.getClock(); + const timeZone = obj.getTimeZone(); + obj.changeCalendarSystem(calendarSystem); + obj.changeClock(clock); + obj.changeTimeZone(timeZone); + const formatted = [ + obj.eraAsString(), + obj.yearAsString(), + obj.monthAsString(), + obj.dayAsString(), + obj.dayOfWeekAsString(), + obj.periodAsString(), + obj.hourAsString(), + obj.minuteAsString(), + obj.secondAsString(), + obj.timeZoneAsString(), + ]; + if (!formatted.every((value) => typeof value === "string")) { + cr.error = "Calendar formatting returned a non-string"; + return cr; + } + const minimum = obj.clone(); + const maximum = obj.clone(); + minimum.setToMin(); + maximum.setToMax(); + if (minimum.compare(maximum) >= 0) { + cr.error = "Calendar min/max ordering was invalid"; + } else { + obj.setToNow(); + cr.pass = true; + } + } else if (kind === "nested_struct_runtime") { + const modulePath = path.resolve(generatedDir, `${clsName}.js`); + const mod = await import(`file://${modulePath.replace(/\\/g, "/")}`); + const DirectXPixelFormat = await importClass( + generatedDir, + "DirectXPixelFormat", + ); + const descriptor = { + width: 1920, + height: 1080, + format: DirectXPixelFormat.R32G32B32A32Typeless, + multisampleDescription: { count: 4, quality: 7 }, + }; + const packed = mod.packDirect3DSurfaceDescription(descriptor); + const roundtrip = mod.unpackDirect3DSurfaceDescription(packed.toValue()); + if ( + roundtrip.width !== descriptor.width || + roundtrip.height !== descriptor.height || + roundtrip.format !== descriptor.format || + roundtrip.multisampleDescription.count !== 4 || + roundtrip.multisampleDescription.quality !== 7 + ) { + cr.error = `nested struct roundtrip failed: ${JSON.stringify(roundtrip)}`; + } else { + cr.pass = true; + } + } else if (kind === "storage_query_temp_folder") { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "dynwinrt-query-")); + try { + fs.writeFileSync(path.join(tempDir, "alpha.txt"), "alpha"); + fs.writeFileSync(path.join(tempDir, "beta.txt"), "beta"); + const folder = await cls.getFolderFromPathAsync(tempDir); + if (folder == null) + throw new Error("StorageFolder path lookup returned null"); + const directView = await folder.getFilesAsync(); + const directFiles = directView?.toArray() ?? []; + const query = folder.createFileQuery(); + if (query == null) throw new Error("createFileQuery returned null"); + const count = await query.getItemCountAsync(); + const queryView = await query.getFilesAsync(); + const queryFiles = queryView?.toArray() ?? []; + const missing = await folder.tryGetItemAsync("missing.file"); + const alpha = await folder.getFileAsync("alpha.txt"); + const directNames = (directFiles || []) + .map((file: any) => file.name) + .sort(); + const queryNames = (queryFiles || []) + .map((file: any) => file.name) + .sort(); + if ( + JSON.stringify(directNames) !== + JSON.stringify(["alpha.txt", "beta.txt"]) || + JSON.stringify(queryNames) !== JSON.stringify(directNames) || + count !== 2 || + missing != null || + alpha?.name !== "alpha.txt" || + !query.folder?.isEqual(folder) + ) { + cr.error = `Storage query failed: direct=${JSON.stringify(directNames)}, query=${JSON.stringify(queryNames)}, count=${count}`; + } else { + cr.pass = true; + } + } finally { + fs.rmSync(tempDir, { recursive: true, force: true }); + } + } else if (kind === "struct_roundtrip") { const structClass = check.struct_class as string; const structModule = check.struct_module as string; // In TS, structs are interfaces + packFn. Find the module file. @@ -386,9 +726,12 @@ async function runCheck( path.resolve(generatedDir, `${toPascalCase(structModule)}.js`), path.resolve(generatedDir, `${structModule}.js`), ]; - let modPath = candidates.find(p => fs.existsSync(p)); - if (!modPath) throw new Error(`Struct module not found: tried ${candidates.join(', ')}`); - const structMod = await import(`file://${modPath.replace(/\\/g, '/')}`); + let modPath = candidates.find((p) => fs.existsSync(p)); + if (!modPath) + throw new Error( + `Struct module not found: tried ${candidates.join(", ")}`, + ); + const structMod = await import(`file://${modPath.replace(/\\/g, "/")}`); // TS structs are plain objects (interfaces), create one directly const structArgs = check.struct_args as Record; @@ -401,45 +744,63 @@ async function runCheck( const staticMethod = cls[methodName].bind(cls); const result = staticMethod(structObj); if (result == null) { - cr.error = 'static method returned null after struct pack'; + cr.error = "static method returned null after struct pack"; } else { cr.pass = true; } - } else if (kind === 'array_roundtrip') { + } else if (kind === "array_roundtrip") { // Use the runtime already imported and passed to runCheck const elemType = check.element_type as string; const values = check.values as any[]; let arr: any; - if (elemType === 'i32') arr = runtime.DynWinRtArray.fromI32Values(values); - else if (elemType === 'string') arr = runtime.DynWinRtArray.fromStringValues(values); - else if (elemType === 'f64') arr = runtime.DynWinRtArray.fromF64Values(values); - else if (elemType === 'u8') arr = runtime.DynWinRtArray.fromU8Values(values); - else if (elemType === 'i64') arr = runtime.DynWinRtArray.fromI64Values(values); - else if (elemType === 'f32') arr = runtime.DynWinRtArray.fromF32Values(values); - else { cr.error = `unsupported element_type: ${elemType}`; return cr; } + if (elemType === "i32") arr = runtime.DynWinRtArray.fromI32Values(values); + else if (elemType === "string") + arr = runtime.DynWinRtArray.fromStringValues(values); + else if (elemType === "f64") + arr = runtime.DynWinRtArray.fromF64Values(values); + else if (elemType === "u8") + arr = runtime.DynWinRtArray.fromU8Values(values); + else if (elemType === "i64") + arr = runtime.DynWinRtArray.fromI64Values(values); + else if (elemType === "f32") + arr = runtime.DynWinRtArray.fromF32Values(values); + else { + cr.error = `unsupported element_type: ${elemType}`; + return cr; + } const methodName = toCamelCase(member); // Find method: try exact, then case-insensitive match let staticMethod = cls[methodName]; if (!staticMethod) { const lowerTarget = methodName.toLowerCase(); - const found = Object.getOwnPropertyNames(cls).find(k => k.toLowerCase() === lowerTarget); + const found = Object.getOwnPropertyNames(cls).find( + (k) => k.toLowerCase() === lowerTarget, + ); if (found) staticMethod = cls[found]; } - if (!staticMethod) { cr.error = `method ${methodName} not found on ${clsName}`; return cr; } + if (!staticMethod) { + cr.error = `method ${methodName} not found on ${clsName}`; + return cr; + } const result = staticMethod.bind(cls)(arr); if (result == null) { - cr.error = 'static method returned null for array'; + cr.error = "static method returned null for array"; } else { cr.pass = true; } - } else if (kind === 'async_memory_roundtrip') { + } else if (kind === "async_memory_roundtrip") { const writeVal = (check as any).write_value ?? 42; - const stream = typeof cls.create === 'function' ? cls.create() : cls.createDefault(); + const stream = + typeof cls.create === "function" ? cls.create() : cls.createDefault(); - const writerMod = await import(`file://${path.resolve(generatedDir, 'DataWriter.js').replace(/\\/g, '/')}`); - const readerMod = await import(`file://${path.resolve(generatedDir, 'DataReader.js').replace(/\\/g, '/')}`); + const writerMod = await import( + `file://${path.resolve(generatedDir, "DataWriter.js").replace(/\\/g, "/")}` + ); + const readerMod = await import( + `file://${path.resolve(generatedDir, "DataReader.js").replace(/\\/g, "/")}` + ); const DataWriter = writerMod.DataWriter; const DataReader = readerMod.DataReader; @@ -457,7 +818,7 @@ async function runCheck( } else { cr.pass = true; } - } else if (kind === 'event_callback') { + } else if (kind === "event_callback") { const sourceMethod = obj[member].bind(obj); const source = sourceMethod(); const eventName = (check as any).event_name as string; @@ -465,28 +826,39 @@ async function runCheck( let fired = false; const onMethod = `on${eventName}`; - source[onMethod]((..._args: any[]) => { fired = true; }); + source[onMethod]((..._args: any[]) => { + fired = true; + }); // Try direct method, fall back to IClosable cast for close() - if (typeof source[triggerMethod] === 'function') { + if (typeof source[triggerMethod] === "function") { source[triggerMethod](); } else { - const IClosable = await importClass(generatedDir, 'IClosable'); + const IClosable = await importClass(generatedDir, "IClosable"); const closable = IClosable.from(source._obj); closable[triggerMethod](); } // NonBlocking TSFN: callback is queued on event loop, await a tick - await new Promise(r => setTimeout(r, 100)); + await new Promise((r) => setTimeout(r, 100)); if (!fired) { cr.error = `event ${eventName} was not fired after ${triggerMethod}()`; } else { cr.pass = true; } - } else if (kind === 'static_string_length') { - const method = cls[member]?.bind(cls) ?? cls[Object.getOwnPropertyNames(cls).find(k => k.toLowerCase() === member.toLowerCase())!]?.bind(cls); - if (!method) { cr.error = `method ${member} not found`; return cr; } + } else if (kind === "static_string_length") { + const method = + cls[member]?.bind(cls) ?? + cls[ + Object.getOwnPropertyNames(cls).find( + (k) => k.toLowerCase() === member.toLowerCase(), + )! + ]?.bind(cls); + if (!method) { + cr.error = `method ${member} not found`; + return cr; + } const args = check.args || []; const actual = String(method(...args)); const minLen = (check as any).min_length ?? 0; @@ -495,37 +867,57 @@ async function runCheck( } else { cr.pass = true; } - } else if (kind === 'static_expect_error') { - const method = cls[member]?.bind(cls) ?? cls[Object.getOwnPropertyNames(cls).find(k => k.toLowerCase() === member.toLowerCase())!]?.bind(cls); - if (!method) { cr.error = `method ${member} not found`; return cr; } + } else if (kind === "static_expect_error") { + const method = + cls[member]?.bind(cls) ?? + cls[ + Object.getOwnPropertyNames(cls).find( + (k) => k.toLowerCase() === member.toLowerCase(), + )! + ]?.bind(cls); + if (!method) { + cr.error = `method ${member} not found`; + return cr; + } const args = check.args || []; try { method(...args); - cr.error = 'expected error but call succeeded'; + cr.error = "expected error but call succeeded"; } catch { cr.pass = true; } - } else if (kind === 'cross_class_chain') { + } else if (kind === "cross_class_chain") { const saved: Record = {}; let chainOk = true; for (const step of (check as any).steps) { const stepClsName = step.class; const stepModPath = path.resolve(generatedDir, `${stepClsName}.js`); - const stepMod = await import(`file://${stepModPath.replace(/\\/g, '/')}`); + const stepMod = await import( + `file://${stepModPath.replace(/\\/g, "/")}` + ); const stepCls = stepMod[stepClsName]; const stepMethodName = toCamelCase(step.method); - const stepMethod = stepCls[stepMethodName]?.bind(stepCls) - ?? stepCls[Object.getOwnPropertyNames(stepCls).find((k: string) => k.toLowerCase() === stepMethodName.toLowerCase())!]?.bind(stepCls); - if (!stepMethod) { cr.error = `method ${stepMethodName} not found on ${stepClsName}`; chainOk = false; break; } + const stepMethod = + stepCls[stepMethodName]?.bind(stepCls) ?? + stepCls[ + Object.getOwnPropertyNames(stepCls).find( + (k: string) => k.toLowerCase() === stepMethodName.toLowerCase(), + )! + ]?.bind(stepCls); + if (!stepMethod) { + cr.error = `method ${stepMethodName} not found on ${stepClsName}`; + chainOk = false; + break; + } const stepArgs: any[] = [...(step.args || [])]; - for (const ref of (step.args_refs || [])) { + for (const ref of step.args_refs || []) { stepArgs.push(saved[ref]); } const result = stepMethod(...stepArgs); if (step.save_as) saved[step.save_as] = result; if (step.expected !== undefined) { - const actual = typeof result === 'object' ? String(result) : result; + const actual = typeof result === "object" ? String(result) : result; if (actual !== step.expected) { cr.error = `${step.method}: expected ${JSON.stringify(step.expected)}, got ${JSON.stringify(actual)}`; chainOk = false; @@ -535,8 +927,8 @@ async function runCheck( } if (chainOk) cr.pass = true; } else if ( - kind === 'device_information_async_collection' - || kind === 'bitmap_encoder_async_create' + kind === "device_information_async_collection" || + kind === "bitmap_encoder_async_create" ) { const child = await runIssueRegression(kind, generatedDir, runtimePath); if (child.timedOut) { @@ -558,31 +950,41 @@ async function runCheck( async function main() { const args = process.argv.slice(2); - let specsPath = ''; - let generatedDir = ''; - let runtimePath = ''; - let outputPath = ''; + let specsPath = ""; + let generatedDir = ""; + let runtimePath = ""; + let outputPath = ""; for (let i = 0; i < args.length; i++) { - if (args[i] === '--specs') specsPath = args[++i]; - else if (args[i] === '--generated') generatedDir = args[++i]; - else if (args[i] === '--runtime') runtimePath = args[++i]; - else if (args[i] === '--output') outputPath = args[++i]; + if (args[i] === "--specs") specsPath = args[++i]; + else if (args[i] === "--generated") generatedDir = args[++i]; + else if (args[i] === "--runtime") runtimePath = args[++i]; + else if (args[i] === "--output") outputPath = args[++i]; } if (!specsPath || !generatedDir || !runtimePath) { - console.error('Usage: ts_runner.ts --specs --generated --runtime [--output ]'); + console.error( + "Usage: ts_runner.ts --specs --generated --runtime [--output ]", + ); process.exit(2); } // Fix imports in generated files (both ESM `import ... from` and CJS `require`) - const absRuntime = path.resolve(runtimePath).replace(/\\/g, '/'); - const tsFiles = fs.readdirSync(generatedDir).filter(f => f.endsWith('.js') || f.endsWith('.mjs')); + const absRuntime = path.resolve(runtimePath).replace(/\\/g, "/"); + const tsFiles = fs + .readdirSync(generatedDir) + .filter((f) => f.endsWith(".js") || f.endsWith(".mjs")); for (const f of tsFiles) { const filePath = path.join(generatedDir, f); - let content = fs.readFileSync(filePath, 'utf8'); - content = content.replace(/from '@microsoft\/dynwinrt'/g, `from 'file://${absRuntime}'`); - content = content.replace(/require\(['"]@microsoft\/dynwinrt['"]\)/g, `require('${absRuntime}')`); + let content = fs.readFileSync(filePath, "utf8"); + content = content.replace( + /from '@microsoft\/dynwinrt'/g, + `from 'file://${absRuntime}'`, + ); + content = content.replace( + /require\(['"]@microsoft\/dynwinrt['"]\)/g, + `require('${absRuntime}')`, + ); fs.writeFileSync(filePath, content); } @@ -591,9 +993,9 @@ async function main() { runtime.roInitialize(1); // Load specs - const data: SpecFile = JSON.parse(fs.readFileSync(specsPath, 'utf8')); - const specs = data.specs.filter(s => - (s.langs || ['py', 'ts']).includes('ts') && !s.skip_reason + const data: SpecFile = JSON.parse(fs.readFileSync(specsPath, "utf8")); + const specs = data.specs.filter( + (s) => (s.langs || ["py", "ts"]).includes("ts") && !s.skip_reason, ); const results: SpecResult[] = []; @@ -608,7 +1010,12 @@ async function main() { console.log(` PASS ${r.id}`); } else { failed++; - const err = r.error || r.checks.filter(c => !c.pass).map(c => c.error).join('; '); + const err = + r.error || + r.checks + .filter((c) => !c.pass) + .map((c) => c.error) + .join("; "); console.log(` FAIL ${r.id}: ${err}`); } } @@ -616,7 +1023,7 @@ async function main() { console.log(`\n TypeScript: ${passed} passed, ${failed} failed`); const output = { - language: 'ts', + language: "ts", total: results.length, passed, failed, @@ -630,7 +1037,7 @@ async function main() { process.exit(failed > 0 ? 1 : 0); } -main().catch(e => { - console.error('Runner error:', e); +main().catch((e) => { + console.error("Runner error:", e); process.exit(2); }); diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs index 7574a8a3..a4a7c3c5 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/collections.rs @@ -120,3 +120,34 @@ pub(crate) fn is_mapping_input(kind: CollectionKind, args: &[TypeMeta]) -> bool TypeMeta::Parameterized { piid, .. } if piid == IKEY_VALUE_PAIR_PIID )) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn map_piids_project_to_python_mapping_protocols() { + assert_eq!( + kind_from_piid(IMAP_VIEW_PIID), + Some(CollectionKind::Mapping) + ); + assert_eq!( + runtime_mixin(CollectionKind::Mapping), + Some("_WinRTMappingMixin") + ); + assert_eq!(abc_name(CollectionKind::Mapping), Some("Mapping")); + + assert_eq!( + kind_from_piid(IMAP_PIID), + Some(CollectionKind::MutableMapping) + ); + assert_eq!( + runtime_mixin(CollectionKind::MutableMapping), + Some("_WinRTMutableMappingMixin") + ); + assert_eq!( + abc_name(CollectionKind::MutableMapping), + Some("MutableMapping") + ); + } +} diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/structs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/structs.rs index a592a383..d17f581b 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/structs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/structs.rs @@ -38,7 +38,7 @@ pub(super) fn generate_struct_helpers(s: &TypeMeta) -> String { format!( "{}: {} = {}", to_snake_case(&f.name), - py_struct_field_type(&f.typ), + py_struct_constructor_field_type(&f.typ), py_default_value(&f.typ) ) }) @@ -49,7 +49,16 @@ pub(super) fn generate_struct_helpers(s: &TypeMeta) -> String { )); for f in fields { let snake = to_snake_case(&f.name); - out.push_str(&format!(" self.{} = {}\n", snake, snake)); + if let TypeMeta::Struct { name, .. } = &f.typ + && foundation_type(&f.typ).is_none() + && name != "HResult" + { + out.push_str(&format!( + " self.{snake} = {name}() if {snake} is None else {snake}\n" + )); + } else { + out.push_str(&format!(" self.{snake} = {snake}\n")); + } } for f in fields { if ireference_inner_type(&f.typ).is_none() { @@ -165,6 +174,12 @@ fn generate_foundation_struct_helpers(s: &TypeMeta, kind: FoundationType) -> Str /// Python default value for struct field initialization. pub(super) fn py_default_value(typ: &TypeMeta) -> String { + match foundation_type(typ) { + Some(FoundationType::DateTime) => return "_dynwinrt_ticks_to_datetime(0)".to_string(), + Some(FoundationType::TimeSpan) => return "timedelta(0)".to_string(), + None => {} + } + match typ { TypeMeta::Bool => "False".to_string(), TypeMeta::I8 @@ -174,16 +189,32 @@ pub(super) fn py_default_value(typ: &TypeMeta) -> String { | TypeMeta::I32 | TypeMeta::U32 | TypeMeta::I64 - | TypeMeta::U64 - | TypeMeta::Enum { .. } => "0".to_string(), + | TypeMeta::U64 => "0".to_string(), + TypeMeta::Enum { + namespace, name, .. + } => format!( + "_dynwinrt_enum('{}', '{}', 0)", + python_module_name(namespace, name), + name + ), TypeMeta::Char16 => "'\\0'".to_string(), TypeMeta::F32 | TypeMeta::F64 => "0.0".to_string(), TypeMeta::String => "''".to_string(), TypeMeta::Guid => "UUID(int=0)".to_string(), + TypeMeta::Struct { name, .. } if name == "HResult" => "0".to_string(), _ => "None".to_string(), } } +fn py_struct_constructor_field_type(typ: &TypeMeta) -> String { + match typ { + TypeMeta::Struct { name, .. } if foundation_type(typ).is_none() && name != "HResult" => { + format!("{} | None", py_struct_field_type(typ)) + } + _ => py_struct_field_type(typ), + } +} + /// Returns the exported names for struct helpers (for Python index). pub(super) fn py_struct_export_names(s: &TypeMeta) -> Vec { match s { diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/structs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/structs.rs index a2b45ec7..b0b7fc38 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/structs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/structs.rs @@ -5,7 +5,7 @@ use crate::types::TypeMeta; -use super::naming::to_snake_case; +use super::naming::{python_module_name, to_snake_case}; use super::native_types::{FoundationType, foundation_type}; use super::signature::{py_runtime_symbol, py_wrap_arg}; use super::type_helpers::py_optional_type; @@ -36,7 +36,7 @@ pub(crate) fn py_struct_field_getter(typ: &TypeMeta, index: usize) -> String { TypeMeta::I16 => format!("s.get_i16({})", index), TypeMeta::U16 => format!("s.get_u16({})", index), TypeMeta::Char16 => format!("chr(s.get_u16({}))", index), - TypeMeta::I32 | TypeMeta::Enum { .. } => format!("s.get_i32({})", index), + TypeMeta::I32 => format!("s.get_i32({})", index), TypeMeta::U32 => format!("s.get_u32({})", index), TypeMeta::I64 => format!("s.get_i64({})", index), TypeMeta::U64 => format!("s.get_u64({})", index), @@ -44,6 +44,17 @@ pub(crate) fn py_struct_field_getter(typ: &TypeMeta, index: usize) -> String { TypeMeta::F64 => format!("s.get_f64({})", index), TypeMeta::String => format!("s.get_hstring({})", index), TypeMeta::Guid => format!("_dynwinrt_uuid(s.get_guid({}))", index), + TypeMeta::Enum { + namespace, + name, + underlying, + .. + } => format!( + "_dynwinrt_enum('{}', '{}', {})", + python_module_name(namespace, name), + name, + py_struct_field_getter(underlying, index) + ), TypeMeta::Struct { name, .. } if name == "HResult" => format!("s.get_i32({})", index), TypeMeta::Struct { name, .. } => format!( "_unpack_{}(s.get_struct({}).to_value())", @@ -67,7 +78,7 @@ pub(crate) fn py_struct_field_setter(typ: &TypeMeta, index: usize, value_expr: & TypeMeta::I16 => format!("s.set_i16({}, {})", index, value_expr), TypeMeta::U16 => format!("s.set_u16({}, {})", index, value_expr), TypeMeta::Char16 => format!("s.set_u16({}, ord({}))", index, value_expr), - TypeMeta::I32 | TypeMeta::Enum { .. } => format!("s.set_i32({}, {})", index, value_expr), + TypeMeta::I32 => format!("s.set_i32({}, {})", index, value_expr), TypeMeta::U32 => format!("s.set_u32({}, {})", index, value_expr), TypeMeta::I64 => format!("s.set_i64({}, {})", index, value_expr), TypeMeta::U64 => format!("s.set_u64({}, {})", index, value_expr), @@ -75,6 +86,9 @@ pub(crate) fn py_struct_field_setter(typ: &TypeMeta, index: usize, value_expr: & TypeMeta::F64 => format!("s.set_f64({}, {})", index, value_expr), TypeMeta::String => format!("s.set_hstring({}, {})", index, value_expr), TypeMeta::Guid => format!("s.set_guid({}, _dynwinrt_guid({}))", index, value_expr), + TypeMeta::Enum { underlying, .. } => { + py_struct_field_setter(underlying, index, &format!("int({value_expr})")) + } TypeMeta::Struct { name, .. } if name == "HResult" => { format!("s.set_i32({}, {})", index, value_expr) } diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/stub_helpers.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/stub_helpers.rs index 0f3fa235..6a1b82b3 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/stub_helpers.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/stub_helpers.rs @@ -141,8 +141,8 @@ pub(super) fn py_struct_field_stub_type(typ: &TypeMeta) -> String { | TypeMeta::I32 | TypeMeta::U32 | TypeMeta::I64 - | TypeMeta::U64 - | TypeMeta::Enum { .. } => "int".to_string(), + | TypeMeta::U64 => "int".to_string(), + TypeMeta::Enum { name, .. } => format!("'{}'", name), TypeMeta::Char16 => "str".to_string(), TypeMeta::F32 | TypeMeta::F64 => "float".to_string(), TypeMeta::String => "str".to_string(), diff --git a/tools/dynwinrt-codegen/src/main.rs b/tools/dynwinrt-codegen/src/main.rs index fce9a05a..d9eeab74 100644 --- a/tools/dynwinrt-codegen/src/main.rs +++ b/tools/dynwinrt-codegen/src/main.rs @@ -2057,7 +2057,7 @@ fn write_python_package_indexes( .collect::>(); let root_index = python::generate_index(&root_classes, &root_interfaces, &root_enums); - write_python_index( + write_python_lazy_root_index( &output_dir.join("__init__.py"), &root_index, append, @@ -2300,12 +2300,135 @@ fn write_python_index( write_file(path, &content) } +fn write_python_lazy_root_index( + path: &Path, + generated: &str, + append: bool, + suppressed_names: &HashSet, +) -> Result<(), String> { + let existing = if append && path.exists() { + fs::read_to_string(path).map_err(|e| format!("Failed to read {}: {}", path.display(), e))? + } else { + GENERATED_PYTHON_HEADER.to_string() + }; + let content = merge_python_lazy_root_indexes(&existing, generated, suppressed_names); + write_file(path, &content) +} + +fn merge_python_lazy_root_indexes( + existing: &str, + generated: &str, + suppressed_names: &HashSet, +) -> String { + let mut exports = BTreeMap::::new(); + collect_python_root_exports(existing, suppressed_names, &mut exports); + collect_python_root_exports(generated, suppressed_names, &mut exports); + + let mut out = String::from(GENERATED_PYTHON_HEADER); + out.push_str("from importlib import import_module as _import_module\n\n"); + out.push_str("__all__ = (\n"); + for name in exports.keys() { + out.push_str(&format!(" \"{name}\",\n")); + } + out.push_str(")\n\n"); + out.push_str("_EXPORTS = {\n"); + for (name, (module, symbol)) in &exports { + out.push_str(&format!(" \"{name}\": (\"{module}\", \"{symbol}\"),\n")); + } + out.push_str( + "}\n\n\ + \n\ + def __getattr__(name):\n\ + \x20 try:\n\ + \x20 module_name, symbol_name = _EXPORTS[name]\n\ + \x20 except KeyError:\n\ + \x20 raise AttributeError(\n\ + \x20 f\"module {__name__!r} has no attribute {name!r}\"\n\ + \x20 ) from None\n\ + \x20 value = getattr(_import_module(module_name, __name__), symbol_name)\n\ + \x20 globals()[name] = value\n\ + \x20 return value\n\ + \n\ + \n\ + def __dir__():\n\ + \x20 return sorted(set(globals()) | set(__all__))\n", + ); + out +} + +fn collect_python_root_exports( + content: &str, + suppressed_names: &HashSet, + exports: &mut BTreeMap, +) { + for line in content.lines() { + if let Some((module, symbols)) = parse_python_import_line(line) { + for (source_symbol, exported_symbol) in symbols { + if suppressed_names.contains(&source_symbol) + || suppressed_names.contains(&exported_symbol) + { + continue; + } + exports + .entry(exported_symbol) + .or_insert_with(|| (module.clone(), source_symbol)); + } + } else if let Some((exported_symbol, module, source_symbol)) = + parse_python_lazy_export(line) + { + if suppressed_names.contains(&source_symbol) + || suppressed_names.contains(&exported_symbol) + { + continue; + } + exports + .entry(exported_symbol) + .or_insert((module, source_symbol)); + } + } +} + +fn parse_python_import_line(line: &str) -> Option<(String, Vec<(String, String)>)> { + let line = line.split_once(" #").map_or(line, |(line, _)| line); + let (source, exports) = line.split_once(" import ")?; + let module = source.strip_prefix("from ")?.to_string(); + if !module.starts_with('.') { + return None; + } + let exports = exports + .split(',') + .map(str::trim) + .filter(|export| !export.is_empty()) + .map(|export| { + export.split_once(" as ").map_or_else( + || (export.to_string(), export.to_string()), + |(source, alias)| (source.trim().to_string(), alias.trim().to_string()), + ) + }) + .collect(); + Some((module, exports)) +} + +fn parse_python_lazy_export(line: &str) -> Option<(String, String, String)> { + let line = line.trim(); + let line = line.strip_prefix('"')?; + let (exported_symbol, line) = line.split_once("\": (\"")?; + let (module, source_symbol) = line.split_once("\", \"")?; + let source_symbol = source_symbol.strip_suffix("\"),")?; + Some(( + exported_symbol.to_string(), + module.to_string(), + source_symbol.to_string(), + )) +} + fn merge_python_indexes( existing: &str, generated: &str, suppressed_names: &HashSet, ) -> String { let mut imports = BTreeSet::new(); + let mut exported_symbols = HashSet::new(); for line in existing.lines().chain(generated.lines()) { if line.starts_with("from .") { let (line, comment) = line @@ -2318,10 +2441,14 @@ fn merge_python_indexes( .split(',') .map(str::trim) .filter(|export| { - let symbol = export + let source_symbol = export .split_once(" as ") .map_or(*export, |(name, _)| name.trim()); - !suppressed_names.contains(symbol) + let exported_symbol = export + .split_once(" as ") + .map_or(*export, |(_, alias)| alias.trim()); + !suppressed_names.contains(source_symbol) + && exported_symbols.insert(exported_symbol.to_string()) }) .collect::>(); if !exports.is_empty() { @@ -3429,6 +3556,16 @@ mod tests { .unwrap(); assert!(facade.contains("IID_IWidget as IID_IWidget")); assert!(facade.contains("IWidget as IWidget")); + let root_runtime = fs::read_to_string(output.join("__init__.py")).unwrap(); + assert!(root_runtime.contains("def __getattr__(name):")); + assert!( + root_runtime.contains("\"IWidget\": (\".contoso__foundation__i_widget\", \"IWidget\")") + ); + assert!(!root_runtime.contains("from .contoso__foundation__i_widget import")); + let root_stub = fs::read_to_string(output.join("__init__.pyi")).unwrap(); + assert!(root_stub.contains( + "from .contoso__foundation__i_widget import IID_IWidget, IWidget as IWidget" + )); fs::remove_dir_all(output).unwrap(); } @@ -3445,6 +3582,51 @@ mod tests { assert!(merged.contains("Point, pack_point # noqa: F401")); } + #[test] + fn root_merge_deduplicates_shared_struct_exports() { + let existing = format!( + "{GENERATED_PYTHON_HEADER}from .contoso__first import First, EventRegistrationToken, pack_event_registration_token\n" + ); + let generated = format!( + "{GENERATED_PYTHON_HEADER}from .contoso__second import Second, EventRegistrationToken, pack_event_registration_token, TextSegment\n" + ); + + let merged = merge_python_indexes(&existing, &generated, &HashSet::new()); + + assert!(merged.contains("from .contoso__first import First, EventRegistrationToken, pack_event_registration_token")); + assert!(merged.contains("from .contoso__second import Second, TextSegment")); + assert_eq!(merged.matches("EventRegistrationToken").count(), 1); + assert_eq!(merged.matches("pack_event_registration_token").count(), 1); + } + + #[test] + fn lazy_root_merge_migrates_eager_indexes_and_appends_exports() { + let existing = + format!("{GENERATED_PYTHON_HEADER}from .contoso__first import First, Shared\n"); + let generated = + format!("{GENERATED_PYTHON_HEADER}from .contoso__second import Second, Shared\n"); + + let merged = merge_python_lazy_root_indexes(&existing, &generated, &HashSet::new()); + + assert!(merged.contains("from importlib import import_module as _import_module")); + assert!(merged.contains("\"First\": (\".contoso__first\", \"First\")")); + assert!(merged.contains("\"Second\": (\".contoso__second\", \"Second\")")); + assert!(merged.contains("\"Shared\": (\".contoso__first\", \"Shared\")")); + assert_eq!(merged.matches("\"Shared\": (").count(), 1); + assert!(!merged.contains("from .contoso__first import")); + assert!(merged.contains("def __getattr__(name):")); + assert!(merged.contains("def __dir__():")); + + let appended = merge_python_lazy_root_indexes( + &merged, + &format!("{GENERATED_PYTHON_HEADER}from .contoso__third import Third\n"), + &HashSet::from(["Second".to_string()]), + ); + assert!(appended.contains("\"First\": (\".contoso__first\", \"First\")")); + assert!(appended.contains("\"Third\": (\".contoso__third\", \"Third\")")); + assert!(!appended.contains("\"Second\": (")); + } + #[test] fn generated_inventory_does_not_claim_nested_manual_metadata() { let output = test_directory("manual-metadata"); diff --git a/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs b/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs index 51c0b245..4c04b7ba 100644 --- a/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs +++ b/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs @@ -251,6 +251,72 @@ fn scalar_ireference_fields_preserve_native_python_types() { assert!(js.contains("DynWinRtValue.enumValue("), "{js}"); } +#[test] +fn nested_struct_defaults_and_enum_fields_are_python_native() { + let mode = TypeMeta::Enum { + namespace: "Synthetic".into(), + name: "Mode".into(), + underlying: Box::new(TypeMeta::U32), + members: vec![], + is_flags: false, + doc: None, + deprecated: None, + }; + let inner = TypeMeta::Struct { + namespace: "Synthetic".into(), + name: "Inner".into(), + fields: vec![FieldMeta { + name: "Count".into(), + typ: TypeMeta::U32, + }], + }; + let outer = TypeMeta::Struct { + namespace: "Synthetic".into(), + name: "Outer".into(), + fields: vec![ + FieldMeta { + name: "Mode".into(), + typ: mode, + }, + FieldMeta { + name: "Inner".into(), + typ: inner, + }, + ], + }; + let class = class_with_struct("UsesNestedStruct", outer); + let known = HashSet::from([ + "UsesNestedStruct".to_string(), + "Mode".to_string(), + "Inner".to_string(), + "Outer".to_string(), + ]); + let py = python::generate_class(&class, &known, &HashSet::new(), &HashSet::new()); + let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); + + assert!( + py.contains("def __init__(self, mode: 'Mode' = _dynwinrt_enum('mode', 'Mode', 0), inner: 'Inner' | None = None):"), + "{py}" + ); + assert!( + py.contains("self.inner = Inner() if inner is None else inner"), + "{py}" + ); + assert!( + py.contains("mode=_dynwinrt_enum('mode', 'Mode', s.get_u32(0))"), + "{py}" + ); + assert!(py.contains("s.set_u32(0, int(v.mode))"), "{py}"); + assert!(py.contains("s.set_struct(1, _pack_inner(v.inner))"), "{py}"); + + assert!( + pyi.contains("def __init__(self, mode: 'Mode' = ..., inner: 'Inner' = ...) -> None: ..."), + "{pyi}" + ); + assert!(pyi.contains("mode: 'Mode'"), "{pyi}"); + assert!(pyi.contains("inner: 'Inner'"), "{pyi}"); +} + #[test] fn sdk_http_progress_ireference_u64_fields_are_native_optional_values() { if !std::path::Path::new(WINDOWS_WINMD).exists() { From 933ede66dc3d72234a7b89cdb79c9879277334e9 Mon Sep 17 00:00:00 2001 From: leileizhang Date: Mon, 10 Aug 2026 12:46:02 +0800 Subject: [PATCH 2/5] Fix CommonJS facade export assertions Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- bindings/js/__test__/index.spec.ts | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index fd55af8d..5c685cd5 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -4,6 +4,7 @@ import test from 'ava' import { spawn, spawnSync } from 'node:child_process' import { existsSync } from 'node:fs' +import { createRequire } from 'node:module' import { resolve } from 'node:path' import { fileURLToPath } from 'node:url' @@ -21,8 +22,6 @@ import { } from '../dist/winrt.js' import * as winrtRuntime from '../dist/winrt.js' import * as comRuntime from '../dist/com.js' -import * as unsafeComRuntime from '../dist/com-unsafe.js' -import * as nativeRuntime from '../dist/index.js' import { DynCom, DynComDispatchParams, @@ -33,6 +32,12 @@ import { DynComVariant, } from '../dist/com-unsafe.js' +const requireFromTest = createRequire(import.meta.url) +const nativeRuntime = requireFromTest('../dist/index.js') as Record +const winrtCjsRuntime = requireFromTest('../dist/winrt.js') as Record +const comCjsRuntime = requireFromTest('../dist/com.js') as Record +const unsafeComRuntime = requireFromTest('../dist/com-unsafe.js') as Record + const moduleKeys = (value: object) => Object.keys(value) .filter((key) => key !== 'default' && key !== 'module.exports') @@ -127,9 +132,9 @@ test('package facades exactly partition native exports', (t) => { 'DynComUnsafeInterface', ]) - t.deepEqual(moduleKeys(winrtRuntime), expectedWinrt) + t.deepEqual(moduleKeys(winrtCjsRuntime), expectedWinrt) t.deepEqual( - moduleKeys(comRuntime), + moduleKeys(comCjsRuntime), nativeKeys.filter((name) => safeComNames.has(name)), ) t.deepEqual( @@ -137,9 +142,9 @@ test('package facades exactly partition native exports', (t) => { nativeKeys.filter((name) => unsafeComNames.has(name)), ) - t.is(winrtRuntime.WinGuid, comRuntime.WinGuid) - t.is(comRuntime.initializeCom, unsafeComRuntime.initializeCom) - for (const name of moduleKeys(comRuntime)) { + t.is(winrtCjsRuntime.WinGuid, comCjsRuntime.WinGuid) + t.is(comCjsRuntime.initializeCom, unsafeComRuntime.initializeCom) + for (const name of moduleKeys(comCjsRuntime)) { t.true(moduleKeys(unsafeComRuntime).includes(name), `${name} must remain available from /com/unsafe`) } }) From 319fa6aaf10d1ecb9a7804da4daf0bc1ee2ec15a Mon Sep 17 00:00:00 2001 From: leileizhang Date: Mon, 10 Aug 2026 13:06:30 +0800 Subject: [PATCH 3/5] Use filesystem identity in storage E2E Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/e2e/runners/py_runner.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/e2e/runners/py_runner.py b/tests/e2e/runners/py_runner.py index c7769ccb..1f3586cd 100644 --- a/tests/e2e/runners/py_runner.py +++ b/tests/e2e/runners/py_runner.py @@ -1282,8 +1282,11 @@ def progress_without_loop(): (root / 'beta.txt').write_text('beta', encoding='utf-8') folder = await cls.get_folder_from_path_async(str(root)) - if folder is None or Path(folder.path) != root: - cr['error'] = 'StorageFolder path lookup failed' + if folder is None or not Path(folder.path).samefile(root): + cr['error'] = ( + 'StorageFolder path lookup failed: ' + f'expected={str(root)!r}, actual={getattr(folder, "path", None)!r}' + ) return cr direct_files = await ( From c57c1f63aea0b0381c74fcc173965b5283b2cb98 Mon Sep 17 00:00:00 2001 From: leileizhang Date: Mon, 10 Aug 2026 13:25:43 +0800 Subject: [PATCH 4/5] Align facade tests with safe COM exports Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- bindings/js/__test__/index.spec.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/bindings/js/__test__/index.spec.ts b/bindings/js/__test__/index.spec.ts index 2cbfe5e6..e95cede1 100644 --- a/bindings/js/__test__/index.spec.ts +++ b/bindings/js/__test__/index.spec.ts @@ -121,9 +121,7 @@ test('package facades exactly partition native exports', (t) => { 'DynComSafeArray', 'DynComVariant', 'DynWinRtValue', - 'DynWinRTValue', 'WinGuid', - 'WinGUID', 'initializeCom', ]) const unsafeComNames = new Set([ @@ -150,6 +148,10 @@ test('package facades exactly partition native exports', (t) => { t.is(winrtCjsRuntime.WinGuid, comCjsRuntime.WinGuid) t.is(comCjsRuntime.initializeCom, unsafeComRuntime.initializeCom) + t.false(Object.prototype.hasOwnProperty.call(comCjsRuntime, 'DynWinRTValue')) + t.false(Object.prototype.hasOwnProperty.call(comCjsRuntime, 'WinGUID')) + t.false(Object.prototype.hasOwnProperty.call(unsafeComRuntime, 'DynWinRTValue')) + t.false(Object.prototype.hasOwnProperty.call(unsafeComRuntime, 'WinGUID')) for (const name of moduleKeys(comCjsRuntime)) { t.true(moduleKeys(unsafeComRuntime).includes(name), `${name} must remain available from /com/unsafe`) } From f6838e4c24bf5fe36e99d62eddfd80c0a192024e Mon Sep 17 00:00:00 2001 From: leileizhang Date: Mon, 10 Aug 2026 15:42:49 +0800 Subject: [PATCH 5/5] Fix nested struct runtime annotations Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- tests/e2e/runners/py_runner.py | 18 ++++++++++++++++++ .../codegen/winrt/python/generator/structs.rs | 3 ++- .../tests/ireference_struct_field_test.rs | 3 ++- 3 files changed, 22 insertions(+), 2 deletions(-) diff --git a/tests/e2e/runners/py_runner.py b/tests/e2e/runners/py_runner.py index 1f3586cd..ba00c2c8 100644 --- a/tests/e2e/runners/py_runner.py +++ b/tests/e2e/runners/py_runner.py @@ -1463,6 +1463,8 @@ def block_on_sta(): cr['pass'] = True elif kind == 'nested_struct_runtime': + from typing import get_type_hints + module = importlib.import_module( implementation_module_name(pkg_name, namespace, cls.__name__) ) @@ -1471,6 +1473,22 @@ def block_on_sta(): pixel_format = generated_type(pkg_name, 'DirectXPixelFormat') pack = getattr(module, 'pack_direct3_d_surface_description') unpack = getattr(module, 'unpack_direct3_d_surface_description') + constructor_hints = get_type_hints( + descriptor_type.__init__, + globalns={ + **vars(module), + 'DirectXPixelFormat': pixel_format, + }, + ) + if ( + constructor_hints.get('multisample_description') + != nested_type | None + ): + cr['error'] = ( + 'nested struct constructor annotation did not resolve: ' + f'{constructor_hints!r}' + ) + return cr first = descriptor_type() second = descriptor_type() diff --git a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/structs.rs b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/structs.rs index d17f581b..aeaf43ed 100644 --- a/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/structs.rs +++ b/tools/dynwinrt-codegen/src/codegen/winrt/python/generator/structs.rs @@ -5,6 +5,7 @@ use super::*; use crate::codegen::winrt::python::native_types::{FoundationType, foundation_type}; +use crate::codegen::winrt::python::type_helpers::py_optional_type; // ====================================================================== // Struct helpers: Python dataclass-style + _unpack/_pack functions @@ -209,7 +210,7 @@ pub(super) fn py_default_value(typ: &TypeMeta) -> String { fn py_struct_constructor_field_type(typ: &TypeMeta) -> String { match typ { TypeMeta::Struct { name, .. } if foundation_type(typ).is_none() && name != "HResult" => { - format!("{} | None", py_struct_field_type(typ)) + py_optional_type(py_struct_field_type(typ)) } _ => py_struct_field_type(typ), } diff --git a/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs b/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs index 4c04b7ba..042a32dc 100644 --- a/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs +++ b/tools/dynwinrt-codegen/tests/ireference_struct_field_test.rs @@ -295,9 +295,10 @@ fn nested_struct_defaults_and_enum_fields_are_python_native() { let pyi = python_stub::generate_class_stub(&class, &known, &HashSet::new(), &HashSet::new()); assert!( - py.contains("def __init__(self, mode: 'Mode' = _dynwinrt_enum('mode', 'Mode', 0), inner: 'Inner' | None = None):"), + py.contains("def __init__(self, mode: 'Mode' = _dynwinrt_enum('mode', 'Mode', 0), inner: Inner | None = None):"), "{py}" ); + assert!(!py.contains("inner: 'Inner' | None"), "{py}"); assert!( py.contains("self.inner = Inner() if inner is None else inner"), "{py}"