Tests/OrgAppTests/RichTextExportTests.swift
61 lines · 3125 bytes
1import AppKit
2import Foundation
3import OrgCore
4import Testing
5@testable import OrgApp
6
7@MainActor
8struct RichTextExportTests {
9 static let html = HTMLExport.page("""
10 #+TITLE: Report
11 * Results
12 Some *bold* text.
13 | Name | Count |
14 |------+-------|
15 | a | 1 |
16 - first
17 - second
18 #+begin_src sh
19 echo hi
20 #+end_src
21 """, fallbackTitle: "t")
22
23 @Test func wordAndRTFReadBackWithTheText() throws {
24 let text = try RichTextExport.attributed(html: Self.html, directory: nil)
25 for data in [try RichTextExport.docx(text), try RichTextExport.rtf(text)] {
26 let back = try NSAttributedString(data: data, options: [:], documentAttributes: nil).string
27 #expect(back.contains("Report") && back.contains("bold") && back.contains("Count") && back.contains("second") && back.contains("echo hi"), "\(back)")
28 }
29 // Word gets a real table, which the system's own writer leaves out.
30 let xml = String(decoding: try RichTextExport.docx(text), as: UTF8.self)
31 #expect(xml.contains("<w:tbl>") && xml.components(separatedBy: "<w:tc>").count - 1 == 4)
32 // Bold survives.
33 let bold = (text.string as NSString).range(of: "bold")
34 let font = text.attribute(.font, at: bold.location, effectiveRange: nil) as? NSFont
35 #expect(font?.fontDescriptor.symbolicTraits.contains(.bold) == true)
36 }
37
38 /// As iOS writes Word, whose HTML import keeps no tables: the tables from the HTML.
39 @Test func wordTablesFromTheHTML() throws {
40 let (page, tables) = RichTextExport.extractingTables(Self.html)
41 #expect(tables.count == 1 && !page.contains("<table") && page.contains(DocxWriter.marker(0)))
42 #expect(tables[0].components(separatedBy: "<w:tc>").count - 1 == 4)
43 #expect(tables[0].contains("<w:b/></w:rPr><w:t xml:space=\"preserve\">Name</w:t>"))
44 #expect(tables[0].contains("<w:r><w:rPr></w:rPr><w:t xml:space=\"preserve\">1</w:t>"))
45 let data = DocxWriter.data(from: try RichTextExport.attributed(html: page, directory: nil), tables: tables)
46 let xml = String(decoding: data, as: UTF8.self)
47 #expect(xml.contains("<w:tbl>") && !xml.contains("\u{E000}"))
48 let back = try NSAttributedString(data: data, options: [:], documentAttributes: nil).string
49 #expect(back.contains("Report") && back.contains("Count") && back.contains("second"), "\(back)")
50 #expect(RichTextExport.decode("a &lt; éA "") == "a < éA \"")
51 }
52
53 @Test func plainTextAndDarkSystemsStayReadable() throws {
54 let text = try RichTextExport.attributed(html: Self.html, directory: nil)
55 let plain = RichTextExport.plain(text)
56 #expect(plain.hasPrefix("Report") && plain.contains("Some bold text.") && plain.hasSuffix("echo hi\n"))
57 // The colors are the light ones whatever the appearance.
58 let color = text.attribute(.foregroundColor, at: 0, effectiveRange: nil) as? NSColor
59 #expect((color?.usingColorSpace(.sRGB)?.brightnessComponent ?? 0) < 0.5)
60 }
61}