<commit_before>import QUnit from 'qunit';
import {
  currentRouteName,
  currentURL,
  getContext,
  getTestMetadata,
} from '@ember/test-helpers';
import { AxeResults, Result } from 'axe-core';
import { setCustomReporter } from './reporter';
import { DEBUG } from '@glimmer/env';

interface AxeTestResult {
  moduleName: string;
  testName: string;
  urls: string[] | Set<string>;
  routes: string[] | Set<string>;
  helpers: string[];
  stack: string;
  violations: Result[];
}

export const TEST_SUITE_RESULTS: AxeTestResult[] = [];

let currentTestResult: AxeTestResult | undefined = undefined;
let currentViolationsMap: Map<string, Result> | undefined = undefined;
let currentUrls = new Set<string>();
let currentRouteNames = new Set<string>();

export async function middlewareReporter(axeResults: AxeResults) {
  if (axeResults.violations.length === 0) {
    return;
  }

  if (!currentTestResult) {
    let { module, testName } = QUnit.config.current;
    let testMetaData = getTestMetadata(getContext());

    let stack = (!DEBUG && new Error().stack) || '';

    currentTestResult = {
      moduleName: module.name,
      testName,
      urls: [],
      routes: [],
      helpers: testMetaData.usedHelpers,
      stack,
      violations: [],
    };

    currentViolationsMap = new Map();
  }

  currentUrls.add(currentURL());
  currentRouteNames.add(currentRouteName());

  axeResults.violations.forEach((violation) => {
    let rule = currentViolationsMap!.get(violation.id);

    if (rule === undefined) {
      currentViolationsMap!.set(violation.id, violation);
    } else {
      rule.nodes.push(...violation.nodes);
    }
  });
}

export function pushTestResult() {
  if (typeof currentTestResult !== 'undefined') {
    currentTestResult.violations = [...currentViolationsMap!.values()];
    currentTestResult.urls = [...currentUrls.values()];
    currentTestResult.routes = [...currentRouteNames.values()];
    TEST_SUITE_RESULTS.push(currentTestResult);

    currentTestResult = undefined;
    currentViolationsMap = undefined;
  }
}

/**
 * Sets up the middleware reporter, which reports results when the test suite is done.
 */
export function setupMiddlewareReporter() {
  setCustomReporter(middlewareReporter);

  QUnit.testDone(pushTestResult);

  QUnit.done(async function () {
    let response = await fetch('/report-violations', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(TEST_SUITE_RESULTS),
    });

    return response.json();
  });
}
<commit_msg>fix: Adjusting time of data gathering in middleware reporter<commit_after>import QUnit from 'qunit';
import {
  currentRouteName,
  currentURL,
  getContext,
  getTestMetadata,
} from '@ember/test-helpers';
import { AxeResults, Result } from 'axe-core';
import { setCustomReporter } from './reporter';
import { DEBUG } from '@glimmer/env';

interface AxeTestResult {
  moduleName: string;
  testName: string;
  urls: string[] | Set<string>;
  routes: string[] | Set<string>;
  helpers: string[];
  stack: string;
  violations: Result[];
}

export const TEST_SUITE_RESULTS: AxeTestResult[] = [];

let currentTestResult: AxeTestResult | undefined = undefined;
let currentViolationsMap: Map<string, Result> | undefined = undefined;
let currentUrls: Set<string> | undefined;
let currentRouteNames: Set<string> | undefined;
let currentTestHelpers: Set<string> | undefined;

/**
 * A custom reporter that is invoke once per failed a11yAudit call. This can be called
 * multiple times per test, and the results are accumulated until testDone.
 *
 * @param axeResults The axe results for each a11yAudit.
 * @returns Early returns if no violations are found.
 */
export async function middlewareReporter(axeResults: AxeResults) {
  if (axeResults.violations.length === 0) {
    return;
  }

  let testMetaData = getTestMetadata(getContext());

  if (!currentTestResult) {
    let { module, testName } = QUnit.config.current;

    let stack = (!DEBUG && new Error().stack) || '';

    currentTestResult = {
      moduleName: module.name,
      testName,
      urls: [],
      routes: [],
      helpers: [],
      stack,
      violations: [],
    };

    currentViolationsMap = new Map();
    currentUrls = new Set();
    currentRouteNames = new Set();
    currentTestHelpers = new Set();
  }

  currentTestHelpers = new Set([
    ...currentTestHelpers!.values(),
    ...testMetaData.usedHelpers,
  ]);
  currentUrls!.add(currentURL());
  currentRouteNames!.add(currentRouteName());

  axeResults.violations.forEach((violation) => {
    let rule = currentViolationsMap!.get(violation.id);

    if (rule === undefined) {
      currentViolationsMap!.set(violation.id, violation);
    } else {
      rule.nodes.push(...violation.nodes);
    }
  });
}

/**
 * Invoked once per test. Accumulates the results into a set of results used for
 * reporting via the middleware reporter.
 */
export function pushTestResult() {
  if (typeof currentTestResult !== 'undefined') {
    currentTestResult.violations = [...currentViolationsMap!.values()];
    currentTestResult.urls = [...currentUrls!.values()];
    currentTestResult.routes = [...currentRouteNames!.values()];
    currentTestResult.helpers = [...currentTestHelpers!.values()];

    TEST_SUITE_RESULTS.push(currentTestResult);

    currentTestResult = undefined;
    currentViolationsMap = undefined;
    currentUrls = undefined;
    currentRouteNames = undefined;
    currentTestHelpers = undefined;
  }
}

/**
 * Sets up the middleware reporter, which reports results when the test suite is done.
 */
export function setupMiddlewareReporter() {
  setCustomReporter(middlewareReporter);

  QUnit.testDone(pushTestResult);

  QUnit.done(async function () {
    let response = await fetch('/report-violations', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(TEST_SUITE_RESULTS),
    });

    return response.json();
  });
}

{'fraction_non_alphanumeric': 0.12992651970607882, 'fraction_numerical': 0.001002004008016032, 'mean_word_length': 3.806581059390048, 'pattern_counts': {'":': 0, '<': 14, '<?xml version=': 0, '>': 16, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3946609', 'n_tokens_mistral': 1806, 'n_tokens_neox': 1786, 'n_words': 426}