Skip to content

Commit 42e2ad3

Browse files
Add LockIsolated test cases (#12)
* Add LockIsolated test cases * wip * wip --------- Co-authored-by: Stephen Celis <[email protected]>
1 parent f7e9d4a commit 42e2ad3

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
#if !os(WASI) && canImport(Dispatch)
2+
import ConcurrencyExtras
3+
import Dispatch
4+
import XCTest
5+
6+
final class LockIsolatedTests: XCTestCase {
7+
func testLockThreadSafety() {
8+
let value = LockIsolated(0)
9+
let iterations = 100_000
10+
let group = DispatchGroup()
11+
12+
for _ in 1...iterations {
13+
group.enter()
14+
DispatchQueue.global().async {
15+
value.withValue { value in
16+
value += 1
17+
}
18+
group.leave()
19+
}
20+
}
21+
22+
for _ in 1...iterations {
23+
group.enter()
24+
DispatchQueue.global().async {
25+
_ = value.value
26+
group.leave()
27+
}
28+
}
29+
30+
group.wait()
31+
XCTAssertEqual(value.value, iterations)
32+
}
33+
34+
func testInitializationWithValue() {
35+
let value = 10
36+
let lockIsolated = LockIsolated(value)
37+
XCTAssertEqual(lockIsolated.value, value)
38+
}
39+
40+
func testInitializationWithClosure() {
41+
let lockIsolated = LockIsolated<Int>(
42+
1 + 1
43+
)
44+
XCTAssertEqual(lockIsolated.value, 2)
45+
}
46+
47+
func testDynamicMemberLookup() {
48+
struct TestValue: Sendable {
49+
var x = 0
50+
var y = 10
51+
}
52+
53+
let testValue = TestValue()
54+
let lockIsolated = LockIsolated(testValue)
55+
56+
XCTAssertEqual(lockIsolated.x, testValue.x)
57+
XCTAssertEqual(lockIsolated.y, testValue.y)
58+
}
59+
60+
func testWithValue() {
61+
let initialValue = 0
62+
let lockIsolated = LockIsolated(initialValue)
63+
let result = lockIsolated.withValue { value in
64+
value += 1
65+
return String(value)
66+
}
67+
68+
XCTAssertEqual(result, "1")
69+
XCTAssertEqual(lockIsolated.value, 1)
70+
}
71+
72+
func testSetValue() {
73+
let initialValue = 0
74+
let lockIsolated = LockIsolated(initialValue)
75+
lockIsolated.setValue(2)
76+
XCTAssertEqual(lockIsolated.value, 2)
77+
}
78+
}
79+
#endif
80+

0 commit comments

Comments
 (0)