Skip to content

Instantly share code, notes, and snippets.

@southerton81
Created November 5, 2022 18:36
Show Gist options
  • Save southerton81/d3404217b93bac6351222258f4fea212 to your computer and use it in GitHub Desktop.
Save southerton81/d3404217b93bac6351222258f4fea212 to your computer and use it in GitHub Desktop.
import XCTest
import CoreData
@testable import iosApp
class iosAppTests: XCTestCase {
func testCoreDataMergeConflict() {
let expectation = XCTestExpectation(description: "")
expectation.expectedFulfillmentCount = 2
Task {
await CoreDataInventory.instance.perform { (context) in
let newChartState = ChartState(context: context)
newChartState.chartLen = 100
newChartState.seed = 1
}
}
Task {
await CoreDataInventory.instance.perform { (context) in
sleep(1)
self.modifyChartStateSeed(context, 2)
sleep(1) // Wait 1 seconds before save for the next background task to read the same version of entity
}
expectation.fulfill()
}
Task {
await CoreDataInventory.instance.perform { (context) in
sleep(1)
self.modifyChartStateSeed(context, 3)
sleep(2)
}
expectation.fulfill()
}
wait(for: [expectation], timeout: 8)
}
private func modifyChartStateSeed(_ context: NSManagedObjectContext, _ seed: Int32) {
let fetchRequest: NSFetchRequest<ChartState> = ChartState.fetchRequest()
fetchRequest.predicate = NSPredicate(format: "chartLen = %i", 100)
let chartStateEntity = try? context.fetch(fetchRequest).first
chartStateEntity?.seed = seed
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment