All files / src/adapters allure.ts

94.5% Statements 86/91
89.02% Branches 73/82
100% Functions 12/12
94.31% Lines 83/88

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                                                                                                                          33x                       153x             153x 153x   567x           153x 18x   13x       18x   12x     18x             135x 135x 135x 135x 135x 135x 547x               547x 414x 414x   6x 6x             6x   408x 137x 271x 137x 134x 133x 5x             128x     135x 4x             135x 4x             135x 8x             135x             1x             135x 9x             126x 2x               135x 135x 1x 134x 1x     133x 1x             132x 1x               135x 109x   115x   115x           109x                 153x             150x 150x 150x   150x 150x 104x     46x             104x   102x 102x                       102x 102x   2x             2x   100x 100x 100x 100x   104x       733x               91x               46x       48x       15x    
import { readdir, readFile } from "node:fs/promises";
import { join } from "node:path";
 
import type { Evidence } from "../model.js";
import {
  canonicalCaseIdError,
  interoperableStringError,
  localId,
} from "../id.js";
 
/** The small, Moura-owned subset of an Allure result used during conversion. */
export interface AllureEvidenceResult {
  readonly name?: unknown;
  readonly labels?: readonly AllureEvidenceLabel[];
  readonly status?: unknown;
}
 
export interface AllureEvidenceLabel {
  readonly name?: unknown;
  readonly value?: unknown;
}
 
export type EvidenceAdapterIssueCode =
  | "invalid-result"
  | "invalid-label"
  | "invalid-moura-requirement-label"
  | "invalid-moura-scenario-label"
  | "invalid-moura-case-label"
  | "invalid-moura-layer-label"
  | "missing-moura-requirement"
  | "missing-moura-scenario"
  | "missing-moura-case"
  | "ambiguous-moura-hierarchy"
  | "missing-moura-layer"
  | "multiple-moura-layers"
  | "missing-status"
  | "malformed-status"
  | "unknown-status"
  | "unsupported-status"
  | "malformed-json"
  | "unreadable-results-directory"
  | "unreadable-result-file";
 
export interface EvidenceAdapterIssue {
  readonly code: EvidenceAdapterIssueCode;
  readonly message: string;
  readonly source?: string;
}
 
export interface EvidenceAdapterResult {
  readonly evidence: readonly Evidence[];
  readonly issues: readonly EvidenceAdapterIssue[];
  readonly unmapped?: readonly UnmappedResult[];
}
 
/** An explicitly Moura-managed Allure result without authoritative mapping. */
export interface UnmappedResult {
  readonly name: string;
  readonly source?: string;
}
 
const supportedStatuses = new Set<Evidence["status"]>([
  "passed",
  "failed",
  "broken",
  "skipped",
]);
 
/** Convert one parsed Allure result. Only explicitly managed unlabeled results are unmapped. */
export function convertAllureResult(
  input: unknown,
  source?: string,
): EvidenceAdapterResult {
  Iif (!isRecord(input))
    return adapterFailure(
      "invalid-result",
      "Allure result must be a JSON object",
      source,
    );
 
  const labels = Array.isArray(input.labels) ? input.labels : [];
  const mouraLabels = labels.filter(
    (label) =>
      isRecord(label) &&
      (label.name === "moura_requirement" ||
        label.name === "moura_scenario" ||
        label.name === "moura_case" ||
        label.name === "moura_layer"),
  );
  if (mouraLabels.length === 0) {
    const managed = labels.some(
      (label) =>
        isRecord(label) &&
        label.name === "moura_traceability" &&
        label.value === "managed",
    );
    if (!managed) return { evidence: [], issues: [] };
    const name =
      typeof input.name === "string" && input.name.length > 0
        ? input.name
        : "Unnamed Allure result";
    return {
      evidence: [],
      issues: [],
      unmapped: [{ name, ...(source === undefined ? {} : { source }) }],
    };
  }
 
  const issues: EvidenceAdapterIssue[] = [];
  const requirementValues: string[] = [];
  const scenarioValues: string[] = [];
  const caseValues: string[] = [];
  const layerValues: string[] = [];
  for (const label of mouraLabels) {
    Iif (typeof label.value !== "string" || label.value.length === 0) {
      issues.push(
        issue(
          "invalid-label",
          `${String(label.name)} must have a non-empty string value`,
          source,
        ),
      );
    } else if (label.name !== "moura_layer") {
      try {
        localId(label.value);
      } catch {
        const kind = String(label.name).replace("moura_", "");
        issues.push(
          issue(
            `invalid-moura-${kind}-label` as EvidenceAdapterIssueCode,
            `${String(label.name)} contains characters or structure not allowed in a local Moura ID`,
            source,
          ),
        );
        continue;
      }
      if (label.name === "moura_requirement")
        requirementValues.push(label.value);
      else if (label.name === "moura_scenario")
        scenarioValues.push(label.value);
      else caseValues.push(label.value);
    } else if (interoperableStringError(label.value)) {
      issues.push(
        issue(
          "invalid-moura-layer-label",
          "moura_layer contains characters not allowed in a Moura verification-layer name",
          source,
        ),
      );
    } else layerValues.push(label.value);
  }
 
  if (requirementValues.length === 0)
    issues.push(
      issue(
        "missing-moura-requirement",
        "Result has no valid moura_requirement label",
        source,
      ),
    );
  if (scenarioValues.length === 0)
    issues.push(
      issue(
        "missing-moura-scenario",
        "Result has no valid moura_scenario label",
        source,
      ),
    );
  if (caseValues.length === 0)
    issues.push(
      issue(
        "missing-moura-case",
        "Result has no valid moura_case label",
        source,
      ),
    );
  if (
    requirementValues.length > 0 &&
    scenarioValues.length > 0 &&
    caseValues.length > 0 &&
    (requirementValues.length !== scenarioValues.length ||
      scenarioValues.length !== caseValues.length)
  )
    issues.push(
      issue(
        "ambiguous-moura-hierarchy",
        "Result must have equally many ordered moura_requirement, moura_scenario, and moura_case labels",
        source,
      ),
    );
  if (layerValues.length === 0)
    issues.push(
      issue(
        "missing-moura-layer",
        "Result has no valid moura_layer label",
        source,
      ),
    );
  else if (layerValues.length > 1)
    issues.push(
      issue(
        "multiple-moura-layers",
        "Result must have exactly one moura_layer label",
        source,
      ),
    );
 
  const status = input.status;
  if (status === undefined)
    issues.push(issue("missing-status", "Result has no status", source));
  else if (typeof status !== "string")
    issues.push(
      issue("malformed-status", "Result status must be a string", source),
    );
  else if (status === "unknown")
    issues.push(
      issue(
        "unknown-status",
        "Allure status unknown is invalid evidence",
        source,
      ),
    );
  else if (!supportedStatuses.has(status as Evidence["status"]))
    issues.push(
      issue(
        "unsupported-status",
        `Unsupported Allure status ${JSON.stringify(status)}`,
        source,
      ),
    );
 
  if (issues.length > 0) return { evidence: [], issues };
  const canonicalCases = caseValues.map(
    (testCase, index) =>
      `${requirementValues[index]}/${scenarioValues[index]}/${testCase}`,
  );
  Iif (canonicalCases.some((caseId) => canonicalCaseIdError(caseId)))
    return adapterFailure(
      "ambiguous-moura-hierarchy",
      "Result hierarchy labels do not form valid canonical Moura Case IDs",
      source,
    );
  const evidence: Evidence = {
    covers: [...new Set(canonicalCases)],
    layer: layerValues[0]!,
    status: status as Evidence["status"],
    ...(typeof input.name === "string" && input.name.trim()
      ? { name: input.name }
      : {}),
    ...(source === undefined ? {} : { source }),
  };
  return { evidence: [evidence], issues: [] };
}
 
/** Load only sorted `*-result.json` files from an Allure results directory. */
export async function loadAllureResultsDirectory(
  directory: string,
): Promise<EvidenceAdapterResult> {
  const evidence: Evidence[] = [];
  const issues: EvidenceAdapterIssue[] = [];
  const unmapped: UnmappedResult[] = [];
  let files: string[];
  try {
    files = (await readdir(directory))
      .filter((file) => file.endsWith("-result.json"))
      .sort(compareStrings);
  } catch (error) {
    return adapterFailure(
      "unreadable-results-directory",
      `Could not read Allure results directory: ${errorMessage(error)}`,
      directory,
    );
  }
 
  for (const source of files) {
    let contents: string;
    try {
      contents = await readFile(join(directory, source), "utf8");
    } catch (error) {
      issues.push(
        issue(
          "unreadable-result-file",
          `Could not read Allure result: ${errorMessage(error)}`,
          source,
        ),
      );
      continue;
    }
    let parsed: unknown;
    try {
      parsed = JSON.parse(contents);
    } catch (error) {
      issues.push(
        issue(
          "malformed-json",
          `Could not parse Allure result JSON: ${errorMessage(error)}`,
          source,
        ),
      );
      continue;
    }
    const converted = convertAllureResult(parsed, source);
    evidence.push(...converted.evidence);
    issues.push(...converted.issues);
    unmapped.push(...(converted.unmapped ?? []));
  }
  return { evidence, issues, unmapped };
}
 
function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}
 
function issue(
  code: EvidenceAdapterIssueCode,
  message: string,
  source?: string,
): EvidenceAdapterIssue {
  return { code, message, ...(source === undefined ? {} : { source }) };
}
 
function adapterFailure(
  code: EvidenceAdapterIssueCode,
  message: string,
  source?: string,
): EvidenceAdapterResult {
  return { evidence: [], issues: [issue(code, message, source)] };
}
 
function errorMessage(error: unknown): string {
  return error instanceof Error ? error.message : String(error);
}
 
function compareStrings(left: string, right: string): number {
  return left < right ? -1 : left > right ? 1 : 0;
}