", with: " ", options: options)
preflight = preflight.replacingOccurrences(of: "|?div>|
|", with: "\n", options: options)
preflight = preflight.removingTagAndContents("script")
preflight = preflight.removingTagAndContents("style")
let preflightCount = preflight.count
let maxChars = maxCharacters ?? preflightCount
var s = String()
s.reserveCapacity(min(maxChars, preflightCount))
var lastCharacterWasSpace = false
var charactersAdded = 0
var level = 0
for char in preflight {
if char == "<" {
level += 1
} else if char == ">" {
level -= 1
} else if level == 0 {
if char == " " || char == "\r" || char == "\t" || char == "\n" {
if lastCharacterWasSpace {
continue
}
lastCharacterWasSpace = true
s.append(" ")
} else {
lastCharacterWasSpace = false
s.append(char)
}
charactersAdded += 1
if charactersAdded >= maxChars {
break
}
}
}
return s
}
}
final class StripHTMLTests: XCTestCase {
func testStrippingHTMLBasic() {
let html = "
Hello world!
"
let result = html.strippingHTML()
XCTAssertEqual(result, "Hello world!")
}
func testStrippingHTMLWithScript() {
let html = "Before
After
"
let result = html.strippingHTML()
XCTAssertEqual(result, "Before After")
}
func testStrippingHTMLWithStyle() {
let html = "Content
More
"
let result = html.strippingHTML()
XCTAssertEqual(result, "Content More")
}
func testStrippingHTMLWithMaxCharacters() {
let html = "This is a long piece of text that should be truncated at some point.
"
let result = html.strippingHTML(maxCharacters: 20)
XCTAssertLessThanOrEqual(result.count, 20)
XCTAssertEqual(result, "This is a long piece")
}
func testStrippingHTMLWithUTF8() {
let html = "Hello 世界 🌍
"
let result = html.strippingHTML()
XCTAssertEqual(result, "Hello 世界 🌍")
}
func testStrippingHTMLWhitespaceCollapsing() {
let html = "Too many\n\n\nspaces
"
let result = html.strippingHTML()
XCTAssertFalse(result.contains(" "))
XCTAssertEqual(result, "Too many spaces")
}
// Commented out because this doesn’t need to run every time.
// Un-comment it when you want to compare legacy performance to C performance.
// func testStrippingHTMLPerformanceLegacySwift() {
// let html = """
//
// This is a test article with bold text and italic text.
//
//
// More content with links and other tags.
// Nested tags are common in HTML.
//
// """
//
// self.measure {
// for _ in 0..<1000 {
// let _ = html.legacyStrippingHTML(maxCharacters: 300)
// }
// }
// }
func testStrippingHTMLPerformance() {
let html = """
This is a test article with bold text and italic text.
More content with links and other tags.
Nested tags are common in HTML.
"""
self.measure {
for _ in 0..<1000 {
let _ = html.strippingHTML(maxCharacters: 300)
}
}
}
func testStrippingHTMLWithRealWorldHTML() throws {
let testFiles = ["daringfireball", "apple", "inessential", "scripting"]
for testFile in testFiles {
guard let url = Bundle.module.url(forResource: testFile, withExtension: "html", subdirectory: "Resources") else {
XCTFail("Could not find \(testFile).html")
return
}
let html = try String(contentsOf: url, encoding: .utf8)
// Test both implementations can process real-world HTML
let result = html.strippingHTML(maxCharacters: 300)
XCTAssertFalse(result.isEmpty, "\(testFile): Result should not be empty")
XCTAssertLessThanOrEqual(result.count, 300, "\(testFile): Result should respect maxCharacters")
XCTAssertFalse(result.contains("<"), "\(testFile): Result should not contain HTML tags")
XCTAssertFalse(result.contains("//"), "\(testFile): Should fully remove script content")
}
}
// Commented out because this doesn’t need to run every time.
// Un-comment it when you want to compare legacy performance to C performance.
// func testStrippingHTMLPerformanceRealWorldLegacySwift() throws {
// let testFiles = ["daringfireball", "apple", "inessential", "scripting"]
// var htmlFiles: [String] = []
//
// for testFile in testFiles {
// guard let url = Bundle.module.url(forResource: testFile, withExtension: "html", subdirectory: "Resources") else {
// XCTFail("Could not find \(testFile).html")
// return
// }
// let html = try String(contentsOf: url, encoding: .utf8)
// htmlFiles.append(html)
// }
//
// self.measure {
// for _ in 0..<100 {
// for html in htmlFiles {
// let _ = html.legacyStrippingHTML(maxCharacters: 300)
// }
// }
// }
// }
func testStrippingHTMLPerformanceRealWorld() throws {
let testFiles = ["daringfireball", "apple", "inessential", "scripting"]
var htmlFiles: [String] = []
for testFile in testFiles {
guard let url = Bundle.module.url(forResource: testFile, withExtension: "html", subdirectory: "Resources") else {
XCTFail("Could not find \(testFile).html")
return
}
let html = try String(contentsOf: url, encoding: .utf8)
htmlFiles.append(html)
}
self.measure {
for _ in 0..<100 {
for html in htmlFiles {
let _ = html.strippingHTML(maxCharacters: 300)
}
}
}
}
// Un-comment this to create the .txt files that contain the expected stripped-HTML results.
// func testRegenerateExpectedOutputFiles() throws {
// let testFiles = ["apple", "daringfireball", "inessential", "scripting"]
//
// for testFile in testFiles {
// guard let htmlURL = Bundle.module.url(forResource: testFile, withExtension: "html", subdirectory: "Resources") else {
// XCTFail("Could not find \(testFile).html")
// return
// }
//
// let html = try String(contentsOf: htmlURL, encoding: .utf8)
// let result = html.strippingHTML()
//
// print("\n=== \(testFile) ===")
// print("Result length: \(result.count) characters")
// print("First 200 chars: \(String(result.prefix(200)))")
//
// // Write to /tmp first, then user can copy to source
// let tmpPath = "/tmp/\(testFile).txt"
// try result.write(toFile: tmpPath, atomically: true, encoding: .utf8)
// print("Wrote to: \(tmpPath)")
// }
//
// print("\n\nTo update the expected output files, run:")
// print("cp /tmp/apple.txt Tests/RSCoreTests/Resources/")
// print("cp /tmp/daringfireball.txt Tests/RSCoreTests/Resources/")
// print("cp /tmp/inessential.txt Tests/RSCoreTests/Resources/")
// print("cp /tmp/scripting.txt Tests/RSCoreTests/Resources/")
// }
func testStrippingHTMLMatchesExpectedOutput() throws {
let testFiles = ["apple", "daringfireball", "inessential", "scripting"]
for testFile in testFiles {
guard let htmlURL = Bundle.module.url(forResource: testFile, withExtension: "html", subdirectory: "Resources") else {
XCTFail("Could not find \(testFile).html")
return
}
guard let txtURL = Bundle.module.url(forResource: testFile, withExtension: "txt", subdirectory: "Resources") else {
XCTFail("Could not find \(testFile).txt")
return
}
let html = try String(contentsOf: htmlURL, encoding: .utf8)
let expectedOutput = try String(contentsOf: txtURL, encoding: .utf8)
// Test implementation produces expected output
let result = html.strippingHTML()
XCTAssertEqual(result, expectedOutput, "\(testFile): Implementation should match expected output")
}
}
}