import Testing @testable import Ch21Kit @Suite("重入") struct ReentrancyTests { @Test func unsafeWithdrawAllowsOverdraw() async { let account = BankAccount(balance: 100) let successes = await withTaskGroup(of: Bool.self) { group -> Int in group.addTask { await account.withdrawUnsafe(80, delay: .milliseconds(20)) } group.addTask { await account.withdrawUnsafe(80, delay: .milliseconds(20)) } var count = 0 for await success in group where success { count += 1 } return count } #expect(successes == 2) #expect(await account.balance == -60) } @Test func safeWithdrawKeepsBalanceNonNegative() async { let account = BankAccount(balance: 100) let successes = await withTaskGroup(of: Bool.self) { group -> Int in group.addTask { await account.withdrawSafe(80, delay: .milliseconds(20)) } group.addTask { await account.withdrawSafe(80, delay: .milliseconds(20)) } var count = 0 for await success in group where success { count += 1 } return count } #expect(successes == 1) #expect(await account.balance == 20) } @Test func insufficientFundsReturnsFalse() async { let account = BankAccount(balance: 10) #expect(await account.withdrawSafe(20, delay: .milliseconds(1)) == false) #expect(await account.balance == 10) } } @Suite("MainActor") struct MainActorTests { @Test @MainActor func viewModelUpdatesOnMainActor() { let model = ViewModel() #expect(model.title.isEmpty) #expect(model.loadTitle() == "loaded") #expect(model.updates == 1) } }