Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Convert parts of `admin > databases` to unit tests (#85036)

Nemanja Glumac6cbc5d865ba8
diff --git a/e2e/test/scenarios/admin/databases.cy.spec.js b/e2e/test/scenarios/admin/databases.cy.spec.js
index 301b7dd801e..0b8be492789 100644
--- a/e2e/test/scenarios/admin/databases.cy.spec.js
+++ b/e2e/test/scenarios/admin/databases.cy.spec.js
@@ -2,43 +2,12 @@ import {
QA_MONGO_PORT,
QA_MYSQL_PORT,
QA_POSTGRES_PORT,
- SAMPLE_DB_ID,
- WRITABLE_DB_CONFIG,
- WRITABLE_DB_ID,
} from "e2e/support/cypress_data";
-import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
-import { ORDERS_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";
-import { visitDatabase, waitForDbSync } from "./helpers/e2e-database-helpers";
+import { waitForDbSync } from "./helpers/e2e-database-helpers";
const { H } = cy;
const IS_ENTERPRISE = Cypress.expose("IS_ENTERPRISE");
-const { ORDERS_ID, ORDERS } = SAMPLE_DATABASE;
-
-describe(
- "admin > database > external databases > enable actions",
- { tags: ["@external", "@actions"] },
- () => {
- ["mysql", "postgres"].forEach((dialect) => {
- it(`should show ${dialect} writable_db with actions enabled`, () => {
- H.restore(`${dialect}-writable`);
- cy.signInAsAdmin();
-
- visitDatabase(WRITABLE_DB_ID).then(({ response: { body } }) => {
- expect(body.name).to.include("Writable");
- expect(body.name.toLowerCase()).to.include(dialect);
-
- expect(body.details.dbname).to.equal(
- WRITABLE_DB_CONFIG[dialect].connection.database,
- );
- expect(body.settings["database-enable-actions"]).to.eq(true);
- });
-
- cy.findByLabelText("Data actions").should("be.checked");
- });
- });
- },
-);
describe("admin > database > add", () => {
function toggleFieldWithDisplayName(displayName) {
@@ -54,19 +23,15 @@ describe("admin > database > add", () => {
selectFieldOption("Database type", database);
}
- function mockUploadServiceAccountJSON(fileContents) {
- // create blob to act as selected file
+ function uploadServiceAccountJSON(fileContents) {
cy.get("input[type=file]")
- .then(async (input) => {
- const blob = await Cypress.Blob.binaryStringToBlob(fileContents);
- const file = new File([blob], "service-account.json");
- const dataTransfer = new DataTransfer();
-
- dataTransfer.items.add(file);
- input[0].files = dataTransfer.files;
- return input;
- })
- .trigger("change", { force: true })
+ .selectFile(
+ {
+ contents: Cypress.Buffer.from(fileContents),
+ fileName: "service-account.json",
+ },
+ { force: true },
+ )
.trigger("blur", { force: true });
}
@@ -88,8 +53,8 @@ describe("admin > database > add", () => {
cy.intercept("GET", "/api/database/:id").as("getDatabase");
cy.visit("/admin/databases/create");
- // should display a setup help link
- cy.findByRole("link", { name: "Need help connecting?" }).should("be.exist");
+ cy.log("should display a setup help link");
+ cy.findByRole("link", { name: "Need help connecting?" }).should("exist");
cy.findByLabelText("Database type").click();
});
@@ -109,14 +74,14 @@ describe("admin > database > add", () => {
cy.findByTestId("database-form").within(() => {
cy.findByText("Show advanced options").click();
+ cy.log("Reproduces metabase#14334");
cy.findByLabelText(/Rerun queries for simple explorations/).should(
"have.attr",
"data-checked",
"true",
);
- // Reproduces (metabase#14334)
cy.findByText("Additional JDBC connection string options");
- // Reproduces (metabase#17450)
+ cy.log("Reproduces metabase#17450");
cy.findByLabelText(/Choose when syncs and scans happen/)
.click({ force: true })
.should("have.attr", "data-checked", "true");
@@ -234,7 +199,9 @@ describe("admin > database > add", () => {
"Connected",
);
- editDatabase();
+ cy.findByTestId("database-connection-info-section")
+ .findByRole("button", { name: "Edit connection details" })
+ .click();
cy.findByLabelText(/Choose when syncs and scans happen/).should(
"have.attr",
@@ -355,12 +322,14 @@ describe("admin > database > add", () => {
);
it("should add MySQL database and redirect to db info page", () => {
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.contains("MySQL").click({ force: true });
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Show advanced options").click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.contains("Additional JDBC connection string options");
+ H.popover().findByText("MySQL").click();
+
+ cy.findByTestId("database-form").within(() => {
+ cy.findByRole("button", { name: /Show advanced options/ }).click();
+ cy.findByLabelText("Additional JDBC connection string options").should(
+ "be.visible",
+ );
+ });
H.typeAndBlurUsingLabel("Display name", "QA MySQL8");
H.typeAndBlurUsingLabel("Host", "localhost");
@@ -376,8 +345,7 @@ describe("admin > database > add", () => {
"allowPublicKeyRetrieval=true",
);
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Save").should("not.be.disabled").click();
+ cy.button("Save").should("not.be.disabled").click();
cy.wait("@createDatabase");
@@ -407,9 +375,9 @@ describe("admin > database > add", () => {
chooseDatabase("BigQuery");
H.typeAndBlurUsingLabel("Display name", "BQ");
selectFieldOption("Datasets", "Only these...");
- cy.findByPlaceholderText("E.x. public,auth*").type("some-dataset");
+ cy.findByPlaceholderText("E.x. public,auth*").type("foo");
- mockUploadServiceAccountJSON(serviceAccountJSON);
+ uploadServiceAccountJSON(serviceAccountJSON);
mockSuccessfulDatabaseSave().then(({ request: { body } }) => {
expect(body.details["service-account-json"]).to.equal(
serviceAccountJSON,
@@ -488,304 +456,12 @@ describe("database page > side panel", () => {
});
});
-describe("scenarios > admin > databases > exceptions", () => {
- beforeEach(() => {
- H.restore();
- cy.signInAsAdmin();
- });
-
- it("should handle malformed (null) database details (metabase#25715)", () => {
- cy.intercept("GET", `/api/database/${SAMPLE_DB_ID}`, (req) => {
- req.reply((res) => {
- res.body.details = null;
- });
- }).as("loadDatabase");
-
- cy.visit("/admin/databases/1");
- cy.wait("@loadDatabase");
-
- // It is unclear how this issue will be handled,
- // but at the very least it shouldn't render the blank page.
- cy.get("nav").should("contain", "Metabase Admin");
- // The response still contains the database name,
- // so there's no reason we can't display it.
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.contains(/Sample Database/i);
- // This seems like a reasonable CTA if the database is beyond repair.
- cy.button("Remove this database").should("not.be.disabled");
- });
-
- it("should handle is_attached_dwh databases", () => {
- cy.intercept("GET", `/api/database/${SAMPLE_DB_ID}`, (req) => {
- req.reply((res) => {
- res.body.details = null;
- res.body.is_attached_dwh = true;
- });
- }).as("loadDatabase");
-
- cy.visit("/admin/databases/1");
- cy.wait("@loadDatabase");
-
- cy.findByTestId("main-logo");
- cy.findByTestId("breadcrumbs").findByText("Sample Database");
- cy.findByTestId("database-connection-info-section")
- .findByRole("button", { name: "Edit connection details" })
- .should("be.disabled");
- cy.findByTestId("database-connection-info-section")
- .findByRole("button", { name: "Edit connection details" })
- .should("be.disabled")
- .trigger("mouseenter", { force: true });
- H.tooltip().findByText("The sample database cannot be edited.");
- cy.findByTestId("database-actions-panel").should("not.exist");
- });
-
- it("should show error upon a bad request", () => {
- cy.intercept("POST", "/api/database", (req) => {
- req.reply({
- statusCode: 400,
- body: "DATABASE CONNECTION ERROR",
- });
- }).as("createDatabase");
-
- cy.visit("/admin/databases/create");
-
- H.typeAndBlurUsingLabel("Display name", "Test");
- H.typeAndBlurUsingLabel("Database name", "db");
- H.typeAndBlurUsingLabel("Username", "admin");
-
- cy.button("Save").click();
- cy.wait("@createDatabase");
-
- cy.findByTestId("database-form")
- .parent()
- .within(() => {
- cy.findByText("DATABASE CONNECTION ERROR").should("be.visible");
- });
- });
-
- it("should show specific error message when error is on host or port", () => {
- cy.intercept("POST", "/api/database", (req) => {
- req.reply({
- statusCode: 400,
- body: {
- message: "DATABASE CONNECTION ERROR",
- errors: {
- host: "Check your host",
- port: "Check your port",
- },
- },
- });
- }).as("createDatabase");
-
- cy.visit("/admin/databases/create");
-
- H.typeAndBlurUsingLabel("Display name", "Test");
- H.typeAndBlurUsingLabel("Database name", "db");
- H.typeAndBlurUsingLabel("Username", "admin");
-
- cy.button("Save").click();
- cy.wait("@createDatabase");
-
- cy.findByTestId("database-form")
- .parent()
- .within(() => {
- cy.findByText("DATABASE CONNECTION ERROR").should("not.exist");
- cy.findByText(
- /Make sure your Host and Port settings are correct/,
- ).should("be.visible");
- });
- });
-
- it("should handle non-existing databases (metabase#11037)", () => {
- cy.intercept("GET", "/api/database/999").as("loadDatabase");
- cy.visit("/admin/databases/999");
- cy.wait("@loadDatabase").then(({ response }) => {
- expect(response.statusCode).to.eq(404);
- });
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Not found.");
- cy.findByRole("table").should("not.exist");
- });
-
- it("should handle a failure to `GET` the list of all databases (metabase#20471)", () => {
- const errorMessage = "Lorem ipsum dolor sit amet, consectetur adip";
-
- if (IS_ENTERPRISE) {
- H.activateToken("pro-self-hosted");
- }
-
- cy.intercept(
- {
- method: "GET",
- pathname: "/api/database",
- query: IS_ENTERPRISE
- ? {
- exclude_uneditable_details: "true",
- }
- : null,
- },
- (req) => {
- req.reply({
- statusCode: 500,
- body: { message: errorMessage },
- });
- },
- ).as("failedGet");
-
- cy.visit("/admin/databases");
- cy.wait("@failedGet");
-
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText(/Something.s gone wrong/);
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText(
- /We.ve run into an error\. You can try refreshing the page, or just go back\./,
- );
-
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText(errorMessage).should("not.be.visible");
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Show error details").click();
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText(errorMessage).should("be.visible");
- });
-});
-
describe("scenarios > admin > databases > sample database", () => {
beforeEach(() => {
H.restore();
cy.signInAsAdmin();
});
- it("database actions", () => {
- cy.intercept("POST", `/api/database/${SAMPLE_DB_ID}/sync_schema`).as(
- "sync_schema",
- );
- cy.intercept("POST", `/api/database/${SAMPLE_DB_ID}/rescan_values`).as(
- "rescan_values",
- );
- cy.intercept("POST", `/api/database/${SAMPLE_DB_ID}/discard_values`).as(
- "discard_values",
- );
- cy.intercept("GET", `/api/database/${SAMPLE_DB_ID}/usage_info`).as(
- "usage_info",
- );
- cy.intercept("DELETE", `/api/database/${SAMPLE_DB_ID}`).as("delete");
- // model
- cy.request("PUT", `/api/card/${ORDERS_QUESTION_ID}`, { type: "model" });
- // Create a segment through API
- H.createSegment({
- name: "Small orders",
- description: "All orders with a total under $100.",
- definition: {
- database: SAMPLE_DB_ID,
- type: "query",
- query: {
- "source-table": ORDERS_ID,
- filter: ["<", ["field", ORDERS.TOTAL, null], 100],
- },
- },
- });
-
- // metric
- H.createQuestion({
- name: "Revenue",
- description: "Sum of orders subtotal",
- type: "metric",
- query: {
- "source-table": ORDERS_ID,
- aggregation: [["sum", ["field", ORDERS.SUBTOTAL, null]]],
- },
- });
-
- visitDatabase(SAMPLE_DB_ID);
-
- // lets you trigger the manual database schema sync
- cy.button("Sync database schema").click();
- cy.wait("@sync_schema");
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Sync triggered!");
-
- // lets you trigger the manual rescan of field values
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Re-scan field values").click();
- cy.wait("@rescan_values");
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.findByText("Scan triggered!");
-
- // lets you discard saved field values
- cy.findByTestId("database-danger-zone-section")
- .as("danger")
- .within(() => {
- cy.button("Discard saved field values").click();
- });
- H.modal().within(() => {
- cy.findByRole("heading").should(
- "have.text",
- "Discard saved field values",
- );
- cy.findByText("Are you sure you want to do this?");
- cy.button("Yes").click();
- });
- cy.wait("@discard_values");
-
- // lets you remove the Sample Database
- cy.get("@danger").within(() => {
- cy.button("Remove this database").click();
- cy.wait("@usage_info");
- });
-
- H.modal().within(() => {
- cy.button("Delete this DB connection")
- .as("deleteButton")
- .should("be.disabled");
- cy.findByLabelText(/Delete [0-9]* saved questions?/)
- .should("not.be.checked")
- .click()
- .should("be.checked");
- cy.findByLabelText(/Delete [0-9]* models?/)
- .should("not.be.checked")
- .click()
- .should("be.checked");
- cy.findByLabelText(/Delete [0-9]* metrics?/)
- .should("not.be.checked")
- .click()
- .should("be.checked");
- cy.findByLabelText(/Delete [0-9]* segments?/)
- .should("not.be.checked")
- .click()
- .should("be.checked");
- cy.findByText(
- "This will delete every saved question, model, metric, and segment you’ve made that uses this data, and can’t be undone. Transforms that use this database won’t be deleted, but they will stop working.",
- );
-
- cy.get("@deleteButton").should("be.disabled");
-
- cy.findByPlaceholderText("Are you completely sure?")
- .type("Sample Database")
- .blur();
-
- cy.intercept("GET", "/api/database").as("fetchDatabases");
- cy.get("@deleteButton").should("be.enabled").click();
- cy.wait(["@delete", "@fetchDatabases"]);
- });
-
- cy.location("pathname").should("eq", "/admin/databases/"); // FIXME why the trailing slash?
- cy.intercept("POST", "/api/database/sample_database").as("sample_database");
- // eslint-disable-next-line metabase/no-unscoped-text-selectors -- deprecated usage
- cy.contains("Bring the sample database back", {
- timeout: 10000,
- }).click();
- cy.wait("@sample_database");
-
- cy.findAllByRole("cell").contains("Sample Database").click();
- const newSampleDatabaseId = SAMPLE_DB_ID + 1;
- cy.location("pathname").should(
- "eq",
- `/admin/databases/${newSampleDatabaseId}`,
- );
- });
-
it("updates databases list in Browse databases after bringing sample database back", () => {
cy.intercept("GET", "/api/database").as("loadDatabases");
cy.intercept("POST", "/api/database/sample_database").as(
@@ -850,35 +526,3 @@ describe("scenarios > admin > databases > sample database", () => {
});
});
});
-
-describe("add database card", () => {
- beforeEach(() => {
- H.resetSnowplow();
- H.restore();
- cy.signInAsAdmin();
- H.enableTracking();
- });
-
- it("should track the click on the card", () => {
- cy.visit("/browse/databases");
-
- // eslint-disable-next-line metabase/no-unsafe-element-filtering
- cy.findByTestId("database-browser")
- .findAllByRole("link")
- .last()
- .as("addDatabaseCard");
-
- cy.get("@addDatabaseCard").findByText("Add a database").click();
- cy.location("pathname").should("eq", "/admin/databases/create");
- H.expectUnstructuredSnowplowEvent({
- event: "database_add_clicked",
- triggered_from: "db-list",
- });
- });
-});
-
-function editDatabase() {
- cy.findByTestId("database-connection-info-section")
- .findByRole("button", { name: "Edit connection details" })
- .click();
-}
diff --git a/frontend/src/metabase/admin/databases/components/DatabaseConnectionInfoSection/DatabaseConnectionInfoSection.unit.spec.tsx b/frontend/src/metabase/admin/databases/components/DatabaseConnectionInfoSection/DatabaseConnectionInfoSection.unit.spec.tsx
index 10eb1290b90..0bf806af31f 100644
--- a/frontend/src/metabase/admin/databases/components/DatabaseConnectionInfoSection/DatabaseConnectionInfoSection.unit.spec.tsx
+++ b/frontend/src/metabase/admin/databases/components/DatabaseConnectionInfoSection/DatabaseConnectionInfoSection.unit.spec.tsx
@@ -1,4 +1,6 @@
-import userEvent from "@testing-library/user-event";
+import userEvent, {
+ PointerEventsCheckLevel,
+} from "@testing-library/user-event";
import fetchMock from "fetch-mock";
import {
@@ -100,6 +102,7 @@ describe("DatabaseConnectionInfoSection", () => {
),
).toBe(true);
});
+ expect(await screen.findByText("Sync triggered!")).toBeInTheDocument();
});
it("shows an error when a schema sync fails", async () => {
@@ -134,6 +137,7 @@ describe("DatabaseConnectionInfoSection", () => {
),
).toBe(true);
});
+ expect(await screen.findByText("Scan triggered!")).toBeInTheDocument();
});
describe("sync indicator", () => {
@@ -236,5 +240,26 @@ describe("DatabaseConnectionInfoSection", () => {
await screen.findByRole("button", { name: /Edit connection details/i }),
).toBeDisabled();
});
+
+ it("should explain why a cloud-attached sample database without details cannot be edited", async () => {
+ setup({
+ database: createMockDatabase({
+ is_sample: true,
+ is_attached_dwh: true,
+ details: undefined,
+ }),
+ });
+ const editButton = await screen.findByRole("button", {
+ name: /Edit connection details/i,
+ });
+ expect(editButton).toBeDisabled();
+
+ await userEvent.hover(editButton, {
+ pointerEventsCheck: PointerEventsCheckLevel.Never,
+ });
+ expect(await screen.findByRole("tooltip")).toHaveTextContent(
+ "The sample database cannot be edited.",
+ );
+ });
});
});
diff --git a/frontend/src/metabase/admin/databases/components/DatabaseDangerZoneSection/DatabaseDangerZoneSection.unit.spec.tsx b/frontend/src/metabase/admin/databases/components/DatabaseDangerZoneSection/DatabaseDangerZoneSection.unit.spec.tsx
index 5d38b24c833..26fe532b6a0 100644
--- a/frontend/src/metabase/admin/databases/components/DatabaseDangerZoneSection/DatabaseDangerZoneSection.unit.spec.tsx
+++ b/frontend/src/metabase/admin/databases/components/DatabaseDangerZoneSection/DatabaseDangerZoneSection.unit.spec.tsx
@@ -8,7 +8,11 @@ import {
import { createMockState } from "__support__/state";
import { createMockEntitiesState } from "__support__/store";
import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
-import type { Database, InitialSyncStatus } from "metabase-types/api";
+import type {
+ Database,
+ DatabaseUsageInfo,
+ InitialSyncStatus,
+} from "metabase-types/api";
import { createMockDatabase } from "metabase-types/api/mocks";
import { DatabaseDangerZoneSection } from "./DatabaseDangerZoneSection";
@@ -29,14 +33,24 @@ function getRemoveDatabaseConfirmModal() {
) as HTMLElement;
}
+const NO_USAGE_INFO: DatabaseUsageInfo = {
+ question: 0,
+ dataset: 0,
+ metric: 0,
+ segment: 0,
+ transform: 0,
+};
+
interface SetupOpts {
database?: Database;
isAdmin?: boolean;
+ usageInfo?: DatabaseUsageInfo;
}
function setup({
database = createMockDatabase(),
isAdmin = true,
+ usageInfo = NO_USAGE_INFO,
}: SetupOpts = {}) {
const state = createMockState({
entities: createMockEntitiesState({
@@ -44,13 +58,7 @@ function setup({
}),
});
setupDatabaseEndpoints(database);
- setupDatabaseUsageInfoEndpoint(database, {
- question: 0,
- dataset: 0,
- metric: 0,
- segment: 0,
- transform: 0,
- });
+ setupDatabaseUsageInfoEndpoint(database, usageInfo);
const deleteDatabase = jest.fn().mockResolvedValue({});
@@ -76,11 +84,14 @@ describe("DatabaseDangerZoneSection", () => {
const { database } = setup();
await userEvent.click(screen.getByText(/Discard saved field values/i));
- await userEvent.click(
- within(getDiscardFieldValuesConfirmModal()).getByRole("button", {
- name: "Yes",
- }),
+ const modal = getDiscardFieldValuesConfirmModal();
+ expect(within(modal).getByRole("heading")).toHaveTextContent(
+ "Discard saved field values",
);
+ expect(
+ within(modal).getByText("Are you sure you want to do this?"),
+ ).toBeInTheDocument();
+ await userEvent.click(within(modal).getByRole("button", { name: "Yes" }));
await waitFor(() => {
expect(
@@ -177,6 +188,56 @@ describe("DatabaseDangerZoneSection", () => {
expect(deleteDatabase).toHaveBeenCalled();
});
+ it("should require confirming the removal of each kind of content that uses the database", async () => {
+ const { database, deleteDatabase } = setup({
+ usageInfo: {
+ question: 1,
+ dataset: 2,
+ metric: 3,
+ segment: 4,
+ transform: 0,
+ },
+ });
+ await userEvent.click(
+ await screen.findByRole("button", { name: /Remove this database/i }),
+ );
+ const modal = getRemoveDatabaseConfirmModal();
+ const deleteButton = within(modal).getByRole("button", {
+ name: "Delete this DB connection",
+ });
+
+ expect(deleteButton).toBeDisabled();
+
+ const contentCheckboxes = await Promise.all(
+ [
+ "Delete 1 saved question",
+ "Delete 2 models",
+ "Delete 3 metrics",
+ "Delete 4 segments",
+ ].map((label) => within(modal).findByLabelText(label)),
+ );
+ for (const checkbox of contentCheckboxes) {
+ expect(checkbox).not.toBeChecked();
+ await userEvent.click(checkbox);
+ expect(checkbox).toBeChecked();
+ }
+ expect(
+ within(modal).getByText(
+ "This will delete every saved question, model, metric, and segment you’ve made that uses this data, and can’t be undone. Transforms that use this database won’t be deleted, but they will stop working.",
+ ),
+ ).toBeInTheDocument();
+ expect(deleteButton).toBeDisabled();
+
+ await userEvent.type(
+ within(modal).getByPlaceholderText("Are you completely sure?"),
+ database.name,
+ );
+ expect(deleteButton).toBeEnabled();
+
+ await userEvent.click(deleteButton);
+ expect(deleteDatabase).toHaveBeenCalledWith(database.id);
+ });
+
it("should allow delete database confirmation modal to be dismissed", async () => {
const { database, deleteDatabase } = setup({ isAdmin: true });
await userEvent.click(
diff --git a/frontend/src/metabase/admin/databases/components/DatabaseList/DatabaseList.unit.spec.tsx b/frontend/src/metabase/admin/databases/components/DatabaseList/DatabaseList.unit.spec.tsx
index 584b207e202..5b5605ee7fb 100644
--- a/frontend/src/metabase/admin/databases/components/DatabaseList/DatabaseList.unit.spec.tsx
+++ b/frontend/src/metabase/admin/databases/components/DatabaseList/DatabaseList.unit.spec.tsx
@@ -59,6 +59,15 @@ describe("DatabaseListApp", () => {
expect(screen.queryByText("Active")).not.toBeInTheDocument();
});
+ it("links each database to its admin page", async () => {
+ await setup({ isAdmin: true });
+
+ expect(screen.getByRole("link", { name: "Database" })).toHaveAttribute(
+ "href",
+ "/admin/databases/1",
+ );
+ });
+
it("shows regular databases as active", async () => {
await setup({ isAdmin: true });
diff --git a/frontend/src/metabase/admin/databases/containers/DatabaseEditApp.unit.spec.tsx b/frontend/src/metabase/admin/databases/containers/DatabaseEditApp.unit.spec.tsx
index a5d54fe98d5..0d46c745281 100644
--- a/frontend/src/metabase/admin/databases/containers/DatabaseEditApp.unit.spec.tsx
+++ b/frontend/src/metabase/admin/databases/containers/DatabaseEditApp.unit.spec.tsx
@@ -2,13 +2,14 @@ import fetchMock from "fetch-mock";
import {
setupDatabaseEndpoints,
+ setupDatabaseNotFoundEndpoint,
setupDatabaseUsageInfoEndpoint,
setupEnginesEndpoint,
} from "__support__/server-mocks";
import { createMockState } from "__support__/state";
-import { renderWithProviders, screen } from "__support__/ui";
+import { renderWithProviders, screen, within } from "__support__/ui";
import { Route } from "metabase/router";
-import type { Database } from "metabase-types/api";
+import type { Database, DatabaseId } from "metabase-types/api";
import {
createMockDatabase,
createMockEngines,
@@ -17,7 +18,27 @@ import {
import { DatabaseEditApp } from "./DatabaseEditApp";
-const setup = ({ database }: { database: Database }) => {
+const NON_EXISTING_DATABASE_ID = 999;
+
+const SAMPLE_DATABASE = createMockDatabase({
+ name: "Sample Database",
+ is_sample: true,
+});
+
+interface SetupOpts {
+ database: Database;
+ hasNullDetails?: boolean;
+}
+
+const setup = ({ database, hasNullDetails = false }: SetupOpts) => {
+ if (hasNullDetails) {
+ // Registered before `setupDatabaseEndpoints` so that this route matches
+ // first. The backend can send `details: null`, which `Database` does not allow.
+ fetchMock.get(`path:/api/database/${database.id}`, {
+ ...database,
+ details: null,
+ });
+ }
setupEnginesEndpoint({});
setupDatabaseEndpoints(database);
setupEnginesEndpoint(createMockEngines());
@@ -32,11 +53,26 @@ const setup = ({ database }: { database: Database }) => {
settings: {},
});
+ renderDatabaseEditApp(database.id);
+};
+
+const setupNonExistingDatabase = () => {
+ setupEnginesEndpoint(createMockEngines());
+ setupDatabaseNotFoundEndpoint(NON_EXISTING_DATABASE_ID);
+ fetchMock.get(
+ `path:/api/database/${NON_EXISTING_DATABASE_ID}/settings-available`,
+ { status: 404, body: "Not found." },
+ );
+
+ renderDatabaseEditApp(NON_EXISTING_DATABASE_ID);
+};
+
+const renderDatabaseEditApp = (databaseId: DatabaseId) => {
renderWithProviders(
<Route path="/admin/databases/:databaseId" element={<DatabaseEditApp />} />,
{
withRouter: true,
- initialRoute: `/admin/databases/${database.id}`,
+ initialRoute: `/admin/databases/${databaseId}`,
storeInitialState: createMockState({
currentUser: createMockUser({ is_superuser: true }),
}),
@@ -74,4 +110,70 @@ describe("DatabaseEditApp", () => {
screen.getByTestId("database-danger-zone-section"),
).toBeInTheDocument();
});
+
+ it("shows the database and lets admins remove it when its details are null (metabase#25715)", async () => {
+ setup({ database: SAMPLE_DATABASE, hasNullDetails: true });
+
+ expect(
+ await screen.findByTestId("database-connection-info-section"),
+ ).toBeInTheDocument();
+ expect(screen.getByTestId("breadcrumbs")).toHaveTextContent(
+ "Sample Database",
+ );
+ expect(
+ screen.getByRole("button", { name: "Remove this database" }),
+ ).toBeEnabled();
+ });
+
+ it("shows a cloud-attached database without editing, removing or data actions", async () => {
+ setup({
+ database: {
+ ...SAMPLE_DATABASE,
+ features: ["actions"],
+ is_attached_dwh: true,
+ },
+ hasNullDetails: true,
+ });
+
+ const connectionSection = await screen.findByTestId(
+ "database-connection-info-section",
+ );
+ expect(screen.getByTestId("breadcrumbs")).toHaveTextContent(
+ "Sample Database",
+ );
+ expect(
+ within(connectionSection).getByRole("button", {
+ name: "Edit connection details",
+ }),
+ ).toBeDisabled();
+ expect(
+ screen.queryByRole("button", { name: "Remove this database" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId("database-data-actions-section"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows that data actions are enabled for the database", async () => {
+ setup({
+ database: createMockDatabase({
+ features: ["actions"],
+ settings: { "database-enable-actions": true },
+ }),
+ });
+
+ expect(await screen.findByLabelText("Data actions")).toBeChecked();
+ });
+
+ it("shows an error instead of the database sections when the database does not exist (metabase#11037)", async () => {
+ setupNonExistingDatabase();
+
+ expect(await screen.findByText("Not found.")).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("database-connection-info-section"),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId("database-danger-zone-section"),
+ ).not.toBeInTheDocument();
+ });
});
diff --git a/frontend/src/metabase/admin/databases/containers/DatabaseListApp.unit.spec.tsx b/frontend/src/metabase/admin/databases/containers/DatabaseListApp.unit.spec.tsx
index a367c8c4d51..bc6edc6165b 100644
--- a/frontend/src/metabase/admin/databases/containers/DatabaseListApp.unit.spec.tsx
+++ b/frontend/src/metabase/admin/databases/containers/DatabaseListApp.unit.spec.tsx
@@ -1,39 +1,114 @@
+import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
+import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
import {
setupDatabaseListEndpoint,
+ setupDatabaseListEndpointError,
setupEnginesEndpoint,
} from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
import { createMockState } from "__support__/state";
import { renderWithProviders, screen } from "__support__/ui";
+import { reinitialize } from "metabase/plugins";
import {
createMockDatabase,
createMockEngines,
+ createMockTokenFeatures,
createMockUser,
} from "metabase-types/api/mocks";
import { DatabaseListApp } from "./DatabaseListApp";
-const setup = () => {
- setupEnginesEndpoint({});
- setupDatabaseListEndpoint([
- createMockDatabase({ id: 1, name: "Stubbed DB", is_stub: true }),
- ]);
+const LIST_ERROR_MESSAGE = "Lorem ipsum dolor sit amet, consectetur adip";
+
+interface SetupOpts {
+ hasListError?: boolean;
+ hasAdvancedPermissions?: boolean;
+}
+
+const setup = ({
+ hasListError = false,
+ hasAdvancedPermissions = false,
+}: SetupOpts = {}) => {
setupEnginesEndpoint(createMockEngines());
+ if (hasListError) {
+ setupDatabaseListEndpointError({
+ status: 500,
+ body: { message: LIST_ERROR_MESSAGE },
+ });
+ } else {
+ setupDatabaseListEndpoint([
+ createMockDatabase({ id: 1, name: "Stubbed DB", is_stub: true }),
+ ]);
+ }
+
+ const settings = mockSettings({
+ "token-features": createMockTokenFeatures({
+ advanced_permissions: hasAdvancedPermissions,
+ }),
+ });
+ if (hasAdvancedPermissions) {
+ setupEnterpriseOnlyPlugin("feature_level_permissions");
+ }
renderWithProviders(<DatabaseListApp />, {
storeInitialState: createMockState({
currentUser: createMockUser({ is_superuser: true }),
+ settings,
}),
});
};
+const getListRequestParams = () => {
+ const [call] = fetchMock.callHistory.calls("path:/api/database");
+ return new URL(call.url).searchParams;
+};
+
describe("DatabaseListApp", () => {
+ afterEach(() => {
+ reinitialize();
+ });
+
it("requests stub databases so they can be listed", async () => {
setup();
expect(await screen.findByText("Stubbed DB")).toBeInTheDocument();
- const [call] = fetchMock.callHistory.calls("path:/api/database");
- expect(new URL(call.url).searchParams.get("include_stubs")).toBe("true");
+ expect(getListRequestParams().get("include_stubs")).toBe("true");
+ expect(getListRequestParams().has("exclude_uneditable_details")).toBe(
+ false,
+ );
+ });
+
+ it("excludes databases with uneditable details when advanced permissions are enabled", async () => {
+ setup({ hasAdvancedPermissions: true });
+
+ expect(await screen.findByText("Stubbed DB")).toBeInTheDocument();
+ expect(getListRequestParams().get("exclude_uneditable_details")).toBe(
+ "true",
+ );
});
+
+ it.each([
+ { hasAdvancedPermissions: false },
+ { hasAdvancedPermissions: true },
+ ])(
+ "shows a generic error with hidden details when the databases fail to load (metabase#20471) (advanced permissions: $hasAdvancedPermissions)",
+ async ({ hasAdvancedPermissions }) => {
+ setup({ hasListError: true, hasAdvancedPermissions });
+
+ expect(
+ await screen.findByText(/Something.s gone wrong/),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText(
+ /We.ve run into an error\. You can try refreshing the page, or just go back\./,
+ ),
+ ).toBeInTheDocument();
+ expect(screen.getByText(LIST_ERROR_MESSAGE)).not.toBeVisible();
+
+ await userEvent.click(screen.getByText("Show error details"));
+ expect(screen.getByText(LIST_ERROR_MESSAGE)).toBeVisible();
+ },
+ );
});
diff --git a/frontend/src/metabase/admin/databases/containers/DatabasePage.unit.spec.tsx b/frontend/src/metabase/admin/databases/containers/DatabasePage.unit.spec.tsx
index 432ff8cca77..5a071231f77 100644
--- a/frontend/src/metabase/admin/databases/containers/DatabasePage.unit.spec.tsx
+++ b/frontend/src/metabase/admin/databases/containers/DatabasePage.unit.spec.tsx
@@ -1,11 +1,19 @@
import { waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
-import { setupEnginesEndpoint } from "__support__/server-mocks";
+import {
+ setupCreateDatabaseEndpointError,
+ setupEnginesEndpoint,
+} from "__support__/server-mocks";
import { createMockState } from "__support__/state";
import { renderWithProviders, screen } from "__support__/ui";
import { Route } from "metabase/router";
-import { createMockEngines } from "metabase-types/api/mocks";
+import {
+ createMockEngine,
+ createMockEngineField,
+ createMockEngines,
+} from "metabase-types/api/mocks";
import { DatabasePage } from "./DatabasePage";
@@ -14,8 +22,42 @@ jest.mock(
() => "Postgres MD Content",
);
-const setup = () => {
- setupEnginesEndpoint(createMockEngines());
+const CONNECTION_ERROR_MESSAGE = "DATABASE CONNECTION ERROR";
+
+const POSTGRES_ENGINE = createMockEngine({
+ "driver-name": "PostgreSQL",
+ "details-fields": [
+ createMockEngineField({ name: "host", "display-name": "Host" }),
+ createMockEngineField({
+ name: "port",
+ "display-name": "Port",
+ type: "integer",
+ }),
+ createMockEngineField({
+ name: "dbname",
+ "display-name": "Database name",
+ required: true,
+ }),
+ createMockEngineField({
+ name: "user",
+ "display-name": "Username",
+ required: true,
+ }),
+ ],
+});
+
+interface SetupOpts {
+ createDatabaseErrorBody?: string | Record<string, unknown>;
+}
+
+const setup = ({ createDatabaseErrorBody }: SetupOpts = {}) => {
+ setupEnginesEndpoint(createMockEngines({ postgres: POSTGRES_ENGINE }));
+ if (createDatabaseErrorBody !== undefined) {
+ setupCreateDatabaseEndpointError({
+ status: 400,
+ body: createDatabaseErrorBody,
+ });
+ }
renderWithProviders(<Route path="/" element={<DatabasePage />} />, {
withRouter: true,
@@ -23,6 +65,20 @@ const setup = () => {
});
};
+const fillInAndSaveDatabase = async () => {
+ await userEvent.type(await screen.findByLabelText("Display name"), "Test");
+ await userEvent.type(screen.getByLabelText("Database name"), "db");
+ await userEvent.type(screen.getByLabelText("Username"), "admin");
+
+ const saveButton = screen.getByRole("button", { name: "Save" });
+ await waitFor(() => expect(saveButton).toBeEnabled());
+ await userEvent.click(saveButton);
+
+ await waitFor(() => {
+ expect(fetchMock.callHistory.called("path:/api/database")).toBe(true);
+ });
+};
+
describe("DatabasePage", () => {
describe("Help button", () => {
it("should render the 'Help is here' button", async () => {
@@ -44,4 +100,39 @@ describe("DatabasePage", () => {
});
});
});
+
+ describe("saving a new database", () => {
+ it("should show the error message when the database cannot be created", async () => {
+ setup({ createDatabaseErrorBody: CONNECTION_ERROR_MESSAGE });
+
+ await fillInAndSaveDatabase();
+
+ expect(
+ await screen.findByText(CONNECTION_ERROR_MESSAGE),
+ ).toBeInTheDocument();
+ });
+
+ it("should show a host and port hint instead of the error message when the error is on the host or port", async () => {
+ setup({
+ createDatabaseErrorBody: {
+ message: CONNECTION_ERROR_MESSAGE,
+ errors: {
+ host: "Check your host",
+ port: "Check your port",
+ },
+ },
+ });
+
+ await fillInAndSaveDatabase();
+
+ expect(
+ await screen.findByText(
+ /Make sure your Host and Port settings are correct/,
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText(CONNECTION_ERROR_MESSAGE),
+ ).not.toBeInTheDocument();
+ });
+ });
});
diff --git a/frontend/src/metabase/browse/databases/BrowseDatabases.unit.spec.tsx b/frontend/src/metabase/browse/databases/BrowseDatabases.unit.spec.tsx
index 3b50a734e67..ce9d51dc7cf 100644
--- a/frontend/src/metabase/browse/databases/BrowseDatabases.unit.spec.tsx
+++ b/frontend/src/metabase/browse/databases/BrowseDatabases.unit.spec.tsx
@@ -106,6 +106,26 @@ describe("BrowseDatabases", () => {
},
);
+ it("opens the add database page from the add database card and tracks the click", async () => {
+ const { trackSimpleEvent } = jest.requireMock<{
+ trackSimpleEvent: jest.Mock<void, [{ event: string }]>;
+ }>("metabase/analytics");
+ const { router } = renderBrowseDatabasesWithRouter(
+ [createMockDatabase({ id: 1, name: "Sales" })],
+ { isAdmin: true },
+ );
+
+ await userEvent.click(await screen.findByText("Add a database"));
+
+ expect(router?.location.pathname).toBe("/admin/databases/create");
+ const addDatabaseEvents = trackSimpleEvent.mock.calls.filter(
+ ([event]) => event.event === "database_add_clicked",
+ );
+ expect(addDatabaseEvents).toEqual([
+ [{ event: "database_add_clicked", triggered_from: "db-list" }],
+ ]);
+ });
+
it("opens the database options menu without opening the database", async () => {
const { router } = renderBrowseDatabasesWithRouter(
[databaseWithSchemas(7, "Sales", ["PUBLIC", "ANALYTICS"])],
diff --git a/frontend/test/__support__/server-mocks/database.ts b/frontend/test/__support__/server-mocks/database.ts
index 2ae2ee99c76..000c41a49af 100644
--- a/frontend/test/__support__/server-mocks/database.ts
+++ b/frontend/test/__support__/server-mocks/database.ts
@@ -64,6 +64,27 @@ export function setupUpdateDatabaseEndpointError(databaseId: Database["id"]) {
fetchMock.put(`path:/api/database/${databaseId}`, { status: 500 });
}
+export function setupDatabaseNotFoundEndpoint(databaseId: DatabaseId) {
+ fetchMock.get(`path:/api/database/${databaseId}`, {
+ status: 404,
+ body: "Not found.",
+ });
+}
+
+export function setupCreateDatabaseEndpointError({
+ status,
+ body,
+}: {
+ status: number;
+ body: string | Record<string, unknown>;
+}) {
+ fetchMock.post(
+ "path:/api/database",
+ { status, body },
+ { name: "create-database" },
+ );
+}
+
export function setupDatabaseHealthcheckEndpoint(databaseId: Database["id"]) {
fetchMock.get(`path:/api/database/${databaseId}/healthcheck`, {
body: { status: "ok" },
@@ -89,6 +110,20 @@ export function setupDatabaseListEndpoint(databases: Database[]) {
);
}
+export function setupDatabaseListEndpointError({
+ status,
+ body,
+}: {
+ status: number;
+ body: Record<string, unknown>;
+}) {
+ fetchMock.get(
+ "path:/api/database",
+ { status, body },
+ { name: "database-list" },
+ );
+}
+
export function setupDatabasesEndpoints(
databases: Database[],
{ hasSavedQuestions = true } = {},
diff --git a/test/metabase/warehouses_rest/api_test.clj b/test/metabase/warehouses_rest/api_test.clj
index ebed0ad3e1b..e57a659bd8d 100644
--- a/test/metabase/warehouses_rest/api_test.clj
+++ b/test/metabase/warehouses_rest/api_test.clj
@@ -213,6 +213,12 @@
:specific-errors {:include ["should be either \"tables\" or \"tables.fields\", received: \"schemas\""]}}
(mt/user-http-request :lucky :get 400 (format "database/%d?include=schemas" (mt/id))))))))
+(deftest ^:parallel get-database-not-found-test
+ (testing "GET /api/database/:id"
+ (testing "A database that does not exist should return a 404 (#11037)"
+ (is (= "Not found."
+ (mt/user-http-request :crowberto :get 404 (format "database/%d" Integer/MAX_VALUE)))))))
+
(deftest get-database-stub-test
(testing "GET /api/database"
(testing "A stub database should not be included in the response"