Skip to content

armgit / kaneo

Public Imported from GitHub
0

⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.

feat(ci): add api project integration harness

Tin8559555e5542
diff --git a/tests/api-integration/helpers/auth.ts b/tests/api-integration/helpers/auth.ts
new file mode 100644
index 000000000..77dd944c6
--- /dev/null
+++ b/tests/api-integration/helpers/auth.ts
@@ -0,0 +1,29 @@
+import type { Session, User } from "better-auth/types";
+import { vi } from "vitest";
+import { auth } from "../../../apps/api/src/auth";
+
+function createSession(userId: string): Session {
+ const now = new Date();
+
+ return {
+ id: `session-${userId}`,
+ token: `token-${userId}`,
+ userId,
+ expiresAt: new Date(now.getTime() + 60 * 60 * 1000),
+ createdAt: now,
+ updatedAt: now,
+ ipAddress: null,
+ userAgent: null,
+ };
+}
+
+export function mockAuthenticatedSession(user: User) {
+ return vi.spyOn(auth.api, "getSession").mockResolvedValue({
+ session: createSession(user.id),
+ user,
+ });
+}
+
+export function mockAnonymousSession() {
+ return vi.spyOn(auth.api, "getSession").mockResolvedValue(null);
+}
diff --git a/tests/api-integration/helpers/database.ts b/tests/api-integration/helpers/database.ts
new file mode 100644
index 000000000..082b21436
--- /dev/null
+++ b/tests/api-integration/helpers/database.ts
@@ -0,0 +1,108 @@
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { sql } from "drizzle-orm";
+import { migrate } from "drizzle-orm/node-postgres/migrator";
+import { Client } from "pg";
+import db from "../../../apps/api/src/database";
+
+const currentDir = dirname(fileURLToPath(import.meta.url));
+const migrationsFolder = resolve(currentDir, "../../../apps/api/drizzle");
+
+let migrationPromise: Promise<void> | null = null;
+
+function getDatabaseName(connectionString: string) {
+ return new URL(connectionString).pathname.replace(/^\//, "");
+}
+
+function getAdminDatabaseUrl(connectionString: string) {
+ const url = new URL(connectionString);
+ const databaseName = getDatabaseName(connectionString);
+
+ if (databaseName.endsWith("_test")) {
+ url.pathname = `/${databaseName.slice(0, -5) || "postgres"}`;
+ }
+
+ return url.toString();
+}
+
+function quoteIdentifier(identifier: string) {
+ return `"${identifier.replaceAll('"', '""')}"`;
+}
+
+async function ensureTestDatabaseExists() {
+ const connectionString = process.env.DATABASE_URL;
+
+ if (!connectionString) {
+ throw new Error("DATABASE_URL must be defined for integration tests");
+ }
+
+ const databaseName = getDatabaseName(connectionString);
+ const adminClient = new Client({
+ connectionString: getAdminDatabaseUrl(connectionString),
+ });
+
+ await adminClient.connect();
+
+ try {
+ const result = await adminClient.query(
+ "SELECT 1 FROM pg_database WHERE datname = $1",
+ [databaseName],
+ );
+
+ if (result.rowCount === 0) {
+ await adminClient.query(
+ `CREATE DATABASE ${quoteIdentifier(databaseName)}`,
+ );
+ }
+ } finally {
+ await adminClient.end();
+ }
+}
+
+export async function ensureTestDatabaseMigrated() {
+ if (!migrationPromise) {
+ migrationPromise = (async () => {
+ await ensureTestDatabaseExists();
+ await migrate(db, {
+ migrationsFolder,
+ });
+ })();
+ }
+
+ await migrationPromise;
+}
+
+export async function resetTestDatabase() {
+ await ensureTestDatabaseMigrated();
+
+ await db.execute(
+ sql.raw(`
+ TRUNCATE TABLE
+ "activity",
+ "account",
+ "apikey",
+ "asset",
+ "column",
+ "comment",
+ "external_link",
+ "github_integration",
+ "integration",
+ "invitation",
+ "label",
+ "notification",
+ "project",
+ "session",
+ "task",
+ "task_relation",
+ "team",
+ "team_member",
+ "time_entry",
+ "verification",
+ "workflow_rule",
+ "workspace",
+ "workspace_member",
+ "user"
+ RESTART IDENTITY CASCADE
+ `),
+ );
+}
diff --git a/tests/api-integration/project.test.ts b/tests/api-integration/project.test.ts
new file mode 100644
index 000000000..48f78ca21
--- /dev/null
+++ b/tests/api-integration/project.test.ts
@@ -0,0 +1,169 @@
+import { randomUUID } from "node:crypto";
+import { eq } from "drizzle-orm";
+import { beforeEach, describe, expect, it } from "vitest";
+import db, { schema } from "../../apps/api/src/database";
+import { createApp } from "../../apps/api/src/index";
+import { mockAnonymousSession, mockAuthenticatedSession } from "./helpers/auth";
+import { resetTestDatabase } from "./helpers/database";
+
+type SeededMemberContext = {
+ user: typeof schema.userTable.$inferSelect;
+ workspace: typeof schema.workspaceTable.$inferSelect;
+};
+
+async function createWorkspaceMember(): Promise<SeededMemberContext> {
+ const userId = `user-${randomUUID()}`;
+ const workspaceId = `workspace-${randomUUID()}`;
+
+ const [user] = await db
+ .insert(schema.userTable)
+ .values({
+ id: userId,
+ email: `${userId}@example.com`,
+ emailVerified: true,
+ name: "Integration Test User",
+ })
+ .returning();
+
+ const [workspace] = await db
+ .insert(schema.workspaceTable)
+ .values({
+ id: workspaceId,
+ createdAt: new Date(),
+ name: "Integration Test Workspace",
+ slug: `workspace-${randomUUID()}`,
+ })
+ .returning();
+
+ await db.insert(schema.workspaceUserTable).values({
+ workspaceId: workspace.id,
+ userId: user.id,
+ role: "owner",
+ joinedAt: new Date(),
+ });
+
+ return { user, workspace };
+}
+
+describe("API integration: project creation", () => {
+ beforeEach(async () => {
+ await resetTestDatabase();
+ });
+
+ it("rejects unauthenticated project creation requests", async () => {
+ mockAnonymousSession();
+ const { app } = createApp();
+
+ const response = await app.request("/api/project", {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ workspaceId: "workspace-missing",
+ name: "Unauthorized Project",
+ icon: "Folder",
+ slug: "unauthorized-project",
+ }),
+ });
+
+ expect(response.status).toBe(401);
+ await expect(response.text()).resolves.toBe("Unauthorized");
+ });
+
+ it("creates a project for a workspace member and seeds default columns", async () => {
+ const member = await createWorkspaceMember();
+ mockAuthenticatedSession(member.user);
+ const { app } = createApp();
+
+ const response = await app.request("/api/project", {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ workspaceId: member.workspace.id,
+ name: "Roadmap",
+ icon: "FolderKanban",
+ slug: "roadmap",
+ }),
+ });
+
+ expect(response.status).toBe(200);
+ const payload =
+ (await response.json()) as typeof schema.projectTable.$inferSelect;
+
+ expect(payload).toMatchObject({
+ workspaceId: member.workspace.id,
+ name: "Roadmap",
+ icon: "FolderKanban",
+ slug: "roadmap",
+ });
+
+ const persistedProject = await db.query.projectTable.findFirst({
+ where: eq(schema.projectTable.id, payload.id),
+ });
+
+ expect(persistedProject).toMatchObject({
+ id: payload.id,
+ workspaceId: member.workspace.id,
+ name: "Roadmap",
+ slug: "roadmap",
+ });
+
+ const columns = await db.query.columnTable.findMany({
+ where: eq(schema.columnTable.projectId, payload.id),
+ orderBy: (column, { asc }) => [asc(column.position)],
+ });
+
+ expect(columns).toHaveLength(4);
+ expect(columns.map((column) => column.slug)).toEqual([
+ "to-do",
+ "in-progress",
+ "in-review",
+ "done",
+ ]);
+ expect(columns.map((column) => column.isFinal)).toEqual([
+ false,
+ false,
+ false,
+ true,
+ ]);
+ });
+
+ it("rejects project creation for users outside the workspace", async () => {
+ const member = await createWorkspaceMember();
+ const outsiderId = `user-${randomUUID()}`;
+
+ const [outsider] = await db
+ .insert(schema.userTable)
+ .values({
+ id: outsiderId,
+ email: `${outsiderId}@example.com`,
+ emailVerified: true,
+ name: "Outsider",
+ })
+ .returning();
+
+ mockAuthenticatedSession(outsider);
+ const { app } = createApp();
+
+ const response = await app.request("/api/project", {
+ method: "POST",
+ headers: {
+ "content-type": "application/json",
+ },
+ body: JSON.stringify({
+ workspaceId: member.workspace.id,
+ name: "Forbidden Project",
+ icon: "Folder",
+ slug: "forbidden-project",
+ }),
+ });
+
+ expect(response.status).toBe(403);
+ await expect(response.text()).resolves.toBe(
+ "You don't have access to this workspace",
+ );
+ });
+});
diff --git a/tests/api-integration/setup.ts b/tests/api-integration/setup.ts
index ea0ce746d..5fd220024 100644
--- a/tests/api-integration/setup.ts
+++ b/tests/api-integration/setup.ts
@@ -1,13 +1,41 @@
-import { vi } from "vitest";
+import { existsSync, readFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterEach, vi } from "vitest";
-vi.mock("dotenv-mono", () => ({
- config: () => ({}),
-}));
+function deriveTestDatabaseUrl(connectionString: string) {
+ const url = new URL(connectionString);
+ const databaseName = url.pathname.replace(/^\//, "");
+
+ if (!databaseName || databaseName.endsWith("_test")) {
+ return connectionString;
+ }
+
+ url.pathname = `/${databaseName}_test`;
+ return url.toString();
+}
+
+function readDatabaseUrlFromEnvFile() {
+ const currentDir = dirname(fileURLToPath(import.meta.url));
+ const envPath = resolve(currentDir, "../../.env");
+
+ if (!existsSync(envPath)) {
+ return null;
+ }
+
+ const envFile = readFileSync(envPath, "utf8");
+ const match = envFile.match(/^DATABASE_URL=(.+)$/m);
+ return match?.[1]?.trim() || null;
+}
process.env.NODE_ENV = "test";
process.env.AUTH_SECRET = "test-secret-with-at-least-32-chars";
process.env.DATABASE_URL =
- "postgresql://postgres:postgres@localhost:5432/kaneo_test";
+ process.env.DATABASE_URL ||
+ deriveTestDatabaseUrl(
+ readDatabaseUrlFromEnvFile() ||
+ "postgresql://postgres:postgres@localhost:5432/kaneo_test",
+ );
process.env.KANEO_API_URL = "http://localhost:1337";
process.env.KANEO_CLIENT_URL = "http://localhost:5173";
process.env.DISABLE_GUEST_ACCESS = "false";
@@ -27,3 +55,7 @@ process.env.DISCORD_CLIENT_ID = "";
process.env.DISCORD_CLIENT_SECRET = "";
process.env.CUSTOM_OAUTH_CLIENT_ID = "";
process.env.CUSTOM_OAUTH_CLIENT_SECRET = "";
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});