Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add LockIsolated test cases #12

Merged
merged 4 commits into from
Jun 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions Tests/ConcurrencyExtrasTests/LockIsolatedTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#if !os(WASI) && canImport(Dispatch)
import ConcurrencyExtras
import Dispatch
import XCTest

final class LockIsolatedTests: XCTestCase {
func testLockThreadSafety() {
let value = LockIsolated(0)
let iterations = 100_000
let group = DispatchGroup()

for _ in 1...iterations {
group.enter()
DispatchQueue.global().async {
value.withValue { value in
value += 1
}
group.leave()
}
}

for _ in 1...iterations {
group.enter()
DispatchQueue.global().async {
_ = value.value
group.leave()
}
}

group.wait()
XCTAssertEqual(value.value, iterations)
}

func testInitializationWithValue() {
let value = 10
let lockIsolated = LockIsolated(value)
XCTAssertEqual(lockIsolated.value, value)
}

func testInitializationWithClosure() {
let lockIsolated = LockIsolated<Int>(
1 + 1
)
XCTAssertEqual(lockIsolated.value, 2)
}

func testDynamicMemberLookup() {
struct TestValue: Sendable {
var x = 0
var y = 10
}

let testValue = TestValue()
let lockIsolated = LockIsolated(testValue)

XCTAssertEqual(lockIsolated.x, testValue.x)
XCTAssertEqual(lockIsolated.y, testValue.y)
}

func testWithValue() {
let initialValue = 0
let lockIsolated = LockIsolated(initialValue)
let result = lockIsolated.withValue { value in
value += 1
return String(value)
}

XCTAssertEqual(result, "1")
XCTAssertEqual(lockIsolated.value, 1)
}

func testSetValue() {
let initialValue = 0
let lockIsolated = LockIsolated(initialValue)
lockIsolated.setValue(2)
XCTAssertEqual(lockIsolated.value, 2)
}
}
#endif

Loading