import Foundation import HelderCore import HelderServices @testable import HelderUI import Testing /// `users` plus tables that each point at it through `user_id`, in name order. func schemaSample(_ names: [String] = ["posts", "users"]) -> SchemaModel { let tables = names.sorted().map { name in SchemaTable(name: name, rows: 3, columns: [ SchemaColumn(name: "id", type: "bigint", isPrimary: true), SchemaColumn(name: "user_id", type: "bigint", isForeign: name != "users", foreignTarget: name == "users" ? nil : SchemaColumnRef(table: "users", column: "id")), ]) } let edges = names.sorted().filter { $0 != "users" }.map { SchemaEdge(from: $0, column: "user_id", columnIndex: 1, to: "users", targetColumnIndex: 0) } return SchemaModel(connectionLabel: "mysql · shop", tables: tables, edges: edges) } @MainActor @Suite struct SchemaViewAvailabilityTests { @Test func aProjectWithoutArtisanHasNoSchemaView() async { let harness = WorkspaceHarness() harness.schema.setLaravelApp(false) await harness.start() await harness.perform(.toggleSchemaView) #expect(!harness.model.layout.isSchemaViewOpen) #expect(harness.model.schema?.isLaravelApp == false) } @Test func aLaravelAppWithoutTheCommandOpensOnTheCommandPrompt() async throws { let harness = WorkspaceHarness() await harness.start() await harness.perform(.toggleSchemaView) let schema = try #require(harness.model.schema) #expect(harness.model.layout.isSchemaViewOpen) #expect(schema.body == .commandMissing) #expect(schema.metaLabel == "no command yet") await harness.perform(.toggleSchemaView) #expect(!harness.model.layout.isSchemaViewOpen) } @Test func anExistingDumpLoadsWhenTheViewOpens() async throws { let harness = WorkspaceHarness() harness.schema.setHasCommand(true) harness.schema.setDump(schemaSample()) await harness.start() #expect(harness.schema.reads == 0) await harness.perform(.toggleSchemaView) let schema = try #require(harness.model.schema) #expect(schema.body == .diagram) #expect(schema.metaLabel.hasPrefix("dumped ")) #expect(schema.metaLabel.hasSuffix(" · 2 tables · 1 relations")) #expect(schema.runLabel == "Re-run helder:schema") } @Test func theGitAndSchemaViewsNeverShowTogether() async { let harness = WorkspaceHarness() await harness.start() await harness.perform(.toggleSchemaView) await harness.perform(.toggleGit) #expect(harness.model.layout.isGitViewOpen) #expect(!harness.model.layout.isSchemaViewOpen) await harness.perform(.toggleSchemaView) #expect(harness.model.layout.isSchemaViewOpen) #expect(!harness.model.layout.isGitViewOpen) } @Test func closingGivesTheKeyboardBackToTheColumn() async { let harness = WorkspaceHarness() await harness.start() harness.model.perform(.focus(.terminal)) await harness.perform(.toggleSchemaView) #expect(harness.model.focusRequest == nil) await harness.perform(.closeSchemaView) #expect(harness.model.focusRequest?.target == .panel(.terminal)) } } @MainActor @Suite struct SchemaCommandPromptTests { @Test func generateCommandPastesThePromptUnsentAndClosesTheView() async { let harness = WorkspaceHarness() await harness.start() await harness.perform(.toggleSchemaView) await harness.perform(.generateSchemaCommand) #expect(!harness.model.layout.isSchemaViewOpen) #expect(harness.agent.sent == [BracketedPaste.wrap(SchemaCommandPrompt.text, composerHasText: false)]) #expect(harness.agent.sent.allSatisfy { !$0.hasSuffix("\r") }) #expect(harness.model.toasts.toasts.last?.title == "Passed to agent") #expect(harness.model.toasts.toasts.last?.detail == "Command prompt") } @Test func copyPromptCopiesAndToasts() async { let harness = WorkspaceHarness() await harness.start() await harness.perform(.toggleSchemaView) await harness.perform(.copySchemaPrompt) #expect(harness.system.copied == [SchemaCommandPrompt.text]) #expect(harness.toastTitles == ["Copied prompt"]) #expect(harness.model.layout.isSchemaViewOpen) } } @MainActor @Suite struct SchemaRunTests { @Test func aSuccessfulRunStreamsReloadsAndToasts() async throws { let harness = WorkspaceHarness() harness.schema.setHasCommand(true) harness.schema.setRun(FakeSchemaRun(lines: [(" Tables ........ 2", false), (" Wrote database/helder/schema.json (1 KB)", false)], writes: schemaSample())) await harness.start() await harness.perform(.toggleSchemaView) let schema = try #require(harness.model.schema) #expect(schema.body == .noDump) #expect(schema.runLabel == "Run helder:schema") await harness.perform(.runSchemaDump) #expect(schema.body == .diagram) #expect(schema.lines.map(\.line.text) == ["$ php artisan helder:schema", " Tables ........ 2", " Wrote database/helder/schema.json (1 KB)"]) #expect(schema.lines.map(\.line.kind) == [.command, .output, .success]) #expect(schema.isConsoleOpen) #expect(!schema.isBusy) #expect(harness.toastTitles == ["Schema dumped · 2 tables"]) } @Test func aFailedRunKeepsTheConsoleOpenAndToastsNothing() async throws { let harness = WorkspaceHarness() harness.schema.setHasCommand(true) harness.schema.setRun(FakeSchemaRun(exitCode: 1, lines: [(" ERROR Connection refused.", false), ("trace", true)])) await harness.start() await harness.perform(.toggleSchemaView) let schema = try #require(harness.model.schema) schema.hideConsole() await harness.perform(.runSchemaDump) #expect(schema.isConsoleOpen) #expect(schema.model == nil) #expect(schema.lines.last?.line.kind == .error) #expect(harness.toastTitles.isEmpty) } @Test func aClickWhileItRunsIsIgnored() async { let harness = WorkspaceHarness() harness.schema.setHasCommand(true) harness.schema.setRun(FakeSchemaRun(writes: schemaSample(), delay: .milliseconds(150))) await harness.start() await harness.perform(.toggleSchemaView) harness.model.perform(.runSchemaDump) #expect(await eventually { harness.model.schema?.isBusy == true }) #expect(harness.model.schema?.runLabel == "Dumping…") harness.model.perform(.runSchemaDump) await harness.model.settle() #expect(harness.schema.runs == 1) } @Test func withoutTheCommandRunDoesNothing() async { let harness = WorkspaceHarness() await harness.start() await harness.perform(.toggleSchemaView) await harness.perform(.runSchemaDump) #expect(harness.schema.runs == 0) } @Test func aCorruptDumpShowsItsErrorInTheConsoleAndAToast() async throws { let harness = WorkspaceHarness() harness.schema.setHasCommand(true) harness.schema.setDump(schemaSample()) harness.schema.setReadError(SchemaDumpError.corrupt(reason: "Unexpected character")) await harness.start() await harness.perform(.toggleSchemaView) let schema = try #require(harness.model.schema) #expect(schema.model == nil) #expect(schema.loadError?.contains("Unexpected character") == true) #expect(schema.lines.last?.line.kind == .error) #expect(schema.isConsoleOpen) #expect(harness.toastTitles == ["Could not read the schema"]) } } @MainActor @Suite struct SchemaLiveTests { @Test func theViewFlipsWhenTheCommandAndItsDumpAppear() async throws { let harness = WorkspaceHarness() await harness.start() await harness.perform(.toggleSchemaView) let schema = try #require(harness.model.schema) #expect(schema.body == .commandMissing) harness.schema.setHasCommand(true) try #require(harness.watchers.last).emit(.project) #expect(await eventually { schema.body == .noDump }) harness.schema.setDump(schemaSample()) try #require(harness.watchers.last).emit(.project) #expect(await eventually { schema.body == .diagram }) } @Test func aChangedDumpReloadsKeepingTheViewAndPositions() async throws { let harness = WorkspaceHarness() harness.schema.setHasCommand(true) harness.schema.setDump(schemaSample(), date: Date(timeIntervalSince1970: 1000)) await harness.start() await harness.perform(.toggleSchemaView) let schema = try #require(harness.model.schema) let view = SchemaViewport(x: 120, y: -40, scale: 0.8) schema.setViewport(view) let moved = SchemaPoint(x: 900, y: 700) schema.moveTable("users", to: moved) schema.endDrag() let grown = schemaSample(["comments", "posts", "users"]) harness.schema.setDump(grown, date: Date(timeIntervalSince1970: 2000)) try #require(harness.watchers.last).emit(.project) #expect(await eventually { schema.model?.tableCount == 3 }) #expect(schema.viewport == view) #expect(schema.positions["users"] == moved) #expect(schema.positions["comments"] == SchemaLayout.defaultPositions(grown)["comments"]) } @Test func anUnchangedDumpIsNotReadAgain() async throws { let harness = WorkspaceHarness() harness.schema.setHasCommand(true) harness.schema.setDump(schemaSample(), date: Date(timeIntervalSince1970: 1000)) await harness.start() await harness.perform(.toggleSchemaView) #expect(harness.schema.reads == 1) try #require(harness.watchers.last).emit(.project) #expect(await eventually { harness.git.loads >= 2 }) await harness.model.settle() #expect(harness.schema.reads == 1) } } @MainActor @Suite struct SchemaCanvasStateTests { private func opened(saved: [String: SchemaPoint]? = nil) async throws -> (WorkspaceHarness, SchemaStore) { let harness = WorkspaceHarness() harness.schema.setHasCommand(true) harness.schema.setDump(schemaSample()) if let saved { harness.schemaLayouts.saved = [harness.root.path: saved] } await harness.start() await harness.perform(.toggleSchemaView) return (harness, try #require(harness.model.schema)) } @Test func positionsAreSavedWhenADragEndsAndComeBackNextTime() async throws { let (harness, schema) = try await opened() let point = SchemaPoint(x: 512, y: 64) schema.moveTable("posts", to: point) #expect(harness.schemaLayouts.saved.isEmpty) schema.endDrag() #expect(harness.schemaLayouts.saved[harness.root.path]?["posts"] == point) let (_, again) = try await opened(saved: ["posts": point]) #expect(again.positions["posts"] == point) #expect(again.positions["users"] == SchemaLayout.defaultPositions(schemaSample())["users"]) } @Test func theFirstDumpFitsOnceTheCanvasHasASize() async throws { let (_, schema) = try await opened() #expect(schema.viewport == SchemaViewport()) schema.setCanvasSize(SchemaSize(width: 1000, height: 600)) let bounds = try #require(SchemaGeometry.bounds(schemaSample(), positions: schema.positions)) #expect(schema.viewport == SchemaGeometry.fit(bounds: bounds, in: SchemaSize(width: 1000, height: 600))) schema.setViewport(SchemaViewport(x: 5, y: 5, scale: 1)) schema.setCanvasSize(SchemaSize(width: 1200, height: 600)) #expect(schema.viewport == SchemaViewport(x: 5, y: 5, scale: 1)) } @Test func centringLeavesRoomForTheDetailPanelThatOpens() async throws { let (_, schema) = try await opened() schema.setCanvasSize(SchemaSize(width: 1000, height: 600)) let before = schema.viewport let users = try #require(schemaSample().table(named: "users")) schema.centre("users") #expect(schema.selected == "users") #expect(schema.viewport == SchemaGeometry.centre(users, at: schema.positions["users"]!, in: SchemaSize(width: 680, height: 600), view: before)) let posts = try #require(schemaSample().table(named: "posts")) let open = schema.viewport schema.centre("posts") #expect(schema.viewport == SchemaGeometry.centre(posts, at: schema.positions["posts"]!, in: SchemaSize(width: 1000, height: 600), view: open)) } @Test func enterInTheSearchCentresTheFirstMatch() async throws { let (_, schema) = try await opened() schema.setCanvasSize(SchemaSize(width: 1000, height: 600)) schema.query = "us" schema.centreFirstMatch() #expect(schema.selected == "users") schema.query = "nothing" schema.clearSelection() schema.centreFirstMatch() #expect(schema.selected == nil) } @Test func aClickSelectsAndASecondClickDeselects() async throws { let (harness, schema) = try await opened() schema.toggleSelection("users") #expect(schema.selectedTable?.name == "users") schema.toggleSelection("users") #expect(schema.selected == nil) schema.toggleSelection("posts") await harness.perform(.clearSchemaSelection) #expect(schema.selected == nil) schema.query = "po" await harness.perform(.clearSchemaSearch) #expect(schema.query.isEmpty) } @Test func hoverWaitsWhileACardIsDragged() async throws { let (_, schema) = try await opened() schema.moveTable("posts", to: SchemaPoint(x: 1, y: 1)) schema.hover("users") #expect(schema.hovered == nil) schema.endDrag() schema.hover("users") schema.hoverColumn("posts.user_id") #expect(schema.highlight?.activeEdges == ["posts.user_id"]) schema.hover(nil) #expect(schema.hoveredColumn == nil) } @Test func passOnAndCopyNameUseTheTable() async throws { let (harness, _) = try await opened() await harness.perform(.copySchemaTableName("users")) #expect(harness.system.copied == ["users"]) #expect(harness.toastTitles == ["Copied table name"]) await harness.perform(.passSchemaTable("users")) #expect(!harness.model.layout.isSchemaViewOpen) #expect(harness.agent.sent == [BracketedPaste.wrap("@schema:users", composerHasText: false)]) } @Test func theCommandPathOpensTheCommandInTheEditor() async { let harness = WorkspaceHarness(contents: [SchemaPaths.commandFile: "