Skip to content

Commit

Permalink
Complete #766: use json objects in DatabaseDateComponents tests
Browse files Browse the repository at this point in the history
  • Loading branch information
groue committed Apr 22, 2020
1 parent 1d760ff commit 132d01f
Showing 1 changed file with 22 additions and 19 deletions.
41 changes: 22 additions & 19 deletions Tests/GRDBTests/FoundationDateComponentsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -507,26 +507,29 @@ class FoundationDateComponentsTests : GRDBTestCase {
XCTAssertTrue(databaseDateComponents == nil)
}

func testJSONEncodingOfDatabaseDateComponents() {
let year = 2018
let month = 12
let day = 31
let dbDateComponents = DatabaseDateComponents(
DateComponents(year: year, month: month, day: day, hour: nil, minute: nil, second: nil, nanosecond: nil),
format: .YMD)
let encoded = try! JSONEncoder().encode(dbDateComponents)
XCTAssertEqual(String(data: encoded, encoding: .utf8)!, "\"\(year)-\(month)-\(day)\"")
func testJSONEncodingOfDatabaseDateComponents() throws {
// Encoding root string is not suppported by all system version: use an object
struct Record: Encodable {
var date: DatabaseDateComponents
}
let record = Record(date: DatabaseDateComponents(DateComponents(year: 2018, month: 12, day: 31), format: .YMD))
let jsonData = try JSONEncoder().encode(record)
let json = String(data: jsonData, encoding: .utf8)!
XCTAssertEqual(json, """
{"date":"2018-12-31"}
""")
}

func testJSONDecodingOfDatabaseDateComponents() {
let year = 2018
let month = 12
let day = 31
let dbDateComponents = DatabaseDateComponents(
DateComponents(year: year, month: month, day: day, hour: nil, minute: nil, second: nil, nanosecond: nil),
format: .YMD)
let json = "\"\(year)-\(month)-\(day)\"".data(using: .utf8)!
let decodedDatabaseDateComponents = try! JSONDecoder().decode(DatabaseDateComponents.self, from: json)
XCTAssertEqual(decodedDatabaseDateComponents.dateComponents, dbDateComponents.dateComponents)
func testJSONDecodingOfDatabaseDateComponents() throws {
// Decoding root string is not suppported by all system version: use an object
struct Record: Decodable {
var date: DatabaseDateComponents
}
let json = """
{"date":"2018-12-31"}
"""
let record = try JSONDecoder().decode(Record.self, from: json.data(using: .utf8)!)
XCTAssertEqual(record.date.format, .YMD)
XCTAssertEqual(record.date.dateComponents, DateComponents(year: 2018, month: 12, day: 31))
}
}

0 comments on commit 132d01f

Please sign in to comment.