From 410eba29f820364c8389b09ad587068c7d858afa Mon Sep 17 00:00:00 2001 From: Matt Carvin <90224411+mcarvin8@users.noreply.github.com> Date: Tue, 21 Jan 2025 12:58:12 -0500 Subject: [PATCH] test: add coverage for concurrency exports --- src/service/withConcurrencyLimit.ts | 8 ++++++-- test/main.spec.ts | 32 +++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/src/service/withConcurrencyLimit.ts b/src/service/withConcurrencyLimit.ts index 53a5ab7..5e4f5f7 100644 --- a/src/service/withConcurrencyLimit.ts +++ b/src/service/withConcurrencyLimit.ts @@ -2,8 +2,12 @@ export async function withConcurrencyLimit( tasks: (() => Promise)[], limit: number, ): Promise { + if (limit <= 0) { + throw new Error("Concurrency limit must be greater than 0"); + } + const results: Promise[] = []; - const executing: Promise[] = []; // Change this to Promise[] + const executing: Promise[] = []; for (const task of tasks) { const p = task().then((result) => { @@ -14,7 +18,7 @@ export async function withConcurrencyLimit( executing.push(p); if (executing.length >= limit) { - await Promise.race(executing); // Wait for the first one to complete + await Promise.race(executing); // Wait for any promise to resolve } } diff --git a/test/main.spec.ts b/test/main.spec.ts index c0f8c7a..9afc4c7 100644 --- a/test/main.spec.ts +++ b/test/main.spec.ts @@ -18,6 +18,8 @@ import { parseXML, buildXMLString, XmlElement, + getConcurrencyThreshold, + withConcurrencyLimit, } from "../src/index"; setLogLevel("debug"); @@ -290,6 +292,36 @@ describe("main function", () => { it("should compare the files created in the mock directory against the baselines to confirm no changes.", async () => { await compareDirectories(baselineDir, mockDir); }); + it("should return a valid concurrency threshold", () => { + const threshold = getConcurrencyThreshold(); + expect(typeof threshold).toBe("number"); + expect(threshold).toBeGreaterThan(0); // Assuming the threshold must be a positive number. + }); + it("should process tasks with concurrency limit", async () => { + const tasks = [ + () => new Promise((resolve) => setTimeout(() => resolve("Task 1"), 100)), + () => new Promise((resolve) => setTimeout(() => resolve("Task 2"), 50)), + () => new Promise((resolve) => setTimeout(() => resolve("Task 3"), 10)), + ]; + const results = await withConcurrencyLimit(tasks, 2); + + expect(results).toEqual(["Task 1", "Task 2", "Task 3"]); + }); + + it("should handle an empty list of tasks", async () => { + const results = await withConcurrencyLimit([], 2); + expect(results).toEqual([]); + }); + + it("should throw an error if concurrency limit is invalid", async () => { + const tasks = [ + () => Promise.resolve("Task 1"), + () => Promise.resolve("Task 2"), + ]; + await expect(withConcurrencyLimit(tasks, 0)).rejects.toThrow( + /Concurrency limit must be greater than 0/, + ); + }); }); async function compareDirectories(