mirror of
https://github.com/electron/electron.git
synced 2026-10-28 11:44:46 +08:00
* test: assert with vitest's matchers instead of chai
Every assertion moves from chai's chainable language to vitest's own
matchers, so an assertion is always a call and never a bare property read:
- `to.equal` → `toBe`, `to.deep.equal`/`eql` → `toEqual`, `to.be.true` →
`toBe(true)`, `to.have.property` → `toHaveProperty`, `to.include` →
`toContain`/`toMatchObject`/`toContainEqual`, `to.be.a('string')` →
`toBeTypeOf('string')`, `instanceOf` → `toBeInstanceOf`, `lengthOf` →
`toHaveLength`, `above`/`least`/`below`/`most` → `toBeGreaterThan` and
friends, `match` → `toMatch`, `throw` → `toThrow`, `oneOf` → `toContain`
with the operands swapped, `closeTo(e, d)` → `Math.abs(x - e) <= d`,
`members`/`keys` → `arrayContaining`/`Object.keys`. A chain that kept
going after `.property()` or `.a()` becomes one matcher where vitest has
one (`toHaveProperty(key, expect.any(String))`) and separate assertions
otherwise. chai-as-promised becomes `.resolves`/`.rejects`, a failed
manual check is `assert.fail()` rather than `new chai.AssertionError`.
- vitest reports promise assertions that are not awaited; the app badge,
webview zoom and `import('electron')` specs had some that never ran and
now do (the service worker badge ones waited for a count the worker had
already cleared, so those just check the worker's answer; the zoom fixture
issued loadURL() from dom-ready, which aborts, and now waits for the load).
- Code that runs outside the spec module graph (itremote bodies in a
renderer, the utility-process net harness, two crash-case apps) is
CommonJS and vitest refuses `require('vitest')`, so it loads the same
module through spec/lib/vitest-cjs.cjs.
- A lint rule (script/lint-plugins/no-chai-assertions.mjs) rejects chai
chains on `expect()`, and no-unused-expressions is on for the specs, so
neither form of property-style assertion can come back.
- chai, chai-as-promised, dirty-chai and their @types leave
spec/package.json; the refresh-page fixture served chai.js only as "a
large script" and serves the jquery fixture instead.
* test: return promises instead of taking mocha's `done` callback
vitest has no `done` parameter. The tests and hooks that used one now
return a promise instead; where the callback was only ever called as
`done()` it is the promise's `resolve`, and where it was also handed to an
error-first API or called as `done(error)` it keeps mocha's meaning
(reject on a truthy argument, resolve otherwise) through a local `done`.
* test: move the spec runner's own semantics out of the mocha shim
Three things the shim did are not mocha compatibility but how the Electron
specs need to run, whichever API they are written against: every hook and
test starts from a fresh macrotask so that Chromium's message loop turns
between them, `defer()`-ed cleanup runs before the enclosing suites' own
afterEach hooks, and spec/disabled-tests.json can switch a test off by its
title. Those now live in a small custom vitest runner
(spec/vitest/runner.ts) that applies to every test, and the shim only
translates mocha's API.
* test: write the specs against vitest's API instead of mocha's
Mechanical conversion of every spec file and helper:
- `describe`/`it`/`beforeEach`/... are imported from 'vitest' rather than
taken from the runner's globals; `before`/`after` become
`beforeAll`/`afterAll`.
- `this.timeout(n)` becomes the `{ timeout: n }` option of the test or
suite (a hook's second argument; hooks inside a suite that had a timeout
get it explicitly, since vitest's suite option only reaches the tests), `this.retries(n)` `{ retry: n }`, and
`this.skip()` the test context's `ctx.skip()`. The two `before` hooks that
skipped a whole suite now compute the condition up front
(`describe.runIf`) or per test. `function () {}` callbacks that only
existed for `this` are arrows again.
- `ifit`/`ifdescribe` map to `it.skip`/`describe.skip`, mocha's chained
`it(...).timeout(n)` and `this.bail()` are gone, and the two helpers that
read `this.test` use the context's task state.
* test: remove the mocha compatibility layer
Nothing imports mocha's API any more, so spec/vitest/mocha-compat.ts and the
setup file that installed its globals go, together with @types/mocha and the
Mocha type overloads in spec/ambient.d.ts. Timeouts are vitest's own again
(30 s per test and hook, ELECTRON_SPEC_TIMEOUT raises it for the sanitizer
jobs, replacing MOCHA_TIMEOUT), the junit path variable becomes
ELECTRON_SPEC_JUNIT_FILE, and `closeAllWindows` loses the parameter that a
hook's context argument would otherwise land in.
137 lines
5.2 KiB
TypeScript
137 lines
5.2 KiB
TypeScript
import { describe, expect, it } from 'vitest';
|
|
|
|
import { spawn, spawnSync } from 'node:child_process';
|
|
import { once } from 'node:events';
|
|
import * as path from 'node:path';
|
|
|
|
import { ifdescribe, isTestingBindingAvailable, startRemoteControlApp } from './lib/spec-helpers.ts';
|
|
|
|
ifdescribe(isTestingBindingAvailable())('fuses', () => {
|
|
it('can be enabled by command-line argument during testing', async () => {
|
|
const child0 = spawn(process.execPath, ['-v'], { env: { NODE_OPTIONS: '-e 0' } });
|
|
const [code0] = await once(child0, 'exit');
|
|
// Should exit with 9 because -e is not allowed in NODE_OPTIONS
|
|
expect(code0).toBe(9);
|
|
const child1 = spawn(process.execPath, ['--set-fuse-node_options=0', '-v'], { env: { NODE_OPTIONS: '-e 0' } });
|
|
const [code1] = await once(child1, 'exit');
|
|
// Should print the version and exit with 0
|
|
expect(code1).toBe(0);
|
|
});
|
|
|
|
it('disables --inspect flag when node_cli_inspect is 0', () => {
|
|
const { status, stderr } = spawnSync(process.execPath, ['--set-fuse-node_cli_inspect=0', '--inspect', '-v'], {
|
|
encoding: 'utf-8'
|
|
});
|
|
expect(stderr).not.toContain('Debugger listening on ws://');
|
|
// Should print the version and exit with 0
|
|
expect(status).toBe(0);
|
|
});
|
|
|
|
it('makes child_process.fork throw when run_as_node is 0', async () => {
|
|
const rc = await startRemoteControlApp(['--set-fuse-run_as_node=0']);
|
|
const message = await rc.remotely(
|
|
(fixture: string) => {
|
|
try {
|
|
require('node:child_process').fork(fixture);
|
|
return 'forked';
|
|
} catch (error) {
|
|
return (error as Error).message;
|
|
}
|
|
},
|
|
path.join(import.meta.dirname, 'fixtures', 'module', 'noop.js')
|
|
);
|
|
expect(message).toContain('runAsNode fuse is disabled');
|
|
});
|
|
|
|
it('disables fetching file:// URLs when grant_file_protocol_extra_privileges is 0', async () => {
|
|
const rc = await startRemoteControlApp(['--set-fuse-grant_file_protocol_extra_privileges=0']);
|
|
await expect(
|
|
rc.remotely(
|
|
async (fixture: string) => {
|
|
const { BrowserWindow } = require('electron');
|
|
const bw = new BrowserWindow({ show: false });
|
|
await bw.loadFile(fixture);
|
|
return await bw.webContents.executeJavaScript("ajax('file:///etc/passwd')");
|
|
},
|
|
path.join(import.meta.dirname, 'fixtures', 'pages', 'fetch.html')
|
|
)
|
|
).rejects.toThrow('Failed to fetch');
|
|
});
|
|
|
|
describe('cookie_encryption', () => {
|
|
it('allows setting and retrieving cookies when enabled', async () => {
|
|
const rc = await startRemoteControlApp(['--set-fuse-cookie_encryption=1']);
|
|
const result = await rc.remotely(async () => {
|
|
const { session } = require('electron');
|
|
const ses = session.defaultSession;
|
|
const testUrl = 'https://example.com';
|
|
|
|
await ses.clearStorageData({ storages: ['cookies'] });
|
|
|
|
await ses.cookies.set({
|
|
url: testUrl,
|
|
name: 'test_cookie',
|
|
value: 'encrypted_value_12345',
|
|
expirationDate: Math.floor(Date.now() / 1000) + 3600
|
|
});
|
|
|
|
await ses.cookies.set({
|
|
url: testUrl,
|
|
name: 'secure_cookie',
|
|
value: 'secret_data_67890',
|
|
secure: true,
|
|
httpOnly: true,
|
|
expirationDate: Math.floor(Date.now() / 1000) + 7200
|
|
});
|
|
|
|
const cookies = await ses.cookies.get({ url: testUrl });
|
|
const testCookie = cookies.find((c: Electron.Cookie) => c.name === 'test_cookie');
|
|
const secureCookie = cookies.find((c: Electron.Cookie) => c.name === 'secure_cookie');
|
|
|
|
return {
|
|
cookieCount: cookies.length,
|
|
testCookieValue: testCookie?.value,
|
|
secureCookieValue: secureCookie?.value,
|
|
secureCookieIsSecure: secureCookie?.secure,
|
|
secureCookieIsHttpOnly: secureCookie?.httpOnly
|
|
};
|
|
});
|
|
|
|
expect(result.cookieCount).toBe(2);
|
|
expect(result.testCookieValue).toBe('encrypted_value_12345');
|
|
expect(result.secureCookieValue).toBe('secret_data_67890');
|
|
expect(result.secureCookieIsSecure).toBe(true);
|
|
expect(result.secureCookieIsHttpOnly).toBe(true);
|
|
});
|
|
|
|
it('persists cookies across sessions when enabled', async () => {
|
|
const rc = await startRemoteControlApp(['--set-fuse-cookie_encryption=1']);
|
|
|
|
await rc.remotely(async () => {
|
|
const { session } = require('electron');
|
|
await session.defaultSession.clearStorageData({ storages: ['cookies'] });
|
|
await session.defaultSession.cookies.set({
|
|
url: 'https://example.com',
|
|
name: 'persistent_cookie',
|
|
value: 'persist_me',
|
|
expirationDate: Math.floor(Date.now() / 1000) + 86400
|
|
});
|
|
});
|
|
|
|
await rc.remotely(async () => {
|
|
const { session } = require('electron');
|
|
await session.defaultSession.cookies.flushStore();
|
|
});
|
|
|
|
const result = await rc.remotely(async () => {
|
|
const { session } = require('electron');
|
|
const cookies = await session.defaultSession.cookies.get({ url: 'https://example.com' });
|
|
const cookie = cookies.find((c: Electron.Cookie) => c.name === 'persistent_cookie');
|
|
return cookie?.value;
|
|
});
|
|
|
|
expect(result).toBe('persist_me');
|
|
});
|
|
});
|
|
});
|