Repository navigation
Expand file tree
/
Copy pathClassTests.swift
More file actions
609 lines (518 loc) · 18.5 KB
/
Copy pathClassTests.swift
File metadata and controls
609 lines (518 loc) · 18.5 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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
//
// Created by Anton Spivak
//
import Python
import Synchronization
import Testing
// MARK: - CounterModule
@PythonExportedModule("counter_base")
private enum CounterModule {}
// MARK: - LabeledCounterModule
@PythonExportedModule("counter_child")
private enum LabeledCounterModule {
@PythonFunction
static func echo(_ value: Counter) -> Counter {
value
}
@PythonFunction
static func echoList(_ values: [Counter]) -> [Counter] {
values
}
}
// MARK: - CounterLifetime
private enum CounterLifetime {
static let instanceCount: Mutex = .init(0)
}
// MARK: - Counter
@PythonExportedClass("Counter", module: CounterModule.self)
private class Counter {
private var secret = 0
@PythonProperty
var value: Int
@PythonProperty("readOnlyValue", isReadOnly: true)
var `default`: Int
@PythonProperty
var callback: Python::Reference?
@PythonProperty
var next: Counter?
@PythonProperty
private var cached: Counter?
@PythonInit
init(_ value: Int = 0, linkToSelf: Bool = false, in context: Python::Context) throws {
CounterLifetime.instanceCount.withLock { $0 += 1 }
try self.$value(value)
try self.$default(7)
if linkToSelf {
try self.$next(self)
// The construction scope keeps the self-linked wrapper alive during collection.
_ = try context.import(module: "gc")(methodNamed: "collect")()
}
guard value >= 0 else {
throw Python::Failure(.valueError, message: "negative")
}
}
deinit {
CounterLifetime.instanceCount.withLock { $0 -= 1 }
}
@PythonFunction
func increment(_ amount: Int = 1) throws -> Int {
secret += 1
try self.$value { $0 + amount }
return try self.value
}
@PythonFunction
func myself() -> Counter {
self
}
@PythonFunction
func describe() -> String {
"base"
}
@PythonFunction
func invoke(_ context: Python::Context) throws -> Int {
guard let reference = try self.callback else {
return -1
}
let function = try context.object(reference)
return try function().decode()
}
@PythonFunction
func cache(_ value: Counter) throws {
try self.$cached(value)
}
@PythonFunction
func recall() throws -> Counter? {
try self.cached
}
}
extension Counter {
@PythonFunction
func extended(_ amount: Int) throws -> Int {
try value + amount
}
@PythonProperty
var doubled: Int {
get {
secret * 2
}
set {
secret = newValue / 2
}
}
}
// MARK: - LabeledCounter
@PythonExportedClass("Labeled", module: LabeledCounterModule.self)
private final class LabeledCounter: Counter {
@PythonProperty
let label: String
@PythonInit
init(_ value: Int, label: String = "label", in context: Python::Context) throws {
self.label = label
try super.init(value, in: context)
}
override func describe() -> String {
"child:" + label
}
}
// MARK: - ExistingCounter
@PythonExportedClass(module: LabeledCounterModule.self)
private final class ExistingCounter: Counter {}
// MARK: - ExistingInstance
@PythonExportedClass(module: LabeledCounterModule.self)
private final class ExistingInstance: Sendable {
@PythonProperty
var note: String?
@PythonProperty
let number = 42
@PythonFunction
func asynchronous(_ context: Python::Context) async -> Int {
await Task.yield()
return number + (context.scope as? Int ?? 0)
}
}
@Test
func exportedClassHelpAndConstructorSignatures() async throws {
try await evaluateInFreshSession(
"""
from counter_base import Counter
from counter_child import Labeled, ExistingCounter, ExistingInstance
from contextlib import redirect_stdout
from inspect import Parameter, Signature, getmro, signature
from io import StringIO
parameters = signature(Counter).parameters
assert list(parameters) == ['value', 'linkToSelf']
assert parameters['value'].annotation == 'int'
assert parameters['value'].default is not Parameter.empty
assert signature(Counter).return_annotation is Signature.empty
parameters = signature(Labeled).parameters
assert list(parameters) == ['value', 'label']
assert parameters['value'].default is Parameter.empty
assert parameters['label'].default is not Parameter.empty
assert getmro(Counter) == (Counter, object)
assert getmro(Labeled) == (Labeled, Counter, object)
for cls in (ExistingCounter, ExistingInstance):
assert all(parameter.kind in (Parameter.VAR_POSITIONAL, Parameter.VAR_KEYWORD)
for parameter in signature(cls).parameters.values())
try:
cls(1)
except TypeError:
pass
else:
raise AssertionError('A returned-only class accepted construction')
for cls in (Counter, Labeled, ExistingCounter, ExistingInstance):
assert cls.__new__.__module__ == cls.__module__
assert cls.__new__.__qualname__ == f'{cls.__name__}.__new__'
with redirect_stdout(StringIO()) as output:
help(cls)
text = output.getvalue()
assert '_swift_python_runtime' not in text
assert '_SwiftObject' not in text
assert 'NativeClasses' not in text and 'initialize(' not in text
""",
modules: [LabeledCounterModule.self],
)
}
@Test
func exportedClassInheritanceAndGarbageCollection() async throws {
let runtime = try await Python::Runtime()
// The base's module is pulled in by the exported Swift inheritance graph.
let session = try await runtime.session(modules: [LabeledCounterModule.self])
try await withSession(session) { session in
try await checkInheritedClass(in: session)
try await checkRejectedClassOperations(in: session)
try await checkClassLifetimes(in: session)
}
}
private func checkInheritedClass(in session: Python::Session) async throws {
_ = try await session.evaluate("""
from counter_base import Counter
from counter_child import Labeled, echo, echoList, ExistingInstance
import inspect, weakref, gc, typing
x = Labeled(40, label='x')
assert isinstance(x, Counter)
assert x.value == 40 and x.label == 'x'
assert x.increment(2) == 42
assert x.extended(1) == 43
assert x.describe() == 'child:x'
assert x.myself() is x and echo(x) is x
assert echoList([x, x]) == [x, x] and echoList([x])[0] is x
x.doubled = 20
assert x.doubled == 20
x.value = 10
x.__init__(999, label='changed')
assert x.value == 10 and x.label == 'x'
assert x.readOnlyValue == 7
assert not hasattr(x, 'secret')
assert list(inspect.signature(Counter.increment).parameters) == ['self', 'amount']
assert inspect.signature(echo).return_annotation == 'counter_base.Counter'
assert typing.get_type_hints(echo) == {'value': Counter, 'return': Counter}
assert typing.get_type_hints(echoList)['return'] == list[Counter]
assert typing.get_type_hints(Counter.recall)['return'] == Counter | None
assert typing.get_type_hints(Counter.next.fget)['return'] == Counter | None
assert Counter.next.__doc__.startswith('counter_base.Counter | None')
linked = Counter(12, True)
assert linked.value == 12 and linked.next is linked
dead_linked = weakref.ref(linked)
del linked
gc.collect()
assert dead_linked() is None
""")
}
private func checkRejectedClassOperations(in session: Python::Session) async throws {
_ = try await session.evaluate("""
rejected = [
(AttributeError, lambda: setattr(x, 'readOnlyValue', 8)),
(AttributeError, lambda: setattr(x, 'other', 1)),
(TypeError, lambda: setattr(Counter, 'extra', 1)),
(TypeError, lambda: ExistingInstance()),
(ValueError, lambda: Counter(-1, True)),
(TypeError, lambda: Counter('bad')),
(TypeError, lambda: x.increment(None)),
(TypeError, lambda: echoList([object()])),
]
for expected_error, action in rejected:
try:
action()
except expected_error:
pass
else:
raise AssertionError(f"Expected {expected_error.__name__}")
try:
class PythonChild(Counter):
pass
except TypeError:
pass
else:
raise AssertionError("Expected Python subclasses of Counter to be rejected")
""")
}
private func checkClassLifetimes(in session: Python::Session) async throws {
_ = try await session.evaluate("""
assert x.callback is None and x.invoke() == -1
assert x.next is None and x.recall() is None
x.next = x
x.cache(x)
x.callback = lambda captured=x: captured.value + 1
assert x.next is x and x.recall() is x
assert not hasattr(x, 'cached')
assert x.invoke() == 11
dead = weakref.ref(x)
try:
x.next = object()
except TypeError:
assert x.next is x
else:
raise AssertionError("Expected a Counter")
""")
try await checkManagedPythonCounter(in: session)
_ = try await session.evaluate("gc.collect(); assert dead() is None")
#expect(CounterLifetime.instanceCount.withLock { $0 } == 0)
try await checkManagedSwiftCounter(in: session)
_ = try await session.evaluate("gc.collect()")
#expect(CounterLifetime.instanceCount.withLock { $0 } == 0)
}
private func checkManagedPythonCounter(in session: Python::Session) async throws {
let managed = try await session.enqueue { context in
try Python::Managed(context.get("x", as: Counter.self))
}
_ = try await session.evaluate("del x; gc.collect(); assert dead() is not None")
let value = try await managed { counter in
#expect(try counter.next === counter)
try counter.$next(nil)
#expect(try counter.next == nil)
try counter.$next(counter)
#expect(throws: CancellationError.self) {
try counter.$value { _ in throw CancellationError() }
}
#expect(try counter.value == 10)
return try counter.increment(2)
}
#expect(value == 12)
}
private func checkManagedSwiftCounter(in session: Python::Session) async throws {
let managed = try await session.enqueue { context in
let counter = try Counter(40, linkToSelf: true, in: context)
#expect(try counter.value == 40)
#expect(try counter.next === counter)
return try Python::Managed(counter)
}
let value = try await managed { counter in
#expect(try counter.next === counter)
return try counter.increment(2)
}
#expect(value == 42)
}
@Test
func classIdentityAndSessionGenerations() async throws {
let runtime = try await Python::Runtime()
let session = try await runtime.session(modules: [LabeledCounterModule.self])
let other = try await runtime.session(modules: [LabeledCounterModule.self])
defer {
await session.close()
await other.close()
}
let peer = ExistingInstance()
try await session.set(peer, forKey: "peer")
let decoded = try await session.get("peer", as: ExistingInstance.self)
#expect(decoded === peer)
_ = try await session.evaluate(
"import weakref; dead_peer = weakref.ref(peer); peer.note = 'old'",
)
try await session.remove("peer")
_ = try await session.evaluate("import gc; gc.collect(); assert dead_peer() is None")
// The Swift instance survives collection of the original Python wrapper.
try await session.set(peer, forKey: "peer")
_ = try await session.evaluate("assert peer.note is None and peer.number == 42")
await #expect(throws: (any Swift::Error).self) { try await other.set(peer, forKey: "peer") }
let managed = try await session.enqueue { _ in try Python::Managed(peer) }
_ = try await session.evaluate("assert await peer.asynchronous() == 43", scope: 1)
_ = try await session.evaluate("assert await peer.asynchronous() == 42")
try await session.set(42, forKey: "value")
let value: Int = try await managed { peer in
await Task.yield()
#expect(peer.number == 42)
return try await session.get("value")
}
#expect(value == 42)
try await session.reset()
await #expect(throws: Python::Failure.self) { try await session.set(peer, forKey: "peer") }
await #expect(throws: Python::Failure.self) { try await managed { $0.number } }
}
// MARK: - ReferenceModule
@PythonExportedModule("reference_fixture")
private enum ReferenceModule {}
// MARK: - ReferencePeer
@PythonExportedClass("Peer", module: ReferenceModule.self)
private final class ReferencePeer {
@PythonProperty
let value: Int
private var peer: ReferencePeer?
private var reference: Python::Reference?
@PythonInit
init(_ value: Int = 0) {
self.value = value
}
@PythonFunction
func retain(_ peer: ReferencePeer) {
self.peer = peer
}
@PythonFunction
func recall() -> ReferencePeer? {
peer
}
@PythonFunction
func remember(_ reference: Python::Reference) {
self.reference = reference
}
@PythonFunction
func remembered() -> Python::Reference? {
reference
}
}
@Test(.timeLimit(.minutes(3)))
func failedEvaluationKeepsPythonAndSwiftObjects() async throws {
let python = try await Python::Runtime()
let session = try await python.session(modules: [ReferenceModule.self])
defer { await session.close() }
let prepared = try await session.evaluate("""
import sys
from reference_fixture import Peer
holder = Peer()
child = Peer(17)
holder.retain(child)
values = [{"nested": [1]}]
holder.remember(values)
alias = values
nested = values[0]["nested"]
""")
#expect(prepared.end == .finished)
let error = try await #require(throws: Python::Failure.self) {
try await session.evaluate(
"""
del child
replacement = holder.recall()
assert replacement.value == 17
nested.extend([2, 3])
values.append(4)
holder.remember(values)
print("diagnostic")
raise ValueError("reference fixture")
""",
filename: "r2",
)
}
#expect(error.traceback?.contains("reference fixture") == true)
#expect(error.traceback?.contains("r2") == true)
#expect(error.output?.stdout == "diagnostic\n")
let retained = try await session.evaluate("""
assert 'child' not in globals()
assert holder.recall() is replacement and replacement.value == 17
assert alias is values and nested is values[0]["nested"]
assert values == [{"nested": [1, 2, 3]}, 4]
assert holder.remembered() is values
""")
#expect(retained.end == .finished)
}
// MARK: - PublicationError
private enum PublicationError: Swift::Error, Equatable {
case failed
}
@Test(.timeLimit(.minutes(3)))
func failedPublicationKeepsAnotherInterpreterAlive() async throws {
let runtime = try await Python::Runtime()
let session = try await runtime.session()
let other = try await runtime.session()
defer {
await session.close()
await other.close()
}
try await session.initialize()
await #expect(throws: PublicationError.failed) {
try await session.evaluate(
"""
import threading
speculative_thread = threading.Thread()
""",
committing: { _ in
// Publication can initialize another interpreter without changing this session.
try await other.initialize()
throw PublicationError.failed
},
)
}
let globals = try await session.evaluate("'speculative_thread' in globals()")
#expect(globals.output.stdout == "True\n")
await session.close()
#expect(try await other.evaluate("6 * 7").output.stdout == "42\n")
}
@Test(.timeLimit(.minutes(3)))
func evaluationWaitsForHostPublication() async throws {
let python = try await Python::Runtime()
let session = try await python.session(.source("values = [1]"))
defer { await session.close() }
await #expect(throws: PublicationError.failed) {
try await session.evaluate(
"values.append(2)",
committing: { seal in
try seal.seal()
throw PublicationError.failed
},
)
}
#expect(try await cancelDuringPublication(in: session, afterSealing: false).end == .stopped)
try await checkDeadlineDuringPublication(in: session)
#expect(try await session.evaluate("assert values == [1, 2, 3, 5]").end == .finished)
let committed = try await cancelDuringPublication(in: session, afterSealing: true)
#expect(committed.end == .finished)
#expect(committed.output.stdout == "ready\n")
#expect(try await session.evaluate("assert values == [1, 2, 3, 5, 4]").end == .finished)
}
private func checkDeadlineDuringPublication(in session: Python::Session) async throws {
let entered = AsyncStream<Void>.makeStream(bufferingPolicy: .bufferingNewest(1))
let cancelledPublication = Mutex(false)
let expired = try await runUntilInterrupted(whenReady: entered, delay: .milliseconds(500)) {
try await session.evaluate(
"values.append(5)",
committing: { seal in
entered.continuation.yield(())
defer { cancelledPublication.withLock { $0 = Task.isCancelled } }
try await Task.sleep(for: .seconds(1))
try seal.seal()
},
)
}
#expect(cancelledPublication.withLock { $0 })
#expect(expired.end == .stopped)
}
private func cancelDuringPublication(
in session: Python::Session,
afterSealing: Bool,
) async throws -> Python::Execution {
let (entered, signal) = AsyncStream<Void>.makeStream()
let (resume, gate) = AsyncStream<Void>.makeStream()
defer {
signal.finish()
gate.finish()
}
let source = afterSealing ? "values.append(4); print('ready')" : "values.append(3)"
let evaluation = Task {
try await session.evaluate(
source,
committing: { seal in
if afterSealing {
try seal.seal()
}
signal.yield(())
_ = await nextSignal(from: resume)
if !afterSealing {
try seal.seal()
}
},
)
}
defer { evaluation.cancel() }
_ = await nextSignal(from: entered)
evaluation.cancel()
gate.yield(())
return try await evaluation.value
}