summaryrefslogtreecommitdiffstats
path: root/remote/test/puppeteer/tools/mocha-runner/src/utils.ts
blob: 066c5fbe57d0315568a068948b6d84af723b0e69 (plain)
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
/**
 * @license
 * Copyright 2022 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */

import fs from 'fs';
import path from 'path';

import type {
  MochaTestResult,
  TestExpectation,
  MochaResults,
  TestResult,
} from './types.js';

export function extendProcessEnv(envs: object[]): NodeJS.ProcessEnv {
  const env = envs.reduce(
    (acc: object, item: object) => {
      Object.assign(acc, item);
      return acc;
    },
    {
      ...process.env,
    }
  );

  if (process.env['CI']) {
    const puppeteerEnv = Object.entries(env).reduce(
      (acc, [key, value]) => {
        if (key.startsWith('PUPPETEER_')) {
          acc[key] = value;
        }

        return acc;
      },
      {} as Record<string, unknown>
    );

    console.log(
      'PUPPETEER env:\n',
      JSON.stringify(puppeteerEnv, null, 2),
      '\n'
    );
  }

  return env as NodeJS.ProcessEnv;
}

export function getFilename(file: string): string {
  return path.basename(file).replace(path.extname(file), '');
}

export function readJSON(path: string): unknown {
  return JSON.parse(fs.readFileSync(path, 'utf-8'));
}

export function writeJSON(path: string, json: unknown): unknown {
  return fs.writeFileSync(path, JSON.stringify(json, null, 2));
}

export function filterByPlatform<T extends {platforms: NodeJS.Platform[]}>(
  items: T[],
  platform: NodeJS.Platform
): T[] {
  return items.filter(item => {
    return item.platforms.includes(platform);
  });
}

export function prettyPrintJSON(json: unknown): void {
  console.log(JSON.stringify(json, null, 2));
}

export function printSuggestions(
  recommendations: RecommendedExpectation[],
  action: RecommendedExpectation['action'],
  message: string
): void {
  const toPrint = recommendations.filter(item => {
    return item.action === action;
  });
  if (toPrint.length) {
    console.log(message);
    prettyPrintJSON(
      toPrint.map(item => {
        return item.expectation;
      })
    );
    if (action !== 'remove') {
      console.log(
        'The recommendations are based on the following applied expectations:'
      );
      prettyPrintJSON(
        toPrint.map(item => {
          return item.basedOn;
        })
      );
    }
  }
}

export function filterByParameters(
  expectations: TestExpectation[],
  parameters: string[]
): TestExpectation[] {
  const querySet = new Set(parameters);
  return expectations.filter(ex => {
    return ex.parameters.every(param => {
      return querySet.has(param);
    });
  });
}

/**
 * The last expectation that matches an empty string as all tests pattern
 * or the name of the file or the whole name of the test the filter wins.
 */
export function findEffectiveExpectationForTest(
  expectations: TestExpectation[],
  result: MochaTestResult
): TestExpectation | undefined {
  return expectations.find(expectation => {
    return testIdMatchesExpectationPattern(result, expectation.testIdPattern);
  });
}

export interface RecommendedExpectation {
  expectation: TestExpectation;
  action: 'remove' | 'add' | 'update';
  basedOn?: TestExpectation;
}

export function isWildCardPattern(testIdPattern: string): boolean {
  return testIdPattern.includes('*');
}

export function getExpectationUpdates(
  results: MochaResults,
  expectations: TestExpectation[],
  context: {
    platforms: NodeJS.Platform[];
    parameters: string[];
  }
): RecommendedExpectation[] {
  const output = new Map<string, RecommendedExpectation>();

  const passesByKey = results.passes.reduce((acc, pass) => {
    acc.add(getTestId(pass.file, pass.fullTitle));
    return acc;
  }, new Set());

  for (const pass of results.passes) {
    const expectationEntry = findEffectiveExpectationForTest(
      expectations,
      pass
    );
    if (expectationEntry && !expectationEntry.expectations.includes('PASS')) {
      if (isWildCardPattern(expectationEntry.testIdPattern)) {
        addEntry({
          expectation: {
            testIdPattern: getTestId(pass.file, pass.fullTitle),
            platforms: context.platforms,
            parameters: context.parameters,
            expectations: ['PASS'],
          },
          action: 'add',
          basedOn: expectationEntry,
        });
      } else {
        addEntry({
          expectation: expectationEntry,
          action: 'remove',
          basedOn: expectationEntry,
        });
      }
    }
  }

  for (const failure of results.failures) {
    // If an error occurs during a hook
    // the error not have a file associated with it
    if (!failure.file) {
      console.error('Hook failed:', failure.err);
      addEntry({
        expectation: {
          testIdPattern: failure.fullTitle,
          platforms: context.platforms,
          parameters: context.parameters,
          expectations: [],
        },
        action: 'add',
      });
      continue;
    }

    if (passesByKey.has(getTestId(failure.file, failure.fullTitle))) {
      continue;
    }

    const expectationEntry = findEffectiveExpectationForTest(
      expectations,
      failure
    );
    if (expectationEntry && !expectationEntry.expectations.includes('SKIP')) {
      if (
        !expectationEntry.expectations.includes(
          getTestResultForFailure(failure)
        )
      ) {
        // If the effective explanation is a wildcard, we recommend adding a new
        // expectation instead of updating the wildcard that might affect multiple
        // tests.
        if (isWildCardPattern(expectationEntry.testIdPattern)) {
          addEntry({
            expectation: {
              testIdPattern: getTestId(failure.file, failure.fullTitle),
              platforms: context.platforms,
              parameters: context.parameters,
              expectations: [getTestResultForFailure(failure)],
            },
            action: 'add',
            basedOn: expectationEntry,
          });
        } else {
          addEntry({
            expectation: {
              ...expectationEntry,
              expectations: [
                ...expectationEntry.expectations,
                getTestResultForFailure(failure),
              ],
            },
            action: 'update',
            basedOn: expectationEntry,
          });
        }
      }
    } else if (!expectationEntry) {
      addEntry({
        expectation: {
          testIdPattern: getTestId(failure.file, failure.fullTitle),
          platforms: context.platforms,
          parameters: context.parameters,
          expectations: [getTestResultForFailure(failure)],
        },
        action: 'add',
      });
    }
  }

  function addEntry(value: RecommendedExpectation) {
    const key = JSON.stringify(value);
    if (!output.has(key)) {
      output.set(key, value);
    }
  }

  return [...output.values()];
}

export function getTestResultForFailure(
  test: Pick<MochaTestResult, 'err'>
): TestResult {
  return test.err?.code === 'ERR_MOCHA_TIMEOUT' ? 'TIMEOUT' : 'FAIL';
}

export function getTestId(file: string, fullTitle?: string): string {
  return fullTitle
    ? `[${getFilename(file)}] ${fullTitle}`
    : `[${getFilename(file)}]`;
}

export function testIdMatchesExpectationPattern(
  test: MochaTestResult | Pick<Mocha.Test, 'title' | 'file' | 'fullTitle'>,
  pattern: string
): boolean {
  const patternRegExString = pattern
    // Replace `*` with non special character
    .replace(/\*/g, '--STAR--')
    // Escape special characters https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
    .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
    // Replace placeholder with greedy match
    .replace(/--STAR--/g, '(.*)?');
  // Match beginning and end explicitly
  const patternRegEx = new RegExp(`^${patternRegExString}$`);
  const fullTitle =
    typeof test.fullTitle === 'string' ? test.fullTitle : test.fullTitle();

  return patternRegEx.test(getTestId(test.file ?? '', fullTitle));
}