Skip to content

Commit

Permalink
fix: json tests (due to a swift upgrade)
Browse files Browse the repository at this point in the history
  • Loading branch information
nathanfallet committed Feb 23, 2024
1 parent 0c68b99 commit 5bfaddf
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
10 changes: 10 additions & 0 deletions Tests/SQLiteTests/TestHelpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,16 @@ func assertSQL(_ expression1: @autoclosure () -> String, _ expression2: @autoclo
XCTAssertEqual(expression1(), expression2().asSQL(), file: file, line: line)
}

func extractAndReplace(_ value: String, regex: String, with replacement: String) -> (String, String) {
// We cannot use `Regex` because it is not available before iOS 16 :(
let regex = try! NSRegularExpression(pattern: regex)
let valueRange = NSRange(location: 0, length: value.utf16.count)
let match = regex.firstMatch(in: value, options: [], range: valueRange)!.range
let range = Range(match, in: value)!
let extractedValue = String(value[range])
return (value.replacingCharacters(in: range, with: replacement), extractedValue)
}

let table = Table("table")
let qualifiedTable = Table("table", database: "main")
let virtualTable = VirtualTable("virtual_table")
Expand Down
15 changes: 12 additions & 3 deletions Tests/SQLiteTests/Typed/QueryTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -364,13 +364,22 @@ class QueryTests: XCTestCase {
let insert = try emails.insert(value)
let encodedJSON = try JSONEncoder().encode(value1)
let encodedJSONString = String(data: encodedJSON, encoding: .utf8)!
assertSQL(

let expectedSQL =
"""
INSERT INTO \"emails\" (\"int\", \"string\", \"bool\", \"float\", \"double\", \"date\", \"uuid\", \"optional\",
\"sub\") VALUES (1, '2', 1, 3.0, 4.0, '1970-01-01T00:00:00.000', 'E621E1F8-C36C-495A-93FC-0C247A3E6E5F',
'optional', '\(encodedJSONString)')
""".replacingOccurrences(of: "\n", with: ""),
insert
""".replacingOccurrences(of: "\n", with: "")

// As JSON serialization gives a different result each time, we extract JSON and compare it by deserializing it
// and keep comparing the query but with the json replaced by the `JSON` string
let (expectedQuery, expectedJSON) = extractAndReplace(expectedSQL, regex: "\\{.*\\}", with: "JSON")
let (actualQuery, actualJSON) = extractAndReplace(insert.asSQL(), regex: "\\{.*\\}", with: "JSON")
XCTAssertEqual(expectedQuery, actualQuery)
XCTAssertEqual(
try JSONDecoder().decode(TestCodable.self, from: expectedJSON.data(using: .utf8)!),
try JSONDecoder().decode(TestCodable.self, from: actualJSON.data(using: .utf8)!)
)
}
#endif
Expand Down

0 comments on commit 5bfaddf

Please sign in to comment.