Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Tests/DocAutomationTests/CommandLineTests.swift3// Description: Spawns the built orixdocs executable: convert, audit, stats, compare, workflow, help, and the exit codes of bad invocations.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import PDFKit9import Testing10import DocModel11import DocContainer12@testable import DocAutomation1314@Suite struct CommandLineTests {15 private func tool() throws -> URL { try #require(Tool.url, "the orixdocs executable was not found next to the test bundle (run `swift build` first)") }1617 @Test func convertMarkdownToPDFAndDOCX() throws {18 let tool = try tool()19 let folder = TempFolder()20 let md = folder.file("notes.md")21 try Data(Sample.markdown.utf8).write(to: md)2223 let pdfOut = folder.file("notes.pdf")24 let r = try Tool.run(["convert", md.path, pdfOut.path, "--theme", "classic", "--paper", "a4"], at: tool)25 #expect(r.status == 0, "\(r.stderr)")26 #expect(r.stdout.trimmingCharacters(in: .whitespacesAndNewlines) == pdfOut.path)27 let pdf = try #require(PDFDocument(url: pdfOut))28 #expect((pdf.string ?? "").contains("Field Notes"))29 let box = try #require(pdf.page(at: 0)?.bounds(for: .mediaBox))30 #expect(abs(box.width - 595.28) < 1)3132 let docxOut = folder.file("notes.docx")33 #expect(try Tool.run(["convert", md.path, docxOut.path], at: tool).status == 0)34 let back = try DocumentConverter.importDocument(at: docxOut).document35 #expect(back.body.contains { $0.paragraph?.plainText == "Field Notes" })36 #expect(back.body.contains { $0.table != nil })37 }3839 @Test func convertNeverOverwritesWithoutForce() throws {40 let tool = try tool()41 let folder = TempFolder()42 let source = try Sample.write(Sample.report(), to: folder.file("report.orixdoc"))43 let target = folder.file("report.txt")44 try Data("precious".utf8).write(to: target)4546 let refused = try Tool.run(["convert", source.path, target.path], at: tool)47 #expect(refused.status == 3)48 #expect(refused.stdout.isEmpty)49 #expect(refused.stderr.contains("already exists"))50 #expect(try String(contentsOf: target, encoding: .utf8) == "precious")5152 let forced = try Tool.run(["convert", source.path, target.path, "--force"], at: tool)53 #expect(forced.status == 0)54 #expect(try String(contentsOf: target, encoding: .utf8).contains("Zebra Findings"))55 }5657 @Test func convertAcceptChanges() throws {58 let tool = try tool()59 let folder = TempFolder()60 var doc = DocumentModel(body: [Sample.para("Hello world")])61 doc.settings.trackChanges = true62 var editor = DocumentEditor(doc: doc, selection: Selection(caret: Position(block: 0, offset: 5)))63 editor.insertText(" big")64 let source = try Sample.write(editor.doc, to: folder.file("tracked.orixdoc"))65 let r = try Tool.run(["convert", source.path, folder.file("clean.orixdoc").path, "--accept-changes"], at: tool)66 #expect(r.status == 0, "\(r.stderr)")67 let clean = try DocumentConverter.importDocument(at: folder.file("clean.orixdoc")).document68 #expect(!clean.hasTrackedChanges)69 #expect(clean.body.first?.paragraph?.plainText == "Hello big world")70 }7172 @Test func auditJSON() throws {73 let tool = try tool()74 let folder = TempFolder()75 var doc = Sample.report()76 var p = Paragraph("See ")77 p.runs.append(Run(inline: .crossRef(CrossRef(target: "no-such-target"))))78 doc.body.append(.paragraph(p))79 let source = try Sample.write(doc, to: folder.file("paper.orixdoc"))8081 let r = try Tool.run(["audit", source.path, "--json", "--profile", "academic"], at: tool)82 #expect(r.status == 0, "\(r.stderr)")83 let json = try #require(try JSONSerialization.jsonObject(with: Data(r.stdout.utf8)) as? [String: Any])84 #expect(json["tool"] as? String == "orixdocs")85 #expect(json["profile"] as? String == "academic")86 let summary = try #require(json["summary"] as? [String: Any])87 #expect((summary["errors"] as? Int ?? 0) >= 1)88 let findings = try #require(json["findings"] as? [[String: Any]])89 #expect(findings.contains { $0["check"] as? String == "brokenCrossReference" && $0["severity"] as? String == "error" })90 #expect(findings.allSatisfy { $0["title"] is String && $0["id"] is String })9192 // Plain text, and the strict exit code.93 let text = try Tool.run(["audit", source.path], at: tool)94 #expect(text.status == 0)95 #expect(text.stdout.contains("[error]"))96 #expect(try Tool.run(["audit", source.path, "--fail-on-error"], at: tool).status == 5)97 let clean = try Sample.write(Sample.report(), to: folder.file("clean.orixdoc"))98 #expect(try Tool.run(["audit", clean.path, "--profile", "minimal", "--fail-on-error"], at: tool).status == 0)99 }100101 @Test func statsJSON() throws {102 let tool = try tool()103 let folder = TempFolder()104 let doc = Sample.report()105 let source = try Sample.write(doc, to: folder.file("report.docx"))106 let r = try Tool.run(["stats", source.path, "--json"], at: tool)107 #expect(r.status == 0, "\(r.stderr)")108 let json = try #require(try JSONSerialization.jsonObject(with: Data(r.stdout.utf8)) as? [String: Any])109 let stats = try #require(json["statistics"] as? [String: Any])110 #expect(stats["words"] as? Int == DocumentStatistics(doc).words)111 #expect(stats["headings"] as? Int == 4)112 #expect((stats["pages"] as? Int ?? 0) >= 1)113 #expect((stats["readingMinutes"] as? Int ?? 0) >= 1)114115 let text = try Tool.run(["stats", source.path], at: tool)116 #expect(text.status == 0)117 #expect(text.stdout.contains("Words"))118 }119120 @Test func compareWritesReportAndMergedDocument() throws {121 let tool = try tool()122 let folder = TempFolder()123 let a = try Sample.write(Sample.report(), to: folder.file("a.orixdoc"))124 var revised = Sample.report()125 revised.body[2] = Sample.para("A completely new introduction about penguins.")126 let b = try Sample.write(revised, to: folder.file("b.orixdoc"))127128 let r = try Tool.run(["compare", a.path, b.path, "--report", folder.file("diff.md").path, "--merged", folder.file("merged.orixdoc").path], at: tool)129 #expect(r.status == 0, "\(r.stderr)")130 #expect(r.stdout.contains("change"))131 #expect(try String(contentsOf: folder.file("diff.md"), encoding: .utf8).contains("penguins"))132 #expect(try DocumentConverter.importDocument(at: folder.file("merged.orixdoc")).document.hasTrackedChanges)133134 #expect(try Tool.run(["compare", a.path, a.path], at: tool).stdout.contains("identical"))135 // The report exists now: a second run refuses to replace it.136 #expect(try Tool.run(["compare", a.path, b.path, "--report", folder.file("diff.md").path], at: tool).status == 3)137 }138139 @Test func workflowRunBatchWithAFailingInput() throws {140 let tool = try tool()141 let folder = TempFolder()142 let good = try (0..<3).map { try Sample.write(Sample.report(title: "Report \($0)"), to: folder.file("r\($0).docx")).path }143 let broken = folder.file("broken.docx")144 try Data("nope".utf8).write(to: broken)145 let out = folder.subfolder("out")146147 let r = try Tool.run(["workflow", "run", "docx-to-styled-pdf"] + good + [broken.path, "--out", out.path, "--jobs", "2"], at: tool)148 #expect(r.status == 4, "\(r.stderr)") // partial failure149 #expect(r.stdout.split(separator: "\n").count == 3)150 #expect(r.stderr.contains("broken.docx"))151 #expect(r.stderr.contains("3 succeeded, 1 failed"))152 #expect(try FileManager.default.contentsOfDirectory(atPath: out.path).sorted() == ["r0.pdf", "r1.pdf", "r2.pdf"])153154 // Again without --force: every output exists, nothing is replaced.155 #expect(try Tool.run(["workflow", "run", "docx-to-styled-pdf"] + good + ["--out", out.path], at: tool).status == 3)156 #expect(try Tool.run(["workflow", "run", "docx-to-styled-pdf"] + good + ["--out", out.path, "--force"], at: tool).status == 0)157158 // A workflow file with a forbidden step is refused before any input is read.159 let evil = folder.file("evil.json")160 try Data(#"{ "name": "Evil", "steps": [ { "type": "shell", "command": "touch /tmp/pwned" } ] }"#.utf8).write(to: evil)161 let refused = try Tool.run(["workflow", "run", evil.path] + good + ["--out", folder.subfolder("out2").path], at: tool)162 #expect(refused.status == 1)163 #expect(refused.stderr.contains("Unknown step type"))164 #expect(!FileManager.default.fileExists(atPath: folder.subfolder("out2").path))165166 let custom = folder.file("custom.json")167 try Data(#"{ "name": "Text", "steps": [ { "type": "import" }, { "type": "export", "format": "txt", "fileName": "text/{name}.txt" } ] }"#.utf8).write(to: custom)168 let ok = try Tool.run(["workflow", "run", custom.path, good[0], "--out", folder.subfolder("out3").path], at: tool)169 #expect(ok.status == 0, "\(ok.stderr)")170 #expect(try String(contentsOf: folder.subfolder("out3").appendingPathComponent("text/r0.txt"), encoding: .utf8).contains("Report 0"))171 }172173 @Test func helpVersionFormatsAndList() throws {174 let tool = try tool()175 let help = try Tool.run(["--help"], at: tool)176 #expect(help.status == 0)177 for word in ["convert", "audit", "stats", "compare", "workflow run", "workflow list", "formats", "EXIT CODES"] { #expect(help.stdout.contains(word), "\(word)") }178 for command in [["convert"], ["audit"], ["stats"], ["compare"], ["workflow"], ["workflow", "run"], ["workflow", "list"], ["formats"]] {179 let r = try Tool.run(command + ["--help"], at: tool)180 #expect(r.status == 0, "\(command)")181 #expect(r.stdout.contains("orixdocs \(command[0])"), "\(command)")182 #expect(r.stderr.isEmpty)183 }184 let version = try Tool.run(["--version"], at: tool)185 #expect(version.status == 0)186 #expect(version.stdout == "orixdocs \(AutomationReports.toolVersion)\n")187 let formats = try Tool.run(["formats"], at: tool)188 #expect(formats.status == 0)189 for f in DocFormat.allCases { #expect(formats.stdout.contains("." + f.fileExtension)) }190 let list = try Tool.run(["workflow", "list"], at: tool)191 #expect(list.status == 0)192 for w in BuiltinWorkflows.all { #expect(list.stdout.contains(w.id)) }193 }194195 @Test func badArgumentsExitWithTwoAndWriteToStandardError() throws {196 let tool = try tool()197 let folder = TempFolder()198 let source = try Sample.write(Sample.report(), to: folder.file("report.orixdoc")).path199 let cases: [[String]] = [200 [], ["frobnicate"], ["convert"], ["convert", source], ["convert", source, folder.file("a.pdf").path, "extra"],201 ["convert", source, folder.file("a.pdf").path, "--bogus"], ["convert", source, folder.file("a.xyz").path],202 ["convert", source, folder.file("a.pdf").path, "--theme"], ["convert", source, folder.file("a.pdf").path, "--theme", "Nope"],203 ["convert", source, folder.file("a.pdf").path, "--paper", "A9"], ["audit"], ["audit", source, "--profile", "strictest"],204 ["stats"], ["stats", source, source], ["compare", source], ["workflow"], ["workflow", "frob"], ["workflow", "run", "audit-only", source],205 ["workflow", "run", "audit-only", source, "--out", folder.subfolder("o").path, "--jobs", "0"],206 ["workflow", "run", "no-such-workflow", source, "--out", folder.subfolder("o").path], ["formats", "extra"]]207 for arguments in cases {208 let r = try Tool.run(arguments, at: tool)209 #expect(r.status == 2, "\(arguments) → \(r.status) \(r.stderr)")210 if !arguments.isEmpty { #expect(r.stderr.hasPrefix("orixdocs: "), "\(arguments)"); #expect(r.stdout.isEmpty, "\(arguments)") }211 }212 #expect(try FileManager.default.contentsOfDirectory(atPath: folder.url.path) == ["report.orixdoc"])213214 // Unreadable inputs are failures (1), not usage errors.215 #expect(try Tool.run(["stats", folder.file("absent.docx").path], at: tool).status == 1)216 #expect(try Tool.run(["audit", folder.file("absent.docx").path], at: tool).status == 1)217 let garbage = folder.file("garbage.docx")218 try Data("garbage".utf8).write(to: garbage)219 let bad = try Tool.run(["convert", garbage.path, folder.file("g.pdf").path], at: tool)220 #expect(bad.status == 1)221 #expect(bad.stderr.contains("garbage.docx"))222 #expect(!FileManager.default.fileExists(atPath: folder.file("g.pdf").path))223 #expect(try Tool.run(["stats", folder.file("report.orixdoc").path + ".unknown"], at: tool).status == 1)224 }225}226