Elgant HTML Parser in Swift.
import Foundation
import XCTest
@testableimport Creak
classHtmlNodeTest:BaseTest{func testInnerHtml(){letdiv=Tag(name:"div")
div.setAttributes(["class":AttrValue("all")])leta=Tag(name:"a")
a.setAttributes(["href":AttrValue("http://google.com", doubleQuote:false)])letbr=Tag(name:"br")
br.selfClosing =trueletparent=HtmlNode(tag: div)letchilda=HtmlNode(tag: a)letchildbr=HtmlNode(tag: br)
parent.addChild(childa)
parent.addChild(childbr)
childa.addChild(TextNode(text:"link"))XCTAssertEqual("<a href='http://google.com'>link</a><br />", parent.innerHtml())
// test cache
XCTAssertEqual("<a href='http://google.com'>link</a><br />", parent.innerHtml())}func testOuterHtml(){letdiv=Tag(name:"div")
div.setAttributes(["class":AttrValue("all")])leta=Tag(name:"a")
a.setAttributes(["href":AttrValue("http://google.com", doubleQuote:false)])letbr=Tag(name:"br")
br.selfClosing =trueletparent=HtmlNode(tag: div)letchilda=HtmlNode(tag: a)letchildbr=HtmlNode(tag: br)
parent.addChild(childa)
parent.addChild(childbr)
childa.addChild(TextNode(text:"link"))XCTAssertEqual("<div class=\"all\"><a href='http://google.com'>link</a><br /></div>", parent.outerHtml())
// test cache
XCTAssertEqual("<div class=\"all\"><a href='http://google.com'>link</a><br /></div>", parent.outerHtml())}func testOuterHtmlEmpty(){leta=Tag(name:"a")
a.setAttributes(["href":AttrValue("http://google.com", doubleQuote:false)])letnode=HtmlNode(tag: a)XCTAssertEqual("<a href='http://google.com'></a>", node.outerHtml())}func testOuterHtmlNoValueAttribute(){letdiv=Tag(name:"div")
div.setAttributes(["class":AttrValue("all")])leta=Tag(name:"a")
a.setAttributes(["href":AttrValue("http://google.com", doubleQuote:false)])letbr=Tag(name:"br")
br.selfClosing =trueletparent=HtmlNode(tag: div)letchilda=HtmlNode(tag: a)
childa.setAttribute("ui-view", attrValue:AttrValue(nil))letchildbr=HtmlNode(tag: br)
parent.addChild(childa)
parent.addChild(childbr)
childa.addChild(TextNode(text:"link"))XCTAssertEqual("<div class=\"all\"><a href='http://google.com' ui-view>link</a><br /></div>", parent.outerHtml())}func testText(){leta=Tag(name:"a")letnode=HtmlNode(tag: a)
node.addChild(TextNode(text:"link"))XCTAssertEqual("link", node.text())
// test cache
XCTAssertEqual("link", node.text())}func testTextLookInChildren(){letp=HtmlNode(tag:"p")leta=HtmlNode(tag:"a")
p.addChild(TextNode(text:"Please "))
a.addChild(TextNode(text:"click me"))
p.addChild(a)
p.addChild(TextNode(text:"!"))XCTAssertEqual("Please click me!", p.textWithChildren(true))}func testGetAttribute(){letnode=HtmlNode(tag:"a")
node.tag.setAttributes(["href":AttrValue("http://google.com", doubleQuote:false),"class":AttrValue("outerlink rounded", doubleQuote:true)])XCTAssertEqual("outerlink rounded", node.attribute("class"))}}