Chapter 12: Automated Testing, CI/CD, and Verification

This is an LLM ass-isted document, as are all in the ass/ subdirectory.
Of these, here in the dump/ subdirectory I keep the sloppy & doubtful ones.
I keep these as learning materials for myself, yet to be went thru.

Return to index

1. The Illusion vs. Reality of Automated UI Testing

A common failure in testing retro software is writing a naive script that clicks a web button, checks that the web page didn't throw a JavaScript exception, and declares victory.

That does not verify that a Palm OS application executed.

When testing Palm OS software inside an emulator (like CloudpilotEmu or Mu), an application can fail in dozens of silent ways while the host emulator happily keeps running:

  1. Corrupted PRC header attribute flags (0x0001 instead of 0x0009): The emulator's installDatabase() promise resolves, but Palm OS silently marks the database non-executable and refuses to show an icon in the launcher.
  2. Odd-Address Alignment Bus Crash: The DragonBall CPU triggers an Address Error exception vector ($0000000C) and freezes the internal Palm OS event loop, but the HTML5 canvas element still displays the previous frame.
  3. A5 World / Global Constructor Crash: Global object memory accessed before Palm OS initialization causes a fatal reset loop, resetting the virtual handheld back to the System Preferences screen.

To achieve genuine automated verification, an automated test harness must inspect the internal state of the emulated system, perform heuristic pixel-level framebuffer analysis, and compare against known golden screenshots.

2. Architecture of a Rigorous Palm OS Test Pipeline

┌────────────────────────────────────────────────────────┐
│                   Test Orchestrator                    │
│   (Node.js / Python / Playwright / HTTP Test Server)   │
└───────────────────────────┬────────────────────────────┘
                            │
              ┌─────────────┼─────────────┐
              ▼             ▼             ▼
   [ Emulation State ] [ Pixel Density ] [ Golden Diff ]
   - ROM load confirm  - White/Black check- Pixel diff vs
   - DB presence test  - UI content ratio - canonical PNG
   - launchByName code - Fatal alert scan - Bounded tolerance
              │             │             │
              └─────────────┼─────────────┘
                            ▼
               ┌────────────────────────┐
               │ Genuine Verdict:       │
               │ PASS: UI Drawn & Valid │
               │ FAIL: Blank/Bus Error  │
               └────────────────────────┘

3. Test Layer 1: Emulation API Verification (JavaScript / CloudpilotEmu)

CloudpilotEmu's embedded API exports asynchronous control hooks. Rather than a monolithic script, we split the responsibilities into focused, clean helper functions.

3.1. Step 1: Fetching and Validating the PRC Binary

Before sending data to the emulator, verify that the file exists and has non-zero size:

// Step 1: Fetch binary buffer from test server
async function fetchPrc(prcUrl) {
    const resp = await fetch(prcUrl);
    if (!resp.ok) {
        throw new Error(`Failed to load PRC from ${prcUrl}: HTTP ${resp.status}`);
    }
    const buffer = await resp.arrayBuffer();
    if (buffer.byteLength < 50) {
        throw new Error(`Corrupted or truncated PRC file (${buffer.byteLength} bytes)`);
    }
    return new Uint8Array(buffer);
}

3.2. Step 2: Database Installation and Storage Check

Install the database into the emulated Storage Heap:

// Step 2: Install into Palm OS Storage Heap
async function installPrc(emulator, prcBytes) {
    // installDatabase throws if the database format or header is invalid
    await emulator.installDatabase(prcBytes);
}

3.3. Step 3: Launch Verification and Render Settling

Launch the database by its internal creator name and allow the Palm OS event loop sufficient clock cycles to draw UI elements:

// Step 3: Launch application and wait for UI paint
async function launchAndSettle(emulator, dbName, waitMs = 2000) {
    try {
        await emulator.launchByName(dbName);
    } catch (err) {
        throw new Error(`Launch failed for '${dbName}'. Verify internal DB name and byte 0x20 flag: ${err.message}`);
    }
    // Palm OS Window Manager requires 1.5 - 2.0s to dispatch frmOpenEvent
    await new Promise(resolve => setTimeout(resolve, waitMs));
}

4. Test Layer 2: Heuristic Framebuffer Analysis (Python / PIL)

Once the application is launched, how do you verify that it actually rendered its form or alert dialog rather than a white screen, black screen, or fatal exception box?

We break the analysis into small, verifiable Python evaluation functions.

4.1. Step 1: Detecting Dead Displays (Whiteout & Blackout)

A crashed emulator or an unhandled exception before the first draw leaves the canvas in an extreme state:

import numpy as np

def check_display_power(arr, threshold=0.98):
    """Fails if the screen is entirely white or entirely black."""
    w, h, _ = arr.shape
    total = w * h

    white = np.sum((arr[:, :, 0] > 240) & (arr[:, :, 1] > 240) & (arr[:, :, 2] > 240)) / total
    black = np.sum((arr[:, :, 0] < 20)  & (arr[:, :, 1] < 20)  & (arr[:, :, 2] < 20))  / total

    if white > threshold:
        return False, f"Screen is {white*100:.1f}% white (unrendered form or early crash)"
    if black > threshold:
        return False, f"Screen is {black*100:.1f}% black (emulator stopped or display off)"
    return True, "Display state active"

4.2. Step 2: Validating Active UI Content Density

An authentic Palm OS form or alert dialog features black borders, labels, and buttons on a light LCD background. We check that active UI content falls within a realistic envelope (3% to 40%):

def check_ui_content_density(arr, min_ratio=0.03, max_ratio=0.50):
    """Asserts that dark pixel ratio matches expected UI elements."""
    w, h, _ = arr.shape
    total = w * h

    dark_pixels = np.sum((arr[:, :, 0] < 70) & (arr[:, :, 1] < 70) & (arr[:, :, 2] < 70))
    ratio = dark_pixels / total

    if ratio < min_ratio:
        return False, f"Insufficient UI content ({ratio*100:.1f}% < {min_ratio*100:.1f}%)"
    if ratio > max_ratio:
        return False, f"Abnormally high dark pixel ratio ({ratio*100:.1f}% > {max_ratio*100:.1f}%)"
    return True, f"UI content density valid ({ratio*100:.1f}%)"

4.3. Step 3: Detecting the Palm OS "Fatal Alert" Banner

When an Address Error or Bus Error occurs, Palm OS halts and draws a characteristic dark banner across the upper third of the screen with the text "Fatal Alert". We scan this region specifically:

def check_for_fatal_alert(arr):
    """Scans upper-third region for the characteristic crash alert header."""
    h = arr.shape[0]
    # Region where Palm OS centers the Fatal Alert banner
    banner_slice = arr[int(h * 0.18):int(h * 0.32), :, :]
    dark_in_banner = np.sum((banner_slice[:, :, 0] < 30) &
                            (banner_slice[:, :, 1] < 30) &
                            (banner_slice[:, :, 2] < 30))
    ratio = dark_in_banner / banner_slice.size

    if ratio > 0.60:
        return False, "Fatal Exception alert dialog detected on screen!"
    return True, "No crash alert detected"

5. Test Layer 3: Visual Regression Testing Against Golden Screenshots

Heuristic analysis confirms that some UI rendered, but visual regression testing verifies that the exact expected UI rendered without layout shifts, clipped fonts, or distorted buttons.

We compare the captured screenshot against a known reference ("golden") screenshot:

5.1. Step 1: Mean Squared Error (MSE) & Peak Signal-to-Noise Ratio (PSNR)

We measure differences across the RGB arrays:

from PIL import Image
import numpy as np

def compute_image_diff(test_path, golden_path):
    """Computes Root Mean Square Error (RMSE) and differing pixel count."""
    img_test = Image.open(test_path).convert('RGB')
    img_gold = Image.open(golden_path).convert('RGB')

    if img_test.size != img_gold.size:
        return False, f"Size mismatch: {img_test.size} vs {img_gold.size}", 100.0

    arr_test = np.array(img_test, dtype=np.float32)
    arr_gold = np.array(img_gold, dtype=np.float32)

    # Compute per-pixel Euclidean color distance
    diff = np.sqrt(np.sum((arr_test - arr_gold) ** 2, axis=2))

    # Tolerant threshold: allow minor 1-2 pixel anti-aliasing variations
    diff_pixels = np.sum(diff > 15.0)
    total_pixels = img_test.size[0] * img_test.size[1]
    diff_pct = (diff_pixels / total_pixels) * 100.0

    rmse = np.sqrt(np.mean((arr_test - arr_gold) ** 2))
    return True, f"Diff: {diff_pct:.2f}% pixels, RMSE: {rmse:.2f}", diff_pct

5.2. Step 2: Generating Visual Diff Heatmaps

When a test fails, developers need to see where the discrepancy occurred. We generate a visual diff mask:

def generate_diff_heatmap(test_path, golden_path, output_heatmap_path):
    """Generates an image highlighting differing pixels in bright red."""
    img_test = Image.open(test_path).convert('RGB')
    img_gold = Image.open(golden_path).convert('RGB')

    arr_test = np.array(img_test)
    arr_gold = np.array(img_gold)

    # Base: dimmed grayscale version of golden image
    gray = np.dot(arr_gold[...,:3], [0.2989, 0.5870, 0.1140]).astype(np.uint8)
    heatmap = np.stack((gray // 2, gray // 2, gray // 2), axis=2)

    # Highlight differences in bright red
    diff_mask = np.any(np.abs(arr_test.astype(int) - arr_gold.astype(int)) > 15, axis=2)
    heatmap[diff_mask] = [255, 0, 0] # Bright red

    diff_img = Image.fromarray(heatmap)
    diff_img.save(output_heatmap_path)
    print(f"Diff heatmap saved to {output_heatmap_path}")

5.3. Step 3: Setting Realistic Retro Tolerances

In retro emulation, why can't we require 0.00% exact bit-for-bit matches?

  • Blinking Insertion Carets: An editable text field toggles its vertical bar cursor every 500 ms (~0.05% pixel variance).
  • Battery & Clock Indicators: The top title bar may update the battery icon or minutes display between runs.
  • Color Depth Mapping: Minor palette quantization differences between display engines.

The Golden Rule: A tolerance of ≤ 0.5% pixel difference accommodates clock ticks and blinking cursors while instantly catching broken layouts, missing buttons, or crash dialogs!

6. Complete Verification Script (verify_app.py)

Here is the clean, integrated verification script:

#!/usr/bin/env python3
import sys
from PIL import Image
import numpy as np

def run_full_verification(screenshot_path, golden_path=None):
    print(f"==================================================")
    print(f"  Palm OS Automated Visual Verification Harness   ")
    print(f"  Target: {screenshot_path}")
    print(f"==================================================")

    img = Image.open(screenshot_path).convert('RGB')
    arr = np.array(img)

    # 1. Screen power check
    ok, msg = check_display_power(arr)
    print(f"  [1/4] Power & Blank Check  : {'PASS' if ok else 'FAIL'} ({msg})")
    if not ok: return False

    # 2. UI Content density check
    ok, msg = check_ui_content_density(arr)
    print(f"  [2/4] Content Density Check: {'PASS' if ok else 'FAIL'} ({msg})")
    if not ok: return False

    # 3. Fatal exception check
    ok, msg = check_for_fatal_alert(arr)
    print(f"  [3/4] Fatal Exception Check: {'PASS' if ok else 'FAIL'} ({msg})")
    if not ok: return False

    # 4. Golden screenshot comparison (if provided)
    if golden_path:
        ok, msg, diff_pct = compute_image_diff(screenshot_path, golden_path)
        passed = ok and (diff_pct <= 0.5)
        print(f"  [4/4] Golden Screenshot Diff: {'PASS' if passed else 'FAIL'} ({msg})")
        if not passed:
            generate_diff_heatmap(screenshot_path, golden_path, "diff-heatmap.png")
            return False
    else:
        print(f"  [4/4] Golden Screenshot Diff: SKIPPED (no reference provided)")

    print("==================================================")
    print("  VERDICT: ALL VERIFICATION CHECKS PASSED!")
    print("==================================================")
    return True

if __name__ == '__main__':
    if len(sys.argv) < 2:
        print(f"Usage: {sys.argv[0]} <test.png> [golden.png]")
        sys.exit(2)
    gold = sys.argv[2] if len(sys.argv) > 2 else None
    success = run_full_verification(sys.argv[1], gold)
    sys.exit(0 if success else 1)

7. Headless Orchestration (Playwright Integration)

We invoke the browser headlessly and run our modular verification:

// run_test.js — Modular Playwright Test Driver
const { chromium } = require('playwright');
const { execSync } = require('child_process');

(async () => {
    const browser = await chromium.launch();
    const page = await browser.newPage();
    await page.goto('http://localhost:3000/index.html');

    // Wait for emulator runtime
    await page.waitForFunction(() => typeof cloudpilot !== 'undefined');

    // 1. Boot ROM
    await page.click('#btnLoad');
    await page.waitForFunction(() => document.getElementById('status').textContent.includes('Running'));

    // 2. Install application PRC
    await page.click('#gpp14h');
    await new Promise(r => setTimeout(r, 1000));

    // 3. Launch application
    await page.evaluate(() => launch('Gpp14Modern'));
    await new Promise(r => setTimeout(r, 2000));

    // 4. Capture canvas
    const canvas = await page.$('#emu');
    await canvas.screenshot({ path: '/tmp/current-run.png' });
    await browser.close();

    // 5. Run Python Verification Suite
    try {
        execSync('python3 verify_app.py /tmp/current-run.png references/golden-gpp14.png', { stdio: 'inherit' });
        console.log("CI Pipeline Success!");
        process.exit(0);
    } catch (err) {
        console.error("CI Pipeline Failed verification!");
        process.exit(1);
    }
})();

8. Unit Testing Business Logic on the Host

Isolate platform-independent algorithms from GUI APIs and test them on Linux host using assertions:

// math_engine.hpp — Portable business logic
#pragma once

class MathEngine {
    long accumulator_ = 0;
public:
    constexpr explicit MathEngine(long initial = 0) : accumulator_(initial) {}
    void add(long val) { accumulator_ += val; }
    void multiply(long val) { accumulator_ *= val; }
    long value() const { return accumulator_; }
};

Compile and run natively in one second on your Linux host:

g++ -std=c++20 -O2 test_math.cpp -o test_math && ./test_math

Once the business logic is verified on the host, include math_engine.hpp into your Palm OS hello.cpp application with complete confidence!

9. Further Reading & Reference Resources