🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
chore: Improve vitest test lifecycle (#13753)
Ben Bachem264db8d81df6
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.ymlindex e3390c958b..a29be0897e 100644--- a/.github/workflows/pipeline.yml+++ b/.github/workflows/pipeline.yml@@ -450,7 +450,7 @@ jobs:LANGFUSE_INIT_USER_PASSWORD: "password"- name: run testsworking-directory: web- run: npx dotenv -e ../.env.test -e ../.env -- vitest run --project server+ run: npx dotenv -e ../.env.test -e ../.env -- vitest run --project server --project server-unit- name: run test-clientif: matrix.deploy-mode == ''working-directory: webdiff --git a/web/package.json b/web/package.jsonindex 545725b0e8..44128f0fdc 100644--- a/web/package.json+++ b/web/package.json@@ -17,10 +17,10 @@"analyze": "dotenv -e ../.env -- next experimental-analyze","clean": "rm -rf node_modules","start": "dotenv -e ../.env -- sh -c 'NEXT_MANUAL_SIG_HANDLE=true next start'",- "test": "vitest run --project server --project in-source",+ "test": "vitest run --project server --project server-unit --project in-source","test:in-source": "vitest run --project in-source","test-client": "vitest run --project client",- "test:watch": "vitest --project client --project server --project in-source",+ "test:watch": "vitest --project client --project server --project server-unit --project in-source","test:e2e": "dotenv -e ../.env.test -e ../.env -- playwright test --reporter=line","test:e2e:server": "vitest run --project e2e-server","build-trace": "dotenv -e ../.env -- next internal trace .next/trace-turbopack",diff --git a/web/src/__tests__/after-teardown.ts b/web/src/__tests__/after-teardown.tsindex 3bfe35b76d..007235af15 100644--- a/web/src/__tests__/after-teardown.ts+++ b/web/src/__tests__/after-teardown.ts@@ -1,26 +1,4 @@-import path from "node:path";import teardown from "@/src/__tests__/teardown";-import { ensureTestDatabaseExists } from "@/src/__tests__/test-utils";--function shouldSkipDatabaseBootstrap() {- const testPath = expect.getState().testPath;-- if (!testPath) {- return false;- }-- return testPath.includes(- `${path.sep}src${path.sep}__tests__${path.sep}server${path.sep}unit${path.sep}`,- );-}--beforeAll(async () => {- if (shouldSkipDatabaseBootstrap()) {- return;- }-- await ensureTestDatabaseExists();-});afterAll(async () => {await teardown();diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.tsindex c27d151ebb..5e3379e2df 100644--- a/web/src/__tests__/test-utils.ts+++ b/web/src/__tests__/test-utils.ts@@ -1,5 +1,3 @@-import { env } from "@/src/env.mjs";-import { prisma } from "@langfuse/shared/src/db";import {EvalExecutionQueue,LLMAsJudgeExecutionQueue,@@ -16,76 +14,6 @@ import {} from "@langfuse/shared/src/server";import { type z } from "zod";-export const ensureTestDatabaseExists = async () => {- // Only create test database if we're in test environment with test database URL- if (- !env.DATABASE_URL.includes("langfuse_test") ||- process.env.NODE_ENV !== "test"- ) {- return; // Not using test database or not in test environment, skip- }-- try {- await prisma.$queryRaw`SELECT 1`;- console.log("Test database already exists and is accessible");-- // Always run migrations to ensure schema is up-to-date- const { execSync } = await import("child_process");- const path = await import("path");- const sharedDir = path.resolve(__dirname, "../../../packages/shared");-- execSync("pnpm run db:migrate", {- cwd: sharedDir,- env: { ...process.env, DATABASE_URL: env.DATABASE_URL },- stdio: "inherit",- });- console.log("Test database schema verified/updated");- } catch {- console.log("Test database not accessible, creating...");-- const url = new URL(env.DATABASE_URL);- const dbName = url.pathname.slice(1); // Remove leading slash- const adminUrl = new URL(env.DATABASE_URL);- adminUrl.pathname = "/postgres";-- const { PrismaClient } = await import("@prisma/client");- const adminPrisma = new PrismaClient({- datasources: {- db: {- url: adminUrl.toString(),- },- },- });-- try {- await adminPrisma.$executeRawUnsafe(`CREATE DATABASE "${dbName}"`);- console.log(`Created test database: ${dbName}`);-- // Migrations- const { execSync } = await import("child_process");- const path = await import("path");- const sharedDir = path.resolve(__dirname, "../../../packages/shared");-- execSync("pnpm run db:migrate", {- cwd: sharedDir,- env: { ...process.env, DATABASE_URL: env.DATABASE_URL },- stdio: "inherit",- });- console.log("Applied migrations to test database");- } catch (createError: any) {- if (createError.message?.includes("already exists")) {- console.log("Test database already exists");- } else {- console.error("Failed to create test database:", createError);- }- } finally {- await adminPrisma.$disconnect();- }- }-- // ClickHouse uses default database (no setup needed)-};-export const getQueues = () => {const queues: string[] = Object.values(QueueName);queues.push(diff --git a/web/src/__tests__/vitest-global-teardown.ts b/web/src/__tests__/vitest-global-teardown.tsdeleted file mode 100644index 65611c84f9..0000000000--- a/web/src/__tests__/vitest-global-teardown.ts+++ /dev/null@@ -1,5 +0,0 @@-import teardownFn from "./teardown";--export async function teardown() {- await teardownFn();-}diff --git a/web/src/__tests__/vitest-test-db-setup.ts b/web/src/__tests__/vitest-test-db-setup.tsnew file mode 100644index 0000000000..4a3a0483ff--- /dev/null+++ b/web/src/__tests__/vitest-test-db-setup.ts@@ -0,0 +1,90 @@+const migrateTestDatabase = async (databaseUrl: string) => {+ const { execSync } = await import("child_process");+ const path = await import("path");+ const sharedDir = path.resolve(__dirname, "../../../packages/shared");++ execSync(+ "dotenv -e ../../.env.test -e ../../.env -- npx prisma migrate deploy",+ {+ cwd: sharedDir,+ env: { ...process.env, DATABASE_URL: databaseUrl },+ stdio: "inherit",+ },+ );++ execSync(+ "dotenv -e ../../.env.test -e ../../.env -- npx prisma generate --no-hints",+ {+ cwd: sharedDir,+ env: { ...process.env, DATABASE_URL: databaseUrl },+ stdio: "inherit",+ },+ );+};++const ensureTestDatabaseExists = async () => {+ const databaseUrl = process.env.DATABASE_URL;++ if (+ !databaseUrl?.includes("langfuse_test") ||+ process.env.NODE_ENV !== "test"+ ) {+ return;+ }++ const { PrismaClient } = await import("@prisma/client");+ const prisma = new PrismaClient({+ datasources: {+ db: {+ url: databaseUrl,+ },+ },+ });++ try {+ await prisma.$queryRaw`SELECT 1`;+ console.log("Test database already exists and is accessible");+ } catch {+ console.log("Test database not accessible, creating...");++ const url = new URL(databaseUrl);+ const dbName = url.pathname.slice(1);+ const adminUrl = new URL(databaseUrl);+ adminUrl.pathname = "/postgres";++ const adminPrisma = new PrismaClient({+ datasources: {+ db: {+ url: adminUrl.toString(),+ },+ },+ });++ try {+ await adminPrisma.$executeRawUnsafe(`CREATE DATABASE "${dbName}"`);+ console.log(`Created test database: ${dbName}`);+ } catch (createError) {+ const message =+ createError instanceof Error+ ? createError.message+ : String(createError);++ if (message.includes("already exists")) {+ console.log("Test database already exists");+ } else {+ console.error("Failed to create test database:", createError);+ }+ } finally {+ await adminPrisma.$disconnect();+ }+ } finally {+ await prisma.$disconnect();+ }++ await migrateTestDatabase(databaseUrl);+ console.log("Test database schema verified/updated");+};++export async function setup() {+ await ensureTestDatabaseExists();+}diff --git a/web/vitest.config.mts b/web/vitest.config.mtsindex 9cfb3d73fd..d4df18337e 100644--- a/web/vitest.config.mts+++ b/web/vitest.config.mts@@ -60,10 +60,24 @@ export default defineConfig({test: {name: "server",include: ["src/**/server/**/*.servertest.{ts,tsx}"],- exclude: [...sharedExclude, "src/__e2e__/**"],+ exclude: [+ ...sharedExclude,+ "src/__e2e__/**",+ "src/__tests__/server/unit/**",+ ],+ environment: "node",+ setupFiles: ["./src/__tests__/after-teardown.ts"],+ globalSetup: ["./src/__tests__/vitest-test-db-setup.ts"],+ },+ },+ {+ extends: true,+ test: {+ name: "server-unit",+ include: ["src/__tests__/server/unit/**/*.servertest.{ts,tsx}"],+ exclude: sharedExclude,environment: "node",setupFiles: ["./src/__tests__/after-teardown.ts"],- globalSetup: ["./src/__tests__/vitest-global-teardown.ts"],},},{@@ -74,7 +88,7 @@ export default defineConfig({exclude: [...sharedExclude, "src/__tests__/**"],environment: "node",setupFiles: ["./src/__tests__/after-teardown.ts"],- globalSetup: ["./src/__tests__/vitest-global-teardown.ts"],+ globalSetup: ["./src/__tests__/vitest-test-db-setup.ts"],},},],