Files
renovate/lib/util/http/gitlab.spec.ts
T
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

276 lines
9.9 KiB
TypeScript

import { HTTPError } from 'got';
import * as httpMock from '~test/http-mock.ts';
import { logger } from '~test/util.ts';
import { EXTERNAL_HOST_ERROR } from '../../constants/error-messages.ts';
import { GitlabReleasesDatasource } from '../../modules/datasource/gitlab-releases/index.ts';
import * as hostRules from '../host-rules.ts';
import { GitlabHttp, setBaseUrl } from './gitlab.ts';
hostRules.add({
hostType: 'gitlab',
token: '123test',
});
const gitlabApiHost = 'https://gitlab.com';
const selfHostedUrl = 'http://mycompany.com/gitlab';
describe('util/http/gitlab', () => {
let gitlabApi: GitlabHttp;
beforeEach(() => {
gitlabApi = new GitlabHttp();
setBaseUrl(`${gitlabApiHost}/api/v4/`);
vi.stubEnv('GITLAB_IGNORE_REPO_URL', undefined);
hostRules.add({
hostType: 'gitlab',
token: 'abc123',
});
});
afterEach(() => {
hostRules.clear();
});
it('paginates', async () => {
httpMock
.scope(gitlabApiHost)
.get('/api/v4/some-url')
.reply(200, ['a'], {
link: '<https://gitlab.com/api/v4/some-url&page=2>; rel="next", <https://gitlab.com/api/v4/some-url&page=4>; rel="last"',
})
.get('/api/v4/some-url&page=2')
.reply(200, ['b', 'c'], {
link: '<https://gitlab.com/api/v4/some-url&page=3>; rel="next", <https://gitlab.com/api/v4/some-url&page=4>; rel="last"',
})
.get('/api/v4/some-url&page=3')
.reply(200, ['d'], {
link: '<https://gitlab.com/api/v4/some-url&page=4>; rel="next", <https://gitlab.com/api/v4/some-url&page=4>; rel="last"',
})
.get('/api/v4/some-url&page=4')
.reply(500);
const res = await gitlabApi.getJsonUnchecked('some-url', {
paginate: true,
});
expect(res.body).toHaveLength(4);
expect(logger.logger.warn).toHaveBeenCalledWith(
{ err: expect.any(Error) },
'Pagination error',
);
});
it('paginates with GITLAB_IGNORE_REPO_URL set', async () => {
vi.stubEnv('GITLAB_IGNORE_REPO_URL', 'true');
setBaseUrl(`${selfHostedUrl}/api/v4/`);
httpMock
.scope(selfHostedUrl)
.get('/api/v4/some-url')
.reply(200, ['a'], {
link: '<https://other.host.com/gitlab/api/v4/some-url&page=2>; rel="next", <https://other.host.com/gitlab/api/v4/some-url&page=3>; rel="last"',
})
.get('/api/v4/some-url&page=2')
.reply(200, ['b', 'c'], {
link: '<https://other.host.com/gitlab/api/v4/some-url&page=3>; rel="next", <https://other.host.com/gitlab/api/v4/some-url&page=3>; rel="last"',
})
.get('/api/v4/some-url&page=3')
.reply(200, ['d']);
const res = await gitlabApi.getJsonUnchecked('some-url', {
paginate: true,
});
expect(res.body).toHaveLength(4);
});
it('does not follow pagination links to a different origin', async () => {
// If a misconfigured/malicious host suggests pagination links across origins, ignore them by default
// In this case, only the first page of results is fetched, and a warning message is logged
httpMock.scope(gitlabApiHost).get('/api/v4/some-url').reply(200, ['a'], {
link: '<https://other.host.com/api/v4/some-url&page=2>; rel="next", <https://other.host.com/api/v4/some-url&page=3>; rel="last"',
});
const res = await gitlabApi.getJsonUnchecked('some-url', {
paginate: true,
});
expect(res.body).toHaveLength(1);
expect(logger.logger.once.warn).toHaveBeenCalledWith(
{
requestHost: 'gitlab.com',
paginationHost: 'other.host.com',
},
'Ignoring cross-origin GitLab pagination link. Set GITLAB_IGNORE_REPO_URL if this is a self-hosted instance that returns a different host in pagination links.',
);
});
it('supports different datasources', async () => {
const gitlabApiDatasource = new GitlabHttp(GitlabReleasesDatasource.id);
hostRules.add({ hostType: 'gitlab', token: 'abc' });
hostRules.add({
hostType: GitlabReleasesDatasource.id,
token: 'def',
});
httpMock
.scope(gitlabApiHost, { reqheaders: { authorization: 'Bearer def' } })
.get('/api/v4/some-url')
.reply(200);
const response = await gitlabApiDatasource.get('/some-url');
expect(response).not.toBeNull();
});
it('attempts to paginate', async () => {
httpMock.scope(gitlabApiHost).get('/api/v4/some-url').reply(200, ['a'], {
link: '<https://gitlab.com/api/v4/some-url&page=3>; rel="last"',
});
const res = await gitlabApi.getJsonUnchecked('some-url', {
paginate: true,
});
expect(res.body).toHaveLength(1);
});
it('posts', async () => {
const body = ['a', 'b'];
httpMock.scope(gitlabApiHost).post('/api/v4/some-url').reply(200, body);
const res = await gitlabApi.postJson('some-url');
expect(res.body).toEqual(body);
});
it('sets baseUrl', () => {
expect(() => setBaseUrl(`${selfHostedUrl}/api/v4/`)).not.toThrow();
});
describe('fails with', () => {
it('403', async () => {
httpMock.scope(gitlabApiHost).get('/api/v4/some-url').reply(403);
await expect(
gitlabApi.get('some-url'),
).rejects.toThrowErrorMatchingInlineSnapshot(
`[HTTPError: Request failed with status code 403 (Forbidden): GET https://gitlab.com/api/v4/some-url]`,
);
});
it('404', async () => {
httpMock.scope(gitlabApiHost).get('/api/v4/some-url').reply(404);
await expect(
gitlabApi.get('some-url'),
).rejects.toThrowErrorMatchingInlineSnapshot(
`[HTTPError: Request failed with status code 404 (Not Found): GET https://gitlab.com/api/v4/some-url]`,
);
});
it('500', async () => {
httpMock.scope(gitlabApiHost).get('/api/v4/some-url').reply(500);
await expect(gitlabApi.get('some-url')).rejects.toThrow(
EXTERNAL_HOST_ERROR,
);
});
it('EAI_AGAIN', async () => {
httpMock
.scope(gitlabApiHost)
.get('/api/v4/some-url')
.replyWithError(httpMock.error({ code: 'EAI_AGAIN' }));
await expect(gitlabApi.get('some-url')).rejects.toThrow(
EXTERNAL_HOST_ERROR,
);
});
it('ParseError', async () => {
httpMock.scope(gitlabApiHost).get('/api/v4/some-url').reply(200, '{{');
await expect(gitlabApi.getJsonUnchecked('some-url')).rejects.toThrow(
EXTERNAL_HOST_ERROR,
);
});
});
describe('handles 409 errors', () => {
beforeEach(() => {
// Unset NODE_ENV so that we can test the retry logic
vi.stubEnv('NODE_ENV', undefined);
gitlabApi = new GitlabHttp();
});
it('retries the request on resource lock', async () => {
const body = { message: '409 Conflict: Resource lock' };
httpMock.scope(gitlabApiHost).post('/api/v4/some-url').reply(409, body);
httpMock.scope(gitlabApiHost).post('/api/v4/some-url').reply(200, {});
const res = await gitlabApi.postJson('some-url', {});
expect(res.statusCode).toBe(200);
});
it('does not retry more than twice on resource lock', async () => {
const body = { message: '409 Conflict: Resource lock' };
httpMock.scope(gitlabApiHost).post('/api/v4/some-url').reply(409, body);
httpMock.scope(gitlabApiHost).post('/api/v4/some-url').reply(409, body);
httpMock.scope(gitlabApiHost).post('/api/v4/some-url').reply(409, body);
await expect(gitlabApi.postJson('some-url', {})).rejects.toThrow(
HTTPError,
);
});
it('does not retry for other reasons', async () => {
const body = { message: 'Other reason' };
httpMock.scope(gitlabApiHost).post('/api/v4/some-url').reply(409, body);
await expect(gitlabApi.postJson('some-url', {})).rejects.toThrow(
HTTPError,
);
});
});
describe('handles 400 source_branch errors', () => {
beforeEach(() => {
// Unset NODE_ENV so that we can test the retry logic
vi.stubEnv('NODE_ENV', undefined);
gitlabApi = new GitlabHttp();
});
it('retries the request when source branch does not yet exist', async () => {
const body = { message: { source_branch: ['does not exist'] } };
httpMock.scope(gitlabApiHost).post('/api/v4/some-url').reply(400, body);
httpMock.scope(gitlabApiHost).post('/api/v4/some-url').reply(200, {});
const res = await gitlabApi.postJson('some-url', {});
expect(res.statusCode).toBe(200);
});
it('does not retry more than twice when source branch does not exist', async () => {
const body = { message: { source_branch: ['does not exist'] } };
httpMock.scope(gitlabApiHost).post('/api/v4/some-url').reply(400, body);
httpMock.scope(gitlabApiHost).post('/api/v4/some-url').reply(400, body);
httpMock.scope(gitlabApiHost).post('/api/v4/some-url').reply(400, body);
await expect(gitlabApi.postJson('some-url', {})).rejects.toThrow(
HTTPError,
);
});
it('does not retry for unrelated 400 errors', async () => {
const body = { message: { base: ['Another error'] } };
httpMock.scope(gitlabApiHost).post('/api/v4/some-url').reply(400, body);
await expect(gitlabApi.postJson('some-url', {})).rejects.toThrow(
HTTPError,
);
});
it('does not retry for other source_branch 400 errors', async () => {
const body = { message: { source_branch: ['is invalid'] } };
httpMock.scope(gitlabApiHost).post('/api/v4/some-url').reply(400, body);
await expect(gitlabApi.postJson('some-url', {})).rejects.toThrow(
HTTPError,
);
});
it('does not retry other POST error codes', async () => {
const body = { message: 'Forbidden' };
httpMock.scope(gitlabApiHost).post('/api/v4/some-url').reply(403, body);
await expect(gitlabApi.postJson('some-url', {})).rejects.toThrow(
HTTPError,
);
});
it('does not retry non-POST requests', async () => {
const body = { message: { source_branch: ['does not exist'] } };
httpMock.scope(gitlabApiHost).get('/api/v4/some-url').reply(400, body);
await expect(gitlabApi.getJsonUnchecked('some-url')).rejects.toThrow(
HTTPError,
);
});
});
});