1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-01-20 00:08:02 +01:00

fix: add unit test for addon-retry

This commit is contained in:
Ivar Conradi Østhus 2021-02-28 22:40:04 +01:00
parent 36bc3b9823
commit 7b2b4acbb6
No known key found for this signature in database
GPG Key ID: 31AC596886B0BD09
2 changed files with 82 additions and 27 deletions

View File

@ -28,36 +28,21 @@ class Addon {
async fetchRetry(url, options = {}, retries = 1, backoff = 300) {
const retryCodes = [408, 500, 502, 503, 504, 522, 524];
let res;
try {
const res = await fetch(url, options);
if (res.ok) {
return res;
}
if (retries > 0 && retryCodes.includes(res.status)) {
setTimeout(() => {
return this.fetchRetry(
url,
options,
retries - 1,
backoff * 2,
);
}, backoff);
}
return res;
res = await fetch(url, options);
} catch (error) {
this.logger.warn(error);
if (retries > 0) {
setTimeout(() => {
return this.fetchRetry(
url,
options,
retries - 1,
backoff * 2,
);
}, backoff);
}
return { status: 500 };
res = { status: 500, ok: false };
}
if (res.ok) {
return res;
}
if (retries > 0 && retryCodes.includes(res.status)) {
setTimeout(() => {
return this.fetchRetry(url, options, retries - 1, backoff * 2);
}, backoff);
}
return res;
}
}

View File

@ -0,0 +1,70 @@
const test = require('ava');
const proxyquire = require('proxyquire');
const lolex = require('lolex');
const fetchMock = require('fetch-mock').sandbox();
const noLogger = require('../../test/fixtures/no-logger');
const Addon = proxyquire('./addon', { 'node-fetch': fetchMock });
test.beforeEach(() => {
fetchMock.restore();
fetchMock.reset();
});
const definition = {
name: 'test',
displayName: 'test',
description: 'hello',
};
test.serial('Retries if fetch throws', async t => {
const url = 'https://test.some.com';
const clock = lolex.install();
const addon = new Addon(definition, {
getLogger: noLogger,
});
fetchMock
.once(
{
name: 'rejection',
type: 'POST',
url: `begin:${url}`,
},
() => {
throw new Error('Network error');
},
)
.mock(
{
name: 'acceptance',
type: 'POST',
url: `begin:${url}`,
},
201,
);
await addon.fetchRetry(url);
clock.tick(1000);
t.true(fetchMock.done());
});
test.serial('does not crash even if fetch throws', async t => {
const url = 'https://test.some.com';
const clock = lolex.install();
const addon = new Addon(definition, {
getLogger: noLogger,
});
fetchMock.mock(
{
name: 'rejection',
type: 'POST',
url: `begin:${url}`,
},
() => {
throw new Error('Network error');
},
);
await addon.fetchRetry(url);
clock.tick(1000);
t.true(fetchMock.done());
t.is(fetchMock.calls().length, 2);
});