Skip to content

Commit 5bfaddf

Browse files
committed
fix: json tests (due to a swift upgrade)
1 parent 0c68b99 commit 5bfaddf

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

Tests/SQLiteTests/TestHelpers.swift

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,16 @@ func assertSQL(_ expression1: @autoclosure () -> String, _ expression2: @autoclo
105105
XCTAssertEqual(expression1(), expression2().asSQL(), file: file, line: line)
106106
}
107107

108+
func extractAndReplace(_ value: String, regex: String, with replacement: String) -> (String, String) {
109+
// We cannot use `Regex` because it is not available before iOS 16 :(
110+
let regex = try! NSRegularExpression(pattern: regex)
111+
let valueRange = NSRange(location: 0, length: value.utf16.count)
112+
let match = regex.firstMatch(in: value, options: [], range: valueRange)!.range
113+
let range = Range(match, in: value)!
114+
let extractedValue = String(value[range])
115+
return (value.replacingCharacters(in: range, with: replacement), extractedValue)
116+
}
117+
108118
let table = Table("table")
109119
let qualifiedTable = Table("table", database: "main")
110120
let virtualTable = VirtualTable("virtual_table")

Tests/SQLiteTests/Typed/QueryTests.swift

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -364,13 +364,22 @@ class QueryTests: XCTestCase {
364364
let insert = try emails.insert(value)
365365
let encodedJSON = try JSONEncoder().encode(value1)
366366
let encodedJSONString = String(data: encodedJSON, encoding: .utf8)!
367-
assertSQL(
367+
368+
let expectedSQL =
368369
"""
369370
INSERT INTO \"emails\" (\"int\", \"string\", \"bool\", \"float\", \"double\", \"date\", \"uuid\", \"optional\",
370371
\"sub\") VALUES (1, '2', 1, 3.0, 4.0, '1970-01-01T00:00:00.000', 'E621E1F8-C36C-495A-93FC-0C247A3E6E5F',
371372
'optional', '\(encodedJSONString)')
372-
""".replacingOccurrences(of: "\n", with: ""),
373-
insert
373+
""".replacingOccurrences(of: "\n", with: "")
374+
375+
// As JSON serialization gives a different result each time, we extract JSON and compare it by deserializing it
376+
// and keep comparing the query but with the json replaced by the `JSON` string
377+
let (expectedQuery, expectedJSON) = extractAndReplace(expectedSQL, regex: "\\{.*\\}", with: "JSON")
378+
let (actualQuery, actualJSON) = extractAndReplace(insert.asSQL(), regex: "\\{.*\\}", with: "JSON")
379+
XCTAssertEqual(expectedQuery, actualQuery)
380+
XCTAssertEqual(
381+
try JSONDecoder().decode(TestCodable.self, from: expectedJSON.data(using: .utf8)!),
382+
try JSONDecoder().decode(TestCodable.self, from: actualJSON.data(using: .utf8)!)
374383
)
375384
}
376385
#endif

0 commit comments

Comments
 (0)