Files
renovate/lib/modules/datasource/npm/npmrc.spec.ts
Sebastian Poxhofer fbedd41e82 test: replace env operation with vi.stubEnv() (#45490)
* 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.
2026-08-28 09:26:20 +00:00

219 lines
5.8 KiB
TypeScript

import ini from 'ini';
import { GlobalConfig } from '../../../config/global.ts';
import * as _sanitize from '../../../util/sanitize.ts';
import { defaultRegistryUrl } from './common.ts';
import {
convertNpmrcToRules,
getMatchHostFromNpmrcHost,
setNpmrc,
} from './npmrc.ts';
vi.mock('../../../util/sanitize.ts');
const sanitize = vi.mocked(_sanitize);
describe('modules/datasource/npm/npmrc', () => {
beforeEach(() => {
setNpmrc('');
GlobalConfig.reset();
});
describe('getMatchHostFromNpmrcHost()', () => {
it('parses //host', () => {
expect(getMatchHostFromNpmrcHost('//registry.npmjs.org')).toBe(
'registry.npmjs.org',
);
});
it('parses //host/path', () => {
expect(
getMatchHostFromNpmrcHost('//registry.company.com/some/path'),
).toBe('https://registry.company.com/some/path');
});
it('parses https://host', () => {
expect(getMatchHostFromNpmrcHost(defaultRegistryUrl)).toBe(
defaultRegistryUrl,
);
});
});
describe('convertNpmrcToRules()', () => {
it('rejects invalid registries', () => {
const res = convertNpmrcToRules(
ini.parse('registry=1\n@scope:registry=2\n'),
);
expect(res.hostRules).toHaveLength(0);
expect(res.packageRules).toHaveLength(0);
});
it('handles naked auth', () => {
expect(convertNpmrcToRules(ini.parse('_auth=abc123\n')))
.toMatchInlineSnapshot(`
{
"hostRules": [
{
"authType": "Basic",
"hostType": "npm",
"token": "abc123",
},
],
"packageRules": [],
}
`);
});
it('handles host, path and auth', () => {
expect(
convertNpmrcToRules(ini.parse('//some.test/with/path:_auth=abc123')),
).toMatchInlineSnapshot(`
{
"hostRules": [
{
"authType": "Basic",
"hostType": "npm",
"matchHost": "https://some.test/with/path",
"token": "abc123",
},
],
"packageRules": [],
}
`);
});
it('handles host, path, port and auth', () => {
expect(
convertNpmrcToRules(
ini.parse('//some.test:8080/with/path:_authToken=abc123'),
),
).toMatchInlineSnapshot(`
{
"hostRules": [
{
"hostType": "npm",
"matchHost": "https://some.test:8080/with/path",
"token": "abc123",
},
],
"packageRules": [],
}
`);
});
it('handles naked authToken', () => {
expect(convertNpmrcToRules(ini.parse('_authToken=abc123\n')))
.toMatchInlineSnapshot(`
{
"hostRules": [
{
"hostType": "npm",
"token": "abc123",
},
],
"packageRules": [],
}
`);
});
it('handles host authToken', () => {
expect(
convertNpmrcToRules(
ini.parse(
'@fontawesome:registry=https://npm.fontawesome.com/\n//npm.fontawesome.com/:_authToken=abc123',
),
),
).toMatchInlineSnapshot(`
{
"hostRules": [
{
"hostType": "npm",
"matchHost": "https://npm.fontawesome.com/",
"token": "abc123",
},
],
"packageRules": [
{
"matchDatasources": [
"npm",
],
"matchPackageNames": [
"@fontawesome/**",
],
"registryUrls": [
"https://npm.fontawesome.com/",
],
},
],
}
`);
});
it('handles username and _password', () => {
expect(
convertNpmrcToRules(
ini.parse(
`//my-registry.example.com/npm-private/:_password=dGVzdA==\n//my-registry.example.com/npm-private/:username=bot\n//my-registry.example.com/npm-private/:always-auth=true`,
),
),
).toMatchInlineSnapshot(`
{
"hostRules": [
{
"hostType": "npm",
"matchHost": "https://my-registry.example.com/npm-private/",
"password": "test",
"username": "bot",
},
],
"packageRules": [],
}
`);
});
});
it('sanitize _auth', () => {
setNpmrc('_auth=test');
expect(sanitize.addSecretForSanitizing).toHaveBeenCalledExactlyOnceWith(
'test',
);
});
it('sanitize _authtoken', () => {
setNpmrc('//registry.test.com:_authToken=test\n_authToken=${NPM_TOKEN}');
expect(sanitize.addSecretForSanitizing).toHaveBeenNthCalledWith(1, 'test');
expect(sanitize.addSecretForSanitizing).toHaveBeenNthCalledWith(
2,
'${NPM_TOKEN}',
);
expect(sanitize.addSecretForSanitizing).toHaveBeenCalledTimes(2);
});
it('sanitize _password', () => {
setNpmrc(
`registry=https://test.org\n//test.org/:username=test\n//test.org/:_password=dGVzdA==`,
);
expect(sanitize.addSecretForSanitizing).toHaveBeenNthCalledWith(1, 'test');
expect(sanitize.addSecretForSanitizing).toHaveBeenNthCalledWith(
2,
'dGVzdDp0ZXN0',
);
expect(sanitize.addSecretForSanitizing).toHaveBeenCalledTimes(2);
});
it('sanitize _authtoken with high trust', () => {
GlobalConfig.set({ exposeAllEnv: true });
vi.stubEnv('TEST_TOKEN', 'test');
setNpmrc(
'//registry.test.com:_authToken=${TEST_TOKEN}\n_authToken=\nregistry=http://localhost',
);
expect(sanitize.addSecretForSanitizing).toHaveBeenCalledExactlyOnceWith(
'test',
);
});
it('ignores localhost', () => {
setNpmrc(`registry=http://localhost`);
expect(sanitize.addSecretForSanitizing).toHaveBeenCalledTimes(0);
});
});