// SPDX-License-Identifier: GPL-3.0-or-later import Foundation import XCTest import WebKit // Content qualification may skip only an explicitly declared lookup edition. // Missing or malformed manifests remain test failures, never silent skips. enum TestBuildContent { struct Manifest: Decodable { let schemaVersion: Int let profile: String let manuals: String } static func read(resources: URL) throws -> Manifest { let bytes = try Data(contentsOf: resources.appendingPathComponent("BuildContent.json")) let value = try JSONDecoder().decode(Manifest.self, from: bytes) guard value.schemaVersion == 1, (value.profile == "normal" && value.manuals == "full") || (value.profile == "source" && value.manuals == "lookup") else { throw CocoaError(.fileReadCorruptFile) } return value } static func requireFullManuals(resources: URL) throws { if try read(resources: resources).manuals == "lookup" { throw XCTSkip("This content profile includes BASIC and Assembly lookup; full-manual qualification is omitted.") } } } final class BASICReferenceTests: XCTestCase { private func requireFullManualEdition() throws { let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) let resources = try XCTUnwrap(app.resourceURL) try TestBuildContent.requireFullManuals(resources: resources) } func testContentQualificationRequiresAValidExplicitManifest() throws { let resources = FileManager.default.temporaryDirectory.appendingPathComponent("VCCContentManifest-" + UUID().uuidString) try FileManager.default.createDirectory(at: resources, withIntermediateDirectories: false) defer { try? FileManager.default.removeItem(at: resources) } let manifest = resources.appendingPathComponent("BuildContent.json") XCTAssertThrowsError(try TestBuildContent.read(resources: resources), "Missing content metadata is a failure") for (profile, manuals) in [("normal", "full"), ("source", "lookup")] { let bytes = try JSONSerialization.data(withJSONObject: ["schemaVersion": 1, "profile": profile, "manuals": manuals]) try bytes.write(to: manifest) XCTAssertEqual(try TestBuildContent.read(resources: resources).manuals, manuals) } for invalid in ["{}", "not json", "{\"schemaVersion\":true,\"profile\":\"source\",\"manuals\":\"lookup\"}", "{\"schemaVersion\":2,\"profile\":\"source\",\"manuals\":\"lookup\"}", "{\"schemaVersion\":1,\"profile\":\"normal\",\"manuals\":\"lookup\"}"] { try Data(invalid.utf8).write(to: manifest) XCTAssertThrowsError(try TestBuildContent.read(resources: resources), invalid) } } func testBASICAndAssemblyLookupTopicsAreReadableThroughTheNativeMCPIndex() async throws { let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) let resources = try XCTUnwrap(app.resourceURL) _ = try TestBuildContent.read(resources: resources) let root = try XCTUnwrap(app.url(forResource: "ManualLibrary", withExtension: nil)) let index = MCPHelpIndex(root: root) for (query, prefix) in [("PRINT", "programming-in-coco-basic/"), ("LDA", "assembly-language-programming/"), ("BHS", "assembly-language-programming/"), ("LBHS", "assembly-language-programming/")] { let hits = try await index.search(query) let hit = try XCTUnwrap(hits.first { $0.id.hasPrefix(prefix) }, query) let topic = try await index.read(hit.id) XCTAssertFalse(try XCTUnwrap(topic).text.isEmpty) } } func testPackagedCollectionsRemainReadableForSelectedContentProfile() async throws { let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) let resources = try XCTUnwrap(app.resourceURL) let content = try TestBuildContent.read(resources: resources) let catalog = try await SoftwareLibraryCatalog.load(from: resources.appendingPathComponent("SoftwareLibrary/catalog.sqlite")) if content.profile == "source" { XCTAssertTrue(catalog.titles.isEmpty) XCTAssertEqual(catalog.releaseCount, 0) } let archiveURL = app.url(forResource: "ArchiveLibrary", withExtension: "sqlite", subdirectory: "ArchiveLibrary") // Normal source checkouts can deliberately omit the optional index. if archiveURL == nil && content.profile == "normal" { return } let archive = ArchiveLibraryCatalog(url: try XCTUnwrap(archiveURL)) let collections = try await archive.collections() let documents = try await archive.browse(collection: nil, limit: 10, offset: 0) let matches = try await archive.search(query: "PRINT", collection: nil, limit: 10, offset: 0) if content.profile == "source" { XCTAssertTrue(collections.isEmpty) XCTAssertTrue(documents.isEmpty) XCTAssertTrue(matches.isEmpty) } } func testManualExamplesResolveOnlyInsideTheBook() throws { let files = FileManager.default let temporary = files.temporaryDirectory.appendingPathComponent(UUID().uuidString) defer { try? files.removeItem(at: temporary) } let root = temporary.appendingPathComponent("ManualLibrary") let examples = root.appendingPathComponent("first-book/examples") try files.createDirectory(at: examples, withIntermediateDirectories: true) let signal = examples.appendingPathComponent("SIGNAL.bas") try Data("10 END".utf8).write(to: signal) let content = ManualLibraryContent(root: root) XCTAssertEqual(content.relativePath(for: signal), "first-book/examples/SIGNAL.bas") XCTAssertEqual(content.exampleURL(for: "first-book/examples/SIGNAL.bas"), signal.resolvingSymlinksInPath()) let outside = temporary.appendingPathComponent("personal.bas") try Data().write(to: outside) try files.createSymbolicLink(at: examples.appendingPathComponent("outside.bas"), withDestinationURL: outside) XCTAssertNil(content.exampleURL(for: "first-book/examples/outside.bas")) XCTAssertNil(content.exampleURL(for: "first-book/examples/../../../personal.bas")) XCTAssertNil(content.exampleURL(for: "first-book/examples/missing.bas")) XCTAssertNil(content.relativePath(for: outside)) } func testPackagedDevelopmentExamplesOfferCopiesAndDoNotUseTheBASICEditor() throws { try requireFullManualEdition() let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) let root = try XCTUnwrap(app.url(forResource: "ManualLibrary", withExtension: nil)) let content = ManualLibraryContent(root: root) let assembly = "your-first-6809-programs/examples/byte.asm" XCTAssertEqual(content.copyTitle(for: assembly), "Save Assembly Example") XCTAssertNil(content.exampleURL(for: assembly)) let source = "programming-in-c/examples/cargo.c" XCTAssertEqual(content.copyTitle(for: source), "Save C Example") XCTAssertNil(content.exampleURL(for: source)) XCTAssertEqual(content.copyTitle(for: "programming-in-c/examples/HelloDisk.zip"), "Save Example Project") let advanced = "assembly-language-programming/examples/" XCTAssertEqual(content.copyTitle(for: advanced + "bankwalk.asm"), "Save Assembly Example") XCTAssertEqual(content.copyTitle(for: advanced + "Dispatch.zip"), "Save Example Project") XCTAssertNil(content.exampleURL(for: advanced + "Dispatch.zip")) let os9 = "working-with-os9/examples/" XCTAssertEqual(content.copyTitle(for: os9 + "beacon.a"), "Save Assembly Example") XCTAssertEqual(content.copyTitle(for: os9 + "night.b09"), "Save BASIC09 Example") XCTAssertEqual(content.copyTitle(for: os9 + "watch.c"), "Save C Example") XCTAssertNil(content.exampleURL(for: os9 + "night.b09")) let hardware = "inside-the-coco-3/examples/" XCTAssertEqual(content.copyTitle(for: hardware + "pixel-mask.asm"), "Save Assembly Example") XCTAssertNotNil(content.exampleURL(for: hardware + "BEACON.bas")) XCTAssertNil(content.copyTitle(for: "programming-in-c/examples/missing.c")) XCTAssertNil(content.copyTitle(for: "programming-in-c/examples/../book-index.js")) XCTAssertNil(content.copyTitle(for: "meet-your-color-computer/examples/SIGNAL.bas")) let starter = "vibe-coding-with-chatgpt/examples/" XCTAssertEqual(content.copyTitle(for: starter + "ProjectStarter.zip"), "Save Example Project") XCTAssertEqual(content.copyTitle(for: starter + "PROJECT_SETUP_PREAMBLE.txt"), "Save Example Text") XCTAssertNil(content.exampleURL(for: starter + "PROJECT_SETUP_PREAMBLE.txt")) let reference = "toolchain-reference/sources/" XCTAssertEqual(content.copyTitle(for: reference + "cmoc-manual.markdown"), "Save Original Manual Source") XCTAssertEqual(content.copyTitle(for: reference + "lwtools-manual.docbook.sgml"), "Save Original Manual Source") XCTAssertNil(content.copyTitle(for: reference + "lwtools-manual.pdf"), "PDFs remain readable in the library") for help in ["cmoc-help.txt", "lwasm-help.txt", "lwlink-help.txt"] { XCTAssertEqual(content.copyTitle(for: reference + help), "Save Command-Line Help") } XCTAssertTrue(content.allowsExternalReference(URL(string: "http://sarrazip.com/dev/cmoc.html")!)) XCTAssertTrue(content.allowsExternalReference(URL(string: "https://learn.chatgpt.com/docs/extend/mcp?surface=cli")!)) XCTAssertFalse(content.allowsExternalReference(URL(string: "https://example.com/unlisted")!)) XCTAssertFalse(content.allowsExternalReference(URL(fileURLWithPath: "/tmp/private.txt"))) } func testOriginalToolReferencesAreReadableThroughTheNativeMCPIndex() async throws { try requireFullManualEdition() let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) let root = try XCTUnwrap(app.url(forResource: "ManualLibrary", withExtension: nil)) let index = MCPHelpIndex(root: root) for query in ["CMOC --initial-s", "LWASM --project-map", "LWLINK --sysroot"] { let hits = try await index.search(query) let hit = try XCTUnwrap(hits.first { $0.id.hasPrefix("toolchain-reference/") }, query) let read = try await index.read(hit.id) XCTAssertFalse(try XCTUnwrap(read).text.isEmpty) } let source = try String(contentsOf: root.appendingPathComponent("toolchain-reference/book-index.js"), encoding: .utf8) let payload = source.dropFirst("(globalThis.manualBooks ??= []).push(".count).dropLast(3) let record = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(payload.utf8)) as? [String: Any]) for chapter in try XCTUnwrap(record["chapters"] as? [[String: Any]]) { let page = try XCTUnwrap(chapter["page"] as? String) for topic in try XCTUnwrap(chapter["sections"] as? [[String: Any]]) { let id = try XCTUnwrap(topic["id"] as? String) let read = try await index.read("toolchain-reference/\(page)#\(id)") XCTAssertLessThanOrEqual(try XCTUnwrap(read).text.utf8.count, 12 * 1024, "Every original-manual section must fit a complete read_topic response") } } } func testEveryBASICQuickReferenceTopicHasItsOwnBundledManualAnchor() throws { let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) let root = try XCTUnwrap(app.url(forResource: "ManualLibrary", withExtension: nil)) let content = ManualLibraryContent(root: root) let catalog = try BASICReferenceCatalog.bundled.get() var pages: [String: String] = [:] var links = Set() for entry in catalog.entries { let url = try XCTUnwrap(content.basicTopicURL(for: entry)) let page = try XCTUnwrap(content.relativePath(for: url), entry.id) let anchor = try XCTUnwrap(url.fragment, entry.id) if pages[page] == nil { pages[page] = try String(contentsOf: root.appendingPathComponent(page), encoding: .utf8) } XCTAssertTrue(links.insert(url).inserted, "Duplicate link for " + entry.id) XCTAssertTrue(pages[page]?.contains("id=\"\(anchor)\"") == true, entry.id) } } @MainActor func testHandbookKeyboardModeLabelsFitAtCompactAndDesktopWidths() async throws { try requireFullManualEdition() let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) let root = try XCTUnwrap(app.url(forResource: "ManualLibrary", withExtension: nil)) let page = root.appendingPathComponent("users-handbook/keyboard.html") for width in [320, 1024] { let reader = ManualReader(content: ManualLibraryContent(root: root)) reader.webView.frame = CGRect(x: 0, y: 0, width: width, height: 800) reader.webView.loadFileURL(page, allowingReadAccessTo: root) let deadline = ContinuousClock.now + .seconds(8) while reader.webView.url != page || reader.webView.isLoading { guard ContinuousClock.now < deadline else { return XCTFail("Keyboard chapter did not load") } try await Task.sleep(for: .milliseconds(40)) } let measurements = try await reader.webView.evaluateJavaScript(""" (() => { const rows = document.querySelectorAll('#keyboard-modes tr'); const lines = Array.from(rows, row => { const range = document.createRange(); range.selectNodeContents(row.cells[0].querySelector('strong') || row.cells[0]); return new Set(Array.from(range.getClientRects(), rect => rect.top)).size; }); return [innerWidth, document.documentElement.scrollWidth, ...lines]; })() """) XCTAssertEqual(measurements as? [Int], [width, width, 1, 1, 1, 1], "The page should fit and each of its four mode labels should occupy one line") } } @MainActor func testKeywordSearchUsesAllBundledBooksAndOpensLiteralCommand() async throws { try requireFullManualEdition() let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) let root = try XCTUnwrap(app.url(forResource: "ManualLibrary", withExtension: nil)) let reader = ManualReader(content: ManualLibraryContent(root: root)) let web = reader.webView reader.showLibrarySearch() let limit = ContinuousClock.now + .seconds(10) while web.isLoading || web.url == nil { guard ContinuousClock.now < limit else { return XCTFail("The manual shelf did not load") } try await Task.sleep(for: .milliseconds(30)) } let indexed = try await web.evaluateJavaScript("globalThis.manualBooks.map(book => book.book)") let shelved = try await web.evaluateJavaScript("Array.from(document.querySelectorAll('.shelf-catalog dt a'), link => link.textContent)") XCTAssertEqual(try XCTUnwrap(indexed as? [String]), try XCTUnwrap(shelved as? [String])) func search(_ query: String) async throws -> [String] { let result = try await web.callAsyncJavaScript(""" const field = document.getElementById("manual-query"); field.value = query; field.dispatchEvent(new Event("input")); return Array.from(document.querySelectorAll("#search-results a"), link => link.href); """, arguments: ["query": query], in: nil, contentWorld: .page) return try XCTUnwrap(result as? [String]) } let capitals = try await search("What happened on the M2") XCTAssertTrue(try XCTUnwrap(capitals.first).hasSuffix("/vibe-coding-with-chatgpt/06-capitals.html#m2-results")) let cmoc = try await search("--initial-s") XCTAssertTrue(cmoc.contains { $0.contains("/toolchain-reference/") }, "Bundled CMOC help must be searchable") let lwasm = try await search("--listcol") XCTAssertTrue(lwasm.contains { $0.contains("/toolchain-reference/") }, "Bundled LWASM help must be searchable") let forward = try await search("joystick keyboard") let reversed = try await search("KEYBOARD joystick") XCTAssertFalse(forward.isEmpty) XCTAssertEqual(Set(forward), Set(reversed)) let missing = try await search("joystick zzNoSuchKeyword") XCTAssertTrue(missing.isEmpty) let broad = try await search("CoCo") let total = try await web.evaluateJavaScript("parseInt(document.getElementById('search-status').textContent, 10)") XCTAssertGreaterThan(try XCTUnwrap(total as? Int), broad.count) let more = try await web.evaluateJavaScript("document.querySelector('#search-results + button').click(); document.querySelectorAll('#search-results a').length") XCTAssertGreaterThan(try XCTUnwrap(more as? Int), broad.count) let command = try await search("print@") let first = try XCTUnwrap(command.first) XCTAssertTrue(first.contains("/programming-in-coco-basic/reference.html#term-print-at"), first) let highlight = try await web.evaluateJavaScript("document.querySelector('#search-results a mark')?.textContent") XCTAssertEqual(highlight as? String, "PRINT@") _ = try await web.evaluateJavaScript("document.querySelector('#search-results a').click()") let pageLimit = ContinuousClock.now + .seconds(5) while web.url?.absoluteString != first || web.isLoading { guard ContinuousClock.now < pageLimit else { return XCTFail("The matching section did not open") } try await Task.sleep(for: .milliseconds(30)) } let heading = try await web.evaluateJavaScript("document.querySelector(':target h2').textContent") XCTAssertEqual(heading as? String, "PRINT@") } @MainActor func testPackagedReaderOpensSignalAndKeepsChapter() async throws { try requireFullManualEdition() let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) let root = try XCTUnwrap(app.url(forResource: "ManualLibrary", withExtension: nil)) let reader = ManualReader(content: ManualLibraryContent(root: root)) func waitForPage(_ name: String) async throws { let limit = ContinuousClock.now + .seconds(8) while reader.webView.url?.lastPathComponent != name || reader.webView.isLoading { guard ContinuousClock.now < limit else { XCTFail("Timed out loading " + name + ": " + (reader.error ?? "no navigation error")) throw CocoaError(.fileReadUnknown) } try await Task.sleep(for: .milliseconds(40)) } } reader.showHome() try await waitForPage("index.html") _ = try await reader.webView.evaluateJavaScript("document.querySelector('.shelf-routes a').click(); true") try await waitForPage("template.html") _ = try await reader.webView.evaluateJavaScript("document.querySelector('a[href*=catch-the-computer]').click(); true") try await waitForPage("catch-the-computer.html") let chapter = reader.webView.url let opened = expectation(description: "Open the bundled example in BASIC") reader.openExample = { path in XCTAssertEqual(path, "meet-your-color-computer/examples/SIGNAL.bas") opened.fulfill() } _ = try await reader.webView.evaluateJavaScript("document.querySelector('a[href$=\"SIGNAL.bas\"]').click(); true") await fulfillment(of: [opened], timeout: 5) XCTAssertEqual(reader.webView.url, chapter) XCTAssertTrue(reader.webView.canGoBack) } @MainActor func testUpdatedHandbookAndCapitalQuestFitAndLoadFigures() async throws { try requireFullManualEdition() let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) let root = try XCTUnwrap(app.url(forResource: "ManualLibrary", withExtension: nil)) let pages = ["users-handbook/desk.html", "users-handbook/media.html", "users-handbook/workbenches.html", "vibe-coding-with-chatgpt/04-c.html", "vibe-coding-with-chatgpt/06-capitals.html", "vibe-coding-with-chatgpt/08-field-guide.html", "vibe-coding-with-chatgpt/09-start-a-project.html", "toolchain-reference/index.html", "toolchain-reference/cmoc.html", "toolchain-reference/lwtools.html", "toolchain-reference/command-line.html"] for width in [420, 1024] { for path in pages { let reader = ManualReader(content: ManualLibraryContent(root: root)) let web = reader.webView web.frame = CGRect(x: 0, y: 0, width: width, height: 850) let page = root.appendingPathComponent(path) web.loadFileURL(page, allowingReadAccessTo: root) let deadline = ContinuousClock.now + .seconds(12) while web.url != page || web.isLoading { guard ContinuousClock.now < deadline else { return XCTFail("Manual did not load: " + path) } try await Task.sleep(for: .milliseconds(40)) } let images = try await web.callAsyncJavaScript(""" await document.fonts.ready; await Promise.all(Array.from(document.images, image => image.decode().catch(() => {}))); return Array.from(document.images).filter(image => !image.complete || image.naturalWidth === 0).map(image => image.getAttribute('src')); """, contentWorld: .page) XCTAssertEqual(images as? [String], [], "Every figure must load: " + path) let size = try await web.evaluateJavaScript("[innerWidth, document.documentElement.scrollWidth]") XCTAssertEqual(size as? [Int], [width, width], "The complete page must fit the reader: " + path) if width == 1024, ["users-handbook/desk.html", "users-handbook/media.html", "vibe-coding-with-chatgpt/06-capitals.html"].contains(path) { let anchor = path.contains("desk") ? "archive-reviewed-code" : path.contains("media") ? "disk-image-editor" : "capital-quest" _ = try await web.callAsyncJavaScript("document.getElementById(anchor).scrollIntoView();", arguments: ["anchor": anchor], contentWorld: .page) let image = try await web.takeSnapshot(configuration: nil) let attachment = XCTAttachment(image: image) attachment.name = "Updated manual — " + path attachment.lifetime = .keepAlways add(attachment) } } } } private func lookup(_ marked: String) -> String? { let marker = (marked as NSString).range(of: "|") precondition(marker.location != NSNotFound) let source = (marked as NSString).replacingCharacters(in: marker, with: "") return BASICReferenceContext.keyword(in: source, at: marker.location) } func testContextResolvesCompositeCommandsAndTokenBoundaries() { let cases: [(String, String)] = [ ("10 LOA|DM \"PROGRAM\"", "LOADM"), ("10 SAVEM| \"PROGRAM\",100,200,100", "SAVEM"), ("10 CLOADM| \"PROGRAM\"", "CLOADM"), ("10 CSAVE|M \"PROGRAM\",100,200,100", "CSAVEM"), ("10 LINE IN|PUT A$", "LINE INPUT"), ("10 LINEINPUT A$|", "LINE INPUT"), ("10 ON ER|R GOTO 100", "ON ERR"), ("10 ONERRGOTO 100|", "ON ERR"), ("10 DEF F|NX(A)=A*2", "DEF FN"), ("10 PRINT US|ING \"###\";A", "PRINT USING"), ("10 PRINT@ 100, A|", "PRINT@"), ("10 PRINT @ 100, A|", "PRINT@"), ("10 GO TO 100|", "GOTO"), ("10 GOSUB 100|", "GOSUB"), ("10 go sub 100|", "GOSUB"), ("10 PRINT| A", "PRINT"), ("10 DATA|", "DATA"), ("10 REM|", "REM") ] for (source, expected) in cases { XCTAssertEqual(lookup(source), expected, source) } } func testContextPrefersPointedFunctionAndOtherwiseUsesOwningStatement() { XCTAssertEqual(lookup("10 PRINT LE|FT$(A$,2)"), "LEFT$") XCTAssertEqual(lookup("10 PRINT LEFT$(A$,2|)"), "PRINT") XCTAssertEqual(lookup("10 A=RN|D(6)"), "RND") XCTAssertEqual(lookup("10 A=RND(6|)"), "LET") XCTAssertEqual(lookup("10 A=42|"), "LET") XCTAssertEqual(lookup("10 FOR I=1 TO 10|"), "FOR") XCTAssertEqual(lookup("10 FOR I=1 TO 10:PRINT I|"), "PRINT") XCTAssertEqual(lookup("10 IF A THEN PRINT A| ELSE PRINT B"), "PRINT") XCTAssertEqual(lookup("10 IF A THEN PRINT A ELSE B=RND(6|)"), "LET") XCTAssertEqual(lookup("10 IF A THEN 100|"), "IF") XCTAssertEqual(lookup("10 ON A GOSUB 100,200|"), "ON") XCTAssertEqual(lookup("10 INPUT \"TIME: \";A|"), "INPUT") } func testContextIgnoresLiteralCommentAndDataContents() { for source in ["10 PRINT \"LE|FT$\"", "10 PRINT \"UNFINISHED|", "10 REM PRI|NT 1", "10 'PRI|NT 1", "10 DATA PRINT,LOAD|", "10 DATA \"PRINT:|LOAD\",1", "10 PRINT 1|:PRINT 2"] { XCTAssertNil(lookup(source), source) } XCTAssertEqual(lookup("10 DATA \"PRINT:LOAD\",1:PR|INT A"), "PRINT") XCTAssertEqual(lookup("10 PRINT \"A:B\":SOUND 100,2|"), "SOUND") XCTAssertEqual(lookup("10 REM 😀\r\n20 PR|INT A"), "PRINT") XCTAssertNil(lookup("10| PRINT 1")) XCTAssertNil(lookup("10 PRINT 1\n|")) } func testContextRejectsInvalidOrExcessiveOffsetsWithoutChangingSource() { let source = "10 PRINT 1\n" XCTAssertNil(BASICReferenceContext.keyword(in: source, at: -1)) XCTAssertNil(BASICReferenceContext.keyword(in: source, at: Int.max)) XCTAssertNil(BASICReferenceContext.keyword(in: "", at: 0)) XCTAssertNil(BASICReferenceContext.keyword(in: String(repeating: "A", count: BASICLanguage.maximumSourceBytes + 1), at: 1)) XCTAssertEqual(source, "10 PRINT 1\n") } private func fixture() throws -> BASICReferenceCatalog { let rows: [(String, String, String, String)] = [ ("PRINT", "PRINT", "common", "Text"), ("DRIVE", "DRIVE", "disk", "Storage"), ("RGB.DRIVE", "DRIVE", "rgbdos", "Storage"), ("SDC.DRIVE", "DRIVE", "sdcdos", "Storage"), ("ERROR.SN", "SN", "common", "Errors") ] let entries: [[String: Any]] = rows.map { id, keyword, dialect, category in ["id": id, "keyword": keyword, "title": id, "category": category, "dialect": dialect, "summary": id == "SDC.DRIVE" ? "Mount an image in a drive." : "Reference for " + keyword, "syntax": [keyword], "parameters": [], "sample": keyword, "related": id == "PRINT" ? ["DRIVE"] : [], "notes": [], "source": "basicGuide", "sourcePage": "1"] } let data = try JSONSerialization.data(withJSONObject: ["entries": entries, "examples": []]) return try JSONDecoder().decode(BASICReferenceCatalog.self, from: data) } func testEveryTopicCitesAnOfflineWorkWithItsOriginalPageConvention() throws { let catalog = try BASICReferenceCatalog.bundled.get() XCTAssertEqual(Set(catalog.entries.map(\.source)), Set(BASICReferenceWork.allCases)) let rgb = try XCTUnwrap(catalog.entries.first { $0.source == .rgbdos }) XCTAssertTrue(rgb.citation.contains("Krupski")) XCTAssertTrue(rgb.citation.contains("PDF page")) XCTAssertTrue(catalog.entries.contains { $0.citation.contains("1986. p. 27.") }) XCTAssertTrue(catalog.entries.allSatisfy { !$0.citation.contains("://") }) } @MainActor func testBrowserLookupSelectsDialectAndClearsFilters() throws { let model = BASICReferenceModel(catalog: try fixture()) model.category = "Text"; model.search = "print" model.show(keyword: "drive", dialect: .sdcdos) XCTAssertEqual(model.selectedID, "SDC.DRIVE") XCTAssertNil(model.category); XCTAssertEqual(model.search, "") model.show(keyword: "DRIVE", dialect: .rgbdos) XCTAssertEqual(model.selectedID, "RGB.DRIVE") model.show(keyword: "DRIVE") XCTAssertEqual(model.selectedID, "DRIVE") model.showError(code: "sn") XCTAssertEqual(model.selectedID, "ERROR.SN") } @MainActor func testBrowserSearchCategoriesAndPinnedSelection() throws { let model = BASICReferenceModel(catalog: try fixture()) model.show(keyword: "DRIVE", dialect: .sdcdos) _ = BASICReferenceContext.keyword(in: "10 PRINT 42", at: 5) XCTAssertEqual(model.selectedID, "SDC.DRIVE", "Reading cursor context must not replace a pinned topic") model.search = "mount IMAGE" XCTAssertEqual(model.filteredEntries.map(\.id), ["SDC.DRIVE"]) model.category = "Text" XCTAssertTrue(model.filteredEntries.isEmpty); XCTAssertNil(model.selectedID) model.category = nil; model.search = "" XCTAssertEqual(model.filteredEntries.count, 5) XCTAssertEqual(model.relatedEntry("DRIVE")?.id, "DRIVE") XCTAssertNil(model.relatedEntry("not-a-topic")) } func testBundledCatalogCoverageLinksAndExampleStructure() throws { let catalog = try BASICReferenceCatalog.bundled.get() let ids = Set(catalog.entries.map(\.id)) XCTAssertEqual(ids.count, catalog.entries.count, "Topic identifiers must be unique") let keywords = Set(catalog.entries.map { $0.keyword.uppercased() }) XCTAssertTrue(Set(BASICLanguage.words).subtracting(keywords).isEmpty, "Every completion keyword should have a reference topic") for keyword in ["LOADM", "SAVEM", "CLOADM", "CSAVEM", "LINE INPUT", "ON ERR", "DEF FN", "PRINT USING", "PRINT@"] { XCTAssertTrue(keywords.contains(keyword), keyword) } let exampleIDs = Set(catalog.examples.map(\.id)) XCTAssertEqual(exampleIDs.count, catalog.examples.count) XCTAssertFalse(catalog.examples.isEmpty) for entry in catalog.entries { XCTAssertFalse(entry.summary.isEmpty, entry.id) XCTAssertFalse(entry.citation.isEmpty, entry.id) XCTAssertTrue(Set(entry.related).isSubset(of: ids), "Broken related topic in " + entry.id) if let exampleID = entry.exampleID { XCTAssertTrue(exampleIDs.contains(exampleID), entry.id) } } for example in catalog.examples { let analysis = BASICLanguage.analyze(example.source) XCTAssertFalse(analysis.hasErrors, example.id) XCTAssertFalse(analysis.lines.isEmpty, example.id) XCTAssertFalse(example.expectedOutput.isEmpty, example.id) } } @MainActor func testExampleWorkspaceKeepsOriginalDraftAndMachineOwnership() async throws { let directory = FileManager.default.temporaryDirectory.appendingPathComponent("BASICReference-" + UUID().uuidString) let suite = "BASICReference-" + UUID().uuidString let defaults = UserDefaults(suiteName: suite)! defer { defaults.removePersistentDomain(forName: suite); try? FileManager.default.removeItem(at: directory) } let machine = MachineModel(diskStore: .init(url: directory.appendingPathComponent("disks.json")), displayDefaults: defaults, inputStore: .init(url: directory.appendingPathComponent("input.json"))) let originalDirectory = directory.appendingPathComponent("original") let exampleDirectory = directory.appendingPathComponent("example") let original = BASICDevelopmentModel(machine: machine, directory: originalDirectory) original.source = "10 PRINT \"MY UNSAVED WORK\"\n" original.persistDraft() machine.basicWorkspaceOwner = original.workspaceID let source = "10 PRINT 42\n20 END\n" let example = BASICDevelopmentModel(machine: machine, directory: exampleDirectory, initialSource: source, title: "Reference Example") XCTAssertEqual(example.source, source) XCTAssertEqual(example.title, "Reference Example") XCTAssertFalse(example.dirty) XCTAssertNil(example.fileURL) XCTAssertNotEqual(original.workspaceID, example.workspaceID) example.source = "10 PRINT 43\n20 END\n" example.persistDraft() XCTAssertEqual(machine.basicWorkspaceOwner, original.workspaceID) XCTAssertEqual(original.source, "10 PRINT \"MY UNSAVED WORK\"\n") XCTAssertTrue(original.dirty) XCTAssertNil(original.fileURL) let restoredExample = BASICDevelopmentModel(machine: machine, directory: exampleDirectory, initialSource: source, title: "Reference Example") let restoredOriginal = BASICDevelopmentModel(machine: machine, directory: originalDirectory) XCTAssertEqual(restoredExample.source, example.source) XCTAssertTrue(restoredExample.dirty) XCTAssertEqual(restoredOriginal.source, original.source) XCTAssertTrue(restoredOriginal.dirty) XCTAssertEqual(machine.basicWorkspaceOwner, original.workspaceID) await withCheckedContinuation { continuation in machine.shutdown { continuation.resume() } } } }