|
| 1 | +import XCTest |
| 2 | +@testable import AsyncObject |
| 3 | + |
| 4 | +class AsyncMutexTests: XCTestCase { |
| 5 | + |
| 6 | + func checkWait( |
| 7 | + for mutex: AsyncMutex, |
| 8 | + durationInSeconds seconds: Int = 0 |
| 9 | + ) async throws { |
| 10 | + Task.detached { |
| 11 | + try await Task.sleep(nanoseconds: UInt64(5E9)) |
| 12 | + await mutex.release() |
| 13 | + } |
| 14 | + await checkExecInterval( |
| 15 | + for: { await mutex.wait() }, |
| 16 | + durationInSeconds: seconds |
| 17 | + ) |
| 18 | + } |
| 19 | + |
| 20 | + func testMutexWait() async throws { |
| 21 | + let mutex = AsyncMutex() |
| 22 | + try await checkWait(for: mutex, durationInSeconds: 5) |
| 23 | + } |
| 24 | + |
| 25 | + func testMutexLockAndWait() async throws { |
| 26 | + let mutex = AsyncMutex(lockedInitially: false) |
| 27 | + await mutex.lock() |
| 28 | + try await checkWait(for: mutex, durationInSeconds: 5) |
| 29 | + } |
| 30 | + |
| 31 | + func testReleasedMutexWait() async throws { |
| 32 | + let mutex = AsyncMutex(lockedInitially: false) |
| 33 | + try await checkWait(for: mutex) |
| 34 | + } |
| 35 | + |
| 36 | + func testMutexWaitWithTimeout() async throws { |
| 37 | + let mutex = AsyncMutex() |
| 38 | + var result: TaskTimeoutResult = .success |
| 39 | + await checkExecInterval( |
| 40 | + for: { |
| 41 | + result = await mutex.wait(forNanoseconds: UInt64(4E9)) |
| 42 | + }, |
| 43 | + durationInSeconds: 4 |
| 44 | + ) |
| 45 | + XCTAssertEqual(result, .timedOut) |
| 46 | + } |
| 47 | + |
| 48 | + func testMutexWaitSuccessWithoutTimeout() async throws { |
| 49 | + let mutex = AsyncMutex() |
| 50 | + var result: TaskTimeoutResult = .timedOut |
| 51 | + Task.detached { |
| 52 | + try await Task.sleep(nanoseconds: UInt64(5E9)) |
| 53 | + await mutex.release() |
| 54 | + } |
| 55 | + await checkExecInterval( |
| 56 | + for: { |
| 57 | + result = await mutex.wait(forNanoseconds: UInt64(10E9)) |
| 58 | + }, |
| 59 | + durationInSeconds: 5 |
| 60 | + ) |
| 61 | + XCTAssertEqual(result, .success) |
| 62 | + } |
| 63 | + |
| 64 | + func testReleasedMutexWaitSuccessWithoutTimeout() async throws { |
| 65 | + let mutex = AsyncMutex(lockedInitially: false) |
| 66 | + var result: TaskTimeoutResult = .timedOut |
| 67 | + await checkExecInterval( |
| 68 | + for: { |
| 69 | + result = await mutex.wait(forNanoseconds: UInt64(10E9)) |
| 70 | + }, |
| 71 | + durationInSeconds: 0 |
| 72 | + ) |
| 73 | + XCTAssertEqual(result, .success) |
| 74 | + } |
| 75 | +} |
0 commit comments