FetchedRecordsController tests WIP

This commit is contained in:
Gwendal Roué committed 2016-04-30 14:50:10 +02:00
1 parent e9e2d0bf10
commit 234e1e6810
7 files changed
+696 -6

No files matched your search

+61
View File
@@ -592,6 +592,9 @@
56AFCAD01CB1ABC800F48B96 /* GRDBTestCase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5623E0901B4AFACC00B20B7F /* GRDBTestCase.swift */; };
56AFCAD21CB1ABC800F48B96 /* GRDBCipher.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56AFCA231CB1A8BB00F48B96 /* GRDBCipher.framework */; };
56AFCAD91CB1AC5C00F48B96 /* EncryptionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567156701CB18050007DC145 /* EncryptionTests.swift */; };
56B15D0B1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; };
56B15D0C1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; };
56B15D0D1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */; };
56B7F42A1BE14A1900E39BBF /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; };
56B7F42F1BE14CD700E39BBF /* CGFloatTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */; };
56B7F4371BE4C11200E39BBF /* DatabaseCoderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56B7F4361BE4C11200E39BBF /* DatabaseCoderTests.swift */; };
@@ -719,6 +722,27 @@
remoteGlobalIDString = 56AFC9EE1CB1A8BB00F48B96;
remoteInfo = GRDBCipheriOS;
};
56B15D041CD4C33A00A24C8B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 03A65E5A1C6BB0F50062603F;
remoteInfo = "SQLite tvOS";
};
56B15D061CD4C33A00A24C8B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = 03A65E631C6BB0F60062603F;
remoteInfo = "SQLiteTests tvOS";
};
56B15D081CD4C33A00A24C8B /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */;
proxyType = 2;
remoteGlobalIDString = A121AC451CA35C79005A31D1;
remoteInfo = "SQLite watchOS";
};
56CA220A1BB414FE009A04C5 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 56CA21FE1BB414FE009A04C5 /* SQLite.xcodeproj */;
@@ -900,6 +924,7 @@
56AFCA231CB1A8BB00F48B96 /* GRDBCipher.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = GRDBCipher.framework; sourceTree = BUILT_PRODUCTS_DIR; };
56AFCA7F1CB1AA9900F48B96 /* GRDBTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
56AFCAD71CB1ABC800F48B96 /* GRDBTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FetchedRecordsControllerTests.swift; sourceTree = "<group>"; };
56B7F4291BE14A1900E39BBF /* CGFloatTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CGFloatTests.swift; sourceTree = "<group>"; };
56B7F4361BE4C11200E39BBF /* DatabaseCoderTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DatabaseCoderTests.swift; sourceTree = "<group>"; };
56B7F4391BEB42D500E39BBF /* Migration.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Migration.swift; sourceTree = "<group>"; };
@@ -1279,6 +1304,7 @@
56A238111B9C74A90082EB20 /* Core */,
56B7F4281BE149F600E39BBF /* CoreGraphics */,
5671566F1CB18039007DC145 /* Encryption */,
56B15CFC1CD4C33A00A24C8B /* FetchedRecordsController */,
56300B5C1C53C38F005A543B /* FetchRequest */,
56F0B98C1B6001C600A2F135 /* Foundation */,
56A238231B9C74A90082EB20 /* Migrations */,
@@ -1443,6 +1469,14 @@
path = Record;
sourceTree = "<group>";
};
56B15CFC1CD4C33A00A24C8B /* FetchedRecordsController */ = {
isa = PBXGroup;
children = (
56B15D0A1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift */,
);
path = FetchedRecordsController;
sourceTree = "<group>";
};
56B7F4281BE149F600E39BBF /* CoreGraphics */ = {
isa = PBXGroup;
children = (
@@ -1501,6 +1535,9 @@
56E667CA1C5A422500D48792 /* SQLiteTests iOS.xctest */,
56CA220F1BB414FE009A04C5 /* SQLite.framework */,
56E667CC1C5A422500D48792 /* SQLiteTests Mac.xctest */,
56B15D051CD4C33A00A24C8B /* SQLite.framework */,
56B15D071CD4C33A00A24C8B /* SQLiteTests tvOS.xctest */,
56B15D091CD4C33A00A24C8B /* SQLite.framework */,
);
name = Products;
sourceTree = "<group>";
@@ -1965,6 +2002,27 @@
remoteRef = 560FC5551CB004AD0014AA8E /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B15D051CD4C33A00A24C8B /* SQLite.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = SQLite.framework;
remoteRef = 56B15D041CD4C33A00A24C8B /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B15D071CD4C33A00A24C8B /* SQLiteTests tvOS.xctest */ = {
isa = PBXReferenceProxy;
fileType = wrapper.cfbundle;
path = "SQLiteTests tvOS.xctest";
remoteRef = 56B15D061CD4C33A00A24C8B /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56B15D091CD4C33A00A24C8B /* SQLite.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
path = SQLite.framework;
remoteRef = 56B15D081CD4C33A00A24C8B /* PBXContainerItemProxy */;
sourceTree = BUILT_PRODUCTS_DIR;
};
56CA220B1BB414FE009A04C5 /* SQLite.framework */ = {
isa = PBXReferenceProxy;
fileType = wrapper.framework;
@@ -2400,6 +2458,7 @@
56AFCA461CB1AA9900F48B96 /* PrimaryKeyMultipleTests.swift in Sources */,
56AFCA471CB1AA9900F48B96 /* MetalRowTests.swift in Sources */,
56AFCA491CB1AA9900F48B96 /* StatementArgumentsTests.swift in Sources */,
56B15D0C1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */,
56AFCA4A1CB1AA9900F48B96 /* RecordInitializersTests.swift in Sources */,
56AFCA4B1CB1AA9900F48B96 /* MutablePersistableTests.swift in Sources */,
56AFCA4C1CB1AA9900F48B96 /* RowConvertible+FetchRequestTests.swift in Sources */,
@@ -2497,6 +2556,7 @@
56AFCAB51CB1ABC800F48B96 /* ReadOnlyDatabaseTests.swift in Sources */,
56AFCAB61CB1ABC800F48B96 /* DatabaseReaderTests.swift in Sources */,
56AFCAB71CB1ABC800F48B96 /* RowConvertibleTests.swift in Sources */,
56B15D0D1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */,
56AFCAB81CB1ABC800F48B96 /* DatabaseValueConvertibleFetchTests.swift in Sources */,
56AFCAB91CB1ABC800F48B96 /* PrimaryKeyRowIDTests.swift in Sources */,
56AFCABA1CB1ABC800F48B96 /* RecordEditedTests.swift in Sources */,
@@ -2602,6 +2662,7 @@
56A238541B9C74A90082EB20 /* PrimaryKeyMultipleTests.swift in Sources */,
56FDECE31BB32DFD009AD709 /* MetalRowTests.swift in Sources */,
56DE7B121C3D93ED00861EB8 /* StatementArgumentsTests.swift in Sources */,
56B15D0B1CD4C35100A24C8B /* FetchedRecordsControllerTests.swift in Sources */,
56A238681B9C74A90082EB20 /* RecordInitializersTests.swift in Sources */,
563363B01C933FF8000BE133 /* MutablePersistableTests.swift in Sources */,
56300B621C53C42C005A543B /* RowConvertible+FetchRequestTests.swift in Sources */,
@@ -0,0 +1,427 @@
import XCTest
#if SQLITE_HAS_CODEC
import GRDBCipher
#else
import GRDB
#endif
private class ChangesRecorder<Record>: FetchedRecordsControllerDelegate {
var changes: [(record: Record, event: FetchedRecordsEvent)] = []
var recordsBeforeChanges: [Record]!
var recordsOnFirstEvent: [Record]!
var transactionExpectation: XCTestExpectation? {
didSet {
changes = []
recordsBeforeChanges = nil
recordsOnFirstEvent = nil
}
}
func controllerWillChangeRecords<T>(controller: FetchedRecordsController<T>) {
recordsBeforeChanges = controller.fetchedRecords!.map { $0 as! Record }
}
/// The default implementation does nothing.
func controller<T>(controller: FetchedRecordsController<T>, didChangeRecord record: T, withEvent event:FetchedRecordsEvent) {
if recordsOnFirstEvent == nil {
recordsOnFirstEvent = controller.fetchedRecords!.map { $0 as! Record }
}
changes.append((record: record as! Record, event: event))
}
/// The default implementation does nothing.
func controllerDidChangeRecords<T>(controller: FetchedRecordsController<T>) {
if let transactionExpectation = transactionExpectation {
transactionExpectation.fulfill()
}
}
}
private class Person : Record {
var id: Int64?
let name: String
let bookCount: Int?
init(name: String) {
self.id = nil
self.name = name
self.bookCount = nil
super.init()
}
required init(_ row: Row) {
id = row.value(named: "id")
name = row.value(named: "name")
bookCount = row.value(named: "bookCount")
super.init(row)
}
override class func databaseTableName() -> String {
return "persons"
}
override var persistentDictionary: [String : DatabaseValueConvertible?] {
return ["id": id, "name": name]
}
override func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
id = rowID
}
}
class FetchedRecordsControllerTests: GRDBTestCase {
override func setUpDatabase(dbWriter: DatabaseWriter) throws {
try dbWriter.write { db in
try db.execute(
"CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT" +
")")
try db.execute(
"CREATE TABLE books (" +
"id INTEGER PRIMARY KEY, " +
"ownerId INTEGER NOT NULL REFERENCES persons(id) ON DELETE CASCADE ON UPDATE CASCADE," +
"title TEXT" +
")")
try db.execute(
"CREATE TABLE flowers (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT" +
")")
}
}
func testRecordsAreNotLoadedUntilPerformFetch() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
let arthur = Person(name: "Arthur")
try dbQueue.inDatabase { db in
try arthur.insert(db)
}
let request = Person.all()
let controller = FetchedRecordsController<Person>(dbQueue, request: request, compareRecordsByPrimaryKey: true)
XCTAssertTrue(controller.fetchedRecords == nil)
controller.performFetch()
XCTAssertEqual(controller.fetchedRecords!.count, 1)
XCTAssertEqual(controller.fetchedRecords![0].name, "Arthur")
XCTAssertEqual(controller.recordAtIndexPath(NSIndexPath(forRow: 0, inSection: 0)).name, "Arthur")
XCTAssertEqual(controller.indexPathForRecord(arthur), NSIndexPath(forRow: 0, inSection: 0))
}
}
func testDatabaseChangesAreNotReReflectedUntilPerformFetchAndDelegateIsSet() {
// TODO: test that controller.fetchedRecords does not eventually change
// after a database change. The difficulty of this test lies in the
// "eventually" word.
}
func testSimpleInsert() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
let controller = FetchedRecordsController<Person>(dbQueue, request: Person.all(), compareRecordsByPrimaryKey: true)
let recorder = ChangesRecorder<Person>()
controller.delegate = recorder
controller.performFetch()
// First insert
recorder.transactionExpectation = expectationWithDescription("First insert")
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"])
return .Commit
}
waitForExpectationsWithTimeout(1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 0)
XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1)
XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Arthur"])
XCTAssertEqual(recorder.changes.count, 1)
XCTAssertEqual(recorder.changes[0].record.id, 1)
XCTAssertEqual(recorder.changes[0].record.name, "Arthur")
switch recorder.changes[0].event {
case .Insertion(let indexPath):
XCTAssertEqual(indexPath, NSIndexPath(forRow: 0, inSection: 0))
default:
XCTFail()
}
// Second insert
recorder.transactionExpectation = expectationWithDescription("Second insert")
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Barbara"])
return .Commit
}
waitForExpectationsWithTimeout(1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 1)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur"])
XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2)
XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Arthur", "Barbara"])
XCTAssertEqual(recorder.changes.count, 1)
XCTAssertEqual(recorder.changes[0].record.id, 2)
XCTAssertEqual(recorder.changes[0].record.name, "Barbara")
switch recorder.changes[0].event {
case .Insertion(let indexPath):
XCTAssertEqual(indexPath, NSIndexPath(forRow: 1, inSection: 0))
default:
XCTFail()
}
}
}
func testSimpleUpdate() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
let controller = FetchedRecordsController<Person>(dbQueue, request: Person.all(), compareRecordsByPrimaryKey: true)
let recorder = ChangesRecorder<Person>()
controller.delegate = recorder
controller.performFetch()
// Insert
recorder.transactionExpectation = expectationWithDescription("Insert")
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"])
try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Barbara"])
return .Commit
}
waitForExpectationsWithTimeout(1, handler: nil)
// First update
recorder.transactionExpectation = expectationWithDescription("First update")
// No change should be recorded
try dbQueue.inTransaction { db in
try db.execute("UPDATE persons SET name = ? WHERE id = ?", arguments: ["Arthur", 1])
return .Commit
}
// One change should be recorded
try dbQueue.inTransaction { db in
try db.execute("UPDATE persons SET name = ? WHERE id = ?", arguments: ["Craig", 1])
return .Commit
}
waitForExpectationsWithTimeout(1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"])
XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2)
XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Craig", "Barbara"])
XCTAssertEqual(recorder.changes.count, 1)
XCTAssertEqual(recorder.changes[0].record.id, 1)
XCTAssertEqual(recorder.changes[0].record.name, "Craig")
switch recorder.changes[0].event {
case .Update(let indexPath, let changes):
XCTAssertEqual(indexPath, NSIndexPath(forRow: 0, inSection: 0))
XCTAssertEqual(changes, ["name": "Arthur".databaseValue])
default:
XCTFail()
}
// Second update
recorder.transactionExpectation = expectationWithDescription("Second update")
try dbQueue.inTransaction { db in
try db.execute("UPDATE persons SET name = ? WHERE id = ?", arguments: ["Danielle", 2])
return .Commit
}
waitForExpectationsWithTimeout(1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Craig", "Barbara"])
XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2)
XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Craig", "Danielle"])
XCTAssertEqual(recorder.changes.count, 1)
XCTAssertEqual(recorder.changes[0].record.id, 2)
XCTAssertEqual(recorder.changes[0].record.name, "Danielle")
switch recorder.changes[0].event {
case .Update(let indexPath, let changes):
XCTAssertEqual(indexPath, NSIndexPath(forRow: 1, inSection: 0))
XCTAssertEqual(changes, ["name": "Barbara".databaseValue])
default:
XCTFail()
}
}
}
func testSimpleDelete() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
let controller = FetchedRecordsController<Person>(dbQueue, request: Person.all(), compareRecordsByPrimaryKey: true)
let recorder = ChangesRecorder<Person>()
controller.delegate = recorder
controller.performFetch()
// Insert
recorder.transactionExpectation = expectationWithDescription("Insert")
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"])
try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Barbara"])
return .Commit
}
waitForExpectationsWithTimeout(1, handler: nil)
// First delete
recorder.transactionExpectation = expectationWithDescription("First delete")
try dbQueue.inTransaction { db in
try db.execute("DELETE FROM persons WHERE id = ?", arguments: [1])
return .Commit
}
waitForExpectationsWithTimeout(1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"])
XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1)
XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Barbara"])
XCTAssertEqual(recorder.changes.count, 1)
XCTAssertEqual(recorder.changes[0].record.id, 1)
XCTAssertEqual(recorder.changes[0].record.name, "Arthur")
switch recorder.changes[0].event {
case .Deletion(let indexPath):
XCTAssertEqual(indexPath, NSIndexPath(forRow: 0, inSection: 0))
default:
XCTFail()
}
// Second delete
recorder.transactionExpectation = expectationWithDescription("Second delete")
try dbQueue.inTransaction { db in
try db.execute("DELETE FROM persons WHERE id = ?", arguments: [2])
return .Commit
}
waitForExpectationsWithTimeout(1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 1)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Barbara"])
XCTAssertEqual(recorder.recordsOnFirstEvent.count, 0)
XCTAssertEqual(recorder.changes.count, 1)
XCTAssertEqual(recorder.changes[0].record.id, 2)
XCTAssertEqual(recorder.changes[0].record.name, "Barbara")
switch recorder.changes[0].event {
case .Deletion(let indexPath):
XCTAssertEqual(indexPath, NSIndexPath(forRow: 0, inSection: 0))
default:
XCTFail()
}
}
}
func testSimpleMove() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
let controller = FetchedRecordsController<Person>(dbQueue, request: Person.order(SQLColumn("name")), compareRecordsByPrimaryKey: true)
let recorder = ChangesRecorder<Person>()
controller.delegate = recorder
controller.performFetch()
// Insert
recorder.transactionExpectation = expectationWithDescription("Insert")
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"])
try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Barbara"])
return .Commit
}
waitForExpectationsWithTimeout(1, handler: nil)
// Move
recorder.transactionExpectation = expectationWithDescription("First delete")
try dbQueue.inTransaction { db in
try db.execute("UPDATE persons SET name = ? WHERE id = ?", arguments: ["Craig", 1])
return .Commit
}
waitForExpectationsWithTimeout(1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 2)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur", "Barbara"])
XCTAssertEqual(recorder.recordsOnFirstEvent.count, 2)
XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Barbara", "Craig"])
XCTAssertEqual(recorder.changes.count, 1)
XCTAssertEqual(recorder.changes[0].record.id, 1)
XCTAssertEqual(recorder.changes[0].record.name, "Craig")
switch recorder.changes[0].event {
case .Move(let indexPath, let newIndexPath, let changes):
XCTAssertEqual(indexPath, NSIndexPath(forRow: 0, inSection: 0))
XCTAssertEqual(newIndexPath, NSIndexPath(forRow: 1, inSection: 0))
XCTAssertEqual(changes, ["name": "Arthur".databaseValue])
default:
XCTFail()
}
}
}
func testSideTableChange() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
let controller = FetchedRecordsController<Person>(
dbQueue,
sql: "SELECT persons.*, COUNT(books.id) AS bookCount " +
"FROM persons " +
"LEFT JOIN books ON books.ownerId = persons.id " +
"GROUP BY persons.id " +
"ORDER BY persons.name",
compareRecordsByPrimaryKey: true)
let recorder = ChangesRecorder<Person>()
controller.delegate = recorder
controller.performFetch()
// Insert
recorder.transactionExpectation = expectationWithDescription("Insert")
try dbQueue.inTransaction { db in
try db.execute("INSERT INTO persons (name) VALUES (?)", arguments: ["Arthur"])
try db.execute("INSERT INTO books (ownerId, title) VALUES (?, ?)", arguments: [1, "Moby Dick"])
return .Commit
}
waitForExpectationsWithTimeout(1, handler: nil)
// Change books
recorder.transactionExpectation = expectationWithDescription("Change books")
try dbQueue.inTransaction { db in
try db.execute("DELETE FROM books")
return .Commit
}
waitForExpectationsWithTimeout(1, handler: nil)
XCTAssertEqual(recorder.recordsBeforeChanges.count, 1)
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.name }, ["Arthur"])
XCTAssertEqual(recorder.recordsBeforeChanges.map { $0.bookCount! }, [1])
XCTAssertEqual(recorder.recordsOnFirstEvent.count, 1)
XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.name }, ["Arthur"])
XCTAssertEqual(recorder.recordsOnFirstEvent.map { $0.bookCount! }, [0])
XCTAssertEqual(recorder.changes.count, 1)
XCTAssertEqual(recorder.changes[0].record.id, 1)
XCTAssertEqual(recorder.changes[0].record.name, "Arthur")
XCTAssertEqual(recorder.changes[0].record.bookCount, 0)
switch recorder.changes[0].event {
case .Update(let indexPath, let changes):
XCTAssertEqual(indexPath, NSIndexPath(forRow: 0, inSection: 0))
XCTAssertEqual(changes, ["bookCount": 1.databaseValue])
default:
XCTFail()
}
}
}
func testExternalTableChange() {
// TODO: test that delegate is not notified after a database change in a
// table not involved in the fetch request. The difficulty of this test
// lies in the "not" word.
}
}
@@ -6,7 +6,7 @@ import XCTest
#endif
// Person has a RowID primary key, and a overriden insert() method.
class Person : Record {
private class Person : Record {
var id: Int64!
var name: String!
var age: Int?
+34
View File
@@ -5,6 +5,40 @@ import XCTest
import GRDB
#endif
private class Person : Record {
var id: Int64!
var name: String!
var age: Int?
var creationDate: NSDate
init(id: Int64?, name: String?, age: Int?, creationDate: NSDate) {
self.id = id
self.name = name
self.age = age
self.creationDate = creationDate
super.init()
}
// Record
required init(_ row: Row) {
id = row.value(named: "id")
age = row.value(named: "age")
name = row.value(named: "name")
creationDate = row.value(named: "creationDate")
super.init(row)
}
override var persistentDictionary: [String: DatabaseValueConvertible?] {
return [
"id": id,
"name": name,
"age": age,
"creationDate": creationDate,
]
}
}
class RecordCopyTests: GRDBTestCase {
func testRecordCopy() {
+63 -2
View File
@@ -5,7 +5,68 @@ import XCTest
import GRDB
#endif
class IntegerPropertyOnRealAffinityColumn : Record {
private class Person : Record {
var id: Int64!
var name: String!
var age: Int?
var creationDate: NSDate!
init(id: Int64? = nil, name: String? = nil, age: Int? = nil, creationDate: NSDate? = nil) {
self.id = id
self.name = name
self.age = age
self.creationDate = creationDate
super.init()
}
static func setupInDatabase(db: Database) throws {
try db.execute(
"CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"creationDate TEXT NOT NULL, " +
"name TEXT NOT NULL, " +
"age INT" +
")")
}
// Record
override class func databaseTableName() -> String {
return "persons"
}
required init(_ row: Row) {
id = row.value(named: "id")
age = row.value(named: "age")
name = row.value(named: "name")
creationDate = row.value(named: "creationDate")
super.init(row)
}
override var persistentDictionary: [String: DatabaseValueConvertible?] {
return [
"id": id,
"name": name,
"age": age,
"creationDate": creationDate,
]
}
override func insert(db: Database) throws {
// This is implicitely tested with the NOT NULL constraint on creationDate
if creationDate == nil {
creationDate = NSDate()
}
try super.insert(db)
}
override func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
self.id = rowID
}
}
private class IntegerPropertyOnRealAffinityColumn : Record {
var value: Int!
init(value: Int?) {
@@ -25,7 +86,7 @@ class IntegerPropertyOnRealAffinityColumn : Record {
}
}
class PersonWithModifiedCaseColumns: Record {
private class PersonWithModifiedCaseColumns: Record {
var id: Int64!
var name: String!
var age: Int?
+47 -1
View File
@@ -5,6 +5,53 @@ import XCTest
import GRDB
#endif
private class Person : Record {
var id: Int64!
var name: String!
var age: Int?
init(id: Int64? = nil, name: String? = nil, age: Int? = nil) {
self.id = id
self.name = name
self.age = age
super.init()
}
static func setupInDatabase(db: Database) throws {
try db.execute(
"CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"name TEXT NOT NULL, " +
"age INT" +
")")
}
// Record
override class func databaseTableName() -> String {
return "persons"
}
required init(_ row: Row) {
id = row.value(named: "id")
age = row.value(named: "age")
name = row.value(named: "name")
super.init(row)
}
override var persistentDictionary: [String: DatabaseValueConvertible?] {
return [
"id": id,
"name": name,
"age": age,
]
}
override func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
self.id = rowID
}
}
class RecordFetchTests: GRDBTestCase {
override func setUpDatabase(dbWriter: DatabaseWriter) throws {
@@ -13,7 +60,6 @@ class RecordFetchTests: GRDBTestCase {
try migrator.migrate(dbWriter)
}
func testSelectStatement() {
assertNoError {
let dbQueue = try makeDatabaseQueue()
+63 -2
View File
@@ -5,7 +5,68 @@ import XCTest
import GRDB
#endif
class MinimalPersonWithOverrides : Person {
private class Person : Record {
var id: Int64!
var name: String!
var age: Int?
var creationDate: NSDate!
init(id: Int64? = nil, name: String? = nil, age: Int? = nil, creationDate: NSDate? = nil) {
self.id = id
self.name = name
self.age = age
self.creationDate = creationDate
super.init()
}
static func setupInDatabase(db: Database) throws {
try db.execute(
"CREATE TABLE persons (" +
"id INTEGER PRIMARY KEY, " +
"creationDate TEXT NOT NULL, " +
"name TEXT NOT NULL, " +
"age INT" +
")")
}
// Record
override class func databaseTableName() -> String {
return "persons"
}
required init(_ row: Row) {
id = row.value(named: "id")
age = row.value(named: "age")
name = row.value(named: "name")
creationDate = row.value(named: "creationDate")
super.init(row)
}
override var persistentDictionary: [String: DatabaseValueConvertible?] {
return [
"id": id,
"name": name,
"age": age,
"creationDate": creationDate,
]
}
override func insert(db: Database) throws {
// This is implicitely tested with the NOT NULL constraint on creationDate
if creationDate == nil {
creationDate = NSDate()
}
try super.insert(db)
}
override func didInsertWithRowID(rowID: Int64, forColumn column: String?) {
self.id = rowID
}
}
private class MinimalPersonWithOverrides : Person {
var extra: Int!
// Record
@@ -16,7 +77,7 @@ class MinimalPersonWithOverrides : Person {
}
}
class PersonWithOverrides : Person {
private class PersonWithOverrides : Person {
enum SavingMethod {
case Insert
case Update