Files
renovate/lib/modules/platform/gitlab/pr-cache.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

302 lines
7.6 KiB
TypeScript

import { fakeSha } from '~test/util.ts';
import * as httpMock from '../../../../test/http-mock.ts';
import { reset as memCacheReset } from '../../../util/cache/memory/index.ts';
import {
getCache,
resetCache as repoCacheReset,
} from '../../../util/cache/repository/index.ts';
import { GitlabHttp, setBaseUrl } from '../../../util/http/gitlab.ts';
import { GitlabPrCache } from './pr-cache.ts';
import type { GitLabMergeRequest } from './schema.ts';
import type { GitlabPrCacheData } from './types.ts';
import { prInfo } from './utils.ts';
const http = new GitlabHttp();
const sha = fakeSha('sha');
const pr1: GitLabMergeRequest = {
iid: 1,
title: 'title',
state: 'opened',
source_branch: 'branch',
target_branch: 'master',
reviewers: [],
updated_at: '2020-01-01T00:00:00.000Z',
created_at: '2020-01-01T00:00:00.000Z',
diverged_commits_count: 5,
labels: [],
detailed_merge_status: 'not_approved',
description: 'a merge request',
sha,
assignee: undefined,
assignees: [],
};
const pr2: GitLabMergeRequest = {
iid: 2,
title: 'title',
state: 'opened',
source_branch: 'branch',
target_branch: 'master',
updated_at: '2023-01-01T00:00:00.000Z',
created_at: '2023-01-01T00:00:00.000Z',
diverged_commits_count: 5,
labels: [],
detailed_merge_status: 'not_approved',
description: 'a merge request',
sha,
assignee: undefined,
assignees: [],
reviewers: [],
};
const pr3: GitLabMergeRequest = {
iid: 3,
title: 'title',
state: 'opened',
source_branch: 'branch',
target_branch: 'master',
updated_at: '2023-01-01T00:00:00.000Z',
created_at: '2023-01-01T00:00:00.000Z',
diverged_commits_count: 5,
labels: [],
detailed_merge_status: 'not_approved',
description: 'a merge request',
sha,
assignee: undefined,
assignees: [],
reviewers: [],
};
describe('modules/platform/gitlab/pr-cache', () => {
let cache = getCache();
beforeEach(() => {
memCacheReset();
repoCacheReset();
cache = getCache();
vi.stubEnv('GITLAB_IGNORE_REPO_URL', undefined);
setBaseUrl('https://gitlab.com/api/v4');
});
it('fetches cache initially', async () => {
httpMock
.scope('https://gitlab.com/api/v4/')
.get(
'/projects/repo/merge_requests?per_page=100&order_by=updated_at&sort=desc&scope=created_by_me',
)
.reply(200, [pr1]);
const res = await GitlabPrCache.getPrs(http, 'repo', 'some-author', false);
expect(res).toMatchObject([
{
number: 1,
title: 'title',
},
]);
expect(cache.platform).toMatchObject({
gitlab: {
pullRequestsCache: {
author: 'some-author',
items: {
'1': prInfo(pr1),
},
updated_at: '2020-01-01T00:00:00Z',
},
},
});
});
it('fetches cache with ignorePrAuthor=true', async () => {
httpMock
.scope('https://gitlab.com/api/v4/')
.get(
'/projects/repo/merge_requests?per_page=100&order_by=updated_at&sort=desc',
)
.reply(200, [pr1]);
const res = await GitlabPrCache.getPrs(http, 'repo', 'some-author', true);
expect(res).toMatchObject([
{
number: 1,
title: 'title',
},
]);
});
it('resets cache for not matching authors', async () => {
cache.platform = {
gitlab: {
pullRequestsCache: {
items: {
'1': prInfo(pr1),
},
author: 'some-other-author',
updated_at: '2020-01-01T00:00:00Z',
},
},
};
httpMock
.scope('https://gitlab.com/api/v4/')
.get(
'/projects/repo/merge_requests?per_page=100&order_by=updated_at&sort=desc&scope=created_by_me',
)
.reply(200, [pr1]);
const res = await GitlabPrCache.getPrs(http, 'repo', 'some-author', false);
expect(res).toMatchObject([
{
number: 1,
title: 'title',
},
]);
expect(cache.platform).toMatchObject({
gitlab: {
pullRequestsCache: {
author: 'some-author',
items: {
'1': prInfo(pr1),
},
updated_at: '2020-01-01T00:00:00Z',
},
},
});
});
it('resets cache for older format with milliseconds', async () => {
cache.platform = {
gitlab: {
pullRequestsCache: {
items: {
'1': prInfo(pr1),
},
author: 'some-author',
updated_at: '2020-01-01T00:00:00.123Z',
},
},
};
httpMock
.scope('https://gitlab.com/api/v4/')
.get(
'/projects/repo/merge_requests?per_page=100&order_by=updated_at&sort=desc&scope=created_by_me',
)
.reply(200, [pr1]);
const res = await GitlabPrCache.getPrs(http, 'repo', 'some-author', false);
expect(res).toMatchObject([
{
number: 1,
title: 'title',
},
]);
expect(cache.platform).toMatchObject({
gitlab: {
pullRequestsCache: {
author: 'some-author',
items: {
'1': prInfo(pr1),
},
updated_at: '2020-01-01T00:00:00Z',
},
},
});
});
it('syncs cache with updated_after parameter', async () => {
cache.platform = {
gitlab: {
pullRequestsCache: {
items: {
'1': prInfo(pr1),
},
author: 'some-author',
updated_at: '2022-01-01T00:00:00Z',
},
},
};
httpMock
.scope('https://gitlab.com/api/v4')
.get(
'/projects/repo/merge_requests?per_page=100&order_by=updated_at&sort=desc&updated_after=2022-01-01T00%3A00%3A00Z&scope=created_by_me',
)
.reply(200, [pr2]);
const res = await GitlabPrCache.getPrs(http, 'repo', 'some-author', false);
// Items are returned in reverse order by number (updateItems() calls reverse())
expect(res).toMatchObject([
{ number: 2, title: 'title' },
{ number: 1, title: 'title' },
]);
expect(cache.platform).toMatchObject({
gitlab: {
pullRequestsCache: {
items: {
'1': prInfo(pr1),
'2': prInfo(pr2),
},
author: 'some-author',
updated_at: '2023-01-01T00:00:00Z',
},
},
});
});
it('handles empty response', async () => {
httpMock
.scope('https://gitlab.com/api/v4/')
.get(
'/projects/repo/merge_requests?per_page=100&order_by=updated_at&sort=desc&scope=created_by_me',
)
.reply(200, []);
const res = await GitlabPrCache.getPrs(http, 'repo', 'some-author', false);
expect(res).toEqual([]);
const prCache = cache.platform?.gitlab
?.pullRequestsCache as GitlabPrCacheData;
expect(prCache.updated_at).toBeNull();
});
it('returns items in reverse order (most recent first)', async () => {
httpMock
.scope('https://gitlab.com/api/v4/')
.get(
'/projects/repo/merge_requests?per_page=100&order_by=updated_at&sort=desc&scope=created_by_me',
)
.reply(200, [pr1, pr2, pr3]);
const res = await GitlabPrCache.getPrs(http, 'repo', 'some-author', false);
expect(res.map((pr) => pr.number)).toEqual([3, 2, 1]);
});
it('normalizes timestamps by removing milliseconds', async () => {
const prWithMilliseconds = {
...pr1,
updated_at: '2020-01-01T00:00:00.123Z',
};
httpMock
.scope('https://gitlab.com/api/v4/')
.get(
'/projects/repo/merge_requests?per_page=100&order_by=updated_at&sort=desc&scope=created_by_me',
)
.reply(200, [prWithMilliseconds]);
await GitlabPrCache.getPrs(http, 'repo', 'some-author', false);
const prCache = cache.platform?.gitlab
?.pullRequestsCache as GitlabPrCacheData;
expect(prCache.updated_at).toBe('2020-01-01T00:00:00Z');
});
});