Skip to content

Commit 13b17b6

Browse files
committed
fix flaky test
motivation: LockTests.testReadWriteFileLock can race read and write threads causing unstable results and failing tests changes: * write zero value to file before starting and reading or writing operations
1 parent fc5b8a5 commit 13b17b6

File tree

1 file changed

+8
-15
lines changed

1 file changed

+8
-15
lines changed

Tests/TSCBasicTests/LockTests.swift

Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -61,34 +61,27 @@ class LockTests: XCTestCase {
6161
}
6262

6363
func testReadWriteFileLock() throws {
64-
try XCTSkipIf(true, "fails spuriously if reader thread beats first writer rdar://78461378")
6564
try withTemporaryDirectory { tempDir in
6665
let fileA = tempDir.appending(component: "fileA")
6766
let fileB = tempDir.appending(component: "fileB")
6867

68+
// write initial value, since reader may start before writers and files would not exist
69+
try localFileSystem.writeFileContents(fileA, bytes: "0")
70+
try localFileSystem.writeFileContents(fileB, bytes: "0")
71+
6972
let writerThreads = (0..<100).map { _ in
7073
return Thread {
7174
let lock = FileLock(name: "foo", cachePath: tempDir)
7275
try! lock.withLock(type: .exclusive) {
73-
// Get thr current contents of the file if any.
74-
let valueA: Int
75-
if localFileSystem.exists(fileA) {
76-
valueA = Int(try localFileSystem.readFileContents(fileA).description) ?? 0
77-
} else {
78-
valueA = 0
79-
}
76+
// Get the current contents of the file if any.
77+
let valueA = Int(try localFileSystem.readFileContents(fileA).description)!
8078
// Sum and write back to file.
8179
try localFileSystem.writeFileContents(fileA, bytes: ByteString(encodingAsUTF8: String(valueA + 1)))
8280

8381
Thread.yield()
8482

85-
// Get thr current contents of the file if any.
86-
let valueB: Int
87-
if localFileSystem.exists(fileB) {
88-
valueB = Int(try localFileSystem.readFileContents(fileB).description) ?? 0
89-
} else {
90-
valueB = 0
91-
}
83+
// Get the current contents of the file if any.
84+
let valueB = Int(try localFileSystem.readFileContents(fileB).description)!
9285
// Sum and write back to file.
9386
try localFileSystem.writeFileContents(fileB, bytes: ByteString(encodingAsUTF8: String(valueB + 1)))
9487
}

0 commit comments

Comments
 (0)