diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.pbxproj b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.pbxproj index 93ad8ffa0..853e801c3 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.pbxproj +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/project.pbxproj @@ -7,6 +7,8 @@ objects = { /* Begin PBXBuildFile section */ + 56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */; }; + 56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */; }; 567C3E1A2520B6DE0011F6E9 /* GRDBCombineDemoApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */; }; 567C3E1E2520B6DF0011F6E9 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */; }; 567C3E212520B6DF0011F6E9 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 567C3E202520B6DF0011F6E9 /* Preview Assets.xcassets */; }; @@ -26,6 +28,13 @@ /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ + 56026C9D25B8A7D000D1DF3F /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 567C3E0E2520B6DE0011F6E9 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 567C3E152520B6DE0011F6E9; + remoteInfo = GRDBCombineDemo; + }; 567C3E342520B7000011F6E9 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */; @@ -106,6 +115,10 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 56026C9825B8A7D000D1DF3F /* GRDBCombineDemoTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBCombineDemoTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 56026C9C25B8A7D000D1DF3F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PlayerTests.swift; sourceTree = ""; }; + 56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDatabaseTests.swift; sourceTree = ""; }; 567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBCombineDemo.app; sourceTree = BUILT_PRODUCTS_DIR; }; 567C3E192520B6DE0011F6E9 /* GRDBCombineDemoApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GRDBCombineDemoApp.swift; sourceTree = ""; }; 567C3E1D2520B6DF0011F6E9 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; @@ -126,6 +139,13 @@ /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ + 56026C9525B8A7D000D1DF3F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; 567C3E132520B6DE0011F6E9 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; @@ -137,6 +157,16 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 56026C9925B8A7D000D1DF3F /* GRDBCombineDemoTests */ = { + isa = PBXGroup; + children = ( + 56026C9C25B8A7D000D1DF3F /* Info.plist */, + 56026CAB25B8A7EF00D1DF3F /* AppDatabaseTests.swift */, + 56026CAA25B8A7EF00D1DF3F /* PlayerTests.swift */, + ); + path = GRDBCombineDemoTests; + sourceTree = ""; + }; 56185BC125B8047D00B9C30F /* Resources */ = { isa = PBXGroup; children = ( @@ -160,6 +190,7 @@ children = ( 567C3E292520B7000011F6E9 /* GRDB.xcodeproj */, 567C3E182520B6DE0011F6E9 /* GRDBCombineDemo */, + 56026C9925B8A7D000D1DF3F /* GRDBCombineDemoTests */, 567C3E172520B6DE0011F6E9 /* Products */, 567C3E4D2520B70E0011F6E9 /* Frameworks */, ); @@ -169,6 +200,7 @@ isa = PBXGroup; children = ( 567C3E162520B6DE0011F6E9 /* GRDBCombineDemo.app */, + 56026C9825B8A7D000D1DF3F /* GRDBCombineDemoTests.xctest */, ); name = Products; sourceTree = ""; @@ -242,6 +274,24 @@ /* End PBXGroup section */ /* Begin PBXNativeTarget section */ + 56026C9725B8A7D000D1DF3F /* GRDBCombineDemoTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 56026CA825B8A7D000D1DF3F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoTests" */; + buildPhases = ( + 56026C9425B8A7D000D1DF3F /* Sources */, + 56026C9525B8A7D000D1DF3F /* Frameworks */, + 56026C9625B8A7D000D1DF3F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 56026C9E25B8A7D000D1DF3F /* PBXTargetDependency */, + ); + name = GRDBCombineDemoTests; + productName = GRDBCombineDemoTests; + productReference = 56026C9825B8A7D000D1DF3F /* GRDBCombineDemoTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; 567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */ = { isa = PBXNativeTarget; buildConfigurationList = 567C3E252520B6DF0011F6E9 /* Build configuration list for PBXNativeTarget "GRDBCombineDemo" */; @@ -267,9 +317,13 @@ 567C3E0E2520B6DE0011F6E9 /* Project object */ = { isa = PBXProject; attributes = { - LastSwiftUpdateCheck = 1200; + LastSwiftUpdateCheck = 1230; LastUpgradeCheck = 1200; TargetAttributes = { + 56026C9725B8A7D000D1DF3F = { + CreatedOnToolsVersion = 12.3; + TestTargetID = 567C3E152520B6DE0011F6E9; + }; 567C3E152520B6DE0011F6E9 = { CreatedOnToolsVersion = 12.0; }; @@ -295,6 +349,7 @@ projectRoot = ""; targets = ( 567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */, + 56026C9725B8A7D000D1DF3F /* GRDBCombineDemoTests */, ); }; /* End PBXProject section */ @@ -359,6 +414,13 @@ /* End PBXReferenceProxy section */ /* Begin PBXResourcesBuildPhase section */ + 56026C9625B8A7D000D1DF3F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; 567C3E142520B6DE0011F6E9 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; @@ -373,6 +435,15 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ + 56026C9425B8A7D000D1DF3F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 56026CAC25B8A7EF00D1DF3F /* PlayerTests.swift in Sources */, + 56026CAD25B8A7EF00D1DF3F /* AppDatabaseTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 567C3E122520B6DE0011F6E9 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -393,6 +464,11 @@ /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ + 56026C9E25B8A7D000D1DF3F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 567C3E152520B6DE0011F6E9 /* GRDBCombineDemo */; + targetProxy = 56026C9D25B8A7D000D1DF3F /* PBXContainerItemProxy */; + }; 567C3E522520B71C0011F6E9 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = GRDBiOS; @@ -420,6 +496,46 @@ /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ + 56026C9F25B8A7D000D1DF3F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 14.3; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCombineDemoTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBCombineDemo.app/GRDBCombineDemo"; + }; + name = Debug; + }; + 56026CA025B8A7D000D1DF3F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CODE_SIGN_STYLE = Automatic; + INFOPLIST_FILE = GRDBCombineDemoTests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 14.3; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@loader_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBCombineDemoTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBCombineDemo.app/GRDBCombineDemo"; + }; + name = Release; + }; 567C3E232520B6DF0011F6E9 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { @@ -583,6 +699,15 @@ /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ + 56026CA825B8A7D000D1DF3F /* Build configuration list for PBXNativeTarget "GRDBCombineDemoTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 56026C9F25B8A7D000D1DF3F /* Debug */, + 56026CA025B8A7D000D1DF3F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; 567C3E112520B6DE0011F6E9 /* Build configuration list for PBXProject "GRDBCombineDemo" */ = { isa = XCConfigurationList; buildConfigurations = ( diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/xcshareddata/xcschemes/GRDBCombineDemo.xcscheme b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/xcshareddata/xcschemes/GRDBCombineDemo.xcscheme new file mode 100644 index 000000000..3b324622e --- /dev/null +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo.xcodeproj/xcshareddata/xcschemes/GRDBCombineDemo.xcscheme @@ -0,0 +1,88 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift index 164271eb2..26d2c2b6f 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/AppDatabase.swift @@ -6,14 +6,18 @@ import GRDB /// It applies the pratices recommended at /// https://github.com/groue/GRDB.swift/blob/master/Documentation/GoodPracticesForDesigningRecordTypes.md struct AppDatabase { - /// Creates an `AppDatabase` from a database connection, - /// and make sure the database schema is ready. + /// Creates an `AppDatabase`, and make sure the database schema is ready. init(_ dbWriter: DatabaseWriter) throws { self.dbWriter = dbWriter try migrator.migrate(dbWriter) } - /// The database connection + /// Provides access to the database. + /// + /// Application can use a `DatabasePool`, while SwiftUI previews and tests + /// can use a fast in-memory `DatabaseQueue`. + /// + /// See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections private let dbWriter: DatabaseWriter /// The DatabaseMigrator that defines the database schema. diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift index 0b3f867b4..eeffaa232 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemo/Player.swift @@ -2,8 +2,9 @@ import GRDB /// The Player struct. /// -/// Identifiable conformance supports SwiftUI list animations -struct Player: Identifiable { +/// Identifiable conformance supports SwiftUI list animations. +/// Equatable conformance supports tests. +struct Player: Identifiable, Equatable { /// The player id. /// /// Int64 is the recommended type for auto-incremented database ids. diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/AppDatabaseTests.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/AppDatabaseTests.swift new file mode 100644 index 000000000..20e319249 --- /dev/null +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/AppDatabaseTests.swift @@ -0,0 +1,254 @@ +import XCTest +import GRDB +@testable import GRDBCombineDemo + +class AppDatabaseTests: XCTestCase { + func test_database_schema() throws { + // Given an empty database + let dbQueue = DatabaseQueue() + + // When we instantiate an AppDatabase + _ = try AppDatabase(dbQueue) + + // Then the player table exists, with id, name & score columns + try dbQueue.read { db in + try XCTAssert(db.tableExists("player")) + let columns = try db.columns(in: "player") + let columnNames = Set(columns.map { $0.name }) + XCTAssertEqual(columnNames, ["id", "name", "score"]) + } + } + + func test_savePlayer_inserts() throws { + // Given an empty players database + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + + // When we save a new player + var player = Player(id: nil, name: "Arthur", score: 100) + try appDatabase.savePlayer(&player) + + // Then the player exists in the database + try XCTAssertTrue(dbQueue.read(player.exists)) + } + + func test_savePlayer_updates() throws { + // Given a players database that contains a player + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + var player = Player(id: nil, name: "Arthur", score: 100) + try dbQueue.write { db in + try player.insert(db) + } + + // When we modify and save the player + player.name = "Barbara" + player.score = 1000 + try appDatabase.savePlayer(&player) + + // Then the player has been updated in the database + let fetchedPlayer = try dbQueue.read { db in + try XCTUnwrap(Player.fetchOne(db, key: player.id)) + } + XCTAssertEqual(fetchedPlayer, player) + } + + func test_deletePlayers() throws { + // Given a players database that contains four players + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + var player1 = Player(id: nil, name: "Arthur", score: 100) + var player2 = Player(id: nil, name: "Barbara", score: 200) + var player3 = Player(id: nil, name: "Craig", score: 150) + var player4 = Player(id: nil, name: "David", score: 120) + try dbQueue.write { db in + try player1.insert(db) + try player2.insert(db) + try player3.insert(db) + try player4.insert(db) + } + + // When we delete two players + try appDatabase.deletePlayers(ids: [player1.id!, player3.id!]) + + // Then the deleted players no longer exist + try dbQueue.read { db in + try XCTAssertFalse(player1.exists(db)) + try XCTAssertFalse(player3.exists(db)) + } + + // Then the database still contains two players + try XCTAssertEqual(dbQueue.read(Player.fetchCount), 2) + } + + func test_deleteAllPlayers() throws { + // Given a players database that contains players + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + var player1 = Player(id: nil, name: "Arthur", score: 100) + var player2 = Player(id: nil, name: "Barbara", score: 200) + var player3 = Player(id: nil, name: "Craig", score: 150) + var player4 = Player(id: nil, name: "David", score: 120) + try dbQueue.write { db in + try player1.insert(db) + try player2.insert(db) + try player3.insert(db) + try player4.insert(db) + } + + // When we delete all players + try appDatabase.deleteAllPlayers() + + // Then the database does not contain any player + try XCTAssertEqual(dbQueue.read(Player.fetchCount), 0) + } + + func test_refreshPlayers_populates_an_empty_database() throws { + // Given an empty players database + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + + // When we refresh players + try appDatabase.refreshPlayers() + + // Then the database is not empty + try XCTAssert(dbQueue.read(Player.fetchCount) > 0) + } + + func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws { + // Given an empty players database + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + + // When we create random players + try appDatabase.createRandomPlayersIfEmpty() + + // Then the database is not empty + try XCTAssert(dbQueue.read(Player.fetchCount) > 0) + } + + func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws { + // Given a players database that contains one player + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + var player = Player(id: nil, name: "Arthur", score: 100) + try dbQueue.write { db in + try player.insert(db) + } + + // When we create random players + try appDatabase.createRandomPlayersIfEmpty() + + // Then the database still only contains the original player + let players = try dbQueue.read(Player.fetchAll) + XCTAssertEqual(players, [player]) + } + + func test_playersOrderedByNamePublisher_publishes_well_ordered_players() throws { + // Given a players database that contains two players + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + var player1 = Player(id: nil, name: "Arthur", score: 100) + var player2 = Player(id: nil, name: "Barbara", score: 1000) + try dbQueue.write { db in + try player1.insert(db) + try player2.insert(db) + } + + // When we observe players and wait for the first value + let exp = expectation(description: "Players") + var players: [Player]? + let cancellable = appDatabase.playersOrderedByNamePublisher().sink { completion in + if case let .failure(error) = completion { + XCTFail("Unexpected error \(error)") + } + } receiveValue: { + players = $0 + exp.fulfill() + } + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + } + + // Then the players are the two players ordered by name + XCTAssertEqual(players, [player1, player2]) + } + + func test_playersOrderedByNamePublisher_publishes_right_on_subscripion() throws { + // Our SwiftUI views have no "waiting" state, and must be fed with + // players without any delay in order to avoid any rendering glitch. + // This test makes sure `playersOrderedByNamePublisher` publishes right + // on subscription. + + // Given a players database + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + + // When we observe players + var players: [Player]? + _ = appDatabase.playersOrderedByNamePublisher().sink { completion in + if case let .failure(error) = completion { + XCTFail("Unexpected error \(error)") + } + } receiveValue: { + players = $0 + } + + // Then the players are published right on subscription + XCTAssertNotNil(players) + } + + func test_playersOrderedByScorePublisher_publishes_well_ordered_players() throws { + // Given a players database that contains two players + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + var player1 = Player(id: nil, name: "Arthur", score: 100) + var player2 = Player(id: nil, name: "Barbara", score: 1000) + try dbQueue.write { db in + try player1.insert(db) + try player2.insert(db) + } + + // When we observe players and wait for the first value + let exp = expectation(description: "Players") + var players: [Player]? + let cancellable = appDatabase.playersOrderedByScorePublisher().sink { completion in + if case let .failure(error) = completion { + XCTFail("Unexpected error \(error)") + } + } receiveValue: { + players = $0 + exp.fulfill() + } + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + } + + // Then the players are the two players ordered by score descending + XCTAssertEqual(players, [player2, player1]) + } + + func test_playersOrderedByScorePublisher_publishes_right_on_subscripion() throws { + // Our SwiftUI views have no "waiting" state, and must be fed with + // players without any delay in order to avoid any rendering glitch. + // This test makes sure `playersOrderedByScorePublisher` publishes right + // on subscription. + + // Given a players database + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + + // When we observe players + var players: [Player]? + _ = appDatabase.playersOrderedByScorePublisher().sink { completion in + if case let .failure(error) = completion { + XCTFail("Unexpected error \(error)") + } + } receiveValue: { + players = $0 + } + + // Then the players are published right on subscription + XCTAssertNotNil(players) + } +} diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/Info.plist b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/Info.plist new file mode 100644 index 000000000..64d65ca49 --- /dev/null +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/Info.plist @@ -0,0 +1,22 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + + diff --git a/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerTests.swift b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerTests.swift new file mode 100644 index 000000000..44b25d383 --- /dev/null +++ b/Documentation/DemoApps/GRDBCombineDemo/GRDBCombineDemoTests/PlayerTests.swift @@ -0,0 +1,108 @@ +import XCTest +import GRDB +@testable import GRDBCombineDemo + +class PlayerTests: XCTestCase { + // MARK: - CRUD + // Test that our Player type properly talks to GRDB. + + func testInsert() throws { + // Given an empty players database + let dbQueue = DatabaseQueue() + _ = try AppDatabase(dbQueue) + + // When we insert a player + var player = Player(id: nil, name: "Arthur", score: 100) + try dbQueue.write { db in + try player.insert(db) + } + + // Then the player gets a non-nil id + XCTAssertNotNil(player.id) + } + + func testRoundtrip() throws { + // Given an empty players database + let dbQueue = DatabaseQueue() + _ = try AppDatabase(dbQueue) + + // When we insert a player and fetch the player with the same id + var insertedPlayer = Player(id: nil, name: "Arthur", score: 100) + let fetchedPlayer: Player? = try dbQueue.write { db in + try insertedPlayer.insert(db) + return try Player.fetchOne(db, key: insertedPlayer.id) + } + + // Then the fetched player is equal to the inserted player + XCTAssertEqual(insertedPlayer, fetchedPlayer) + } + + // MARK: - Requests + // Test that requests defined on the Player type behave as expected. + + func testOrderedByScore() throws { + // Given a players database that contains players with distinct scores + let dbQueue = DatabaseQueue() + _ = try AppDatabase(dbQueue) + var player1 = Player(id: 1, name: "Arthur", score: 100) + var player2 = Player(id: 2, name: "Barbara", score: 200) + var player3 = Player(id: 3, name: "Craig", score: 150) + var player4 = Player(id: 4, name: "David", score: 120) + try dbQueue.write { db in + try player1.insert(db) + try player2.insert(db) + try player3.insert(db) + try player4.insert(db) + } + + // When we fetch players ordered by score + let players = try dbQueue.read(Player.all().orderedByScore().fetchAll) + + // Then fetched players are ordered by score descending + XCTAssertEqual(players, [player2, player3, player4, player1]) + } + + func testOrderedByScoreSortsIdenticalScoresByName() throws { + // Given a players database that contains players with common scores + let dbQueue = DatabaseQueue() + _ = try AppDatabase(dbQueue) + var player1 = Player(id: 1, name: "Arthur", score: 100) + var player2 = Player(id: 2, name: "Barbara", score: 200) + var player3 = Player(id: 3, name: "Craig", score: 200) + var player4 = Player(id: 4, name: "David", score: 200) + try dbQueue.write { db in + try player1.insert(db) + try player2.insert(db) + try player3.insert(db) + try player4.insert(db) + } + + // When we fetch players ordered by score + let players = try dbQueue.read(Player.all().orderedByScore().fetchAll) + + // Then fetched players are ordered by score descending and by name + XCTAssertEqual(players, [player2, player3, player4, player1]) + } + + func testOrderedByName() throws { + // Given a players database that contains players with distinct names + let dbQueue = DatabaseQueue() + _ = try AppDatabase(dbQueue) + var player1 = Player(id: 1, name: "Arthur", score: 100) + var player2 = Player(id: 2, name: "Barbara", score: 200) + var player3 = Player(id: 3, name: "Craig", score: 150) + var player4 = Player(id: 4, name: "David", score: 120) + try dbQueue.write { db in + try player1.insert(db) + try player2.insert(db) + try player3.insert(db) + try player4.insert(db) + } + + // When we fetch players ordered by name + let players = try dbQueue.read(Player.all().orderedByName().fetchAll) + + // Then fetched players are ordered by name + XCTAssertEqual(players, [player1, player2, player3, player4]) + } +} diff --git a/Documentation/DemoApps/GRDBCombineDemo/README.md b/Documentation/DemoApps/GRDBCombineDemo/README.md index 23dd4793f..620a24552 100644 --- a/Documentation/DemoApps/GRDBCombineDemo/README.md +++ b/Documentation/DemoApps/GRDBCombineDemo/README.md @@ -40,3 +40,9 @@ The topics covered in this demo are: - [PlayerForm.swift](GRDBCombineDemo/Views/PlayerForm.swift), [PlayerEditionView.swift](GRDBCombineDemo/Views/PlayerEditionView.swift), [PlayerCreationSheet.swift](GRDBCombineDemo/Views/PlayerCreationSheet.swift) and [PlayerFormViewModel.swift](GRDBCombineDemo/ViewModels/PlayerFormViewModel.swift). `PlayerForm` is the SwiftUI view that displays a Player editing form. It is embedded in `PlayerEditionView` and `PlayerCreationSheet`, two SwiftUI views that edit or create a player. All those views are fed by `PlayerFormViewModel`. + +- [GRDBCombineDemoTests](GRDBCombineDemoTests) + + - Test the database schema + - Test the `Player` record and its requests + - Test the `AppDatabase` methods that let the app access the database. diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj index 04e9ba43c..c6fb87b72 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/project.pbxproj @@ -8,6 +8,8 @@ /* Begin PBXBuildFile section */ 56185BBF25B8036100B9C30F /* Persistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185BBE25B8036100B9C30F /* Persistence.swift */; }; + 56185BF325B80B8900B9C30F /* AppDatabaseTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185BF225B80B8900B9C30F /* AppDatabaseTests.swift */; }; + 56185C0725B80CEC00B9C30F /* PlayerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 56185C0625B80CEC00B9C30F /* PlayerTests.swift */; }; 56606D202355938A00185962 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D142355931F00185962 /* GRDB.framework */; }; 56606D212355938A00185962 /* GRDB.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D142355931F00185962 /* GRDB.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 56606D24235593AB00185962 /* GRDB.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 56606D182355931F00185962 /* GRDB.framework */; }; @@ -31,6 +33,13 @@ /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ + 56185BF525B80B8900B9C30F /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 56B035FB1E8D9EBE003B6DA4 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 56B036021E8D9EBE003B6DA4; + remoteInfo = GRDBDemoiOS; + }; 56606D092355931F00185962 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = 56B036261E8D9F79003B6DA4 /* GRDB.xcodeproj */; @@ -166,6 +175,10 @@ /* Begin PBXFileReference section */ 56185BBE25B8036100B9C30F /* Persistence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Persistence.swift; sourceTree = ""; }; + 56185BF025B80B8900B9C30F /* GRDBDemoiOSTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = GRDBDemoiOSTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + 56185BF225B80B8900B9C30F /* AppDatabaseTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDatabaseTests.swift; sourceTree = ""; }; + 56185BF425B80B8900B9C30F /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 56185C0625B80CEC00B9C30F /* PlayerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlayerTests.swift; sourceTree = ""; }; 568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = GRDBDemoWatchOS.app; sourceTree = BUILT_PRODUCTS_DIR; }; 568E5FC21E926430002582E0 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Interface.storyboard; sourceTree = ""; }; 568E5FC41E926430002582E0 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; @@ -190,6 +203,13 @@ /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ + 56185BED25B80B8900B9C30F /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; 568E5FC81E926430002582E0 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; @@ -209,6 +229,16 @@ /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ + 56185BF125B80B8900B9C30F /* GRDBDemoiOSTests */ = { + isa = PBXGroup; + children = ( + 56185BF425B80B8900B9C30F /* Info.plist */, + 56185BF225B80B8900B9C30F /* AppDatabaseTests.swift */, + 56185C0625B80CEC00B9C30F /* PlayerTests.swift */, + ); + path = GRDBDemoiOSTests; + sourceTree = ""; + }; 56606CFD2355931F00185962 /* Products */ = { isa = PBXGroup; children = ( @@ -259,6 +289,7 @@ 56B036051E8D9EBE003B6DA4 /* GRDBDemoiOS */, 568E5FC01E926430002582E0 /* GRDBDemoWatchOS */, 568E5FCF1E926430002582E0 /* GRDBDemoWatchOS Extension */, + 56185BF125B80B8900B9C30F /* GRDBDemoiOSTests */, 56B036041E8D9EBE003B6DA4 /* Products */, 56606D1F2355938A00185962 /* Frameworks */, ); @@ -270,6 +301,7 @@ 56B036031E8D9EBE003B6DA4 /* GRDBDemoiOS.app */, 568E5FBF1E926430002582E0 /* GRDBDemoWatchOS.app */, 568E5FCB1E926430002582E0 /* GRDBDemoWatchOS Extension.appex */, + 56185BF025B80B8900B9C30F /* GRDBDemoiOSTests.xctest */, ); name = Products; sourceTree = ""; @@ -319,6 +351,24 @@ /* End PBXGroup section */ /* Begin PBXNativeTarget section */ + 56185BEF25B80B8900B9C30F /* GRDBDemoiOSTests */ = { + isa = PBXNativeTarget; + buildConfigurationList = 56185BFF25B80B8900B9C30F /* Build configuration list for PBXNativeTarget "GRDBDemoiOSTests" */; + buildPhases = ( + 56185BEC25B80B8900B9C30F /* Sources */, + 56185BED25B80B8900B9C30F /* Frameworks */, + 56185BEE25B80B8900B9C30F /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + 56185BF625B80B8900B9C30F /* PBXTargetDependency */, + ); + name = GRDBDemoiOSTests; + productName = GRDBDemoiOSTests; + productReference = 56185BF025B80B8900B9C30F /* GRDBDemoiOSTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; + }; 568E5FBE1E926430002582E0 /* GRDBDemoWatchOS */ = { isa = PBXNativeTarget; buildConfigurationList = 568E5FDE1E926430002582E0 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS" */; @@ -382,10 +432,16 @@ 56B035FB1E8D9EBE003B6DA4 /* Project object */ = { isa = PBXProject; attributes = { - LastSwiftUpdateCheck = 0830; + LastSwiftUpdateCheck = 1230; LastUpgradeCheck = 1200; ORGANIZATIONNAME = "Gwendal Roué"; TargetAttributes = { + 56185BEF25B80B8900B9C30F = { + CreatedOnToolsVersion = 12.3; + DevelopmentTeam = AMD8W895CT; + ProvisioningStyle = Automatic; + TestTargetID = 56B036021E8D9EBE003B6DA4; + }; 568E5FBE1E926430002582E0 = { CreatedOnToolsVersion = 8.3; DevelopmentTeam = AMD8W895CT; @@ -427,6 +483,7 @@ 56B036021E8D9EBE003B6DA4 /* GRDBDemoiOS */, 568E5FBE1E926430002582E0 /* GRDBDemoWatchOS */, 568E5FCA1E926430002582E0 /* GRDBDemoWatchOS Extension */, + 56185BEF25B80B8900B9C30F /* GRDBDemoiOSTests */, ); }; /* End PBXProject section */ @@ -491,6 +548,13 @@ /* End PBXReferenceProxy section */ /* Begin PBXResourcesBuildPhase section */ + 56185BEE25B80B8900B9C30F /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; 568E5FBD1E926430002582E0 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; @@ -521,6 +585,15 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ + 56185BEC25B80B8900B9C30F /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 56185C0725B80CEC00B9C30F /* PlayerTests.swift in Sources */, + 56185BF325B80B8900B9C30F /* AppDatabaseTests.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; 568E5FC71E926430002582E0 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; @@ -547,6 +620,11 @@ /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ + 56185BF625B80B8900B9C30F /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 56B036021E8D9EBE003B6DA4 /* GRDBDemoiOS */; + targetProxy = 56185BF525B80B8900B9C30F /* PBXContainerItemProxy */; + }; 56606D1E2355937900185962 /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = GRDBiOS; @@ -597,6 +675,51 @@ /* End PBXVariantGroup section */ /* Begin XCBuildConfiguration section */ + 56185BF725B80B8900B9C30F /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = AMD8W895CT; + GCC_C_LANGUAGE_STANDARD = gnu11; + INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 14.3; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOSTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemoiOS.app/GRDBDemoiOS"; + }; + name = Debug; + }; + 56185BF825B80B8900B9C30F /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + BUNDLE_LOADER = "$(TEST_HOST)"; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CODE_SIGN_STYLE = Automatic; + DEVELOPMENT_TEAM = AMD8W895CT; + GCC_C_LANGUAGE_STANDARD = gnu11; + INFOPLIST_FILE = GRDBDemoiOSTests/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 14.3; + LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; + MTL_FAST_MATH = YES; + PRODUCT_BUNDLE_IDENTIFIER = com.github.groue.GRDBDemoiOSTests; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2"; + TEST_HOST = "$(BUILT_PRODUCTS_DIR)/GRDBDemoiOS.app/GRDBDemoiOS"; + }; + name = Release; + }; 568E5FDB1E926430002582E0 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { @@ -811,6 +934,15 @@ /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ + 56185BFF25B80B8900B9C30F /* Build configuration list for PBXNativeTarget "GRDBDemoiOSTests" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 56185BF725B80B8900B9C30F /* Debug */, + 56185BF825B80B8900B9C30F /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; 568E5FDA1E926430002582E0 /* Build configuration list for PBXNativeTarget "GRDBDemoWatchOS Extension" */ = { isa = XCConfigurationList; buildConfigurations = ( diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme index e99af2836..237e9f7b3 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOS.xcodeproj/xcshareddata/xcschemes/GRDBDemoWatchOS.xcscheme @@ -56,6 +56,16 @@ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" shouldUseLaunchSchemeArgsEnv = "YES"> + + + + + + + + AppDatabase { - // Connect to an in-memory database - // See https://github.com/groue/GRDB.swift/blob/master/README.md#database-connections - let dbQueue = DatabaseQueue() - return try! AppDatabase(dbQueue) - } } diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/AppDatabaseTests.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/AppDatabaseTests.swift new file mode 100644 index 000000000..731cfc2b0 --- /dev/null +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/AppDatabaseTests.swift @@ -0,0 +1,234 @@ +import XCTest +import GRDB +@testable import GRDBDemoiOS + +class AppDatabaseTests: XCTestCase { + func test_database_schema() throws { + // Given an empty database + let dbQueue = DatabaseQueue() + + // When we instantiate an AppDatabase + _ = try AppDatabase(dbQueue) + + // Then the player table exists, with id, name & score columns + try dbQueue.read { db in + try XCTAssert(db.tableExists("player")) + let columns = try db.columns(in: "player") + let columnNames = Set(columns.map { $0.name }) + XCTAssertEqual(columnNames, ["id", "name", "score"]) + } + } + + func test_savePlayer_inserts() throws { + // Given an empty players database + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + + // When we save a new player + var player = Player(id: nil, name: "Arthur", score: 100) + try appDatabase.savePlayer(&player) + + // Then the player exists in the database + try XCTAssertTrue(dbQueue.read(player.exists)) + } + + func test_savePlayer_updates() throws { + // Given a players database that contains a player + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + var player = Player(id: nil, name: "Arthur", score: 100) + try dbQueue.write { db in + try player.insert(db) + } + + // When we modify and save the player + player.name = "Barbara" + player.score = 1000 + try appDatabase.savePlayer(&player) + + // Then the player has been updated in the database + let fetchedPlayer = try dbQueue.read { db in + try XCTUnwrap(Player.fetchOne(db, key: player.id)) + } + XCTAssertEqual(fetchedPlayer, player) + } + + func test_deletePlayers() throws { + // Given a players database that contains four players + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + var player1 = Player(id: nil, name: "Arthur", score: 100) + var player2 = Player(id: nil, name: "Barbara", score: 200) + var player3 = Player(id: nil, name: "Craig", score: 150) + var player4 = Player(id: nil, name: "David", score: 120) + try dbQueue.write { db in + try player1.insert(db) + try player2.insert(db) + try player3.insert(db) + try player4.insert(db) + } + + // When we delete two players + try appDatabase.deletePlayers(ids: [player1.id!, player3.id!]) + + // Then the deleted players no longer exist + try dbQueue.read { db in + try XCTAssertFalse(player1.exists(db)) + try XCTAssertFalse(player3.exists(db)) + } + + // Then the database still contains two players + try XCTAssertEqual(dbQueue.read(Player.fetchCount), 2) + } + + func test_deleteAllPlayers() throws { + // Given a players database that contains players + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + var player1 = Player(id: nil, name: "Arthur", score: 100) + var player2 = Player(id: nil, name: "Barbara", score: 200) + var player3 = Player(id: nil, name: "Craig", score: 150) + var player4 = Player(id: nil, name: "David", score: 120) + try dbQueue.write { db in + try player1.insert(db) + try player2.insert(db) + try player3.insert(db) + try player4.insert(db) + } + + // When we delete all players + try appDatabase.deleteAllPlayers() + + // Then the database does not contain any player + try XCTAssertEqual(dbQueue.read(Player.fetchCount), 0) + } + + func test_refreshPlayers_populates_an_empty_database() throws { + // Given an empty players database + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + + // When we refresh players + try appDatabase.refreshPlayers() + + // Then the database is not empty + try XCTAssert(dbQueue.read(Player.fetchCount) > 0) + } + + func test_createRandomPlayersIfEmpty_populates_an_empty_database() throws { + // Given an empty players database + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + + // When we create random players + try appDatabase.createRandomPlayersIfEmpty() + + // Then the database is not empty + try XCTAssert(dbQueue.read(Player.fetchCount) > 0) + } + + func test_createRandomPlayersIfEmpty_does_not_modify_a_non_empty_database() throws { + // Given a players database that contains one player + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + var player = Player(id: nil, name: "Arthur", score: 100) + try dbQueue.write { db in + try player.insert(db) + } + + // When we create random players + try appDatabase.createRandomPlayersIfEmpty() + + // Then the database still only contains the original player + let players = try dbQueue.read(Player.fetchAll) + XCTAssertEqual(players, [player]) + } + + func test_observePlayerCount() throws { + // Given a players database that contains one player + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + var player = Player(id: nil, name: "Arthur", score: 100) + try dbQueue.write { db in + try player.insert(db) + } + + // When we observe the player count and wait for the first value + let exp = expectation(description: "Player count") + var count: Int? + let cancellable = appDatabase.observePlayerCount( + onError: { error in + XCTFail("Unexpected error \(error)") + }, + onChange: { + count = $0 + exp.fulfill() + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + } + + // Then that first value is one + XCTAssertEqual(count, 1) + } + + func test_observePlayersOrderedByName() throws { + // Given a players database that contains two players + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + var player1 = Player(id: nil, name: "Arthur", score: 100) + var player2 = Player(id: nil, name: "Barbara", score: 1000) + try dbQueue.write { db in + try player1.insert(db) + try player2.insert(db) + } + + // When we observe players and wait for the first value + let exp = expectation(description: "Players") + var players: [Player]? + let cancellable = appDatabase.observePlayersOrderedByName( + onError: { error in + XCTFail("Unexpected error \(error)") + }, + onChange: { + players = $0 + exp.fulfill() + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + } + + // Then the players are the two players ordered by name + XCTAssertEqual(players, [player1, player2]) + } + + func test_observePlayersOrderedByScore() throws { + // Given a players database that contains two players + let dbQueue = DatabaseQueue() + let appDatabase = try AppDatabase(dbQueue) + var player1 = Player(id: nil, name: "Arthur", score: 100) + var player2 = Player(id: nil, name: "Barbara", score: 1000) + try dbQueue.write { db in + try player1.insert(db) + try player2.insert(db) + } + + // When we observe players and wait for the first value + let exp = expectation(description: "Players") + var players: [Player]? + let cancellable = appDatabase.observePlayersOrderedByScore( + onError: { error in + XCTFail("Unexpected error \(error)") + }, + onChange: { + players = $0 + exp.fulfill() + }) + withExtendedLifetime(cancellable) { + waitForExpectations(timeout: 1, handler: nil) + } + + // Then the players are the two players ordered by score descending + XCTAssertEqual(players, [player2, player1]) + } +} diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/Info.plist b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/Info.plist new file mode 100644 index 000000000..64d65ca49 --- /dev/null +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/Info.plist @@ -0,0 +1,22 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + + diff --git a/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift new file mode 100644 index 000000000..a05e04f78 --- /dev/null +++ b/Documentation/DemoApps/GRDBDemoiOS/GRDBDemoiOSTests/PlayerTests.swift @@ -0,0 +1,108 @@ +import XCTest +import GRDB +@testable import GRDBDemoiOS + +class PlayerTests: XCTestCase { + // MARK: - CRUD + // Test that our Player type properly talks to GRDB. + + func testInsert() throws { + // Given an empty players database + let dbQueue = DatabaseQueue() + _ = try AppDatabase(dbQueue) + + // When we insert a player + var player = Player(id: nil, name: "Arthur", score: 100) + try dbQueue.write { db in + try player.insert(db) + } + + // Then the player gets a non-nil id + XCTAssertNotNil(player.id) + } + + func testRoundtrip() throws { + // Given an empty players database + let dbQueue = DatabaseQueue() + _ = try AppDatabase(dbQueue) + + // When we insert a player and fetch the player with the same id + var insertedPlayer = Player(id: nil, name: "Arthur", score: 100) + let fetchedPlayer: Player? = try dbQueue.write { db in + try insertedPlayer.insert(db) + return try Player.fetchOne(db, key: insertedPlayer.id) + } + + // Then the fetched player is equal to the inserted player + XCTAssertEqual(insertedPlayer, fetchedPlayer) + } + + // MARK: - Requests + // Test that requests defined on the Player type behave as expected. + + func testOrderedByScore() throws { + // Given a players database that contains players with distinct scores + let dbQueue = DatabaseQueue() + _ = try AppDatabase(dbQueue) + var player1 = Player(id: 1, name: "Arthur", score: 100) + var player2 = Player(id: 2, name: "Barbara", score: 200) + var player3 = Player(id: 3, name: "Craig", score: 150) + var player4 = Player(id: 4, name: "David", score: 120) + try dbQueue.write { db in + try player1.insert(db) + try player2.insert(db) + try player3.insert(db) + try player4.insert(db) + } + + // When we fetch players ordered by score + let players = try dbQueue.read(Player.all().orderedByScore().fetchAll) + + // Then fetched players are ordered by score descending + XCTAssertEqual(players, [player2, player3, player4, player1]) + } + + func testOrderedByScoreSortsIdenticalScoresByName() throws { + // Given a players database that contains players with common scores + let dbQueue = DatabaseQueue() + _ = try AppDatabase(dbQueue) + var player1 = Player(id: 1, name: "Arthur", score: 100) + var player2 = Player(id: 2, name: "Barbara", score: 200) + var player3 = Player(id: 3, name: "Craig", score: 200) + var player4 = Player(id: 4, name: "David", score: 200) + try dbQueue.write { db in + try player1.insert(db) + try player2.insert(db) + try player3.insert(db) + try player4.insert(db) + } + + // When we fetch players ordered by score + let players = try dbQueue.read(Player.all().orderedByScore().fetchAll) + + // Then fetched players are ordered by score descending and by name + XCTAssertEqual(players, [player2, player3, player4, player1]) + } + + func testOrderedByName() throws { + // Given a players database that contains players with distinct names + let dbQueue = DatabaseQueue() + _ = try AppDatabase(dbQueue) + var player1 = Player(id: 1, name: "Arthur", score: 100) + var player2 = Player(id: 2, name: "Barbara", score: 200) + var player3 = Player(id: 3, name: "Craig", score: 150) + var player4 = Player(id: 4, name: "David", score: 120) + try dbQueue.write { db in + try player1.insert(db) + try player2.insert(db) + try player3.insert(db) + try player4.insert(db) + } + + // When we fetch players ordered by name + let players = try dbQueue.read(Player.all().orderedByName().fetchAll) + + // Then fetched players are ordered by name + XCTAssertEqual(players, [player1, player2, player3, player4]) + } +} diff --git a/Documentation/DemoApps/GRDBDemoiOS/README.md b/Documentation/DemoApps/GRDBDemoiOS/README.md index 49778dac6..1227e514a 100644 --- a/Documentation/DemoApps/GRDBDemoiOS/README.md +++ b/Documentation/DemoApps/GRDBDemoiOS/README.md @@ -22,7 +22,7 @@ The topics covered in this demo are: - [Persistence.swift](GRDBDemoiOS/Persistence.swift) - This file instantiates various `AppDatabase` for the various projects needs: one database on disk for the application, and in-memory databases for tests. + This file defines the `AppDatabase` instance used by the application. - [Player.swift](GRDBDemoiOS/Player.swift) @@ -35,3 +35,9 @@ The topics covered in this demo are: - [PlayerEditionViewController.swift](GRDBDemoiOS/ViewControllers/PlayerEditionViewController.swift) `PlayerEditionViewController` can create or edit a player, and save it in the database. + +- [GRDBDemoiOSTests](GRDBDemoiOSTests) + + - Test the database schema + - Test the `Player` record and its requests + - Test the `AppDatabase` methods that let the app access the database.