test: drop source-text assertion tests and merge locale checks

This commit is contained in:
t8y2 committed 2026-09-23 22:10:06 +08:00
1 parent 349d77d180
commit 8897e12714
257 files changed
+166 -12815

No files matched your search

@@ -1,65 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "utf8");
describe("add to AI database context", () => {
it("accepts database tree nodes with an empty database identifier", () => {
const addToAiStart = appSource.indexOf("async function addToAi");
const addToAiEnd = appSource.indexOf("function openAiPanel", addToAiStart);
const addToAiSource = appSource.slice(addToAiStart, addToAiEnd);
expect(addToAiSource).toContain("else if (hasTreeNodeDatabaseContext(node))");
expect(addToAiSource).not.toContain("else if (node.database)");
});
it("adds every selected table as an AI mention", () => {
const addToAiStart = appSource.indexOf("async function addToAi");
const addToAiEnd = appSource.indexOf("function openAiPanel", addToAiStart);
const addToAiSource = appSource.slice(addToAiStart, addToAiEnd);
expect(addToAiSource).toContain("Array.isArray(nodesInput) ? nodesInput : [nodesInput]");
expect(addToAiSource).toContain('entry.type === "table"');
// Every selected table still becomes a mention, and it now carries the
// binding the conversation must adopt (#9902).
expect(addToAiSource).toContain("for (const mention of tableMentions) handle.addTableMention(mention, binding)");
});
it("retargets the conversation instead of moving the workspace (#9902)", () => {
const addToAiStart = appSource.indexOf("async function addToAi");
const addToAiEnd = appSource.indexOf("function openAiPanel", addToAiStart);
const addToAiSource = appSource.slice(addToAiStart, addToAiEnd);
expect(addToAiSource).toContain("const binding: AiConversationBinding = { connectionId: node.connectionId");
// Asking about a table must not reassign the global active connection or
// switch/create an editor tab — that is what made the AI panel's target
// global.
expect(addToAiSource).not.toContain("connectionStore.activeConnectionId =");
expect(addToAiSource).not.toContain("queryStore.switchTab(");
expect(addToAiSource).not.toContain("queryStore.createTab(");
});
it("retargets even when the entry adds no table mention", () => {
// "Ask AI" on a connection or database node produces no mentions at all, so
// applying the binding only inside the mention loop would silently skip it.
const addToAiStart = appSource.indexOf("async function addToAi");
const addToAiEnd = appSource.indexOf("function openAiPanel", addToAiStart);
const addToAiSource = appSource.slice(addToAiStart, addToAiEnd);
expect(addToAiSource).toContain("void handle.bindConversation(binding);");
// The call must not live inside the mention loop.
const loopIdx = addToAiSource.indexOf("for (const mention of tableMentions)");
const bindIdx = addToAiSource.indexOf("void handle.bindConversation(binding);");
expect(bindIdx).toBeLessThan(loopIdx);
});
it("resolves the AI execution tab by the exact namespace", () => {
// `(!schema || tab.schema === schema)` used to accept a tab on ANY schema
// when the target had none, and execution then inherited that tab's schema.
const start = appSource.indexOf("function ensureQueryTabForConnection");
const body = appSource.slice(start, appSource.indexOf("queryStore.createTab", start));
expect(body).toContain("(tab.schema || undefined) === schema");
expect(body).not.toContain("!schema ||");
});
});
@@ -1,9 +1,6 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { MAX_AGENT_TURNS_DEFAULT, MAX_AGENT_TURNS_MAX, MAX_AGENT_TURNS_MIN, maxAgentTurnsOutOfRange, normalizeMaxAgentTurns } from "@/lib/ai/maxAgentTurns";
const settingsDialogSource = readFileSync(new URL("../../../components/editor/EditorSettingsDialog.vue", import.meta.url), "utf8");
describe("maxAgentTurnsOutOfRange", () => {
it("accepts values within [min, max]", () => {
expect(maxAgentTurnsOutOfRange(30)).toBe(false);
@@ -27,24 +24,6 @@ describe("maxAgentTurnsOutOfRange", () => {
});
});
describe("agent turn limit loading", () => {
it("starts loading independently and blocks saves until the persisted value arrives", () => {
const aiTabStart = settingsDialogSource.indexOf('if (tab === "ai") {');
const aiTabBranch = settingsDialogSource.slice(aiTabStart, settingsDialogSource.indexOf('if (tab === "about"', aiTabStart));
expect(aiTabBranch.indexOf("void loadMaxAgentTurnsSetting()")).toBeLessThan(aiTabBranch.indexOf("await promptTemplateStore.ensureLoaded()"));
expect(settingsDialogSource).toContain("if (!maxAgentTurnsLoaded.value) return;");
expect(settingsDialogSource).toContain(':disabled="!maxAgentTurnsLoaded || maxAgentTurnsSaving"');
expect(settingsDialogSource).toContain(':disabled="!maxAgentTurnsLoaded || maxAgentTurnsSaving || maxAgentTurnsOutOfRange(editMaxAgentTurns)"');
});
it("keeps failed loads retryable instead of replacing them with the default", () => {
const loadFunction = settingsDialogSource.slice(settingsDialogSource.indexOf("async function loadMaxAgentTurnsSetting()"), settingsDialogSource.indexOf("async function saveMaxAgentTurnsSetting()"));
expect(loadFunction).toContain("maxAgentTurnsLoadError.value = e?.message || String(e)");
expect(loadFunction).not.toContain("editMaxAgentTurns.value = MAX_AGENT_TURNS_DEFAULT");
expect(settingsDialogSource).toContain('v-if="maxAgentTurnsLoadError"');
});
});
describe("normalizeMaxAgentTurns", () => {
it("preserves and rounds finite values within the supported range", () => {
expect(normalizeMaxAgentTurns(100)).toBe(100);
@@ -1,82 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "utf8");
const toolbarSource = readFileSync(new URL("../../../components/layout/AppToolbar.vue", import.meta.url), "utf8");
function functionSource(name: string, nextName: string): string {
const start = appSource.indexOf(`function ${name}`);
const end = appSource.indexOf(`function ${nextName}`, start + 1);
return appSource.slice(start, end);
}
describe("right sidebar panel entry points", () => {
it("routes toolbar and close actions through the centralized controller", () => {
expect(appSource).toContain("@toggle-ai=\"toggleRightSidebarPanel('ai')\"");
expect(appSource).toContain("@toggle-history=\"toggleRightSidebarPanel('history')\"");
expect(appSource).toContain("@toggle-sql-library=\"toggleRightSidebarPanel('sqlLibrary')\"");
expect(appSource).toContain("@toggle-sql-file-panel=\"toggleRightSidebarPanel('sqlFile')\"");
expect(appSource).toContain("@close=\"closeRightSidebarPanel('history')\"");
expect(appSource).toContain("@close=\"closeRightSidebarPanel('sqlLibrary')\"");
expect(appSource).toContain("@close=\"closeRightSidebarPanel('sqlFile')\"");
});
it("toggles the AI panel through the configured global shortcut", () => {
expect(appSource).toContain("isToggleAiPanelShortcut(e, shortcuts)");
expect(appSource).toContain('toggleRightSidebarPanel("ai");');
});
it("routes welcome, history analysis, selection, and error-fix opens through the same controller", () => {
expect(appSource).toContain("@show-history=\"openRightSidebarPanel('history')\"");
expect(functionSource("fixWithAi", "sendSelectionToAi")).toContain('openRightSidebarPanel("ai")');
expect(functionSource("sendSelectionToAi", "openAiPanel")).toContain('openRightSidebarPanel("ai")');
expect(functionSource("openAiPanel", "analyzeHistoryWithAi")).toContain('openRightSidebarPanel("ai")');
});
it("keeps existing persisted panel keys and synchronizes exclusivity after settings load", () => {
expect(appSource).toContain('ai: "dbx-ai-panel-open"');
expect(appSource).toContain('sqlLibrary: "dbx-sql-library-open"');
expect(appSource).toContain('sqlFile: "dbx-sql-file-panel-open"');
expect(appSource).not.toContain('history: "dbx-');
expect(appSource).toContain("settingsStore.isEditorSettingsLoaded");
expect(appSource).toContain("enforceRightSidebarPanelExclusivity(currentRightSidebarPanelState(), lastOpenedRightSidebarPanel)");
});
it("does not couple toolbar visibility to panel closing", () => {
for (const [setting, event] of [
["sqlLibrary", "toggle-sql-library"],
["sqlFileTree", "toggle-sql-file-panel"],
["history", "toggle-history"],
["ai", "toggle-ai"],
]) {
expect(toolbarSource).toContain(`<Tooltip v-if="toolbarItems.${setting}">`);
expect(toolbarSource).toContain(`@click="emit('${event}')"`);
}
expect(appSource).not.toMatch(/watch\([\s\S]{0,180}toolbarItems\.(ai|history|sqlLibrary|sqlFileTree)[\s\S]{0,180}closeRightSidebarPanel/);
});
it("keeps the maximized AI surface in the parent layout", () => {
expect(appSource).toContain("const isAiPanelMaximized = ref(false);");
expect(appSource).toContain(':maximized="isAiPanelMaximized"');
expect(appSource).toContain('@toggle-maximize="toggleAiPanelMaximized"');
expect(appSource).toContain("isAiPanelMaximized ? 'min-w-0 flex-1' : 'min-w-[240px] max-w-full'");
expect(appSource).toContain('v-show="!isAiPanelMaximized && !isZenMode"');
expect(functionSource("setRightSidebarPanelOpen", "toggleRightSidebarPanel")).toContain("isAiPanelMaximized.value = false;");
});
it("keeps Zen mode as a temporary data or Nacos-tab layout", () => {
expect(appSource).toContain("const isZenMode = ref(false);");
expect(appSource).toContain('return mode === "data" || mode === "nacos";');
expect(appSource).toContain("function toggleZenMode() {");
expect(appSource).toContain("if (!supportsZenMode(activeTab.value?.mode)) return;");
expect(appSource).toContain("isToggleZenModeShortcut(e, shortcuts) && supportsZenMode(activeTab.value?.mode)");
expect(appSource).toContain('@toggle-zen-mode="toggleZenMode"');
expect(appSource).toContain('v-show="sidebarOpen && !isZenMode"');
expect(appSource).toContain(':show-sidebar-expand="!sidebarOpen && !isZenMode"');
expect(toolbarSource).toContain('<Tooltip v-if="showSidebarExpand">');
expect(toolbarSource).toContain("@click=\"emit('expand-sidebar')\"");
expect(appSource).toContain('@expand-sidebar="setSidebarOpen(true)"');
expect(appSource).toContain('v-show="!isAiPanelMaximized || isZenMode"');
expect(appSource).toContain('v-show="!isZenMode"');
});
});
@@ -1,30 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const settingsDialogSource = readFileSync(new URL("../../../components/editor/EditorSettingsDialog.vue", import.meta.url), "utf8");
const httpBackendSource = readFileSync(new URL("../../backend/http.ts", import.meta.url), "utf8");
const tauriBackendSource = readFileSync(new URL("../../backend/tauri.ts", import.meta.url), "utf8");
describe("snippet migration cleanup recovery", () => {
it("restores pending cleanup state and keeps it visible after restart", () => {
expect(settingsDialogSource).toContain('pendingLegacyCleanupId.value = settings.legacyCleanupRequiredId || ""');
expect(settingsDialogSource).toContain('v-if="pendingLegacyCleanupId"');
expect(settingsDialogSource).toContain('t("settings.syncSnippetMigrateLegacyCleanupRequired", { id: pendingLegacyCleanupId })');
});
it("clears the UI state only after the retry response confirms cleanup", () => {
const retryStart = settingsDialogSource.indexOf("async function retryLegacySnippetCleanup()");
const retryEnd = settingsDialogSource.indexOf("async function downloadSnippetSnapshot()", retryStart);
const retrySource = settingsDialogSource.slice(retryStart, retryEnd);
expect(retrySource).toContain("await retrySnippetLegacyCleanup(currentSnippetConfig())");
expect(retrySource).toContain('pendingLegacyCleanupId.value = settings.legacyCleanupRequiredId || ""');
expect(retrySource).toContain("if (settings.legacyCleanupRequiredId)");
});
it("wires the retry operation through both Web and Tauri backends", () => {
expect(httpBackendSource).toContain('post("/api/cloud-sync/snippet/retry-legacy-cleanup", { config })');
expect(tauriBackendSource).toContain('invoke("retry_snippet_legacy_cleanup", { config })');
expect(httpBackendSource).toContain("legacyCleanupRequiredId?: string");
expect(tauriBackendSource).toContain("legacyCleanupRequiredId?: string");
});
});
@@ -1,46 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const source = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
describe("ConnectionDialog service deep-link hydration", () => {
it("hydrates specialized refs after generic fields and before one-time submit", () => {
const applyStart = source.indexOf("function applyConnectionDraftToForm");
const applyEnd = source.indexOf("function applyConnectionPrefill", applyStart);
const applyBody = source.slice(applyStart, applyEnd);
expect(applyBody.indexOf("applyConnectionDraftToConfig")).toBeGreaterThanOrEqual(0);
expect(applyBody.indexOf("hydrateConsulFields")).toBeGreaterThan(applyBody.indexOf("applyConnectionDraftToConfig"));
expect(applyBody.indexOf("hydrateNacosFields")).toBeGreaterThan(applyBody.indexOf("applyConnectionDraftToConfig"));
const prefillStart = source.indexOf("function applyConnectionPrefill");
const prefillEnd = source.indexOf("watch(\n open", prefillStart);
const prefillBody = source.slice(prefillStart, prefillEnd);
expect(prefillBody.indexOf("applyConnectionDraftToForm")).toBeLessThan(prefillBody.indexOf("submitOneTimePrefill"));
});
it("includes service configuration in one-time submission deduplication", () => {
const keyStart = source.indexOf("function oneTimePrefillKey");
const keyEnd = source.indexOf("function submitOneTimePrefill", keyStart);
expect(source.slice(keyStart, keyEnd)).toContain("draft.serviceConfig");
});
it("hydrates raw service URLs through the deep-link draft path", () => {
const applyStart = source.indexOf("function applyConnectionUrlToForm");
const applyEnd = source.indexOf("function hasPendingConnectionUrlInput", applyStart);
const applyBody = source.slice(applyStart, applyEnd);
expect(applyBody).toContain("parseConnectionDeepLink(input) ?? parseServiceConnectionUrl(input)");
expect(applyBody.indexOf("applyConnectionDraftToForm")).toBeLessThan(applyBody.indexOf("parseConnectionUrl(input"));
});
it("keeps failed one-time connections available for error inspection and retry", () => {
// The save path delegates one-time connects to startSavedConnection,
// which owns the connectFailed emission for failed retries.
const start = source.indexOf("function startSavedConnection");
const saveStart = source.indexOf("async function save(", start);
const saveEnd = source.indexOf('const dialogTitle = ref("")', saveStart);
const saveBody = source.slice(start, saveEnd);
expect(saveBody).not.toContain("store.removeConnection(config.id)");
expect(saveBody).toContain('emit("connectFailed"');
});
});
@@ -1,33 +0,0 @@
import { readFileSync } from "node:fs";
import { parse } from "vue/compiler-sfc";
import ts from "typescript";
import { describe, expect, it } from "vitest";
const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
const parsedDialog = parse(dialogSource, { filename: "ConnectionDialog.vue" });
function connectionConfigForSubmitSource(): string {
const script = parsedDialog.descriptor.scriptSetup;
expect(parsedDialog.errors).toEqual([]);
expect(script).toBeDefined();
const source = ts.createSourceFile("ConnectionDialog.vue.ts", script!.content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
const declaration = source.statements.find((statement): statement is ts.FunctionDeclaration => ts.isFunctionDeclaration(statement) && statement.name?.text === "connectionConfigForSubmit");
expect(declaration).toBeDefined();
return declaration!.getText();
}
describe("ConnectionDialog driver profile configuration", () => {
it("preserves GaussDB routing and Dolt external configuration on submit", () => {
const submitConfig = connectionConfigForSubmitSource();
expect(submitConfig).toContain("setGaussdbTargetServerType(config, targetServerType)");
expect(submitConfig).toContain('else if (config.db_type !== "plugin" && !isDoltDriverProfile(config.driver_profile))');
});
it("preserves plugin external configuration on submit", () => {
const submitConfig = connectionConfigForSubmitSource();
expect(submitConfig).toContain('else if (config.db_type !== "plugin" && !isDoltDriverProfile(config.driver_profile))');
});
});
@@ -1,21 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
describe("connection dialog error layout", () => {
it("installs a required agent before running a connection test", () => {
const installIndex = dialogSource.indexOf("await ensureRequiredAgentDriverInstalled(config);");
const testIndex = dialogSource.indexOf("const result = await testConnectionWithTimeout(config, runId);");
expect(installIndex).toBeGreaterThan(-1);
expect(testIndex).toBeGreaterThan(installIndex);
});
it("wraps long connection and driver installation errors inside the dialog", () => {
const wrappingClasses = "min-w-0 max-w-full overflow-x-hidden overflow-y-auto whitespace-pre-wrap break-all [overflow-wrap:anywhere]";
expect(dialogSource.split(wrappingClasses)).toHaveLength(3);
expect(dialogSource).toContain('<DialogContent class="min-w-0 sm:max-w-[680px]">');
});
});
@@ -1,62 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
describe("ConnectionDialog plugin connection timeout inheritance", () => {
const submitFn = dialogSource.slice(dialogSource.indexOf("function connectionConfigForSubmit"));
const pluginBranch = submitFn.slice(0, submitFn.indexOf("} else {"));
it("keeps the connect timeout inherit flag when submitting plugin connections", () => {
// buildPluginConnectionConfig rebuilds the config from scratch and drops
// the inherit flags; without this mirror the store normalizes the absent
// flag back to the persisted scope and the Advanced-tab radio reverts.
expect(pluginBranch).toContain("config.connect_timeout_inherit = form.value.connect_timeout_inherit;");
});
it("keeps the query timeout inherit flag when submitting plugin connections", () => {
expect(pluginBranch).toContain("config.query_timeout_inherit = form.value.query_timeout_inherit;");
});
it("still forces connect inheritance off for providers declaring their own handshake timeout field", () => {
// The resolvedPluginConnectTimeout override must run after the generic
// mirror so a provider-declared connect_timeout_secs stays the single
// source of truth and the host RPC deadline cannot inherit the global.
const mirrorIndex = pluginBranch.indexOf("config.connect_timeout_inherit = form.value.connect_timeout_inherit;");
const overrideIndex = pluginBranch.indexOf("config.connect_timeout_inherit = false;");
expect(mirrorIndex).toBeGreaterThan(-1);
expect(overrideIndex).toBeGreaterThan(mirrorIndex);
});
it("keeps the per-connection timeout scalars when submitting plugin connections", () => {
// Toggling back to "current connection" must preserve the typed value:
// the store treats a stored scalar with inherit=false as a local override.
expect(pluginBranch).toContain("config.query_timeout_secs = form.value.query_timeout_secs;");
expect(pluginBranch).toContain("config.connect_timeout_secs = form.value.connect_timeout_secs;");
});
});
describe("ConnectionDialog plugin connection timeout scope UI", () => {
const hydrateBlock = dialogSource.slice(dialogSource.indexOf("connect_timeout_inherit: config.connect_timeout_inherit === true"));
const queryTimeoutRowStart = dialogSource.lastIndexOf("<div", dialogSource.indexOf('t("connection.queryTimeout")'));
const connectTimeoutRowStart = dialogSource.lastIndexOf("<div", dialogSource.indexOf('t("connection.connectTimeout")'));
it("hydrates the global scope only from an explicit inherit flag", () => {
// Round trip with the submit mirror above: only a stored `true` counts as
// "global", so a preserved flag reopens as global and a preserved scalar
// reopens as a local override.
expect(hydrateBlock).toContain("query_timeout_inherit: config.query_timeout_inherit === true,");
});
it("hides the generic query timeout radio from plugin connections", () => {
// query_timeout_secs only feeds the database query pipeline, which plugin
// connections (SSH, ...) never run, so the control would be dead weight.
expect(dialogSource.slice(queryTimeoutRowStart, queryTimeoutRowStart + 220)).toContain('v-if="!isPluginConnection"');
});
it("keeps the generic connect timeout radio visible for plugin connections", () => {
// Deliberate scope cut: for providers without their own handshake timeout
// field the connect radio is still effective, so it stays rendered.
expect(dialogSource.slice(connectTimeoutRowStart, connectTimeoutRowStart + 220)).not.toContain('v-if="!isPluginConnection"');
});
});
@@ -1,37 +1,8 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { DEFAULT_CONNECT_TIMEOUT_SECS, normalizeConnectTimeoutSecs } from "@/lib/connection/timeoutLimits";
const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
describe("ConnectionDialog timeout controls", () => {
it("uses separate maximums for connection and query timeouts", () => {
expect(dialogSource).toMatch(/v-model\.number="editGlobalConnectTimeoutSecs"[\s\S]*?min="1"[\s\S]*?:max="MAX_CONNECT_TIMEOUT_SECS"[\s\S]*?step="1"/);
expect(dialogSource).toMatch(/v-model\.number="form\.connect_timeout_secs"[\s\S]*?min="1"[\s\S]*?:max="MAX_CONNECT_TIMEOUT_SECS"[\s\S]*?step="1"/);
expect(dialogSource).toMatch(/v-model\.number="editGlobalQueryTimeoutSecs"[\s\S]*?min="0"[\s\S]*?:max="MAX_QUERY_TIMEOUT_SECS"[\s\S]*?step="1"/);
expect(dialogSource).toMatch(/v-model\.number="form\.query_timeout_secs"[\s\S]*?min="0"[\s\S]*?:max="MAX_QUERY_TIMEOUT_SECS"[\s\S]*?step="1"/);
expect(dialogSource).not.toContain('v-model.number="editGlobalQueryTimeoutSecs" type="number" min="0" max="300"');
expect(dialogSource).not.toContain('v-model.number="form.query_timeout_secs" type="number" min="0" max="300"');
expect(dialogSource).toContain("@input=\"clampQueryTimeoutInput($event, 'global')\"");
expect(dialogSource).toContain("@input=\"clampQueryTimeoutInput($event, 'connection')\"");
expect(dialogSource).toContain("@input=\"clampConnectTimeoutInput($event, 'global')\"");
expect(dialogSource).toContain("@input=\"clampConnectTimeoutInput($event, 'connection')\"");
expect(dialogSource).not.toContain('@blur="editGlobalQueryTimeoutSecs = normalizeGlobalQueryTimeoutSecs');
});
it("restores the default when the connection timeout input is cleared", () => {
expect(normalizeConnectTimeoutSecs("")).toBe(DEFAULT_CONNECT_TIMEOUT_SECS);
expect(dialogSource).toContain("normalizeConnectionTimeouts(config");
expect(dialogSource).not.toContain("Number(config.connect_timeout_secs)");
});
it("uses button-backed help tooltips beside both global timeout labels", () => {
const connectGlobalControl = dialogSource.slice(dialogSource.indexOf('id="connect-timeout-global"'), dialogSource.indexOf('id="connect-timeout-connection"'));
const queryGlobalControl = dialogSource.slice(dialogSource.indexOf('id="query-timeout-global"'), dialogSource.indexOf('id="query-timeout-connection"'));
expect(connectGlobalControl).toContain(`<HelpTooltip :label="t('connection.globalConnectTimeoutHint')"`);
expect(queryGlobalControl).toContain(`<HelpTooltip :label="t('connection.globalQueryTimeoutHint')"`);
expect(connectGlobalControl).not.toContain("<TooltipTrigger");
expect(queryGlobalControl).not.toContain("<TooltipTrigger");
});
});
@@ -1,20 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
describe("ConnectionDialog Xugu database requirement", () => {
it("shows the existing required-database hint only for Xugu", () => {
const placeholder = dialogSource.slice(dialogSource.indexOf("const databasePlaceholder = computed"), dialogSource.indexOf("const transportLayers"));
expect(placeholder).toContain('if (form.value.db_type === "xugu") return t("connection.databasePlaceholderRequired")');
expect(placeholder).toContain('if (form.value.db_type === "kingbase") return t("connection.databasePlaceholderRequired")');
});
it("validates Xugu's effective database before connection testing or saving", () => {
const submit = dialogSource.slice(dialogSource.indexOf("function connectionConfigForSubmit"), dialogSource.indexOf("function ", dialogSource.indexOf("function connectionConfigForSubmit") + 10));
expect(submit).toContain('if (config.db_type === "xugu")');
expect(submit).toContain("hasXuguConnectionDatabase(config.database, config.connection_string)");
expect(submit).toContain('throw new Error(t("connection.xuguDatabaseRequired"))');
expect(submit).toContain('if (config.db_type === "kingbase")');
});
});
@@ -1,35 +1,9 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { CONNECTION_PICKER_OPTIONS, CONNECTION_PROFILES } from "@/types/generated/connectionProfiles";
const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
const browserSource = readFileSync(new URL("../../../components/etcd/EtcdKeyBrowser.vue", import.meta.url), "utf8");
describe("etcd connection dialog API versions", () => {
it("offers v3 and v2 API profile switches", () => {
expect(dialogSource).toContain("@click=\"switchEtcdApiVersion('etcd')\"");
expect(dialogSource).toContain("@click=\"switchEtcdApiVersion('etcd-v2')\"");
expect(dialogSource).toContain("v3 (etcd 3.x)");
expect(dialogSource).toContain("v2 (etcd 2.x)");
});
it("hydrates the v2 profile without exposing a second catalog entry", () => {
expect(CONNECTION_PROFILES["etcd-v2"]).toMatchObject({ type: "etcd", port: 2379 });
expect(CONNECTION_PICKER_OPTIONS.some((option) => option.value === "etcd-v2")).toBe(false);
});
});
describe("etcd v2 feature trimming", () => {
it("detects the v2 profile from the connection config", () => {
expect(browserSource).toContain('connectionStore.getConfig(props.connectionId)?.driver_profile === "etcd-v2"');
});
it("hides key history for v2 connections", () => {
expect(browserSource).toContain("history: isV2Api.value ? undefined : api.etcdHistory");
});
it("hides lease binding and the maintenance/lease workspaces for v2 connections", () => {
expect(browserSource).toContain(':supports-lease-binding="!isV2Api && canManageEtcd"');
expect(browserSource).toContain('<Button v-if="!isV2Api && canManageEtcd"');
});
});
@@ -34,10 +34,6 @@ function selectedProfileHarness(selectedTypeValue: string, driverProfile: string
}
describe("GBase 8s connection dialog", () => {
it("hydrates DBSERVERNAME when editing a saved connection", () => {
expect(dialogSource).toContain('gbase_server: config.gbase_server || ""');
});
it.each([
["gbase8a", "南大通用 GBase 8a"],
["gbase8s", "南大通用 GBase 8s"],
@@ -1,39 +1,7 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { CONNECTION_PICKER_OPTIONS, CONNECTION_PROFILES } from "@/types/generated/connectionProfiles";
const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
describe("H2 connection dialog driver profiles", () => {
it("offers auto, bundled compatibility ranges, and a custom JAR fallback", () => {
expect(dialogSource).toContain("@click=\"switchH2DriverProfile('h2')\"");
expect(dialogSource).toContain("@click=\"switchH2DriverProfile('h2-v1')\"");
expect(dialogSource).toContain("@click=\"switchH2DriverProfile('h2-v2')\"");
expect(dialogSource).toContain("@click=\"switchH2DriverProfile('h2-v3')\"");
expect(dialogSource).toContain("@click=\"switchH2DriverProfile('h2-custom')\"");
expect(dialogSource).toContain(">Custom JAR</Button>");
});
it("reuses the JDBC classpath picker only for the custom profile", () => {
expect(dialogSource).toContain('const isH2CustomDriver = computed(() => form.value.db_type === "h2" && form.value.driver_profile === "h2-custom");');
expect(dialogSource).toContain('<template v-if="isH2CustomDriver">');
expect(dialogSource).toContain('v-model="jdbcDriverPathsInput"');
expect(dialogSource).toContain('@click="browseJdbcDriverPaths"');
expect(dialogSource).toContain('placeholder="org.h2.Driver"');
});
it("defaults the custom class and clears stale classpath data for bundled profiles", () => {
const switchBlock = dialogSource.match(/function switchH2DriverProfile[\s\S]*?\n\}/)?.[0] ?? "";
expect(switchBlock).toContain('form.value.jdbc_driver_class = form.value.jdbc_driver_class?.trim() || "org.h2.Driver";');
expect(switchBlock).toContain("form.value.jdbc_driver_paths = [];");
expect(switchBlock).toContain('jdbcDriverPathsInput.value = "";');
const submitBlock = dialogSource.match(/if \(config\.db_type === "h2"\) \{[\s\S]*?const h2Mode/)?.[0] ?? "";
expect(submitBlock).toContain('config.driver_profile === "h2-custom"');
expect(submitBlock).toContain("config.jdbc_driver_paths = parsedJdbcDriverPaths();");
expect(submitBlock).toContain("config.jdbc_driver_paths = [];");
});
it("keeps legacy profile hydration without exposing a second H2 catalog entry", () => {
expect(CONNECTION_PROFILES["h2-legacy"]).toMatchObject({ type: "h2", port: 9092, user: "sa" });
expect(CONNECTION_PICKER_OPTIONS.find((option) => option.value === "h2")?.category).toBe("lightweight");
@@ -1,27 +0,0 @@
import { readFileSync } from "node:fs";
import { parse } from "vue/compiler-sfc";
import ts from "typescript";
import { describe, expect, it } from "vitest";
const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
const parsedDialog = parse(dialogSource, { filename: "ConnectionDialog.vue" });
function findFunction(name: string): ts.FunctionDeclaration {
const script = parsedDialog.descriptor.scriptSetup;
expect(parsedDialog.errors).toEqual([]);
expect(script).toBeDefined();
const source = ts.createSourceFile("ConnectionDialog.vue.ts", script!.content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
const declaration = source.statements.find((statement): statement is ts.FunctionDeclaration => ts.isFunctionDeclaration(statement) && statement.name?.text === name);
expect(declaration).toBeDefined();
return declaration!;
}
describe("JDBCX connection dialog", () => {
it("preserves the connection-level high-privilege extension opt-in on submit", () => {
const submitConfig = findFunction("connectionConfigForSubmit").getText();
expect(submitConfig).toContain('config.db_type === "jdbc" && config.driver_profile === JDBCX_DRIVER_PROFILE');
expect(submitConfig).toContain("config.agent_java_options = undefined");
});
});
@@ -4,139 +4,6 @@ import { describe, expect, it } from "vitest";
const source = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
describe("Nacos connection dialog layout", () => {
it("presents implementation and version as one explicit connection profile", () => {
expect(source).toContain("data-nacos-profile-selector");
expect(source).toContain('v-for="profile in NACOS_CONNECTION_PROFILES"');
expect(source).toContain("selectNacosConnectionProfile(profile.value)");
expect(source).not.toContain("nacosVersionMode = 'auto'");
expect(source).not.toContain("tryNacosDockerConsoleFallback");
expect(source).not.toContain("dockerNacosConsoleFallbackUrl");
});
it("persists the explicit Nacos 3 Admin or Console API selection", () => {
expect(source).toContain('const nacosApiPlane = ref<NacosApiPlane>("admin")');
expect(source).toContain('config?.apiPlane || "admin"');
expect(source).toContain('apiPlane: nacosImplementation.value === "nacos" && nacosVersionMode.value === "v3" ? nacosApiPlane.value : undefined');
expect(source).toContain("nacos.nacosConsoleServiceAddressHint");
});
it("keeps the primary form focused on endpoints and authentication", () => {
const mainStart = source.indexOf("data-nacos-profile-selector");
const mainEnd = source.indexOf("<!-- Redis: host, port, user, password, ssl -->", mainStart);
const main = source.slice(mainStart, mainEnd);
expect(main).toContain("data-nacos-endpoint-section");
expect(main).toContain("data-nacos-access-section");
expect(main).toContain("data-nacos-advanced-hint");
expect(main).toContain('t("nacos.nacosAdvancedHint")');
expect(main).toContain("@click=\"configTab = 'advanced'\"");
expect(main).toContain('v-model="nacosServerAddr"');
expect(main).not.toContain('v-model="nacosConsoleUrl"');
expect(main).not.toContain('v-model="nacosManagedNamespacesText"');
expect(main).not.toContain("data-nacos-namespace-access-scope");
expect(main).not.toContain("data-nacos-ordinary-user-toggle");
expect(main).not.toContain("nacosOrdinaryAccount");
expect(main).toContain("nacosAuthKind === 'usernamePassword'");
expect(main).not.toContain('v-model="nacosNamespace"');
expect(main).toContain('t("nacos.nacosAuthHint")');
expect(main).not.toContain('v-model="nacosMetricsMode"');
expect(main).not.toContain('v-model.number="nacosPageSize"');
});
it("moves low-frequency and r-nacos console settings to the advanced tab", () => {
const advancedStart = source.indexOf("data-nacos-advanced-settings");
const advancedEnd = source.indexOf('v-if="showGaussdbConnectionMode"', advancedStart);
const advanced = source.slice(advancedStart, advancedEnd);
expect(advanced).not.toContain('v-model="nacosContextPathInput"');
expect(advanced).not.toContain("配置上下文路径");
expect(advanced).toContain('v-model="nacosContextPath"');
expect(advanced).toContain('t("nacos.nacosContextPathHint")');
expect(advanced).toContain('v-model="nacosMetricsMode"');
expect(advanced).toContain('v-model="nacosConsoleUrl"');
expect(advanced).toContain('t("connection.nacosWebConsoleUrlHint")');
expect(advanced).toContain('v-if="isNacosV3AdminPlane"');
expect(advanced).toContain('v-model="nacosRNacosConsoleAddr"');
expect(advanced).toContain('v-if="nacosRNacosConsoleAddr.trim()"');
expect(advanced).toContain('v-model="nacosHistoryEnabled"');
expect(advanced).toContain('v-model="nacosTlsSkipVerify"');
expect(advanced).toContain('v-model.number="nacosPageSize"');
});
it("documents product default ports instead of local Docker mappings", () => {
expect(source).toContain('t("nacos.nacosServiceAddressHint")');
expect(source).toContain('t("nacos.nacosMetricsHint")');
expect(source).not.toContain("DBX 不需要配置该地址");
const mainStart = source.indexOf("data-nacos-profile-selector");
const mainEnd = source.indexOf("<!-- Redis: host, port, user, password, ssl -->", mainStart);
expect(source.slice(mainStart, mainEnd)).not.toContain("data-nacos-managed-namespaces");
expect(source.slice(mainStart, mainEnd)).not.toContain('placeholder="http://127.0.0.1:8080"');
expect(source).toContain('return "http://127.0.0.1:8080";');
expect(source).not.toContain("http://127.0.0.1:8010");
expect(source).not.toContain("http://127.0.0.1:8818");
});
it("uses a dedicated namespace selector instead of the database selector", () => {
expect(source).toContain("t(nacosNamespacePickerTitleKey)");
expect(source).toContain('"nacos.nacosDetectAccessibleNamespaces"');
expect(source).toContain("openVisibleNacosNamespacesPicker");
expect(source).toContain("loadReadableNacosNamespaces(draftId, api)");
expect(source).toContain("showVisibleNacosNamespacesDialog");
expect(source).toContain('v-model="visibleNacosNamespaceAccessMode"');
expect(source).toContain('TabsTrigger value="automatic"');
expect(source).toContain('TabsTrigger v-if="canDetectNacosNamespaceAccess" value="manual"');
expect(source).toContain('v-model="nacosManagedNamespacesText"');
expect(source).not.toContain("!isNacosV3AdminPlane.value");
expect(source).toContain('visibleNacosNamespaceAccessMode.value === "manual"');
});
it("guides namespace listing permission failures to manual scope entry", () => {
expect(source).toContain("function isNacosNamespaceListingPermissionError(error: unknown): boolean");
expect(source).toContain("NACOS_ERROR\\[rnacosNamespaceDirectoryUnavailable\\]");
expect(source).toContain("NACOS_ERROR\\[(?:v3ManagedNamespacesRequired|managedNamespacesRequired)\\]");
expect(source).toContain("/\\/v3\\/(?:admin|console)\\/core\\/namespace\\/list/");
expect(source).toContain("visibleNacosNamespaceListingPermissionDenied.value = isNacosNamespaceListingPermissionError(e)");
expect(source).toContain('t("nacos.nacosManagedNamespacesRequired")');
expect(source).toContain('v-else-if="visibleNacosNamespaceListingPermissionDenied"');
expect(source).toContain("@click=\"visibleNacosNamespaceAccessMode = 'manual'\"");
});
it("resolves unique manually entered namespace names to their Nacos IDs", () => {
expect(source).toContain("function normalizeManualNacosNamespaceNames(namespaces: string[], availableNamespaces: NacosNamespaceInfo[]): string[]");
expect(source).toContain("matchingNames.length === 1 ? matchingNames[0] : namespace");
expect(source).toContain("async function resolveManualNacosNamespaceNames(namespaces: string[]): Promise<string[]>");
expect(source).toContain("managedNamespaces: undefined");
expect(source).toContain(": await resolveManualNacosNamespaceNames(manualNamespaces)");
});
it("distinguishes the manual namespace input for the V3 Admin and Console API planes", () => {
expect(source).toContain("const isNacosV3ConsolePlane = computed(");
expect(source).toContain('isNacosV3AdminPlane.value ? "nacos.nacosManagedNamespaces" : "nacos.nacosManagedNamespacesNameOrId"');
expect(source).toContain('isNacosV3AdminPlane.value ? "nacos.nacosManagedNamespacesIdPlaceholder" : "nacos.nacosManagedNamespacesPlaceholder"');
expect(source).toContain('if (isNacosV3AdminPlane.value) return "nacos.nacosV3AdminManagedNamespacesHint"');
expect(source).toContain('if (isNacosV3ConsolePlane.value) return "nacos.nacosV3ConsoleManagedNamespacesHint"');
expect(source).toContain('v-if="isNacosV3AdminPlane" class="flex gap-2 rounded-md border border-amber-500/30');
expect(source).toContain('isNacosV3AdminPlane.value || nacosImplementation.value === "rnacos"');
expect(source).toContain("? manualNamespaces");
expect(source).toContain(": await resolveManualNacosNamespaceNames(manualNamespaces)");
});
it("opens namespace access setup instead of showing a save validation error", () => {
expect(source).toContain("if (!hasNacosNamespaceScopeForSave()) {");
expect(source).toContain("await openVisibleNacosNamespacesPicker();");
expect(source).not.toContain('message: t("nacos.nacosNamespaceScopeRequiredBeforeSave")');
});
it("stores automatic full access as a dynamic namespace scope", () => {
expect(source).toContain("const nacosDynamicAllNamespaces = ref(false)");
expect(source).toContain("const useDynamicAll = selectsEntireReadableList && visibleNacosNamespaceDynamicAllSupported.value");
expect(source).toContain("const readableSet = new Set(readableIds.map(nacosNamespaceIdentity))");
expect(source).toContain("readableSet.size === sidebarSet.size");
expect(source).toContain("form.value.visible_databases = useDynamicAll ? undefined : selected");
expect(source).toContain("nacosDynamicAllNamespaces.value = useDynamicAll");
expect(source).toContain("function showAllVisibleNacosNamespaces()");
});
it("uses namespaces when scoping Nacos production safeguards", () => {
expect(source).toContain('form.value.db_type === "nacos"');
expect(source).toContain("production.allNamespaces");
@@ -1,62 +1,9 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { CONNECTION_PICKER_OPTIONS, CONNECTION_PROFILES } from "@/types/generated/connectionProfiles";
const dialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
const fieldsSource = readFileSync(new URL("../../../components/connection/SpannerConnectionFields.vue", import.meta.url), "utf8");
describe("Cloud Spanner connection dialog", () => {
it("registers the bundled agent profile in the SQL category", () => {
expect(CONNECTION_PROFILES.spanner).toMatchObject({ type: "spanner", port: 443, user: "", label: "Cloud Spanner", icon: "spanner" });
expect(CONNECTION_PICKER_OPTIONS.find((option) => option.value === "spanner")).toEqual({ value: "spanner", label: "Cloud Spanner", category: "sql" });
});
it("does not expose external JDBC driver configuration because the driver is bundled", () => {
const nativeAgentDriverSupport = dialogSource.match(/function supportsNativeAgentJdbcDriverConfigType\(dbType: DatabaseType\): boolean \{([\s\S]*?)\}/)?.[1] ?? "";
const jdbcBackedDatabaseTypes = dialogSource.match(/const jdbcBackedDatabaseTypes = new Set<DatabaseType>\(\[([\s\S]*?)\]\);/)?.[1] ?? "";
expect(nativeAgentDriverSupport).toContain('dbType === "bigquery"');
expect(nativeAgentDriverSupport).not.toContain('dbType === "spanner"');
expect(jdbcBackedDatabaseTypes).not.toContain('"spanner"');
});
it("collects the resource path through dedicated fields instead of host and credentials", () => {
expect(dialogSource).toContain('import SpannerConnectionFields from "@/components/connection/SpannerConnectionFields.vue";');
expect(dialogSource).toContain('<SpannerConnectionFields v-model:database="form.database" @change="resetTestState" />');
// User, password, and the generic database row are hidden for Spanner.
// These pin the whole v-if because the rows are shared, so adding another
// database that opts out of one of them means updating the string here too.
expect(dialogSource).toContain("<div v-if=\"form.db_type !== 'meilisearch' && form.db_type !== 'spanner'\" class=\"grid grid-cols-4 items-center gap-4\">");
expect(dialogSource).toContain('<div v-if="form.db_type !== \'spanner\'" class="grid grid-cols-4 items-center gap-4">');
expect(dialogSource).toContain("<div v-if=\"form.db_type !== 'hbase' && form.db_type !== 'meilisearch' && form.db_type !== 'solr' && form.db_type !== 'spanner'\" class=\"grid grid-cols-4 items-center gap-4\">");
// Switching to the Spanner profile clears host and credentials.
expect(dialogSource).toContain('if (profile.type === "spanner") {');
// Save/Test gating and submit-time normalization.
expect(dialogSource).toContain("if (isSpannerConnection(form.value)) return hasSpannerResourcePath(form.value);");
expect(dialogSource).toContain("normalizeSpannerConnection(config);");
expect(dialogSource).toContain('throw new Error(t("connection.spannerFieldsRequired"));');
});
it("stays inside the generic branch so the agent install hint and URL params remain available", () => {
const spannerBlockStart = dialogSource.indexOf("<!-- Cloud Spanner: project/instance/database resource path instead of user/password/database -->");
const genericBranchStart = dialogSource.indexOf("<!-- MySQL / PostgreSQL: host, port, user, password, database -->");
const urlParamsRow = dialogSource.indexOf('v-if="supportsGenericUrlParams"');
const agentInstallHint = dialogSource.indexOf('v-if="shouldShowAgentDriverInstallHint"');
expect(genericBranchStart).toBeGreaterThan(0);
expect(spannerBlockStart).toBeGreaterThan(genericBranchStart);
expect(urlParamsRow).toBeGreaterThan(spannerBlockStart);
expect(agentInstallHint).toBeGreaterThan(spannerBlockStart);
expect(dialogSource).toContain("'credentials=/path/key.json;autocommit=true'");
});
it("offers both the structured editor and the raw resource path editor", () => {
expect(fieldsSource).toContain('const database = defineModel<string | undefined>("database");');
expect(fieldsSource).toContain("data-spanner-resource-fields");
expect(fieldsSource).toContain('t("connection.spannerProject")');
expect(fieldsSource).toContain('t("connection.spannerInstance")');
expect(fieldsSource).toContain('t("connection.spannerDatabase")');
expect(fieldsSource).toContain('t("connection.spannerResourcePathMode")');
expect(fieldsSource).toContain('emit("change")');
});
});
@@ -1,18 +1,10 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { compactJsonText, valueEditorActions } from "@/lib/dataGrid/cellDetailPresentation";
const dataGridSource = readFileSync(new URL("../../../components/grid/DataGrid.vue", import.meta.url), "utf8");
describe("cellDetailPresentation", () => {
it("offers compact JSON beside format JSON for editable JSON values", () => {
expect(valueEditorActions({ canSetNull: true, canFormatJson: true })).toEqual(["formatJson", "compactJson", "setNull", "restoreOriginal"]);
expect(valueEditorActions({ canSetNull: false, canFormatJson: false })).toEqual(["restoreOriginal"]);
expect(compactJsonText('{\n "name": "DBX",\n "enabled": true\n}')).toBe('{"name":"DBX","enabled":true}');
});
it("wires the value editor compact action to the existing compact handler", () => {
expect(dataGridSource).toContain("activeValueEditorActions.includes('compactJson')");
expect(dataGridSource).toContain('@click="compactDetailJson"');
});
});
@@ -1,9 +1,6 @@
import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import { escapeCustomBasemapAttribution, loadCustomBasemapConfig, loadSelectedBasemapId, normalizeCustomBasemapConfig, resolveSelectedBasemapId, saveCustomBasemapConfig, saveSelectedBasemapId } from "@/lib/dataGrid/customBasemap";
const layerPreviewSource = readFileSync(new URL("../../../components/grid/LayerPreviewDialog.vue", import.meta.url), "utf8");
function storage() {
const values = new Map<string, string>();
return {
@@ -13,12 +10,6 @@ function storage() {
}
describe("custom basemap configuration", () => {
it("keeps a saved custom basemap available after switching to a built-in basemap", () => {
expect(layerPreviewSource).toMatch(/<option v-if="customBasemapConfig" value="custom">/);
expect(layerPreviewSource).toMatch(/id === "custom" && customBasemapConfig\.value/);
expect(layerPreviewSource).toMatch(/v-model="customBasemapName"/);
});
it("normalizes a valid XYZ configuration", () => {
expect(
normalizeCustomBasemapConfig({
@@ -57,7 +48,6 @@ describe("custom basemap configuration", () => {
expect(escaped).toBe("&lt;img src=x onerror=&quot;alert(1)&quot;&gt;&lt;svg onload=&#39;alert(2)&#39;&gt;&lt;script&gt;alert(3)&lt;/script&gt;&amp;");
expect(escaped).not.toMatch(/<(?:img|svg|script)\b/i);
expect(layerPreviewSource).toMatch(/basemap\.custom \? escapeCustomBasemapAttribution\(basemap\.attribution\) : basemap\.attribution/);
});
it("persists the actual basemap selection separately from the custom configuration", () => {
@@ -67,7 +57,6 @@ describe("custom basemap configuration", () => {
expect(saveSelectedBasemapId(target, "osm")).toBe(true);
expect(loadSelectedBasemapId(target)).toBe("osm");
expect(layerPreviewSource).toMatch(/saveSelectedBasemapId\(basemapStorage, basemap\.id\)/);
});
it("does not enable a stored custom basemap unless it was selected", () => {
@@ -1,11 +1,7 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { resolveDataGridCellTextRole } from "@/lib/dataGrid/dataGridCellTextVisual";
import { resolveDataGridTypeVisualKind, resolveHeaderColumnType, type DataGridTypeVisualKind } from "@/lib/dataGrid/dataGridColumnType";
const dataGridSource = readFileSync(new URL("../../../components/grid/DataGrid.vue", import.meta.url), "utf8");
const globalStylesSource = readFileSync(new URL("../../../styles/globals.css", import.meta.url), "utf8");
describe("data grid type visual kind", () => {
it.each<[string, DataGridTypeVisualKind]>([
["BIGINT", "integer"],
@@ -75,8 +71,6 @@ describe("data grid header type color", () => {
expect(displayedType).toBe("decimal(10,2)");
expect(resolveDataGridTypeVisualKind(displayedType)).toBe("numeric");
expect(dataGridSource).toContain(':type-class="typeColorClass(headerColumnType(col.name, col.actualColIdx))"');
expect(dataGridSource).not.toContain("typeColorClass(allColumnTypes[col.actualColIdx]");
});
});
@@ -101,24 +95,4 @@ describe("data grid cell text visual priority", () => {
it("keeps NULL muted when type colors are disabled", () => {
expect(resolveDataGridCellTextRole({ ...ordinaryInteger, colorizeTypes: false, isNull: true })).toBe("muted");
});
it("uses a neutral foreground on editable DOM hover surfaces", () => {
expect(dataGridSource).toContain("'hover:bg-gray-200 hover:text-foreground dark:hover:bg-gray-800':");
expect(dataGridSource).toContain("'cursor-text hover:bg-gray-200 hover:text-foreground dark:hover:bg-gray-800':");
});
it("checks NULL before applying the optional type-color setting", () => {
expect(dataGridSource).toContain("function gridCellTextColorClass(item: RowItem, actualColIdx: number, visibleColIdx: number): string {\n const value = item.data[actualColIdx];");
expect(dataGridSource).toContain("function transposeCellTextColorClass(recordIndex: number, actualColIdx: number): string {\n const item = displayItems.value[recordIndex];");
expect(dataGridSource).not.toContain('function gridCellTextColorClass(item: RowItem, actualColIdx: number, visibleColIdx: number): string {\n if (!colorizeDataGridCellTypes.value) return "text-foreground";');
expect(dataGridSource).not.toContain('function transposeCellTextColorClass(recordIndex: number, actualColIdx: number): string {\n if (!colorizeDataGridCellTypes.value) return "text-foreground";');
});
it("places data-grid type selectors in the components layer", () => {
const componentsLayerStart = globalStylesSource.indexOf("@layer components {");
const integerTypeSelector = globalStylesSource.indexOf(".data-grid-type-integer");
expect(componentsLayerStart).toBeGreaterThan(-1);
expect(integerTypeSelector).toBeGreaterThan(componentsLayerStart);
});
});
@@ -1,14 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const dataGridSource = readFileSync(new URL("../../../components/grid/DataGrid.vue", import.meta.url), "utf8");
describe("DataGrid context menu state", () => {
it("clears the context target whenever the result is replaced", () => {
expect(dataGridSource).toMatch(/watch\(\s*\(\) => props\.result,[\s\S]*?clearRowSelection\(\);\s*invalidateContextMenuTarget\(\);[\s\S]*?exitTransaction\(\);/);
});
it("uses the actual copyable row count in the copy menu", () => {
expect(dataGridSource).toContain('label: copyRowCount.value > 1 ? t("grid.copyRows", { count: copyRowCount.value }) : t("grid.copyRow")');
});
});
@@ -1,4 +1,3 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS, normalizeDataGridCopyPreference, normalizeDataGridExtractorOptions, resolveDataGridCopyPreference, validateDataGridExtractorOptions } from "@/lib/dataGrid/dataGridCopyExtractor";
@@ -37,14 +36,6 @@ describe("data-grid extractor options", () => {
expect(normalizeDataGridExtractorOptions({ json: { camelCaseFieldNames: "true" } }).json.camelCaseFieldNames).toBe(false);
});
it("exposes the camel-case field-name switch only with JSON extractor options", () => {
const dialog = readFileSync(new URL("../../../components/grid/DataGridExtractorDialog.vue", import.meta.url), "utf8");
expect(dialog).toContain('v-if="isJson"');
expect(dialog).toContain("draftOptions.json.camelCaseFieldNames");
expect(dialog).toContain('t("grid.copyExtractorCamelCaseJsonFields")');
});
it("rejects overlapping effective row and column separators", () => {
const options = normalizeDataGridExtractorOptions(DEFAULT_DATA_GRID_EXTRACTOR_OPTIONS);
options.dsv.rowSeparator = ",";
@@ -1,5 +1,4 @@
import { describe, expect, it } from "vitest";
import { readFileSync } from "node:fs";
import {
DATA_GRID_DARK_ACTIVE_ROW_BG,
DATA_GRID_DARK_CROSSHAIR_COL_BG,
@@ -104,16 +103,6 @@ describe("data grid paint theme", () => {
expect(theme.cellCrosshairCol).toBe("rgb(153, 187, 177)");
});
it("propagates crosshair fills through the base cell variable so DOM and frozen cells stay visible", () => {
const gridSource = readFileSync(new URL("../../../components/grid/DataGrid.vue", import.meta.url), "utf8");
expect(gridSource).toMatch(/\.crosshair-row\s*\{\s*--data-grid-cell-bg:\s*var\(--data-grid-cell-crosshair-row-bg\)\s*!important;/);
expect(gridSource).toMatch(/\.crosshair-column\s*\{\s*--data-grid-cell-bg:\s*var\(--data-grid-cell-crosshair-col-bg\)\s*!important;/);
expect(gridSource).toContain("color-mix(in srgb, var(--primary) 34%, var(--background))");
expect(gridSource).toContain("color-mix(in srgb, var(--primary) 50%, var(--background))");
expect(gridSource).toMatch(/\.data-grid-cell--frozen\s*\{\s*background-color:\s*var\(--data-grid-cell-bg,/);
});
it("falls back to the built-in type palette for the active appearance", () => {
const emptyCssVariable = () => "";
@@ -245,16 +234,3 @@ describe("data grid paint theme", () => {
expect(theme.typeForegrounds.spatial).toBe("rgb(12, 98, 74)");
});
});
describe("dbx-control-chrome cascade contract", () => {
it("keeps chrome defaults layered and low-specificity so invalid/focus utilities can win", () => {
const css = readFileSync(new URL("../../../styles/globals.css", import.meta.url), "utf8");
const chromeBlockStart = css.indexOf("Shared control chrome defaults");
expect(chromeBlockStart).toBeGreaterThanOrEqual(0);
const chromeSlice = css.slice(chromeBlockStart - 40, chromeBlockStart + 1600);
expect(chromeSlice).toMatch(/@layer components/);
expect(chromeSlice).toMatch(/:where\(\.dbx-control-chrome\)/);
expect(chromeSlice).toMatch(/\[aria-invalid="true"\]/);
expect(chromeSlice).not.toMatch(/box-shadow:\s*none/);
});
});
@@ -3,37 +3,7 @@ import { join } from "node:path";
import { describe, expect, it, vi } from "vitest";
import { createDataGridRuntimeScope } from "@/lib/dataGrid/dataGridRuntime";
const dataGridSource = readFileSync(new URL("../../../components/grid/DataGrid.vue", import.meta.url), "utf8");
function extractFunction(name: string): string {
const start = dataGridSource.indexOf(`async function ${name}(`);
if (start < 0) throw new Error(`Missing DataGrid function: ${name}`);
const bodyStart = dataGridSource.indexOf("{", start);
let depth = 0;
for (let index = bodyStart; index < dataGridSource.length; index++) {
const character = dataGridSource[index];
if (character === "{") depth++;
if (character === "}" && --depth === 0) return dataGridSource.slice(start, index + 1);
}
throw new Error(`Unterminated DataGrid function: ${name}`);
}
describe("dataGridRuntime", () => {
it("keeps WHERE and ORDER BY execution errors separate from save errors", () => {
for (const name of ["applyWhereFilter", "applyOrderBySearch"]) {
const source = extractFunction(name);
expect(source).toContain('queryControlError.value = ""');
expect(source).toContain("queryControlError.value = String(e?.message || e)");
expect(source).not.toContain("saveError.value");
}
expect(dataGridSource).toContain('v-if="queryControlError"');
expect(dataGridSource).toContain(":title=\"t('grid.queryError')\"");
});
it("redraws canvas rows when multiline flattening changes", () => {
expect(dataGridSource).toContain("watch(flatteningMultiLineEnabled, () => scheduleCanvasDraw());");
});
it("disposes registered resources in reverse order and only once", () => {
const scope = createDataGridRuntimeScope();
const calls: string[] = [];
@@ -1,12 +1,7 @@
import { readFileSync } from "node:fs";
import { EditorSelection } from "@codemirror/state";
import { describe, expect, it } from "vitest";
import { appendSearchMatchSelection, findSearchMatch, isSearchAddSelectionModifier, selectionRangesForSearchMatches } from "@/lib/editor/editorSearchSelection";
const searchPanelSource = readFileSync(new URL("../../../components/editor/EditorSearchPanel.vue", import.meta.url), "utf8");
const ddlViewSource = readFileSync(new URL("../../../components/objects/DdlViewDialog.vue", import.meta.url), "utf8");
const nacosSource = readFileSync(new URL("../../../components/nacos/NacosAdminConsole.vue", import.meta.url), "utf8");
const matches = [
{ from: 0, to: 3 },
{ from: 6, to: 9 },
@@ -76,22 +71,4 @@ describe("editorSearchSelection", () => {
expect(isSearchAddSelectionModifier({ metaKey: true }, "Win32")).toBe(false);
expect(isSearchAddSelectionModifier({ ctrlKey: true }, "Linux x86_64")).toBe(true);
});
it("wires select-all and platform-modifier-click match selection into the search panel", () => {
expect(searchPanelSource).toContain("selectionRangesForSearchMatches");
expect(searchPanelSource).toContain("appendSearchMatchSelection");
expect(searchPanelSource).toContain("isSearchAddSelectionModifier(event)");
expect(searchPanelSource).toContain('@click="selectAllMatches"');
expect(searchPanelSource).toContain("editor.search.selectAll");
expect(searchPanelSource).toContain("collectAllMatches(v, limit + 1)");
expect(searchPanelSource).toContain("matches.slice(0, limit)");
expect(searchPanelSource).toContain("countEditorSearchMatches");
expect(searchPanelSource).toContain("editor.search.selectionLimitSummary");
expect(searchPanelSource).not.toContain("matchCountLimited");
});
it("enables multiple selections in every editor using the shared panel", () => {
expect(ddlViewSource).toContain("EditorState.allowMultipleSelections.of(true)");
expect(nacosSource).toContain("EditorState.allowMultipleSelections.of(true)");
});
});
@@ -1,4 +1,3 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { createEditorWheelZoomGestureGuard } from "@/lib/editor/editorZoom";
@@ -44,16 +43,3 @@ describe("createEditorWheelZoomGestureGuard", () => {
expect(guard.accepts(wheelEvent(120, true))).toBe(true);
});
});
describe("editor wheel zoom integration", () => {
it.each([
["SQL editor", "../../../components/editor/QueryEditor.vue", "wheelZoomGestureGuard"],
["cell detail editor", "../../../composables/useCellDetailEditor.ts", "wheelZoomGestureGuard"],
["Nacos editor", "../../../components/nacos/NacosAdminConsole.vue", "configEditorWheelZoomGestureGuard"],
])("guards %s wheel zoom by gesture origin", (_name, path, guardName) => {
const source = readFileSync(new URL(path, import.meta.url), "utf8");
expect(source).toContain("createEditorWheelZoomGestureGuard");
expect(source).toContain(`if (!${guardName}.accepts(event)) return false;`);
});
});
@@ -1,15 +1,8 @@
import { readFileSync } from "node:fs";
import { toggleBlockComment } from "@codemirror/commands";
import { sql } from "@codemirror/lang-sql";
import { EditorSelection, EditorState, type Transaction } from "@codemirror/state";
import { describe, expect, it, vi } from "vitest";
const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
const contextMenuSource = readFileSync(new URL("../../../components/editor/QueryEditorContextMenu.vue", import.meta.url), "utf8");
const runtimeSource = readFileSync(new URL("../../../components/editor/queryEditorCodeMirrorRuntime.ts", import.meta.url), "utf8");
function runToggleBlockComment(doc: string, selection: EditorSelection | { anchor: number; head?: number }) {
let state = EditorState.create({ doc, selection, extensions: [sql()] });
const dispatch = vi.fn((transaction: Transaction) => {
@@ -26,19 +19,6 @@ function runToggleBlockComment(doc: string, selection: EditorSelection | { ancho
}
describe("QueryEditor block comment", () => {
it("wires toggleBlockComment into the right-click context menu, the keymap, and the editor module load", () => {
expect(runtimeSource).toContain('codeMirrorToggleBlockComment: typeof import("@codemirror/commands").toggleBlockComment | null;');
expect(runtimeSource).toContain("codeMirrorToggleBlockComment: null,");
expect(queryEditorSource).toContain("codeMirrorToggleBlockComment?.(currentView);");
expect(contextMenuSource).toContain('label: t("editor.contextMenu.blockCommentSelection")');
expect(contextMenuSource).toContain("shortcut: shortcuts.toggleBlockComment");
expect(queryEditorSource).toContain("...binding(shortcuts.toggleBlockComment, (view) => {");
expect(queryEditorSource).toContain("!supportsQueryEditorBlockComments(props.databaseType)");
expect(queryEditorSource).toContain("defaultKeymapForGlobalShortcuts(codeMirrorRuntime.codeMirrorDefaultKeymap, settingsStore.editorSettings.shortcuts).filter((item) => item.run !== codeMirrorRuntime.codeMirrorToggleBlockComment)");
expect(queryEditorSource).toContain("defaultKeymapComp.reconfigure(defaultKeymapExtension())");
expect(runtimeSource).toContain("runtime.codeMirrorToggleBlockComment = toggleBlockComment;");
});
it("wraps the selected SQL in a block comment", () => {
const doc = "SELECT id FROM users;";
const selection = EditorSelection.range(doc.indexOf("id"), doc.indexOf("id") + "id".length);
@@ -188,9 +188,6 @@ afterEach(() => {
});
describe("QueryEditor completion Tab keymap", () => {
it("guards the batch INSERT snippet factory before applying", () => {
expect(batchSource).toContain('if (session.mode === "insert" && !runtime.codeMirrorSnippetCompletion)');
});
it("closes completion and suppresses its restart for the Enter newline", () => {
const closeCompletion = vi.fn(() => true);
let harness: TabHarness;
@@ -1,7 +1,5 @@
// @vitest-environment happy-dom
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { acceptCompletion, autocompletion, completionStatus, currentCompletions, moveCompletionSelection, selectedCompletionIndex, startCompletion } from "@codemirror/autocomplete";
import { EditorState, Prec, Transaction } from "@codemirror/state";
import { insertNewlineKeepIndent } from "@codemirror/commands";
@@ -9,8 +7,6 @@ import { EditorView, keymap, runScopeHandlers } from "@codemirror/view";
import { describe, expect, it, vi } from "vitest";
import { acceptSelectedCompletionWithRetry, acceptSelectedOrFirstCompletion } from "@/lib/editor/queryEditorCompletionAcceptance";
const queryEditorSource = readFileSync(resolve(process.cwd(), "apps/desktop/src/components/editor/queryEditorSqlExtensions.ts"), "utf8");
function createCompletionView(doc = "", selectFirstCompletionOnOpen = false, interactionDelay: number | null = 0) {
return new EditorView({
parent: document.createElement("div"),
@@ -67,10 +63,6 @@ async function expectCompletionOpenWithoutSelection(view: EditorView) {
}
describe("QueryEditor completion selection", () => {
it("binds SQL completion to CodeMirror's unselected-on-open mode", () => {
expect(queryEditorSource).toMatch(/selectOnOpen: settingsStore\.editorSettings\.selectFirstCompletionOnOpen/);
});
it("opens manual completion unselected and accepts the first option with Tab", async () => {
const view = createCompletionView();
@@ -1,71 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
const diagnosticsSource = readFileSync(new URL("../../../components/editor/useQueryEditorDiagnostics.ts", import.meta.url), "utf8");
const completionSource = readFileSync(new URL("../../../components/editor/useQueryEditorCompletion.ts", import.meta.url), "utf8");
const metadataSource = readFileSync(new URL("../../../components/editor/useQueryEditorCompletionMetadata.ts", import.meta.url), "utf8");
function extractFunction(name: string): string {
const source = [queryEditorSource, completionSource, metadataSource, diagnosticsSource].find((candidate) => candidate.includes(`function ${name}(`)) ?? "";
const start = source.indexOf(`function ${name}(`);
if (start < 0) throw new Error(`Missing QueryEditor function: ${name}`);
const bodyStart = source.indexOf("{", start);
let depth = 0;
for (let index = bodyStart; index < source.length; index++) {
const character = source[index];
if (character === "{") depth++;
if (character === "}" && --depth === 0) return source.slice(start, index + 1);
}
throw new Error(`Unterminated QueryEditor function: ${name}`);
}
describe("QueryEditor database name completion wiring", () => {
it("uses the shared capability for local lookup, background refresh, and async loading", () => {
expect(extractFunction("localCompletionDatabaseNames")).toContain("supportsDatabaseNameCompletion(props.databaseType)");
expect(extractFunction("scheduleCompletionMetadataRefresh")).toMatch(/supportsDatabaseNameCompletion\(props\.databaseType\)[\s\S]*?refreshCompletionDatabases\(connectionId\)/);
expect(extractFunction("performAsyncCompletionWithResult")).toMatch(/supportsDatabaseNameCompletion\(props\.databaseType\)[\s\S]*?listCompletionDatabases\(props\.connectionId!\)/);
});
it("does not reuse cached tables while completing schemas inside a database", () => {
expect(extractFunction("buildLocalSqlCompletionResult")).toMatch(/const tables = schemaLookupDatabase\s*\?\s*\[\]/);
expect(extractFunction("performAsyncCompletionWithResult")).toMatch(/let tables = schemaLookupDatabase\s*\?\s*\[\]/);
});
it("limits database and schema disambiguation to engines with both capabilities", () => {
const guard = extractFunction("mayCompleteDatabaseSchemaQualifier");
expect(guard).toContain("supportsDatabaseNameCompletion(props.databaseType)");
expect(guard).toContain("supportsDatabaseSchemaQualifierCompletion()");
});
it("uses the resolved database scope for routine completion and isolates the editor cache", () => {
expect(extractFunction("routineCompletionTargetForContext")).toContain("currentDatabase: scope.database");
expect(extractFunction("routineCompletionTargetForContext")).toContain("supportsDatabaseSchemaQualifier: supportsDatabaseSchemaQualifierCompletion()");
expect(extractFunction("lookupLocalCompletionObjectsForContext")).toContain("target.database");
expect(extractFunction("listCompletionObjectsForContext")).toContain("target.database");
expect(extractFunction("routineCompletionScopeForContext")).toContain("database: target.database");
expect(extractFunction("completionObjectScopeKey")).toContain("scope.database");
expect(extractFunction("completionObjectScopeKey")).toContain("scope.schema");
expect(metadataSource).toContain("cachedCompletionObjectsByScope");
});
it("loads SQL Server capability metadata before offering or applying USE completion", () => {
const provider = extractFunction("provideSqlCompletions");
expect(provider).toContain("getSqlServerCompletionContext");
expect(provider).toContain("supports_session_database_switch");
expect(provider).toContain("useDatabaseDefaultSchema");
});
it("scopes SQL Server semantic metadata to the database selected by a preceding USE", () => {
const scope = extractFunction("semanticDiagnosticMetadataScope");
expect(scope).toContain("sqlServerUseDatabaseBeforeCursor(sql, range.from)");
expect(scope).toContain("lookupLocalCompletionDatabases");
expect(diagnosticsSource).toMatch(/async function refreshSemanticDiagnostics[\s\S]*?semanticDiagnosticTablesForScope\(semanticAnalysis\.tables, metadataScope\)/);
expect(diagnosticsSource).toContain("enrichSemanticDiagnosticTables(scopedAnalysis.tables, metadataScope)");
expect(diagnosticsSource).toContain("ensureColumnsForSemanticDiagnostics(tables, metadataScope)");
});
});
@@ -1,4 +1,3 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { needsDiagnosticCaretReanchor, type DiagnosticCaretAnchorState } from "@/lib/editor/queryEditorDiagnosticCaretAnchor";
@@ -47,14 +46,3 @@ describe("needsDiagnosticCaretReanchor", () => {
expect(needsDiagnosticCaretReanchor(state({ domRangeCount: 0, currentAnchorNode: null }))).toBe(false);
});
});
describe("QueryEditor diagnostic caret re-anchor wiring", () => {
const queryEditorSource = readFileSync(new URL("../../../components/editor/useQueryEditorDiagnostics.ts", import.meta.url), "utf8");
it("re-anchors the browser caret after applying diagnostics, outside a transaction", () => {
expect(queryEditorSource).toMatch(/function reconfigureDiagnostics\(\)[\s\S]*?reanchorCaretAfterDiagnostics\(currentView\)/);
// The re-anchor must not dispatch a selection transaction: that closes the
// completion popup the user is looking at (#9480).
expect(queryEditorSource).toMatch(/function reanchorCaretAfterDiagnostics\(currentView: EditorViewType\)[\s\S]*?domSelection\.collapse\(target\.node, target\.offset\)/);
});
});
@@ -3,153 +3,12 @@ import { describe, expect, it } from "vitest";
import { createQueryEditorExecutionViewportOwnership, isQueryEditorPositionVisible } from "../../editor/queryEditorExecutionViewport";
const queryEditorSource = ["QueryEditor.vue", "useQueryEditorExecution.ts"].map((file) => readFileSync(new URL(`../../../components/editor/${file}`, import.meta.url), "utf8")).join("\n");
const contentAreaSource = readFileSync(new URL("../../../components/layout/ContentArea.vue", import.meta.url), "utf8");
const editorToolbarSource = readFileSync(new URL("../../../components/layout/EditorToolbar.vue", import.meta.url), "utf8");
const editorGroupSource = readFileSync(new URL("../../../components/layout/EditorGroup.vue", import.meta.url), "utf8");
const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "utf8");
const sqlExecutionSource = readFileSync(new URL("../../../composables/useSqlExecution.ts", import.meta.url), "utf8");
const queryStoreSource = readFileSync(new URL("../../../stores/queryStore.ts", import.meta.url), "utf8");
describe("QueryEditor execution routing", () => {
it("routes the execution shortcut through the shared execution-mode contract while bypassing the picker", () => {
expect(queryEditorSource).toContain("createQueryEditorExecutionShortcutBindings(shortcuts.executeSql");
expect(queryEditorSource).not.toContain("forceCurrent");
});
it("guards both CodeMirror execution bindings and the app-level fallback during IME composition", () => {
expect(queryEditorSource).toContain("createQueryEditorExecutionShortcutBindings(shortcuts.executeSql");
expect(queryEditorSource).toContain("createQueryEditorExecutionShortcutBindings(shortcuts.executeSqlInNewResultTab");
expect(queryEditorSource).toContain("isEditorComposing");
expect(queryEditorSource).toContain("function shouldBlockExecutionShortcut(event?: KeyboardEvent");
expect(queryEditorSource).toContain("postCompositionKeyGuard.blocks(event)");
expect(contentAreaSource).toContain("function shouldBlockQueryEditorExecutionShortcut(event: KeyboardEvent)");
expect(contentAreaSource).toContain("queryEditorRef.value?.shouldBlockExecutionShortcut?.(event)");
expect(appSource).toContain("if (!contentAreaRef.value?.shouldBlockQueryEditorExecutionShortcut?.(e)) requestActiveEditorExecuteInNewResultTab();");
expect(appSource).toContain("if (!contentAreaRef.value?.shouldBlockQueryEditorExecutionShortcut?.(e)) requestActiveEditorExecute();");
});
it("keeps toolbar, context-menu, and gutter execution outside the shortcut guard", () => {
expect(queryEditorSource).toContain("function executeFromContextMenu()");
expect(queryEditorSource).toContain("requestExecute();\n focusEditor();");
expect(queryEditorSource).toContain("function executeSqlStatementFromGutter");
expect(queryEditorSource).toContain("const hasSelectedSql = !selection.empty && currentView.state.sliceDoc(selection.from, selection.to).trim().length > 0;");
expect(queryEditorSource).toContain("const selectionOverlapsStatement = hasSelectedSql && selection.from < statementRange.to && statementRange.from < selection.to;");
expect(queryEditorSource).toContain("const executionSnapshot = selectionOverlapsStatement ? sqlExecutionSnapshotFromView(currentView) : sqlExecutionSnapshotForRange(currentView, statementRange);");
expect(queryEditorSource).toContain("emitExecutionRequest({ ...executionSnapshot, editorViewportRequestId })");
});
it("routes the new-result-tab shortcut through the same target selection contract", () => {
expect(queryEditorSource).toContain("createQueryEditorExecutionShortcutBindings(shortcuts.executeSqlInNewResultTab");
expect(queryEditorSource).toContain('emit("executeInNewResultTab", source)');
expect(queryEditorSource).toContain("requestExecute({ bypassPicker: true, openInNewResultTab: true })");
expect(contentAreaSource).toContain('const showResultRunTabs = computed(() => resultRuns.value.length > 0 && resultRunDisplayMode.value === "tabs")');
expect(contentAreaSource).toContain("!!props.activeTab.resultRuns?.length");
expect(contentAreaSource).toContain('role="tablist" :aria-label="t(\'tabs.resultRuns\')"');
});
it("keeps selection priority and the configured current/all target choice", () => {
const selectionBranch = queryEditorSource.indexOf("if (!options.ignoreSelection && !selection.empty)");
const executeModeBranch = queryEditorSource.indexOf("executionCandidateForMode(candidates, executeMode");
expect(selectionBranch).toBeGreaterThan(-1);
expect(executeModeBranch).toBeGreaterThan(selectionBranch);
});
it("captures the toolbar selection before the click event can change focus", () => {
expect(queryEditorSource).toContain("function captureExecutionSnapshot(): SqlExecutionSnapshot | undefined");
expect(queryEditorSource).toContain("return sqlExecutionSnapshotFromView(currentView);");
expect(contentAreaSource).toContain("function captureQueryEditorExecutionSnapshot()");
expect(contentAreaSource).toContain("queryEditorRef.value?.captureExecutionSnapshot();");
expect(appSource).toContain("const pendingToolbarExecutionSnapshot = ref<SqlExecutionSnapshot & { tabId?: string }>();");
expect(appSource).toContain("contentAreaRef.value?.captureQueryEditorExecutionSnapshot?.(tabId)");
expect(appSource).toContain("pendingToolbarExecutionSnapshot.value = snapshot ? { ...snapshot, tabId } : undefined;");
expect(appSource).toContain('if (source === "pointer" && snapshot && snapshot.tabId === targetTabId)');
expect(appSource).toContain("pendingToolbarExecutionSnapshot.value = undefined;");
expect(appSource).toContain("void tryExecute(snapshot, { tabId: targetTabId });");
expect(appSource).toContain('@execute="(tabId: string, override?: SqlExecutionOverride) => tryExecute(override, { tabId })"');
expect(appSource).toContain("async function resolveActiveExecutableSql(snapshot?: SqlExecutionSnapshot, executionTab?: QueryTab)");
expect(appSource).toContain("const connection = connectionStore.getConfig(tab.connectionId) ?? activeConnection.value;");
// Per-group toolbars call back into App-owned orchestration via injection.
expect(appSource).toContain("provide(EDITOR_TOOLBAR_ACTIONS, {");
expect(appSource).toContain("captureExecutionSnapshot: captureActiveEditorExecutionSnapshot,");
expect(appSource).toContain("toolbarExecute: requestActiveEditorExecute,");
expect(editorGroupSource).toContain('@execute-pointer-down="toolbar.captureExecutionSnapshot(activeTab.id)"');
expect(editorGroupSource).toContain('@toolbar-execute="toolbar.toolbarExecute($event, activeTab.id)"');
expect(editorToolbarSource).toContain("function onExecutePointerDown(event: MouseEvent)");
expect(editorToolbarSource).toContain('emit("toolbarExecute", event.detail > 0 ? "pointer" : "keyboard")');
expect(editorToolbarSource).not.toContain('emit("execute", event.detail > 0 ? "pointer" : "keyboard")');
});
it("uses the opt-in blank-line fallback and otherwise reports the missing cursor statement", () => {
expect(queryEditorSource).toContain("executeAllOnBlankLine: settingsStore.editorSettings.executeAllOnBlankLine");
expect(queryEditorSource).toContain('toast(t("editor.noExecutableStatementAtCursor"), 3000)');
expect(queryEditorSource).not.toContain("?? candidates[0]");
});
it("consumes the execution shortcut and reports an empty current target", () => {
expect(queryEditorSource).toContain("if (candidates.length === 0)");
expect(queryEditorSource).toContain('if (executeMode === "current") toast(t("editor.noExecutableStatementAtCursor"), 3000)');
});
it("preserves the source range when executing a current/all candidate without a manual selection", () => {
expect(queryEditorSource).toContain("emitExecutionRequest(sqlExecutionSnapshotForRange(currentView, candidate), options.openInNewResultTab)");
expect(queryEditorSource).toContain("currentView ? sqlExecutionSnapshotForRange(currentView, candidate) : candidate.sql");
expect(queryEditorSource).toContain("selectionFrom: range.from");
expect(queryEditorSource).toContain("selectionTo: range.to");
});
it("preserves the source range when executing from the statement gutter", () => {
expect(queryEditorSource).toContain("const editorViewportRequestId = executionViewportOwnership.beginRequest()");
expect(queryEditorSource).toContain("sqlExecutionSnapshotFromView(currentView)");
expect(queryEditorSource).toContain("sqlExecutionSnapshotForRange(currentView, statementRange)");
expect(queryEditorSource).toContain("emitExecutionRequest({ ...executionSnapshot, editorViewportRequestId })");
expect(queryEditorSource).not.toContain('emit("execute", statementRange.sql)');
});
it("claims gutter viewport ownership only after the matching execution starts", () => {
expect(appSource).toContain("acceptQueryEditorExecutionViewport(editorViewportRequestId)");
expect(appSource).toContain("onExecutionCancelled: (editorViewportRequestId) => contentAreaRef.value?.cancelQueryEditorExecutionViewport(editorViewportRequestId)");
expect(contentAreaSource).toContain("acceptGutterExecutionViewport(requestId)");
expect(contentAreaSource).toContain("cancelGutterExecutionViewport(requestId)");
expect(sqlExecutionSource).toContain("onExecutionStarted: () => deps.onExecutionStarted?.(options.editorViewportRequestId!)");
expect(sqlExecutionSource).toContain("onExecutionCancelled?: (editorViewportRequestId: number) => void;");
expect(queryStoreSource.indexOf("tab.isExecuting = true")).toBeLessThan(queryStoreSource.indexOf("options?.onExecutionStarted?.()"));
});
it("tracks editor interaction while a query is executing", () => {
expect(contentAreaSource).toContain("queryEditorRef.value?.beginExecutionViewportTracking()");
expect(queryEditorSource).toContain('@wheel="recordExecutionViewportInteraction"');
expect(queryEditorSource).toContain('@pointerdown="recordExecutionViewportInteraction"');
expect(queryEditorSource).toContain("executionViewportOwnership.recordUserInteraction()");
});
it("lets the shortcut skip the picker without affecting other execution entry points", () => {
// The picker guard must also honor the shortcut's bypass flag, otherwise Ctrl+Enter would keep popping the dialog.
expect(queryEditorSource).toContain("if (options.bypassPicker || !settingsStore.editorSettings.showExecutionTargetPicker");
});
it("inserts a complete indented line below the current line", () => {
expect(queryEditorSource).toContain('userEvent: "input.insertLineBelow"');
expect(queryEditorSource).toContain("changes: { from: line.to, to: line.to, insert: insertion }");
expect(queryEditorSource).toContain("const cursor = line.to + insertion.length");
expect(queryEditorSource).not.toMatch(/key:\s*"Enter"[\s\S]{0,180}shift:\s*codeMirrorInsertNewlineKeepIndent/);
});
it("routes custom SQL shortcuts through selection-aware execution with dual keymap and DOM handlers", () => {
expect(queryEditorSource).toContain("function runSqlShortcutAction(");
expect(queryEditorSource).toContain('if (queryEditorSelectionLanguage() !== "sql") return false;');
expect(queryEditorSource).toContain("buildSqlShortcutExecutionSql(action, selected, props.databaseType)");
expect(queryEditorSource).toContain("enabledSqlShortcutActions(settingsStore.editorSettings.sqlShortcuts)");
expect(queryEditorSource).toContain("uniqueSqlShortcutBindings(sqlShortcutActions)");
expect(queryEditorSource).toContain("resolveSqlShortcutForDatabase(settingsStore.editorSettings.sqlShortcuts, shortcut, props.databaseType)");
expect(queryEditorSource).toContain("isCharacterProducingShortcut(shortcut)");
expect(queryEditorSource).toContain("createQueryEditorSqlShortcutDomHandler(");
expect(queryEditorSource).toContain("() => props.databaseType");
expect(queryEditorSource).toContain("shouldBlockExecutionShortcut(event, currentView)");
expect(queryEditorSource).toContain("if (props.readOnly) return true;");
expect(queryEditorSource).toContain("settingsStore.editorSettings.sqlShortcuts");
expect(queryEditorSource).toContain("runKeymapComp.reconfigure(runKeymapExtension(codeMirrorRuntime.editorViewModule.keymap))");
});
});
describe("QueryEditor execution viewport ownership", () => {
@@ -253,24 +112,4 @@ describe("QueryEditor completion cursor visibility", () => {
expect(isQueryEditorPositionVisible(15, [], viewport)).toBe(true);
expect(isQueryEditorPositionVisible(21, undefined, viewport)).toBe(false);
});
it("checks visibility after completion ownership and before centering", () => {
const ownershipCheck = queryEditorSource.indexOf("executionViewportOwnership.consumeCompletionPreservation()");
const visibilityCheck = queryEditorSource.indexOf("if (isQueryEditorPositionVisible(pos, currentView.visibleRanges, currentView.viewport)) return");
const centerScroll = queryEditorSource.indexOf('EditorView.scrollIntoView(pos, { y: "center" })');
expect(ownershipCheck).toBeGreaterThan(-1);
expect(visibilityCheck).toBeGreaterThan(ownershipCheck);
expect(centerScroll).toBeGreaterThan(visibilityCheck);
});
});
describe("ContentArea execution summary errors", () => {
it("keeps batch errors selectable and copyable without triggering statement navigation", () => {
expect(contentAreaSource).toContain('class="absolute inset-0 z-0 cursor-pointer');
expect(contentAreaSource).toContain('data-native-clipboard class="min-w-0 flex-1 cursor-text select-text truncate"');
expect(contentAreaSource).toContain("@mousedown.stop @click.stop @dblclick.stop");
expect(contentAreaSource).toContain('@click.stop="copyExecutionSummaryError(item.error)"');
expect(contentAreaSource).toContain("await copyToClipboard(error)");
});
});
@@ -1,4 +1,3 @@
import { readFileSync } from "node:fs";
import { selectParentSyntax } from "@codemirror/commands";
import { sql } from "@codemirror/lang-sql";
import { EditorSelection, EditorState } from "@codemirror/state";
@@ -9,8 +8,6 @@ import { extendQueryEditorSelection, runQueryEditorAltExtendSelection } from "@/
import { chooseNextSemanticSelectionRange, type SemanticSelectionRange } from "@/lib/editor/semanticSelectionRanges";
import { sqlSemanticSelectionRanges } from "@/lib/editor/sqlSemanticSelectionRanges";
const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
function runCommand(command: Command, state: EditorState): EditorState {
let nextState = state;
const handled = command({
@@ -390,18 +387,6 @@ describe("query editor extend selection", () => {
expect(next.sliceDoc(next.selection.main.from, next.selection.main.to)).toBe("'001'");
});
it("binds the configurable editor shortcut to CodeMirror semantic selection", () => {
expect(queryEditorSource).toContain("extendQueryEditorSelection");
expect(queryEditorSource).not.toContain("selectParentSyntax");
expect(queryEditorSource).not.toContain("codeMirrorSelectParentSyntax");
expect(queryEditorSource).toContain("shortcuts.extendSelection");
expect(queryEditorSource).toContain("runQueryEditorAltExtendSelection");
});
it("registers a high-priority SQL string mouse selection style", () => {
expect(queryEditorSource).toMatch(/Prec\.highest\(\s*EditorView\.mouseSelectionStyle\.of/);
});
it("matches macOS Option+W by physical key when the event key is transformed", () => {
let commandRuns = 0;
let prevented = false;
@@ -1,11 +1,6 @@
import { readFileSync } from "node:fs";
import { describe, expect, it, vi } from "vitest";
import { focusEditorView, type EditorViewLike } from "@/lib/editor/queryEditorFocus";
const queryEditorSource = ["QueryEditor.vue", "queryEditorTypes.ts", "useQueryEditorExecution.ts", "useQueryEditorDocumentState.ts"].map((file) => readFileSync(new URL(`../../../components/editor/${file}`, import.meta.url), "utf8")).join("\n");
const contentAreaSource = readFileSync(new URL("../../../components/layout/ContentArea.vue", import.meta.url), "utf8");
const editorToolbarSource = readFileSync(new URL("../../../components/layout/EditorToolbar.vue", import.meta.url), "utf8");
function createMockView(overrides: Partial<EditorViewLike> = {}): EditorViewLike {
return {
hasFocus: false,
@@ -37,25 +32,3 @@ describe("focusEditorView", () => {
expect(focusEditorView(undefined)).toBe(false);
});
});
describe("QueryEditor auto focus wiring", () => {
it("keeps auto focus opt-in for shared editor instances", () => {
expect(queryEditorSource).toContain("autoFocus?: boolean;");
expect(queryEditorSource).toMatch(/if \(props\.autoFocus\) \{[\s\S]*focusEditorView\(view\.value\);/);
});
it("enables auto focus for query tabs", () => {
expect(contentAreaSource).toMatch(/<QueryEditor[\s\S]*?:\s*auto-focus="autoFocus !== false"\s[\s\S]*?:model-value="activeTab\.sql"/);
});
it("restores focus when the active query tab changes", () => {
expect(queryEditorSource).toMatch(/if \(tabId !== prevTabId\) \{[\s\S]*?activateTabDocument\(prevTabId, tabId, val\);[\s\S]*?if \(props\.autoFocus\) restoreEditorFocus\(\);/);
});
});
describe("QueryEditor toolbar focus", () => {
it("does not move focus from the editor when clicking execute", () => {
expect(editorToolbarSource).toMatch(/:disabled="activeTab\.isCancelling[\s\S]*?@mousedown\.prevent="onExecutePointerDown"[\s\S]*?@click="onExecuteClick"/);
expect(queryEditorSource).toMatch(/function requestExecute\([\s\S]*?const currentView = view\.value;[\s\S]*?currentView\.focus\(\);[\s\S]*?requestExecuteFromView\(currentView/);
});
});
@@ -1,37 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const queryEditorSource = readFileSync(new URL("../../../components/editor/useQueryEditorHover.ts", import.meta.url), "utf8");
const contentSource = readFileSync(new URL("../../../components/editor/queryEditorHoverContent.ts", import.meta.url), "utf8");
describe("QueryEditor hover DDL copy", () => {
it("reconciles the local sidebar index before remote hover fallback", () => {
const hoverStart = queryEditorSource.indexOf("async function resolveSqlHoverTooltip");
const hoverEnd = queryEditorSource.indexOf("\n }\n", hoverStart);
const hoverSource = queryEditorSource.slice(hoverStart, hoverEnd);
const localLookup = hoverSource.indexOf("connectionStore.lookupLocalCompletionTables");
const remoteLookup = hoverSource.indexOf("connectionStore.listCompletionTables");
expect(hoverStart).toBeGreaterThanOrEqual(0);
expect(hoverEnd).toBeGreaterThan(hoverStart);
expect(localLookup).toBeGreaterThanOrEqual(0);
expect(remoteLookup).toBeGreaterThan(localLookup);
expect(hoverSource).toContain("hoverTables = mergeCompletionTables(localHoverTables, hoverTables);");
expect(hoverSource).toContain("completionMetadata.cachedTables = mergeCompletionTables(localHoverTables, completionMetadata.cachedTables);");
});
it("gates only the table DDL branch on the preference, keeping column hover", () => {
expect(queryEditorSource).not.toContain("if (!settingsStore.editorSettings.showTableDdlHoverPreview) return null;");
expect(queryEditorSource).toContain("if (table && settingsStore.editorSettings.showTableDdlHoverPreview && !semanticQualifierIsRowSource");
});
it("adds an accessible copy button that preserves SQL whitespace semantics", () => {
expect(contentSource).toContain('copyButton.textContent = t("grid.copyDdl");');
expect(contentSource).toContain('copyButton.setAttribute("aria-label", t("grid.copyDdl"));');
expect(contentSource).toContain('copyButton.addEventListener("pointerdown"');
expect(contentSource).toContain("event.stopPropagation();");
expect(contentSource).toContain("await copyToClipboard(normalizeAlignedSqlWhitespace(sqlContent));");
expect(contentSource).toContain('toast(t("contextMenu.ddlCopied"), 2000);');
expect(contentSource).toContain('toast(t("grid.copyFailed", { message: error?.message || String(error) }), 5000);');
});
});
@@ -1,10 +1,7 @@
import { readFileSync } from "node:fs";
import { EditorSelection, EditorState, type Extension, type Transaction } from "@codemirror/state";
import { describe, expect, it, vi } from "vitest";
import { joinQueryEditorLines } from "@/lib/editor/queryEditorJoinLines";
const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
function runJoinLines(doc: string, selection: EditorSelection | { anchor: number; head?: number }, extensions: Extension[] = []) {
let state = EditorState.create({ doc, selection, extensions });
const dispatch = vi.fn((transaction: Transaction) => {
@@ -21,11 +18,6 @@ function runJoinLines(doc: string, selection: EditorSelection | { anchor: number
}
describe("joinQueryEditorLines", () => {
it("binds the configurable join-lines shortcut in QueryEditor", () => {
expect(queryEditorSource).toContain('import { joinQueryEditorLines } from "@/lib/editor/queryEditorJoinLines";');
expect(queryEditorSource).toContain("...binding(shortcuts.joinLines, joinQueryEditorLines)");
});
it("joins every selected line with one separating space", () => {
const doc = "SELECT id,\n name\nFROM users;";
const result = runJoinLines(doc, EditorSelection.range(0, doc.length));
@@ -1,11 +1,8 @@
import { readFileSync } from "node:fs";
import { history, undo, undoDepth } from "@codemirror/commands";
import { EditorState, Transaction } from "@codemirror/state";
import { describe, expect, it } from "vitest";
import { LARGE_PASTE_HISTORY_USER_EVENT, LARGE_PASTE_NATIVE_RECOVERY_THRESHOLD, normalizeQueryEditorPasteText, recoverableNativePasteSuffix, shouldRecoverLargeTauriPaste } from "@/lib/editor/queryEditorLargePaste";
const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
describe("QueryEditor large paste recovery", () => {
it("recovers the suffix of a SQL paste truncated at the WebView boundary", () => {
const sql = Array.from({ length: 10_925 }, (_, index) => `('Z${String(index).padStart(13, "0")}'),`).join("\r\n");
@@ -59,8 +56,4 @@ describe("QueryEditor large paste recovery", () => {
expect(state.doc.toString()).toBe("SELECT ");
expect(state.selection.main.from).toBe(7);
});
it("wires the recovery into the editor paste event", () => {
expect(queryEditorSource).toMatch(/paste\(event, currentView\)[\s\S]*?recoverLargeTauriPaste\(event, currentView\)/);
});
});
@@ -1,15 +1,9 @@
import { readFileSync } from "node:fs";
import { toggleLineComment } from "@codemirror/commands";
import { sql } from "@codemirror/lang-sql";
import { EditorState, Prec, type Transaction } from "@codemirror/state";
import { describe, expect, it, vi } from "vitest";
import { queryEditorCommentTokens, queryEditorLineCommentToken, queryEditorWordLanguageData } from "@/lib/editor/queryEditorLineComment";
const editorThemesSource = readFileSync(new URL("../../editor/editorThemes.ts", import.meta.url), "utf8");
const shellHighlightSource = readFileSync(new URL("../../editor/codemirrorShellLineCommentHighlight.ts", import.meta.url), "utf8");
const extensionsSource = readFileSync(new URL("../../../components/editor/queryEditorSqlExtensions.ts", import.meta.url), "utf8");
function runToggleLineComment(doc: string, commentToken: string) {
let state = EditorState.create({
doc,
@@ -72,24 +66,6 @@ describe("QueryEditor word selection", () => {
});
describe("QueryEditor line comment", () => {
it("overrides the language comment tokens in the SQL language compartment", () => {
expect(extensionsSource).toContain("Prec.highest(EditorState.languageData.of(() => [{ commentTokens: queryEditorCommentTokens(props.databaseType) }]))");
});
it("highlights // comments with the theme's comment style", () => {
expect(extensionsSource).toContain('queryEditorLineCommentToken(props.databaseType) === "//" ? shellLineCommentHighlightPlugin : []');
expect(extensionsSource).toContain("const shellLineCommentHighlightPlugin = createShellLineCommentHighlight({ ViewPlugin, Decoration, highlightingFor, syntaxTree });");
expect(extensionsSource).toContain("shellLineCommentTheme(EditorView),");
expect(editorThemesSource).toContain('".cm-shell-line-comment *"');
expect(editorThemesSource).toContain('color: "inherit !important"');
});
it("bounds shell comment scanning to syntax-aware visible lines", () => {
expect(shellHighlightSource).toContain("view.state.doc.lineAt(visibleRange.from).from");
expect(shellHighlightSource).toContain("tree.resolveInner(absoluteFrom, 1)");
expect(shellHighlightSource).not.toContain("sliceString(0, end)");
});
it("comments a MongoDB line with //", () => {
const result = runToggleLineComment("db.users.find({})", "//");
@@ -1,10 +1,7 @@
import { readFileSync } from "node:fs";
import { EditorSelection } from "@codemirror/state";
import { describe, expect, it } from "vitest";
import { computePasteCaretResyncTarget } from "@/lib/editor/queryEditorPasteCaretResync";
const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
describe("computePasteCaretResyncTarget", () => {
it("nudges a single caret forward when there is room", () => {
expect(computePasteCaretResyncTarget(EditorSelection.single(3), 10)).toBe(4);
@@ -27,10 +24,3 @@ describe("computePasteCaretResyncTarget", () => {
expect(computePasteCaretResyncTarget(EditorSelection.single(0), 0)).toBeNull();
});
});
describe("QueryEditor paste caret resync wiring", () => {
it("resyncs only an unchanged single caret after an input.paste transaction", () => {
expect(queryEditorSource).toMatch(/update\.transactions\.some\(\(tr\) => tr\.isUserEvent\("input\.paste"\)\)[\s\S]*?resyncCaretAfterPaste\(update\.view\)/);
expect(queryEditorSource).toMatch(/computePasteCaretResyncTarget\(selection, view\.state\.doc\.length\)/);
});
});
@@ -1,13 +1,6 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { expandToSqlStatementWindow } from "@/lib/sql/insertValueHints";
const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
const diagnosticsSource = readFileSync(new URL("../../../components/editor/useQueryEditorDiagnostics.ts", import.meta.url), "utf8");
const extensionsSource = readFileSync(new URL("../../../components/editor/queryEditorSqlExtensions.ts", import.meta.url), "utf8");
describe("QueryEditor semantic highlighting while scrolling", () => {
it("recognizes the large single-statement shape from the reported regression", () => {
const sql = `CREATE TABLE [dbo].[code] ([id] int, [label] nvarchar(32));\nINSERT INTO [dbo].[code] ([id], [label]) VALUES\n${Array.from({ length: 240 }, (_, index) => `(${index}, N'row-${String(index).padStart(4, "0")}'),`).join("\n")}`;
@@ -17,42 +10,4 @@ describe("QueryEditor semantic highlighting while scrolling", () => {
expect(window.to - window.from).toBeGreaterThan(2_000);
expect(window.from).toBe(insertStart);
});
it("reuses semantic statement windows across viewport-only updates", () => {
expect(extensionsSource).toContain('private cachedDoc: import("@codemirror/state").Text | null = null;');
expect(extensionsSource).toContain("private cachedWindows: Array<{");
expect(extensionsSource).toContain("const cached = this.cachedWindows.find");
expect(extensionsSource).toContain("const pendingWindows: Array<{ from: number; to: number }>");
expect(extensionsSource).toContain("MAX_SQL_SEMANTIC_HIGHLIGHT_WINDOWS = 32");
expect(extensionsSource).toContain("this.cachedWindows.splice(0, this.cachedWindows.length - MAX_SQL_SEMANTIC_HIGHLIGHT_WINDOWS)");
});
it("defers semantic highlighting while the document is changing", () => {
expect(extensionsSource).toContain("SQL_SEMANTIC_HIGHLIGHT_DEBOUNCE_MS = 100");
expect(extensionsSource).toContain("this.decorations = this.decorations.map(update.changes)");
expect(extensionsSource).toContain("refreshSqlSemanticHighlightEffect.of(null)");
});
it("never exposes undefined decorations and prewarms the full document only once per document", () => {
expect(extensionsSource).toContain("this.decorations = Decoration.none;");
expect(extensionsSource).toContain('private prewarmedDoc: import("@codemirror/state").Text | null = null;');
expect(extensionsSource).toContain("const shouldPrewarmFullDocument =");
expect(extensionsSource).toContain("if (shouldPrewarmFullDocument) this.prewarmedDoc = doc;");
});
it("keeps existing highlights while the parser catches up instead of wiping them", () => {
// An incomplete Lezer parse must not clear table-name decorations: the
// deferred refresh retries, so a freshly mounted editor (tab switch) also
// recovers even without a later viewport change.
expect(extensionsSource).toContain("this.scheduleRefresh(currentView);");
expect(extensionsSource).toContain("return this.decorations;");
});
it("keeps preview and diagnostics on the shared statement-range cache", () => {
expect(queryEditorSource).toContain("executableStatementRangeCache = executableStatementRangeCacheForDoc");
expect(diagnosticsSource).toContain('props.databaseType === "sqlserver" ? undefined : runtime.executableStatementRangeCache?.ranges');
expect(queryEditorSource).toContain("get executableStatementRangeCache()");
expect(queryEditorSource).toContain("set executableStatementRangeCache(value)");
expect(queryEditorSource).toContain("const cursorRange = executableStatementRangeAtCursor(executableStatementRangeCache, cursorPos)");
});
});
@@ -1,22 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
const runtimeSource = readFileSync(new URL("../../../components/editor/queryEditorCodeMirrorRuntime.ts", import.meta.url), "utf8");
describe("QueryEditor SQL signature refresh wiring", () => {
it("reconfigures signature help when the database dialect or driver profile changes", () => {
expect(runtimeSource).toContain('sqlSignatureComp: import("@codemirror/state").Compartment | null;');
expect(runtimeSource).toContain("runtime.sqlSignatureComp = new Compartment();");
expect(queryEditorSource).toContain("initializedRuntime.sqlSignatureComp.of(sqlExtensions.buildSqlSignatureExtension())");
const watcherStart = queryEditorSource.indexOf("watch([() => props.databaseType, () => props.dialect, () => props.syntaxDialect, sqlDriverProfile]");
const watcherEnd = queryEditorSource.indexOf("\n});", watcherStart);
const dialectWatcher = queryEditorSource.slice(watcherStart, watcherEnd);
expect(watcherStart).toBeGreaterThanOrEqual(0);
expect(watcherEnd).toBeGreaterThan(watcherStart);
expect(dialectWatcher).toContain("codeMirrorRuntime.sqlSignatureComp.reconfigure(codeMirrorRuntime.buildSqlSignatureExtension())");
});
});
@@ -1,12 +1,7 @@
import { readFileSync } from "node:fs";
import { EditorSelection, EditorState } from "@codemirror/state";
import { describe, expect, it, vi } from "vitest";
import { blankLineDeletionChanges, replaceSelectedEditorText } from "@/lib/editor/queryEditorTextEdits";
const queryEditorSource = ["QueryEditor.vue", "useQueryEditorTextActions.ts"].map((file) => readFileSync(new URL(`../../../components/editor/${file}`, import.meta.url), "utf8")).join("\n");
const contextMenuSource = readFileSync(new URL("../../../components/editor/QueryEditorContextMenu.vue", import.meta.url), "utf8");
function applyBlankLineDeletion(doc: string, from: number, to: number): string {
const state = EditorState.create({
doc,
@@ -27,12 +22,6 @@ describe("replaceSelectedEditorText", () => {
expect(replaceSelectedEditorText({ state, dispatch }, "'a','b'")).toBe(false);
expect(dispatch).not.toHaveBeenCalled();
});
it("disables and guards delimited-list generation in QueryEditor", () => {
expect(contextMenuSource).toContain("disabled: state.readOnly || !canCopySelectedSql");
expect(queryEditorSource).toMatch(/function openDelimitedListDialog\(\) \{\s+if \(props\.readOnly\) return;/);
expect(queryEditorSource).toMatch(/function applyDelimitedListResult\(result: string\) \{[\s\S]*if \(!currentView \|\| props\.readOnly\) return;[\s\S]*replaceSelectedEditorText/);
});
});
describe("blankLineDeletionChanges", () => {
@@ -16,7 +16,6 @@ import {
} from "@/lib/mcp/mcpPolicySelection";
const settingsDialogSource = readFileSync(new URL("../../../components/editor/EditorSettingsDialog.vue", import.meta.url), "utf8");
const scopePickerSource = readFileSync(new URL("../../../components/settings/McpConnectionScopePicker.vue", import.meta.url), "utf8");
const mcpServerSource = readFileSync(new URL("../../../../../../crates/dbx-mcp/src/server.rs", import.meta.url), "utf8");
describe("MCP execution permission selection", () => {
@@ -133,76 +132,6 @@ describe("MCP policy settings state", () => {
expect(loadingStart).toBeLessThan(policyLoad);
expect(loadingEnd).toBeGreaterThan(policyLoad);
});
it("renders one static mode hint in place of stacked per-mode description tracks", () => {
expect(settingsDialogSource).not.toContain("data-mcp-execution-mode-description");
const groupStart = settingsDialogSource.indexOf('role="radiogroup" aria-labelledby="mcp-execution-mode-label"');
const hintIndex = settingsDialogSource.indexOf("settings.mcpPermissionGlobalDefaultHint");
expect(groupStart).toBeGreaterThan(-1);
expect(hintIndex).toBeGreaterThan(groupStart);
});
it("keeps execution mode cards accessible as a keyboard radio group", () => {
expect(settingsDialogSource).toContain('role="radiogroup" aria-labelledby="mcp-execution-mode-label"');
expect(settingsDialogSource).toContain('v-for="mode in mcpExecutionModeOptions"');
expect(settingsDialogSource.match(/role="radio"/g)).toHaveLength(1);
expect(settingsDialogSource).toContain(':aria-checked="mcpExecutionMode === mode"');
expect(settingsDialogSource).toContain(':tabindex="mcpExecutionMode === mode ? 0 : -1"');
expect(settingsDialogSource).toContain("onMcpExecutionModeKeydown($event, mode)");
expect(settingsDialogSource).toContain('@keydown="onMcpExecutionModeKeydown($event, mode)"');
});
it("keeps MCP client config tabs on a single scrollable row", () => {
const tabsStart = settingsDialogSource.indexOf('<Tabs v-model="mcpConfigTab"');
const tabsEnd = settingsDialogSource.indexOf("</TabsList>", tabsStart);
const tabsSource = settingsDialogSource.slice(tabsStart, tabsEnd);
expect(tabsStart).toBeGreaterThan(-1);
expect(tabsEnd).toBeGreaterThan(tabsStart);
expect(tabsSource).toContain("overflow-x-auto");
expect(tabsSource).toContain("min-w-0");
expect(tabsSource).toContain("max-w-full");
expect(tabsSource).toContain("overscroll-x-contain");
expect(tabsSource).not.toContain("flex-wrap");
expect(tabsSource).not.toContain("grid-cols-");
expect(tabsSource.match(/flex-none shrink-0/g)).toHaveLength(14);
expect(tabsSource).toContain('<TabsTrigger value="deepseek-harness"');
expect(tabsSource).toContain('<TabsTrigger value="codebuddy"');
expect(tabsSource).toContain('<TabsTrigger value="zcode"');
expect(tabsSource).toContain('<TabsTrigger value="qoder"');
expect(tabsSource).toContain('<TabsTrigger value="workbuddy"');
expect(tabsSource).not.toContain("min-w-0 px-");
const codeBuddyStart = settingsDialogSource.indexOf('<TabsContent value="codebuddy"', tabsEnd);
const codeBuddyEnd = settingsDialogSource.indexOf("</TabsContent>", codeBuddyStart);
const codeBuddySource = settingsDialogSource.slice(codeBuddyStart, codeBuddyEnd);
expect(codeBuddyStart).toBeGreaterThan(tabsEnd);
expect(codeBuddyEnd).toBeGreaterThan(codeBuddyStart);
expect(codeBuddySource).toContain("settings.mcpCodeBuddyConfigPath");
expect(codeBuddySource).toContain("mcpJsonRecommendedConfig");
expect(codeBuddySource).toContain("copyMcpText('codebuddy-config', mcpJsonRecommendedConfig)");
const zCodeStart = settingsDialogSource.indexOf('<TabsContent value="zcode"', tabsEnd);
const zCodeEnd = settingsDialogSource.indexOf("</TabsContent>", zCodeStart);
const zCodeSource = settingsDialogSource.slice(zCodeStart, zCodeEnd);
expect(zCodeStart).toBeGreaterThan(tabsEnd);
expect(zCodeEnd).toBeGreaterThan(zCodeStart);
expect(zCodeSource).toContain("settings.mcpZCodeConfigPath");
expect(zCodeSource).toContain("mcpJsonRecommendedConfig");
expect(zCodeSource).toContain("copyMcpText('zcode-config', mcpJsonRecommendedConfig)");
const qoderStart = settingsDialogSource.indexOf('<TabsContent value="qoder"', tabsEnd);
const qoderEnd = settingsDialogSource.indexOf("</TabsContent>", qoderStart);
const qoderSource = settingsDialogSource.slice(qoderStart, qoderEnd);
expect(qoderStart).toBeGreaterThan(tabsEnd);
expect(qoderEnd).toBeGreaterThan(qoderStart);
expect(qoderSource).toContain("settings.mcpQoderConfigPath");
expect(qoderSource).toContain("mcpQoderRecommendedConfig");
expect(qoderSource).toContain("copyMcpText('qoder-config', mcpQoderRecommendedConfig)");
});
});
describe("MCP connection search", () => {
@@ -218,12 +147,4 @@ describe("MCP connection search", () => {
expect(matchesMcpSearchQuery(" ", [null, undefined])).toBe(true);
expect(matchesMcpSearchQuery("missing-id", ["missing-id-123", "Previously selected connection (unavailable)"])).toBe(true);
});
it("uses responsive allowed and available panes with an allowed-first compact view", () => {
expect(scopePickerSource).toContain('const compactPane = ref<ScopePane>("allowed")');
expect(scopePickerSource).toContain('data-scope-pane="available"');
expect(scopePickerSource).toContain('data-scope-pane="allowed"');
expect(scopePickerSource).toContain("@container mcp-scope (min-width: 42rem)");
expect(scopePickerSource).toContain("filteredUnavailableAllowedIds");
});
});
-63
View File
@@ -1,63 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
function componentSource(name: string): string {
return readFileSync(new URL(`../../../components/mq/${name}`, import.meta.url), "utf8");
}
describe("MQ list panels", () => {
it("does not issue per-tenant detail requests from the tenant list UI", () => {
const source = componentSource("TenantsPanel.vue");
expect(source).not.toContain("mqGetTenant");
});
it("does not issue per-namespace permission requests from the namespace list UI", () => {
const source = componentSource("NamespacesPanel.vue");
expect(source).not.toContain("mqListPermissions");
});
it("refreshing policies hydrates missing fields from defaults instead of dirty form values", () => {
const source = componentSource("PoliciesPanel.vue");
expect(source).not.toContain("policyFormsFromEffectivePolicies(loaded, currentPolicyForms())");
expect(source).toContain("policyFormsFromEffectivePolicies(loaded, defaultMqPolicyForms())");
});
it("raw api panel includes common endpoint presets that use the selected mq context", () => {
const rawSource = componentSource("RawApiPanel.vue");
const consoleSource = componentSource("MqAdminConsole.vue");
expect(rawSource).toContain("const presets = computed<RawApiPreset[]>");
expect(rawSource).toContain("/admin/v2/brokers/version");
expect(rawSource).toContain("/internalStats");
expect(rawSource).toContain("/partitioned-stats");
expect(rawSource).toContain("/schema");
expect(rawSource).toContain("presetsCollapsed");
expect(rawSource).toContain("formatJsonBody");
expect(rawSource).toContain("bodyTextareaRows");
expect(rawSource).toContain("body: isReadMethod.value ? undefined : parseBody()");
expect(consoleSource).toContain(':tenant="selectedTenant"');
expect(consoleSource).toContain(':namespace="selectedNamespace"');
expect(consoleSource).toContain(':topic="selectedTopic"');
});
it("keeps Kafka topic subscriptions and cluster-wide consumer groups on separate panels", () => {
const consoleSource = componentSource("MqAdminConsole.vue");
expect(consoleSource).toContain("KafkaConsumerGroupsPanel");
expect(consoleSource).toContain("activeTab === 'subscriptions' && canManageSubscriptions");
expect(consoleSource).toContain("activeTab === 'consumerGroups' && isKafkaCluster");
expect(consoleSource).not.toContain("activeTab === 'subscriptions' && canManageSubscriptions && isKafkaCluster");
});
it("routes a Kafka consumer-group partition topic to its topic-scoped subscriptions", () => {
const consoleSource = componentSource("MqAdminConsole.vue");
expect(consoleSource).toContain("function handleKafkaConsumerGroupTopicSelected(topic: string)");
expect(consoleSource).toContain("shortName: topic");
expect(consoleSource).toContain('setActiveTab("subscriptions")');
expect(consoleSource).toContain('@navigate-subscriptions="handleKafkaConsumerGroupTopicSelected"');
});
});
@@ -1,98 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const appSource = readFileSync(new URL("../../../App.vue", import.meta.url), "utf8");
const toolbarSource = readFileSync(new URL("../../../components/layout/AppToolbar.vue", import.meta.url), "utf8");
const groupTabBarSource = readFileSync(new URL("../../../components/layout/EditorGroupTabBar.vue", import.meta.url), "utf8");
const driverStoreSource = readFileSync(new URL("../../../components/config/DriverStoreDialog.vue", import.meta.url), "utf8");
const appDialogsSource = readFileSync(new URL("../../../components/layout/AppDialogs.vue", import.meta.url), "utf8");
const connectionDialogSource = readFileSync(new URL("../../../components/connection/ConnectionDialog.vue", import.meta.url), "utf8");
const pluginCenterSource = readFileSync(new URL("../../../components/plugins/PluginContributionsPanel.vue", import.meta.url), "utf8");
const settingsDialogSource = readFileSync(new URL("../../../components/editor/EditorSettingsDialog.vue", import.meta.url), "utf8");
const connectionStoreSource = readFileSync(new URL("../../../stores/connectionStore.ts", import.meta.url), "utf8");
describe("plugin center integration", () => {
it("opens from the top toolbar as an independent app surface", () => {
expect(toolbarSource).toContain("toolbarItems.pluginCenter");
expect(toolbarSource).toContain("emit('open-plugin-center')");
expect(appSource).toContain('@open-plugin-center="openPluginCenterPage()"');
expect(appSource).toContain("<PluginCenterPage");
// The plugin center pill lives in the focused group's tab strip, like the
// settings and driver-store special pages.
expect(groupTabBarSource).toContain("data-plugin-center-tab");
expect(appSource).toContain(':plugin-center-open="pluginCenterTabOpen"');
});
it("keeps plugin management out of Driver Manager", () => {
expect(driverStoreSource).not.toContain('value="plugins"');
expect(driverStoreSource).not.toContain("PluginContributionsPanel");
});
it("refreshes toolbar update state after manual and component update checks", () => {
expect(appSource).toContain('if (componentRefresh.status === "fulfilled" && componentRefresh.value) syncToolbarComponentUpdateState()');
expect(appSource).toContain("if (result.failed.length === 0) syncToolbarComponentUpdateState()");
expect(appSource).toContain("function syncToolbarComponentUpdateState()");
});
it("refreshes all update sources in the background whenever the update center opens", () => {
expect(appSource).toContain("function handleToolbarUpdateClick() {\n showUpdateDialog.value = true;\n if (!checkingAllUpdates.value) void checkAllUpdates();\n}");
});
it("refreshes the plugin center after component-level plugin updates", () => {
expect(appSource).toContain("notifyComponentPluginsUpdated()");
expect(pluginCenterSource).toContain("COMPONENT_PLUGINS_UPDATED_EVENT");
expect(pluginCenterSource).toContain("window.addEventListener(COMPONENT_PLUGINS_UPDATED_EVENT, handleComponentPluginsUpdated)");
expect(pluginCenterSource).toContain("installedPlugins.value = await api.listPlugins()");
});
it("refreshes global component update state after manual management-surface changes", () => {
expect(appSource).toContain("COMPONENT_UPDATES_CHANGED_EVENT");
expect(appSource).toContain("window.addEventListener(COMPONENT_UPDATES_CHANGED_EVENT, handleComponentUpdatesChanged)");
expect(appSource).toContain("componentUpdates.refresh({ force: true })");
for (const source of [pluginCenterSource, driverStoreSource, settingsDialogSource, connectionDialogSource, connectionStoreSource]) {
expect(source).toContain("notifyComponentUpdatesChanged()");
}
});
it("formats structured backend errors for local and URL package installs", () => {
const localInstall = pluginCenterSource.slice(pluginCenterSource.indexOf("async function installPlugin("), pluginCenterSource.indexOf("function isHttpPackageUrl("));
const urlInstall = pluginCenterSource.slice(pluginCenterSource.indexOf("async function installPluginFromUrl("), pluginCenterSource.indexOf("const urlProgressPercent"));
for (const installSource of [localInstall, urlInstall]) {
expect(installSource).toContain("toast(translateBackendError(t, cause), 8000)");
expect(installSource).not.toContain("String(cause)");
}
});
it("creates and edits plugin connections in the unified connection dialog", () => {
expect(appDialogsSource).toContain(':edit-config="editConfig"');
expect(appDialogsSource).toContain(':plugin-provider="connectionPluginProvider"');
expect(appDialogsSource).not.toContain("pluginEditConfig");
expect(connectionDialogSource).toContain("pluginConnectionProviderOptionValue");
expect(connectionDialogSource).toContain("<PluginConnectionFields");
expect(connectionDialogSource).toContain("buildPluginConnectionConfig");
});
it("keeps marketplace security automatic and developer controls hidden", () => {
const template = pluginCenterSource.split("<template>")[1];
const settingsIndex = template.indexOf('value="settings"');
const developerOptionsIndex = template.indexOf("pluginPlatform.developerOptionsTitle");
const allowUnsignedIndex = template.indexOf("pluginPlatform.allowUnsignedDevelopmentPackage");
expect(template).toContain('value="marketplace"');
expect(template).toContain('value="installed"');
expect(template).toContain('value="settings"');
expect(settingsIndex).toBeLessThan(developerOptionsIndex);
expect(developerOptionsIndex).toBeLessThan(allowUnsignedIndex);
expect(template).toContain("pluginPlatform.signedPackagesVerifiedAutomatically");
expect(template).toContain('<template v-if="showCustomRepositoryTrustSettings">');
expect(pluginCenterSource).toContain("customRepositories.value.length > 0 || trustedKeys.value.length > 0");
expect(template).not.toContain("pluginPlatform.advancedSecurityTitle");
expect(pluginCenterSource).toContain("fetchPluginMarketplaceCatalogs");
expect(template).not.toContain("pluginPlatform.centerTitle");
expect(template).not.toContain("marketplaceTarget");
expect(template).not.toContain("<select");
expect(template).toContain("<SelectTrigger");
expect(template).not.toContain("max-w-md grid-cols-3");
expect(template).not.toContain("marketplaceCategory");
});
});
@@ -1,239 +0,0 @@
import { readFileSync } from "node:fs";
import { parse } from "vue/compiler-sfc";
import ts from "typescript";
import { describe, expect, it } from "vitest";
const browserSource = readFileSync(new URL("../../../components/redis/RedisKeyBrowser.vue", import.meta.url), "utf8");
const viewerSource = readFileSync(new URL("../../../components/redis/RedisValueViewer.vue", import.meta.url), "utf8");
const localeSources = {
az: readFileSync(new URL("../../../i18n/locales/az.ts", import.meta.url), "utf8"),
en: readFileSync(new URL("../../../i18n/locales/en.ts", import.meta.url), "utf8"),
es: readFileSync(new URL("../../../i18n/locales/es.ts", import.meta.url), "utf8"),
it: readFileSync(new URL("../../../i18n/locales/it.ts", import.meta.url), "utf8"),
ja: readFileSync(new URL("../../../i18n/locales/ja.ts", import.meta.url), "utf8"),
ko: readFileSync(new URL("../../../i18n/locales/ko.ts", import.meta.url), "utf8"),
"pt-BR": readFileSync(new URL("../../../i18n/locales/pt-BR.ts", import.meta.url), "utf8"),
tr: readFileSync(new URL("../../../i18n/locales/tr.ts", import.meta.url), "utf8"),
"zh-CN": readFileSync(new URL("../../../i18n/locales/zh-CN.ts", import.meta.url), "utf8"),
"zh-TW": readFileSync(new URL("../../../i18n/locales/zh-TW.ts", import.meta.url), "utf8"),
};
function findFunction(source: string, name: string): ts.FunctionDeclaration {
const parsed = parse(source, { filename: `${name}.vue` });
expect(parsed.errors).toEqual([]);
const script = parsed.descriptor.scriptSetup;
expect(script).toBeDefined();
const program = ts.createSourceFile(`${name}.ts`, script!.content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
const declaration = program.statements.find((statement): statement is ts.FunctionDeclaration => ts.isFunctionDeclaration(statement) && statement.name?.text === name);
expect(declaration).toBeDefined();
return declaration!;
}
function callsIn(node: ts.Node): ts.CallExpression[] {
const calls: ts.CallExpression[] = [];
const visit = (child: ts.Node) => {
if (ts.isCallExpression(child)) calls.push(child);
ts.forEachChild(child, visit);
};
visit(node);
return calls;
}
function callName(call: ts.CallExpression): string | undefined {
if (ts.isIdentifier(call.expression)) return call.expression.text;
if (ts.isPropertyAccessExpression(call.expression)) return `${call.expression.expression.getText()}.${call.expression.name.text}`;
return undefined;
}
describe("Redis expiry mode wiring", () => {
it("writes every create type before applying exactly one shared expiration policy", () => {
const create = findFunction(browserSource, "createRedisKey");
const calls = callsIn(create);
const expectedWriterArgumentCounts: Record<string, number> = {
"api.redisSetString": 4,
"api.redisJsonSet": 4,
"api.redisHashSet": 5,
"api.redisListPush": 4,
"api.redisSetAdd": 4,
"api.redisZadd": 5,
"api.redisStreamAdd": 5,
};
for (const [name, argumentCount] of Object.entries(expectedWriterArgumentCounts)) {
const writerCalls = calls.filter((call) => callName(call) === name);
expect(writerCalls.length, `${name} should be used by the create flow`).toBeGreaterThan(0);
expect(
writerCalls.every((call) => call.arguments.length === argumentCount),
`${name} must not receive a per-write TTL`,
).toBe(true);
}
expect(calls.map(callName)).toContain("applyRedisExpiryPolicy");
expect(create.getText()).toContain("if (creatingKey.value) return;");
expect(calls.map(callName)).not.toContain("api.redisSetTtl");
expect(calls.map(callName)).not.toContain("api.redisSetExpireAt");
expect(create.getText().lastIndexOf("applyRedisExpiryPolicy")).toBeGreaterThan(create.getText().lastIndexOf("api.redisStreamAdd"));
expect(findFunction(browserSource, "syncWrittenKey").getText()).toContain('if (created.redis_type === "none")');
expect(create.getText()).toContain('toast(t("redis.keyExpiredBeforeDisplay"), 3000)');
expect(create.getText()).toContain("if (wroteValue && writtenKeyRaw)");
expect(findFunction(browserSource, "reflectWrittenKey").getText()).toContain("removeKnownKey(keyRaw)");
});
it("keeps only unwritten structured entries after a later writer fails", () => {
const create = findFunction(browserSource, "createRedisKey").getText();
const partialRecoveryStart = create.indexOf("if (writingStructuredEntries)");
const genericRecoveryStart = create.lastIndexOf("if (wroteValue && writtenKeyRaw)");
const partialRecovery = create.slice(partialRecoveryStart, genericRecoveryStart);
expect(create).toContain("let writingStructuredEntries = false;");
expect(create).toContain("const pendingEntries = createKeyEntries.value.slice();");
expect(create.match(/for \(const entry of pendingEntries\)/g)).toHaveLength(4);
expect(create.match(/removeWrittenCreateKeyEntry\(entry\.id\)/g)).toHaveLength(4);
expect(create).toContain("createKeyPartiallyWritten.value = true;");
expect(partialRecovery).toContain("await reflectWrittenKey(writtenKeyRaw);");
expect(partialRecovery).toContain('t("redis.createKeyPartialWrite")');
expect(partialRecovery).not.toContain("showCreateKeyDialog.value = false;");
expect(browserSource).toContain(':disabled="creatingKey || createKeyPartiallyWritten"');
expect(findFunction(browserSource, "onCreateKeyDialogOpenChange").getText()).toContain("if (!open && creatingKey.value) return;");
expect(findFunction(browserSource, "onCreateKeyTypeChange").getText()).toContain("if (creatingKey.value || createKeyPartiallyWritten.value) return;");
});
it("defaults TTL editing by server state, supports absolute prefill, and keeps teleported controls inside the editor", () => {
const start = findFunction(viewerSource, "startEditTtl").getText();
const save = findFunction(viewerSource, "saveTtl").getText();
const currentTtl = findFunction(viewerSource, "currentEditableTtl").getText();
expect(start).toContain("redisExpiryModeForTtl(ttl)");
expect(currentTtl).toContain("computeTtlForExpiryEdit(countdownTtl.value, data.value.ttl)");
expect(viewerSource).toContain("unixSecondsToCalendarDateTime(Math.ceil(Date.now() / 1_000) + ttl)");
expect(save).toContain("validateRedisExpiry");
expect(save).toContain("applyRedisExpiryPolicy");
expect(save).toContain("toast(errorMessage(error), 3000)");
expect(viewerSource).toContain('"[data-date-time-picker-content]"');
expect(viewerSource).toContain('"[data-redis-expiry-mode-content]"');
expect(viewerSource).toContain('v-model="ttlExpireAt" compact');
expect(viewerSource.match(/as="button"/g) ?? []).toHaveLength(2);
expect(viewerSource).toContain(":aria-label=\"t('redis.expiry')\"");
expect(viewerSource).toContain(":aria-label=\"t('grid.save')\"");
});
it("moves keyboard focus to the active TTL editor control", () => {
const start = findFunction(viewerSource, "startEditTtl").getText();
const focus = findFunction(viewerSource, "focusTtlExpiryControl").getText();
expect(start).toContain("focusTtlExpiryControl()");
expect(focus).toContain('mode === "ttl"');
expect(focus).toContain("ttlInputEl.value?.$el?.focus()");
expect(focus).toContain("[data-slot='select-trigger']");
expect(focus).toContain("[data-date-time-picker-trigger]");
expect(viewerSource).toContain("if (editingTtl.value && mode !== previousMode) focusTtlExpiryControl(mode);");
});
it("serializes expiry saves and preserves unrelated value drafts", () => {
const save = findFunction(viewerSource, "saveTtl").getText();
const load = findFunction(viewerSource, "load").getText();
expect(save).toContain("if (savingTtl.value) return;");
expect(save).toContain("savingTtl.value = true;");
expect(save).toContain("await refreshTtlState(error);");
expect(save).toContain("const refreshError = await refreshTtlState();");
expect(save).toContain("savingTtl.value = false;");
expect(load).toContain("const preservedValue = { ...currentValue, ttl: loadedValue.ttl };");
expect(viewerSource).toContain(':disabled="savingTtl"');
});
it("keeps expiry controls compact and inline in the value header", () => {
expect(viewerSource).toContain("flex min-w-0 max-w-full flex-wrap items-center gap-1");
expect(viewerSource).toContain('SelectTrigger size="sm"');
expect(viewerSource).toContain("max-w-[min(100%,14rem)]");
expect(viewerSource).toContain('v-model="ttlExpireAt" compact');
expect(viewerSource).not.toContain("full-width");
expect(viewerSource).not.toContain("basis-full");
expect(viewerSource).not.toContain("redis-expiry-mode-trigger");
expect(viewerSource).not.toContain('class="h-6 w-30 text-xs"');
});
it("uses the positive-seconds TTL placeholder in both expiration editors", () => {
const obsoletePlaceholders = {
en: "empty = no expiry",
es: "vacío = sin expiración",
it: "vuoto = senza scadenza",
ja: "空 = 期限なし",
"pt-BR": "vazio = sem expiração",
"zh-CN": "留空表示永不过期",
"zh-TW": "留空表示永不過期",
};
for (const [locale, source] of Object.entries(localeSources)) {
const ttlPlaceholder = source.match(/createKeyTtlPlaceholder: "([^"]+)"/)?.[1];
expect(ttlPlaceholder, locale).toBeDefined();
expect(source, locale).toContain("createKeyPartialWrite:");
expect(ttlPlaceholder, locale).not.toBe(obsoletePlaceholders[locale as keyof typeof obsoletePlaceholders]);
}
expect(browserSource).toContain("t('redis.createKeyTtlPlaceholder')");
expect(viewerSource).toContain("t('redis.createKeyTtlPlaceholder')");
});
it("removes a key that expires while its detail view is refreshing", () => {
const load = findFunction(viewerSource, "load").getText();
const deleted = findFunction(browserSource, "onKeyDeleted").getText();
const loaded = findFunction(browserSource, "onKeyLoaded").getText();
expect(load).toContain('if (loadedValue.redis_type === "none")');
expect(load).toContain('emit("deleted", props.keyRaw)');
expect(deleted).toContain("removeKnownKey(keyRaw)");
expect(loaded).toContain('if (value.redis_type === "none")');
});
it("reuses the shared expiry validator and the batch transport for one bulk policy", () => {
const open = findFunction(browserSource, "openBatchExpiryDialog").getText();
const save = findFunction(browserSource, "saveBatchExpiry").getText();
const calls = callsIn(findFunction(browserSource, "saveBatchExpiry"));
expect(open).toContain("if (checkedKeys.value.size === 0 || selectionBusy.value) return;");
expect(open).toContain("batchExpiryKeyRaws.value = [...checkedKeys.value];");
expect(save).toContain("validateRedisExpiry");
expect(save).toContain("expiryValidationMessage(validation.reason)");
expect(calls.map(callName)).toContain("applyRedisBatchExpiryPolicy");
expect(calls.map(callName)).toContain("applyBatchExpiryMetadata");
// The single-key API must never be looped over a multi-selection.
expect(calls.map(callName)).not.toContain("api.redisSetTtl");
expect(calls.map(callName)).not.toContain("api.redisSetExpireAt");
expect(calls.map(callName)).not.toContain("applyRedisExpiryPolicy");
expect(save).toContain("if (savingBatchExpiry.value || batchExpiryKeyRaws.value.length === 0) return;");
expect(browserSource).toContain("setKeysTtl: api.redisSetKeysTtl");
expect(browserSource).toContain("setKeysExpireAt: api.redisSetKeysExpireAt");
// A batch mutation owns the selection like a batch delete does.
expect(browserSource).toContain("const mutatingKeys = computed(() => deletingKeys.value || savingBatchExpiry.value);");
expect(findFunction(browserSource, "retainCheckedKeys").getText()).toContain("loadedKeyRaws.has(keyRaw)");
});
it("updates the loaded TTL badge instead of rescanning every applied key", () => {
const applyMetadata = findFunction(browserSource, "applyBatchExpiryMetadata").getText();
const applyTtl = findFunction(browserSource, "applyKeyTtlMetadata").getText();
expect(applyTtl).toContain("updateRedisKeyInfoMetadataByRaw(flatKeyByRaw, nextKeyInfo)");
expect(applyTtl).toContain("recordKeyTtlObservedAt(nextKeyInfo)");
expect(applyTtl).toContain("updateRedisKeyTreeLeafMetadata(treeIndex, nextKeyInfo)");
expect(applyMetadata).toContain('policy.mode === "ttl" ? policy.ttl : -1');
// EXPIREAT with a past timestamp deletes the key, so the row must not keep a stale TTL.
expect(applyMetadata).toContain("onKeyDeleted(keyRaw)");
// One reactive refresh per batch, not one per selected key.
expect(applyMetadata.match(/noExpiryProjectionEpoch\.value\+\+/g) ?? []).toHaveLength(1);
expect(applyMetadata.match(/keyMetadataEpoch\.value\+\+/g) ?? []).toHaveLength(1);
expect(applyMetadata.match(/syncListTtlTimer\(\)/g) ?? []).toHaveLength(1);
});
it("ships the batch expiration copy in every supported locale", () => {
for (const [locale, source] of Object.entries(localeSources)) {
for (const key of ["batchExpiry:", "batchExpiryTitle:", "batchExpirySelected:", "batchExpiryApply:", "batchExpirySuccess:", "batchExpiryPartial:"]) {
expect(source, `${locale} is missing redis.${key}`).toContain(` ${key}`);
}
}
// The dialog must resolve its copy through i18n instead of hard-coded text.
expect(browserSource).toContain('t("redis.batchExpiryTitle")');
expect(browserSource).toContain('t("redis.batchExpirySelected", { count: batchExpiryKeyRaws.length })');
expect(browserSource).toContain('t("redis.batchExpiryPartial", { success: summary.applied, failed: failed.size })');
});
});
@@ -1,13 +1,7 @@
import { readFileSync } from "node:fs";
import { parse } from "vue/compiler-sfc";
import ts from "typescript";
import { describe, expect, it } from "vitest";
import { formatRedisMemberDetail, normalizeRedisJsonDraft } from "@/lib/redis/redisValuePresentation";
const viewerSource = readFileSync(new URL("../../../components/redis/RedisValueViewer.vue", import.meta.url), "utf8");
const parsedViewer = parse(viewerSource, { filename: "RedisValueViewer.vue" });
/** Owner-review fixture: compact save must not drop the second "role" member. */
const DUPLICATE_MEMBER_COMPACT = '{"role":"reader","role":"writer"}';
const DUPLICATE_MEMBER_PRETTY = `{
@@ -15,175 +9,7 @@ const DUPLICATE_MEMBER_PRETTY = `{
"role": "writer"
}`;
type TemplateElement = {
type: number;
tag: string;
children?: TemplateNode[];
props: Array<{
type: number;
name?: string;
arg?: { content?: string };
exp?: { content?: string };
value?: { content?: string };
}>;
};
type TemplateNode = {
type: number;
children?: TemplateNode[];
};
function directiveExpression(element: TemplateElement, name: string, arg?: string): string | undefined {
return element.props.find((prop) => prop.type === 7 && prop.name === name && (arg == null || prop.arg?.content === arg))?.exp?.content;
}
function staticAttribute(element: TemplateElement, name: string): string | undefined {
return element.props.find((prop) => prop.type === 6 && prop.name === name)?.value?.content;
}
function templateElements(node: TemplateNode): TemplateElement[] {
const children = (node.children ?? []).flatMap(templateElements);
return node.type === 1 ? [node as TemplateElement, ...children] : children;
}
function findTemplateElement(predicate: (element: TemplateElement) => boolean): TemplateElement {
const template = parsedViewer.descriptor.template;
expect(parsedViewer.errors).toEqual([]);
expect(template).toBeDefined();
const element = templateElements(template!.ast as unknown as TemplateElement).find(predicate);
expect(element).toBeDefined();
return element!;
}
function findFunction(name: string): ts.FunctionDeclaration {
const script = parsedViewer.descriptor.scriptSetup;
expect(script).toBeDefined();
const source = ts.createSourceFile("RedisValueViewer.vue.ts", script!.content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
const declaration = source.statements.find((statement): statement is ts.FunctionDeclaration => ts.isFunctionDeclaration(statement) && statement.name?.text === name);
expect(declaration).toBeDefined();
return declaration!;
}
function findVariableInitializer(name: string): ts.Expression {
const script = parsedViewer.descriptor.scriptSetup;
expect(script).toBeDefined();
const source = ts.createSourceFile("RedisValueViewer.vue.ts", script!.content, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
for (const statement of source.statements) {
if (!ts.isVariableStatement(statement)) continue;
const declaration = statement.declarationList.declarations.find((candidate) => ts.isIdentifier(candidate.name) && candidate.name.text === name);
if (declaration?.initializer) return declaration.initializer;
}
throw new Error(`Expected ${name} to have an initializer`);
}
function callsIn(node: ts.Node): ts.CallExpression[] {
const calls: ts.CallExpression[] = [];
const visit = (child: ts.Node) => {
if (ts.isCallExpression(child)) calls.push(child);
ts.forEachChild(child, visit);
};
visit(node);
return calls;
}
function assignmentsIn(node: ts.Node): ts.BinaryExpression[] {
const assignments: ts.BinaryExpression[] = [];
const visit = (child: ts.Node) => {
if (ts.isBinaryExpression(child) && child.operatorToken.kind === ts.SyntaxKind.EqualsToken) assignments.push(child);
ts.forEachChild(child, visit);
};
visit(node);
return assignments;
}
function calledName(call: ts.CallExpression): string | undefined {
if (ts.isIdentifier(call.expression)) return call.expression.text;
if (ts.isPropertyAccessExpression(call.expression)) return `${call.expression.expression.getText()}.${call.expression.name.text}`;
return undefined;
}
describe("native RedisJSON editor", () => {
it("opens full member values in a centered dialog instead of an app-height side sheet", () => {
const memberDialog = findTemplateElement((element) => element.tag === "Dialog" && directiveExpression(element, "bind", "open") === "showMemberDetail");
const memberDetailTags = templateElements(memberDialog).map((element) => element.tag);
const memberDetailFooter = templateElements(memberDialog).find((element) => element.tag === "DialogFooter");
expect(memberDetailTags).toContain("DialogContent");
expect(memberDetailTags).toContain("DialogHeader");
expect(memberDetailTags).toContain("DialogFooter");
expect(memberDetailTags).not.toContain("SheetContent");
expect(staticAttribute(memberDetailFooter!, "class")).toContain("mx-0 mb-0");
expect(viewerSource).not.toContain("memberDetailSheetWidth");
expect(viewerSource).not.toContain("startResizeMemberSheet");
});
it("uses the same foldable source editor as JSON strings and hash fields", () => {
const stringEditor = findTemplateElement((element) => element.tag === "RedisJsonEditor" && directiveExpression(element, "if") === "stringValueView === 'json' && stringValueDetail.json && stringValueCodec === 'none'");
const nativeJsonBranch = findTemplateElement((element) => directiveExpression(element, "else-if") === "redisKind === 'json'");
const hashEditor = findTemplateElement((element) => element.tag === "RedisJsonEditor" && directiveExpression(element, "if") === "isEditingHashJson");
const nativeJsonEditors = templateElements(nativeJsonBranch).filter((element) => element.tag === "RedisJsonEditor");
expect(stringEditor.tag).toBe("RedisJsonEditor");
expect(hashEditor.tag).toBe("RedisJsonEditor");
expect(nativeJsonEditors).toHaveLength(1);
const [nativeJsonEditor] = nativeJsonEditors;
expect(directiveExpression(nativeJsonEditor, "model")).toBe("editValue");
expect(directiveExpression(nativeJsonEditor, "bind", "save-disabled")).toBe("savingJson || !redisJsonValueChanged");
expect(directiveExpression(nativeJsonEditor, "bind", "read-only")).toBe("savingJson");
expect(directiveExpression(nativeJsonEditor, "bind", "word-wrap")).toBe("redisJsonWordWrap");
expect(directiveExpression(nativeJsonEditor, "on", "save")).toBe("saveJson");
});
it("does not leave a native RedisJSON tree or textarea rendering branch behind", () => {
const nativeJsonBranch = findTemplateElement((element) => directiveExpression(element, "else-if") === "redisKind === 'json'");
const nativeJsonTags = templateElements(nativeJsonBranch).map((element) => element.tag);
expect(nativeJsonTags).not.toContain("JsonTree");
expect(nativeJsonTags).not.toContain("textarea");
});
it("validates and compacts native RedisJSON before retaining JSON.SET save semantics", () => {
const saveJson = findFunction("saveJson");
const calls = callsIn(saveJson);
const normalizeCall = calls.find((call) => calledName(call) === "normalizeRedisJsonDraft");
const redisJsonSetCall = calls.find((call) => calledName(call) === "api.redisJsonSet");
expect(normalizeCall?.arguments.map((argument) => argument.getText())).toEqual(["jsonDraftForSave(redisJsonRawBaseline.value, editValue.value)"]);
expect(redisJsonSetCall?.arguments.map((argument) => argument.getText())).toEqual(["props.connectionId", "props.db", "props.keyRaw", "normalized.compactText"]);
});
it("routes string and hash JSON saves through the same source-preserving normalize helper", () => {
const saveString = findFunction("saveString");
const saveMemberEdit = findFunction("saveMemberEdit");
const saveStringText = saveString.getText();
const saveMemberText = saveMemberEdit.getText();
const saveStringCalls = callsIn(saveString).map(calledName);
const saveMemberCalls = callsIn(saveMemberEdit).map(calledName);
// String JSON draft (current tab or retained draft format) compact-writes via SET.
expect(saveStringText).toContain('stringValueView.value === "json" || stringDraftFormat.value === "json"');
expect(saveStringCalls).toContain("normalizeRedisJsonDraft");
expect(saveStringText).toContain("value = normalized.compactText");
expect(saveStringCalls).toContain("api.redisSetString");
expect(saveStringText).toMatch(/redisSetString\([\s\S]*\bvalue\b/);
// Hash JSON draft (editor open or retained after leaving JSON tab) compact-writes via the atomic field update.
expect(saveMemberText).toContain("savingHashJson");
expect(saveMemberText).toContain('memberDraftFormat.value === "json"');
expect(saveMemberCalls).toContain("normalizeRedisJsonDraft");
expect(saveMemberText).toContain("writeValue = normalized.compactText");
expect(saveMemberCalls).toContain("api.redisHashFieldUpdate");
expect(saveMemberText).toMatch(/redisHashFieldUpdate\([\s\S]*\bwriteValue\b/);
// Editor pretty baseline also uses the source-preserving formatter.
expect(findFunction("formatJsonText").getText()).toContain("formatJsonSource");
});
it("string JSON editor open+save keeps duplicate members end-to-end", () => {
// Open: string JSON view pretty baseline comes from formatRedisMemberDetail.
const opened = formatRedisMemberDetail(DUPLICATE_MEMBER_COMPACT, { allowJsonText: true });
@@ -192,11 +18,6 @@ describe("native RedisJSON editor", () => {
// Save: saveString always compact-writes through normalizeRedisJsonDraft.
const saved = normalizeRedisJsonDraft(opened.json!.formattedText);
expect(saved).toEqual({ ok: true, compactText: DUPLICATE_MEMBER_COMPACT });
// Wiring: that compact text is what redisSetString receives.
const saveString = findFunction("saveString");
expect(saveString.getText()).toContain("value = normalized.compactText");
expect(callsIn(saveString).map(calledName)).toEqual(expect.arrayContaining(["normalizeRedisJsonDraft", "api.redisSetString"]));
});
it("hash JSON editor open+save keeps duplicate members end-to-end", () => {
@@ -207,145 +28,5 @@ describe("native RedisJSON editor", () => {
// Save: saveMemberEdit compact-writes hash JSON drafts through the same helper.
const saved = normalizeRedisJsonDraft(opened.json!.formattedText);
expect(saved).toEqual({ ok: true, compactText: DUPLICATE_MEMBER_COMPACT });
// Wiring: hash path only normalizes when savingHashJson, then atomically updates the field with writeValue.
const saveMemberEdit = findFunction("saveMemberEdit");
const text = saveMemberEdit.getText();
expect(text).toContain("if (savingHashJson)");
expect(text).toContain("writeValue = normalized.compactText");
expect(callsIn(saveMemberEdit).map(calledName)).toEqual(expect.arrayContaining(["normalizeRedisJsonDraft", "api.redisHashFieldUpdate"]));
});
it("keeps the native editor and export paths on the RedisJSON value-text contract", () => {
const load = findFunction("load");
const discard = findFunction("discardRedisJsonEdit");
const exportStatements = findFunction("generateInsertStatements");
const valueTextCalls = (node: ts.Node) => callsIn(node).filter((call) => calledName(call) === "redisJsonValueText");
expect(valueTextCalls(load).map((call) => call.arguments.map((argument) => argument.getText()))).toContainEqual(["loadedValue.data"]);
expect(valueTextCalls(exportStatements).map((call) => call.arguments.map((argument) => argument.getText()))).toContainEqual(["data.value.data"]);
expect(callsIn(load).map(calledName)).toContain("jsonDraftPairForEditor");
expect(callsIn(load).map(calledName)).toContain("redisJsonValueText");
expect(assignmentsIn(load).some((assignment) => assignment.left.getText() === "redisJsonRawBaseline.value" && assignment.right.getText() === "pair.rawBaseline")).toBe(true);
expect(assignmentsIn(load).some((assignment) => assignment.left.getText() === "redisJsonDraftBaseline.value" && assignment.right.getText() === "pair.displayBaseline")).toBe(true);
expect(assignmentsIn(discard).some((assignment) => assignment.left.getText() === "editValue.value" && assignment.right.getText() === "redisJsonDraftBaseline.value")).toBe(true);
for (const node of [load, discard, exportStatements]) {
expect(callsIn(node).map(calledName)).not.toContain("JSON.stringify");
}
expect(viewerSource).not.toContain("isRedisJsonDraftDirty");
});
it("keeps retained drafts out of background refresh and exposes word wrap for every JSON editor", () => {
const refreshAutoValue = findFunction("refreshAutoValue");
const collectionSearch = findFunction("onCollectionSearch");
const viewMember = findFunction("viewMember");
const setMemberValueFormat = findFunction("setMemberValueFormat");
const selectMember = findFunction("selectMember");
const startEditMember = findFunction("startEditMember");
const saveMemberEdit = findFunction("saveMemberEdit");
const memberValueChanged = findVariableInitializer("memberValueChanged");
const memberFieldChanged = findVariableInitializer("memberFieldChanged");
const unsavedDraft = findVariableInitializer("hasUnsavedRedisDraft");
const textFormat = findFunction("isTextRedisFormat");
const labels = templateElements(parsedViewer.descriptor.template!.ast as unknown as TemplateElement);
const stringTextarea = findTemplateElement((element) => element.tag === "textarea" && directiveExpression(element, "model") === "editValue");
const memberTextarea = findTemplateElement((element) => element.tag === "textarea" && directiveExpression(element, "model") === "memberEditValue");
const refreshButton = findTemplateElement((element) => element.tag === "Button" && element.props.some((prop) => prop.type === 6 && prop.name === "data-redis-value-refresh"));
expect(refreshAutoValue.getText().match(/hasUnsavedRedisDraft\.value/g)).toHaveLength(2);
expect(collectionSearch.getText()).toContain("if (!hasRetainedMemberDraft.value) clearSelectedMember();");
expect(viewMember.getText()).toContain("hasRetainedMemberDraft.value");
// Clean JSON → other format must clear memberDraftFormat so rawText is not compared to the pretty baseline.
expect(setMemberValueFormat.getText()).toContain("memberDraftFormat.value = null");
expect(setMemberValueFormat.getText()).toContain('memberDraftFormat.value = "utf8"');
expect(unsavedDraft.getText()).toContain("hasRetainedStringDraft.value");
expect(unsavedDraft.getText()).toContain("hasRetainedMemberDraft.value");
expect(unsavedDraft.getText()).toContain("memberFieldChanged.value");
expect(memberFieldChanged.getText()).toContain("memberFieldDraftBaseline.value");
expect(memberValueChanged.getText()).toContain("memberFieldChanged.value");
expect(selectMember.getText()).toContain("memberFieldDraftBaseline.value");
expect(startEditMember.getText()).toContain("!memberFieldChanged.value");
expect(saveMemberEdit.getText()).toContain("memberFieldEditValue.value");
expect(saveMemberEdit.getText()).not.toContain("memberFieldEditValue.value.trim()");
expect(viewerSource).toContain(':disabled="savingMember || !memberValueChanged"');
expect(textFormat.getText()).toContain('format === "json"');
expect(labels.some((element) => element.tag === "label" && directiveExpression(element, "if") === "isTextRedisFormat(stringValueView) || activeStructuredStringDetail || isDecompressCodec(stringValueCodec)")).toBe(true);
expect(labels.some((element) => element.tag === "label" && directiveExpression(element, "if") === "isTextRedisFormat(memberValueView) || activeStructuredMemberDetail || isDecompressCodec(memberValueCodec)")).toBe(true);
expect(directiveExpression(stringTextarea, "bind", "readonly")).toBe("!canEditCurrentStringFormat || savingString");
expect(directiveExpression(memberTextarea, "bind", "readonly")).toBe("savingMember");
expect(directiveExpression(refreshButton, "bind", "disabled")).toBe("loading || refreshingValue || hasUnsavedRedisDraft");
});
it("passes the loaded ZSet score into both update entry points", () => {
const inlineSave = findFunction("saveZsetInlineEdit").getText();
const detailSave = findFunction("saveMemberEdit").getText();
expect(inlineSave).toContain("originalMember, item.score, zsetInlineMember.value, scoreText");
expect(detailSave).toContain("context.member, context.score, writeValue, context.score");
});
});
describe("Redis JSON unicode display mode", () => {
it("exposes a raw/decoded toggle on every JSON editor surface", () => {
// String JSON, native RedisJSON, and member JSON edit surfaces each render
// the same two-segment "原始 / 解码" control wired to setRedisJsonUnicodeMode.
expect(viewerSource.match(/setRedisJsonUnicodeMode\('raw'\)/g)).toHaveLength(3);
expect(viewerSource.match(/setRedisJsonUnicodeMode\('decoded'\)/g)).toHaveLength(3);
expect(viewerSource.match(/t\("redis\.jsonViewRaw"\)/g)).toHaveLength(3);
expect(viewerSource.match(/t\("redis\.jsonViewDecoded"\)/g)).toHaveLength(3);
});
it("defaults to decoded and persists the choice under its own storage key", () => {
expect(findFunction("readRedisJsonUnicodeMode").getText()).toContain('=== "raw" ? "raw" : "decoded"');
expect(findVariableInitializer("redisJsonUnicodeMode").getText()).toBe("ref(readRedisJsonUnicodeMode())");
expect(viewerSource).toContain('const REDIS_JSON_UNICODE_MODE_STORAGE_KEY = "dbx-redis-json-unicode-mode"');
});
it("derives JSON editor baselines through the display-only unicode decode", () => {
expect(findFunction("formatJsonText").getText()).toContain("decodeJsonUnicodeEscapes(formatted)");
expect(findFunction("jsonDraftBaseline").getText()).toContain("decodeJsonUnicodeEscapes(formattedText)");
expect(findFunction("jsonDraftPairForEditor").getText()).toContain("jsonDraftBaseline(rawBaseline, redisJsonDecoded.value)");
expect(findFunction("setRedisJsonUnicodeMode").getText()).toContain("rememberRedisJsonUnicodeMode(mode)");
expect(findFunction("setRedisJsonUnicodeMode").getText()).toContain("stringJsonDraftBaseline.value = jsonDraftBaseline(stringJsonRawBaseline.value, decoded)");
expect(findFunction("setRedisJsonUnicodeMode").getText()).toContain("redisJsonDraftBaseline.value = jsonDraftBaseline(redisJsonRawBaseline.value, decoded)");
expect(findFunction("setRedisJsonUnicodeMode").getText()).toContain("memberJsonDraftBaseline.value = jsonDraftBaseline(memberJsonRawBaseline.value, decoded)");
});
it("converts the active draft across a Raw/Decoded toggle instead of resetting it", () => {
// Toggling must not drop unsaved edits: the draft goes through the mode
// transform (decode when entering decoded, map back to raw when leaving it).
expect(findFunction("convertJsonDraftAcrossMode").getText()).toContain("decoded ? decodeJsonUnicodeEscapes(draft) : mapDisplayToRaw(rawBaseline, draft)");
const setMode = findFunction("setRedisJsonUnicodeMode").getText();
expect(setMode).toContain("editValue.value = convertJsonDraftAcrossMode(editValue.value, stringJsonRawBaseline.value, decoded)");
expect(setMode).toContain("editValue.value = convertJsonDraftAcrossMode(editValue.value, redisJsonRawBaseline.value, decoded)");
expect(setMode).toContain("memberEditValue.value = convertJsonDraftAcrossMode(memberEditValue.value, memberJsonRawBaseline.value, decoded)");
// The reset-to-baseline assignments must not reappear; they drop unsaved edits.
expect(setMode).not.toContain("editValue.value = stringJsonDraftBaseline.value");
expect(setMode).not.toContain("editValue.value = redisJsonDraftBaseline.value");
expect(setMode).not.toContain("memberEditValue.value = memberJsonDraftBaseline.value");
});
it("routes every JSON editor save through the raw draft mapping so escapes are preserved", () => {
// Save writes the mapped canonical raw draft, never the decoded display text:
// opening {"name":"张"} in decoded mode and saving must store the escape.
const jsonDraftForSave = findFunction("jsonDraftForSave");
expect(jsonDraftForSave.getText()).toContain("mapDisplayToRaw(rawBaseline, displayValue)");
expect(jsonDraftForSave.getText()).toContain("redisJsonDecoded.value ? mapDisplayToRaw(rawBaseline, displayValue) : displayValue");
// String JSON draft, native RedisJSON, and hash member JSON draft all go
// through jsonDraftForSave before the source-preserving normalize/compact.
const saveString = findFunction("saveString").getText();
const saveJson = findFunction("saveJson").getText();
const saveMemberEdit = findFunction("saveMemberEdit").getText();
expect(saveString).toContain("normalizeRedisJsonDraft(jsonDraftForSave(stringJsonRawBaseline.value, value))");
expect(saveJson).toContain("normalizeRedisJsonDraft(jsonDraftForSave(redisJsonRawBaseline.value, editValue.value))");
expect(saveMemberEdit).toContain("normalizeRedisJsonDraft(jsonDraftForSave(memberJsonRawBaseline.value, writeValue))");
// Raw baselines (what saves write back to) are captured on load/select.
expect(findFunction("load").getText()).toContain('stringJsonRawBaseline.value = detail.json?.formattedText ?? ""');
expect(findFunction("load").getText()).toContain("const pair = jsonDraftPairForEditor(redisJsonValueText(loadedValue.data))");
expect(findFunction("selectMember").getText()).toContain('memberJsonRawBaseline.value = detail.json?.formattedText ?? ""');
});
});
@@ -1,4 +1,3 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { resolveSidebarFilterGuards } from "@/lib/sidebar/sidebarSearchTree";
@@ -18,18 +17,4 @@ describe("sidebar filter guards", () => {
isRootListPartial: rootPartial,
});
});
it("keeps descendant-local features separate from partial-root operations", () => {
const source = readFileSync(new URL("../../../components/sidebar/ConnectionTree.vue", import.meta.url), "utf8");
expect(source).toContain("sidebarTableSearchEnabled && !isTreeSearchFiltering.value");
expect(source).toContain("!useVirtualTree.value || isTreeSearchFiltering.value");
expect(source.match(/if \(isRootListPartial\.value\)/g)).toHaveLength(2);
// Alphabetical sort only suppresses before/after position reordering (the manual
// order it would act on is invisible while sorted); moving a connection into a
// different group stays available so drag stays usable while sorted (#6669).
expect(source.match(/:reorder-disabled="isRootListPartial"/g)).toHaveLength(2);
expect(source.match(/:move-to-group-only="isConnectionListAlphabeticallySorted"/g)).toHaveLength(2);
expect(source).not.toContain("isFiltering");
});
});
@@ -1,29 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const contentAreaSource = readFileSync(new URL("../../../components/layout/ContentArea.vue", import.meta.url), "utf8");
const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
const queryEditorPropsSource = readFileSync(new URL("../../../components/editor/queryEditorTypes.ts", import.meta.url), "utf8");
const completionSource = readFileSync(new URL("../../../components/editor/useQueryEditorCompletion.ts", import.meta.url), "utf8");
const metadataSource = readFileSync(new URL("../../../components/editor/useQueryEditorCompletionMetadata.ts", import.meta.url), "utf8");
const sidebarRuntimeSource = readFileSync(new URL("../../../components/sidebar/SidebarTreeRuntimeHost.vue", import.meta.url), "utf8");
const openTabsPersistenceSource = readFileSync(new URL("../../app/openTabsPersistence.ts", import.meta.url), "utf8");
describe("Doris external catalog completion wiring", () => {
it("preserves the selected catalog from the sidebar query action into QueryEditor", () => {
expect(sidebarRuntimeSource).toContain('queryStore.createTab(node.connectionId, node.database, undefined, "query", node.schema, undefined, node.catalog)');
expect(contentAreaSource).toContain(':catalog="activeTab.catalog"');
expect(queryEditorSource).toContain("defineProps<QueryEditorProps>()");
expect(queryEditorPropsSource).toContain("catalog?: string;");
expect(openTabsPersistenceSource).toContain("catalog: tab.catalog");
});
it("includes catalog scope in table and column completion requests", () => {
expect(completionSource).toMatch(/lookupLocalCompletionTables\([\s\S]*?props\.catalog/);
expect(completionSource).toMatch(/listCompletionTables\([\s\S]*?props\.catalog/);
expect(metadataSource).toMatch(/listCompletionColumns\([\s\S]*?catalog\)/);
expect(queryEditorSource).toMatch(/watch\(\s*\(\) => props\.catalog,[\s\S]*?refreshCompletionCache\(\)/);
expect(completionSource).toMatch(/function shouldLoadCompletionObjects[\s\S]*?if \(props\.catalog\) return false/);
expect(completionSource).toMatch(/if \(!props\.catalog && props\.databaseType !== "oracle"[\s\S]*?listCompletionObjects/);
});
});
@@ -1,10 +1,6 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { usesOracleSessionCompletionColumns } from "@/lib/sql/oracleCompletionSession";
const queryEditorSource = readFileSync(new URL("../../../components/editor/QueryEditor.vue", import.meta.url), "utf8");
const contentAreaSource = readFileSync(new URL("../../../components/layout/ContentArea.vue", import.meta.url), "utf8");
describe("Oracle session-scoped completion", () => {
it("uses the tab session only for unqualified references without a selected schema", () => {
expect(usesOracleSessionCompletionColumns({ databaseType: "oracle", clientSessionId: "tab-a" })).toBe(true);
@@ -16,10 +12,4 @@ describe("Oracle session-scoped completion", () => {
expect(usesOracleSessionCompletionColumns({ databaseType: "postgres", clientSessionId: "tab-a" })).toBe(false);
expect(usesOracleSessionCompletionColumns({ databaseType: "oracle" })).toBe(false);
});
it("passes tab context into QueryEditor and clears local caches when the tab or context changes", () => {
expect(contentAreaSource).toContain(':client-session-id="activeTab.id"');
expect(contentAreaSource).toContain(':completion-context-version="activeTab.completionContextVersion"');
expect(queryEditorSource).toMatch(/watch\(\s*\[\(\) => props\.clientSessionId, \(\) => props\.completionContextVersion\][\s\S]*?refreshCompletionCache\(\)/);
});
});
@@ -1,16 +1,8 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { canFormatSqlForDatabaseType, formatSqlForDisplay, formatSqlForEditing, formatSqlText, MAX_SQL_FORMAT_CHARS, sqlFormatDialectForDbType, UnsupportedStructuredInputError } from "@/lib/sql/sqlFormatter";
import { extractSqlParameters } from "@/lib/sql/sqlParameters";
const sqlFormatterSource = readFileSync(new URL("../../sql/sqlFormatter.ts", import.meta.url), "utf8");
describe("sqlFormatter", () => {
it("does not use lookbehind regular expressions in the startup path", () => {
expect(sqlFormatterSource).not.toContain("(?<!");
expect(sqlFormatterSource).not.toContain("(?<=");
});
it("disables SQL formatting for Redis and VictoriaMetrics queries", () => {
expect(canFormatSqlForDatabaseType("redis")).toBe(false);
expect(canFormatSqlForDatabaseType("victoriametrics")).toBe(false);
@@ -1,59 +0,0 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
const contentAreaSource = readFileSync(new URL("../../../components/layout/ContentArea.vue", import.meta.url), "utf8");
const connectionTreeSource = readFileSync(new URL("../../../components/sidebar/ConnectionTree.vue", import.meta.url), "utf8");
const ddlViewDialogSource = readFileSync(new URL("../../../components/objects/DdlViewDialog.vue", import.meta.url), "utf8");
const objectBrowserSource = readFileSync(new URL("../../../components/objects/ObjectBrowser.vue", import.meta.url), "utf8");
const fetchTableDdlSource = objectBrowserSource.match(/async function fetchTableDdl(?:\([^)]*\))?[\s\S]*?(?=\nasync function fetchTableColumns\()/)?.[0] ?? "";
const exportStructureSource = objectBrowserSource.match(/async function exportStructure\([\s\S]*?(?=\nasync function exportDataLegacy\()/)?.[0] ?? "";
function openingTag(source: string, componentName: string): string {
return source.match(new RegExp(`<${componentName}\\b[\\s\\S]*?>`))?.[0] ?? "";
}
describe("ContentArea external catalog wiring", () => {
it("passes the object browser catalog to ObjectBrowser", () => {
expect(openingTag(contentAreaSource, "ObjectBrowser")).toContain(':catalog="activeTab.objectBrowser?.catalog"');
});
it("does not attach object browser state to DataGrid", () => {
expect(openingTag(contentAreaSource, "DataGrid")).not.toContain("activeTab.objectBrowser?.catalog");
});
it("passes the sidebar catalog to the DDL dialog", () => {
expect(openingTag(connectionTreeSource, "SidebarDdlViewDialog")).toContain(':catalog="sidebarDdlTarget.catalog"');
});
it("forwards the DDL dialog catalog to the persistent DDL loader", () => {
expect(ddlViewDialogSource).toMatch(/loadObjectDdl\([\s\S]*?objectType: props\.objectType,[\s\S]*?catalog: props\.catalog/);
});
});
describe("ContentArea object browser refresh wiring", () => {
it("routes content refresh through the ObjectBrowser handle", () => {
expect(contentAreaSource).toContain('if (props.activeTab.mode === "objects") return objectBrowserRef.value?.refresh?.() ?? false;');
});
it("exposes object and active table-info reloads as refresh", () => {
expect(objectBrowserSource).toMatch(/function refresh\(\): boolean \{\s+void reload\(\{ preserveExistingRows: true \}\);\s+void refreshActiveTableInfo\(\);\s+return true;\s+\}/);
expect(objectBrowserSource).toContain("defineExpose({ focusSearch, refresh, matchesRefreshScope });");
});
it("shows the configured content refresh shortcut on the refresh button", () => {
expect(objectBrowserSource).toContain("formatShortcut(settingsStore.editorSettings.shortcuts.refreshData)");
expect(objectBrowserSource).toMatch(/<Button[^>]*:title="refreshTooltip"[^>]*@click="refresh">/);
});
});
describe("ObjectBrowser DDL API boundaries", () => {
it("uses the cached display DDL boundary for the table information panel", () => {
expect(fetchTableDdlSource).toMatch(/loadObjectDdl\(tableMetadataRequest\(row\), \{ force \}\)/);
expect(objectBrowserSource).toMatch(/function tableMetadataRequest\([\s\S]*?catalog: props\.catalog/);
});
it("keeps structure exports on the portable base DDL", () => {
expect(exportStructureSource).toMatch(/api\.getTableDdl\([\s\S]*?props\.catalog, true\);/);
expect(exportStructureSource).not.toContain("api.getTableDisplayDdl(");
});
});
@@ -1,29 +1,7 @@
import { readFileSync } from "node:fs";
import { nextTick, ref, watch } from "vue";
import { describe, expect, it } from "vitest";
const objectBrowserSource = readFileSync(new URL("../../../components/objects/ObjectBrowser.vue", import.meta.url), "utf8");
describe("ObjectBrowser context watcher", () => {
it("watches context fields independently", () => {
expect(objectBrowserSource).toContain("[() => props.connection.id, () => props.database, () => props.schema]");
expect(objectBrowserSource).not.toContain("() => [props.connection.id, props.database, props.schema]");
});
it("invalidates object requests before waiting for the new connection", () => {
const watcher = objectBrowserSource.match(/watch\(\s*\[\(\) => props\.connection\.id[\s\S]*?\{ immediate: true \},\s*\);/)?.[0] ?? "";
expect(watcher).toContain("const contextEpoch = objectBrowserRowsLoadGuard.invalidate();");
expect(watcher.indexOf("objectBrowserRowsLoadGuard.invalidate()")).toBeLessThan(watcher.indexOf("await connectionStore.ensureConnected"));
expect(watcher).toContain("reload({ allowCachedObjects: true, contextEpoch })");
});
it("loads MongoDB collections through the existing objects view", () => {
expect(objectBrowserSource).toContain("api.mongoListCollections");
expect(objectBrowserSource).toContain("buildMongoObjectBrowserRows");
expect(objectBrowserSource).toContain("objects.searchCollections");
});
it("ignores connection object replacement when the context values stay unchanged", async () => {
const connection = ref({ id: "connection-1" });
const database = ref("database-1");