Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
import { create } from "@bufbuild/protobuf";
import { timestampFromMs } from "@bufbuild/protobuf/wkt";
import { render, screen } from "@testing-library/react";
import type { AnchorHTMLAttributes, ReactNode } from "react";
import { describe, expect, test, vi } from "vitest";
import { PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL } from "@/app/router/handles";
import { IssueStatus } from "@/types/proto-es/v1/common_pb";
import {
IssueComment_Approval_Status,
IssueComment_PlanUpdateSchema,
Issue_Type,
IssueComment_ReviewSubmissionSchema,
IssueCommentSchema,
IssueSchema,
ReviewRun_Type,
} from "@/types/proto-es/v1/issue_service_pb";
import {
Plan_ChangeDatabaseConfigSchema,
Plan_CreateDatabaseConfigSchema,
Plan_SpecSchema,
PlanSchema,
} from "@/types/proto-es/v1/plan_service_pb";
import {
getIssueCommentType,
IssueCommentType,
} from "@/stores/app/issueComment";
import { canEditIssueComment, IssueCommentRow } from "./IssueCommentActivity";
vi.mock("react-i18next", async (importOriginal) => ({
...(await importOriginal<typeof import("react-i18next")>()),
useTranslation: () => ({
t: (key: string) => {
if (key === "plan.review.activity.marked-ready-for-review") {
return "marked this plan ready for review";
}
if (key === "plan.spec.change") {
return "Change";
}
return key;
},
}),
}));
const mocks = vi.hoisted(() => ({
hasPermission: vi.fn((_project: unknown, _permission: unknown) => false),
}));
vi.mock("@/utils/iam/permission", async (importOriginal) => ({
...(await importOriginal<typeof import("@/utils/iam/permission")>()),
hasProjectPermissionV2: (project: unknown, permission: unknown) =>
mocks.hasPermission(project, permission),
}));
vi.mock("@/stores/app", () => ({
useAppStore: (selector: (state: unknown) => unknown) => selector({}),
}));
// What usePrincipal resolves: two people and a service account.
vi.mock("@/hooks/usePrincipal", async (importOriginal) => ({
...(await importOriginal<typeof import("@/hooks/usePrincipal")>()),
usePrincipal: (identifier?: string) => {
if (!identifier) return undefined;
if (identifier.includes("alice")) {
return { email: "[email protected]", title: "Alice" };
}
if (identifier.includes("service.bytebase.com")) {
return { email: "[email protected]", title: "Deploy bot" };
}
return { email: "[email protected]", title: "Submitter" };
},
}));
vi.mock("@/components/HumanizeTs", async () => ({
...(await import("@/test-utils/humanizeTs")).humanizeTsStub(),
}));
vi.mock("@/components/monaco", () => ({
ReadonlyDiffMonaco: () => null,
}));
vi.mock("@/components/UserAvatar", () => ({
UserAvatar: () => <span data-testid="user-avatar" />,
}));
vi.mock("@/components/RouterLink", () => ({
RouterLink: ({
children,
preventScrollReset,
to,
...props
}: AnchorHTMLAttributes<HTMLAnchorElement> & {
children: ReactNode;
preventScrollReset?: boolean;
to: unknown;
}) => (
<a
{...props}
data-prevent-scroll-reset={preventScrollReset || undefined}
data-to={JSON.stringify(to)}
>
{children}
</a>
),
}));
const reviewSubmission = create(IssueCommentSchema, {
name: "projects/p1/issues/1/issueComments/1",
creator: "users/[email protected]",
event: {
case: "reviewSubmission",
value: create(IssueComment_ReviewSubmissionSchema),
},
});
const changeSpec = ({
id = "spec-1",
sheet,
target,
}: {
id?: string;
sheet: string;
target: string;
}) =>
create(Plan_SpecSchema, {
id,
config: {
case: "changeDatabaseConfig",
value: create(Plan_ChangeDatabaseConfigSchema, {
sheet,
targets: [`instances/instance-1/databases/${target}`],
}),
},
});
// The issue-update comment the server writes when a rollout is created.
const rolloutCreatedComment = create(IssueCommentSchema, {
creator: "users/[email protected]",
event: {
case: "issueUpdate",
value: {
fromStatus: IssueStatus.OPEN,
toStatus: IssueStatus.DONE,
},
},
});
describe("canEditIssueComment", () => {
const project = { name: "projects/p1" } as Parameters<typeof canEditIssueComment>[1];
const own = create(IssueCommentSchema, {
name: "projects/p1/issues/1/issueComments/9",
creator: "users/[email protected]",
comment: "mine",
});
test("authoring a comment grants no edit without the update permission", () => {
mocks.hasPermission.mockImplementation(
(_project: unknown, permission: unknown) =>
permission === "bb.issueComments.create"
);
expect(canEditIssueComment(own, project)).toBe(false);
});
test("the update permission allows editing a user comment", () => {
mocks.hasPermission.mockImplementation(
(_project: unknown, permission: unknown) =>
permission === "bb.issueComments.update"
);
expect(canEditIssueComment(own, project)).toBe(true);
expect(canEditIssueComment(reviewSubmission, project)).toBe(false);
expect(canEditIssueComment(own, undefined)).toBe(false);
});
test("a review result is never editable: its text is the reviewer's", () => {
mocks.hasPermission.mockImplementation(
(_project: unknown, permission: unknown) =>
permission === "bb.issueComments.update"
);
const result = create(IssueCommentSchema, {
name: "projects/p1/issues/1/issueComments/10",
comment: "DELETE FROM employee has no WHERE clause",
reviewMetadata: { runType: ReviewRun_Type.RULE },
});
expect(canEditIssueComment(result, project)).toBe(false);
});
});
describe("IssueCommentRow", () => {
test("times a comment by when it was written, not when it was edited", () => {
// The two instants sit beside each other and feed the same "edited"
// marker, so the row has to say which one the timestamp is.
const writtenMs = Date.UTC(2026, 2, 2, 12);
render(
<IssueCommentRow
comment={create(IssueCommentSchema, {
creator: "users/[email protected]",
comment: "a remark",
createTime: timestampFromMs(writtenMs),
updateTime: timestampFromMs(writtenMs + 60_000),
})}
isLast
issue={create(IssueSchema, { type: Issue_Type.DATABASE_CHANGE })}
linkless
plan={create(PlanSchema, {})}
/>
);
expect(screen.getByTestId("humanize-ts").textContent).toBe(
String(writtenMs)
);
expect(screen.getByText("(common.edited)")).toBeInTheDocument();
});
test("shows who bypassed review and created the rollout", () => {
const issue = create(IssueSchema, {
type: Issue_Type.DATABASE_CHANGE,
});
const plan = create(PlanSchema, { hasRollout: true });
const comment = create(IssueCommentSchema, {
creator: "users/[email protected]",
event: {
case: "issueUpdate",
value: {
fromStatus: IssueStatus.OPEN,
toStatus: IssueStatus.DONE,
},
},
});
render(
<IssueCommentRow
comment={comment}
isLast
issue={issue}
linkless
plan={plan}
/>
);
expect(screen.getByText("Alice")).toBeInTheDocument();
expect(
screen.getByText("activity.sentence.review-skipped-rollout-created")
).toBeInTheDocument();
});
test("links the rollout of a change plan from Issue Detail", () => {
const { container } = render(
<IssueCommentRow
comment={rolloutCreatedComment}
isLast
issue={create(IssueSchema, { type: Issue_Type.DATABASE_CHANGE })}
plan={create(PlanSchema, {
name: "projects/p1/plans/677",
hasRollout: true,
specs: [changeSpec({ sheet: "s1", target: "db1" })],
})}
/>
);
expect(
screen.getByText(
"activity.sentence.review-skipped-rollout-created-for-plan"
)
).toBeInTheDocument();
expect(container.querySelector("a")?.textContent).toBe("#677");
});
test("a create-database rollout lives on Issue Detail, so no plan link", () => {
const { container } = render(
<IssueCommentRow
comment={rolloutCreatedComment}
isLast
issue={create(IssueSchema, { type: Issue_Type.DATABASE_CHANGE })}
plan={create(PlanSchema, {
name: "projects/p1/plans/677",
hasRollout: true,
specs: [
create(Plan_SpecSchema, {
id: "spec-1",
config: {
case: "createDatabaseConfig",
value: create(Plan_CreateDatabaseConfigSchema, {
target: "instances/i1",
database: "db1",
}),
},
}),
],
})}
/>
);
expect(
screen.getByText("activity.sentence.review-skipped-rollout-created")
).toBeInTheDocument();
expect(container.querySelector("a")).toBeNull();
});
test("names the service account that approved and marks its account type", () => {
const comment = create(IssueCommentSchema, {
creator: "users/[email protected]",
event: {
case: "approval",
value: { status: IssueComment_Approval_Status.APPROVED },
},
});
render(
<IssueCommentRow
comment={comment}
isLast
issue={create(IssueSchema, { type: Issue_Type.DATABASE_CHANGE })}
linkless
/>
);
expect(screen.getByText("Deploy bot")).toBeInTheDocument();
expect(
screen.getByText("settings.members.service-account")
).toBeInTheDocument();
});
test("a person's activity carries no account-type mark", () => {
const comment = create(IssueCommentSchema, {
creator: "users/[email protected]",
event: {
case: "approval",
value: { status: IssueComment_Approval_Status.APPROVED },
},
});
render(
<IssueCommentRow
comment={comment}
isLast
issue={create(IssueSchema, { type: Issue_Type.DATABASE_CHANGE })}
linkless
/>
);
expect(screen.getByText("Alice")).toBeInTheDocument();
expect(screen.queryByText(/settings\.members\./)).not.toBeInTheDocument();
});
test("renders Review Submission as a meaningful Issue Detail activity", () => {
expect(getIssueCommentType(reviewSubmission)).toBe(
IssueCommentType.REVIEW_SUBMISSION
);
const { container } = render(
<IssueCommentRow comment={reviewSubmission} isLast={true} />
);
expect(screen.getByText("Submitter")).toBeInTheDocument();
expect(
screen.getByText("marked this plan ready for review")
).toBeInTheDocument();
expect(container.querySelectorAll(".lucide-send")).toHaveLength(1);
expect(container.querySelector("[data-testid='user-avatar']")).toBeNull();
});
test("links a computed change reference from the plan timeline", () => {
const fromSpec = changeSpec({
sheet: "sheets/1",
target: "orders",
});
const toSpec = changeSpec({
sheet: "sheets/2",
target: "orders",
});
const comment = create(IssueCommentSchema, {
creator: "users/[email protected]",
event: {
case: "planUpdate",
value: create(IssueComment_PlanUpdateSchema, {
fromSpecs: [fromSpec],
toSpecs: [toSpec],
}),
},
});
render(
<IssueCommentRow
comment={comment}
isLast
linkless
plan={create(PlanSchema, {
name: "projects/p1/plans/1",
specs: [toSpec],
})}
renderPlanChangeReference={({ siblings, spec }) => (
<span data-testid="change-reference">
{siblings.indexOf(spec) + 1}{" "}
{spec.config.case === "changeDatabaseConfig"
? spec.config.value.targets[0].split("/").at(-1)
: ""}
</span>
)}
/>
);
expect(
screen.getByText("activity.sentence.modified-sql-of")
).toBeInTheDocument();
const reference = screen.getByTestId("change-reference");
expect(reference).toHaveTextContent("1 orders");
expect(screen.getByText("Change")).toHaveAttribute("aria-hidden", "true");
const link = reference.closest("a");
expect(JSON.parse(link?.dataset.to ?? "")).toEqual({
name: PROJECT_V1_ROUTE_PLAN_DETAIL_SPEC_DETAIL,
params: {
planId: "1",
projectId: "p1",
specId: "spec-1",
},
});
expect(link).toHaveClass(
"text-main",
"hover:text-accent",
"hover:no-underline"
);
expect(link).not.toHaveAttribute("data-prevent-scroll-reset");
});
test("uses the new target in a changed-targets reference", () => {
const fromSpec = changeSpec({
sheet: "sheets/1",
target: "orders",
});
const toSpec = changeSpec({
sheet: "sheets/1",
target: "employees",
});
const comment = create(IssueCommentSchema, {
creator: "users/[email protected]",
event: {
case: "planUpdate",
value: create(IssueComment_PlanUpdateSchema, {
fromSpecs: [fromSpec],
toSpecs: [toSpec],
}),
},
});
render(
<IssueCommentRow
comment={comment}
isLast
plan={create(PlanSchema, {
name: "projects/p1/plans/1",
specs: [toSpec],
})}
renderPlanChangeReference={({ spec }) => (
<span data-testid="change-reference">
{spec.config.case === "changeDatabaseConfig"
? spec.config.value.targets[0].split("/").at(-1)
: ""}
</span>
)}
/>
);
expect(
screen.getByText("activity.sentence.changed-targets-of")
).toBeInTheDocument();
const reference = screen.getByTestId("change-reference");
expect(reference).toHaveTextContent("employees");
expect(reference.closest("a")).not.toHaveAttribute(
"data-prevent-scroll-reset"
);
});
test("uses the historical index and target for a removed change", () => {
const remainingSpec = changeSpec({
sheet: "sheets/1",
target: "orders",
});
const removedSpec = changeSpec({
id: "spec-2",
sheet: "sheets/2",
target: "employees",
});
const comment = create(IssueCommentSchema, {
creator: "users/[email protected]",
event: {
case: "planUpdate",
value: create(IssueComment_PlanUpdateSchema, {
fromSpecs: [remainingSpec, removedSpec],
toSpecs: [remainingSpec],
}),
},
});
render(
<IssueCommentRow
comment={comment}
isLast
plan={create(PlanSchema, {
name: "projects/p1/plans/1",
specs: [remainingSpec],
})}
renderPlanChangeReference={({ siblings, spec }) => (
<span data-testid="change-reference">
{siblings.indexOf(spec) + 1}{" "}
{spec.config.case === "changeDatabaseConfig"
? spec.config.value.targets[0].split("/").at(-1)
: ""}
</span>
)}
/>
);
expect(screen.getByText("activity.sentence.removed-spec")).toBeVisible();
const reference = screen.getByTestId("change-reference");
expect(reference).toHaveTextContent("2 employees");
expect(reference.closest("a")).toBeNull();
});
});