forked from vapor/postgres-nio
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPostgresJSONCodingTests.swift
61 lines (57 loc) · 2.35 KB
/
PostgresJSONCodingTests.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
import NIOCore
import XCTest
import PostgresNIO
class PostgresJSONCodingTests: XCTestCase {
// https://github.com/vapor/postgres-nio/issues/126
func testCustomJSONEncoder() {
let previousDefaultJSONEncoder = PostgresNIO._defaultJSONEncoder
defer {
PostgresNIO._defaultJSONEncoder = previousDefaultJSONEncoder
}
final class CustomJSONEncoder: PostgresJSONEncoder {
var didEncode = false
func encode<T>(_ value: T) throws -> Data where T : Encodable {
self.didEncode = true
return try JSONEncoder().encode(value)
}
}
struct Object: Codable {
var foo: Int
var bar: Int
}
let customJSONEncoder = CustomJSONEncoder()
PostgresNIO._defaultJSONEncoder = customJSONEncoder
XCTAssertNoThrow(try PostgresData(json: Object(foo: 1, bar: 2)))
XCTAssert(customJSONEncoder.didEncode)
let customJSONBEncoder = CustomJSONEncoder()
PostgresNIO._defaultJSONEncoder = customJSONBEncoder
XCTAssertNoThrow(try PostgresData(json: Object(foo: 1, bar: 2)))
XCTAssert(customJSONBEncoder.didEncode)
}
// https://github.com/vapor/postgres-nio/issues/126
func testCustomJSONDecoder() {
let previousDefaultJSONDecoder = PostgresNIO._defaultJSONDecoder
defer {
PostgresNIO._defaultJSONDecoder = previousDefaultJSONDecoder
}
final class CustomJSONDecoder: PostgresJSONDecoder {
var didDecode = false
func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable {
self.didDecode = true
return try JSONDecoder().decode(type, from: data)
}
}
struct Object: Codable {
var foo: Int
var bar: Int
}
let customJSONDecoder = CustomJSONDecoder()
PostgresNIO._defaultJSONDecoder = customJSONDecoder
XCTAssertNoThrow(try PostgresData(json: Object(foo: 1, bar: 2)).json(as: Object.self))
XCTAssert(customJSONDecoder.didDecode)
let customJSONBDecoder = CustomJSONDecoder()
PostgresNIO._defaultJSONDecoder = customJSONBDecoder
XCTAssertNoThrow(try PostgresData(json: Object(foo: 1, bar: 2)).json(as: Object.self))
XCTAssert(customJSONBDecoder.didDecode)
}
}