All files / core/blong-browser/src/components/TestRun testRunProjection.ts

18.03% Statements 11/61
9.61% Branches 5/52
7.14% Functions 1/14
19.6% Lines 10/51

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                                                                8x     8x                         27x 11x 11x 11x 11x 2x   9x           8x                                                                                                                                                                                                                                                                                                                                                
/**
 * Pure projection of executor progress into the console model.
 *
 * Kept free of the executor class and of React so a server host can import it through
 * `@feasibleone/blong-browser/testRun.ts`; the browser source and the server runner share it.
 */
import type {
    IAssertion,
    IDependencyEdge,
    IDependencyGraph,
    IStepProgress,
    ITestLatency,
    ITestProgress,
    StepArray,
} from '@feasibleone/blong-chain/browser.ts';
import type {
    ITestAssertionModel,
    ITestEdgeModel,
    ITestRunModel,
    ITestSourcePointer,
    ITestStepModel,
} from '../../types/testRun.js';
import {deriveTestRun} from './testRunModel.ts';
 
export interface ITestRunProjectionOptions {
    name: string;
    method: string;
    steps: StepArray;
    concurrency?: number;
    source?: {file?: string};
}
 
let runCounter = 0;
 
/** The largest JSON payload a step result may contribute to the wire model. */
const RESULT_LIMIT = 32_000;
 
/**
 * Make a step result JSON-safe and bounded.
 *
 * A result can be circular, hold functions or be megabytes of rows; the console only needs a
 * preview. A JSON round-trip drops what cannot cross the wire, and a payload over the limit is
 * replaced by a marker so the browser never receives the whole result.
 */
export function sanitizeResult(value: unknown): {
    result?: unknown;
    resultTruncated?: boolean;
} {
    if (value === undefined) return {};
    try {
        const json = JSON.stringify(value);
        Iif (json === undefined) return {};
        if (json.length > RESULT_LIMIT) {
            return {result: {truncated: true, bytes: json.length}, resultTruncated: true};
        }
        return {result: JSON.parse(json)};
    } catch {
        return {result: {truncated: true}, resultTruncated: true};
    }
}
 
const wireStatus = (status: IStepProgress['status']): ITestStepModel['status'] => status;
 
function pointer(source: IStepProgress['sourceLocation']): ITestSourcePointer | undefined {
    return source ? {file: source.file, line: source.line, column: source.column} : undefined;
}
 
function assertionModel(assertion: IAssertion): ITestAssertionModel {
    return {
        message: assertion.message,
        passed: assertion.passed,
        timestamp: assertion.timestamp,
        source: pointer(assertion.source),
    };
}
 
function edgeModel(edge: IDependencyEdge, run: ITestRunModel): ITestEdgeModel {
    const from = run.steps[edge.from]?.status;
    const to = run.steps[edge.to]?.status;
    const status: ITestEdgeModel['status'] =
        from === 'completed' && to === 'completed'
            ? 'done'
            : from === 'running' || to === 'running'
              ? 'active'
              : 'pending';
    return {
        id: `${edge.from}->${edge.to}:${edge.property}`,
        from: edge.from,
        to: edge.to,
        property: edge.property,
        status,
    };
}
 
function countsOf(run: ITestRunModel): ITestRunModel['counts'] {
    const counts = {total: 0, pending: 0, running: 0, completed: 0, failed: 0};
    for (const step of Object.values(run.steps)) {
        counts.total += 1;
        counts[step.status] += 1;
    }
    return counts;
}
 
function stepModels(
    steps: StepArray,
    groupPath: string[],
    order: string[],
    map: Record<string, ITestStepModel>,
): void {
    for (const item of steps) {
        if (Array.isArray(item)) {
            if (item.every(entry => typeof entry === 'string')) continue;
            const group = item as StepArray;
            stepModels(
                group,
                [...groupPath, group.name ?? `group-${groupPath.length}`],
                order,
                map,
            );
            continue;
        }
        if (typeof item !== 'function') continue;
        const stepName = item.name || 'anonymous';
        if (map[stepName]) continue;
        order.push(stepName);
        map[stepName] = {
            stepName,
            displayName: stepName,
            groupPath,
            status: 'pending',
            dependencies: [],
            dependents: [],
            assertions: {total: 0, threw: 0},
        };
    }
}
 
export function pendingBrowserRun(options: ITestRunProjectionOptions): ITestRunModel {
    const order: string[] = [];
    const steps: Record<string, ITestStepModel> = {};
    stepModels(options.steps, [], order, steps);
    const runId = `run-browser-${Date.now()}-${runCounter++}`;
    return deriveTestRun({
        runId,
        name: options.name,
        method: options.method,
        host: 'browser',
        status: 'pending',
        startedAt: Date.now(),
        concurrency: options.concurrency ?? 10,
        order,
        steps,
        edges: [],
        groups: [],
        counts: {total: 0, pending: 0, running: 0, completed: 0, failed: 0},
        assertions: {total: 0, threw: 0},
        criticalPath: [],
        logs: [],
        source: options.source,
    });
}
 
export function projectBrowserRun(
    base: ITestRunModel,
    progress: ITestProgress,
    graph: IDependencyGraph,
    latency: ITestLatency,
): ITestRunModel {
    const steps: Record<string, ITestStepModel> = {};
    for (const [name, step] of progress.steps) {
        const firstAssertionSource = step.assertionLog?.find(assertion => assertion.source)?.source;
        const projectedResult = sanitizeResult(step.result);
        steps[name] = {
            stepName: step.stepName,
            displayName: step.displayName,
            groupPath: step.groupPath,
            status: wireStatus(step.status),
            queuedAt:
                step.startTime === undefined ? undefined : step.startTime - (step.queueTime ?? 0),
            startedAt: step.startTime,
            endedAt: step.endTime,
            queueTime: step.queueTime,
            waitTime: step.waitTime,
            executionTime: step.executionTime,
            duration: step.duration,
            dependencies: [...step.dependencies],
            dependents: [...step.dependents],
            assertions: step.assertions ?? {total: 0, threw: 0},
            assertionLog: step.assertionLog?.map(assertionModel),
            progress: step.progress,
            ...projectedResult,
            error: step.error
                ? {
                      message: step.error.message,
                      stack: step.error.stack,
                      context: step.error.context,
                  }
                : undefined,
            sourceLocation: pointer(step.sourceLocation ?? firstAssertionSource),
        };
    }
    const edgeList: ITestEdgeModel[] = [...base.edges];
    for (const edge of graph.edges) {
        const model = edgeModel(edge, base);
        if (!edgeList.some(item => item.id === model.id)) edgeList.push(model);
    }
    const run = deriveTestRun({
        ...base,
        status:
            progress.status === 'failed'
                ? 'failed'
                : progress.status === 'completed'
                  ? 'completed'
                  : progress.status === 'running'
                    ? 'running'
                    : 'pending',
        startedAt: progress.startTime || base.startedAt,
        endedAt: progress.endTime,
        order: base.order
            .filter(name => steps[name])
            .concat(Object.keys(steps).filter(name => !base.order.includes(name))),
        steps,
        edges: edgeList,
        counts: {total: 0, pending: 0, running: 0, completed: 0, failed: 0},
        assertions: progress.assertions ?? {total: 0, threw: 0},
        criticalPath: latency.criticalPath,
    });
    return {...run, counts: countsOf(run)};
}