From 292afac93196723af36a5bc9ea75f8e389dc5573 Mon Sep 17 00:00:00 2001 From: Jason Date: Sat, 4 Nov 2023 14:26:35 -0700 Subject: [PATCH] reorder teardown callback to after the error event, and setResults. I'm not sure why you would ever call teardown before dealing with an error that was part of the test run. Putting teardown after setResults allows a person to purge the samples to avoid memory starvation in longer test runs. --- src/task.ts | 23 +++++++++-------------- test/index.test.ts | 12 ++++++++++-- 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/src/task.ts b/src/task.ts index da9d162..ebb6e6b 100644 --- a/src/task.ts +++ b/src/task.ts @@ -113,9 +113,10 @@ export default class Task extends EventTarget { } } - await this.bench.teardown(this, 'run'); - - if (!this.result?.error) { + if (this.result?.error) { + this.dispatchEvent(createBenchEvent('error', this)); + this.bench.dispatchEvent(createBenchEvent('error', this)); + } else { samples.sort((a, b) => a - b); const period = totalTime / this.runs; @@ -165,18 +166,12 @@ export default class Task extends EventTarget { }); } - // eslint-disable-next-line no-lone-blocks - { - if (this.result?.error) { - this.dispatchEvent(createBenchEvent('error', this)); - this.bench.dispatchEvent(createBenchEvent('error', this)); - } + await this.bench.teardown(this, 'run'); - this.dispatchEvent(createBenchEvent('cycle', this)); - this.bench.dispatchEvent(createBenchEvent('cycle', this)); - // cycle and complete are equal in Task - this.dispatchEvent(createBenchEvent('complete', this)); - } + this.dispatchEvent(createBenchEvent('cycle', this)); + this.bench.dispatchEvent(createBenchEvent('cycle', this)); + // cycle and complete are equal in Task + this.dispatchEvent(createBenchEvent('complete', this)); return this; } diff --git a/test/index.test.ts b/test/index.test.ts index 5b42b26..d2fd597 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -43,11 +43,18 @@ test('runs should be equal-more than time and iterations', async () => { test('events order', async () => { const controller = new AbortController(); + const events: string[] = []; const bench = new Bench({ signal: controller.signal, warmupIterations: 0, warmupTime: 0, + teardown: (task, mode) => { + if (mode === 'run') { + events.push('teardown'); + } + }, }); + bench // eslint-disable-next-line @typescript-eslint/no-empty-function .add('foo', async () => {}) @@ -60,8 +67,6 @@ test('events order', async () => { await new Promise((resolve) => setTimeout(resolve, 1000)); }); - const events: string[] = []; - const error = bench.getTask('error')!; error.addEventListener('start', () => { @@ -136,11 +141,14 @@ test('events order', async () => { 'remove', 'warmup', 'start', + 'teardown', 'cycle', + 'teardown', 'cycle', 'error-start', 'error-error', 'error', + 'teardown', 'error-cycle', 'cycle', 'error-complete',