e2e-stage0-setup.js
1 #!/usr/bin/env node 2 /** 3 * E2E Test - Stage 0: Setup 4 * Creates test database and inserts test site with keyword 5 */ 6 7 import 'dotenv/config'; 8 import Database from 'better-sqlite3'; 9 import fs from 'fs'; 10 import path from 'path'; 11 import { fileURLToPath } from 'url'; 12 13 const __dirname = path.dirname(fileURLToPath(import.meta.url)); 14 15 // Test configuration from environment 16 const { TEST_E2E_URL } = process.env; 17 const { TEST_E2E_KEYWORD } = process.env; 18 19 if (!TEST_E2E_URL || !TEST_E2E_KEYWORD) { 20 console.error('ERROR: TEST_E2E_URL and TEST_E2E_KEYWORD must be set in .env'); 21 process.exit(1); 22 } 23 24 const testDbPath = 'db/test-e2e.db'; 25 const testScreenshotsDir = 'screenshots-test-e2e'; 26 27 console.log('[STAGE 0] Setting up E2E test database...'); 28 console.log(` URL: ${TEST_E2E_URL}`); 29 console.log(` Keyword: ${TEST_E2E_KEYWORD}`); 30 31 // Clean up any previous test artifacts 32 if (fs.existsSync(testDbPath)) { 33 fs.unlinkSync(testDbPath); 34 console.log(' Removed existing test database'); 35 } 36 37 if (fs.existsSync(testScreenshotsDir)) { 38 fs.rmSync(testScreenshotsDir, { recursive: true, force: true }); 39 console.log(' Removed existing test screenshots'); 40 } 41 42 // Create test database 43 const db = new Database(testDbPath); 44 db.pragma('foreign_keys = ON'); 45 46 // Load and execute schema 47 const schemaPath = path.join(__dirname, '../db/schema.sql'); 48 const schema = fs.readFileSync(schemaPath, 'utf-8'); 49 50 // Split schema into statements and execute 51 const statements = schema 52 .split(';') 53 .map(s => s.trim()) 54 .filter(s => s.length > 0); 55 56 for (const statement of statements) { 57 try { 58 db.exec(statement); 59 } catch (error) { 60 if (!error.message.includes('already exists')) { 61 console.error(`Error executing statement: ${statement.substring(0, 100)}...`); 62 throw error; 63 } 64 } 65 } 66 67 console.log(' Created test database with schema'); 68 69 // Extract domain from URL 70 const domain = new URL(TEST_E2E_URL).hostname; 71 72 // Insert test site 73 const insert = db.prepare(` 74 INSERT INTO sites (domain, landing_page_url, keyword, status) 75 VALUES (?, ?, ?, 'found') 76 `); 77 78 const result = insert.run(domain, TEST_E2E_URL, TEST_E2E_KEYWORD); 79 80 console.log(` Inserted site: ${domain} (ID: ${result.lastInsertRowid})`); 81 82 // Verify 83 const site = db.prepare('SELECT * FROM sites WHERE id = ?').get(result.lastInsertRowid); 84 console.log(' Verification:'); 85 console.log(` - Domain: ${site.domain}`); 86 console.log(` - URL: ${site.landing_page_url}`); 87 console.log(` - Keyword: ${site.keyword}`); 88 console.log(` - Status: ${site.status}`); 89 90 db.close(); 91 92 console.log('[STAGE 0] ✅ Setup complete\n');