Skip to content

Commit

Permalink
Merge pull request #1 from tachyonics/master
Browse files Browse the repository at this point in the history
Handle empty XML elements and unit test.
  • Loading branch information
rafiki270 authored Aug 1, 2018
2 parents 344c27d + 6270a69 commit a4475f1
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 6 deletions.
4 changes: 4 additions & 0 deletions Sources/XMLCoding/XMLStackParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,10 @@ internal class _XMLElement {
} else {
node[childElement.key] = newValue
}
// if the node is empty and there is no existing value
} else if node[childElement.key] == nil {
// an empty node can be treated as an empty dictionary
node[childElement.key] = [:]
}
}
}
Expand Down
72 changes: 66 additions & 6 deletions Tests/XMLCodingTests/XMLParsingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,75 @@ import XCTest


class XMLParsingTests: XCTestCase {
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct
// results.
// XCTAssertEqual(XMLParsing().text, "Hello, World!")
struct Result: Codable {
let message: String?

enum CodingKeys: String, CodingKey {
case message = "Message"
}
}

struct Metadata: Codable {
let id: String

enum CodingKeys: String, CodingKey {
case id = "Id"
}
}

struct Response: Codable {
let result: Result
let metadata: Metadata

enum CodingKeys: String, CodingKey {
case result = "Result"
case metadata = "Metadata"
}
}

func testEmptyElement() throws {
let inputString = """
<Response>
<Result/>
<Metadata>
<Id>id</Id>
</Metadata>
</Response>
"""

guard let inputData = inputString.data(using: .utf8) else {
return XCTFail()
}

let response = try XMLDecoder().decode(Response.self, from: inputData)

XCTAssertNil(response.result.message)
}

func testEmptyElementNotEffectingPreviousElement() throws {
let inputString = """
<Response>
<Result>
<Message>message</Message>
</Result>
<Result/>
<Metadata>
<Id>id</Id>
</Metadata>
</Response>
"""

guard let inputData = inputString.data(using: .utf8) else {
return XCTFail()
}

let response = try XMLDecoder().decode(Response.self, from: inputData)

XCTAssertEqual("message", response.result.message)
}

static var allTests = [
("testExample", testExample),
("testEmptyElement", testEmptyElement),
("testEmptyElementNotEffectingPreviousElement", testEmptyElementNotEffectingPreviousElement),
]
}

0 comments on commit a4475f1

Please sign in to comment.