-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathEncodeDecode.swift
More file actions
53 lines (41 loc) · 1.33 KB
/
EncodeDecode.swift
File metadata and controls
53 lines (41 loc) · 1.33 KB
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
//
// EncodeDecode.swift
// JSONAPITests
//
// Created by Mathew Polzin on 11/16/18.
//
import Foundation
import XCTest
let testDecoder = JSONDecoder()
let testEncoder: JSONEncoder = {
let encoder = JSONEncoder()
if #available(OSX 10.13, iOS 11.0, *) {
encoder.outputFormatting = .sortedKeys
}
#if os(Linux)
encoder.outputFormatting = .sortedKeys
#endif
return encoder
}()
func decoded<T: Decodable>(type: T.Type, data: Data) -> T {
return try! testDecoder.decode(T.self, from: data)
}
func decodedThrows<T: Decodable>(type: T.Type, data: Data) throws -> T {
return try testDecoder.decode(T.self, from: data)
}
func encoded<T: Encodable>(value: T) -> Data {
return try! testEncoder.encode(value)
}
/// A helper function that tests that decode() == decode().encode().decode().
/// If decoding is well tested and the above is true then encoding is well
/// tested.
func test_DecodeEncodeEquality<T: Codable & Equatable>(type: T.Type, data: Data) {
let entity = try? JSONDecoder().decode(T.self, from: data)
XCTAssertNotNil(entity)
guard let e = entity else { return }
let encodedEntity = try? JSONEncoder().encode(e)
XCTAssertNotNil(encodedEntity)
guard let ee = encodedEntity else { return }
// check that decoding ee results in e
XCTAssertEqual(try? JSONDecoder().decode(T.self, from: ee), e)
}