Cleanup demo app, and add tests for the view model

This commit is contained in:
Gwendal Roué committed 2024-09-28 15:54:23 +02:00
1 parent 073682c4f0
commit d68e55c184
9 files changed
+118 -9

No files matched your search

@@ -4,7 +4,7 @@ import SwiftUI
struct GRDBDemoApp: App {
var body: some Scene {
WindowGroup {
PlayerNavigationView().appDatabase(.shared)
PlayersNavigationView().appDatabase(.shared)
}
}
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 447 KiB

After

Width:  |  Height:  |  Size: 586 KiB

@@ -1,5 +1,6 @@
import SwiftUI
/// A view that creates a `Player`. Display it as a sheet.
struct PlayerCreationSheet: View {
@Environment(\.appDatabase) var appDatabase
@Environment(\.dismiss) var dismiss
@@ -1,7 +1,6 @@
import SwiftUI
struct PlayerEditionView: View {
@Environment(\.dismiss) var dismiss
@Environment(\.isPresented) var isPresented
@Environment(\.appDatabase) var appDatabase
@State var form: PlayerForm
@@ -1,5 +1,6 @@
import SwiftUI
/// A view that edits a `PlayerForm`.
struct PlayerFormView: View {
@Binding var form: PlayerForm
@@ -38,6 +39,7 @@ struct PlayerFormView: View {
}
}
/// The model edited by `PlayerFormView`.
struct PlayerForm {
var name: String
var score: Int?
@@ -2,6 +2,12 @@ import Foundation
import Observation
import GRDB
/// The observable model that drives the main navigation view.
///
/// It observes the database in order to always display an up-to-date list
/// of players.
///
/// This class is testable. See `PlayerListModelTests.swift`.
@Observable @MainActor final class PlayerListModel {
/// A player ordering
enum Ordering {
@@ -22,6 +28,8 @@ import GRDB
private let appDatabase: AppDatabase
@ObservationIgnored private var cancellable: AnyDatabaseCancellable?
// MARK: - Initialization
/// Creates a `PlayerListModel`.
init(appDatabase: AppDatabase) {
self.appDatabase = appDatabase
@@ -29,6 +37,7 @@ import GRDB
/// Start observing the database.
func observePlayers() {
// We observe all players, sorted according to `ordering`.
let observation = ValueObservation.tracking { [ordering] db in
switch ordering {
case .byName:
@@ -38,6 +47,8 @@ import GRDB
}
}
// Start observing the database.
// Previous observation, if any, is cancelled.
cancellable = observation.start(in: appDatabase.reader) { error in
// Handle error
} onChange: { [unowned self] players in
@@ -45,21 +56,26 @@ import GRDB
}
}
// MARK: - Actions
/// Delete players at specified indexes in `self.players`.
func deletePlayers(at offsets: IndexSet) throws {
let playerIds = offsets.compactMap { players[$0].id }
try appDatabase.deletePlayers(ids: playerIds)
}
/// Delete all players.
func deleteAllPlayers() throws {
try appDatabase.deleteAllPlayers()
}
/// Refresh all players (by performing some random changes, for demo purpose).
func refreshPlayers() async throws {
try await appDatabase.refreshPlayers()
}
/// Perform 50 refreshes in parallel, for demo purpose.
func refreshPlayersManyTimes() async throws {
// Perform 50 refreshes in parallel
try await withThrowingTaskGroup(of: Void.self) { group in
for _ in 0..<50 {
group.addTask {
@@ -1,5 +1,6 @@
import SwiftUI
/// A view that displays a list of players.
struct PlayerListView: View {
@Bindable var model: PlayerListModel
@@ -50,6 +51,8 @@ struct PlayerRow: View {
@Environment(\.appDatabase) var appDatabase
var body: some View {
// This technique makes it possible to create an observable object
// (PlayerListModel) from the SwiftUI environment.
ContentView(appDatabase: appDatabase)
}
}
@@ -64,8 +67,8 @@ struct PlayerRow: View {
var body: some View {
NavigationStack {
PlayerListView(model: model)
.onAppear { model.observePlayers() }
}
.onAppear { model.observePlayers() }
}
}
@@ -1,9 +1,12 @@
import SwiftUI
struct PlayerNavigationView: View {
/// The main navigation view.
struct PlayersNavigationView: View {
@Environment(\.appDatabase) var appDatabase
var body: some View {
// This technique makes it possible to create an observable object
// (PlayerListModel) from the SwiftUI environment.
ContentView(appDatabase: appDatabase)
}
}
@@ -12,7 +15,7 @@ private struct ContentView: View {
/// The model for the player list.
@State var model: PlayerListModel
/// We'll need to leave edit mode in several occasions.
/// Tracks the edit mode of the player list.
@State var editMode = EditMode.inactive
/// Tracks the presentation of the player creation sheet.
@@ -36,7 +39,7 @@ private struct ContentView: View {
stopEditing()
}
.onChange(of: model.players.isEmpty) {
// Stop editing when last player is deleted.
// Stop editing when the last player is deleted.
if model.players.isEmpty {
stopEditing()
}
@@ -168,11 +171,11 @@ private struct ToggleOrderingButton: View {
// MARK: - Previews
#Preview("Populated") {
PlayerNavigationView()
PlayersNavigationView()
.appDatabase(.random())
}
#Preview("Empty") {
PlayerNavigationView()
PlayersNavigationView()
.appDatabase(.empty())
}
@@ -0,0 +1,85 @@
import Testing
import GRDB
@testable import GRDBDemo
struct PlayerListModelTests {
// MARK: - PlayerListModel.observePlayers tests
@Test(.timeLimit(.minutes(1)))
@MainActor func observation_started_after_player_creation() async throws {
// Given a PlayerListModel on a database that contains a player
let (appDatabase, _) = try makeEmptyTestDatabase()
var player = Player(name: "Arthur", score: 1000)
try appDatabase.savePlayer(&player)
let model = PlayerListModel(appDatabase: appDatabase)
// When we start observing the database
model.observePlayers()
// Then the model eventually fetches the player.
// We poll because we do not know when the model will update its players.
await pollUntil {
model.players.isEmpty == false
}
#expect(model.players == [player])
}
@Test(.timeLimit(.minutes(1)))
@MainActor func observation_started_before_player_creation() async throws {
// Given a PlayerListModel that observes a empty database
let (appDatabase, _) = try makeEmptyTestDatabase()
let model = PlayerListModel(appDatabase: appDatabase)
model.observePlayers()
// When we insert a player
var player = Player(name: "Arthur", score: 1000)
try appDatabase.savePlayer(&player)
// Then the model eventually fetches the player.
// We poll because we do not know when the model will update its players.
await pollUntil {
model.players.isEmpty == false
}
#expect(model.players == [player])
}
@Test
@MainActor func test_deleteAllPlayers_deletes_players_in_the_database() async throws {
// Given a PlayerListModel on a database that contains a player
let (appDatabase, dbQueue) = try makeEmptyTestDatabase()
var player = Player(name: "Arthur", score: 1000)
try appDatabase.savePlayer(&player)
let model = PlayerListModel(appDatabase: appDatabase)
// When we delete all players
try model.deleteAllPlayers()
// Then the database is empty.
let playerCount = try await dbQueue.read { db in
try Player.fetchCount(db)
}
#expect(playerCount == 0)
}
/// Returns an `AppDatabase`, and its underlying database connection.
private func makeEmptyTestDatabase() throws -> (AppDatabase, DatabaseQueue) {
let config = AppDatabase.makeConfiguration()
let dbQueue = try DatabaseQueue(configuration: config)
let appDatabase = try AppDatabase(dbQueue)
return (appDatabase, dbQueue)
}
/// Convenience method that loops until a condition is met.
private func pollUntil(condition: @escaping @MainActor () async -> Bool) async {
await confirmation { confirmation in
while true {
if await condition() {
confirmation()
return
} else {
await Task.yield()
}
}
}
}
}