Files
renovate/lib/modules/manager/gomod/artifacts-gomodtidyall.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

245 lines
7.9 KiB
TypeScript

import { codeBlock } from 'common-tags';
import upath from 'upath';
import { mockDeep } from 'vitest-mock-extended';
import { envMock, mockExecAll } from '~test/exec-util.ts';
import { env, fs, git, partial } from '~test/util.ts';
import { GlobalConfig } from '../../../config/global.ts';
import type {
InternalGlobalConfigOptions,
RepoGlobalConfig,
} from '../../../config/types.ts';
import * as docker from '../../../util/exec/docker/index.ts';
import type { StatusResult } from '../../../util/git/types.ts';
import * as hostRules from '../../../util/host-rules.ts';
import * as _datasource from '../../datasource/index.ts';
import type { UpdateArtifactsConfig } from '../types.ts';
import * as gomod from './index.ts';
import * as _packageTree from './package-tree.ts';
type FS = typeof import('../../../util/fs/index.ts');
vi.mock('../../../util/exec/env.ts');
vi.mock('../../../util/http/index.ts');
vi.mock('../../../util/fs/index.ts', async () => {
return mockDeep({
isValidLocalPath: (await vi.importActual<FS>('../../../util/fs/index.ts'))
.isValidLocalPath,
});
});
vi.mock('../../datasource/index.ts', () => mockDeep());
vi.mock('./artifacts-extra.ts', () => mockDeep());
vi.mock('./package-tree.ts', () => ({ getGoModulesInTidyOrder: vi.fn() }));
const datasource = vi.mocked(_datasource);
const packageTree = vi.mocked(_packageTree);
process.env.CONTAINERBASE = 'true';
const gomod1 = codeBlock`
module github.com/renovate-tests/gomod1
require github.com/pkg/errors v0.7.0
replace github.com/pkg/errors => ../errors
`;
const adminConfig: RepoGlobalConfig & InternalGlobalConfigOptions = {
localDir: upath.join('/tmp/github/some/repo'),
cacheDir: upath.join('/tmp/renovate/cache'),
containerbaseDir: upath.join('/tmp/renovate/cache/containerbase'),
dockerSidecarImage: 'ghcr.io/renovatebot/base-image',
};
const goEnv = {
GONOSUMDB: '1',
GOPROXY: 'proxy.example.com',
GOPRIVATE: 'private.example.com/*',
GONOPROXY: 'noproxy.example.com/*',
GOINSECURE: 'insecure.example.com/*',
CGO_ENABLED: '1',
};
function baseConfig(
overrides: Partial<UpdateArtifactsConfig> = {},
): UpdateArtifactsConfig {
return {
constraints: { go: '1.21' },
postUpdateOptions: ['gomodTidyAll', 'gomodTidy'],
...overrides,
};
}
describe('modules/manager/gomod/artifacts-gomodtidyall', () => {
beforeEach(() => {
vi.stubEnv('GOPATH', undefined);
env.getChildProcessEnv.mockReturnValue({ ...envMock.basic, ...goEnv });
GlobalConfig.set(adminConfig);
docker.resetPrefetchedImages();
hostRules.clear();
datasource.getPkgReleases.mockResolvedValue({
releases: [{ version: '1.21.0' }],
});
fs.findLocalSiblingOrParent.mockResolvedValueOnce('vendor');
fs.readLocalFile.mockResolvedValueOnce('Current go.sum');
fs.readLocalFile.mockResolvedValueOnce(null); // vendor modules.txt
});
it('emits subshell tidy commands with correct relative dirs, tidyOpts, and returns dependent sum files', async () => {
const execSnapshots = mockExecAll();
packageTree.getGoModulesInTidyOrder.mockResolvedValueOnce([
'api/go.mod',
'cmd/go.mod',
]);
git.getRepoStatus.mockResolvedValueOnce(
partial<StatusResult>({
modified: ['shared/go.sum', 'api/go.sum', 'cmd/go.sum'],
}),
);
fs.readLocalFile.mockResolvedValueOnce('New go.sum');
fs.readLocalFile.mockResolvedValueOnce('New api/go.sum');
fs.readLocalFile.mockResolvedValueOnce('New cmd/go.sum');
fs.readLocalFile.mockResolvedValueOnce(gomod1);
const result = await gomod.updateArtifacts({
packageFileName: 'shared/go.mod',
updatedDeps: [],
newPackageFileContent: gomod1,
config: baseConfig({
postUpdateOptions: ['gomodTidyAll', 'gomodTidy1.17', 'gomodTidyE'],
}),
});
// Relative paths from shared/ and tidyOpts propagation in one shot.
expect(execSnapshots).toEqual(
expect.arrayContaining([
expect.objectContaining({
cmd: 'go -C ../api mod tidy -compat=1.17 -e',
}),
expect.objectContaining({
cmd: 'go -C ../cmd mod tidy -compat=1.17 -e',
}),
]),
);
expect(result).toEqual(
expect.arrayContaining([
expect.objectContaining({
file: expect.objectContaining({ path: 'api/go.sum' }),
}),
expect.objectContaining({
file: expect.objectContaining({ path: 'cmd/go.sum' }),
}),
]),
);
});
it('implies primary tidy when only gomodTidyAll is set', async () => {
const execSnapshots = mockExecAll();
packageTree.getGoModulesInTidyOrder.mockResolvedValueOnce(['api/go.mod']);
git.getRepoStatus.mockResolvedValueOnce(
partial<StatusResult>({ modified: ['go.sum', 'api/go.sum'] }),
);
fs.readLocalFile.mockResolvedValueOnce('New go.sum');
fs.readLocalFile.mockResolvedValueOnce('New api/go.sum');
fs.readLocalFile.mockResolvedValueOnce(gomod1);
await gomod.updateArtifacts({
packageFileName: 'go.mod',
updatedDeps: [],
newPackageFileContent: gomod1,
config: baseConfig({ postUpdateOptions: ['gomodTidyAll'] }),
});
expect(execSnapshots).toEqual(
expect.arrayContaining([
expect.objectContaining({ cmd: 'go mod tidy' }),
expect.objectContaining({ cmd: 'go -C api mod tidy' }),
]),
);
});
it('collects updated dependent go.mod when only that file changed', async () => {
mockExecAll();
packageTree.getGoModulesInTidyOrder.mockResolvedValueOnce(['api/go.mod']);
git.getRepoStatus.mockResolvedValueOnce(
partial<StatusResult>({ modified: ['api/go.mod'] }),
);
fs.readLocalFile.mockResolvedValueOnce('New api/go.mod');
fs.readLocalFile.mockResolvedValueOnce(gomod1);
const result = await gomod.updateArtifacts({
packageFileName: 'go.mod',
updatedDeps: [],
newPackageFileContent: gomod1,
config: baseConfig(),
});
expect(result).toEqual(
expect.arrayContaining([
expect.objectContaining({
file: expect.objectContaining({ path: 'api/go.mod' }),
}),
]),
);
});
it('is a no-op when no dependents are found', async () => {
mockExecAll();
packageTree.getGoModulesInTidyOrder.mockResolvedValueOnce([]);
git.getRepoStatus.mockResolvedValueOnce(
partial<StatusResult>({ modified: ['go.sum'] }),
);
fs.readLocalFile.mockResolvedValueOnce('New go.sum');
fs.readLocalFile.mockResolvedValueOnce(gomod1);
const result = await gomod.updateArtifacts({
packageFileName: 'go.mod',
updatedDeps: [],
newPackageFileContent: gomod1,
config: baseConfig(),
});
expect(result).toHaveLength(1);
expect(result![0].file!.path).toBe('go.sum');
});
it('continues when dependent-module resolution throws', async () => {
mockExecAll();
packageTree.getGoModulesInTidyOrder.mockRejectedValueOnce(
new Error('graph build failed'),
);
git.getRepoStatus.mockResolvedValueOnce(
partial<StatusResult>({ modified: ['go.sum'] }),
);
fs.readLocalFile.mockResolvedValueOnce('New go.sum');
fs.readLocalFile.mockResolvedValueOnce(gomod1);
const result = await gomod.updateArtifacts({
packageFileName: 'go.mod',
updatedDeps: [],
newPackageFileContent: gomod1,
config: baseConfig(),
});
expect(result).toHaveLength(1);
expect(result![0].file!.path).toBe('go.sum');
});
it('does not consult package-tree when gomodTidyAll is disabled', async () => {
mockExecAll();
git.getRepoStatus.mockResolvedValueOnce(
partial<StatusResult>({ modified: ['go.sum'] }),
);
fs.readLocalFile.mockResolvedValueOnce('New go.sum');
fs.readLocalFile.mockResolvedValueOnce(gomod1);
await gomod.updateArtifacts({
packageFileName: 'go.mod',
updatedDeps: [],
newPackageFileContent: gomod1,
config: baseConfig({ postUpdateOptions: ['gomodTidy'] }),
});
expect(packageTree.getGoModulesInTidyOrder).not.toHaveBeenCalled();
});
});