fixes and refactor
This commit is contained in:
69
e2e/global-setup.js
Normal file
69
e2e/global-setup.js
Normal file
@@ -0,0 +1,69 @@
|
||||
// Global setup to seed admin user before Playwright tests
|
||||
const { spawnSync } = require('child_process');
|
||||
const fs = require('fs');
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
module.exports = async () => {
|
||||
const SECRET_KEY = process.env.SECRET_KEY || 'x'.repeat(32);
|
||||
const path = require('path');
|
||||
const dbPath = path.resolve(__dirname, '..', '.e2e-db.sqlite');
|
||||
const DATABASE_URL = process.env.DATABASE_URL || `sqlite:////${dbPath}`;
|
||||
|
||||
// Ensure a clean database for deterministic tests
|
||||
try { fs.rmSync(dbPath, { force: true }); } catch (_) {}
|
||||
|
||||
const pyCode = `
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from app.database.base import engine
|
||||
from app.models import BaseModel
|
||||
from app.models.user import User
|
||||
from app.auth.security import get_password_hash
|
||||
import os
|
||||
|
||||
# Ensure tables
|
||||
BaseModel.metadata.create_all(bind=engine)
|
||||
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
db = SessionLocal()
|
||||
try:
|
||||
admin = db.query(User).filter(User.username=='admin').first()
|
||||
if not admin:
|
||||
admin = User(
|
||||
username=os.getenv('ADMIN_USERNAME','admin'),
|
||||
email=os.getenv('ADMIN_EMAIL','admin@delphicg.local'),
|
||||
full_name=os.getenv('ADMIN_FULLNAME','System Administrator'),
|
||||
hashed_password=get_password_hash(os.getenv('ADMIN_PASSWORD','admin123')),
|
||||
is_active=True,
|
||||
is_admin=True,
|
||||
)
|
||||
db.add(admin)
|
||||
db.commit()
|
||||
print('Seeded admin user')
|
||||
else:
|
||||
print('Admin user already exists')
|
||||
finally:
|
||||
db.close()
|
||||
`;
|
||||
|
||||
const env = {
|
||||
...process.env,
|
||||
SECRET_KEY,
|
||||
DATABASE_URL,
|
||||
ADMIN_EMAIL: 'admin@example.com',
|
||||
ADMIN_USERNAME: 'admin',
|
||||
ADMIN_PASSWORD: process.env.ADMIN_PASSWORD || 'admin123',
|
||||
};
|
||||
let res = spawnSync('python3', ['-c', pyCode], { env, stdio: 'inherit' });
|
||||
if (res.error) {
|
||||
res = spawnSync('python', ['-c', pyCode], { env, stdio: 'inherit' });
|
||||
if (res.error) throw res.error;
|
||||
}
|
||||
|
||||
// Pre-generate a valid access token to bypass login DB writes in tests
|
||||
const token = jwt.sign({ sub: env.ADMIN_USERNAME, type: 'access' }, env.SECRET_KEY, { expiresIn: '4h' });
|
||||
// Persist to a file for the tests to read
|
||||
const tokenPath = path.resolve(__dirname, '..', '.e2e-token');
|
||||
fs.writeFileSync(tokenPath, token, 'utf-8');
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user