HTMLStreamer/Tests/HTMLStreamerTests/TextConverterTests.swift

67 lines
2.5 KiB
Swift
Raw Normal View History

2023-12-23 01:30:29 +00:00
//
// TextConverterTests.swift
//
//
// Created by Shadowfacts on 12/22/23.
//
import XCTest
@testable import HTMLStreamer
final class TextConverterTests: XCTestCase {
private func convert(_ html: String, configuration: TextConverterConfiguration = .init()) -> String {
convert(html, configuration: configuration, callbacks: DefaultCallbacks.self)
}
private func convert<Callbacks: HTMLConversionCallbacks>(_ html: String, configuration: TextConverterConfiguration = .init(), callbacks _: Callbacks.Type = Callbacks.self) -> String {
var converter = TextConverter<Callbacks>(configuration: configuration)
return converter.convert(html: html)
}
func testConvertBR() {
XCTAssertEqual(convert("a<br>b"), "a\nb")
XCTAssertEqual(convert("a<br />b"), "a\nb")
}
func testConvertA() {
XCTAssertEqual(convert("<a href='https://example.com'>link</a>"), "link")
}
func testIncorrectNesting() {
XCTAssertEqual(convert("<strong>bold <em>both</strong> italic</em>"), "bold both italic")
}
func testTextAfterBlockElement() {
XCTAssertEqual(convert("<blockquote>wee</blockquote>after"), "wee\n\nafter")
XCTAssertEqual(convert("<blockquote>wee</blockquote>after", configuration: .init(insertNewlines: false)), "wee after")
2023-12-23 01:30:29 +00:00
}
func testMultipleBlockElements() {
XCTAssertEqual(convert("<blockquote>a</blockquote><blockquote>b</blockquote>"), "a\n\nb")
XCTAssertEqual(convert("<blockquote>a</blockquote><blockquote>b</blockquote>", configuration: .init(insertNewlines: false)), "a b")
2023-12-23 01:30:29 +00:00
}
func testElementActionCallback() {
struct Callbacks: HTMLConversionCallbacks {
static func elementAction(name: String, attributes: [Attribute]) -> ElementAction {
let clazz = attributes.attributeValue(for: "class")
if clazz == "invisible" {
return .skip
} else if clazz == "ellipsis" {
return .replace("")
} else {
return .default
}
}
}
let skipped = convert("<span class='invisible'>test</span>", callbacks: Callbacks.self)
XCTAssertEqual(skipped, "")
let skipNested = convert("<span class='invisible'><b>test</b></span>", callbacks: Callbacks.self)
XCTAssertEqual(skipNested, "")
let replaced = convert("<span class='ellipsis'>test</span>", callbacks: Callbacks.self)
XCTAssertEqual(replaced, "")
}
}