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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions .github/workflows/coverage.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ on:

permissions:
contents: read
pull-requests: write

concurrency:
group: coverage-${{ github.ref }}
Expand Down Expand Up @@ -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 `
Expand All @@ -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 = '<!-- dynwinrt-mixed-language-coverage -->'
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,
})
}
104 changes: 81 additions & 23 deletions bindings/js/__test__/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -31,6 +32,17 @@ import {
DynComVariant,
} from '../dist/com-unsafe.js'

const requireFromTest = createRequire(import.meta.url)
const nativeRuntime = requireFromTest('../dist/index.js') as Record<string, unknown>
const winrtCjsRuntime = requireFromTest('../dist/winrt.js') as Record<string, unknown>
const comCjsRuntime = requireFromTest('../dist/com.js') as Record<string, unknown>
const unsafeComRuntime = requireFromTest('../dist/com-unsafe.js') as Record<string, unknown>

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'))
Expand Down Expand Up @@ -96,6 +108,67 @@ 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',
'WinGuid',
'initializeCom',
])
const unsafeComNames = new Set([
...safeComNames,
'DynCom',
'DynComDispatchInvokeResult',
'DynComInterface',
'DynComMethodHandle',
'DynComMethodSig',
'DynComType',
'DynComUnsafe',
'DynComUnsafeInterface',
])

t.deepEqual(moduleKeys(winrtCjsRuntime), expectedWinrt)
t.deepEqual(
moduleKeys(comCjsRuntime),
nativeKeys.filter((name) => safeComNames.has(name)),
)
t.deepEqual(
moduleKeys(unsafeComRuntime),
nativeKeys.filter((name) => unsafeComNames.has(name)),
)

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`)
}
})

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(
Expand All @@ -105,10 +178,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())
Expand All @@ -117,10 +187,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/ },
)
})
Expand Down Expand Up @@ -217,14 +284,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)
Expand All @@ -238,10 +300,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) => {
Expand Down Expand Up @@ -417,10 +478,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])
Expand Down
31 changes: 9 additions & 22 deletions bindings/py/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> {
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 {
Expand Down
88 changes: 88 additions & 0 deletions bindings/py/tests/test_basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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", [
Expand Down
Loading
Loading