Repository Public License
1// ORIX Secure2// File: Packages/ORIXReporting/Tests/ORIXReportingTests/PDFTests.swift3// Description: Tests of the PDF renderer: validity, pagination, selectable text read back with PDFKit, metadata, page4// numbering, Unicode and a 300-finding document.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import ORIXSecureModel10import PDFKit11import Testing12@testable import ORIXReporting1314@Suite("PDF")15struct PDFTests {16 let generator = ReportGenerator()1718 private func open(_ data: Data) throws -> PDFDocument {19 #expect(data.prefix(4) == Data("%PDF".utf8))20 return try #require(PDFDocument(data: data))21 }2223 /// Body text of the whole document without white space; the header band and the footer of each page are removed so24 /// that a paragraph continuing on the next page reads continuously.25 private func bodyText(_ pdf: PDFDocument, title: String) -> String {26 var body = ""27 for index in 0..<pdf.pageCount {28 var page = (pdf.page(at: index)?.string ?? "").squashed29 let footer = ReportStrings.footer(page: index + 1, of: pdf.pageCount).squashed30 if let range = page.range(of: footer, options: .backwards) { page.removeSubrange(range) }31 let header = ("ORIX Secure" + title).squashed32 if page.hasPrefix(header) { page.removeFirst(header.count) }33 body += page34 }35 return body36 }3738 @Test func richDocumentTextIsSelectableAndComplete() throws {39 let document = Fixtures.rich40 let data = try generator.pdf(document, options: PDFOptions(paperSize: .letter))41 let pdf = try open(data)42 #expect(pdf.pageCount > 1)43 let text = bodyText(pdf, title: document.title)44 func has(_ value: String, _ comment: Comment? = nil) { #expect(text.contains(value.squashed), comment) }4546 has(document.title)47 has(document.kind.title)48 has(ReportStrings.date(document.createdAt))49 has(document.generator)50 for paragraph in document.summary.reportParagraphs { has(paragraph) }51 for section in document.sections {52 has(section.title)53 for paragraph in section.paragraphs { has(paragraph) }54 for fact in section.facts {55 has(fact.label)56 has(fact.value)57 }58 for bullet in section.bullets { has(bullet) }59 }60 for finding in Fixtures.latinFindings {61 has(finding.title, "title \(finding.id)")62 has("\(finding.state.title) · \(ReportStrings.severity): \(finding.severity.title)", "state \(finding.id)")63 has("\(ReportStrings.confidence): \(finding.confidence.title)")64 has("\(ReportStrings.verification): \(finding.verification.title)")65 has("\(ReportStrings.assessed): \(ReportStrings.date(finding.assessedAt))")66 for evidence in finding.evidence {67 has(evidence.label, "label \(evidence.label)")68 has(evidence.value, "value \(evidence.label)")69 if let source = evidence.source { has("\(ReportStrings.source): \(source)") }70 }71 for paragraph in finding.explanation.reportParagraphs { has(paragraph, "explanation \(finding.id)") }72 for paragraph in (finding.recommendation ?? "").reportParagraphs { has(paragraph, "recommendation \(finding.id)") }73 for item in finding.notInspected { has(item) }74 }75 has(ReportStrings.noEvidence)76 has(ReportStrings.unavailableTitle)77 for item in document.unavailable { has(item) }78 has(ReportGenerator.closingStatement)79 // French accents survive extraction.80 has("Vérification du réseau privé à l’aéroport")81 has("Activé — confirmé à l’écran")82 has("Revérifiez ce réglage après chaque mise à jour du système.")83 // PDFKit search finds text too.84 #expect(!pdf.findString("réseau privé", withOptions: [.caseInsensitive]).isEmpty)85 #expect(!pdf.findString("F1-value-26.5", withOptions: []).isEmpty)86 }8788 @Test func unicodeDoesNotCrashAndIsMostlyExtractable() throws {89 var document = Fixtures.rich90 document.title = "Rapport 检查 🔒 مرحبا — vérifié"91 let data = try generator.pdf(document)92 let pdf = try open(data)93 let text = (pdf.string ?? "").squashed94 #expect(text.contains("报告文件.pdf"))95 #expect(text.contains("日本語のテキスト"))96 #expect(text.contains("한국어"))97 #expect(text.contains("vérifié"))98 }99100 @Test func metadataIsPresent() throws {101 let document = Fixtures.rich102 let before = Date().addingTimeInterval(-5)103 let data = try generator.pdf(document)104 let pdf = try open(data)105 let attributes = try #require(pdf.documentAttributes)106 #expect(attributes[PDFDocumentAttribute.titleAttribute] as? String == document.title)107 #expect(attributes[PDFDocumentAttribute.authorAttribute] as? String == "ORIX Secure")108 #expect(attributes[PDFDocumentAttribute.creatorAttribute] as? String == document.generator)109 #expect(attributes[PDFDocumentAttribute.subjectAttribute] as? String == document.kind.title)110 let created = try #require(attributes[PDFDocumentAttribute.creationDateAttribute] as? Date)111 #expect(created > before)112 }113114 @Test func paperSizesAndMargins() throws {115 for size in PDFOptions.PaperSize.allCases {116 let data = try generator.pdf(Fixtures.rich, options: PDFOptions(paperSize: size, margin: 72))117 let pdf = try open(data)118 let box = try #require(pdf.page(at: 0)?.bounds(for: .mediaBox))119 #expect(abs(box.width - size.size.width) < 0.01 && abs(box.height - size.size.height) < 0.01)120 }121 #expect(PDFOptions.PaperSize.default(for: Locale(identifier: "en_US")) == .letter)122 #expect(PDFOptions.PaperSize.default(for: Locale(identifier: "fr_CA")) == .letter)123 #expect(PDFOptions.PaperSize.default(for: Locale(identifier: "fr_FR")) == .a4)124 // Absurd margins are clamped instead of producing an unusable page.125 let narrow = try generator.pdf(Fixtures.rich, options: PDFOptions(paperSize: .a4, margin: 5_000))126 let wide = try generator.pdf(Fixtures.rich, options: PDFOptions(paperSize: .a4, margin: -.infinity))127 let narrowPDF = try open(narrow)128 let widePDF = try open(wide)129 #expect(narrowPDF.pageCount > widePDF.pageCount)130 }131132 @Test func emptyDocumentRendersOneValidPage() throws {133 let data = try generator.pdf(Fixtures.empty)134 let pdf = try open(data)135 #expect(pdf.pageCount == 1)136 let text = (pdf.string ?? "").squashed137 #expect(text.contains(ReportStrings.footer(page: 1, of: 1).squashed))138 #expect(text.contains(ReportGenerator.closingStatement.squashed))139 #expect(text.contains(ReportStrings.unavailableNone.squashed))140 }141142 @Test func longDocumentPaginatesWithCorrectTotals() throws {143 let document = Fixtures.long(300)144 let clock = ContinuousClock()145 var rendered = Data()146 let elapsed = try clock.measure { rendered = try generator.pdf(document, options: PDFOptions(paperSize: .letter)) }147 let milliseconds = Double(elapsed.components.seconds) * 1000 + Double(elapsed.components.attoseconds) / 1e15148 let pdf = try open(rendered)149 print("PDF 300 findings: \(Int(milliseconds)) ms, \(rendered.count) bytes, \(pdf.pageCount) pages")150 #expect(milliseconds < 15_000)151 #expect(pdf.pageCount > 30)152153 var body = ""154 for index in 0..<pdf.pageCount {155 let page = (pdf.page(at: index)?.string ?? "").squashed156 #expect(page.contains(ReportStrings.footer(page: index + 1, of: pdf.pageCount).squashed), "page \(index + 1)")157 #expect(page.hasPrefix("ORIXSecureLonginvestigation"), "header of page \(index + 1)")158 // No page is left nearly empty by the keep-together rules.159 if index < pdf.pageCount - 1 { #expect(page.count > 400, "page \(index + 1) has \(page.count) characters") }160 body += page161 }162 for finding in document.allFindings {163 #expect(body.contains(finding.title.squashed), "\(finding.id)")164 #expect(body.contains((finding.evidence.first?.value ?? finding.title).squashed), "\(finding.id)")165 }166 }167168 @Test func findingTitleStaysWithItsStateLine() throws {169 // On every page, a finding title is followed on the same page by its state line.170 let document = Fixtures.long(120)171 let data = try generator.pdf(document, options: PDFOptions(paperSize: .a4))172 let pdf = try open(data)173 var found = 0174 for finding in document.allFindings {175 let title = finding.title.squashed176 let state = "\(finding.state.title) · \(ReportStrings.severity): \(finding.severity.title)".squashed177 let label = "\(ReportStrings.confidence): \(finding.confidence.title)".squashed178 for index in 0..<pdf.pageCount {179 let page = (pdf.page(at: index)?.string ?? "").squashed180 if page.contains(title + state) {181 found += 1182 #expect(page.contains(title + state + label), "\(finding.id) lost its details on page \(index + 1)")183 }184 }185 }186 #expect(found == 120)187 }188189 @Test func rendersConcurrently() async throws {190 let sizes = try await withThrowingTaskGroup(of: Int.self) { group in191 for _ in 0..<6 {192 group.addTask { try ReportGenerator().pdf(Fixtures.rich, options: PDFOptions(paperSize: .a4)).count }193 }194 var sizes: [Int] = []195 for try await size in group { sizes.append(size) }196 return sizes197 }198 #expect(sizes.count == 6)199 #expect(sizes.allSatisfy { $0 > 10_000 })200 }201}202