Skip to content

Commit

Permalink
refactor(lib/workers): fix null-check for tests (#16163)
Browse files Browse the repository at this point in the history
Co-authored-by: Michael Kriese <michael.kriese@visualon.de>
  • Loading branch information
RahulGautamSingh and viceice committed Jun 21, 2022
1 parent 7f48897 commit 03b0d2a
Show file tree
Hide file tree
Showing 41 changed files with 270 additions and 208 deletions.
6 changes: 3 additions & 3 deletions lib/config/migration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export function migrateConfig(config: RenovateConfig): MigratedConfig {
const payload = migrateConfig(
packageFile as RenovateConfig
).migratedConfig;
for (const subrule of payload.packageRules || []) {
for (const subrule of payload.packageRules ?? []) {
subrule.paths = [(packageFile as any).packageFile];
migratedConfig.packageRules.push(subrule);
}
Expand Down Expand Up @@ -157,7 +157,7 @@ export function migrateConfig(config: RenovateConfig): MigratedConfig {
// validated non-null
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
delete migratedConfig.node!.enabled;
migratedConfig.travis = migratedConfig.travis || {};
migratedConfig.travis = migratedConfig.travis ?? {};
migratedConfig.travis.enabled = true;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
if (Object.keys(migratedConfig.node!).length) {
Expand Down Expand Up @@ -259,7 +259,7 @@ export function migrateConfig(config: RenovateConfig): MigratedConfig {
}
if (is.nonEmptyObject(migratedConfig['gradle-lite'])) {
migratedConfig.gradle = mergeChildConfig(
migratedConfig.gradle || {},
migratedConfig.gradle ?? {},
migratedConfig['gradle-lite']
);
}
Expand Down
2 changes: 1 addition & 1 deletion lib/workers/global/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ describe('workers/global/index', () => {
endpoint: 'https://github.com/',
writeDiscoveredRepos: '/tmp/renovate-output.json',
});
fs.writeFile.mockReturnValueOnce(null);
fs.writeFile.mockResolvedValueOnce();

expect(await globalWorker.start()).toBe(0);
expect(fs.writeFile).toHaveBeenCalledTimes(1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ jest.mock('./rebase');
jest.mock('./create');
jest.mock('../../../../util/git');

const migratedData: MigratedData = Fixtures.getJson('./migrated-data.json');
const migratedData = Fixtures.getJson<MigratedData>('./migrated-data.json');

describe('workers/repository/config-migration/branch/index', () => {
describe('checkConfigMigrationBranch', () => {
Expand Down
2 changes: 1 addition & 1 deletion lib/workers/repository/config-migration/branch/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { rebaseMigrationBranch } from './rebase';

export async function checkConfigMigrationBranch(
config: RenovateConfig,
migratedConfigData: MigratedData
migratedConfigData: MigratedData | null
): Promise<string | null> {
logger.debug('checkConfigMigrationBranch()');
if (!migratedConfigData) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ describe('workers/repository/config-migration/branch/migrated-data', () => {
it('Calls getAsync a first when migration not needed', async () => {
mockedFunction(migrateConfig).mockReturnValueOnce({
isMigrated: false,
migratedConfig: null,
migratedConfig: {},
});
await expect(MigratedDataFactory.getAsync()).resolves.toBeNull();
});
Expand All @@ -62,12 +62,12 @@ describe('workers/repository/config-migration/branch/migrated-data', () => {
describe('MigratedData class', () => {
it('gets the filename from the class instance', async () => {
const data = await MigratedDataFactory.getAsync();
expect(data.filename).toBe('renovate.json');
expect(data?.filename).toBe('renovate.json');
});

it('gets the content from the class instance', async () => {
const data = await MigratedDataFactory.getAsync();
expect(data.content).toBe(migratedData.content);
expect(data?.content).toBe(migratedData.content);
});
});

Expand All @@ -80,9 +80,10 @@ describe('workers/repository/config-migration/branch/migrated-data', () => {

it('Resets the factory and gets a new value with default indentation', async () => {
mockedFunction(detectIndent).mockReturnValueOnce({
type: null,
type: undefined,
amount: 0,
indent: null,
// TODO: incompatible types (#7154)
indent: null as never,
});
MigratedDataFactory.reset();
await expect(MigratedDataFactory.getAsync()).resolves.toEqual(
Expand All @@ -103,7 +104,7 @@ describe('workers/repository/config-migration/branch/migrated-data', () => {

it('Returns nothing due to fs error', async () => {
mockedFunction(detectRepoFileConfig).mockResolvedValueOnce({
configFileName: null,
configFileName: undefined,
});
mockedFunction(readLocalFile).mockRejectedValueOnce(null);
MigratedDataFactory.reset();
Expand Down
4 changes: 2 additions & 2 deletions lib/workers/repository/config-migration/pr/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ describe('workers/repository/config-migration/pr/index', () => {

it('creates PR with default PR title', async () => {
await ensureConfigMigrationPr(
{ ...config, onboardingPrTitle: null },
{ ...config, onboardingPrTitle: '' },
migratedData
);
expect(platform.getBranchPr).toHaveBeenCalledTimes(1);
Expand Down Expand Up @@ -229,7 +229,7 @@ describe('workers/repository/config-migration/pr/index', () => {
});

it('deletes branch when PR already exists but cannot find it', async () => {
err.response.body = {
response.body = {
errors: [{ message: 'A pull request already exists' }],
};
platform.createPr.mockRejectedValue(err);
Expand Down
4 changes: 3 additions & 1 deletion lib/workers/repository/dependency-dashboard.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
RenovateConfig,
getConfig,
logger,
mockedFunction,
platform,
} from '../../../test/util';
import { GlobalConfig } from '../../config/global';
Expand Down Expand Up @@ -517,7 +518,8 @@ describe('workers/repository/dependency-dashboard', () => {
config.dependencyDashboard = true;
config.dependencyDashboardChecks = { branchName2: 'approve-branch' };
config.dependencyDashboardIssue = 1;
platform.getIssue.mockResolvedValueOnce({
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
mockedFunction(platform.getIssue!).mockResolvedValueOnce({
title: 'Dependency Dashboard',
body: `This issue contains a list of Renovate updates and their statuses.
Expand Down
6 changes: 3 additions & 3 deletions lib/workers/repository/errors-warnings.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ describe('workers/repository/errors-warnings', () => {
packageFile: 'package.json',
deps: [
{
warnings: [{ message: 'Warning 1', topic: undefined }],
warnings: [{ message: 'Warning 1', topic: '' }],
},
{},
],
Expand All @@ -54,7 +54,7 @@ describe('workers/repository/errors-warnings', () => {
packageFile: 'backend/package.json',
deps: [
{
warnings: [{ message: 'Warning 1', topic: undefined }],
warnings: [{ message: 'Warning 1', topic: '' }],
},
],
},
Expand All @@ -64,7 +64,7 @@ describe('workers/repository/errors-warnings', () => {
packageFile: 'Dockerfile',
deps: [
{
warnings: [{ message: 'Warning 2', topic: undefined }],
warnings: [{ message: 'Warning 2', topic: '' }],
},
],
},
Expand Down
2 changes: 1 addition & 1 deletion lib/workers/repository/extract/file-match.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ describe('workers/repository/extract/file-match', () => {
});

it('deduplicates', () => {
config.fileMatch.push('package.json');
config.fileMatch?.push('package.json');
const res = fileMatch.getMatchingFiles(config, fileList);
expect(res).toMatchSnapshot();
expect(res).toHaveLength(2);
Expand Down
5 changes: 2 additions & 3 deletions lib/workers/repository/extract/manager-files.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import type { WorkerExtractConfig } from '../../types';

export async function getManagerPackageFiles(
config: WorkerExtractConfig
): Promise<PackageFile[]> {
): Promise<PackageFile[] | null> {
const { enabled, manager, fileList } = config;
logger.trace(`getPackageFiles(${manager})`);
if (!enabled) {
Expand Down Expand Up @@ -42,8 +42,7 @@ export async function getManagerPackageFiles(
}
}
}
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
return allPackageFiles!;
return allPackageFiles;
}
const packageFiles: PackageFile[] = [];
for (const packageFile of fileList) {
Expand Down
2 changes: 1 addition & 1 deletion lib/workers/repository/finalise/prune.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ async function cleanUpBranches(

export async function pruneStaleBranches(
config: RenovateConfig,
branchList: string[]
branchList: string[] | null | undefined
): Promise<void> {
logger.debug('Removing any stale branches');
logger.trace({ config }, `pruneStaleBranches`);
Expand Down
4 changes: 2 additions & 2 deletions lib/workers/repository/init/merge.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,14 +186,14 @@ describe('workers/repository/init/merge', () => {
migrateAndValidate.migrateAndValidate.mockResolvedValueOnce({
errors: [{ topic: 'dep', message: 'test error' }],
});
let e: Error;
let e: Error | undefined;
try {
await mergeRenovateConfig(config);
} catch (err) {
e = err;
}
expect(e).toBeDefined();
expect(e.toString()).toBe('Error: config-validation');
expect(e?.toString()).toBe('Error: config-validation');
});

it('migrates nested config', async () => {
Expand Down
4 changes: 2 additions & 2 deletions lib/workers/repository/init/semantic.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ describe('workers/repository/init/semantic', () => {
});

it('detects false if unknown', async () => {
config.semanticCommits = null;
config.semanticCommits = undefined;
git.getCommitMessages.mockResolvedValueOnce(['foo', 'bar']);
git.getCommitMessages.mockResolvedValueOnce([
'fix: foo',
Expand All @@ -33,7 +33,7 @@ describe('workers/repository/init/semantic', () => {
});

it('detects true if known', async () => {
config.semanticCommits = null;
config.semanticCommits = undefined;
git.getCommitMessages.mockResolvedValue(['fix: foo', 'refactor: bar']);
const res = await detectSemanticCommits();
expect(res).toBe('enabled');
Expand Down
13 changes: 9 additions & 4 deletions lib/workers/repository/init/vulnerability.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,16 @@ describe('workers/repository/init/vulnerability', () => {
});

it('returns if alerts are disabled', async () => {
config.vulnerabilityAlerts.enabled = false;
// TODO #7154
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
config.vulnerabilityAlerts!.enabled = false;
expect(await detectVulnerabilityAlerts(config)).toEqual(config);
});

it('returns if no alerts', async () => {
delete config.vulnerabilityAlerts.enabled;
// TODO #7154
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
delete config.vulnerabilityAlerts!.enabled;
platform.getVulnerabilityAlerts.mockResolvedValue([]);
expect(await detectVulnerabilityAlerts(config)).toEqual(config);
});
Expand All @@ -43,7 +47,8 @@ describe('workers/repository/init/vulnerability', () => {

it('returns alerts and remediations', async () => {
config.transitiveRemediation = true;
delete config.vulnerabilityAlerts.enabled;
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
delete config.vulnerabilityAlerts!.enabled;
platform.getVulnerabilityAlerts.mockResolvedValue([
partial<VulnerabilityAlert>({}),
{
Expand Down Expand Up @@ -73,7 +78,7 @@ describe('workers/repository/init/vulnerability', () => {
vulnerableManifestPath: 'backend/package-lock.json',
securityAdvisory: {
references: [],
severity: null,
severity: '',
},
securityVulnerability: {
package: { ecosystem: 'NPM', name: 'yargs-parser' },
Expand Down
6 changes: 3 additions & 3 deletions lib/workers/repository/model/semantic-commit-message.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ describe('workers/repository/model/semantic-commit-message', () => {
const instance = SemanticCommitMessage.fromString('feat: ticket 123');

expect(SemanticCommitMessage.is(instance)).toBeTrue();
expect(instance.toJSON()).toEqual({
expect(instance?.toJSON()).toEqual({
body: '',
footer: '',
scope: '',
Expand All @@ -44,7 +44,7 @@ describe('workers/repository/model/semantic-commit-message', () => {
);

expect(SemanticCommitMessage.is(instance)).toBeTrue();
expect(instance.toJSON()).toEqual({
expect(instance?.toJSON()).toEqual({
body: '',
footer: '',
scope: 'dashboard',
Expand All @@ -57,7 +57,7 @@ describe('workers/repository/model/semantic-commit-message', () => {
const instance = SemanticCommitMessage.fromString('fix(deps): ');

expect(SemanticCommitMessage.is(instance)).toBeTrue();
expect(instance.toJSON()).toEqual({
expect(instance?.toJSON()).toEqual({
body: '',
footer: '',
scope: 'deps',
Expand Down
10 changes: 6 additions & 4 deletions lib/workers/repository/onboarding/branch/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,10 @@ describe('workers/repository/onboarding/branch/index', () => {
fs.readLocalFile.mockResolvedValue('{}');
await checkOnboardingBranch(config);
const file = git.commitFiles.mock.calls[0][0].files[0] as FileAddition;
const contents = file.contents.toString();
const contents = file.contents?.toString();
expect(contents).toBeJsonString();
expect(JSON.parse(contents)).toEqual({
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
expect(JSON.parse(contents!)).toEqual({
$schema: 'https://docs.renovatebot.com/renovate-schema.json',
});
});
Expand Down Expand Up @@ -110,9 +111,10 @@ describe('workers/repository/onboarding/branch/index', () => {
configFileNames[0]
);
const file = git.commitFiles.mock.calls[0][0].files[0] as FileAddition;
const contents = file.contents.toString();
const contents = file.contents?.toString();
expect(contents).toBeJsonString();
expect(JSON.parse(contents)).toEqual({
// eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
expect(JSON.parse(contents!)).toEqual({
$schema: 'https://docs.renovatebot.com/renovate-schema.json',
extends: ['some/renovate-config'],
});
Expand Down
2 changes: 1 addition & 1 deletion lib/workers/repository/onboarding/pr/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ describe('workers/repository/onboarding/pr/index', () => {
});

it('deletes branch when PR already exists but cannot find it', async () => {
err.response.body = {
response.body = {
errors: [{ message: 'A pull request already exists' }],
};
platform.createPr.mockRejectedValueOnce(err);
Expand Down
2 changes: 1 addition & 1 deletion lib/workers/repository/process/fetch.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ describe('workers/repository/process/fetch', () => {
{ depName: 'abcd' },
{ currentValue: '2.8.11', datasource: 'docker' },
{ depName: ' ' },
{ depName: null },
{},
{ depName: undefined },
{ depName: { oh: 'no' } as unknown as string },
],
Expand Down
2 changes: 1 addition & 1 deletion lib/workers/repository/process/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ async function fetchDepUpdates(
...(await lookupUpdates(depConfig as LookupUpdateConfig)),
};
}
dep.updates = dep.updates || [];
dep.updates = dep.updates ?? [];
}
return dep;
}
Expand Down
3 changes: 2 additions & 1 deletion lib/workers/repository/process/limits.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,8 @@ describe('workers/repository/process/limits', () => {

it('returns prConcurrentLimit if errored', () => {
config.branchConcurrentLimit = 2;
const res = limits.getConcurrentBranchesRemaining(config, null);
// TODO: #7154
const res = limits.getConcurrentBranchesRemaining(config, null as never);
expect(res).toBe(2);
});
});
Expand Down
1 change: 1 addition & 0 deletions lib/workers/repository/process/limits.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ export function getConcurrentBranchesRemaining(

return concurrentRemaining;
} catch (err) {
// TODO: #7154 should never throw
logger.error({ err }, 'Error checking concurrent branches');
return limit;
}
Expand Down
4 changes: 3 additions & 1 deletion lib/workers/repository/process/vulnerabilities.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ jest.mock('@jamiemagee/osv-offline', () => {
return {
__esModule: true,
OsvOffline: class {
static create = () => createMock();
static create() {
return createMock();
}
},
};
});
Expand Down

0 comments on commit 03b0d2a

Please sign in to comment.