|
| 1 | +// |
| 2 | +// CompositeChoiceTests.swift |
| 3 | +// XMLCoderTests |
| 4 | +// |
| 5 | +// Created by James Bean on 7/15/19. |
| 6 | +// |
| 7 | + |
| 8 | +import XCTest |
| 9 | +import XMLCoder |
| 10 | + |
| 11 | +private struct IntWrapper: Codable, Equatable { |
| 12 | + let wrapped: Int |
| 13 | +} |
| 14 | + |
| 15 | +private struct StringWrapper: Codable, Equatable { |
| 16 | + let wrapped: String |
| 17 | +} |
| 18 | + |
| 19 | +private enum IntOrStringWrapper: Equatable { |
| 20 | + case int(IntWrapper) |
| 21 | + case string(StringWrapper) |
| 22 | +} |
| 23 | + |
| 24 | +extension IntOrStringWrapper: Codable { |
| 25 | + enum CodingKeys: String, CodingKey { |
| 26 | + case int |
| 27 | + case string |
| 28 | + } |
| 29 | + |
| 30 | + init(from decoder: Decoder) throws { |
| 31 | + let container = try decoder.container(keyedBy: CodingKeys.self) |
| 32 | + do { |
| 33 | + self = .int(try container.decode(IntWrapper.self, forKey: .int)) |
| 34 | + } catch { |
| 35 | + self = .string(try container.decode(StringWrapper.self, forKey: .string)) |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + func encode(to encoder: Encoder) throws { |
| 40 | + var container = encoder.container(keyedBy: CodingKeys.self) |
| 41 | + switch self { |
| 42 | + case let .int(value): |
| 43 | + try container.encode(value, forKey: .int) |
| 44 | + case let .string(value): |
| 45 | + try container.encode(value, forKey: .string) |
| 46 | + } |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +class CompositeChoiceTests: XCTestCase { |
| 51 | + func testIntOrStringWrapper() throws { |
| 52 | + let xml = """ |
| 53 | + <container> |
| 54 | + <string> |
| 55 | + <wrapped>A Word About Woke Times</wrapped> |
| 56 | + </string> |
| 57 | + </container> |
| 58 | + """ |
| 59 | + let result = try XMLDecoder().decode(IntOrStringWrapper.self, from: xml.data(using: .utf8)!) |
| 60 | + let expected = IntOrStringWrapper.string(StringWrapper(wrapped: "A Word About Woke Times")) |
| 61 | + XCTAssertEqual(result, expected) |
| 62 | + } |
| 63 | + |
| 64 | + func testArrayOfIntOrStringWrappers() throws { |
| 65 | + let xml = """ |
| 66 | + <container> |
| 67 | + <string> |
| 68 | + <wrapped>A Word About Woke Times</wrapped> |
| 69 | + </string> |
| 70 | + <int> |
| 71 | + <wrapped>9000</wrapped> |
| 72 | + </int> |
| 73 | + <string> |
| 74 | + <wrapped>A Word About Woke Tomes</wrapped> |
| 75 | + </string> |
| 76 | + </container> |
| 77 | + """ |
| 78 | + let result = try XMLDecoder().decode([IntOrStringWrapper].self, from: xml.data(using: .utf8)!) |
| 79 | + let expected: [IntOrStringWrapper] = [ |
| 80 | + .string(StringWrapper(wrapped: "A Word About Woke Times")), |
| 81 | + .int(IntWrapper(wrapped: 9000)), |
| 82 | + .string(StringWrapper(wrapped: "A Word About Woke Tomes")), |
| 83 | + ] |
| 84 | + XCTAssertEqual(result, expected) |
| 85 | + } |
| 86 | +} |
0 commit comments