All files / src/tester testProject.ts

16.07% Statements 18/112
15.68% Branches 8/51
25% Functions 2/8
15.88% Lines 17/107

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 3121x       1x 1x 1x   1x 1x   1x   1x 1x 1x                                             4x 4x   3x 3x 8x     3x                                                                                                                                                                                                                                                                                                                                                                                                                                   1x                                                                                                              
import * as fs from "fs";
 
import type { TestSegment, TestFeature, Test, DatafileContent } from "@featurevisor/types";
 
import { testSegment } from "./testSegment";
import { testFeature } from "./testFeature";
import { CLI_FORMAT_BOLD, CLI_FORMAT_GREEN, CLI_FORMAT_RED } from "./cliFormat";
import { Dependencies } from "../dependencies";
import { prettyDuration } from "./prettyDuration";
import { printTestResult } from "./printTestResult";
 
import { buildDatafile, buildTargetDatafile } from "../builder";
import { Plugin } from "../cli";
import { listEntities } from "../list";
import { getProjectSetExecutions, printSetHeader } from "../sets";
import { resolveTargets } from "../targeting";
 
export interface TestProjectOptions {
  keyPattern?: string;
  assertionPattern?: string;
  verbose?: boolean;
  showDatafile?: boolean;
  onlyFailures?: boolean;
  inflate?: number;
  target?: string | string[];
}
 
export interface ExecutionResult {
  passed: boolean;
  assertionsCount: {
    passed: number;
    failed: number;
  };
}
 
// the key can be either "<EnvironmentKey>" or "<EnvironmentKey>-target-<Target>"
export type DatafileContentByKey = Map<string | false, DatafileContent>;
 
export function filterTestForTargets(test: Test, selectedTargetKeys?: string[]): Test | undefined {
  if (!selectedTargetKeys || !(test as TestFeature).feature) return test;
 
  const featureTest = test as TestFeature;
  const assertions = featureTest.assertions.filter(
    (assertion) => !assertion.target || selectedTargetKeys.includes(assertion.target),
  );
 
  return assertions.length > 0 ? { ...featureTest, assertions } : undefined;
}
 
async function buildTestDatafilesForEnvironment(
  deps: Dependencies,
  datafileContentByKey: DatafileContentByKey,
  environment: string | false,
  selectedTargetKeys?: string[],
) {
  const { projectConfig, datasource, options } = deps;
  const existingState = await datasource.readState(environment);
  const datafileContent = await buildDatafile(
    projectConfig,
    datasource,
    {
      revision: "include-all-features",
      environment,
      inflate: options.inflate,
    },
    existingState,
  );
 
  datafileContentByKey.set(environment, datafileContent as DatafileContent);
 
  const targetKeys = selectedTargetKeys || (await datasource.listTargets());
  for (const targetKey of targetKeys) {
    const target = await datasource.readTarget(targetKey);
    const targetDatafileContent = await buildTargetDatafile({
      projectConfig,
      datasource,
      target,
      environment,
      existingState,
      revision: "include-target-features",
      inflate: options.inflate,
    });
 
    datafileContentByKey.set(`${environment}-target-${targetKey}`, targetDatafileContent);
  }
}
 
export async function executeTest(
  test: Test,
  deps: Dependencies,
  options: TestProjectOptions,
  datafileContentByKey: DatafileContentByKey,
): Promise<ExecutionResult | undefined> {
  const { datasource, projectConfig, rootDirectoryPath } = deps;
 
  const extension = datasource.getExtension();
  const relativeTestFilePath = test.key + (extension ? `.${extension}` : "");
 
  const tAsSegment = test as TestSegment;
  const tAsFeature = test as TestFeature;
  const key = tAsSegment.segment || tAsFeature.feature;
  const type = tAsSegment.segment ? "segment" : "feature";
 
  const executionResult: ExecutionResult = {
    passed: true,
    assertionsCount: {
      passed: 0,
      failed: 0,
    },
  };
 
  if (!key) {
    console.error(`  => Invalid test: ${JSON.stringify(test)}`);
    executionResult.passed = false;
 
    return executionResult;
  }
 
  let testResult;
  if (type === "segment") {
    testResult = await testSegment(datasource, tAsSegment, options);
  } else {
    testResult = await testFeature(
      datasource,
      projectConfig,
      tAsFeature,
      options,
      datafileContentByKey,
    );
  }
 
  if (!options.onlyFailures) {
    // show all
    printTestResult(testResult, relativeTestFilePath, rootDirectoryPath);
  } else {
    // show failed only
    if (!testResult.passed) {
      printTestResult(testResult, relativeTestFilePath, rootDirectoryPath);
    }
  }
 
  if (!testResult.passed) {
    executionResult.passed = false;
 
    executionResult.assertionsCount.failed = testResult.assertions.filter((a) => !a.passed).length;
    executionResult.assertionsCount.passed +=
      testResult.assertions.length - executionResult.assertionsCount.failed;
  } else {
    executionResult.assertionsCount.passed = testResult.assertions.length;
  }
 
  return executionResult;
}
 
export async function testProject(
  deps: Dependencies,
  testOptions: TestProjectOptions = {},
): Promise<boolean> {
  const { rootDirectoryPath, projectConfig, datasource, options } = deps;
 
  let hasError = false;
 
  if (!fs.existsSync(projectConfig.testsDirectoryPath)) {
    console.error(`Tests directory does not exist: ${projectConfig.testsDirectoryPath}`);
    hasError = true;
 
    return hasError;
  }
 
  const startTime = Date.now();
 
  let passedTestsCount = 0;
  let failedTestsCount = 0;
 
  let passedAssertionsCount = 0;
  let failedAssertionsCount = 0;
 
  const datafileContentByKey: DatafileContentByKey = new Map();
  const selectedTargets = testOptions.target
    ? await resolveTargets(datasource, testOptions.target, { defaultToAll: false })
    : undefined;
  const selectedTargetKeys = selectedTargets?.map((target) => target.key);
 
  // with environments
  if (Array.isArray(projectConfig.environments)) {
    for (const environment of projectConfig.environments) {
      await buildTestDatafilesForEnvironment(
        deps,
        datafileContentByKey,
        environment,
        selectedTargetKeys,
      );
    }
  }
 
  // no environments
  if (!Array.isArray(projectConfig.environments)) {
    await buildTestDatafilesForEnvironment(deps, datafileContentByKey, false, selectedTargetKeys);
  }
 
  const tests = await listEntities<Test>(
    {
      rootDirectoryPath,
      projectConfig,
      datasource,
      options: {
        ...testOptions,
        applyMatrix: true,
      },
    },
    "test",
  );
 
  for (const originalTest of tests) {
    const test = filterTestForTargets(originalTest, selectedTargetKeys);
    if (!test) continue;
 
    const executionResult = await executeTest(test, deps, options, datafileContentByKey);
 
    if (!executionResult) {
      continue;
    }
 
    if (executionResult.passed) {
      passedTestsCount += 1;
    } else {
      hasError = true;
      failedTestsCount += 1;
    }
 
    passedAssertionsCount += executionResult.assertionsCount.passed;
    failedAssertionsCount += executionResult.assertionsCount.failed;
  }
 
  const diffInMs = Date.now() - startTime;
 
  if (options.onlyFailures !== true || hasError) {
    console.log("\n---");
  }
  console.log("");
 
  const testSpecsMessage = `Test specs: ${passedTestsCount} passed, ${failedTestsCount} failed`;
  const testAssertionsMessage = `Assertions: ${passedAssertionsCount} passed, ${failedAssertionsCount} failed`;
  if (hasError) {
    console.log(CLI_FORMAT_RED, testSpecsMessage);
    console.log(CLI_FORMAT_RED, testAssertionsMessage);
  } else {
    console.log(CLI_FORMAT_GREEN, testSpecsMessage);
    console.log(CLI_FORMAT_GREEN, testAssertionsMessage);
  }
 
  console.log(CLI_FORMAT_BOLD, `Time:       ${prettyDuration(diffInMs)}`);
 
  return hasError;
}
 
export const testPlugin: Plugin = {
  command: "test",
  handler: async function ({ rootDirectoryPath, projectConfig, datasource, parsed }) {
    const executions = await getProjectSetExecutions(projectConfig, datasource, parsed.set);
    let hasError = false;
 
    for (const execution of executions) {
      printSetHeader(projectConfig, execution.set);
 
      const executionHasError = await testProject(
        {
          rootDirectoryPath,
          projectConfig: execution.projectConfig,
          datasource: execution.datasource,
          options: parsed,
        },
        parsed as TestProjectOptions,
      );
 
      if (executionHasError) {
        hasError = true;
      }
    }
 
    if (hasError) {
      return false;
    }
  },
  examples: [
    {
      command: "test",
      description: "run all tests",
    },
    {
      command: "test --keyPattern=pattern",
      description: "run tests matching key pattern",
    },
    {
      command: "test --assertionPattern=pattern",
      description: "run tests matching assertion pattern",
    },
    {
      command: "test --onlyFailures",
      description: "run only failed tests",
    },
    {
      command: "test --showDatafile",
      description: "show datafile content for each test",
    },
    {
      command: "test --verbose",
      description: "show all test results",
    },
  ],
};