From 79351683797acd60f708668f0cd5d2c12cf1307b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gwendal=20Roue=CC=81?= Date: Sun, 15 Mar 2020 16:44:43 +0100 Subject: [PATCH] ValueObservation test refactoring WIP --- .../ValueObservationCountTests.swift | 51 +++++++++++-------- 1 file changed, 30 insertions(+), 21 deletions(-) diff --git a/Tests/GRDBTests/ValueObservationCountTests.swift b/Tests/GRDBTests/ValueObservationCountTests.swift index a625aa5c2..48cc1701e 100644 --- a/Tests/GRDBTests/ValueObservationCountTests.swift +++ b/Tests/GRDBTests/ValueObservationCountTests.swift @@ -12,25 +12,15 @@ import XCTest class ValueObservationCountTests: GRDBTestCase { func testCount() throws { - let dbQueue = try makeDatabaseQueue() - try dbQueue.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } - - var counts: [Int] = [] - let notificationExpectation = expectation(description: "notification") - notificationExpectation.assertForOverFulfill = true - notificationExpectation.expectedFulfillmentCount = 5 - - struct T: TableRecord { } - let observation = T.all().observationForCount() - let observer = observation.start( - in: dbQueue, - onError: { error in XCTFail("Unexpected error: \(error)") }, - onChange: { count in - counts.append(count) - notificationExpectation.fulfill() - }) - try withExtendedLifetime(observer) { - try dbQueue.inDatabase { db in + func test(writer: DatabaseWriter, scheduling: ValueObservationScheduling) throws { + try writer.write { try $0.execute(sql: "CREATE TABLE t(id INTEGER PRIMARY KEY AUTOINCREMENT)") } + + struct T: TableRecord { } + var observation = T.all().observationForCount() + observation.scheduling = scheduling + let recorder = observation.record(in: writer) + + try writer.writeWithoutTransaction { db in try db.execute(sql: "INSERT INTO t DEFAULT VALUES") // +1 try db.execute(sql: "UPDATE t SET id = id") // = try db.execute(sql: "INSERT INTO t DEFAULT VALUES") // +1 @@ -43,8 +33,27 @@ class ValueObservationCountTests: GRDBTestCase { try db.execute(sql: "DELETE FROM t WHERE id = 2") // -1 } - waitForExpectations(timeout: 1, handler: nil) - XCTAssertEqual(counts, [0, 1, 2, 3, 2]) + // We don't expect more than five values: [0, 1, 2, 3, 2] + let expectedValues = [0, 1, 2, 3, 2] + let values = try wait(for: recorder.prefix(expectedValues.count + 1).inverted, timeout: 0.5) + let context = "\(type(of: writer)), \(scheduling)" + XCTAssert(!values.isEmpty, context) + for count in 1...max(expectedValues.count, values.count) where count <= values.count { + XCTAssertEqual( + expectedValues.suffix(count), + values.suffix(count), + context) + } + } + let schedulings: [ValueObservationScheduling] = [ + .mainQueue, + .async(onQueue: .main), + .unsafe + ] + for scheduling in schedulings { + try test(writer: DatabaseQueue(), scheduling: scheduling) + try test(writer: makeDatabaseQueue(), scheduling: scheduling) + try test(writer: makeDatabasePool(), scheduling: scheduling) } }