-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
TestSwiftData.swift
166 lines (138 loc) · 6.44 KB
/
TestSwiftData.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
@testable import Storage
@testable import Client
import XCTest
// TODO: rewrite this test to not use BrowserSchema. It used to use HistoryTable…
class TestSwiftData: XCTestCase {
var swiftData: SwiftData?
var urlCounter = 1
var testDB: String!
override func setUp() {
let files = MockFiles()
do {
try files.remove("testSwiftData.db")
} catch _ {
}
testDB = (try! (files.getAndEnsureDirectory() as NSString)).appendingPathComponent("testSwiftData.db")
swiftData = SwiftData(filename: testDB, schema: BrowserSchema(), files: files)
let table = BrowserSchema()
// Ensure static flags match expected values.
XCTAssert(SwiftData.EnableWAL, "WAL enabled")
XCTAssertNil(addSite(table, url: "http://url0", title: "title0"), "Added url0.")
}
override func tearDown() {
// Restore static flags to their default values.
SwiftData.EnableWAL = true
}
func testNoWAL() {
SwiftData.EnableWAL = false
let error = writeDuringRead()
XCTAssertNil(error, "Insertion succeeded")
}
func testDefaultSettings() {
SwiftData.EnableWAL = true
let error = writeDuringRead()
XCTAssertNil(error, "Insertion succeeded")
}
func testBusyTimeout() {
SwiftData.EnableWAL = false
let error = writeDuringRead(closeTimeout: 1)
XCTAssertNil(error, "Insertion succeeded")
}
func testFilledCursor() {
SwiftData.EnableWAL = false
XCTAssertNil(writeDuringRead(true), "Insertion succeeded")
}
fileprivate func writeDuringRead(_ safeQuery: Bool = false, closeTimeout: UInt64? = nil) -> MaybeErrorType? {
// Query the database and hold the cursor.
var c: Cursor<SDRow>!
let result = swiftData!.withConnection(SwiftData.Flags.readOnly) { db -> Void in
if safeQuery {
c = db.executeQuery("SELECT * FROM history", factory: { $0 })
} else {
c = db.executeQueryUnsafe("SELECT * FROM history", factory: { $0 }, withArgs: nil)
}
return ()
}
XCTAssertNil(result.value.failureValue, "Queried database")
// If we have a live cursor, this will step to the first result.
// Stepping through a prepared statement without resetting it will lock the connection.
let _ = c[0]
// Close the cursor after a delay if there's a close timeout set.
if let closeTimeout = closeTimeout {
let queue = DispatchQueue(label: "cursor timeout queue", attributes: [])
queue.asyncAfter(deadline: DispatchTime.now() + Double(Int64(closeTimeout * NSEC_PER_SEC)) / Double(NSEC_PER_SEC)) {
c.close()
}
}
defer { urlCounter += 1 }
return addSite(BrowserSchema(), url: "http://url/\(urlCounter)", title: "title\(urlCounter)")
}
fileprivate func addSite(_ table: BrowserSchema, url: String, title: String) -> MaybeErrorType? {
let result = swiftData!.withConnection(SwiftData.Flags.readWrite) { connection -> Void in
let args: Args = [Bytes.generateGUID(), url, title]
try connection.executeChange("INSERT INTO history (guid, url, title, is_deleted, should_upload) VALUES (?, ?, ?, 0, 0)", withArgs: args)
}
return result.value.failureValue
}
func testNulls() {
guard let db = swiftData else {
XCTFail("DB not open")
return
}
db.withConnection(SwiftData.Flags.readWriteCreate) { db in
try! db.executeChange("CREATE TABLE foo ( bar TEXT, baz INTEGER )")
try! db.executeChange("INSERT INTO foo VALUES (NULL, 1), ('here', 2)")
let shouldBeString = db.executeQuery("SELECT bar FROM foo WHERE baz = 2", factory: { (row) in row["bar"] }).asArray()[0]
guard let s = shouldBeString as? String else {
XCTFail("Couldn't cast.")
return
}
XCTAssertEqual(s, "here")
let shouldBeNull = db.executeQuery("SELECT bar FROM foo WHERE baz = 1", factory: { (row) in row["bar"] }).asArray()[0]
XCTAssertNil(shouldBeNull as? String)
XCTAssertNil(shouldBeNull)
}.succeeded()
}
func testArrayCursor() {
let data = ["One", "Two", "Three"]
let t = ArrayCursor<String>(data: data)
// Test subscript access
XCTAssertNil(t[-1], "Subscript -1 returns nil")
XCTAssertEqual(t[0]!, "One", "Subscript zero returns the correct data")
XCTAssertEqual(t[1]!, "Two", "Subscript one returns the correct data")
XCTAssertEqual(t[2]!, "Three", "Subscript two returns the correct data")
XCTAssertNil(t[3], "Subscript three returns nil")
// Test status data with default initializer
XCTAssertEqual(t.status, CursorStatus.success, "Cursor as correct status")
XCTAssertEqual(t.statusMessage, "Success", "Cursor as correct status message")
XCTAssertEqual(t.count, 3, "Cursor as correct size")
// Test generator access
var i = 0
for s in t {
XCTAssertEqual(s!, data[i], "Subscript zero returns the correct data")
i += 1
}
// Test creating a failed cursor
let t2 = ArrayCursor<String>(data: data, status: CursorStatus.failure, statusMessage: "Custom status message")
XCTAssertEqual(t2.status, CursorStatus.failure, "Cursor as correct status")
XCTAssertEqual(t2.statusMessage, "Custom status message", "Cursor as correct status message")
XCTAssertEqual(t2.count, 0, "Cursor as correct size")
// Test subscript access return nil for a failed cursor
XCTAssertNil(t2[0], "Subscript zero returns nil if failure")
XCTAssertNil(t2[1], "Subscript one returns nil if failure")
XCTAssertNil(t2[2], "Subscript two returns nil if failure")
XCTAssertNil(t2[3], "Subscript three returns nil if failure")
// Test that generator doesn't work with failed cursors
var ran = false
for s in t2 {
print("Got \(s ?? "nil")", terminator: "\n")
ran = true
}
XCTAssertFalse(ran, "for...in didn't run for failed cursor")
}
}