GRDBSnapshotTesting 0.3.0

GRDBSnapshotTesting 0.3.0

Sebastian Osiński 维护。



 
依赖
GRDB.swift~> 5
SnapshotTesting~> 1.8
 

  • SebastianOsinski

GRDBSnapshotTesting

Swift 5.2 Pod version License

SnapshotTesting 插件,用于测试 GRDB 数据库迁移。

它允许您轻松测试您的数据库模式和数据是否正确迁移。

特性

GRDBSnapshotTesting 创建表示您的数据库模式和数据的快照文件。

快照文件包含

  • 表定义
  • (如果存在)索引定义
  • (如果存在)触发器定义
  • (如果存在)视图定义
  • 所有表中的所有数据

示例快照文件

======== TABLES ========

CREATE TABLE "author" (
  "id" INTEGER PRIMARY KEY AUTOINCREMENT
  "name" TEXT NOT NULL
  "country" TEXT NOT NULL
  "lastUpdate" DATETIME
)

CREATE TABLE "book" (
  "id" INTEGER PRIMARY KEY AUTOINCREMENT
  "title" TEXT NOT NULL
  "authorId" INTEGER NOT NULL REFERENCES "author"("id") ON DELETE CASCADE
  "lastUpdate" DATETIME
)

======== DATA ========

## author
(1, "J.K. Rowling", "UK", NULL)
(2, "J.R.R. Tolkien", "UK", NULL)

## book
(1, "Harry Potter and the Philosopher\'s Stone", 1, NULL)
(2, "Harry Potter and the Chamber of Secrets", 1, NULL)
(3, "Harry Potter and the Prisoner of Azkaban", 1, NULL)
(4, "The Hobbit", 2, NULL)
(5, "The Fellowship of the Ring", 2, NULL)

用法

import XCTest
import SnapshotTesting
import GRDB
import GRDBSnapshotTesting

class DatabaseMigrationTests: XCTestCase {
  func testInitialMigration() throws {
    let db = DatabaseQueue()
    
    var migrator = DatabaseMigrator()
    migrator.registerMigration("v1", migrate: Migrations.firstMigration)
  
    try migrator.migrate(db)
    
    assertSnapshot(matching: db, as: .dbDump)
  }
}

首次运行时,上述测试将在您的数据库模式和内容中创建参考快照文件。

随后的运行将检查新创建的快照是否与预先记录的参考匹配。

GRDBSnapshotTesting 还包含了针对 GRDB 的一些扩展,使得您可以在不覆盖的情况下对预先记录的数据库文件进行迁移测试

class DatabaseMigrationTests: XCTestCase {
  func testSecondMigration() throws {
    // V1DatabaseWithData.sqlite is added to the testing target
    let path = Bundle(for: Self.self).path(forResource: "V1DatabaseWithData", ofType: "sqlite")!

    let db = DatabaseQueue.inMemoryDatabase(fromPath: path)
    
    var migrator = DatabaseMigrator()
    migrator.registerMigration("v2", migrate: Migrations.secondMigration)
  
    try migrator.migrate(db)
    
    assertSnapshot(matching: db, as: .dbDump)
  }
}

DatabaseQueue.inMemoryDatabase(fromPath:) 创建与给定路径的数据库文件相同的模式和数据的内存数据库。

这样,您可以创建具有边缘数据的多余数据库文件并彻底测试您的迁移。

安装

CocoaPods

Podfile 中将 pod 添加到你的测试目标

target 'MyAppTests' do
  pod 'GRDBSnapshotTesting', '~> 0.2'
end

Swift 包管理器

Package.swift 中将包添加到你的测试目标

 let package = Package(
     dependencies: [
+        .package(url: "https://github.com/SebastianOsinski/GRDBSnapshotTesting.git", ...)
     ],
     targets: [
         .testTarget(
             dependencies: [
+                "GRDBSnapshotTesting"
             ])
     ]
 )