Skip to content

Commit

Permalink
test: add coverage for concurrency exports
Browse files Browse the repository at this point in the history
  • Loading branch information
mcarvin8 committed Jan 21, 2025
1 parent a8e53b8 commit 410eba2
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/service/withConcurrencyLimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@ export async function withConcurrencyLimit<T>(
tasks: (() => Promise<T>)[],
limit: number,
): Promise<T[]> {
if (limit <= 0) {
throw new Error("Concurrency limit must be greater than 0");
}

const results: Promise<T>[] = [];
const executing: Promise<T>[] = []; // Change this to Promise<T>[]
const executing: Promise<T>[] = [];

for (const task of tasks) {
const p = task().then((result) => {
Expand All @@ -14,7 +18,7 @@ export async function withConcurrencyLimit<T>(
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
}
}

Expand Down
32 changes: 32 additions & 0 deletions test/main.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ import {
parseXML,
buildXMLString,
XmlElement,
getConcurrencyThreshold,
withConcurrencyLimit,
} from "../src/index";

setLogLevel("debug");
Expand Down Expand Up @@ -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(
Expand Down

0 comments on commit 410eba2

Please sign in to comment.