The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
e2e2unit: card template tag normalization (#85829)
Nemanja Glumac53166aa8b036
diff --git a/e2e/test/scenarios/native/card-tag-normalization.cy.spec.ts b/e2e/test/scenarios/native/card-tag-normalization.cy.spec.tsdeleted file mode 100644index 69028c5134c..00000000000--- a/e2e/test/scenarios/native/card-tag-normalization.cy.spec.ts+++ /dev/null@@ -1,62 +0,0 @@-const { H } = cy;--// The frontend names card template tags `#<card-id>-<slugg(card.name)>` (see NativeQuery.ts), but any-// `#<id>-<slug>` is accepted. The backend stores tag names verbatim on save — names are only rewritten-// during serdes import, when the referenced card's id changes. These tests pin the FE->BE->FE edit-// cycle: saving never errors and never rewrites what the frontend sent.--describe("scenarios > native > card template tag normalization", () => {- beforeEach(() => {- H.restore();- cy.signInAsAdmin();- });-- it("saves differently-named card references verbatim and reopens frontend-named ones clean", () => {- H.createNativeQuestion({- name: "Basic Aggregations",- native: { query: 'SELECT COUNT(*) AS "count" FROM PEOPLE' },- }).then(({ body: { id: cardId } }) => {- H.startNewNativeQuestion({ query: "" });- H.NativeEditor.type(- `SELECT 1 FROM {{#${cardId}-foo}} AS a, {{#${cardId}-bar}} AS b`,- { allowFastSet: true },- );- H.saveQuestionToCollection("Duplicate Card Refs", undefined, {- wrapId: true,- });-- cy.get("@questionId").then((questionId) => {- cy.request("GET", `/api/card/${questionId}`).then(({ body }) => {- const query = JSON.stringify(body.dataset_query);- expect(query).to.contain(`#${cardId}-foo`);- expect(query).to.contain(`#${cardId}-bar`);- });- });- });-- cy.log(- "reopens clean when the tag name matches what the frontend generated",- );- H.createNativeQuestion({- name: "Bob's Café",- native: { query: 'SELECT COUNT(*) AS "count" FROM PEOPLE' },- }).then(({ body: { id: cardId } }) => {- // slugg("Bob's Café") === "bobs-cafe", so this is the exact tag name the frontend generates- const frontendTag = `#${cardId}-bobs-cafe`;-- H.startNewNativeQuestion({ query: "" });- H.NativeEditor.type(`SELECT * FROM {{${frontendTag}}}`, {- allowFastSet: true,- });- H.saveQuestionToCollection("Cafe Ref", undefined, { wrapId: true });-- cy.get("@questionId").then((questionId) => {- H.visitQuestion(questionId);- });- cy.findByTestId("visibility-toggler").click();- H.NativeEditor.get().should("contain", `{{${frontendTag}}}`);- cy.findByTestId("qb-header").should("be.visible");- cy.findByTestId("qb-header").button("Save").should("not.exist");- });- });-});diff --git a/frontend/src/metabase-lib/v1/queries/NativeQuery.unit.spec.ts b/frontend/src/metabase-lib/v1/queries/NativeQuery.unit.spec.tsindex 5873af9a71b..39aa0fb9310 100644--- a/frontend/src/metabase-lib/v1/queries/NativeQuery.unit.spec.ts+++ b/frontend/src/metabase-lib/v1/queries/NativeQuery.unit.spec.ts@@ -402,6 +402,25 @@ describe("NativeQuery", () => {);expect(q.templateTags().map((v) => v["card-id"])).toEqual([1, 2, 1]);});++ it("should keep differently-named tags for the same card verbatim", () => {+ const queryText = "SELECT 1 FROM {{#1-foo}} AS a, {{#1-bar}} AS b";+ const q = makeQuery().setQueryText(queryText);++ expect(q.queryText()).toBe(queryText);+ expect(q.templateTagsMap()).toEqual({+ "#1-foo": expect.objectContaining({+ name: "#1-foo",+ type: "card",+ "card-id": 1,+ }),+ "#1-bar": expect.objectContaining({+ name: "#1-bar",+ type: "card",+ "card-id": 1,+ }),+ });+ });});});diff --git a/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts b/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.tsindex 4594577c850..a0d1bdf196c 100644--- a/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts+++ b/frontend/src/metabase/query_builder/actions/core/initializeQB.unit.spec.ts@@ -3,7 +3,7 @@ import fetchMock from "fetch-mock";import { createMockMetadataFromState } from "__support__/metadata";import { createMockLocation, createMockState } from "__support__/state";import { createMockEntitiesState } from "__support__/store";-import { databaseApi, snippetApi } from "metabase/api";+import { cardApi, databaseApi, snippetApi } from "metabase/api";import * as rtkEndpointUtils from "metabase/api/utils/run-rtk-endpoint";import * as CardLib from "metabase/common/utils/card";import * as questionActions from "metabase/questions/actions";@@ -15,6 +15,7 @@ import { defer } from "metabase/utils/promise";import { checkNotNull } from "metabase/utils/types";import * as Lib from "metabase-lib";import Question from "metabase-lib/v1/Question";+import type Metadata from "metabase-lib/v1/metadata/Metadata";import type NativeQuery from "metabase-lib/v1/queries/NativeQuery";import type {Card,@@ -26,7 +27,9 @@ import type {User,} from "metabase-types/api";import {+ createMockCard,createMockSegment,+ createMockTemplateTag,createMockUser,createMockUserPermissions,} from "metabase-types/api/mocks";@@ -682,6 +685,88 @@ describe("QB Actions > initializeQB", () => {});});+ describe("native questions with card references", () => {+ const REFERENCED_CARD = createMockCard({ id: 10, name: "Bob's Café" });++ function setupCardReference({ tagName }: { tagName: string }) {+ const actualRunRtkEndpoint = rtkEndpointUtils.runRtkEndpoint;+ jest+ .spyOn(rtkEndpointUtils, "runRtkEndpoint")+ .mockImplementation((request, dispatch, endpoint, options) =>+ endpoint === cardApi.endpoints.getCard+ ? Promise.resolve(REFERENCED_CARD)+ : actualRunRtkEndpoint(request, dispatch, endpoint, options),+ );++ return setup({+ card: createSavedNativeCard({+ dataset_query: {+ type: "native",+ database: SAMPLE_DB_ID,+ native: {+ query: `SELECT * FROM {{${tagName}}}`,+ "template-tags": {+ [tagName]: createMockTemplateTag({+ name: tagName,+ "display-name": tagName,+ type: "card",+ "card-id": REFERENCED_CARD.id,+ }),+ },+ },+ },+ }),+ });+ }++ function getQueryText(card: Card, metadata: Metadata) {+ return checkNotNull(+ new Question(card, metadata).legacyNativeQuery(),+ ).queryText();+ }++ function isDirty(+ { card, originalCard }: { card: Card; originalCard: Card },+ metadata: Metadata,+ ) {+ return new Question(card, metadata).isDirtyComparedTo(+ new Question(originalCard, metadata),+ );+ }++ it("fetches the card that the tag references", async () => {+ await setupCardReference({ tagName: "#10-bobs-cafe" });++ expect(rtkEndpointUtils.runRtkEndpoint).toHaveBeenCalledWith(+ { id: REFERENCED_CARD.id, ignore_error: true },+ expect.anything(),+ cardApi.endpoints.getCard,+ );+ });++ it("keeps a card reference unchanged when its tag name matches the name the frontend generates", async () => {+ const { result, metadata } = await setupCardReference({+ tagName: "#10-bobs-cafe",+ });++ expect(getQueryText(result.card, metadata)).toBe(+ "SELECT * FROM {{#10-bobs-cafe}}",+ );+ expect(isDirty(result, metadata)).toBe(false);+ });++ it("renames a card reference whose tag name does not match the name the frontend generates", async () => {+ const { result, metadata } = await setupCardReference({+ tagName: "#10-foo",+ });++ expect(getQueryText(result.card, metadata)).toBe(+ "SELECT * FROM {{#10-bobs-cafe}}",+ );+ expect(isDirty(result, metadata)).toBe(true);+ });+ });+function startInitializeDB(card: Card,dispatch: jest.Mock,