Elffuss BraidHub

kikocis/continue public

3a1e5cc69df2 · 1.9 KiBRawPermalink
1import { PrecalculatedLruCache } from "./LruCache";
2
3describe("PrecalculatedLruCache", () => {
4 const N = 2;
5
6 let calculateValue: jest.MockedFunction<(key: string) => Promise<number>>;
7 let cache: PrecalculatedLruCache<number>;
8
9 beforeEach(() => {
10 calculateValue = jest.fn(async (key: string) => {
11 return parseInt(key, 10) * 2;
12 });
13
14 cache = new PrecalculatedLruCache<number>(calculateValue, N);
15 });
16
17 it("should calculate and cache values", async () => {
18 await cache.initKey("1");
19 expect(calculateValue).toHaveBeenCalledWith("1");
20 expect(cache.get("1")).toBe(2);
21 });
22
23 it("should not recalculate cached values", async () => {
24 await cache.initKey("1");
25 calculateValue.mockClear();
26
27 await cache.initKey("1");
28 expect(calculateValue).not.toHaveBeenCalled();
29 expect(cache.get("1")).toBe(2);
30 });
31
32 it("should evict least recently used items when capacity is exceeded", async () => {
33 await cache.initKey("1");
34 await cache.initKey("2");
35 await cache.initKey("3"); // Exceeds capacity, should evict "1"
36
37 expect(cache.get("1")).toBeUndefined();
38 expect(cache.get("2")).toBe(4);
39 expect(cache.get("3")).toBe(6);
40 });
41
42 it("should update LRU order when keys are accessed", async () => {
43 await cache.initKey("1");
44 await cache.initKey("2");
45
46 // Access "1" to make it most recently used
47 await cache.initKey("1");
48 await cache.initKey("3"); // Exceeds capacity, should evict "2"
49
50 expect(cache.get("1")).toBe(2);
51 expect(cache.get("2")).toBeUndefined();
52 expect(cache.get("3")).toBe(6);
53 });
54
55 it("should handle get for keys not initialized", () => {
56 expect(cache.get("not-initialized")).toBeUndefined();
57 });
58
59 it("should propagate errors from calculateValue", async () => {
60 calculateValue.mockRejectedValue(new Error("Calculation failed"));
61 await expect(cache.initKey("error")).rejects.toThrow("Calculation failed");
62 expect(cache.get("error")).toBeUndefined();
63 });
64});