reworked stack

This commit is contained in:
johba 2025-10-07 21:57:32 +00:00
parent 6cbb1781ce
commit f7ef56f65f
12 changed files with 853 additions and 458 deletions

View file

@ -1,13 +1,16 @@
import { expect, test, type APIRequestContext } from '@playwright/test';
import { Wallet } from 'ethers';
import { createWalletContext } from '../setup/wallet-provider';
import { startStack, waitForStackReady, stopStack } from '../setup/stack';
import { getStackConfig, validateStackHealthy } from '../setup/stack';
const ACCOUNT_PRIVATE_KEY = '0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80';
const ACCOUNT_ADDRESS = new Wallet(ACCOUNT_PRIVATE_KEY).address.toLowerCase();
const STACK_RPC_URL = process.env.STACK_RPC_URL ?? 'http://127.0.0.1:8545';
const STACK_WEBAPP_URL = process.env.STACK_WEBAPP_URL ?? 'http://localhost:5173';
const STACK_GRAPHQL_URL = process.env.STACK_GRAPHQL_URL ?? 'http://localhost:42069/graphql';
// Get stack configuration from environment (or defaults)
const STACK_CONFIG = getStackConfig();
const STACK_RPC_URL = STACK_CONFIG.rpcUrl;
const STACK_WEBAPP_URL = STACK_CONFIG.webAppUrl;
const STACK_GRAPHQL_URL = STACK_CONFIG.graphqlUrl;
async function fetchPositions(request: APIRequestContext, owner: string) {
const response = await request.post(STACK_GRAPHQL_URL, {
@ -42,17 +45,10 @@ async function fetchPositions(request: APIRequestContext, owner: string) {
}
test.describe('Acquire & Stake', () => {
// Validate that a healthy stack exists before running tests
// Tests do NOT start their own stack - stack must be running already
test.beforeAll(async () => {
await startStack();
await waitForStackReady({
rpcUrl: STACK_RPC_URL,
webAppUrl: STACK_WEBAPP_URL,
graphqlUrl: STACK_GRAPHQL_URL,
});
});
test.afterAll(async () => {
await stopStack();
await validateStackHealthy(STACK_CONFIG);
});
test('users can swap KRK via UI', async ({ browser, request }) => {
@ -153,22 +149,30 @@ test.describe('Acquire & Stake', () => {
// Wait for the stake form to be initialized
console.log('[TEST] Waiting for stake form to load...');
await page.waitForSelector('text=Token Amount', { timeout: 15_000 });
const tokenAmountSlider = page.getByRole('slider', { name: 'Token Amount' });
await expect(tokenAmountSlider).toBeVisible({ timeout: 15_000 });
// Use the test helper to fill the stake form
console.log('[TEST] Filling stake form via test helper...');
await page.evaluate(async () => {
if (!window.__testHelpers) {
throw new Error('Test helpers not available');
}
await window.__testHelpers.fillStakeForm({
amount: 100, // Stake 100 KRK
taxRateIndex: 2, // 5% tax rate option
});
});
console.log('[TEST] Filling stake form via accessible controls...');
// Take screenshot before interaction
await page.screenshot({ path: 'test-results/before-stake-fill.png' });
// Check if input is visible and enabled
const stakeAmountInput = page.getByLabel('Staking Amount');
console.log('[TEST] Checking if staking amount input is visible...');
await expect(stakeAmountInput).toBeVisible({ timeout: 10_000 });
console.log('[TEST] Staking amount input is visible, filling value...');
await stakeAmountInput.fill('100');
console.log('[TEST] Filled staking amount!');
const taxSelect = page.getByRole('combobox', { name: 'Tax' });
console.log('[TEST] Selecting tax rate...');
await taxSelect.selectOption({ value: '2' });
console.log('[TEST] Tax rate selected!');
console.log('[TEST] Clicking stake button...');
const stakeButton = page.getByRole('button', { name: /Stake|Snatch and Stake/i });
// Use the main form's submit button (large/block), not the small position card buttons
const stakeButton = page.getByRole('main').getByRole('button', { name: /Stake|Snatch and Stake/i });
await expect(stakeButton).toBeVisible({ timeout: 5_000 });
await stakeButton.click();
@ -190,7 +194,7 @@ test.describe('Acquire & Stake', () => {
console.log(`[TEST] Found ${positions.length} position(s)`);
expect(positions.length).toBeGreaterThan(0);
const activePositions = positions.filter(p => p.status === 'OPEN');
const activePositions = positions.filter(p => p.status === 'Active');
expect(activePositions.length).toBeGreaterThan(0);
console.log(`[TEST] ✅ Staking successful! Created ${activePositions.length} active position(s)`);

View file

@ -1,118 +1,49 @@
import { exec as execCallback } from 'node:child_process';
import { readFile } from 'node:fs/promises';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util';
import {
runAllHealthChecks,
formatHealthCheckError,
type HealthCheckResult,
} from './health-checks.js';
const exec = promisify(execCallback);
const DEFAULT_RPC_URL = 'http://127.0.0.1:8545';
const DEFAULT_WEBAPP_URL = 'http://localhost:8081';
const DEFAULT_GRAPHQL_URL = 'http://localhost:8081/graphql';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const repoRoot = resolve(__dirname, '..', '..');
const DEFAULT_RPC_URL = process.env.STACK_RPC_URL ?? 'http://127.0.0.1:8545';
const DEFAULT_WEBAPP_URL = process.env.STACK_WEBAPP_URL ?? 'http://localhost:5173';
const DEFAULT_GRAPHQL_URL = process.env.STACK_GRAPHQL_URL ?? 'http://localhost:42069/graphql';
let stackStarted = false;
async function cleanupContainers(): Promise<void> {
try {
await run("podman pod ps -q --filter name=harb | xargs -r podman pod rm -f || true");
await run("podman ps -aq --filter name=harb | xargs -r podman rm -f || true");
} catch (error) {
console.warn('[stack] Failed to cleanup containers', error);
}
}
function delay(ms: number): Promise<void> {
return new Promise(resolveDelay => setTimeout(resolveDelay, ms));
}
async function run(command: string): Promise<void> {
await exec(command, { cwd: repoRoot, shell: true });
export interface StackConfig {
rpcUrl: string;
webAppUrl: string;
graphqlUrl: string;
}
/**
* Run functional health checks that verify services are actually usable, not just running
* Get stack configuration from environment variables.
* Tests should NOT start their own stack - they require a pre-existing healthy stack.
*/
async function checkStackFunctional(
rpcUrl: string,
webAppUrl: string,
graphqlUrl: string
): Promise<void> {
const results = await runAllHealthChecks({ rpcUrl, webAppUrl, graphqlUrl });
export function getStackConfig(): StackConfig {
return {
rpcUrl: process.env.STACK_RPC_URL ?? DEFAULT_RPC_URL,
webAppUrl: process.env.STACK_WEBAPP_URL ?? DEFAULT_WEBAPP_URL,
graphqlUrl: process.env.STACK_GRAPHQL_URL ?? DEFAULT_GRAPHQL_URL,
};
}
/**
* Validate that a healthy stack exists and is functional.
* If validation fails, the test run should exit immediately.
*
* Tests do NOT manage stack lifecycle - stack must be started externally via:
* ./scripts/dev.sh start
*/
export async function validateStackHealthy(config: StackConfig): Promise<void> {
const results = await runAllHealthChecks(config);
const failures = results.filter(r => !r.success);
if (failures.length > 0) {
throw new Error(formatHealthCheckError(results));
}
}
export async function startStack(): Promise<void> {
if (stackStarted) {
return;
}
await cleanupContainers();
await run('nohup ./scripts/dev.sh start > ./tests/.stack.log 2>&1 &');
stackStarted = true;
}
export async function waitForStackReady(options: {
rpcUrl?: string;
webAppUrl?: string;
graphqlUrl?: string;
timeoutMs?: number;
pollIntervalMs?: number;
} = {}): Promise<void> {
const rpcUrl = options.rpcUrl ?? DEFAULT_RPC_URL;
const webAppUrl = options.webAppUrl ?? DEFAULT_WEBAPP_URL;
const graphqlUrl = options.graphqlUrl ?? DEFAULT_GRAPHQL_URL;
const timeoutMs = options.timeoutMs ?? 180_000;
const pollIntervalMs = options.pollIntervalMs ?? 2_000;
const start = Date.now();
const errors = new Map<string, string>();
while (Date.now() - start < timeoutMs) {
try {
await checkStackFunctional(rpcUrl, webAppUrl, graphqlUrl);
console.log('✅ All stack health checks passed');
return;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
errors.set('lastError', message);
await delay(pollIntervalMs);
}
}
const logPath = resolve(repoRoot, 'tests', '.stack.log');
let logTail = '';
try {
const contents = await readFile(logPath, 'utf-8');
logTail = contents.split('\n').slice(-40).join('\n');
} catch (readError) {
logTail = `Unable to read stack log: ${readError}`;
}
throw new Error(`Stack failed to become ready within ${timeoutMs}ms\nLast error: ${errors.get('lastError')}\nLog tail:\n${logTail}`);
}
export async function stopStack(): Promise<void> {
if (!stackStarted) {
return;
}
try {
await run('./scripts/dev.sh stop');
} finally {
stackStarted = false;
const errorMessage = formatHealthCheckError(results);
console.error('\n❌ Stack health validation failed');
console.error('Tests require a pre-existing healthy stack.');
console.error('Start the stack with: ./scripts/dev.sh start\n');
console.error(errorMessage);
process.exit(1);
}
console.log('✅ Stack health validation passed');
}