All files / web/scripts smoke-test-runner.ts

0% Statements 0/463
0% Branches 0/1
0% Functions 0/1
0% Lines 0/463

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
#!/usr/bin/env npx tsx
/**
 * Smoke Test Runner
 *
 * Runs Playwright smoke tests and reports results to the abaci-app API.
 * Optionally saves HTML reports to a filesystem directory for viewing.
 *
 * Environment variables:
 * - BASE_URL: The base URL to test against (default: http://localhost:3000)
 * - RESULTS_API_URL: The URL to POST results to (default: http://localhost:3000/api/smoke-test-results)
 * - REPORT_DIR: Directory to save HTML reports (optional, e.g., /artifacts/smoke-reports)
 * - PUSHGATEWAY_URL: Prometheus Pushgateway base URL (optional, e.g.
 *     http://pushgateway.monitoring.svc.cluster.local:9091). When set, the run's
 *     result metrics are pushed as a single series (job="smoke-tests"); when
 *     unset (local dev) the push is skipped.
 *
 * Usage:
 *   npx tsx scripts/smoke-test-runner.ts
 */

import { spawn, execSync } from 'child_process'
import { randomUUID } from 'crypto'
import {
  existsSync,
  mkdirSync,
  cpSync,
  rmSync,
  symlinkSync,
  unlinkSync,
  readdirSync,
  statSync,
} from 'fs'
import { join } from 'path'

const BASE_URL = process.env.BASE_URL || 'http://localhost:3000'
const RESULTS_API_URL = process.env.RESULTS_API_URL || `${BASE_URL}/api/smoke-test-results`
const REPORT_DIR = process.env.REPORT_DIR // Optional: directory to save HTML reports
const PUSHGATEWAY_URL = process.env.PUSHGATEWAY_URL // Optional: Prometheus Pushgateway base URL

interface PlaywrightTestResult {
  title: string
  status: 'passed' | 'failed' | 'skipped' | 'timedOut'
  duration: number
  errors?: string[]
}

interface PlaywrightReport {
  suites: Array<{
    title: string
    specs: Array<{
      title: string
      tests: Array<{
        status: 'expected' | 'unexpected' | 'skipped'
        results: Array<{
          status: 'passed' | 'failed' | 'skipped' | 'timedOut'
          duration: number
          error?: { message: string }
        }>
      }>
    }>
  }>
  stats: {
    expected: number
    unexpected: number
    skipped: number
    duration: number
  }
}

async function reportResults(results: {
  id: string
  startedAt: string
  completedAt?: string
  status: 'running' | 'passed' | 'failed' | 'error'
  totalTests?: number
  passedTests?: number
  failedTests?: number
  durationMs?: number
  resultsJson?: string
  errorMessage?: string
}): Promise<void> {
  try {
    console.log(`Reporting results to ${RESULTS_API_URL}...`)
    const response = await fetch(RESULTS_API_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(results),
    })

    if (!response.ok) {
      const text = await response.text()
      console.error(`Failed to report results: ${response.status} ${text}`)
    } else {
      console.log('Results reported successfully')
    }
  } catch (error) {
    console.error('Error reporting results:', error)
  }
}

/**
 * Push the run's result metrics to the Prometheus Pushgateway as a single
 * series (job="smoke-tests", no pod label).
 *
 * Why: the smoke result is one logical fact about a load-balanced run, not a
 * per-pod fact. The abaci-app replicas each keep their own in-memory prom-client
 * gauges, so a result POST only updates one pod's gauge and the others go stale
 * (diverging series in Prometheus). Pushgateway is the canonical batch-job sink:
 * a single, pod-independent series. No-op when PUSHGATEWAY_URL is unset (local
 * dev). Best-effort — never throws, never fails the run.
 */
async function pushMetricsToPushgateway(m: {
  status: 'passed' | 'failed' | 'error'
  completedAt: string
  durationMs?: number
  totalTests?: number
  passedTests?: number
  failedTests?: number
}): Promise<void> {
  if (!PUSHGATEWAY_URL) return

  const lines: string[] = []
  const gauge = (name: string, help: string, value: number) => {
    lines.push(`# HELP ${name} ${help}`)
    lines.push(`# TYPE ${name} gauge`)
    lines.push(`${name} ${value}`)
  }

  gauge(
    'smoke_test_last_status',
    'Status of the last smoke test run (1=passed, 0=failed/error)',
    m.status === 'passed' ? 1 : 0
  )
  gauge(
    'smoke_test_last_run_timestamp_seconds',
    'Unix timestamp of the last completed smoke test run',
    Math.floor(new Date(m.completedAt).getTime() / 1000)
  )
  if (m.durationMs !== undefined) {
    gauge(
      'smoke_test_last_duration_seconds',
      'Duration of the last smoke test run in seconds',
      m.durationMs / 1000
    )
  }
  if (m.totalTests !== undefined) {
    gauge(
      'smoke_test_last_total_count',
      'Total number of tests in the last smoke test run',
      m.totalTests
    )
  }
  if (m.passedTests !== undefined) {
    gauge(
      'smoke_test_last_passed_count',
      'Number of passed tests in the last smoke test run',
      m.passedTests
    )
  }
  if (m.failedTests !== undefined) {
    gauge(
      'smoke_test_last_failed_count',
      'Number of failed tests in the last smoke test run',
      m.failedTests
    )
  }

  // Exposition format requires a trailing newline.
  const body = lines.join('\n') + '\n'
  // Group by job + app so the pushed series carry job="smoke-tests" AND
  // app="abaci-app". The app grouping label matches the existing Grafana
  // "Testing" dashboard panels (which select {app="abaci-app"}), so once the
  // per-pod app-side gauges are removed this single series is the only match and
  // the dashboard reads correctly with no panel changes. PUT replaces the entire
  // group, so a prior run's metrics can't linger (e.g. passed_count from a run
  // that didn't parse a report).
  const url = `${PUSHGATEWAY_URL.replace(/\/$/, '')}/metrics/job/smoke-tests/app/abaci-app`

  try {
    console.log(`Pushing metrics to Pushgateway: ${url}`)
    // Bound the request: this push is awaited immediately before process.exit,
    // so a Pushgateway that accepts the connection but never responds (wedged
    // pod, black-holed Service IP) would otherwise hang the whole CronJob until
    // its deadline. Connection-refused already fails fast; this covers no-reply.
    const response = await fetch(url, {
      method: 'PUT',
      headers: { 'Content-Type': 'text/plain; version=0.0.4' },
      body,
      signal: AbortSignal.timeout(5000),
    })
    if (!response.ok) {
      const text = await response.text()
      console.error(`Failed to push metrics to Pushgateway: ${response.status} ${text}`)
    } else {
      console.log('Metrics pushed to Pushgateway successfully')
    }
  } catch (error) {
    console.error('Error pushing metrics to Pushgateway:', error)
  }
}

/**
 * Save HTML report to the artifacts directory
 */
function saveHtmlReport(runId: string, htmlReportDir: string, passed: boolean): string | null {
  if (!REPORT_DIR) {
    return null
  }

  try {
    // Ensure report directory exists
    if (!existsSync(REPORT_DIR)) {
      mkdirSync(REPORT_DIR, { recursive: true })
    }

    // Create run-specific directory with timestamp prefix for sorting
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
    const status = passed ? 'passed' : 'failed'
    const reportDirName = `${timestamp}_${status}_${runId.slice(0, 8)}`
    const destDir = join(REPORT_DIR, reportDirName)

    // Copy HTML report to destination
    if (existsSync(htmlReportDir)) {
      cpSync(htmlReportDir, destDir, { recursive: true })
      console.log(`HTML report saved to: ${destDir}`)

      // Copy screenshots into the report directory
      const screenshotsDir = join(process.cwd(), 'screenshots')
      if (existsSync(screenshotsDir)) {
        const destScreenshots = join(destDir, 'screenshots')
        cpSync(screenshotsDir, destScreenshots, { recursive: true })
        console.log(`Screenshots copied to: ${destScreenshots}`)
      }

      // Update "latest" symlink
      const latestLink = join(REPORT_DIR, 'latest')
      try {
        if (existsSync(latestLink)) {
          unlinkSync(latestLink)
        }
        symlinkSync(reportDirName, latestLink)
        console.log(`Updated 'latest' symlink to: ${reportDirName}`)
      } catch (symlinkError) {
        console.warn('Could not create latest symlink:', symlinkError)
      }

      // Clean up old reports (keep last 20)
      cleanupOldReports(20)

      return reportDirName
    } else {
      console.warn(`HTML report directory not found: ${htmlReportDir}`)
      return null
    }
  } catch (error) {
    console.error('Error saving HTML report:', error)
    return null
  }
}

/**
 * Remove old reports, keeping only the most recent N
 */
function cleanupOldReports(keepCount: number): void {
  if (!REPORT_DIR || !existsSync(REPORT_DIR)) {
    return
  }

  try {
    const entries = readdirSync(REPORT_DIR)
      .filter((name) => {
        // Only consider directories that match our naming pattern (timestamp_status_id)
        const fullPath = join(REPORT_DIR, name)
        return (
          name !== 'latest' &&
          existsSync(fullPath) &&
          statSync(fullPath).isDirectory() &&
          /^\d{4}-\d{2}-\d{2}T/.test(name)
        )
      })
      .sort()
      .reverse() // Most recent first

    // Remove old entries
    const toRemove = entries.slice(keepCount)
    for (const dir of toRemove) {
      const fullPath = join(REPORT_DIR, dir)
      rmSync(fullPath, { recursive: true, force: true })
      console.log(`Removed old report: ${dir}`)
    }
  } catch (error) {
    console.error('Error cleaning up old reports:', error)
  }
}

async function runTests(): Promise<void> {
  const runId = randomUUID()
  const startedAt = new Date().toISOString()

  console.log(`Starting smoke test run: ${runId}`)
  console.log(`Base URL: ${BASE_URL}`)
  console.log(`Results API: ${RESULTS_API_URL}`)

  // Report that we're starting
  await reportResults({
    id: runId,
    startedAt,
    status: 'running',
  })

  const reportDir = join(process.cwd(), 'playwright-report')
  const htmlReportDir = join(process.cwd(), 'playwright-html-report')
  const jsonReportPath = join(reportDir, 'results.json')

  // Ensure report directories exist
  if (!existsSync(reportDir)) {
    mkdirSync(reportDir, { recursive: true })
  }
  if (!existsSync(htmlReportDir)) {
    mkdirSync(htmlReportDir, { recursive: true })
  }

  try {
    // Run Playwright tests with JSON reporter (stdout) and HTML reporter (directory)
    // Note: testDir in playwright.config.ts is './e2e', so we pass 'smoke' not 'e2e/smoke'
    const playwrightProcess = spawn(
      'npx',
      ['playwright', 'test', 'smoke', '--reporter=json,html', `--output=${reportDir}`],
      {
        cwd: process.cwd(),
        env: {
          ...process.env,
          BASE_URL,
          CI: 'true', // Ensure CI mode
          PLAYWRIGHT_HTML_REPORT: htmlReportDir, // Output directory for HTML report
        },
        stdio: ['inherit', 'pipe', 'pipe'],
      }
    )

    let stdout = ''
    let stderr = ''

    playwrightProcess.stdout?.on('data', (data) => {
      stdout += data.toString()
    })

    playwrightProcess.stderr?.on('data', (data) => {
      stderr += data.toString()
      process.stderr.write(data)
    })

    const exitCode = await new Promise<number>((resolve) => {
      playwrightProcess.on('close', (code) => {
        resolve(code ?? 1)
      })
    })

    const completedAt = new Date().toISOString()
    const durationMs = new Date(completedAt).getTime() - new Date(startedAt).getTime()

    // Try to parse the JSON report from stdout
    let report: PlaywrightReport | null = null
    try {
      report = JSON.parse(stdout)
    } catch {
      console.log('Could not parse JSON report from stdout')
    }

    if (report) {
      const totalTests = report.stats.expected + report.stats.unexpected + report.stats.skipped
      const passedTests = report.stats.expected
      const failedTests = report.stats.unexpected
      const passed = failedTests === 0

      // Save HTML report to artifacts directory
      const savedReportDir = saveHtmlReport(runId, htmlReportDir, passed)
      if (savedReportDir) {
        console.log(`HTML report: https://dev.abaci.one/smoke-reports/${savedReportDir}/`)
      }

      await reportResults({
        id: runId,
        startedAt,
        completedAt,
        status: passed ? 'passed' : 'failed',
        totalTests,
        passedTests,
        failedTests,
        durationMs,
        resultsJson: JSON.stringify(report),
      })

      await pushMetricsToPushgateway({
        status: passed ? 'passed' : 'failed',
        completedAt,
        durationMs,
        totalTests,
        passedTests,
        failedTests,
      })

      console.log(`\nTest run completed:`)
      console.log(`  Total: ${totalTests}`)
      console.log(`  Passed: ${passedTests}`)
      console.log(`  Failed: ${failedTests}`)
      console.log(`  Duration: ${durationMs}ms`)

      process.exit(exitCode)
    } else {
      // Fallback: report based on exit code
      const passed = exitCode === 0

      // Save HTML report to artifacts directory
      const savedReportDir = saveHtmlReport(runId, htmlReportDir, passed)
      if (savedReportDir) {
        console.log(`HTML report: https://dev.abaci.one/smoke-reports/${savedReportDir}/`)
      }

      await reportResults({
        id: runId,
        startedAt,
        completedAt,
        status: passed ? 'passed' : 'failed',
        durationMs,
        errorMessage: exitCode !== 0 ? `Playwright exited with code ${exitCode}` : undefined,
      })

      await pushMetricsToPushgateway({
        status: passed ? 'passed' : 'failed',
        completedAt,
        durationMs,
      })

      process.exit(exitCode)
    }
  } catch (error) {
    const completedAt = new Date().toISOString()
    const durationMs = new Date(completedAt).getTime() - new Date(startedAt).getTime()

    await reportResults({
      id: runId,
      startedAt,
      completedAt,
      status: 'error',
      durationMs,
      errorMessage: error instanceof Error ? error.message : 'Unknown error',
    })

    await pushMetricsToPushgateway({
      status: 'error',
      completedAt,
      durationMs,
    })

    console.error('Error running tests:', error)
    process.exit(1)
  }
}

runTests()