Files
renovate/lib/modules/datasource/go/index.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

313 lines
9.2 KiB
TypeScript

import { Fixtures } from '~test/fixtures.ts';
import * as httpMock from '~test/http-mock.ts';
import type { ReleaseResult } from '../index.ts';
import { getPkgReleases } from '../index.ts';
import { GoDatasource } from './index.ts';
const getReleasesDirectMock = vi.fn();
const getDigestForgejoMock = vi.fn();
const getDigestGiteaMock = vi.fn();
const getDigestGithubMock = vi.fn();
const getDigestGitlabMock = vi.fn();
const getDigestGitMock = vi.fn();
const getDigestBitbucketMock = vi.fn();
vi.mock('./releases-direct.ts', () => {
return {
GoDirectDatasource: vi.fn(
class {
forgejo = {
getDigest: (...args: any[]) => getDigestForgejoMock(...args),
};
git = { getDigest: (...args: any[]) => getDigestGitMock(...args) };
gitea = { getDigest: (...args: any[]) => getDigestGiteaMock(...args) };
github = {
getDigest: (...args: any[]) => getDigestGithubMock(...args),
};
gitlab = {
getDigest: (...args: any[]) => getDigestGitlabMock(...args),
};
bitbucket = {
getDigest: (...args: any[]) => getDigestBitbucketMock(...args),
};
getReleases = (...args: any[]) => getReleasesDirectMock(...args);
},
),
};
});
const getReleasesProxyMock = vi.fn();
vi.mock('./releases-goproxy.ts', () => {
return {
GoProxyDatasource: vi.fn(
class {
getReleases = () => getReleasesProxyMock();
},
),
};
});
const datasource = new GoDatasource();
describe('modules/datasource/go/index', () => {
describe('getReleases', () => {
it('fetches releases', async () => {
const expected = { releases: [{ version: '0.0.1' }] };
getReleasesProxyMock.mockResolvedValue(expected);
getReleasesDirectMock.mockResolvedValue(null);
const res = await datasource.getReleases({
packageName: 'golang.org/foo/bar',
});
expect(res).toBe(expected);
expect(getReleasesProxyMock).toHaveBeenCalled();
expect(getReleasesDirectMock).not.toHaveBeenCalled();
});
});
describe('getDigest', () => {
it('returns null for no go-source tag', async () => {
httpMock
.scope('https://golang.org/')
.get('/y/text?go-get=1')
.reply(200, '');
const res = await datasource.getDigest(
{ packageName: 'golang.org/y/text' },
undefined,
);
expect(res).toBeNull();
});
it('returns null for wrong name', async () => {
httpMock
.scope('https://golang.org/')
.get('/y/text?go-get=1')
.reply(200, Fixtures.get('go-get-github.html'));
const res = await datasource.getDigest(
{ packageName: 'golang.org/y/text' },
undefined,
);
expect(res).toBeNull();
});
it('supports gitlab digest', async () => {
httpMock
.scope('https://gitlab.com/')
.get('/group/subgroup?go-get=1')
.reply(200, Fixtures.get('go-get-gitlab.html'));
getDigestGitlabMock.mockResolvedValue('abcdefabcdefabcdefabcdef');
const res = await datasource.getDigest(
{ packageName: 'gitlab.com/group/subgroup' },
undefined,
);
expect(res).toBe('abcdefabcdefabcdefabcdef');
});
it('supports git digest', async () => {
httpMock
.scope('https://renovatebot.com/')
.get('/abc/def?go-get=1')
.reply(200, Fixtures.get('go-get-git-digest.html'));
getDigestGitMock.mockResolvedValue('abcdefabcdefabcdefabcdef');
const res = await datasource.getDigest(
{ packageName: 'renovatebot.com/abc/def' },
undefined,
);
expect(res).toBe('abcdefabcdefabcdefabcdef');
});
it('supports gitlab digest with a specific branch', async () => {
const branch = 'some-branch';
httpMock
.scope('https://gitlab.com/')
.get('/group/subgroup?go-get=1')
.reply(200, Fixtures.get('go-get-gitlab.html'));
getDigestGitlabMock.mockResolvedValue('abcdefabcdefabcdefabcdef');
const res = await datasource.getDigest(
{ packageName: 'gitlab.com/group/subgroup' },
branch,
);
expect(res).toBe('abcdefabcdefabcdefabcdef');
});
it('returns github digest', async () => {
httpMock
.scope('https://golang.org/')
.get('/x/text?go-get=1')
.reply(200, Fixtures.get('go-get-github.html'));
getDigestGithubMock.mockResolvedValueOnce('abcdefabcdefabcdefabcdef');
const res = await datasource.getDigest(
{ packageName: 'golang.org/x/text' },
'v1.2.3',
);
expect(res).toBe('abcdefabcdefabcdefabcdef');
expect(getDigestGithubMock).toHaveBeenCalledExactlyOnceWith(
{
datasource: 'github-tags',
packageName: 'golang/text',
registryUrl: 'https://github.com',
},
'v1.2.3',
);
});
it('returns github default branch digest', async () => {
httpMock
.scope('https://golang.org/')
.get('/x/text?go-get=1')
.reply(200, Fixtures.get('go-get-github.html'));
getDigestGithubMock.mockResolvedValueOnce('abcdefabcdefabcdefabcdef');
const res = await datasource.getDigest(
{ packageName: 'golang.org/x/text' },
'v0.0.0',
);
expect(res).toBe('abcdefabcdefabcdefabcdef');
expect(getDigestGithubMock).toHaveBeenCalledExactlyOnceWith(
{
datasource: 'github-tags',
packageName: 'golang/text',
registryUrl: 'https://github.com',
},
undefined,
);
});
it('support bitbucket digest', async () => {
getDigestBitbucketMock.mockResolvedValueOnce('123');
const res = await datasource.getDigest(
{
packageName: 'bitbucket.org/golang/text',
},
undefined,
);
expect(res).toBe('123');
});
it('support forgejo digest', async () => {
getDigestForgejoMock.mockResolvedValueOnce('123');
const res = await datasource.getDigest(
{
packageName: 'code.forgejo.org/go-chi/cache',
},
undefined,
);
expect(res).toBe('123');
});
it('support gitea digest', async () => {
getDigestGiteaMock.mockResolvedValueOnce('123');
const res = await datasource.getDigest(
{
packageName: 'gitea.com/go-chi/cache',
},
undefined,
);
expect(res).toBe('123');
});
describe('GOPROXY', () => {
it('returns null when GOPROXY contains off', async () => {
vi.stubEnv('GOPROXY', 'https://proxy.golang.org,off');
const res = await datasource.getDigest(
{ packageName: 'golang.org/x/text' },
'v1.2.3',
);
expect(res).toBeNull();
});
});
});
describe('using getPkgReleases', () => {
describe('constraints', () => {
// TODO deprecated #42600
it('are respected based on an exact match on the `go` constraint', async () => {
const expected: ReleaseResult = {
releases: [
// Go 1.24
{
version: 'v0.32.0',
constraints: {
go: ['1.24.0'],
},
},
{
version: 'v0.33.0',
constraints: {
go: ['1.24.2'],
},
},
// Go 1.25
{
version: 'v0.34.0',
constraints: {
go: ['1.25.0'],
},
},
],
};
getReleasesProxyMock.mockResolvedValue(expected);
getReleasesDirectMock.mockResolvedValue(null);
const res = await getPkgReleases({
datasource: GoDatasource.id,
packageName: 'golang.org/x/mod',
constraints: { go: '1.24.0' },
constraintsFiltering: 'strict',
});
expect(res).toBeDefined();
expect(res?.releases).toHaveLength(1);
expect(res?.releases[0].version).toEqual('v0.32.0');
});
it('are respected based on a SemVer-style range based on the `%goMod` constraint', async () => {
const expected: ReleaseResult = {
releases: [
// Go 1.24
{
version: 'v0.32.0',
constraints: {
'%goMod': ['1.24.0'],
},
},
{
version: 'v0.33.0',
constraints: {
'%goMod': ['1.24.1'],
},
},
// Go 1.25
{
version: 'v0.34.0',
constraints: {
'%goMod': ['1.25.0'],
},
},
],
};
getReleasesProxyMock.mockResolvedValue(expected);
getReleasesDirectMock.mockResolvedValue(null);
const res = await getPkgReleases({
datasource: GoDatasource.id,
packageName: 'golang.org/x/mod',
constraints: { '%goMod': '~1.24.x' },
constraintsFiltering: 'strict',
constraintsVersioning: {
'%goMod': 'semver-coerced',
},
});
expect(res).toBeDefined();
expect(res?.releases).toHaveLength(2);
expect(res?.releases[0].version).toEqual('v0.32.0');
expect(res?.releases[1].version).toEqual('v0.33.0');
});
});
});
});