|
| 1 | +import { describe, expect, test } from "bun:test" |
| 2 | +import { createHighlightCache } from "../../src/util/highlight-cache" |
| 3 | + |
| 4 | +function worker() { |
| 5 | + const calls: string[] = [] |
| 6 | + const highlightOnce = (content: string, filetype: string) => { |
| 7 | + calls.push(`${filetype}:${content}`) |
| 8 | + if (content === "fail") return Promise.reject(new Error("worker failed")) |
| 9 | + return Promise.resolve({ highlights: [[0, content.length, "string"] as [number, number, string]] }) |
| 10 | + } |
| 11 | + return { calls, highlightOnce } |
| 12 | +} |
| 13 | + |
| 14 | +describe("createHighlightCache", () => { |
| 15 | + test("answers the same text and language from the first result", async () => { |
| 16 | + const fake = worker() |
| 17 | + const highlight = createHighlightCache(fake.highlightOnce) |
| 18 | + const first = highlight("echo hi", "bash") |
| 19 | + const second = highlight("echo hi", "bash") |
| 20 | + expect(second).toBe(first) |
| 21 | + expect(await second).toEqual({ highlights: [[0, 7, "string"]] }) |
| 22 | + expect(fake.calls).toEqual(["bash:echo hi"]) |
| 23 | + }) |
| 24 | + |
| 25 | + test("keys by language as well as content", async () => { |
| 26 | + const fake = worker() |
| 27 | + const highlight = createHighlightCache(fake.highlightOnce) |
| 28 | + await highlight("x = 1", "bash") |
| 29 | + await highlight("x = 1", "python") |
| 30 | + expect(fake.calls).toEqual(["bash:x = 1", "python:x = 1"]) |
| 31 | + }) |
| 32 | + |
| 33 | + test("drops the least recently used entry past the entry limit", async () => { |
| 34 | + const fake = worker() |
| 35 | + const highlight = createHighlightCache(fake.highlightOnce, { entries: 2, chars: 1000 }) |
| 36 | + await highlight("a", "bash") |
| 37 | + await highlight("b", "bash") |
| 38 | + await highlight("a", "bash") |
| 39 | + await highlight("c", "bash") |
| 40 | + await highlight("a", "bash") |
| 41 | + await highlight("b", "bash") |
| 42 | + expect(fake.calls).toEqual(["bash:a", "bash:b", "bash:c", "bash:b"]) |
| 43 | + }) |
| 44 | + |
| 45 | + test("drops entries past the character budget", async () => { |
| 46 | + const fake = worker() |
| 47 | + const highlight = createHighlightCache(fake.highlightOnce, { entries: 100, chars: 5 }) |
| 48 | + await highlight("aaa", "bash") |
| 49 | + await highlight("bbb", "bash") |
| 50 | + await highlight("aaa", "bash") |
| 51 | + expect(fake.calls).toEqual(["bash:aaa", "bash:bbb", "bash:aaa"]) |
| 52 | + }) |
| 53 | + |
| 54 | + test("asks the worker again after a failed request", async () => { |
| 55 | + const fake = worker() |
| 56 | + const highlight = createHighlightCache(fake.highlightOnce) |
| 57 | + await expect(highlight("fail", "bash")).rejects.toThrow("worker failed") |
| 58 | + await expect(highlight("fail", "bash")).rejects.toThrow("worker failed") |
| 59 | + expect(fake.calls).toEqual(["bash:fail", "bash:fail"]) |
| 60 | + }) |
| 61 | +}) |
0 commit comments