RotNot / src /lib /sources /__tests__ /openstax.test.ts
deploy
Deploy RotNot
9580dce
Raw History Blame Contribute Delete
14.2 kB
import { describe, it, expect, vi, beforeEach } from "vitest";
import {
searchOpenStaxBooks,
fetchOpenStaxPageContent,
fetchOpenStaxSources,
extractSearchTerms,
generatePageSlugs,
} from "../openstax";
// Mock global fetch
const mockFetch = vi.fn();
vi.stubGlobal("fetch", mockFetch);
beforeEach(() => {
vi.clearAllMocks();
});
// --- Test data ---
const mockBookSearchResponse = {
meta: { total_count: 3 },
items: [
{
id: 603,
meta: {
slug: "college-physics-2e",
type: "books.Book",
detail_url: "https://openstax.org/apps/cms/api/v2/pages/603/",
html_url: "https://openstax.org/details/books/college-physics-2e",
first_published_at: "2022-06-24T11:12:49.206000-05:00",
locale: "en",
},
title: "College Physics 2e",
},
{
id: 415,
meta: {
slug: "physics",
type: "books.Book",
detail_url: "https://openstax.org/apps/cms/api/v2/pages/415/",
html_url: "https://openstax.org/details/books/physics",
first_published_at: "2020-03-26T17:09:27.082000-05:00",
locale: "en",
},
title: "Physics",
},
],
};
const mockPageHtml = `
<!DOCTYPE html>
<html>
<head><title>1.1 Newton's Laws of Motion - College Physics 2e | OpenStax</title></head>
<body>
<nav>Skip to content</nav>
<header>Header content</header>
<div class="main-content">
<h1>Newton's Laws of Motion</h1>
<p>Newton's first law states that a body at rest remains at rest, or, if in motion,
remains in motion at a constant velocity unless acted on by a net external force.
This is also known as the law of inertia.</p>
<p>Newton's second law of motion is closely related to the first law. It states that
the acceleration of an object depends directly upon the net force acting upon the object,
and inversely upon the mass of the object. As the force acting upon an object is increased,
the acceleration of the object is increased. As the mass of an object is increased,
the acceleration of the object is decreased.</p>
<p>Newton's third law states that for every action there is an equal and opposite reaction.
In other words, if object A exerts a force on object B, then object B also exerts an equal
and opposite force on object A.</p>
<div class="teacher-support">Teacher Support: This section covers Newton's laws.</div>
</div>
<footer>Citation/Attribution This book may not be used in the training of large language models.</footer>
</body>
</html>`;
const mockEmptyPageHtml = `
<!DOCTYPE html>
<html>
<head><title>Empty Page | OpenStax</title></head>
<body><div>Short.</div></body>
</html>`;
// --- searchOpenStaxBooks ---
describe("searchOpenStaxBooks", () => {
it("returns parsed book search results", async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => mockBookSearchResponse,
});
const results = await searchOpenStaxBooks("physics");
expect(results).toHaveLength(2);
expect(results[0]).toEqual({
id: 603,
title: "College Physics 2e",
slug: "college-physics-2e",
url: "https://openstax.org/details/books/college-physics-2e",
});
});
it("returns empty array when no results", async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({ meta: { total_count: 0 }, items: [] }),
});
const results = await searchOpenStaxBooks("xyznonexistent");
expect(results).toEqual([]);
});
it("throws on non-OK response", async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
status: 500,
statusText: "Internal Server Error",
});
await expect(searchOpenStaxBooks("physics")).rejects.toThrow("OpenStax book search failed");
});
it("passes correct query params to CMS API", async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({ meta: { total_count: 0 }, items: [] }),
});
await searchOpenStaxBooks("quantum mechanics", 5);
const calledUrl = mockFetch.mock.calls[0][0] as string;
expect(calledUrl).toContain("type=books.Book");
expect(calledUrl).toContain("search=quantum+mechanics");
expect(calledUrl).toContain("limit=5");
expect(calledUrl).toContain("format=json");
});
it("uses User-Agent header", async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({ meta: { total_count: 0 }, items: [] }),
});
await searchOpenStaxBooks("test");
const options = mockFetch.mock.calls[0][1] as { headers: Record<string, string> };
expect(options.headers["User-Agent"]).toContain("RotNot");
});
it("generates fallback URL when html_url is missing", async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({
meta: { total_count: 1 },
items: [
{
id: 1,
title: "Test Book",
meta: { slug: "test-book", html_url: null, type: "books.Book", detail_url: "", first_published_at: "", locale: "en" },
},
],
}),
});
const results = await searchOpenStaxBooks("test");
expect(results[0].url).toBe("https://openstax.org/details/books/test-book");
});
});
// --- fetchOpenStaxPageContent ---
describe("fetchOpenStaxPageContent", () => {
it("extracts title and content from a valid page", async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => mockPageHtml,
});
const result = await fetchOpenStaxPageContent("college-physics-2e", "1-1-newtons-laws-of-motion");
expect(result).not.toBeNull();
expect(result!.title).toBe("1.1 Newton's Laws of Motion");
expect(result!.url).toBe("https://openstax.org/books/college-physics-2e/pages/1-1-newtons-laws-of-motion");
expect(result!.content).toContain("Newton's first law states");
expect(result!.content).toContain("law of inertia");
expect(result!.content).toContain("third law states");
});
it("strips LLM training restriction notice", async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => mockPageHtml,
});
const result = await fetchOpenStaxPageContent("college-physics-2e", "1-1-newtons-laws");
expect(result!.content).not.toContain("training of large language models");
});
it("strips Citation/Attribution section", async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => mockPageHtml,
});
const result = await fetchOpenStaxPageContent("college-physics-2e", "test");
expect(result!.content).not.toContain("Citation/Attribution");
});
it("returns null for non-OK responses", async () => {
mockFetch.mockResolvedValueOnce({
ok: false,
status: 404,
statusText: "Not Found",
});
const result = await fetchOpenStaxPageContent("nonexistent-book", "nonexistent-page");
expect(result).toBeNull();
});
it("returns null for pages with too little content", async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => mockEmptyPageHtml,
});
const result = await fetchOpenStaxPageContent("test-book", "empty-page");
expect(result).toBeNull();
});
it("truncates content exceeding maxChars", async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => mockPageHtml,
});
const result = await fetchOpenStaxPageContent("college-physics-2e", "test", 200);
expect(result).not.toBeNull();
expect(result!.content.length).toBeLessThanOrEqual(201); // 200 + "…"
expect(result!.content).toMatch(/…$/);
});
it("constructs correct URL from book and page slugs", async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => mockPageHtml,
});
await fetchOpenStaxPageContent("biology-2e", "3-1-dna-replication");
const calledUrl = mockFetch.mock.calls[0][0] as string;
expect(calledUrl).toBe("https://openstax.org/books/biology-2e/pages/3-1-dna-replication");
});
it("strips nav, header, and footer elements", async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => mockPageHtml,
});
const result = await fetchOpenStaxPageContent("test", "test");
expect(result!.content).not.toContain("Skip to content");
expect(result!.content).not.toContain("Header content");
});
});
// --- extractSearchTerms ---
describe("extractSearchTerms", () => {
it("removes stop words and returns key terms", () => {
expect(extractSearchTerms("How a hash table works")).toBe("hash table");
});
it("handles possessives and special characters", () => {
expect(extractSearchTerms("Newton's three laws of motion")).toBe("newton's laws motion");
});
it("limits to 4 terms", () => {
const result = extractSearchTerms("The economic factors behind the fall of the Roman Empire and its consequences");
const terms = result.split(" ");
expect(terms.length).toBeLessThanOrEqual(4);
});
it("filters single-character words", () => {
expect(extractSearchTerms("What is a B-tree")).toBe("b-tree");
});
it("handles empty input", () => {
expect(extractSearchTerms("")).toBe("");
});
it("handles all stop words", () => {
expect(extractSearchTerms("how the a an")).toBe("");
});
});
// --- generatePageSlugs ---
describe("generatePageSlugs", () => {
it("generates slug from full topic name", () => {
const slugs = generatePageSlugs("Newton's three laws of motion");
expect(slugs).toContain("newtons-three-laws-of-motion");
});
it("generates key-term slug variant", () => {
const slugs = generatePageSlugs("How a hash table works");
expect(slugs).toContain("hash-table");
});
it("generates shorter word-prefix variants", () => {
const slugs = generatePageSlugs("How public-key cryptography works");
// Should include shorter variants from the first few significant words
expect(slugs.some((s) => s.split("-").length <= 3)).toBe(true);
});
it("deduplicates slugs", () => {
const slugs = generatePageSlugs("Hash table");
const unique = new Set(slugs);
expect(slugs.length).toBe(unique.size);
});
it("strips special characters", () => {
const slugs = generatePageSlugs("Euler's identity & why it connects five constants");
for (const slug of slugs) {
expect(slug).not.toMatch(/[&']/);
}
});
});
// --- fetchOpenStaxSources ---
describe("fetchOpenStaxSources", () => {
it("returns sections from domain-mapped books on successful page fetch", async () => {
// First call: CMS search (search terms from topic)
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({ meta: { total_count: 0 }, items: [] }),
});
// Second call: page content fetch for first domain book + first slug
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => mockPageHtml,
});
const results = await fetchOpenStaxSources("Newton's three laws of motion", "Physics", 1);
expect(results).toHaveLength(1);
expect(results[0].bookSlug).toBe("college-physics-2e");
expect(results[0].excerpt).toContain("Newton");
expect(results[0].url).toContain("openstax.org/books/college-physics-2e/pages/");
});
it("returns empty array when no domain books and no search results", async () => {
// CMS search returns nothing
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({ meta: { total_count: 0 }, items: [] }),
});
const results = await fetchOpenStaxSources("Some unknown topic", "UnknownDomain");
expect(results).toEqual([]);
});
it("falls back to CMS search when domain has no mapped books", async () => {
// CMS search
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => mockBookSearchResponse,
});
// Page fetch for first search result book + first slug
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => mockPageHtml,
});
const results = await fetchOpenStaxSources("Newton's laws", undefined, 1);
expect(results.length).toBeGreaterThanOrEqual(0);
});
it("handles CMS search failures gracefully", async () => {
// CMS search fails
mockFetch.mockResolvedValueOnce({
ok: false,
status: 500,
statusText: "Error",
});
// Still tries domain-mapped books; page fetch works
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => mockPageHtml,
});
const results = await fetchOpenStaxSources("Newton's laws", "Physics", 1);
// Should still work since domain books are available
expect(results.length).toBeGreaterThanOrEqual(0);
});
it("skips books where page content is too short", async () => {
// CMS search
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({ meta: { total_count: 0 }, items: [] }),
});
// First book, first slug → empty page
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => mockEmptyPageHtml,
});
// First book, second slug → empty page
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => mockEmptyPageHtml,
});
// First book, third slug → empty page
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => mockEmptyPageHtml,
});
// Second book, first slug → good page
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => mockPageHtml,
});
const results = await fetchOpenStaxSources("Newton's laws", "Physics", 1);
expect(results.length).toBeLessThanOrEqual(1);
});
it("respects maxResults limit", async () => {
// CMS search
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({ meta: { total_count: 0 }, items: [] }),
});
// Page fetches — 2 books succeed
mockFetch.mockResolvedValueOnce({
ok: true,
text: async () => mockPageHtml,
});
const results = await fetchOpenStaxSources("Newton's laws", "Physics", 1);
expect(results.length).toBeLessThanOrEqual(1);
});
});