Download src/lib/reading/__tests__/extract.test.ts from NAP1320/RotNot: direct link, hf CLI and curl.
- Browser
- Download file 11.7 kB
-
https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/lib/reading/__tests__/extract.test.ts
- Command line
-
hf download hf://spaces/NAP1320/RotNot/src/lib/reading/__tests__/extract.test.ts
-
curl -L -o extract.test.ts https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/lib/reading/__tests__/extract.test.ts
11.7 kB
| import { describe, it, expect, vi, beforeEach } from "vitest"; | |
| // Mock fetch globally before any imports that use it | |
| const mockFetch = vi.fn(); | |
| vi.stubGlobal("fetch", mockFetch); | |
| import { | |
| stripHtml, | |
| extractTitle, | |
| extractContent, | |
| estimateDifficulty, | |
| createFromText, | |
| fetchAndExtract, | |
| MIN_CONTENT_CHARS, | |
| MAX_CONTENT_CHARS, | |
| } from "../extract"; | |
| // --------------------------------------------------------------------------- | |
| // Helpers for fetchAndExtract tests | |
| // --------------------------------------------------------------------------- | |
| function makeResponse( | |
| opts: { | |
| ok?: boolean; | |
| status?: number; | |
| statusText?: string; | |
| contentType?: string; | |
| body?: string; | |
| } = {}, | |
| ) { | |
| const { | |
| ok = true, | |
| status = 200, | |
| statusText = "OK", | |
| contentType = "text/html; charset=utf-8", | |
| body = "", | |
| } = opts; | |
| return { | |
| ok, | |
| status, | |
| statusText, | |
| headers: { get: (key: string) => (key === "content-type" ? contentType : null) }, | |
| text: vi.fn().mockResolvedValue(body), | |
| }; | |
| } | |
| /** Build an HTML page with enough body text to pass MIN_CONTENT_CHARS */ | |
| function makeHtmlPage(opts: { | |
| title?: string; | |
| body?: string; | |
| wrap?: "article" | "main" | "body"; | |
| } = {}): string { | |
| const title = opts.title ?? "Test Article"; | |
| const bodyText = opts.body ?? "This is a test sentence. ".repeat(20); | |
| const wrap = opts.wrap ?? "article"; | |
| const inner = | |
| wrap === "article" | |
| ? `<article>${bodyText}</article>` | |
| : wrap === "main" | |
| ? `<main>${bodyText}</main>` | |
| : `<body>${bodyText}</body>`; | |
| return `<html><head><title>${title}</title></head><body>${inner}</body></html>`; | |
| } | |
| beforeEach(() => { | |
| mockFetch.mockReset(); | |
| }); | |
| describe("stripHtml", () => { | |
| it("removes basic tags", () => { | |
| expect(stripHtml("<p>Hello <b>world</b></p>")).toBe("Hello world"); | |
| }); | |
| it("removes script and style tags with content", () => { | |
| expect( | |
| stripHtml('<p>text</p><script>alert("x")</script><style>.a{}</style><p>more</p>'), | |
| ).toBe("text more"); | |
| }); | |
| it("removes nav, header, footer, aside", () => { | |
| expect( | |
| stripHtml("<nav>nav</nav><main>content</main><footer>foot</footer>"), | |
| ).toBe("content"); | |
| }); | |
| it("decodes common HTML entities", () => { | |
| expect(stripHtml("& < > " ' — – …")).toBe( | |
| '& < > " \' — – …', | |
| ); | |
| }); | |
| it("collapses whitespace", () => { | |
| expect(stripHtml(" hello world ")).toBe("hello world"); | |
| }); | |
| }); | |
| describe("extractTitle", () => { | |
| it("extracts from <title> tag", () => { | |
| expect(extractTitle("<html><head><title>My Article</title></head></html>")).toBe( | |
| "My Article", | |
| ); | |
| }); | |
| it("falls back to og:title", () => { | |
| const html = | |
| '<html><head><meta property="og:title" content="OG Title"></head></html>'; | |
| expect(extractTitle(html)).toBe("OG Title"); | |
| }); | |
| it("returns 'Untitled Article' when no title found", () => { | |
| expect(extractTitle("<html><head></head></html>")).toBe("Untitled Article"); | |
| }); | |
| it("strips HTML from title content", () => { | |
| expect(extractTitle("<title>My <b>Bold</b> Title</title>")).toBe("My Bold Title"); | |
| }); | |
| }); | |
| describe("extractContent", () => { | |
| const longText = "A ".repeat(200); // > MIN_CONTENT_CHARS | |
| it("prefers <article> tag", () => { | |
| const html = `<body><div>sidebar</div><article><p>${longText}</p></article></body>`; | |
| const result = extractContent(html); | |
| expect(result).toContain("A"); | |
| expect(result).not.toContain("sidebar"); | |
| }); | |
| it("falls back to <main> if no article", () => { | |
| const html = `<body><div>sidebar</div><main><p>${longText}</p></main></body>`; | |
| const result = extractContent(html); | |
| expect(result.length).toBeGreaterThan(MIN_CONTENT_CHARS); | |
| }); | |
| it("falls back to body if no article or main", () => { | |
| const html = `<body><p>${longText}</p></body>`; | |
| const result = extractContent(html); | |
| expect(result.length).toBeGreaterThan(0); | |
| }); | |
| it("skips short article tags", () => { | |
| const html = `<body><article>Short</article><main><p>${longText}</p></main></body>`; | |
| const result = extractContent(html); | |
| expect(result.length).toBeGreaterThan(MIN_CONTENT_CHARS); | |
| }); | |
| }); | |
| describe("estimateDifficulty", () => { | |
| it("returns beginner for simple text", () => { | |
| const simple = "The cat sat on the mat. It was a good day. The sun was out."; | |
| expect(estimateDifficulty(simple)).toBe("beginner"); | |
| }); | |
| it("returns advanced for complex text", () => { | |
| const complex = | |
| "The epistemological implications of Bayesian probabilistic reasoning fundamentally reconceptualize our understanding of inferential methodologies across interdisciplinary academic paradigms."; | |
| expect(estimateDifficulty(complex)).toBe("advanced"); | |
| }); | |
| it("returns intermediate for mixed text", () => { | |
| const medium = | |
| "Understanding economic principles requires careful analysis. Market dynamics and behavioral patterns interact in complex ways. The relationship between supply and demand forms the foundation of modern economic theory."; | |
| const result = estimateDifficulty(medium); | |
| expect(["intermediate", "advanced"]).toContain(result); | |
| }); | |
| }); | |
| describe("createFromText", () => { | |
| const validText = "A ".repeat(150); // 300 chars, > MIN_CONTENT_CHARS | |
| it("creates article from valid text", () => { | |
| const result = createFromText(validText, "Test Title"); | |
| expect(result.title).toBe("Test Title"); | |
| expect(result.body).toBe(validText.trim()); | |
| expect(result.domain).toBe("Custom"); | |
| expect(result.sourceUrl).toBe(""); | |
| expect(result.wordCount).toBeGreaterThan(0); | |
| expect(result.estimatedMinutes).toBeGreaterThanOrEqual(1); | |
| }); | |
| it("uses default title when none provided", () => { | |
| const result = createFromText(validText); | |
| expect(result.title).toBe("Custom Reading"); | |
| }); | |
| it("throws on text shorter than minimum", () => { | |
| expect(() => createFromText("Too short")).toThrow(/too short/i); | |
| }); | |
| it("truncates text exceeding maximum", () => { | |
| const longText = "Word. ".repeat(5000); // way over MAX_CONTENT_CHARS | |
| const result = createFromText(longText); | |
| expect(result.body.length).toBeLessThanOrEqual(MAX_CONTENT_CHARS + 1); | |
| }); | |
| it("trims whitespace", () => { | |
| const result = createFromText(" " + validText + " "); | |
| expect(result.body).not.toMatch(/^\s/); | |
| expect(result.body).not.toMatch(/\s$/); | |
| }); | |
| }); | |
| // --------------------------------------------------------------------------- | |
| // fetchAndExtract — fetch-layer tests | |
| // --------------------------------------------------------------------------- | |
| describe("fetchAndExtract", () => { | |
| it("returns extracted article for a valid HTML response", async () => { | |
| const html = makeHtmlPage({ title: "Great Article", wrap: "article" }); | |
| mockFetch.mockResolvedValue(makeResponse({ body: html })); | |
| const result = await fetchAndExtract("https://example.com/article"); | |
| expect(result.title).toBe("Great Article"); | |
| expect(result.domain).toBe("example.com"); | |
| expect(result.sourceUrl).toBe("https://example.com/article"); | |
| expect(result.wordCount).toBeGreaterThan(0); | |
| expect(result.estimatedMinutes).toBeGreaterThanOrEqual(1); | |
| expect(result.body.length).toBeGreaterThan(0); | |
| }); | |
| it("strips www. from domain", async () => { | |
| const html = makeHtmlPage(); | |
| mockFetch.mockResolvedValue(makeResponse({ body: html })); | |
| const result = await fetchAndExtract("https://www.example.com/page"); | |
| expect(result.domain).toBe("example.com"); | |
| }); | |
| it("throws on non-ok HTTP response", async () => { | |
| mockFetch.mockResolvedValue( | |
| makeResponse({ ok: false, status: 404, statusText: "Not Found" }), | |
| ); | |
| await expect(fetchAndExtract("https://example.com/missing")).rejects.toThrow( | |
| /404.*Not Found/i, | |
| ); | |
| }); | |
| it("throws on unsupported content type (PDF)", async () => { | |
| mockFetch.mockResolvedValue( | |
| makeResponse({ contentType: "application/pdf" }), | |
| ); | |
| await expect(fetchAndExtract("https://example.com/file.pdf")).rejects.toThrow( | |
| /unsupported content type/i, | |
| ); | |
| }); | |
| it("accepts text/plain content type", async () => { | |
| const plainText = "This is a plain text article. ".repeat(15); | |
| mockFetch.mockResolvedValue( | |
| makeResponse({ contentType: "text/plain", body: plainText }), | |
| ); | |
| // text/plain has no article/main tags — falls back to body strip | |
| const result = await fetchAndExtract("https://example.com/plain.txt"); | |
| expect(result.body.length).toBeGreaterThan(0); | |
| }); | |
| it("accepts application/xhtml content type", async () => { | |
| const html = makeHtmlPage({ title: "XHTML Page", wrap: "article" }); | |
| mockFetch.mockResolvedValue( | |
| makeResponse({ contentType: "application/xhtml+xml", body: html }), | |
| ); | |
| const result = await fetchAndExtract("https://example.com/page.xhtml"); | |
| expect(result.title).toBe("XHTML Page"); | |
| }); | |
| it("throws when extracted content is too short", async () => { | |
| const html = "<html><head><title>Short</title></head><body><p>Hi</p></body></html>"; | |
| mockFetch.mockResolvedValue(makeResponse({ body: html })); | |
| await expect(fetchAndExtract("https://example.com/short")).rejects.toThrow( | |
| /could not extract enough/i, | |
| ); | |
| }); | |
| it("truncates content exceeding MAX_CONTENT_CHARS", async () => { | |
| // Build a very long article body | |
| const longContent = "This is a complete sentence. ".repeat(1500); // ~45K chars | |
| const html = makeHtmlPage({ body: longContent, wrap: "article" }); | |
| mockFetch.mockResolvedValue(makeResponse({ body: html })); | |
| const result = await fetchAndExtract("https://example.com/long"); | |
| // Body is formatted text; underlying raw content was capped at MAX_CONTENT_CHARS | |
| // so word count won't be absurdly large | |
| expect(result.wordCount).toBeLessThan(15_000); | |
| }); | |
| it("sends correct User-Agent header", async () => { | |
| const html = makeHtmlPage(); | |
| mockFetch.mockResolvedValue(makeResponse({ body: html })); | |
| await fetchAndExtract("https://example.com/article"); | |
| const [, options] = mockFetch.mock.calls[0] as [string, RequestInit]; | |
| const headers = options.headers as Record<string, string>; | |
| expect(headers["User-Agent"]).toMatch(/RotNot/); | |
| }); | |
| it("propagates network errors", async () => { | |
| mockFetch.mockRejectedValue(new TypeError("Network error")); | |
| await expect(fetchAndExtract("https://example.com/article")).rejects.toThrow( | |
| "Network error", | |
| ); | |
| }); | |
| it("falls back to main tag when article is absent", async () => { | |
| const html = makeHtmlPage({ wrap: "main" }); | |
| mockFetch.mockResolvedValue(makeResponse({ body: html })); | |
| const result = await fetchAndExtract("https://example.com/article"); | |
| expect(result.body.length).toBeGreaterThan(0); | |
| }); | |
| it("computes estimatedMinutes from word count", async () => { | |
| // ~400 words → 2 minutes at 200 wpm | |
| const body = "word ".repeat(400); | |
| const html = makeHtmlPage({ body, wrap: "article" }); | |
| mockFetch.mockResolvedValue(makeResponse({ body: html })); | |
| const result = await fetchAndExtract("https://example.com/article"); | |
| expect(result.estimatedMinutes).toBeGreaterThanOrEqual(1); | |
| }); | |
| it("uses og:title when <title> is absent", async () => { | |
| const bodyText = "This is a test sentence. ".repeat(20); | |
| const html = `<html><head><meta property="og:title" content="OG Article Title"></head><body><article>${bodyText}</article></body></html>`; | |
| mockFetch.mockResolvedValue(makeResponse({ body: html })); | |
| const result = await fetchAndExtract("https://example.com/article"); | |
| expect(result.title).toBe("OG Article Title"); | |
| }); | |
| }); | |