Skip to content

Commit ec3ff3d

Browse files
committed
Add a unit test for a captured codable object
1 parent d17f3a7 commit ec3ff3d

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

Diff for: Tests/TestingTests/ExitTestTests.swift

+43
Original file line numberDiff line numberDiff line change
@@ -410,6 +410,49 @@ private import _TestingInternals
410410
}
411411
}
412412
}
413+
414+
class CapturableBaseClass: @unchecked Sendable, Codable {
415+
init() {}
416+
417+
required init(from decoder: any Decoder) throws {}
418+
func encode(to encoder: any Encoder) throws {}
419+
}
420+
421+
final class CapturableDerivedClass: CapturableBaseClass, @unchecked Sendable {
422+
let x: Int
423+
424+
init(x: Int) {
425+
self.x = x
426+
super.init()
427+
}
428+
429+
required init(from decoder: any Decoder) throws {
430+
let container = try decoder.singleValueContainer()
431+
self.x = try container.decode(Int.self)
432+
super.init()
433+
}
434+
435+
override func encode(to encoder: any Encoder) throws {
436+
var container = encoder.singleValueContainer()
437+
try container.encode(x)
438+
}
439+
}
440+
441+
@Test("Capturing an instance of a subclass")
442+
func captureSubclass() async {
443+
let instance = CapturableDerivedClass(x: 123)
444+
await #expect(exitsWith: .success) { [instance = instance as CapturableBaseClass] in
445+
#expect((instance as AnyObject) is CapturableBaseClass)
446+
// However, because the static type of `instance` is not Derived, we won't
447+
// be able to cast it to Derived.
448+
#expect(!((instance as AnyObject) is CapturableDerivedClass))
449+
}
450+
await #expect(exitsWith: .success) { [instance = instance as CapturableDerivedClass] in
451+
#expect((instance as AnyObject) is CapturableBaseClass)
452+
#expect((instance as AnyObject) is CapturableDerivedClass)
453+
#expect(instance.x == 123)
454+
}
455+
}
413456
}
414457

415458
// MARK: - Fixtures

0 commit comments

Comments
 (0)