Tests/OrgAppTests/CitationActionsTests.swift

754eac2f33eae31805a148fcf0bddeb74b95a4a3
orgstar/Tests/OrgAppTests/CitationActionsTests.swift

143 lines · 7183 bytes

  1import Foundation
  2import OrgCore
  3import OrgDocument
  4import Testing
  5@testable import OrgApp
  6
  7/// Insert Citation… and following citations, with the questions answered here.
  8@MainActor
  9struct CitationActionsTests {
 10    static let bib = #"""
 11        @book{smith1999,
 12          author = {Smith, John},
 13          title = {The Book},
 14          publisher = {Pub House},
 15          year = 1999,
 16          url = {https://example.org/book},
 17          doi = {10.1000/book},
 18          file = {:papers/smith.pdf:PDF}
 19        }
 20        @article{doe2020,
 21          author = {Doe, Jane},
 22          title = {A Study},
 23          year = {2020}
 24        }
 25        """#
 26
 27    final class Log {
 28        var prompts: [Prompt] = []
 29        var messages: [String] = []
 30    }
 31
 32    func setUp(_ text: String, caret: Int? = nil) throws -> (Folder, DocumentSession, () -> EditContext) {
 33        let folder = try Folder()
 34        try folder.write("refs.bib", Self.bib)
 35        let doc = try folder.write("doc.org", text)
 36        let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.url.appendingPathComponent(".r")))
 37        session.open(doc.path)
 38        let context = {
 39            let caret = caret ?? text.utf16.count
 40            return EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [caret..<caret])
 41        }
 42        return (folder, session, context)
 43    }
 44
 45    /// The text after `command` runs in `context`.
 46    func applying(_ command: any OrgCommand, _ context: EditContext) -> String? {
 47        guard case .commit(let result) = command.run(in: context) else { return nil }
 48        var text = context.text
 49        for edit in result.edits.sorted(by: { $0.range.lowerBound > $1.range.lowerBound }) { text = edit.apply(to: text) }
 50        return text
 51    }
 52
 53    @Test func insertsAKeyChosenFromTheBibliography() async throws {
 54        let (folder, session, context) = try setUp("#+bibliography: refs.bib\nSee ")
 55        defer { withExtendedLifetime(folder) {} }
 56        let log = Log()
 57        let command: (any OrgCommand)? = await withCheckedContinuation { done in
 58            let actions = CitationActions(
 59                session: session, context: { context() }, perform: { done.resume(returning: $0) }, show: { log.messages.append($0) },
 60                ask: { prompt, reply in
 61                    log.prompts.append(prompt)
 62                    switch prompt.key {
 63                    case "key": reply(prompt.choices.first { $0.hasPrefix("smith1999") })
 64                    case "prefix": reply("see")
 65                    case "suffix": reply("p. 5")
 66                    default: reply("t")
 67                    }
 68                }, present: { _ in })
 69            actions.insert()
 70        }
 71        #expect(log.prompts.map(\.key) == ["key", "prefix", "suffix", "style"])
 72        #expect(log.prompts[0].choices == ["doe2020  Doe, Jane  2020  A Study", "smith1999  Smith, John  1999  The Book"])
 73        #expect(log.prompts[3].choices == ["author", "noauthor", "nocite", "note", "numeric", "text", "nil"])
 74        #expect(applying(try #require(command), context()) == "#+bibliography: refs.bib\nSee [cite/t:see @smith1999 p. 5]")
 75    }
 76
 77    @Test func onAKeyReplacesItWithoutAskingMore() async throws {
 78        let text = "#+bibliography: refs.bib\nSee [cite:@doe2020]"
 79        let (folder, session, context) = try setUp(text, caret: text.utf16.count - 3)
 80        defer { withExtendedLifetime(folder) {} }
 81        let log = Log()
 82        let command: (any OrgCommand)? = await withCheckedContinuation { done in
 83            CitationActions(
 84                session: session, context: { context() }, perform: { done.resume(returning: $0) }, show: { log.messages.append($0) },
 85                ask: { prompt, reply in
 86                    log.prompts.append(prompt)
 87                    reply(prompt.choices.first { $0.hasPrefix("smith1999") })
 88                }, present: { _ in }).insert()
 89        }
 90        #expect(log.prompts.map(\.key) == ["key"])
 91        #expect(applying(try #require(command), context()) == "#+bibliography: refs.bib\nSee [cite:@smith1999]")
 92    }
 93
 94    @Test func withoutABibliographySaysSo() throws {
 95        let (folder, session, context) = try setUp("No keywords here ")
 96        defer { withExtendedLifetime(folder) {} }
 97        let log = Log()
 98        CitationActions(session: session, context: { context() }, perform: { _ in }, show: { log.messages.append($0) },
 99                        ask: { prompt, _ in log.prompts.append(prompt) }, present: { _ in }).insert()
100        #expect(log.messages == ["No bibliography set"])
101        #expect(log.prompts.isEmpty)
102    }
103
104    @Test func followingShowsTheEntryAndWhatItOffers() async throws {
105        let (folder, session, context) = try setUp("#+bibliography: refs.bib\nSee [cite:@smith1999; @doe2020]")
106        let log = Log()
107        let entry: CitationEntry = await withCheckedContinuation { done in
108            CitationActions(session: session, context: { context() }, perform: { _ in }, show: { log.messages.append($0) },
109                            ask: { prompt, reply in
110                                log.prompts.append(prompt)
111                                reply("smith1999")
112                            }, present: { done.resume(returning: $0) }).follow(["smith1999", "doe2020"])
113        }
114        #expect(log.prompts.map(\.choices) == [["smith1999", "doe2020"]])
115        #expect(entry.key == "smith1999")
116        #expect(entry.summary == "Smith, John (1999). The Book. Pub House.")
117        let bib = folder.url.appendingPathComponent("refs.bib").path
118        #expect(entry.links.map(\.label) == ["Open smith.pdf", "Open DOI", "Open URL", "Show in Bibliography"])
119        #expect(entry.links.map(\.link) == [
120            OrgLink(type: "file", path: folder.url.appendingPathComponent("papers/smith.pdf").path, raw: "file:" + folder.url.appendingPathComponent("papers/smith.pdf").path),
121            OrgLink(type: "doi", path: "10.1000/book", raw: "doi:10.1000/book"),
122            Links.parse(plain: "https://example.org/book"),
123            OrgLink(type: "file", path: bib, searchOption: "1", raw: "file:" + bib),
124        ])
125        #expect(session.follow(entry.links[1].link, workspace: nil, isText: { _ in false }) == .openExternally(URL(string: "https://doi.org/10.1000/book")!))
126
127        let missing: String = await withCheckedContinuation { done in
128            CitationActions(session: session, context: { context() }, perform: { _ in }, show: { done.resume(returning: $0) },
129                            ask: { _, _ in }, present: { _ in }).follow(["nope"])
130        }
131        #expect(missing == "Cannot find citation key: nope")
132    }
133
134    @Test func completionAnswersWithTheKeys() async throws {
135        let folder = try Folder()
136        defer { withExtendedLifetime(folder) {} }
137        let bib = try folder.write("refs.bib", Self.bib)
138        let workspace = try WorkspaceModel(directory: nil)
139        let result = await CompletionSources.answer(.citationKeys([bib.path]), index: workspace.index, excluding: nil)
140        #expect(result.strings == ["doe2020", "smith1999"])
141        #expect(result.annotations["smith1999"] == "Smith, John  1999  The Book")
142    }
143}
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form