Repository navigation
Expand file tree
/
Copy pathtest_python_collections.py
More file actions
509 lines (371 loc) · 17.3 KB
/
Copy pathtest_python_collections.py
File metadata and controls
509 lines (371 loc) · 17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
"""
A Python list, dict or iterable passed where WinRT wants a collection.
test_collections.py is the other direction - a WinRT collection read from
Python - and these are the calls where the Python object is the collection and
WinRT is the one reading it. TestComponent's collectionN() methods take one of
each of the five collection interfaces and hand back a copy of it; its
collectionN_call() methods run the pass the other way round, calling a Python
handler that returns one and then reading, changing and emptying what it gets,
which is what reaches the members that only a mutable collection has.
"""
import ctypes
import sys
import unittest
from collections.abc import Iterable, Mapping, MutableMapping, MutableSequence, Sequence
from typing import Any, SupportsIndex
import test_winrt.testcomponent as tc
from winrt.windows.foundation.collections import IKeyValuePair
from winrt.system.hresult import E_BOUNDS, PYWINRT_E_UNRAISABLE_PYTHON_EXCEPTION
from ._util import catch_unraisable
E_POINTER = ctypes.HRESULT(0x80004003).value
class LoggingSequence:
"""A sequence that records the Python operations WinRT reads it with."""
def __init__(self, items: list[str]) -> None:
self.items = list(items)
self.log: list[str] = []
def __len__(self) -> int:
self.log.append("len")
return len(self.items)
def __getitem__(self, index: int) -> str:
self.log.append("getitem")
return self.items[index]
class LoggingMapping:
"""A mapping that records the Python operations WinRT reads it with."""
def __init__(self, items: dict[str, str]) -> None:
self.items = dict(items)
self.log: list[str] = []
def __len__(self) -> int:
self.log.append("len")
return len(self.items)
def __getitem__(self, key: str) -> str:
self.log.append("getitem")
return self.items[key]
def __iter__(self) -> Any:
self.log.append("iter")
return iter(self.items)
class LoggingList(list[str]):
"""A list that records every operation, including the ones that change it."""
log: list[str]
def __init__(self, items: Any) -> None:
super().__init__(items)
self.log = []
def __len__(self) -> int:
self.log.append("len")
return super().__len__()
def __getitem__(self, index: SupportsIndex | slice) -> Any:
self.log.append("getitem")
return super().__getitem__(index)
def __setitem__(self, index: SupportsIndex | slice, value: Any) -> None:
self.log.append("setitem")
super().__setitem__(index, value)
def __delitem__(self, index: SupportsIndex | slice) -> None:
self.log.append("delslice" if isinstance(index, slice) else "delitem")
super().__delitem__(index)
def __iter__(self) -> Any:
self.log.append("iter")
return super().__iter__()
def append(self, value: Any) -> None:
self.log.append("append")
super().append(value)
class LoggingDict(dict[str, str]):
"""A dict that records every operation, including the ones that change it."""
log: list[str]
def __init__(self, items: Any) -> None:
super().__init__(items)
self.log = []
def __len__(self) -> int:
self.log.append("len")
return super().__len__()
def __getitem__(self, key: Any) -> Any:
self.log.append("getitem")
return super().__getitem__(key)
def __setitem__(self, key: Any, value: Any) -> None:
self.log.append("setitem")
super().__setitem__(key, value)
def __delitem__(self, key: Any) -> None:
self.log.append("delitem")
super().__delitem__(key)
def __iter__(self) -> Any:
self.log.append("iter")
return super().__iter__()
def clear(self) -> None:
self.log.append("clear")
super().clear()
class TestSequenceAsCollection(unittest.TestCase):
def setUp(self) -> None:
self.tests = tc.TestRunner.make_tests()
def test_a_list_is_an_iterable(self) -> None:
items = ["1", "2", "3"]
ret, out = self.tests.collection1(items)
self.assertListEqual(list(ret), items)
self.assertListEqual(list(out), items)
def test_a_generator_is_an_iterable(self) -> None:
items = ["1", "2", "3"]
ret, _ = self.tests.collection1(x for x in items)
self.assertListEqual(list(ret), items)
def test_a_list_is_a_vector(self) -> None:
items = ["1", "2", "3"]
ret, out = self.tests.collection5(items)
self.assertListEqual(list(ret), items)
self.assertListEqual(list(out), items)
def test_a_tuple_is_a_vector(self) -> None:
# Nothing this call asks a vector of changes it, so a sequence that
# cannot be changed still stands in for one.
ret, _ = self.tests.collection5(("1", "2")) # type: ignore
self.assertListEqual(list(ret), ["1", "2"])
def test_a_list_is_a_vector_view(self) -> None:
items = ["1", "2", "3"]
ret, out = self.tests.collection6(items)
self.assertListEqual(list(ret), items)
self.assertListEqual(list(out), items)
def test_an_empty_list_is_a_collection(self) -> None:
for method in (
self.tests.collection1,
self.tests.collection5,
self.tests.collection6,
):
with self.subTest(method=method):
ret, _ = method([])
self.assertListEqual(list(ret), [])
def test_a_sequence_is_read_rather_than_copied(self) -> None:
sequence = LoggingSequence(["1", "2"])
self.tests.collection5(sequence) # type: ignore
# The call reached the Python object itself, which is what makes both
# sides see the same collection.
self.assertIn("len", sequence.log)
self.assertIn("getitem", sequence.log)
def test_the_sequence_is_let_go_of_after_the_call(self) -> None:
items = ["1", "2"]
before = sys.getrefcount(items)
self.tests.collection5(items)
self.assertEqual(sys.getrefcount(items), before)
def test_an_index_the_sequence_does_not_have_is_out_of_bounds(self) -> None:
class ShortSequence:
def __len__(self) -> int:
return 3
def __getitem__(self, index: int) -> str:
return ["1", "2"][index]
# The one failure WinRT has a name for, so the call reports it rather
# than the unraisable hook.
with self.assertRaises(OSError) as ctx, catch_unraisable() as exceptions:
self.tests.collection5(ShortSequence()) # type: ignore
self.assertEqual(ctx.exception.winerror, E_BOUNDS)
self.assertEqual(exceptions, [])
def test_an_element_of_the_wrong_type_is_unraisable(self) -> None:
# There is no Python caller to raise it to while WinRT is reading the
# list, so the TypeError goes to the unraisable hook and the call
# fails with the HRESULT that says one was raised.
with self.assertRaises(OSError) as ctx, catch_unraisable() as exceptions:
self.tests.collection5([1]) # type: ignore
self.assertEqual(ctx.exception.winerror, PYWINRT_E_UNRAISABLE_PYTHON_EXCEPTION)
self.assertEqual(len(exceptions), 1)
self.assertEqual(exceptions[0].exc_type, TypeError)
# the type, rather than a list whose repr() could be any size
self.assertIs(exceptions[0].object, list)
def test_none_is_passed_as_a_null_collection(self) -> None:
# Some WinRT methods take null for no collection at all, so the callee
# is the one to refuse it, as TestComponent does.
with self.assertRaises(OSError) as ctx:
self.tests.collection5(None) # type: ignore[arg-type]
self.assertEqual(ctx.exception.winerror, E_POINTER)
def test_a_str_is_not_a_collection_of_strings(self) -> None:
# A str iterates as the strings of its characters, which is never what
# it is passed for, so it is refused rather than read that way.
for method in (
self.tests.collection1,
self.tests.collection5,
self.tests.collection6,
):
with (
self.subTest(method=method),
self.assertRaisesRegex(TypeError, "collection of strings, not a str"),
):
method("ab") # type: ignore[arg-type]
def test_something_that_is_not_a_sequence_is_refused(self) -> None:
with self.assertRaisesRegex(TypeError, "sequence"):
self.tests.collection5(42) # type: ignore
def test_something_that_cannot_be_iterated_is_refused(self) -> None:
with self.assertRaisesRegex(TypeError, "iterable"):
self.tests.collection1(42) # type: ignore
def test_a_winrt_collection_is_still_passed_as_itself(self) -> None:
ret, _ = self.tests.collection5(["1", "2"])
again, _ = self.tests.collection5(ret)
self.assertListEqual(list(again), ["1", "2"])
class TestMappingAsCollection(unittest.TestCase):
def setUp(self) -> None:
self.tests = tc.TestRunner.make_tests()
def test_a_dict_is_a_map(self) -> None:
entries = {"1": "2", "3": "4"}
ret, out = self.tests.collection3(entries)
self.assertDictEqual(dict(ret), entries)
self.assertDictEqual(dict(out), entries)
def test_a_dict_is_a_map_view(self) -> None:
entries = {"1": "2", "3": "4"}
ret, out = self.tests.collection4(entries)
self.assertDictEqual(dict(ret), entries)
self.assertDictEqual(dict(out), entries)
def test_a_dict_is_an_iterable_of_pairs(self) -> None:
entries = {"1": "2", "3": "4"}
ret, out = self.tests.collection2(entries)
# An IIterable<IKeyValuePair<K, V>> yields pairs where Python yields
# keys, so the runtime makes a pair of each entry as it goes.
self.assertDictEqual({i.key: i.value for i in ret}, entries)
self.assertDictEqual({i.key: i.value for i in out}, entries)
def test_an_empty_dict_is_a_collection(self) -> None:
for method in (
self.tests.collection2,
self.tests.collection3,
self.tests.collection4,
):
with self.subTest(method=method):
ret, _ = method({})
self.assertEqual(len(list(ret)), 0)
def test_a_mapping_is_read_rather_than_copied(self) -> None:
mapping = LoggingMapping({"1": "2"})
self.tests.collection3(mapping) # type: ignore
self.assertIn("iter", mapping.log)
self.assertIn("getitem", mapping.log)
def test_the_mapping_is_let_go_of_after_the_call(self) -> None:
entries = {"1": "2"}
before = sys.getrefcount(entries)
self.tests.collection3(entries)
self.assertEqual(sys.getrefcount(entries), before)
def assert_an_entry_is_unraisable(self, entries: dict[Any, Any]) -> None:
# WinRT reads each entry through a pair the runtime makes of it, and a
# key or value that fails to convert there is reported against the
# mapping, as an element of a list is against the list.
for method in (
self.tests.collection2,
self.tests.collection3,
self.tests.collection4,
):
with (
self.subTest(method=method),
self.assertRaises(OSError) as ctx,
catch_unraisable() as exceptions,
):
method(entries)
self.assertEqual(
ctx.exception.winerror, PYWINRT_E_UNRAISABLE_PYTHON_EXCEPTION
)
self.assertEqual(len(exceptions), 1)
self.assertEqual(exceptions[0].exc_type, TypeError)
self.assertIs(exceptions[0].object, dict)
def test_a_key_of_the_wrong_type_is_unraisable(self) -> None:
self.assert_an_entry_is_unraisable({1: "2"})
def test_a_value_of_the_wrong_type_is_unraisable(self) -> None:
self.assert_an_entry_is_unraisable({"1": 2})
def test_a_value_of_none_is_unraisable(self) -> None:
self.assert_an_entry_is_unraisable({"1": None})
def test_something_that_is_not_a_mapping_is_refused(self) -> None:
with self.assertRaisesRegex(TypeError, "mapping"):
self.tests.collection3(42) # type: ignore
class TestCollectionFromAHandler(unittest.TestCase):
"""
The same collections, handed to WinRT out of a Python implementation.
A value that leaves a call the other way round is converted by the
callback half of the interpreter rather than by the call half, so this is
the second of the two places a Python object becomes a WinRT collection -
and the only one that reaches the members WinRT uses to change one, since
TestComponent checks each step it takes and fails the call if what it
reads back is not what it asked for.
"""
def setUp(self) -> None:
self.tests = tc.TestRunner.make_tests()
def test_a_handler_hands_back_an_iterable(self) -> None:
handed: list[LoggingList] = []
def handler(items: Iterable[str]) -> tuple[LoggingList, LoggingList]:
handed.append(LoggingList(items))
handed.append(LoggingList(items))
return handed[-2], handed[-1]
self.tests.collection1_call(handler)
self.assertIn("iter", handed[0].log)
def test_a_handler_hands_back_a_vector(self) -> None:
handed: list[LoggingList] = []
def handler(items: MutableSequence[str]) -> tuple[LoggingList, LoggingList]:
handed.append(LoggingList(items))
handed.append(LoggingList(items))
return handed[-2], handed[-1]
self.tests.collection5_call(handler)
# The call is what says the members did the right thing - it checks
# every step and fails if they did not - and the log is which of them
# it took.
log = set(handed[0].log)
self.assertIn("len", log)
self.assertIn("getitem", log)
self.assertIn("iter", log)
self.assertIn("append", log)
self.assertIn("setitem", log)
self.assertIn("delitem", log)
self.assertIn("delslice", log)
def test_a_handler_hands_back_none(self) -> None:
# None is handed back as a null collection, not refused as an error in
# the handler, so the callee is the one to refuse it.
with (
self.assertRaisesRegex(OSError, "return value") as ctx,
catch_unraisable() as exceptions,
):
self.tests.collection5_call(lambda items: (None, items)) # type: ignore[arg-type,return-value]
self.assertEqual(ctx.exception.winerror, E_POINTER)
self.assertEqual(exceptions, [])
def test_a_handler_hands_back_a_vector_view(self) -> None:
handed: list[LoggingList] = []
def handler(items: Sequence[str]) -> tuple[LoggingList, LoggingList]:
handed.append(LoggingList(items))
handed.append(LoggingList(items))
return handed[-2], handed[-1]
self.tests.collection6_call(handler)
log = set(handed[0].log)
self.assertIn("len", log)
self.assertIn("getitem", log)
def test_a_handler_hands_back_a_map(self) -> None:
handed: list[LoggingDict] = []
def handler(
entries: MutableMapping[str, str],
) -> tuple[LoggingDict, LoggingDict]:
values = dict(entries)
handed.append(LoggingDict(values))
handed.append(LoggingDict(values))
return handed[-2], handed[-1]
self.tests.collection3_call(handler)
log = set(handed[0].log)
self.assertIn("len", log)
self.assertIn("getitem", log)
self.assertIn("iter", log)
self.assertIn("setitem", log)
self.assertIn("delitem", log)
self.assertIn("clear", log)
def test_a_handler_hands_back_a_map_view(self) -> None:
handed: list[LoggingDict] = []
def handler(entries: Mapping[str, str]) -> tuple[LoggingDict, LoggingDict]:
values = dict(entries)
handed.append(LoggingDict(values))
handed.append(LoggingDict(values))
return handed[-2], handed[-1]
self.tests.collection4_call(handler)
self.assertIn("getitem", handed[0].log)
def test_a_handler_hands_back_an_iterable_of_pairs(self) -> None:
handed: list[LoggingDict] = []
def handler(
pairs: Iterable[IKeyValuePair[str, str]],
) -> tuple[LoggingDict, LoggingDict]:
values = {pair.key: pair.value for pair in pairs}
handed.append(LoggingDict(values))
handed.append(LoggingDict(values))
return handed[-2], handed[-1]
self.tests.collection2_call(handler)
self.assertIn("iter", handed[0].log)
class TestCollectionElements(unittest.TestCase):
def test_a_list_of_numbers_is_an_iterable(self) -> None:
# Every element goes through the conversion its own type code names,
# so a collection of something other than strings needs nothing of its
# own.
expected = [1, 2, 3]
actual: list[int] = []
op = tc.TestRunner.create_async_action_with_progress(10, expected)
# https://github.com/microsoft/pyright/issues/11833
op.progress = lambda sender, value: actual.append(value) # pyright: ignore[reportAttributeAccessIssue, reportUnknownLambdaType, reportUnknownArgumentType]
op.get()
self.assertListEqual(actual, expected)
if __name__ == "__main__":
unittest.main()