forked from CoreOffice/XMLCoder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
OptionalTests.swift
76 lines (59 loc) · 1.91 KB
/
OptionalTests.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//
// OptionalTests.swift
// XMLCoder
//
// Created by Max Desiatov on 24/01/2019.
//
import XCTest
@testable import XMLCoder
private struct ExpectNonNil: Decodable, Equatable {
var optional: String?
private enum CodingKeys: String, CodingKey {
case optional
}
init() {}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if container.contains(.optional) {
optional = try container.decode(String.self, forKey: .optional)
}
}
}
private struct ExpectOptional: Decodable, Equatable {
var optional: String?
private enum CodingKeys: String, CodingKey {
case optional
}
init() {}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if container.contains(.optional) {
optional = try container.decode(String?.self, forKey: .optional)
}
}
}
private struct DecodeIfPresent: Decodable, Equatable {
var optional: String?
private enum CodingKeys: String, CodingKey {
case optional
}
init() {}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
optional = try container.decodeIfPresent(String.self, forKey: .optional)
}
}
class OptionalTests: XCTestCase {
func testMissing() throws {
let decoder = XMLDecoder()
let xml = """
<container><optional></optional></container>
""".data(using: .utf8)!
XCTAssertThrowsError(try decoder.decode(ExpectNonNil.self,
from: xml))
let decoded1 = try decoder.decode(ExpectOptional.self, from: xml)
XCTAssertEqual(decoded1, ExpectOptional())
let decoded2 = try decoder.decode(DecodeIfPresent.self, from: xml)
XCTAssertEqual(decoded2, DecodeIfPresent())
}
}