Skip to content

Commit

Permalink
async tests [nfc]: Put BackoffMachine tests where they belong.
Browse files Browse the repository at this point in the history
Follow and delete a code comment at the top of
`backoffMachine-test`, suggesting that we move these tests.
  • Loading branch information
chrisbobbe committed Feb 8, 2021
1 parent 5b7e2f5 commit f13fee9
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 55 deletions.
50 changes: 49 additions & 1 deletion src/utils/__tests__/async-test.js
@@ -1,7 +1,55 @@
/* @flow strict-local */
import { sleep } from '../async';
import { sleep, BackoffMachine } from '../async';
import { assertUsingModernFakeTimers } from '../../__tests__/lib/fakeTimers';

describe('BackoffMachine', () => {
beforeAll(() => {
assertUsingModernFakeTimers();
});

afterEach(() => {
expect(jest.getTimerCount()).toBe(0);
jest.clearAllTimers();
});

const measureWait = async (promise: Promise<void>) => {
const start = Date.now();
jest.runOnlyPendingTimers();
await promise;
return Date.now() - start;
};

test('timeouts are random from zero to 100ms, 200ms, 400ms, 800ms...', async () => {
// This is a randomized test. NUM_TRIALS is chosen so that the failure
// probability < 1e-9. There are 2 * 11 assertions, and each one has a
// failure probability < 1e-12; see below.
const NUM_TRIALS = 100;
const expectedMaxDurations = [100, 200, 400, 800, 1600, 3200, 6400, 10000, 10000, 10000, 10000];

const trialResults: Array<number[]> = [];

for (let i = 0; i < NUM_TRIALS; i++) {
const resultsForThisTrial = [];
const backoffMachine = new BackoffMachine();
for (let j = 0; j < expectedMaxDurations.length; j++) {
const duration = await measureWait(backoffMachine.wait());
resultsForThisTrial.push(duration);
}
trialResults.push(resultsForThisTrial);
}

expectedMaxDurations.forEach((expectedMax, i) => {
const maxFromAllTrials = Math.max(...trialResults.map(r => r[i]));
const minFromAllTrials = Math.min(...trialResults.map(r => r[i]));

// Each of these assertions has a failure probability of:
// 0.75 ** NUM_TRIALS = 0.75 ** 100 < 1e-12
expect(minFromAllTrials).toBeLessThan(expectedMax * 0.25);
expect(maxFromAllTrials).toBeGreaterThan(expectedMax * 0.75);
});
});
});

const sleepMeasure = async (expectedMs: number) => {
const start = Date.now();
await sleep(expectedMs);
Expand Down
54 changes: 0 additions & 54 deletions src/utils/__tests__/backoffMachine-test.js

This file was deleted.

0 comments on commit f13fee9

Please sign in to comment.