feat: SDLC database separation for CI/testing (#35)
## Summary - Fix `isProductionDatabase()` to allow CI database (`euchre_camp_ci`) - Add database schema reset before CI test runs - Create `global.teardown.ts` for cleanup (CI: full reset, dev/prod: selective cleanup) - Add `acceptance-tests` job to PR workflow with CI database - Create `sync-prod-to-dev.js` script for one-way prod→dev sync - Add `just` recipes: `sync-dev`, `test-prod`, `reset-ci-db` - Store credentials in `.credentials` (gitignored) with unique CI user ## Testing Verified against CI database: - Schema reset works - Migrations apply correctly - Test users created successfully - 219 tests pass (slow but working) ## Next Steps - Set `CI_DATABASE_URL` as Gitea repository variable Reviewed-on: #35 Co-authored-by: David Gwilliam <dhgwilliam@gmail.com> Co-committed-by: David Gwilliam <dhgwilliam@gmail.com>
This commit was merged in pull request #35.
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* Epic 3: Rankings & Public Data
|
||||
* Acceptance Test: Player Rankings Page
|
||||
*
|
||||
* User Story: As a visitor, I want to view player rankings so that I can see top players
|
||||
*
|
||||
* Acceptance Criteria:
|
||||
* - Sortable rankings table
|
||||
* - Columns: Rank, Name, Elo, Win Rate, Games Played
|
||||
* - Search/filter functionality
|
||||
* - Pagination
|
||||
*/
|
||||
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
test.describe('Epic 3: Rankings Page', () => {
|
||||
test('Rankings page loads and displays rankings table', async ({ page }) => {
|
||||
await page.goto('http://localhost:3000/rankings');
|
||||
|
||||
// Check page title or heading
|
||||
await expect(page.locator('h1, h2')).toContainText(/rankings?/i);
|
||||
|
||||
// Check for rankings table
|
||||
await expect(page.locator('table')).toBeVisible();
|
||||
});
|
||||
|
||||
test('Rankings table displays player columns', async ({ page }) => {
|
||||
await page.goto('http://localhost:3000/rankings');
|
||||
|
||||
// Check for expected column headers
|
||||
const table = page.locator('table');
|
||||
await expect(table).toBeVisible();
|
||||
|
||||
// Check for column headers (may vary based on implementation)
|
||||
const headerCount = await page.locator('th').count();
|
||||
expect(headerCount).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test('Rankings page is publicly accessible (no login required)', async ({ page }) => {
|
||||
// Navigate directly to rankings without logging in
|
||||
await page.goto('http://localhost:3000/rankings');
|
||||
|
||||
// Page should load without redirecting to login
|
||||
await expect(page).toHaveURL(/.*rankings.*/);
|
||||
await expect(page.locator('body')).toBeVisible();
|
||||
});
|
||||
});
|
||||
+58
-83
@@ -4,40 +4,28 @@
|
||||
*/
|
||||
|
||||
import { chromium, type FullConfig } from '@playwright/test';
|
||||
import { prisma } from '@/lib/prisma';
|
||||
import { cleanupAllTestData } from '@/__tests__/test-utils';
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { PrismaPg } from '@prisma/adapter-pg';
|
||||
import path from 'path';
|
||||
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 adminAuthFile = 'playwright/.auth/admin.json';
|
||||
|
||||
// Check if we're using the dev database
|
||||
function isDevDatabase(): boolean {
|
||||
const dbUrl = process.env.DATABASE_URL || '';
|
||||
return dbUrl.includes('euchre_camp_dev');
|
||||
function isDatabase(url: string, name: string): boolean {
|
||||
return url.includes(name);
|
||||
}
|
||||
|
||||
function isProductionDatabase(): boolean {
|
||||
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()) {
|
||||
console.error('');
|
||||
console.error('='.repeat(80));
|
||||
@@ -46,59 +34,70 @@ if (isProductionDatabase()) {
|
||||
console.error('');
|
||||
console.error('Current DATABASE_URL:', process.env.DATABASE_URL);
|
||||
console.error('');
|
||||
console.error('Tests MUST run against the development database (euchre_camp_dev)');
|
||||
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('Tests MUST run against development (euchre_camp_dev) or CI (euchre_camp_ci)');
|
||||
console.error('');
|
||||
console.error('Aborting test execution to prevent data corruption.');
|
||||
console.error('');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (!isDevDatabase()) {
|
||||
console.warn('⚠️ WARNING: DATABASE_URL does not contain euchre_camp_dev');
|
||||
console.warn(' Current DATABASE_URL:', process.env.DATABASE_URL);
|
||||
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 });
|
||||
}
|
||||
|
||||
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 browser = await chromium.launch();
|
||||
const context = await browser.newContext();
|
||||
const page = await context.newPage();
|
||||
|
||||
// Log all responses for debugging
|
||||
page.on('response', response => {
|
||||
if (response.url().includes('/api/auth')) {
|
||||
console.log('API Response:', response.status(), response.url());
|
||||
}
|
||||
});
|
||||
|
||||
// Generate unique test credentials
|
||||
const timestamp = Date.now();
|
||||
const testEmail = `setup-user-${timestamp}@example.com`;
|
||||
const testPassword = 'TestPassword1234!';
|
||||
const testName = 'Setup User';
|
||||
|
||||
try {
|
||||
// Navigate to registration page
|
||||
console.log('Navigating to registration page...');
|
||||
await page.goto(`${baseURL}/auth/register`);
|
||||
|
||||
// Fill in registration form
|
||||
await page.fill('input[name="name"]', testName);
|
||||
await page.fill('input[name="email"]', testEmail);
|
||||
await page.fill('input[name="password"]', testPassword);
|
||||
|
||||
// Submit the form
|
||||
console.log('Submitting registration form...');
|
||||
await page.click('button[type="submit"]');
|
||||
|
||||
// Wait for the sign-up API call to complete
|
||||
console.log('Waiting for sign-up API call...');
|
||||
try {
|
||||
await page.waitForResponse(response =>
|
||||
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');
|
||||
}
|
||||
|
||||
// Wait a bit for session to be established
|
||||
console.log('Waiting for session establishment...');
|
||||
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 });
|
||||
|
||||
console.log(`Created and authenticated test user: ${testEmail}`);
|
||||
|
||||
// Now create admin user
|
||||
const adminTimestamp = timestamp + 1;
|
||||
const adminEmail = `setup-admin-${adminTimestamp}@example.com`;
|
||||
const adminPassword = 'AdminPassword123!';
|
||||
const adminName = 'Setup Admin';
|
||||
|
||||
// Navigate to registration page again
|
||||
console.log('Navigating to registration page for admin...');
|
||||
await page.goto(`${baseURL}/auth/register`);
|
||||
|
||||
// Fill in registration form
|
||||
await page.fill('input[name="name"]', adminName);
|
||||
await page.fill('input[name="email"]', adminEmail);
|
||||
await page.fill('input[name="password"]', adminPassword);
|
||||
|
||||
// Submit the form
|
||||
console.log('Submitting admin registration form...');
|
||||
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 {
|
||||
await page.waitForResponse(response =>
|
||||
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');
|
||||
}
|
||||
|
||||
// Wait a bit for session to be established
|
||||
console.log('Waiting for admin session establishment...');
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// Update user role to admin via database
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { email: adminEmail }
|
||||
});
|
||||
const prisma = createPrismaClient();
|
||||
const user = await prisma.user.findUnique({ where: { email: adminEmail } });
|
||||
|
||||
if (user) {
|
||||
await prisma.user.update({
|
||||
@@ -169,44 +149,39 @@ export default async function globalSetup(config: FullConfig) {
|
||||
});
|
||||
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...');
|
||||
await page.goto(`${baseURL}/admin`);
|
||||
await page.waitForLoadState('domcontentloaded');
|
||||
console.log('Admin page loaded:', page.url());
|
||||
|
||||
// Wait a bit to ensure session is refreshed
|
||||
await page.waitForTimeout(2000);
|
||||
|
||||
// Refresh the page to force session reload
|
||||
await page.reload();
|
||||
await page.waitForLoadState('domcontentloaded');
|
||||
console.log('Page reloaded');
|
||||
|
||||
// Save the authentication state
|
||||
await context.storageState({ path: adminAuthFile });
|
||||
|
||||
console.log(`Created and authenticated admin user: ${adminEmail}`);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Global setup error:', error);
|
||||
throw error;
|
||||
} finally {
|
||||
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');
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { test, expect } from '@playwright/test'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
test.describe('Home Page', () => {
|
||||
const createdIds = {
|
||||
players: [] as number[],
|
||||
events: [] as number[],
|
||||
matches: [] as number[],
|
||||
users: [] as string[],
|
||||
}
|
||||
|
||||
test.afterEach(async () => {
|
||||
await prisma.match.deleteMany({ where: { id: { in: createdIds.matches } } })
|
||||
await prisma.event.deleteMany({ where: { id: { in: createdIds.events } } })
|
||||
await prisma.player.deleteMany({ id: { in: createdIds.players } })
|
||||
await prisma.user.deleteMany({ where: { id: { in: createdIds.users } } })
|
||||
createdIds.players = []
|
||||
createdIds.events = []
|
||||
createdIds.matches = []
|
||||
createdIds.users = []
|
||||
})
|
||||
|
||||
test('displays top 10 players section', async ({ page }) => {
|
||||
const timestamp = Date.now()
|
||||
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const player = await prisma.player.create({
|
||||
data: {
|
||||
name: `Home Test Player ${timestamp} ${i + 1}`,
|
||||
normalizedName: `home_test_player_${timestamp}_${i + 1}`.toLowerCase(),
|
||||
currentElo: 2000 - i * 10,
|
||||
gamesPlayed: 10,
|
||||
wins: 7,
|
||||
},
|
||||
})
|
||||
createdIds.players.push(player.id)
|
||||
}
|
||||
|
||||
await page.goto('/')
|
||||
|
||||
await expect(page.locator('text=Top 10 Players')).toBeVisible()
|
||||
await expect(
|
||||
page.locator(`a:has-text("Home Test Player ${timestamp} 1")`)
|
||||
).toBeVisible()
|
||||
})
|
||||
|
||||
test('displays club president section', async ({ page }) => {
|
||||
const timestamp = Date.now()
|
||||
const user = await prisma.user.create({
|
||||
data: {
|
||||
email: `president-${timestamp}@example.com`,
|
||||
name: `Club President ${timestamp}`,
|
||||
role: 'club_admin',
|
||||
},
|
||||
})
|
||||
createdIds.users.push(user.id)
|
||||
|
||||
await page.goto('/')
|
||||
|
||||
await expect(page.locator('text=Club President')).toBeVisible()
|
||||
})
|
||||
|
||||
test('displays most recent tournament section', async ({ page }) => {
|
||||
const timestamp = Date.now()
|
||||
|
||||
const tournament = await prisma.event.create({
|
||||
data: {
|
||||
name: `Recent Tournament ${timestamp}`,
|
||||
eventType: 'tournament',
|
||||
eventDate: new Date(Date.now() + 86400000),
|
||||
status: 'completed',
|
||||
},
|
||||
})
|
||||
createdIds.events.push(tournament.id)
|
||||
|
||||
const p1 = await prisma.player.create({
|
||||
data: { name: `HP1 ${timestamp}`, normalizedName: `hp1_${timestamp}`.toLowerCase(), currentElo: 1500 },
|
||||
})
|
||||
const p2 = await prisma.player.create({
|
||||
data: { name: `HP2 ${timestamp}`, normalizedName: `hp2_${timestamp}`.toLowerCase(), currentElo: 1480 },
|
||||
})
|
||||
const p3 = await prisma.player.create({
|
||||
data: { name: `HP3 ${timestamp}`, normalizedName: `hp3_${timestamp}`.toLowerCase(), currentElo: 1450 },
|
||||
})
|
||||
const p4 = await prisma.player.create({
|
||||
data: { name: `HP4 ${timestamp}`, normalizedName: `hp4_${timestamp}`.toLowerCase(), currentElo: 1420 },
|
||||
})
|
||||
createdIds.players.push(p1.id, p2.id, p3.id, p4.id)
|
||||
|
||||
const match = await prisma.match.create({
|
||||
data: {
|
||||
eventId: tournament.id,
|
||||
player1P1Id: p1.id,
|
||||
player1P2Id: p2.id,
|
||||
player2P1Id: p3.id,
|
||||
player2P2Id: p4.id,
|
||||
team1Score: 10,
|
||||
team2Score: 5,
|
||||
status: 'completed',
|
||||
playedAt: new Date(),
|
||||
},
|
||||
})
|
||||
createdIds.matches.push(match.id)
|
||||
|
||||
await page.goto('/')
|
||||
|
||||
await expect(page.locator('text=Most Recent Tournament')).toBeVisible()
|
||||
await expect(page.locator(`text=Recent Tournament ${timestamp}`)).toBeVisible()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user