summaryrefslogtreecommitdiffstats
path: root/remote/test/puppeteer/test/src/mocha-utils.ts
blob: 70d9ab505e542403934821d17fd917f5242a33d7 (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
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
/**
 * Copyright 2020 Google Inc. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

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

import {TestServer} from '@pptr/testserver';
import {Protocol} from 'devtools-protocol';
import expect from 'expect';
import * as Mocha from 'mocha';
import puppeteer from 'puppeteer/lib/cjs/puppeteer/puppeteer.js';
import {Browser} from 'puppeteer-core/internal/api/Browser.js';
import {BrowserContext} from 'puppeteer-core/internal/api/BrowserContext.js';
import {Page} from 'puppeteer-core/internal/api/Page.js';
import {
  setLogCapture,
  getCapturedLogs,
} from 'puppeteer-core/internal/common/Debug.js';
import {
  PuppeteerLaunchOptions,
  PuppeteerNode,
} from 'puppeteer-core/internal/node/PuppeteerNode.js';
import {rmSync} from 'puppeteer-core/internal/node/util/fs.js';
import {isErrorLike} from 'puppeteer-core/internal/util/ErrorLike.js';
import sinon from 'sinon';

import {extendExpectWithToBeGolden} from './utils.js';

const setupServer = async () => {
  const assetsPath = path.join(__dirname, '../assets');
  const cachedPath = path.join(__dirname, '../assets', 'cached');

  const server = await TestServer.create(assetsPath);
  const port = server.port;
  server.enableHTTPCache(cachedPath);
  server.PORT = port;
  server.PREFIX = `http://localhost:${port}`;
  server.CROSS_PROCESS_PREFIX = `http://127.0.0.1:${port}`;
  server.EMPTY_PAGE = `http://localhost:${port}/empty.html`;

  const httpsServer = await TestServer.createHTTPS(assetsPath);
  const httpsPort = httpsServer.port;
  httpsServer.enableHTTPCache(cachedPath);
  httpsServer.PORT = httpsPort;
  httpsServer.PREFIX = `https://localhost:${httpsPort}`;
  httpsServer.CROSS_PROCESS_PREFIX = `https://127.0.0.1:${httpsPort}`;
  httpsServer.EMPTY_PAGE = `https://localhost:${httpsPort}/empty.html`;

  return {server, httpsServer};
};

export const getTestState = (): PuppeteerTestState => {
  return state as PuppeteerTestState;
};

const product =
  process.env['PRODUCT'] || process.env['PUPPETEER_PRODUCT'] || 'chrome';

const alternativeInstall = process.env['PUPPETEER_ALT_INSTALL'] || false;

const headless = (process.env['HEADLESS'] || 'true').trim().toLowerCase() as
  | 'true'
  | 'false'
  | 'new';
const isHeadless = headless === 'true' || headless === 'new';
const isFirefox = product === 'firefox';
const isChrome = product === 'chrome';
const protocol = process.env['PUPPETEER_PROTOCOL'] || 'cdp';

let extraLaunchOptions = {};
try {
  extraLaunchOptions = JSON.parse(process.env['EXTRA_LAUNCH_OPTIONS'] || '{}');
} catch (error) {
  if (isErrorLike(error)) {
    console.warn(
      `Error parsing EXTRA_LAUNCH_OPTIONS: ${error.message}. Skipping.`
    );
  } else {
    throw error;
  }
}

const defaultBrowserOptions = Object.assign(
  {
    handleSIGINT: true,
    executablePath: process.env['BINARY'],
    headless: headless === 'new' ? ('new' as const) : isHeadless,
    dumpio: !!process.env['DUMPIO'],
    protocol: protocol as 'cdp' | 'webDriverBiDi',
  },
  extraLaunchOptions
);

(async (): Promise<void> => {
  if (defaultBrowserOptions.executablePath) {
    console.warn(
      `WARN: running ${product} tests with ${defaultBrowserOptions.executablePath}`
    );
  } else {
    const executablePath = puppeteer.executablePath();
    if (!fs.existsSync(executablePath)) {
      throw new Error(
        `Browser is not downloaded at ${executablePath}. Run 'npm install' and try to re-run tests`
      );
    }
  }
})();

const setupGoldenAssertions = (): void => {
  const suffix = product.toLowerCase();
  const GOLDEN_DIR = path.join(__dirname, `../golden-${suffix}`);
  const OUTPUT_DIR = path.join(__dirname, `../output-${suffix}`);
  if (fs.existsSync(OUTPUT_DIR)) {
    rmSync(OUTPUT_DIR);
  }
  extendExpectWithToBeGolden(GOLDEN_DIR, OUTPUT_DIR);
};

setupGoldenAssertions();

interface PuppeteerTestState {
  browser: Browser;
  context: BrowserContext;
  page: Page;
  puppeteer: PuppeteerNode;
  defaultBrowserOptions: PuppeteerLaunchOptions;
  server: TestServer;
  httpsServer: TestServer;
  isFirefox: boolean;
  isChrome: boolean;
  isHeadless: boolean;
  headless: 'true' | 'false' | 'new';
  puppeteerPath: string;
}
const state: Partial<PuppeteerTestState> = {};

export const itOnlyRegularInstall = (
  description: string,
  body: Mocha.AsyncFunc
): Mocha.Test => {
  if (alternativeInstall || process.env['BINARY']) {
    return it.skip(description, body);
  } else {
    return it(description, body);
  }
};

if (
  process.env['MOCHA_WORKER_ID'] === undefined ||
  process.env['MOCHA_WORKER_ID'] === '0'
) {
  console.log(
    `Running unit tests with:
  -> product: ${product}
  -> binary: ${
    defaultBrowserOptions.executablePath ||
    path.relative(process.cwd(), puppeteer.executablePath())
  }
  -> mode: ${
    isHeadless
      ? headless === 'new'
        ? '--headless=new'
        : '--headless'
      : 'headful'
  }`
  );
}

process.on('unhandledRejection', reason => {
  throw reason;
});

export const setupTestBrowserHooks = (): void => {
  before(async () => {
    const browser = await puppeteer.launch(defaultBrowserOptions);
    state.browser = browser;
  });

  after(async () => {
    await state.browser?.close();
    state.browser = undefined;
  });
};

export const setupTestPageAndContextHooks = (): void => {
  beforeEach(async () => {
    state.context = await state.browser!.createIncognitoBrowserContext();
    state.page = await state.context.newPage();
  });

  afterEach(async () => {
    await state.context?.close();
    state.context = undefined;
    state.page = undefined;
  });
};

export const mochaHooks = {
  beforeAll: [
    async (): Promise<void> => {
      const {server, httpsServer} = await setupServer();

      state.puppeteer = puppeteer;
      state.defaultBrowserOptions = defaultBrowserOptions;
      state.server = server;
      state.httpsServer = httpsServer;
      state.isFirefox = isFirefox;
      state.isChrome = isChrome;
      state.isHeadless = isHeadless;
      state.headless = headless;
      state.puppeteerPath = path.resolve(
        path.join(__dirname, '..', '..', 'packages', 'puppeteer')
      );
    },
  ],

  beforeEach: async (): Promise<void> => {
    state.server!.reset();
    state.httpsServer!.reset();
  },

  afterAll: [
    async (): Promise<void> => {
      await state.server!.stop();
      state.server = undefined;
      await state.httpsServer!.stop();
      state.httpsServer = undefined;
    },
  ],

  afterEach: (): void => {
    sinon.restore();
  },
};

export const expectCookieEquals = (
  cookies: Protocol.Network.Cookie[],
  expectedCookies: Array<Partial<Protocol.Network.Cookie>>
): void => {
  const {isChrome} = getTestState();
  if (!isChrome) {
    // Only keep standard properties when testing on a browser other than Chrome.
    expectedCookies = expectedCookies.map(cookie => {
      return {
        domain: cookie.domain,
        expires: cookie.expires,
        httpOnly: cookie.httpOnly,
        name: cookie.name,
        path: cookie.path,
        secure: cookie.secure,
        session: cookie.session,
        size: cookie.size,
        value: cookie.value,
      };
    });
  }

  expect(cookies.length).toBe(expectedCookies.length);
  for (let i = 0; i < cookies.length; i++) {
    expect(cookies[i]).toMatchObject(expectedCookies[i]!);
  }
};

/**
 * Use it if you want to capture debug logs for a specitic test suite in CI.
 * This describe function enables capturing of debug logs and would print them
 * only if a test fails to reduce the amount of output.
 */
export const describeWithDebugLogs = (
  description: string,
  body: (this: Mocha.Suite) => void
): Mocha.Suite | void => {
  describe(description + '-debug', () => {
    beforeEach(() => {
      setLogCapture(true);
    });

    afterEach(function () {
      if (this.currentTest?.state === 'failed') {
        console.log(
          `\n"${this.currentTest.fullTitle()}" failed. Here is a debug log:`
        );
        console.log(getCapturedLogs().join('\n') + '\n');
      }
      setLogCapture(false);
    });

    describe(description, body);
  });
};

export const shortWaitForArrayToHaveAtLeastNElements = async (
  data: unknown[],
  minLength: number,
  attempts = 3,
  timeout = 50
): Promise<void> => {
  for (let i = 0; i < attempts; i++) {
    if (data.length >= minLength) {
      break;
    }
    await new Promise(resolve => {
      return setTimeout(resolve, timeout);
    });
  }
};

export const createTimeout = <T>(
  n: number,
  value?: T
): Promise<T | undefined> => {
  return new Promise(resolve => {
    setTimeout(() => {
      return resolve(value);
    }, n);
  });
};