49 lines
1.6 KiB
TypeScript
49 lines
1.6 KiB
TypeScript
/**
|
|
* Helper to reset the database before each test.
|
|
* Calls the /api/test/reset endpoint on the worker's backend.
|
|
*/
|
|
|
|
import { APIRequestContext } from "@playwright/test";
|
|
import { getBackendUrl } from "./backend-url";
|
|
|
|
/**
|
|
* Reset the database for the current worker.
|
|
* Truncates all tables and re-seeds base data.
|
|
* Retries up to 3 times with exponential backoff to handle transient failures.
|
|
*/
|
|
export async function resetDatabase(request: APIRequestContext): Promise<void> {
|
|
const backendUrl = getBackendUrl();
|
|
const maxRetries = 3;
|
|
let lastError: Error | null = null;
|
|
|
|
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
try {
|
|
const response = await request.post(`${backendUrl}/api/test/reset`);
|
|
|
|
if (response.ok()) {
|
|
// Verify the response body indicates success
|
|
const body = await response.json();
|
|
if (body.status === "reset") {
|
|
return; // Success
|
|
}
|
|
throw new Error(`Unexpected reset response: ${JSON.stringify(body)}`);
|
|
}
|
|
|
|
const text = await response.text();
|
|
throw new Error(`Failed to reset database: ${response.status()} - ${text}`);
|
|
} catch (error) {
|
|
lastError = error instanceof Error ? error : new Error(String(error));
|
|
|
|
// Don't retry on the last attempt
|
|
if (attempt < maxRetries - 1) {
|
|
// Exponential backoff: 100ms, 200ms, 400ms
|
|
const delay = 100 * Math.pow(2, attempt);
|
|
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
|
|
// If we get here, all retries failed
|
|
throw new Error(`Failed to reset database after ${maxRetries} attempts: ${lastError?.message}`);
|
|
}
|