Merge pull request #2896 from balena-io/unnecessary-promise-resolve-reject

Remove unnecessary `Promise.resolve` and `Promise.reject`
This commit is contained in:
Page- 2024-12-17 11:34:05 +00:00 committed by GitHub
commit 5d687f5a55
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
12 changed files with 75 additions and 87 deletions

View File

@ -101,11 +101,9 @@ async function init() {
/** Execute the oclif parser and the CLI command. */ /** Execute the oclif parser and the CLI command. */
async function oclifRun(command: string[], options: AppOptions) { async function oclifRun(command: string[], options: AppOptions) {
let deprecationPromise: Promise<void>; let deprecationPromise: Promise<void> | undefined;
// check and enforce the CLI's deprecation policy // check and enforce the CLI's deprecation policy
if (unsupportedFlag || process.env.BALENARC_UNSUPPORTED) { if (!(unsupportedFlag || process.env.BALENARC_UNSUPPORTED)) {
deprecationPromise = Promise.resolve();
} else {
const { DeprecationChecker } = await import('./deprecation'); const { DeprecationChecker } = await import('./deprecation');
const deprecationChecker = new DeprecationChecker(packageJSON.version); const deprecationChecker = new DeprecationChecker(packageJSON.version);
// warnAndAbortIfDeprecated uses previously cached data only // warnAndAbortIfDeprecated uses previously cached data only

View File

@ -75,13 +75,13 @@ export async function disambiguateReleaseParam(
return (await balena.models.release.get(release, { $select: 'id' })).id; return (await balena.models.release.get(release, { $select: 'id' })).id;
} }
/* eslint-disable @typescript-eslint/require-await -- oclif parse functions require a Promise return */
/** /**
* Convert to lowercase if looks like slug * Convert to lowercase if looks like slug
*/ */
export function lowercaseIfSlug(s: string) { export async function lowercaseIfSlug(s: string) {
return s.includes('/') /* eslint-enable @typescript-eslint/require-await */
? Promise.resolve(s.toLowerCase()) return s.includes('/') ? s.toLowerCase() : s;
: Promise.resolve(s);
} }
export function normalizeOsVersion(version: string) { export function normalizeOsVersion(version: string) {

View File

@ -110,7 +110,7 @@ export async function startRemoteBuild(
const [buildRequest, stream] = await getRemoteBuildStream(build); const [buildRequest, stream] = await getRemoteBuildStream(build);
// Setup CTRL-C handler so the user can interrupt the build // Setup CTRL-C handler so the user can interrupt the build
let cancellationPromise = Promise.resolve(); let cancellationPromise: Promise<void> | undefined;
const sigintHandler = () => { const sigintHandler = () => {
process.exitCode = 130; process.exitCode = 130;
console.error('\nReceived SIGINT, cleaning up. Please wait.'); console.error('\nReceived SIGINT, cleaning up. Please wait.');

View File

@ -87,7 +87,8 @@ export function looksLikeInteger(input: string) {
return /^(?:0|[1-9][0-9]*)$/.test(input); return /^(?:0|[1-9][0-9]*)$/.test(input);
} }
export function parseAsInteger(input: string, paramName?: string) { // eslint-disable-next-line @typescript-eslint/require-await -- oclif parse functions require a Promise return
export async function parseAsInteger(input: string, paramName?: string) {
if (!looksLikeInteger(input)) { if (!looksLikeInteger(input)) {
const message = const message =
paramName == null paramName == null
@ -97,7 +98,7 @@ export function parseAsInteger(input: string, paramName?: string) {
throw new ExpectedError(message); throw new ExpectedError(message);
} }
return Promise.resolve(Number(input)); return Number(input);
} }
export async function tryAsInteger(input: string): Promise<number | string> { export async function tryAsInteger(input: string): Promise<number | string> {
@ -108,13 +109,14 @@ export async function tryAsInteger(input: string): Promise<number | string> {
} }
} }
export function parseAsLocalHostnameOrIp(input: string) { // eslint-disable-next-line @typescript-eslint/require-await -- oclif parse functions require a Promise return
export async function parseAsLocalHostnameOrIp(input: string) {
if (input && !validateLocalHostnameOrIp(input)) { if (input && !validateLocalHostnameOrIp(input)) {
throw new ExpectedError( throw new ExpectedError(
'The parameter must be a local hostname or IP address.', 'The parameter must be a local hostname or IP address.',
); );
} }
return Promise.resolve(input); return input;
} }
export function looksLikeFleetSlug(input: string) { export function looksLikeFleetSlug(input: string) {

View File

@ -134,7 +134,7 @@ describe('Login server:', function () {
describe('given the token authenticates with the server', function () { describe('given the token authenticates with the server', function () {
beforeEach(function () { beforeEach(function () {
this.loginIfTokenValidStub = sinon.stub(utils, 'loginIfTokenValid'); this.loginIfTokenValidStub = sinon.stub(utils, 'loginIfTokenValid');
this.loginIfTokenValidStub.returns(Promise.resolve(true)); this.loginIfTokenValidStub.resolves(true);
}); });
afterEach(function () { afterEach(function () {
@ -153,7 +153,7 @@ describe('Login server:', function () {
describe('given the token does not authenticate with the server', function () { describe('given the token does not authenticate with the server', function () {
beforeEach(function () { beforeEach(function () {
this.loginIfTokenValidStub = sinon.stub(utils, 'loginIfTokenValid'); this.loginIfTokenValidStub = sinon.stub(utils, 'loginIfTokenValid');
return this.loginIfTokenValidStub.returns(Promise.resolve(false)); return this.loginIfTokenValidStub.resolves(false);
}); });
afterEach(function () { afterEach(function () {

View File

@ -188,7 +188,6 @@ export async function testDockerBuildStream(o: {
expect(deepJsonParse(queryParams)).to.have.deep.members( expect(deepJsonParse(queryParams)).to.have.deep.members(
deepJsonParse(expectedQueryParams), deepJsonParse(expectedQueryParams),
); );
return Promise.resolve();
}, },
checkBuildRequestBody: (buildRequestBody: string) => checkBuildRequestBody: (buildRequestBody: string) =>
inspectTarStream(buildRequestBody, expectedFiles, projectPath), inspectTarStream(buildRequestBody, expectedFiles, projectPath),
@ -246,7 +245,6 @@ export async function testPushBuildStream(o: {
expect(deepJsonParse(queryParams)).to.have.deep.members( expect(deepJsonParse(queryParams)).to.have.deep.members(
deepJsonParse(expectedQueryParams), deepJsonParse(expectedQueryParams),
); );
return Promise.resolve();
}, },
checkBuildRequestBody: (buildRequestBody) => checkBuildRequestBody: (buildRequestBody) =>
inspectTarStream(buildRequestBody, o.expectedFiles, o.projectPath), inspectTarStream(buildRequestBody, o.expectedFiles, o.projectPath),

View File

@ -37,7 +37,7 @@ export class BuilderMock extends NockMock {
persist?: boolean; persist?: boolean;
responseBody: any; responseBody: any;
responseCode: number; responseCode: number;
checkURI: (uri: string) => Promise<void>; checkURI: (uri: string) => Promise<void> | void;
checkBuildRequestBody: (requestBody: string | Buffer) => Promise<void>; checkBuildRequestBody: (requestBody: string | Buffer) => Promise<void>;
}) { }) {
this.optPost(/^\/v3\/build($|[(?])/, opts).reply( this.optPost(/^\/v3\/build($|[(?])/, opts).reply(

View File

@ -75,7 +75,7 @@ export class DockerMock extends NockMock {
responseBody: any; responseBody: any;
responseCode: number; responseCode: number;
tag: string; tag: string;
checkURI: (uri: string) => Promise<void>; checkURI: (uri: string) => Promise<void> | void;
checkBuildRequestBody: (requestBody: string) => Promise<void>; checkBuildRequestBody: (requestBody: string) => Promise<void>;
}) { }) {
this.optPost( this.optPost(

View File

@ -75,12 +75,12 @@ describe('detectEncoding() function', function () {
for (const fname of sampleBinary) { for (const fname of sampleBinary) {
const buf = await fs.readFile(path.join('node_modules', fname)); const buf = await fs.readFile(path.join('node_modules', fname));
const encoding = await detectEncoding(buf); const encoding = detectEncoding(buf);
expect(encoding).to.equal('binary'); expect(encoding).to.equal('binary');
} }
for (const fname of sampleText) { for (const fname of sampleText) {
const buf = await fs.readFile(fname); const buf = await fs.readFile(fname);
const encoding = await detectEncoding(buf); const encoding = detectEncoding(buf);
expect(encoding).to.equal('utf-8'); expect(encoding).to.equal('utf-8');
} }
}); });

View File

@ -32,9 +32,7 @@ describe('image-manager', function () {
fs.writeSync(this.image.fd, 'Cache image', 0, 'utf8'); fs.writeSync(this.image.fd, 'Cache image', 0, 'utf8');
this.cacheGetImagePathStub = stub(imageManager, 'getImagePath'); this.cacheGetImagePathStub = stub(imageManager, 'getImagePath');
return this.cacheGetImagePathStub.returns( return this.cacheGetImagePathStub.resolves(this.image.name);
Promise.resolve(this.image.name),
);
}); });
afterEach(function () { afterEach(function () {
@ -45,7 +43,7 @@ describe('image-manager', function () {
describe('given the image is fresh', function () { describe('given the image is fresh', function () {
beforeEach(function () { beforeEach(function () {
this.cacheIsImageFresh = stub(imageManager, 'isImageFresh'); this.cacheIsImageFresh = stub(imageManager, 'isImageFresh');
return this.cacheIsImageFresh.returns(Promise.resolve(true)); return this.cacheIsImageFresh.resolves(true);
}); });
afterEach(function () { afterEach(function () {
@ -71,7 +69,7 @@ describe('image-manager', function () {
describe('given the image is not fresh', function () { describe('given the image is not fresh', function () {
beforeEach(function () { beforeEach(function () {
this.cacheIsImageFresh = stub(imageManager, 'isImageFresh'); this.cacheIsImageFresh = stub(imageManager, 'isImageFresh');
return this.cacheIsImageFresh.returns(Promise.resolve(false)); return this.cacheIsImageFresh.resolves(false);
}); });
afterEach(function () { afterEach(function () {
@ -82,9 +80,7 @@ describe('image-manager', function () {
describe.skip('given a valid download endpoint', function () { describe.skip('given a valid download endpoint', function () {
beforeEach(function () { beforeEach(function () {
this.osDownloadStub = stub(balena.models.os, 'download'); this.osDownloadStub = stub(balena.models.os, 'download');
this.osDownloadStub.returns( this.osDownloadStub.resolves(stringToStream('Download image'));
Promise.resolve(stringToStream('Download image')),
);
}); });
afterEach(function () { afterEach(function () {
@ -131,7 +127,7 @@ describe('image-manager', function () {
beforeEach(function () { beforeEach(function () {
this.osDownloadStream = new stream.PassThrough(); this.osDownloadStream = new stream.PassThrough();
this.osDownloadStub = stub(balena.models.os, 'download'); this.osDownloadStub = stub(balena.models.os, 'download');
this.osDownloadStub.returns(Promise.resolve(this.osDownloadStream)); this.osDownloadStub.resolves(this.osDownloadStream);
}); });
afterEach(function () { afterEach(function () {
@ -182,7 +178,7 @@ describe('image-manager', function () {
mime?: string; mime?: string;
}; };
mockResultStream.mime = 'application/zip'; mockResultStream.mime = 'application/zip';
this.osDownloadStub.returns(Promise.resolve(mockResultStream)); this.osDownloadStub.resolves(mockResultStream);
}); });
afterEach(function () { afterEach(function () {
@ -207,12 +203,10 @@ describe('image-manager', function () {
this.balenaSettingsGetStub this.balenaSettingsGetStub
.withArgs('cacheDirectory') .withArgs('cacheDirectory')
.returns( .resolves(
Promise.resolve( os.platform() === 'win32'
os.platform() === 'win32' ? 'C:\\Users\\johndoe\\_balena\\cache'
? 'C:\\Users\\johndoe\\_balena\\cache' : '/Users/johndoe/.balena/cache',
: '/Users/johndoe/.balena/cache',
),
); );
}); });
@ -226,21 +220,21 @@ describe('image-manager', function () {
balena.models.config, balena.models.config,
'getDeviceTypeManifestBySlug', 'getDeviceTypeManifestBySlug',
); );
this.getDeviceTypeManifestBySlugStub.withArgs('raspberry-pi').returns( this.getDeviceTypeManifestBySlugStub
Promise.resolve({ .withArgs('raspberry-pi')
.resolves({
yocto: { yocto: {
fstype: 'resin-sdcard', fstype: 'resin-sdcard',
}, },
}), });
);
this.getDeviceTypeManifestBySlugStub.withArgs('intel-edison').returns( this.getDeviceTypeManifestBySlugStub
Promise.resolve({ .withArgs('intel-edison')
.resolves({
yocto: { yocto: {
fstype: 'zip', fstype: 'zip',
}, },
}), });
);
}); });
afterEach(function () { afterEach(function () {
@ -293,13 +287,11 @@ describe('image-manager', function () {
balena.models.config, balena.models.config,
'getDeviceTypeManifestBySlug', 'getDeviceTypeManifestBySlug',
); );
this.getDeviceTypeManifestBySlugStub.returns( this.getDeviceTypeManifestBySlugStub.resolves({
Promise.resolve({ yocto: {
yocto: { fstype: 'balena-sdcard',
fstype: 'balena-sdcard', },
}, });
}),
);
}); });
afterEach(function () { afterEach(function () {
@ -312,8 +304,8 @@ describe('image-manager', function () {
imageManager, imageManager,
'getFileCreatedDate', 'getFileCreatedDate',
); );
this.utilsGetFileCreatedDate.returns( this.utilsGetFileCreatedDate.rejects(
Promise.reject(new Error("ENOENT, stat 'raspberry-pi'")), new Error("ENOENT, stat 'raspberry-pi'"),
); );
}); });
@ -333,8 +325,8 @@ describe('image-manager', function () {
imageManager, imageManager,
'getFileCreatedDate', 'getFileCreatedDate',
); );
this.utilsGetFileCreatedDate.returns( this.utilsGetFileCreatedDate.resolves(
Promise.resolve(new Date('2014-01-01T00:00:00.000Z')), new Date('2014-01-01T00:00:00.000Z'),
); );
}); });
@ -345,8 +337,8 @@ describe('image-manager', function () {
describe('given the file was created before the os last modified time', function () { describe('given the file was created before the os last modified time', function () {
beforeEach(function () { beforeEach(function () {
this.osGetLastModified = stub(balena.models.os, 'getLastModified'); this.osGetLastModified = stub(balena.models.os, 'getLastModified');
this.osGetLastModified.returns( this.osGetLastModified.resolves(
Promise.resolve(new Date('2014-02-01T00:00:00.000Z')), new Date('2014-02-01T00:00:00.000Z'),
); );
}); });
@ -363,8 +355,8 @@ describe('image-manager', function () {
describe('given the file was created after the os last modified time', function () { describe('given the file was created after the os last modified time', function () {
beforeEach(function () { beforeEach(function () {
this.osGetLastModified = stub(balena.models.os, 'getLastModified'); this.osGetLastModified = stub(balena.models.os, 'getLastModified');
this.osGetLastModified.returns( this.osGetLastModified.resolves(
Promise.resolve(new Date('2013-01-01T00:00:00.000Z')), new Date('2013-01-01T00:00:00.000Z'),
); );
}); });
@ -381,8 +373,8 @@ describe('image-manager', function () {
describe('given the file was created just at the os last modified time', function () { describe('given the file was created just at the os last modified time', function () {
beforeEach(function () { beforeEach(function () {
this.osGetLastModified = stub(balena.models.os, 'getLastModified'); this.osGetLastModified = stub(balena.models.os, 'getLastModified');
this.osGetLastModified.returns( this.osGetLastModified.resolves(
Promise.resolve(new Date('2014-00-01T00:00:00.000Z')), new Date('2014-00-01T00:00:00.000Z'),
); );
}); });
@ -406,7 +398,7 @@ describe('image-manager', function () {
fs.writeSync(this.image.fd, 'Lorem ipsum dolor sit amet', 0, 'utf8'); fs.writeSync(this.image.fd, 'Lorem ipsum dolor sit amet', 0, 'utf8');
this.cacheGetImagePathStub = stub(imageManager, 'getImagePath'); this.cacheGetImagePathStub = stub(imageManager, 'getImagePath');
this.cacheGetImagePathStub.returns(Promise.resolve(this.image.name)); this.cacheGetImagePathStub.resolves(this.image.name);
}); });
afterEach(function (done) { afterEach(function (done) {
@ -443,7 +435,7 @@ describe('image-manager', function () {
beforeEach(function () { beforeEach(function () {
this.image = tmp.fileSync(); this.image = tmp.fileSync();
this.cacheGetImagePathStub = stub(imageManager, 'getImagePath'); this.cacheGetImagePathStub = stub(imageManager, 'getImagePath');
this.cacheGetImagePathStub.returns(Promise.resolve(this.image.name)); this.cacheGetImagePathStub.resolves(this.image.name);
}); });
afterEach(function (done) { afterEach(function (done) {
@ -486,9 +478,7 @@ describe('image-manager', function () {
beforeEach(function () { beforeEach(function () {
this.date = new Date(2014, 1, 1); this.date = new Date(2014, 1, 1);
this.fsStatStub = stub(fs.promises, 'stat'); this.fsStatStub = stub(fs.promises, 'stat');
this.fsStatStub this.fsStatStub.withArgs('foo').resolves({ ctime: this.date });
.withArgs('foo')
.returns(Promise.resolve({ ctime: this.date }));
}); });
afterEach(function () { afterEach(function () {
@ -506,7 +496,7 @@ describe('image-manager', function () {
this.fsStatStub = stub(fs.promises, 'stat'); this.fsStatStub = stub(fs.promises, 'stat');
this.fsStatStub this.fsStatStub
.withArgs('foo') .withArgs('foo')
.returns(Promise.reject(new Error("ENOENT, stat 'foo'"))); .rejects(new Error("ENOENT, stat 'foo'"));
}); });
afterEach(function () { afterEach(function () {

View File

@ -117,7 +117,7 @@ describe('disambiguateReleaseParam() function', () => {
it('should return id from SDK on first call, if match is found', async () => { it('should return id from SDK on first call, if match is found', async () => {
const input = '1234'; const input = '1234';
const output = 1234; const output = 1234;
const getRelease = sinon.stub().returns(Promise.resolve({ id: output })); const getRelease = sinon.stub().resolves({ id: output });
const sdk: any = { const sdk: any = {
models: { models: {
release: { release: {
@ -139,9 +139,9 @@ describe('disambiguateReleaseParam() function', () => {
const getRelease = sinon const getRelease = sinon
.stub() .stub()
.onCall(0) .onCall(0)
.returns(Promise.reject(new BalenaReleaseNotFound(input))) .rejects(new BalenaReleaseNotFound(input))
.onCall(1) .onCall(1)
.returns(Promise.resolve({ id: output })); .resolves({ id: output });
const sdk: any = { const sdk: any = {
models: { models: {
@ -161,9 +161,7 @@ describe('disambiguateReleaseParam() function', () => {
it('should throw error if no match found', async () => { it('should throw error if no match found', async () => {
const input = '1234'; const input = '1234';
const getRelease = sinon const getRelease = sinon.stub().rejects(new BalenaReleaseNotFound(input));
.stub()
.returns(Promise.reject(new BalenaReleaseNotFound(input)));
const sdk: any = { const sdk: any = {
models: { models: {
@ -185,9 +183,7 @@ describe('disambiguateReleaseParam() function', () => {
it('should throw error if unknown error returned from SDK', async () => { it('should throw error if unknown error returned from SDK', async () => {
const input = '1234'; const input = '1234';
const getRelease = sinon const getRelease = sinon.stub().rejects(new Error('some error'));
.stub()
.returns(Promise.reject(new Error('some error')));
const sdk: any = { const sdk: any = {
models: { models: {

View File

@ -15,10 +15,14 @@
* limitations under the License. * limitations under the License.
*/ */
import { expect } from 'chai'; import * as chaiAsPromised from 'chai-as-promised';
import * as chai from 'chai';
import { ExpectedError } from '../../build/errors'; import { ExpectedError } from '../../build/errors';
import * as v from '../../build/utils/validation'; import * as v from '../../build/utils/validation';
chai.use(chaiAsPromised);
const { expect } = chai;
describe('validateEmail() function', () => { describe('validateEmail() function', () => {
it('should reject invalid email addresses with a message', () => { it('should reject invalid email addresses with a message', () => {
const errorMessage = 'Email is not valid'; const errorMessage = 'Email is not valid';
@ -186,26 +190,26 @@ describe('validateUuid() function', () => {
describe('parseAsInteger() function', () => { describe('parseAsInteger() function', () => {
it('should reject non-numeric characters', () => { it('should reject non-numeric characters', () => {
expect(() => v.parseAsInteger('abc')).to.throw(ExpectedError); expect(v.parseAsInteger('abc')).to.be.rejectedWith(ExpectedError);
expect(() => v.parseAsInteger('1a')).to.throw(ExpectedError); expect(v.parseAsInteger('1a')).to.be.rejectedWith(ExpectedError);
expect(() => v.parseAsInteger('a1')).to.throw(ExpectedError); expect(v.parseAsInteger('a1')).to.be.rejectedWith(ExpectedError);
expect(() => v.parseAsInteger('a')).to.throw(ExpectedError); expect(v.parseAsInteger('a')).to.be.rejectedWith(ExpectedError);
expect(() => v.parseAsInteger('1.0')).to.throw(ExpectedError); expect(v.parseAsInteger('1.0')).to.be.rejectedWith(ExpectedError);
}); });
it('should reject leading zeros', () => { it('should reject leading zeros', () => {
expect(() => v.parseAsInteger('01')).to.throw(ExpectedError); expect(v.parseAsInteger('01')).to.be.rejectedWith(ExpectedError);
expect(() => v.parseAsInteger('001')).to.throw(ExpectedError); expect(v.parseAsInteger('001')).to.be.rejectedWith(ExpectedError);
}); });
it('should throw with specific message when param name passed', () => { it('should throw with specific message when param name passed', () => {
expect(() => v.parseAsInteger('abc')).to.throw( expect(v.parseAsInteger('abc')).to.be.rejectedWith(
'The parameter must be an integer.', 'The parameter must be an integer.',
); );
}); });
it('should throw with general message when no param name passed', () => { it('should throw with general message when no param name passed', () => {
expect(() => v.parseAsInteger('abc', 'foo')).to.throw( expect(v.parseAsInteger('abc', 'foo')).to.be.rejectedWith(
"The parameter 'foo' must be an integer.", "The parameter 'foo' must be an integer.",
); );
}); });