Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/api/bunfig.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[test]
preload = ["./test/setup-env.ts"]
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import {
afterEach,
beforeEach,
describe,
expect,
mock,
spyOn,
test,
} from "bun:test";
import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
import { db } from "@superset/db/client";
import * as accountPurge from "@superset/trpc/account-purge";
import type { SQL } from "drizzle-orm";
import { PgDialect } from "drizzle-orm/pg-core";
import * as singleFlight from "@/lib/singleFlight";
import * as verifyQstash from "@/lib/verifyQstash";
import { stub } from "../../../../../../test/stub";

interface FakeUser {
id: string;
Expand All @@ -29,39 +26,35 @@ const dialect = new PgDialect();
const params = (condition: SQL) => dialect.sqlToQuery(condition).params;
const userById = (id: string) => fakeUsers.find((user) => user.id === id);

mock.module("@/lib/verifyQstash", () => ({
stub(verifyQstash, {
verifyQstashRequest: async () => null,
}));
});

// Evaluates the route's own predicate: the cutoff is read back out of the
// query so the test exercises the window arithmetic, not a copy of it.
mock.module("@superset/db/client", () => ({
db: {
select: () => ({
from: () => ({
where: (condition: SQL) => {
const cutoff = new Date(params(condition)[0] as string);
const matching = fakeUsers
.filter(
(user) =>
user.deletedAt === null && user.deletionRequestedAt < cutoff,
)
.sort(
(a, b) =>
a.deletionRequestedAt.getTime() -
b.deletionRequestedAt.getTime(),
);
return {
orderBy: async () => matching.map(({ id }) => ({ id })),
};
},
}),
stub(db, {
select: () => ({
from: () => ({
where: (condition: SQL) => {
const cutoff = new Date(params(condition)[0] as string);
const matching = fakeUsers
.filter(
(user) =>
user.deletedAt === null && user.deletionRequestedAt < cutoff,
)
.sort(
(a, b) =>
a.deletionRequestedAt.getTime() - b.deletionRequestedAt.getTime(),
);
return {
orderBy: async () => matching.map(({ id }) => ({ id })),
};
},
}),
},
dbWs: {},
}));
}),
});

mock.module("@/lib/singleFlight", () => ({
stub(singleFlight, {
singleFlight: async (_job: string, fn: (tx: unknown) => Promise<unknown>) => {
if (lockHeld) return { ran: false };
const tx = {
Expand All @@ -77,9 +70,9 @@ mock.module("@/lib/singleFlight", () => ({
};
return { ran: true, result: await fn(tx) };
},
}));
});

mock.module("@superset/trpc/account-purge", () => ({
stub(accountPurge, {
findOrganizationSolelyOwnedBy: async (userId: string) =>
soleOwnerOf.get(userId) ?? null,
purgeAccount: async (userId: string) => {
Expand All @@ -88,7 +81,7 @@ mock.module("@superset/trpc/account-purge", () => ({
const user = userById(userId);
if (user) user.deletedAt = NOW;
},
}));
});

const { POST } = await import("./route");

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { beforeEach, describe, expect, mock, test } from "bun:test";
import { db } from "@superset/db/client";
import * as connectors from "@superset/trpc/connectors";
import * as linear from "@superset/trpc/integrations/linear";
import * as syncPolicy from "@superset/trpc/sync-policy";
import * as automationEvent from "@/lib/automations/ingestAutomationEvent";
import * as webhookDelivery from "@/lib/ingest/recordWebhookDelivery";
import { stub } from "../../../../../../test/stub";

const ORG = "org-1";
const WORKSPACE = "linear-workspace-1";
Expand All @@ -16,48 +23,43 @@ function connection(id: string, userId: string) {
}

let subscribers: ReturnType<typeof connection>[] = [];
// `mock.module` is process-wide, so every export the real module has must be
// here: another file's import of `connectionBotToken` resolves against this
// stub too.
mock.module("@superset/trpc/connectors", () => ({
stub(connectors, {
accountConnection: mock(async () => subscribers[0] ?? null),
accountConnections: mock(async () => subscribers),
connectionBotToken: mock(async () => "bot-token"),
}));
});

// The plan gate is exercised on the route, not here: these cases are about
// how one delivery fans out across connections.
mock.module("@superset/trpc/sync-policy", () => ({
stub(syncPolicy, {
organizationSyncs: mock(() => undefined),
organizationSyncsNow: mock(async () => true),
syncingOrganizationIds: mock(
async (organizationIds: string[]) => new Set(organizationIds),
),
}));
});

mock.module("@superset/trpc/integrations/linear", () => ({
stub(linear, {
getLinearClient: mock(async () => null),
linearClientFor: mock(async () => null),
isLinearAuthError: () => false,
mapPriorityFromLinear: () => null,
}));
});

let eventSeq = 0;
mock.module("@/lib/ingest/recordWebhookDelivery", () => ({
stub(webhookDelivery, {
recordWebhookDelivery: mock(async () => ({
id: `webhook-event-${++eventSeq}`,
status: "pending",
retryCount: 0,
receivedAt: new Date(),
})),
}));
});

const ingestCalls: Array<{
connectionId: string | null;
externalEventId: string;
ownerUserId: string | null;
}> = [];
mock.module("@/lib/automations/ingestAutomationEvent", () => ({
stub(automationEvent, {
ingestAutomationEvent: mock(async (_db: unknown, delivery: never) => {
const d = delivery as {
skip?: string;
Expand All @@ -75,11 +77,11 @@ mock.module("@/lib/automations/ingestAutomationEvent", () => ({
});
return { status: "dispatched", eventId: "e" };
}),
}));
});

mock.module("@superset/db/client", () => ({
db: { update: () => ({ set: () => ({ where: async () => undefined }) }) },
}));
stub(db, {
update: () => ({ set: () => ({ where: async () => undefined }) }),
});

const { processDelivery } = await import("./processDelivery");

Expand Down
34 changes: 15 additions & 19 deletions apps/api/src/app/api/integrations/linear/webhook/route.test.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
import { beforeEach, describe, expect, mock, test } from "bun:test";

mock.module("@/env", () => ({
env: { LINEAR_WEBHOOK_SECRET: "test-secret" },
}));

mock.module("@linear/sdk/webhooks", () => ({
LINEAR_WEBHOOK_SIGNATURE_HEADER: "linear-signature",
LinearWebhookClient: class {
parseData(body: Buffer) {
return JSON.parse(body.toString());
}
},
}));
import { LinearWebhookClient } from "@linear/sdk/webhooks";
import * as webhookDelivery from "@/lib/ingest/recordWebhookDelivery";
import { stub } from "../../../../../../test/stub";
import * as processDelivery from "./processDelivery";
import * as queue from "./queue";

stub(LinearWebhookClient.prototype, {
parseData: (body: Buffer) => JSON.parse(body.toString()),
});

let recorded: {
id: string;
Expand All @@ -21,27 +17,27 @@ let recorded: {
} | null = null;
let recordCalls = 0;
let recordThrows: Error | null = null;
mock.module("@/lib/ingest/recordWebhookDelivery", () => ({
stub(webhookDelivery, {
recordWebhookDelivery: mock(async () => {
recordCalls += 1;
if (recordThrows) throw recordThrows;
return recorded;
}),
}));
});

let subscribed = true;
mock.module("./processDelivery", () => ({
stub(processDelivery, {
hasActiveSubscriber: mock(async () => subscribed),
}));
});

let enqueued: unknown[] = [];
let enqueueThrows: Error | null = null;
mock.module("./queue", () => ({
stub(queue, {
enqueueLinearDelivery: mock(async (work: unknown) => {
if (enqueueThrows) throw enqueueThrows;
enqueued.push(work);
}),
}));
});

const { POST } = await import("./route");

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,16 @@
import { beforeEach, expect, mock, test } from "bun:test";
import { db } from "@superset/db/client";
import * as connectors from "@superset/trpc/connectors";
import { Client } from "@upstash/qstash";
import { posthog } from "@/lib/analytics";
import { stub } from "../../../../../../../test/stub";
import * as slackUserLink from "../../lib/find-slack-user-link";
import * as agentDelivery from "../utils/agent-delivery";
import * as connectUrl from "../utils/generate-connect-url";
import * as agent from "../utils/run-agent";
import * as slackClient from "../utils/slack-client";
import * as slackImageAssets from "../utils/slack-image-assets";
import * as threadSessions from "../utils/thread-sessions";

let postCount = 0;
const postMessage = mock(async (_args: Record<string, unknown>) => ({
Expand Down Expand Up @@ -28,57 +40,39 @@ const claim = mock(
const finish = mock(async (_id: string, _succeeded: boolean) => {});
const release = mock(async (_id: string) => {});
const publishJSON = mock(async (_options: unknown) => ({}));
mock.module("@upstash/qstash", () => ({
Client: class {
publishJSON = publishJSON;
},
}));
stub(Client.prototype, { publishJSON });
const findLink = mock(
async (_args: unknown): Promise<{ userId: string } | undefined> => ({
userId: "linked-user",
}),
);
mock.module("@superset/db/client", () => ({
db: {
query: {
subscriptions: { findFirst: async () => ({ id: "subscription" }) },
},
},
}));
// `mock.module` is process-wide, so every export the real module has must be
// here: another file's import of one of these resolves against this stub too.
mock.module("@superset/trpc/connectors", () => ({
stub(db.query.subscriptions, {
findFirst: async () => ({ id: "subscription" }),
});
stub(connectors, {
accountConnection: async () => ({ organizationId: "org" }),
accountConnections: async () => [{ organizationId: "org" }],
connectionBotToken: async () => "token",
}));
mock.module("@/env", () => ({
env: {
NEXT_PUBLIC_WEB_URL: "https://app.superset.sh",
NEXT_PUBLIC_API_URL: "https://api.test",
QSTASH_TOKEN: "qstash-token",
},
}));
mock.module("@/lib/analytics", () => ({ posthog: { capture: () => {} } }));
mock.module("../../lib/find-slack-user-link", () => ({
});
stub(posthog, { capture: () => {} });
stub(slackUserLink, {
findSlackUserLink: findLink,
}));
mock.module("../utils/generate-connect-url", () => ({
});
stub(connectUrl, {
generateConnectUrl: () => "https://app.superset.sh/connect",
}));
mock.module("../utils/run-agent", () => ({
});
stub(agent, {
runSlackAgent: runAgent,
resolveUserMentions: async () => (text: string) => text,
formatErrorForSlack: async () => "Unable to finish",
mentionsPlugin: (text: string, plugin: { displayName: string }) =>
text.toLowerCase().includes(plugin.displayName.toLowerCase()),
SlackAgentError: class extends Error {},
}));
mock.module("../utils/agent-delivery", () => ({
});
stub(agentDelivery, {
claimAgentDelivery: claim,
finishAgentDelivery: finish,
releaseAgentDelivery: release,
}));
});
const session = {
id: "thread-session",
quiet: false,
Expand Down Expand Up @@ -109,7 +103,7 @@ const takeQueued = mock(
);
const completeHandoff = mock(async (_id: string, _handoff: string) => {});
const abandonHandoff = mock(async (_id: string, _handoff: string) => {});
mock.module("../utils/thread-sessions", () => ({
stub(threadSessions, {
beginThreadRun: beginThread,
finishThreadRun: finishThread,
setThreadQuiet: setQuiet,
Expand All @@ -131,11 +125,8 @@ mock.module("../utils/thread-sessions", () => ({
},
renderThreadMemory: (entities: { label: string }[]) =>
entities.map((e) => e.label).join(", "),
}));
const { slackRateLimitRetryAfterMs } = await import(
"../utils/slack-client/request-bounds"
);
mock.module("../utils/slack-client", () => ({
});
stub(slackClient, {
createSlackClient: (_token: string, options: { deadline?: number } = {}) => {
const bounded =
<A, R>(call: (args: A) => Promise<R>) =>
Expand All @@ -156,14 +147,11 @@ mock.module("../utils/slack-client", () => ({
};
},
isUnpostableChannelError: () => false,
slackRateLimitRetryAfterMs,
}));
// Mock the barrel only; the image utility's own tests import its implementation.
mock.module("../utils/slack-image-assets", () => ({
});
stub(slackImageAssets, {
extractSlackImageAssets: async () => [],
formatSlackImageAssetError: () => "Invalid image",
SlackImageAssetError: class extends Error {},
}));
});
const { processAgentMessage } = await import("./process-agent-message");
const params = {
teamId: "T1",
Expand Down
Loading
Loading