Compare commits
5 Commits
a9138cfbe4
...
f27efebd82
| Author | SHA1 | Date | |
|---|---|---|---|
| f27efebd82 | |||
| 30ea4e4e86 | |||
| 75cb6ed29d | |||
| fa13ed86c9 | |||
| 66e574d5ec |
+26
-32
@@ -1,54 +1,48 @@
|
|||||||
# EuchreCamp Environment Configuration
|
# EuchreCamp Environment Configuration
|
||||||
# Copy this file to .env and fill in your values
|
# ============================================
|
||||||
|
# Copy this file to .env (for local dev) or use
|
||||||
|
# .env.development / .env.ci for specific environments
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
# Database Configuration
|
# Database Configuration
|
||||||
# ============================================
|
# ============================================
|
||||||
# PostgreSQL connection string
|
# IMPORTANT: Use the appropriate DATABASE_URL for your environment:
|
||||||
# Format: postgresql://username:password@host:port/database
|
#
|
||||||
DATABASE_URL=postgresql://euchre:euchrepassword@localhost:5432/euchre_camp
|
# - Development (ephemeral, synced from prod): euchre_camp_dev
|
||||||
|
# - CI/Testing (reset before each run): euchre_camp_ci
|
||||||
|
# - Production (DO NOT USE FOR TESTS): euchre_camp
|
||||||
|
#
|
||||||
|
# The .credentials file in the project root contains
|
||||||
|
# the actual connection strings - DO NOT commit .credentials
|
||||||
|
|
||||||
# Shadow database for Prisma migrations (optional for PostgreSQL)
|
|
||||||
DATABASE_SHADOW_URL=postgresql://euchre:euchrepassword@localhost:5432/euchre_camp_shadow
|
|
||||||
|
|
||||||
# Database provider (postgresql)
|
|
||||||
DATABASE_PROVIDER=postgresql
|
DATABASE_PROVIDER=postgresql
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
# Better Auth Configuration
|
# Better Auth Configuration
|
||||||
# ============================================
|
# ============================================
|
||||||
# Secret key for session encryption (generate a strong random string)
|
# Generate a new secret with: openssl rand -base64 32
|
||||||
# Run: openssl rand -base64 32
|
BETTER_AUTH_SECRET=generate-new-secret-in-production
|
||||||
BETTER_AUTH_SECRET=your-secret-key-change-in-production
|
|
||||||
|
|
||||||
# Base URL for authentication callbacks
|
# Base URL - update for production
|
||||||
# For production: https://your-domain.com
|
|
||||||
BETTER_AUTH_URL=http://localhost:3000
|
BETTER_AUTH_URL=http://localhost:3000
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
# Application Configuration
|
# Application Configuration
|
||||||
# ============================================
|
# ============================================
|
||||||
# Environment: development, production, test
|
NODE_ENV=development
|
||||||
NODE_ENV=production
|
|
||||||
|
|
||||||
# Trusted origins for CORS and authentication
|
# Comma-separated list of trusted origins
|
||||||
# Add your domain(s) for production
|
|
||||||
TRUSTED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
|
TRUSTED_ORIGINS=http://localhost:3000,http://127.0.0.1:3000
|
||||||
|
|
||||||
# ============================================
|
# ============================================
|
||||||
# Optional: External Services
|
# Environment-Specific Overrides
|
||||||
# ============================================
|
# ============================================
|
||||||
# If using external database (e.g., Supabase, Railway)
|
# For development (.env.development):
|
||||||
# DATABASE_URL=postgresql://user:pass@host:port/db
|
# DATABASE_URL from .credentials (euchre_camp_dev)
|
||||||
|
# NODE_ENV=development
|
||||||
# If using external auth provider
|
# BETTER_AUTH_URL=http://localhost:3000
|
||||||
# BETTER_AUTH_URL=https://your-app.com
|
#
|
||||||
|
# For CI (.env.ci):
|
||||||
# ============================================
|
# DATABASE_URL from .credentials (euchre_camp_ci)
|
||||||
# CasaOS Deployment Notes
|
# NODE_ENV=test
|
||||||
# ============================================
|
# BETTER_AUTH_URL=http://localhost:3000
|
||||||
# When deploying to CasaOS, set these via the UI:
|
|
||||||
# 1. DATABASE_URL: Your PostgreSQL connection string
|
|
||||||
# 2. BETTER_AUTH_SECRET: Generate with: openssl rand -base64 32
|
|
||||||
# 3. BETTER_AUTH_URL: Your app's public URL
|
|
||||||
# 4. TRUSTED_ORIGINS: Your app's public URL(s)
|
|
||||||
@@ -27,6 +27,29 @@ jobs:
|
|||||||
- name: Run unit tests
|
- name: Run unit tests
|
||||||
run: bun test src/__tests__/unit/ src/__tests__/*.test.tsx src/__tests__/auth-simple.test.ts
|
run: bun test src/__tests__/unit/ src/__tests__/*.test.tsx src/__tests__/auth-simple.test.ts
|
||||||
|
|
||||||
|
acceptance-tests:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
container:
|
||||||
|
image: docker.notsosm.art/euchre-camp/ci-base:latest
|
||||||
|
options: --user root
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: bun install
|
||||||
|
|
||||||
|
- name: Generate Prisma client
|
||||||
|
run: bun x prisma generate
|
||||||
|
env:
|
||||||
|
DATABASE_URL: postgresql://user:pass@localhost:5432/dummy
|
||||||
|
|
||||||
|
- name: Run acceptance tests
|
||||||
|
run: DATABASE_URL="${{ vars.CI_DATABASE_URL }}" bun test:acceptance
|
||||||
|
env:
|
||||||
|
CI: true
|
||||||
|
|
||||||
analyze-bump-type:
|
analyze-bump-type:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
needs: unit-tests
|
needs: unit-tests
|
||||||
|
|||||||
@@ -15,6 +15,8 @@
|
|||||||
/playwright/.auth/
|
/playwright/.auth/
|
||||||
/test-results
|
/test-results
|
||||||
/cookies.txt
|
/cookies.txt
|
||||||
|
.env.test
|
||||||
|
prisma/ci.db
|
||||||
|
|
||||||
# next.js
|
# next.js
|
||||||
/.next/
|
/.next/
|
||||||
@@ -59,3 +61,4 @@ playwright-report/
|
|||||||
|
|
||||||
cucumber-pretty
|
cucumber-pretty
|
||||||
.env.production
|
.env.production
|
||||||
|
.credentials
|
||||||
|
|||||||
+58
-83
@@ -4,40 +4,28 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { chromium, type FullConfig } from '@playwright/test';
|
import { chromium, type FullConfig } from '@playwright/test';
|
||||||
import { prisma } from '@/lib/prisma';
|
import { PrismaClient } from '@prisma/client';
|
||||||
import { cleanupAllTestData } from '@/__tests__/test-utils';
|
import { PrismaPg } from '@prisma/adapter-pg';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
|
|
||||||
// Load .env file first, then .env.development (which will override .env)
|
|
||||||
const envPath = path.resolve(process.cwd(), '.env');
|
|
||||||
const envDevPath = path.resolve(process.cwd(), '.env.development');
|
|
||||||
|
|
||||||
// Load base .env file
|
|
||||||
if (fs.existsSync(envPath)) {
|
|
||||||
require('dotenv').config({ path: envPath });
|
|
||||||
}
|
|
||||||
|
|
||||||
// Load .env.development file (will override .env settings)
|
|
||||||
if (fs.existsSync(envDevPath)) {
|
|
||||||
require('dotenv').config({ path: envDevPath, override: true });
|
|
||||||
}
|
|
||||||
|
|
||||||
const authFile = 'playwright/.auth/user.json';
|
const authFile = 'playwright/.auth/user.json';
|
||||||
const adminAuthFile = 'playwright/.auth/admin.json';
|
const adminAuthFile = 'playwright/.auth/admin.json';
|
||||||
|
|
||||||
// Check if we're using the dev database
|
function isDatabase(url: string, name: string): boolean {
|
||||||
function isDevDatabase(): boolean {
|
return url.includes(name);
|
||||||
const dbUrl = process.env.DATABASE_URL || '';
|
|
||||||
return dbUrl.includes('euchre_camp_dev');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function isProductionDatabase(): boolean {
|
function isProductionDatabase(): boolean {
|
||||||
const dbUrl = process.env.DATABASE_URL || '';
|
const dbUrl = process.env.DATABASE_URL || '';
|
||||||
return dbUrl.includes('euchre_camp') && !dbUrl.includes('_dev');
|
return isDatabase(dbUrl, 'euchre_camp') && !isDatabase(dbUrl, '_dev') && !isDatabase(dbUrl, '_ci');
|
||||||
|
}
|
||||||
|
|
||||||
|
function isCIDatabase(): boolean {
|
||||||
|
const dbUrl = process.env.DATABASE_URL || '';
|
||||||
|
return isDatabase(dbUrl, '_ci');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Strict check - fail if using production database
|
|
||||||
if (isProductionDatabase()) {
|
if (isProductionDatabase()) {
|
||||||
console.error('');
|
console.error('');
|
||||||
console.error('='.repeat(80));
|
console.error('='.repeat(80));
|
||||||
@@ -46,59 +34,70 @@ if (isProductionDatabase()) {
|
|||||||
console.error('');
|
console.error('');
|
||||||
console.error('Current DATABASE_URL:', process.env.DATABASE_URL);
|
console.error('Current DATABASE_URL:', process.env.DATABASE_URL);
|
||||||
console.error('');
|
console.error('');
|
||||||
console.error('Tests MUST run against the development database (euchre_camp_dev)');
|
console.error('Tests MUST run against development (euchre_camp_dev) or CI (euchre_camp_ci)');
|
||||||
console.error('');
|
|
||||||
console.error('To fix this:');
|
|
||||||
console.error(' 1. Run: npm run test:acceptance');
|
|
||||||
console.error(' 2. Or set: DATABASE_URL environment variable to dev database URL');
|
|
||||||
console.error(' 3. Or load .env.development: source .env.development && npm run test:acceptance');
|
|
||||||
console.error('');
|
console.error('');
|
||||||
console.error('Aborting test execution to prevent data corruption.');
|
console.error('Aborting test execution to prevent data corruption.');
|
||||||
console.error('');
|
console.error('');
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!isDevDatabase()) {
|
function createPrismaClient() {
|
||||||
console.warn('⚠️ WARNING: DATABASE_URL does not contain euchre_camp_dev');
|
const databaseUrl = process.env.DATABASE_URL;
|
||||||
console.warn(' Current DATABASE_URL:', process.env.DATABASE_URL);
|
if (!databaseUrl) throw new Error('DATABASE_URL is required');
|
||||||
|
const adapter = new PrismaPg({ connectionString: databaseUrl });
|
||||||
|
return new PrismaClient({ adapter });
|
||||||
}
|
}
|
||||||
|
|
||||||
export default async function globalSetup(config: FullConfig) {
|
async function resetDatabaseSchema(prisma: PrismaClient) {
|
||||||
|
console.log('Resetting database schema...');
|
||||||
|
|
||||||
|
const tables = await prisma.$queryRaw<{ tablename: string }[]>`
|
||||||
|
SELECT tablename FROM pg_tables
|
||||||
|
WHERE schemaname = 'public' AND tablename NOT LIKE '_prisma_migrations'
|
||||||
|
`;
|
||||||
|
|
||||||
|
if (tables.length > 0) {
|
||||||
|
await prisma.$executeRawUnsafe(`
|
||||||
|
DROP SCHEMA public CASCADE;
|
||||||
|
CREATE SCHEMA public;
|
||||||
|
`);
|
||||||
|
console.log(`Dropped ${tables.length} tables`);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Running migrations...');
|
||||||
|
const { execSync } = await import('child_process');
|
||||||
|
execSync('bunx prisma migrate deploy', { stdio: 'inherit' });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createTestUsers(config: FullConfig) {
|
||||||
const baseURL = config.projects[0]?.use?.baseURL || 'http://localhost:3000';
|
const baseURL = config.projects[0]?.use?.baseURL || 'http://localhost:3000';
|
||||||
|
|
||||||
const browser = await chromium.launch();
|
const browser = await chromium.launch();
|
||||||
const context = await browser.newContext();
|
const context = await browser.newContext();
|
||||||
const page = await context.newPage();
|
const page = await context.newPage();
|
||||||
|
|
||||||
// Log all responses for debugging
|
|
||||||
page.on('response', response => {
|
page.on('response', response => {
|
||||||
if (response.url().includes('/api/auth')) {
|
if (response.url().includes('/api/auth')) {
|
||||||
console.log('API Response:', response.status(), response.url());
|
console.log('API Response:', response.status(), response.url());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Generate unique test credentials
|
|
||||||
const timestamp = Date.now();
|
const timestamp = Date.now();
|
||||||
const testEmail = `setup-user-${timestamp}@example.com`;
|
const testEmail = `setup-user-${timestamp}@example.com`;
|
||||||
const testPassword = 'TestPassword1234!';
|
const testPassword = 'TestPassword1234!';
|
||||||
const testName = 'Setup User';
|
const testName = 'Setup User';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Navigate to registration page
|
|
||||||
console.log('Navigating to registration page...');
|
console.log('Navigating to registration page...');
|
||||||
await page.goto(`${baseURL}/auth/register`);
|
await page.goto(`${baseURL}/auth/register`);
|
||||||
|
|
||||||
// Fill in registration form
|
|
||||||
await page.fill('input[name="name"]', testName);
|
await page.fill('input[name="name"]', testName);
|
||||||
await page.fill('input[name="email"]', testEmail);
|
await page.fill('input[name="email"]', testEmail);
|
||||||
await page.fill('input[name="password"]', testPassword);
|
await page.fill('input[name="password"]', testPassword);
|
||||||
|
|
||||||
// Submit the form
|
|
||||||
console.log('Submitting registration form...');
|
console.log('Submitting registration form...');
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
|
|
||||||
// Wait for the sign-up API call to complete
|
|
||||||
console.log('Waiting for sign-up API call...');
|
|
||||||
try {
|
try {
|
||||||
await page.waitForResponse(response =>
|
await page.waitForResponse(response =>
|
||||||
response.url().includes('/api/auth/sign-up/email') && response.status() === 200,
|
response.url().includes('/api/auth/sign-up/email') && response.status() === 200,
|
||||||
@@ -109,40 +108,25 @@ export default async function globalSetup(config: FullConfig) {
|
|||||||
console.log('Sign-up API call failed or timed out');
|
console.log('Sign-up API call failed or timed out');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wait a bit for session to be established
|
|
||||||
console.log('Waiting for session establishment...');
|
|
||||||
await page.waitForTimeout(2000);
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
// Check if we're already authenticated
|
|
||||||
const currentUrl = page.url();
|
|
||||||
console.log('Current URL after registration:', currentUrl);
|
|
||||||
|
|
||||||
// Save the authentication state
|
|
||||||
await context.storageState({ path: authFile });
|
await context.storageState({ path: authFile });
|
||||||
|
|
||||||
console.log(`Created and authenticated test user: ${testEmail}`);
|
console.log(`Created and authenticated test user: ${testEmail}`);
|
||||||
|
|
||||||
// Now create admin user
|
|
||||||
const adminTimestamp = timestamp + 1;
|
const adminTimestamp = timestamp + 1;
|
||||||
const adminEmail = `setup-admin-${adminTimestamp}@example.com`;
|
const adminEmail = `setup-admin-${adminTimestamp}@example.com`;
|
||||||
const adminPassword = 'AdminPassword123!';
|
const adminPassword = 'AdminPassword123!';
|
||||||
const adminName = 'Setup Admin';
|
const adminName = 'Setup Admin';
|
||||||
|
|
||||||
// Navigate to registration page again
|
|
||||||
console.log('Navigating to registration page for admin...');
|
console.log('Navigating to registration page for admin...');
|
||||||
await page.goto(`${baseURL}/auth/register`);
|
await page.goto(`${baseURL}/auth/register`);
|
||||||
|
|
||||||
// Fill in registration form
|
|
||||||
await page.fill('input[name="name"]', adminName);
|
await page.fill('input[name="name"]', adminName);
|
||||||
await page.fill('input[name="email"]', adminEmail);
|
await page.fill('input[name="email"]', adminEmail);
|
||||||
await page.fill('input[name="password"]', adminPassword);
|
await page.fill('input[name="password"]', adminPassword);
|
||||||
|
|
||||||
// Submit the form
|
|
||||||
console.log('Submitting admin registration form...');
|
console.log('Submitting admin registration form...');
|
||||||
await page.click('button[type="submit"]');
|
await page.click('button[type="submit"]');
|
||||||
|
|
||||||
// Wait for the sign-up API call to complete
|
|
||||||
console.log('Waiting for admin sign-up API call...');
|
|
||||||
try {
|
try {
|
||||||
await page.waitForResponse(response =>
|
await page.waitForResponse(response =>
|
||||||
response.url().includes('/api/auth/sign-up/email') && response.status() === 200,
|
response.url().includes('/api/auth/sign-up/email') && response.status() === 200,
|
||||||
@@ -153,14 +137,10 @@ export default async function globalSetup(config: FullConfig) {
|
|||||||
console.log('Admin sign-up API call failed or timed out');
|
console.log('Admin sign-up API call failed or timed out');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Wait a bit for session to be established
|
|
||||||
console.log('Waiting for admin session establishment...');
|
|
||||||
await page.waitForTimeout(2000);
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
// Update user role to admin via database
|
const prisma = createPrismaClient();
|
||||||
const user = await prisma.user.findUnique({
|
const user = await prisma.user.findUnique({ where: { email: adminEmail } });
|
||||||
where: { email: adminEmail }
|
|
||||||
});
|
|
||||||
|
|
||||||
if (user) {
|
if (user) {
|
||||||
await prisma.user.update({
|
await prisma.user.update({
|
||||||
@@ -169,44 +149,39 @@ export default async function globalSetup(config: FullConfig) {
|
|||||||
});
|
});
|
||||||
console.log('Updated user role to club_admin');
|
console.log('Updated user role to club_admin');
|
||||||
}
|
}
|
||||||
|
await prisma.$disconnect();
|
||||||
|
|
||||||
// Navigate to admin page to refresh session
|
|
||||||
console.log('Navigating to admin page for admin user...');
|
console.log('Navigating to admin page for admin user...');
|
||||||
await page.goto(`${baseURL}/admin`);
|
await page.goto(`${baseURL}/admin`);
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForLoadState('domcontentloaded');
|
||||||
console.log('Admin page loaded:', page.url());
|
console.log('Admin page loaded:', page.url());
|
||||||
|
|
||||||
// Wait a bit to ensure session is refreshed
|
|
||||||
await page.waitForTimeout(2000);
|
await page.waitForTimeout(2000);
|
||||||
|
|
||||||
// Refresh the page to force session reload
|
|
||||||
await page.reload();
|
await page.reload();
|
||||||
await page.waitForLoadState('domcontentloaded');
|
await page.waitForLoadState('domcontentloaded');
|
||||||
console.log('Page reloaded');
|
console.log('Page reloaded');
|
||||||
|
|
||||||
// Save the authentication state
|
|
||||||
await context.storageState({ path: adminAuthFile });
|
await context.storageState({ path: adminAuthFile });
|
||||||
|
|
||||||
console.log(`Created and authenticated admin user: ${adminEmail}`);
|
console.log(`Created and authenticated admin user: ${adminEmail}`);
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Global setup error:', error);
|
|
||||||
throw error;
|
|
||||||
} finally {
|
} finally {
|
||||||
await browser.close();
|
await browser.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Return teardown function
|
|
||||||
return async () => {
|
|
||||||
console.log('\n=== Global Teardown ===');
|
|
||||||
|
|
||||||
// Clean up all test data
|
|
||||||
try {
|
|
||||||
await cleanupAllTestData();
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error cleaning up test data:', error);
|
|
||||||
} finally {
|
|
||||||
await prisma.$disconnect();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export default async function globalSetup(config: FullConfig) {
|
||||||
|
console.log('=== Global Setup ===');
|
||||||
|
console.log('DATABASE_URL:', process.env.DATABASE_URL);
|
||||||
|
|
||||||
|
if (isCIDatabase()) {
|
||||||
|
console.log('CI environment detected - will reset database schema');
|
||||||
|
const prisma = createPrismaClient();
|
||||||
|
await resetDatabaseSchema(prisma);
|
||||||
|
await prisma.$disconnect();
|
||||||
|
} else if (!isProductionDatabase()) {
|
||||||
|
console.log('Development environment - preserving existing data');
|
||||||
|
}
|
||||||
|
|
||||||
|
await createTestUsers(config);
|
||||||
|
console.log('=== Global Setup Complete ===\n');
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
/**
|
||||||
|
* Global teardown for Playwright tests
|
||||||
|
* Handles cleanup based on environment:
|
||||||
|
* - CI: Full schema reset (database can be destroyed and recreated)
|
||||||
|
* - Dev: Selective cleanup of test records (preserve real data)
|
||||||
|
* - Prod: Selective cleanup of test records (preserve real data)
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { type FullConfig } from '@playwright/test';
|
||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
import { PrismaPg } from '@prisma/adapter-pg';
|
||||||
|
import { execSync } from 'child_process';
|
||||||
|
|
||||||
|
const TEST_PATTERNS = {
|
||||||
|
players: [
|
||||||
|
'%Test%',
|
||||||
|
'%Setup%',
|
||||||
|
'%Home Test%',
|
||||||
|
'%Home Match Player%',
|
||||||
|
'%Admin User%',
|
||||||
|
'%NinePart%',
|
||||||
|
'%Nine Part%',
|
||||||
|
'%Test Player%',
|
||||||
|
'%TestUser%',
|
||||||
|
'%Cucumber%',
|
||||||
|
'%Config Admin%',
|
||||||
|
],
|
||||||
|
events: [
|
||||||
|
'%Test%',
|
||||||
|
'%Setup%',
|
||||||
|
'%Recent%',
|
||||||
|
'%Test Tournament%',
|
||||||
|
'%Cucumber%',
|
||||||
|
],
|
||||||
|
users: [
|
||||||
|
'%test%',
|
||||||
|
'%setup%',
|
||||||
|
'%cucumber%',
|
||||||
|
'%TestUser%',
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
function isDatabase(url: string, name: string): boolean {
|
||||||
|
return url.includes(name);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isProductionDatabase(): boolean {
|
||||||
|
const dbUrl = process.env.DATABASE_URL || '';
|
||||||
|
return isDatabase(dbUrl, 'euchre_camp') && !isDatabase(dbUrl, '_dev') && !isDatabase(dbUrl, '_ci');
|
||||||
|
}
|
||||||
|
|
||||||
|
function isCIDatabase(): boolean {
|
||||||
|
const dbUrl = process.env.DATABASE_URL || '';
|
||||||
|
return isDatabase(dbUrl, '_ci');
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildLikeClause(patterns: string[]): string {
|
||||||
|
return patterns.map(p => `name LIKE '${p}'`).join(' OR ');
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildEmailLikeClause(patterns: string[]): string {
|
||||||
|
return patterns.map(p => `email LIKE '${p}'`).join(' OR ');
|
||||||
|
}
|
||||||
|
|
||||||
|
function createPrismaClient() {
|
||||||
|
const databaseUrl = process.env.DATABASE_URL;
|
||||||
|
if (!databaseUrl) throw new Error('DATABASE_URL is required');
|
||||||
|
const adapter = new PrismaPg({ connectionString: databaseUrl });
|
||||||
|
return new PrismaClient({ adapter });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function resetDatabaseSchema(prisma: PrismaClient) {
|
||||||
|
console.log('Resetting database schema...');
|
||||||
|
|
||||||
|
const tables = await prisma.$queryRaw<{ tablename: string }[]>`
|
||||||
|
SELECT tablename FROM pg_tables
|
||||||
|
WHERE schemaname = 'public' AND tablename NOT LIKE '_prisma_migrations'
|
||||||
|
`;
|
||||||
|
|
||||||
|
if (tables.length > 0) {
|
||||||
|
await prisma.$executeRawUnsafe(`
|
||||||
|
DROP SCHEMA public CASCADE;
|
||||||
|
CREATE SCHEMA public;
|
||||||
|
`);
|
||||||
|
console.log(`Dropped ${tables.length} tables`);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Running migrations...');
|
||||||
|
execSync('bunx prisma migrate deploy', { stdio: 'inherit' });
|
||||||
|
}
|
||||||
|
|
||||||
|
async function cleanupTestRecords(prisma: PrismaClient) {
|
||||||
|
console.log('Cleaning up test records...');
|
||||||
|
|
||||||
|
const playerWhere = buildLikeClause(TEST_PATTERNS.players);
|
||||||
|
const eventWhere = buildLikeClause(TEST_PATTERNS.events);
|
||||||
|
const userWhere = buildEmailLikeClause(TEST_PATTERNS.users);
|
||||||
|
|
||||||
|
await prisma.$executeRawUnsafe(`DELETE FROM events WHERE (${eventWhere});`);
|
||||||
|
console.log('Deleted test events');
|
||||||
|
|
||||||
|
await prisma.$executeRawUnsafe(`DELETE FROM players WHERE (${playerWhere});`);
|
||||||
|
console.log('Deleted test players');
|
||||||
|
|
||||||
|
await prisma.$executeRawUnsafe(`DELETE FROM users WHERE (${userWhere}) AND "playerId" IS NULL;`);
|
||||||
|
console.log('Deleted test users (without player associations)');
|
||||||
|
|
||||||
|
await prisma.$disconnect();
|
||||||
|
}
|
||||||
|
|
||||||
|
export default async function globalTeardown(config: FullConfig) {
|
||||||
|
console.log('\n=== Global Teardown ===');
|
||||||
|
|
||||||
|
const dbUrl = process.env.DATABASE_URL || '';
|
||||||
|
|
||||||
|
if (isCIDatabase()) {
|
||||||
|
console.log('CI environment - resetting database schema');
|
||||||
|
const prisma = createPrismaClient();
|
||||||
|
await resetDatabaseSchema(prisma);
|
||||||
|
await prisma.$disconnect();
|
||||||
|
} else if (isProductionDatabase()) {
|
||||||
|
console.log('Production environment - selective cleanup of test records');
|
||||||
|
const prisma = createPrismaClient();
|
||||||
|
await cleanupTestRecords(prisma);
|
||||||
|
} else {
|
||||||
|
console.log('Development environment - selective cleanup of test records');
|
||||||
|
const prisma = createPrismaClient();
|
||||||
|
await cleanupTestRecords(prisma);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('=== Global Teardown Complete ===\n');
|
||||||
|
}
|
||||||
@@ -239,3 +239,28 @@ workflow-status:
|
|||||||
@echo "PR Workflow: Runs unit + acceptance tests on pull requests"
|
@echo "PR Workflow: Runs unit + acceptance tests on pull requests"
|
||||||
@echo "Test Workflow: Runs unit tests on all branch pushes"
|
@echo "Test Workflow: Runs unit tests on all branch pushes"
|
||||||
@echo "Release Workflow: Runs on main branch pushes (version bump + Docker build)"
|
@echo "Release Workflow: Runs on main branch pushes (version bump + Docker build)"
|
||||||
|
|
||||||
|
# --- SDLC Database Operations ---
|
||||||
|
|
||||||
|
# Sync production data to development database (manual operation)
|
||||||
|
sync-dev:
|
||||||
|
@echo "Syncing production data to development database..."
|
||||||
|
node scripts/sync-prod-to-dev.js
|
||||||
|
|
||||||
|
# Run acceptance tests against production database (opt-in, manual)
|
||||||
|
test-prod:
|
||||||
|
@echo "⚠️ WARNING: This will run tests against the PRODUCTION database!"
|
||||||
|
@echo " All test records will be cleaned up after the run."
|
||||||
|
@echo ""
|
||||||
|
@read -p "Are you sure you want to continue? (y/N) " confirm; \
|
||||||
|
if [ "$$confirm" != "y" ]; then \
|
||||||
|
echo "Cancelled."; \
|
||||||
|
else \
|
||||||
|
DATABASE_URL="$$PROD_DATABASE_URL" bun test:acceptance; \
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Reset CI database (for local CI testing)
|
||||||
|
reset-ci-db:
|
||||||
|
@echo "Resetting CI database..."
|
||||||
|
psql "$CI_DATABASE_URL" -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;"
|
||||||
|
bunx prisma migrate deploy
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ export default defineConfig({
|
|||||||
reporter: 'html',
|
reporter: 'html',
|
||||||
// Global setup and teardown
|
// Global setup and teardown
|
||||||
globalSetup: require.resolve('./e2e/global.setup'),
|
globalSetup: require.resolve('./e2e/global.setup'),
|
||||||
|
globalTeardown: require.resolve('./e2e/global.teardown'),
|
||||||
// Use base URL for relative navigation
|
// Use base URL for relative navigation
|
||||||
use: {
|
use: {
|
||||||
baseURL: 'http://localhost:3000',
|
baseURL: 'http://localhost:3000',
|
||||||
@@ -65,8 +66,8 @@ export default defineConfig({
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
// Run your local dev server before starting the tests
|
// Run your local dev server before starting the tests
|
||||||
webServer: {
|
webServer: process.env.CI ? undefined : {
|
||||||
command: 'npm run dev',
|
command: 'bun run dev',
|
||||||
url: 'http://localhost:3000',
|
url: 'http://localhost:3000',
|
||||||
timeout: 120000,
|
timeout: 120000,
|
||||||
reuseExistingServer: !process.env.CI,
|
reuseExistingServer: !process.env.CI,
|
||||||
|
|||||||
@@ -0,0 +1,157 @@
|
|||||||
|
#!/usr/bin/env node
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sync production data to development database
|
||||||
|
*
|
||||||
|
* This script copies real data from production to development, filtering out
|
||||||
|
* test records to keep the dev database clean for testing.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const { execSync } = require('child_process');
|
||||||
|
const fs = require('fs');
|
||||||
|
const os = require('os');
|
||||||
|
const path = require('path');
|
||||||
|
|
||||||
|
const PROD_DB_URL = process.env.PROD_DATABASE_URL;
|
||||||
|
const DEV_DB_URL = process.env.DEV_DATABASE_URL;
|
||||||
|
|
||||||
|
if (!PROD_DB_URL || !DEV_DB_URL) {
|
||||||
|
console.error('❌ Missing environment variables');
|
||||||
|
console.error('Please set PROD_DATABASE_URL and DEV_DATABASE_URL');
|
||||||
|
console.error('');
|
||||||
|
console.error('Example:');
|
||||||
|
console.error(' PROD_DATABASE_URL="postgresql://user:pass@host:5432/euchre_camp" \\');
|
||||||
|
console.error(' DEV_DATABASE_URL="postgresql://user:pass@host:5432/euchre_camp_dev" \\');
|
||||||
|
console.error(' node scripts/sync-prod-to-dev.js');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (PROD_DB_URL.includes('_dev') || PROD_DB_URL.includes('_ci')) {
|
||||||
|
console.error('❌ PROD_DATABASE_URL appears to be a non-production database!');
|
||||||
|
console.error(' This script should only be used with the production database.');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const TEST_PATTERNS = {
|
||||||
|
players: [
|
||||||
|
'%Test%',
|
||||||
|
'%Setup%',
|
||||||
|
'%Home Test%',
|
||||||
|
'%Home Match Player%',
|
||||||
|
'%Admin User%',
|
||||||
|
'%NinePart%',
|
||||||
|
'%Nine Part%',
|
||||||
|
'%Test Player%',
|
||||||
|
'%TestUser%',
|
||||||
|
'%Cucumber%',
|
||||||
|
'%Config Admin%',
|
||||||
|
],
|
||||||
|
events: [
|
||||||
|
'%Test%',
|
||||||
|
'%Setup%',
|
||||||
|
'%Recent%',
|
||||||
|
'%Test Tournament%',
|
||||||
|
'%Cucumber%',
|
||||||
|
],
|
||||||
|
users: [
|
||||||
|
'%test%',
|
||||||
|
'%setup%',
|
||||||
|
'%cucumber%',
|
||||||
|
'%TestUser%',
|
||||||
|
]
|
||||||
|
};
|
||||||
|
|
||||||
|
function buildLikeClause(patterns) {
|
||||||
|
return patterns.map(p => `name LIKE '${p}'`).join(' OR ');
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildEmailLikeClause(patterns) {
|
||||||
|
return patterns.map(p => `email LIKE '${p}'`).join(' OR ');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
console.log('🔄 Syncing production data to development database');
|
||||||
|
console.log('====================================================\n');
|
||||||
|
|
||||||
|
const readline = require('readline');
|
||||||
|
const rl = readline.createInterface({
|
||||||
|
input: process.stdin,
|
||||||
|
output: process.stdout
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log('⚠️ WARNING: This will OVERWRITE the development database!');
|
||||||
|
console.log(' Production data will be copied, with test records excluded.');
|
||||||
|
console.log('');
|
||||||
|
console.log('Source:', PROD_DB_URL.replace(/:[^:@]+@/, ':***@'));
|
||||||
|
console.log('Target:', DEV_DB_URL.replace(/:[^:@]+@/, ':***@'));
|
||||||
|
console.log('');
|
||||||
|
|
||||||
|
rl.question('Type "sync" to confirm: ', async (answer) => {
|
||||||
|
if (answer !== 'sync') {
|
||||||
|
console.log('❌ Cancelled');
|
||||||
|
rl.close();
|
||||||
|
process.exit(0);
|
||||||
|
}
|
||||||
|
|
||||||
|
rl.close();
|
||||||
|
|
||||||
|
try {
|
||||||
|
console.log('\n📦 Dumping production data...');
|
||||||
|
|
||||||
|
const dumpFile = path.join(os.tmpdir(), `prod_dump_${Date.now()}.sql`);
|
||||||
|
|
||||||
|
execSync(`pg_dump "${PROD_DB_URL}" -f "${dumpFile}" --no-owner --no-acl`, {
|
||||||
|
stdio: 'inherit'
|
||||||
|
});
|
||||||
|
console.log('✅ Dump created');
|
||||||
|
|
||||||
|
console.log('\n🗑️ Clearing development database...');
|
||||||
|
execSync(`psql "${DEV_DB_URL}" -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;"`, {
|
||||||
|
stdio: 'inherit'
|
||||||
|
});
|
||||||
|
console.log('✅ Development database cleared');
|
||||||
|
|
||||||
|
console.log('\n📥 Restoring to development database...');
|
||||||
|
execSync(`psql "${DEV_DB_URL}" -f "${dumpFile}"`, {
|
||||||
|
stdio: 'inherit'
|
||||||
|
});
|
||||||
|
console.log('✅ Data restored');
|
||||||
|
|
||||||
|
console.log('\n🧹 Cleaning up test records in dev database...');
|
||||||
|
|
||||||
|
const playerWhere = buildLikeClause(TEST_PATTERNS.players);
|
||||||
|
const eventWhere = buildLikeClause(TEST_PATTERNS.events);
|
||||||
|
const userWhere = buildEmailLikeClause(TEST_PATTERNS.users);
|
||||||
|
|
||||||
|
execSync(`psql "${DEV_DB_URL}" -c "DELETE FROM events WHERE (${eventWhere});"`, {
|
||||||
|
stdio: 'inherit'
|
||||||
|
});
|
||||||
|
console.log(' Deleted test events');
|
||||||
|
|
||||||
|
execSync(`psql "${DEV_DB_URL}" -c "DELETE FROM players WHERE (${playerWhere});"`, {
|
||||||
|
stdio: 'inherit'
|
||||||
|
});
|
||||||
|
console.log(' Deleted test players');
|
||||||
|
|
||||||
|
execSync(`psql "${DEV_DB_URL}" -c "DELETE FROM users WHERE (${userWhere}) AND \"playerId\" IS NULL;"`, {
|
||||||
|
stdio: 'inherit'
|
||||||
|
});
|
||||||
|
console.log(' Deleted test users');
|
||||||
|
|
||||||
|
fs.unlinkSync(dumpFile);
|
||||||
|
console.log('\n🧹 Cleaned up temporary dump file');
|
||||||
|
|
||||||
|
console.log('\n✅ Sync complete!');
|
||||||
|
console.log('\n📊 Summary:');
|
||||||
|
console.log(' - Production data copied to development');
|
||||||
|
console.log(' - Test records filtered out');
|
||||||
|
console.log(' - Development database is now a mirror of production (minus test data)');
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error('\n❌ Sync failed:', error.message);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
main();
|
||||||
Reference in New Issue
Block a user