Tests/OrgAppTests/PrintingTests.swift
179 lines · 9174 bytes
13 symbols in this file
1import Foundation
2import OrgCore
3import OrgDocument
4import OrgMathJax
5import PDFKit
6import Testing
7@testable import OrgApp
8
9/// What Print… sends to the printer: the page PDF export makes of the file, the subtree or the
10/// selection, and the agenda as shown.
11@MainActor
12struct PrintingTests {
13 init() { PDFExport.mathJaxURL = OrgMathJax.script }
14
15 static let text = "#+TITLE: Notes\n* One\nFirst body.\n** Inner\nInner body.\n* Two\nSecond body.\n"
16
17 func page(_ scope: PrintScope, text: String = Self.text) -> String? {
18 Printing.page(text, path: "/notes/a.org", scope: scope, settings: .default, codeStyle: nil, language: "en")
19 }
20
21 func offset(of needle: String, in text: String = Self.text) -> Int { (text as NSString).range(of: needle).location }
22
23 @Test func eachScope() throws {
24 let file = try #require(page(.file))
25 #expect(file.contains("<title>Notes</title>") && file.contains("First body.") && file.contains("Second body."))
26 #expect(file == HTMLExport.page(Self.text, fallbackTitle: "a", settings: .default, path: "/notes/a.org", language: "en"))
27
28 // As Export Subtree: the heading is the title, its children promoted.
29 let subtree = try #require(page(.subtree(offset(of: "First body."))))
30 #expect(subtree.contains("<title>One</title>") && subtree.contains("Inner body."))
31 #expect(!subtree.contains("Second body."))
32 #expect(page(.subtree(0)) == nil)
33
34 // The selection with the file's keywords.
35 let start = offset(of: "Second body.")
36 let selection = try #require(page(.selection(start..<(start + 6))))
37 #expect(selection.contains("<title>Notes</title>") && selection.contains("Second"))
38 #expect(!selection.contains("Second body.") && !selection.contains("First body."))
39 #expect(page(.selection(start..<start)) == nil)
40 }
41
42 @Test func regionKeepsTheFileKeywordsOnce() {
43 #expect(ExportScope.region(Self.text, 0..<15) == "#+TITLE: Notes\n")
44 let start = offset(of: "* Two")
45 #expect(ExportScope.region(Self.text, start..<(start + 5)) == "#+TITLE: Notes\n* Two")
46 #expect(ExportScope.region("* A\nbody\n", 4..<8) == "body")
47 }
48
49 /// The pages the print panel gets: PDF export's layout, with page numbers. The print
50 /// operation itself isn't run here: it stops the test process's main run loop.
51 @Test func printsThePDFExportPages() async throws {
52 let html = try #require(page(.subtree(offset(of: "First body."))))
53 let document = try #require(PDFDocument(data: try await Printing.pages(html: html, directory: nil)))
54 let text = document.string ?? ""
55 #expect(text.contains("One") && text.contains("Inner body."))
56 #expect(!text.contains("Second body."))
57 #expect(document.page(at: 0)?.annotations.first { $0.type == "FreeText" }?.contents == "1")
58 #expect(Printing.title(html) == "One")
59 }
60
61 /// Printing a file needs orgstar+ as PDF export does, since the print panel saves PDFs; the
62 /// agenda prints without it.
63 @Test func gating() {
64 for id in Printing.commands { #expect(ProFeature.required(byCommand: id) == .export) }
65 #expect(ProFeature.required(byCommand: "app.print-agenda") == nil)
66 let access = ProAccess(defaults: TestDefaults("orgstar-printing"))
67 #expect(!access.allows(ProFeature.required(byCommand: "app.print")!))
68 #expect(access.paywall == .export)
69 }
70
71 /// An entry encrypted on disk prints as its message, as PDF export exports it, until it's
72 /// decrypted in the editor.
73 @Test func encryptedEntriesPrintOnlyOnceDecrypted() throws {
74 let secret = "Account 12345"
75 let plain = "* Plain\nOpen text.\n* Bank :crypt:\n\(secret)\n* Last\n"
76 let encrypted = try #require(try OrgCrypt.encrypt(plain, at: offset(of: "* Bank", in: plain), passphrase: "pw"))
77 let notes = try Folder()
78 let file = try notes.write("a.org", encrypted)
79 let session = DocumentSession(recovery: FileRecoveryStore(directory: notes.url.appendingPathComponent(".recovery")))
80 session.saveMode = .explicit
81 session.encryptsTaggedEntries = true
82 session.passphrases = FakeKeychain.passphrases(.undecided).passphrases
83 session.open(file.path)
84 let text = try #require(session.document?.text)
85 let bank = offset(of: "* Bank", in: text)
86 for scope in [PrintScope.file, .subtree(bank), .selection(0..<(text as NSString).length)] {
87 let html = try #require(page(scope, text: text))
88 #expect(!html.contains(secret))
89 #expect(html.contains("Bank"))
90 }
91
92 let buffer = StateBuffer(try #require(session.document))
93 session.attach(buffer)
94 let decrypted = try OrgCrypt.decryptInPlace(text, at: bank, passphrase: "pw")
95 try buffer.update { try $0.apply([TextEdit(range: 0..<($0.text as NSString).length, replacement: decrypted)], baseRevision: $0.revision) }
96 session.bufferChanged()
97 let shown = try #require(session.document?.text)
98 #expect(try #require(page(.file, text: shown)).contains(secret))
99 #expect(try #require(page(.subtree(offset(of: "* Bank", in: shown)), text: shown)).contains(secret))
100 }
101
102 // MARK: - Agenda
103
104 static let calendar: Calendar = {
105 var calendar = Calendar(identifier: .gregorian)
106 calendar.timeZone = TimeZone(identifier: "UTC")!
107 return calendar
108 }()
109 static let now = calendar.date(from: DateComponents(year: 2026, month: 11, day: 26, hour: 8))!
110
111 func agenda(_ mode: AgendaMode) async throws -> (AgendaModel, Folder) {
112 let notes = try Folder()
113 try notes.write("work.org", """
114 * TODO Call the bank :phone:
115 SCHEDULED: <2026-11-26 Thu 09:00>
116 * TODO [#A] Send the report
117 DEADLINE: <2026-11-20 Fri>
118 * DONE Filed
119 CLOSED: [2026-11-25 Wed 10:00]
120 * TODO Read <b>this</b>
121 SCHEDULED: <2026-11-27 Fri>
122
123 """)
124 let workspace = try WorkspaceModel(directory: nil)
125 try await workspace.addRoot(notes.url)
126 let agenda = AgendaModel(workspace: workspace)
127 agenda.mode = mode
128 await agenda.refresh(open: [:], now: Self.now, calendar: Self.calendar)
129 return (agenda, notes)
130 }
131
132 func page(_ agenda: AgendaModel, filter: AgendaFilter = AgendaFilter(), overdueShown: Bool = true, showAllDates: Bool = false) -> String {
133 AgendaPrint.page(title: "Agenda", subtitle: "work", parts: agenda.printParts(showAllDates: showAllDates, filter: filter, overdueShown: overdueShown),
134 today: agenda.today, calendar: Self.calendar, locale: Locale(identifier: "en_US"))
135 }
136
137 @Test func agendaDaysAsShown() async throws {
138 let (agenda, notes) = try await agenda(.agenda(span: 2, startOffset: nil))
139 _ = notes
140 let html = page(agenda)
141 #expect(html.contains("<title>Agenda</title>") && html.contains("<p class=\"subtitle\">work</p>"))
142 #expect(html.contains("Today · Thursday, November 26, 2026") && html.contains("Tomorrow · Friday, November 27, 2026"))
143 #expect(html.contains("<span class=\"todo\">TODO</span> <span class=\"title\">Call the bank</span>"))
144 #expect(html.contains("09:00") && html.contains("work · :phone:"))
145 #expect(html.contains("<p class=\"overdue\">Overdue 1</p>") && html.contains("[#A] <span class=\"title\">Send the report</span>"))
146 // Escaped, not markup.
147 #expect(html.contains("Read <b>this</b>"))
148 // Folded overdue entries stay folded; a filter leaves out what it hides.
149 let folded = page(agenda, overdueShown: false)
150 #expect(folded.contains("Overdue 1") && !folded.contains("Send the report"))
151 var filter = AgendaFilter()
152 filter.tags = ["-phone"]
153 #expect(!page(agenda, filter: filter).contains("Call the bank"))
154 }
155
156 @Test func agendaListsAndEmptyDays() async throws {
157 let (list, notes) = try await agenda(.todo(keywords: nil))
158 _ = notes
159 let html = page(list)
160 #expect(html.contains("Call the bank") && html.contains("Send the report") && !html.contains("Filed"))
161 #expect(!html.contains("class=\"gutter\""))
162 var none = AgendaFilter()
163 none.tags = ["+nothing"]
164 #expect(page(list, filter: none).contains("No entries"))
165
166 let (days, more) = try await agenda(.agenda(span: 1, startOffset: 3))
167 _ = more
168 #expect(!page(days).contains("<h3"))
169 #expect(page(days, showAllDates: true).contains("Sunday, November 29, 2026</h3>\n<p class=\"empty\">Nothing scheduled</p>"))
170 }
171
172 /// The agenda's page goes through the same pages as a file's.
173 @Test func agendaPrintsAsPages() async throws {
174 let (agenda, notes) = try await agenda(.agenda(span: 2, startOffset: nil))
175 _ = notes
176 let text = try #require(PDFDocument(data: try await Printing.pages(html: page(agenda), directory: nil))).string ?? ""
177 #expect(text.contains("Call the bank") && text.contains("Send the report"))
178 }
179}