|
| 1 | +// RUN: %empty-directory(%t) |
| 2 | +// RUN: %target-build-swift -Xfrontend -disable-availability-checking %s -o %t/a.out |
| 3 | +// RUN: %target-codesign %t/a.out |
| 4 | +// RUN: %target-run %t/a.out |
| 5 | + |
| 6 | +// REQUIRES: executable_test |
| 7 | +// REQUIRES: concurrency |
| 8 | +// REQUIRES: concurrency_runtime |
| 9 | +// UNSUPPORTED: back_deployment_runtime |
| 10 | +// UNSUPPORTED: back_deploy_concurrency |
| 11 | +// UNSUPPORTED: use_os_stdlib |
| 12 | +// UNSUPPORTED: freestanding |
| 13 | + |
| 14 | +import StdlibUnittest |
| 15 | +@_spi(MainActorUtilities) import _Concurrency |
| 16 | + |
| 17 | +func doStuffAsync() async { |
| 18 | + await Task.sleep(500) |
| 19 | +} |
| 20 | + |
| 21 | +let tests = TestSuite("StartOnMainActor") |
| 22 | + |
| 23 | +tests.test("startOnMainActor") { |
| 24 | + // "global" variables for this test |
| 25 | + struct Globals { |
| 26 | + @MainActor |
| 27 | + static var ran = false |
| 28 | + } |
| 29 | + |
| 30 | + @MainActor |
| 31 | + func run() async { |
| 32 | + Globals.ran = true |
| 33 | + await doStuffAsync() |
| 34 | + } |
| 35 | + |
| 36 | + // enqueue item on the MainActor |
| 37 | + let t1 = Task { @MainActor in |
| 38 | + await Task.sleep(1000) |
| 39 | + } |
| 40 | + |
| 41 | + expectFalse(Globals.ran) |
| 42 | + |
| 43 | + // Run something with side-effects on the main actor |
| 44 | + let t2 = Task.startOnMainActor { |
| 45 | + return await run() |
| 46 | + } |
| 47 | + |
| 48 | + expectTrue(Globals.ran) |
| 49 | + await t1.value |
| 50 | + await t2.value |
| 51 | +} |
| 52 | + |
| 53 | +tests.test("throwing startOnMainActor") { |
| 54 | + // "global" variables for this test |
| 55 | + struct Globals { |
| 56 | + @MainActor |
| 57 | + static var ran = false |
| 58 | + } |
| 59 | + |
| 60 | + struct StringError: Error { |
| 61 | + let message: String |
| 62 | + } |
| 63 | + |
| 64 | + @MainActor |
| 65 | + func run() async throws { |
| 66 | + Globals.ran = true |
| 67 | + await doStuffAsync() |
| 68 | + throw StringError(message: "kablamo!") |
| 69 | + } |
| 70 | + |
| 71 | + // enqueue item on the MainActor |
| 72 | + let t1 = Task { @MainActor in |
| 73 | + await Task.sleep(1000) |
| 74 | + } |
| 75 | + |
| 76 | + expectFalse(Globals.ran) |
| 77 | + |
| 78 | + // Run something with side-effects on the main actor |
| 79 | + let t2 = Task.startOnMainActor { |
| 80 | + return try await run() |
| 81 | + } |
| 82 | + |
| 83 | + expectTrue(Globals.ran) |
| 84 | + await t1.value |
| 85 | + expectNil(try? await t2.value) |
| 86 | +} |
| 87 | + |
| 88 | +await runAllTestsAsync() |
0 commit comments