forked from CoreOffice/XMLCoder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EnumAssociatedValueTestSimple.swift
99 lines (88 loc) · 2.85 KB
/
EnumAssociatedValueTestSimple.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//
// EnumAssociatedValueTestSimple.swift
// XMLCoderTests
//
// Created by James Bean on 7/9/19.
//
import XCTest
import XMLCoder
private enum IntOrString {
case int(Int)
case string(String)
}
extension IntOrString: Codable {
enum CodingKeys: String, CodingKey {
case int
case string
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
switch self {
case let .int(value):
try container.encode(value, forKey: .int)
case let .string(value):
try container.encode(value, forKey: .string)
}
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
do {
self = .int(try container.decode(Int.self, forKey: .int))
} catch {
self = .string(try container.decode(String.self, forKey: .string))
}
}
}
extension IntOrString: Equatable {}
class EnumAssociatedValuesTest: XCTestCase {
func testIntOrStringIntDecoding() throws {
let xml = "<int>42</int>"
let result = try XMLDecoder().decode(IntOrString.self, from: xml.data(using: .utf8)!)
let expected = IntOrString.int(42)
XCTAssertEqual(result, expected)
}
func testIntOrStringStringDecoding() throws {
let xml = "<string>forty-two</string>"
let result = try XMLDecoder().decode(IntOrString.self, from: xml.data(using: .utf8)!)
let expected = IntOrString.string("forty-two")
XCTAssertEqual(result, expected)
}
func testIntOrStringArrayDecoding() throws {
let xml = """
<container>
<int>1</int>
<string>two</string>
<string>three</string>
<int>4</int>
<int>5</int>
</container>
"""
let result = try XMLDecoder().decode([IntOrString].self, from: xml.data(using: .utf8)!)
let expected: [IntOrString] = [
.int(1),
.string("two"),
.string("three"),
.int(4),
.int(5),
]
XCTAssertEqual(result, expected)
}
func testIntOrStringRoundTrip() throws {
let original = IntOrString.int(5)
let encoded = try XMLEncoder().encode(original, withRootKey: "container")
let decoded = try XMLDecoder().decode(IntOrString.self, from: encoded)
XCTAssertEqual(original, decoded)
}
func testIntOrStringArrayRoundTrip() throws {
let original: [IntOrString] = [
.int(1),
.string("two"),
.string("three"),
.int(4),
.int(5),
]
let encoded = try XMLEncoder().encode(original, withRootKey: "container")
let decoded = try XMLDecoder().decode([IntOrString].self, from: encoded)
XCTAssertEqual(original, decoded)
}
}