mirror of
https://github.com/renovatebot/renovate.git
synced 2026-10-26 07:20:39 +00:00
fbedd41e82
* test: replace manual process.env mutation with vi.stubEnv
Enable Vitest's `unstubEnvs` so env stubs are reverted automatically
before every test, and convert the manual `process.env.X = ...` /
`delete process.env.X` pairs in specs to `vi.stubEnv()`.
This removes the hand-written `afterEach` cleanup blocks and the
`const OLD_ENV = process.env` / `process.env = { ...OLD_ENV }`
save-restore dance, which silently leaked state between tests when a
test set a variable without a matching delete.
Left as-is (incompatible with `unstubEnvs`, which unstubs before each
test, not after):
- module top-level env writes (cocoapods, gomod, post-update, pip-compile
and bundler artifacts specs)
- `beforeAll` env writes -- the two in `util/http` moved to `beforeEach`
* test: stop asserting on ambient environment variables
Three specs asserted on values that the surrounding environment can
override, so they only passed on a machine that happened not to set them:
- `util/exec/env`: `getChildProcessEnv()` forwards every entry of
`basicEnvVars`, but the spec only seeded a subset. Any other forwarded
variable that was set ambiently (e.g. a lowercase `http_proxy`) leaked
into the `toEqual` assertion. Clear all of them first.
- `util/git/index`: `process.env.GIT_SSH_COMMAND` deliberately overrides
the default that the two env-inheritance tests assert on. Clear it.
- `logger/pretty-stdout`: the colorized level strings are built at import
time, so the `beforeEach` setting `FORCE_COLOR` could never affect them
-- it was dead code, and the test silently assumed a terminal without
colour support. Derive the expectation the same way the module does.
* test(datasource/nuget): use a throwaway cache dir for nupkg downloads
The `determine source URL from nupkg` tests do not mock the filesystem,
so they really wrote downloaded packages into a fixed `/tmp/cache` path.
That fails wherever the system tmpdir is not writable, and two checkouts
running the suite at once would share the same directory.
Use `tmp.dir({ unsafeCleanup: true })` and clean it up afterwards, which
is the pattern the other specs that touch disk already use.
* feat(lint): add renovate/prefer-stub-env rule
Enforces in specs what the migration to `vi.stubEnv` established:
- assigning to or deleting `process.env.X` inside `beforeEach`, `afterEach`,
`it` or `test` is reported, with a fixer that rewrites it to `vi.stubEnv()`
- module scope, `describe` bodies and `beforeAll` / `afterAll` are left alone:
`unstubEnvs` reverts stubs *before* each test, so a stub created there is
gone by the time the first test runs, and those must keep assigning directly
- replacing the `process.env` object is reported everywhere and never fixed.
`vi.stubEnv()` captures the original object when the worker starts, so after
a reassignment its deletes silently target the old object
The rule found 28 further violations in specs the earlier sweep missed, since
that one was anchored on `delete process.env`. Twelve were auto-fixed; the
rest replaced `process.env` wholesale and are now `clearEnv()` from test/util.
`util/exec/index.spec.ts` opts out with a comment: it asserts on the whole
child env, and `vi.stubEnv()` cannot express that because it maps `PROD`,
`DEV` and `SSR` onto '' instead of deleting them.
121 lines
3.8 KiB
TypeScript
121 lines
3.8 KiB
TypeScript
import upath from 'upath';
|
|
import type { DeepMockProxy } from 'vitest-mock-extended';
|
|
import type { RenovateConfig } from '../lib/config/types.ts';
|
|
import * as _logger from '../lib/logger/index.ts';
|
|
import type { Platform } from '../lib/modules/platform/index.ts';
|
|
import { platform as _platform } from '../lib/modules/platform/index.ts';
|
|
import { scm as _scm } from '../lib/modules/platform/scm.ts';
|
|
import * as _env from '../lib/util/exec/env.ts';
|
|
import * as _fs from '../lib/util/fs/index.ts';
|
|
import * as _git from '../lib/util/git/index.ts';
|
|
import { hash } from '../lib/util/hash.ts';
|
|
import * as _hostRules from '../lib/util/host-rules.ts';
|
|
import {
|
|
type LongCommitSha,
|
|
toLongCommitSha,
|
|
} from '../lib/util/schema-utils/git.ts';
|
|
|
|
/**
|
|
* Simple wrapper for getting mocked version of a module
|
|
* @param module module which is mocked by `vitest-mock-extended.mockDeep`
|
|
*/
|
|
export function mockedExtended<T extends object>(module: T): DeepMockProxy<T> {
|
|
return module as DeepMockProxy<T>;
|
|
}
|
|
|
|
/**
|
|
* Simply wrapper to create partial mocks.
|
|
* @param obj Object to cast to final type
|
|
*/
|
|
export function partial<T>(): T;
|
|
export function partial<T>(obj: Partial<T>): T;
|
|
export function partial<T>(obj: Partial<T>[]): T[];
|
|
export function partial(obj: unknown = {}): unknown {
|
|
return obj;
|
|
}
|
|
|
|
export const fs = vi.mocked(_fs);
|
|
export const git = vi.mocked(_git);
|
|
|
|
export const platform = vi.mocked(partial<Required<Platform>>(_platform));
|
|
export const scm = vi.mocked(_scm);
|
|
export const env = vi.mocked(_env);
|
|
export const hostRules = vi.mocked(_hostRules);
|
|
export const logger = vi.mocked(_logger, true);
|
|
|
|
export type { RenovateConfig };
|
|
|
|
function getCallerFileName(): string | null {
|
|
let result: string | null = null;
|
|
|
|
const prepareStackTrace = Error.prepareStackTrace;
|
|
const stackTraceLimit = Error.stackTraceLimit;
|
|
|
|
Error.prepareStackTrace = (_err, stack) => stack;
|
|
Error.stackTraceLimit = 5; // max calls inside this file + 1
|
|
|
|
try {
|
|
const err = new Error();
|
|
|
|
const stack = err.stack as unknown as NodeJS.CallSite[];
|
|
|
|
let currentFile: string | null = null;
|
|
for (const frame of stack) {
|
|
const fileName = frame.getFileName() ?? null;
|
|
if (!currentFile) {
|
|
currentFile = fileName;
|
|
} else if (currentFile !== fileName) {
|
|
result = fileName;
|
|
break;
|
|
}
|
|
}
|
|
} catch {
|
|
// no-op
|
|
}
|
|
|
|
Error.prepareStackTrace = prepareStackTrace;
|
|
Error.stackTraceLimit = stackTraceLimit;
|
|
|
|
return result;
|
|
}
|
|
|
|
export function getFixturePath(fixtureFile: string, fixtureRoot = '.'): string {
|
|
const callerDir = upath.dirname(getCallerFileName()!);
|
|
return upath.join(callerDir, fixtureRoot, '__fixtures__', fixtureFile);
|
|
}
|
|
|
|
/**
|
|
* Deterministically derive a valid {@link LongCommitSha} from a seed, for tests.
|
|
* Same seed always yields the same SHA, keeping snapshots stable.
|
|
* Defaults to a 40-char (sha1) hash; pass 'sha256' for a 64-char hash.
|
|
*/
|
|
export function fakeSha(
|
|
seed: string,
|
|
algorithm: 'sha1' | 'sha256' = 'sha1',
|
|
): LongCommitSha {
|
|
return toLongCommitSha(hash(seed, algorithm));
|
|
}
|
|
|
|
/**
|
|
* Variables that `vi.stubEnv()` treats as booleans: it maps them onto '1' / ''
|
|
* rather than deleting them, so they cannot be cleared through a stub.
|
|
* Vitest sets them itself, and nothing under test reads them.
|
|
*/
|
|
const unstubbableEnvVars = new Set(['PROD', 'DEV', 'SSR']);
|
|
|
|
/**
|
|
* Clear every environment variable for the duration of the current test.
|
|
*
|
|
* Replacing `process.env` wholesale would break `vi.stubEnv()`, which captures
|
|
* the original object when the worker starts and would keep deleting from it.
|
|
* Stubbing each key instead keeps that intact, and `unstubEnvs` restores them
|
|
* all before the next test.
|
|
*/
|
|
export function clearEnv(): void {
|
|
for (const key of Object.keys(process.env)) {
|
|
if (!unstubbableEnvVars.has(key)) {
|
|
vi.stubEnv(key, undefined);
|
|
}
|
|
}
|
|
}
|