From 153c085d92805e03e2c8a781b4d95f7e5afda874 Mon Sep 17 00:00:00 2001 From: Test Date: Mon, 9 Sep 2024 10:36:45 -0700 Subject: [PATCH] test: update DocsCrawler tests --- core/indexing/docs/DocsCrawler.skip.ts | 268 +++++++++++-------------- core/indexing/docs/DocsCrawler.ts | 46 ++--- 2 files changed, 131 insertions(+), 183 deletions(-) diff --git a/core/indexing/docs/DocsCrawler.skip.ts b/core/indexing/docs/DocsCrawler.skip.ts index 5f7bd8936..4e9f00de8 100644 --- a/core/indexing/docs/DocsCrawler.skip.ts +++ b/core/indexing/docs/DocsCrawler.skip.ts @@ -1,180 +1,138 @@ -// import { SpiedFunction } from "jest-mock"; -// import DocsCrawler, { -// ChromiumCrawler, -// ChromiumInstaller, -// type PageData, -// } from "./DocsCrawler"; -// import preIndexedDocs from "./preIndexedDocs"; -// import { jest } from "@jest/globals"; -// import FileSystemIde from "../../util/filesystem"; +import DocsCrawler, { ChromiumInstaller, type PageData } from "./DocsCrawler"; +import preIndexedDocs from "./preIndexedDocs"; +import { jest } from "@jest/globals"; +import FileSystemIde from "../../util/filesystem"; +import { testConfigHandler } from "../../test/util/fixtures"; +import os from "os"; +import { ContinueConfig } from "../.."; -// // Temporary workaround until we have better caching of Chromium -// // download between test runs -// const TIMEOUT_MS = 1_000_000_000; +// Temporary workaround until we have better caching of Chromium +// download between test runs +const TIMEOUT_MS = 1_000_000_000; -// // Skipped until we have a better way to cache Chromium installs -// // between tests and in CI -// describe.skip("crawl", () => { -// const mockIde = new FileSystemIde(process.cwd()); +// Overwrite the Chromium download path to `os.tmpdir()` +// so that we don't delete the Chromium install between tests +ChromiumInstaller.PCR_CONFIG = { downloadPath: os.tmpdir() }; -// const chromiumInstaller = new ChromiumInstaller(mockIde); -// beforeAll(async () => { -// // Make sure we have Chromium pulled down before beginning tests -// await ChromiumInstaller.install(); -// }, TIMEOUT_MS); +// Skipped until we have a better way to cache Chromium installs +// between tests and in CI +describe.skip("DocsCrawler", () => { + const NUM_PAGES_TO_CRAWL = 5; -// describe("GitHub Crawler", () => { -// const repoUrl = -// "https://github.com/Patrick-Erichsen/test-github-repo-for-crawling"; + let config: ContinueConfig; + let mockIde: FileSystemIde; + let chromiumInstaller; + let docsCrawler: DocsCrawler; -// let crawlResults: PageData[]; + beforeAll(async () => { + config = await testConfigHandler.loadConfig(); + mockIde = new FileSystemIde(process.cwd()); + chromiumInstaller = new ChromiumInstaller(mockIde, config); + docsCrawler = new DocsCrawler(mockIde, config); -// beforeAll(async () => { -// const docsCrawler = new DocsCrawler(); + // Make sure we have Chromium pulled down before beginning tests + await chromiumInstaller.install(); + }, TIMEOUT_MS); -// crawlResults = []; + function crawlTest( + urls: string[], + numPagesToCrawl: number = NUM_PAGES_TO_CRAWL, + ) { + const numUrlsToTest = 5; + const randomUrls = urls + .sort(() => 0.5 - Math.random()) + .slice(0, numUrlsToTest); -// for await (const page of docsCrawler.crawl(new URL(repoUrl))) { -// crawlResults.push(page); -// } -// }, TIMEOUT_MS); + randomUrls.forEach((url) => { + it( + `Crawl test for ${url}`, + async () => { + const crawlResults: PageData[] = []; -// test("finds expected markdown files", async () => { -// expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe( -// true, -// ); + for await (const page of docsCrawler.crawl( + new URL(url), + NUM_PAGES_TO_CRAWL, + )) { + crawlResults.push(page); + } -// expect( -// crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")), -// ).toBe(true); -// }); + expect(crawlResults.length).toBeGreaterThanOrEqual(numPagesToCrawl); + }, + TIMEOUT_MS, + ); + }); + } -// test("html includes the correct content", async () => { -// const doc = crawlResults.find((page) => -// page.path.endsWith("docs-depth-1.md"), -// ); + describe("GitHub Crawler", () => { + const repoUrl = + "https://github.com/Patrick-Erichsen/test-github-repo-for-crawling"; -// expect(doc?.content.includes("Test body")).toBe(true); -// expect(doc?.content.includes("Test H2 Header")).toBe(true); -// }); + let crawlResults: PageData[]; -// test("ignores non-markdown files, e.g. `test.js` at the root", async () => { -// expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe( -// false, -// ); -// }); -// }); + beforeAll(async () => { + crawlResults = []; -// describe("Chromium Crawler", () => { -// it("Pre-indexed Docs", () => { -// const results: { [url: string]: boolean } = {}; -// let totalTests = 0; -// let passedTests = 0; + for await (const page of docsCrawler.crawl(new URL(repoUrl))) { + crawlResults.push(page); + } + }, TIMEOUT_MS); -// Object.keys(preIndexedDocs).forEach((url) => { -// it( -// `Crawl test for ${url}`, -// async () => { -// totalTests++; -// let pageFound = false; + test("finds expected markdown files", async () => { + expect(crawlResults.some((page) => page.path.endsWith("README.md"))).toBe( + true, + ); -// try { -// const docsCrawler = new DocsCrawler(); + expect( + crawlResults.some((page) => page.path.endsWith("docs-depth-1.md")), + ).toBe(true); + }); -// for await (const page of docsCrawler.crawl(new URL(url), 1)) { -// if (page.url === url) { -// pageFound = true; -// break; -// } -// } -// } catch (error) { -// console.error(`Error crawling ${url}:`, error); -// } + test("html includes the correct content", async () => { + const doc = crawlResults.find((page) => + page.path.endsWith("docs-depth-1.md"), + ); -// results[url] = pageFound; -// if (pageFound) { -// passedTests++; -// console.log(`✅ ${url}`); -// } else { -// console.log(`❌ ${url}`); -// } + expect(doc?.content.includes("Test body")).toBe(true); + expect(doc?.content.includes("Test H2 Header")).toBe(true); + }); -// expect(pageFound).toBe(true); -// }, -// TIMEOUT_MS, -// ); -// }); -// }); + test("ignores non-markdown files, e.g. `test.js` at the root", async () => { + expect(crawlResults.some((page) => page.path.endsWith("test.js"))).toBe( + false, + ); + }); + }); -// it( -// "succeeds in crawling a list of common sites", -// async () => { -// const TEST_SITES = [ -// "https://docs.nestjs.com/", -// "https://docs.nestjs.com/", -// "https://go.dev/doc/", -// "https://clickhouse.com/docs", -// "https://www.tensorflow.org/api_docs", -// "https://www.rust-lang.org/learn", -// "https://docs.anthropic.com/en/docs", -// ]; + describe("Chromium Crawler", () => { + let shouldUseChromiumSpy: any; -// const NUM_PAGES_TO_CRAWL = 10; + beforeAll(() => { + shouldUseChromiumSpy = jest + .spyOn(docsCrawler as any, "shouldUseChromium") + .mockReturnValue(true); + }); -// for (const site of TEST_SITES) { -// const crawlResults: PageData[] = []; -// const docsCrawler = new DocsCrawler(); + afterAll(() => { + shouldUseChromiumSpy.mockRestore(); + }); -// for await (const page of docsCrawler.crawl( -// new URL(site), -// NUM_PAGES_TO_CRAWL, -// )) { -// crawlResults.push(page); -// } + describe("Pre-indexed Docs", () => { + crawlTest(Object.keys(preIndexedDocs)); + }); -// // `toBeGreaterThanOrEqual` because Crawlee doesn't guarantee -// // an exact number of pages to crawl since it runs in parallel -// expect(crawlResults.length).toBeGreaterThanOrEqual( -// NUM_PAGES_TO_CRAWL, -// ); -// } -// }, -// TIMEOUT_MS, -// ); -// }); + describe("Running list of common sites", () => { + crawlTest([ + "https://docs.nestjs.com/", + "https://go.dev/doc/", + "https://clickhouse.com/docs", + "https://www.tensorflow.org/api_docs", + // "https://www.rust-lang.org/learn", TODO: This is failing + "https://docs.anthropic.com/en/docs", + ]); + }); + }); -// describe("Cheerio Crawler", () => { -// let mockVerifyOrInstallChromium: SpiedFunction<() => Promise>; - -// beforeAll(() => { -// mockVerifyOrInstallChromium = jest -// .spyOn(ChromiumCrawler, "verifyOrInstallChromium") -// .mockResolvedValue(false); -// }); - -// afterAll(() => { -// mockVerifyOrInstallChromium.mockRestore(); -// }); - -// it( -// "succeeds in crawling a basic site", -// async () => { -// const NUM_PAGES_TO_CRAWL = 1; -// const site = "https://amplified.dev/"; - -// const crawlResults: PageData[] = []; -// const docsCrawler = new DocsCrawler(); - -// for await (const page of docsCrawler.crawl( -// new URL(site), -// NUM_PAGES_TO_CRAWL, -// )) { -// crawlResults.push(page); -// } - -// expect(crawlResults.length).toBeGreaterThanOrEqual(NUM_PAGES_TO_CRAWL); -// }, -// TIMEOUT_MS, -// ); -// }); -// }); + describe("Cheerio Crawler", () => { + crawlTest(["https://amplified.dev/"], 1); + }); +}); diff --git a/core/indexing/docs/DocsCrawler.ts b/core/indexing/docs/DocsCrawler.ts index 7b0541559..aea21e3cf 100644 --- a/core/indexing/docs/DocsCrawler.ts +++ b/core/indexing/docs/DocsCrawler.ts @@ -71,7 +71,7 @@ class DocsCrawler { ); if (didInstall) { - this.ide.showToast( + await this.ide.showToast( "info", `Successfully installed Chromium! Retrying crawl of: ${startUrl.toString()}`, ); @@ -273,7 +273,9 @@ class CheerioCrawler { $("a").each((_: any, element: any) => { const href = $(element).attr("href"); - if (!href) return; + if (!href) { + return; + } const parsedUrl = new URL(href, url); if (parsedUrl.hostname === baseUrl.hostname) { @@ -302,6 +304,7 @@ class CheerioCrawler { class ChromiumCrawler { private readonly LINK_GROUP_SIZE = 2; + private curCrawlCount = 0; constructor( private readonly startUrl: URL, @@ -337,7 +340,7 @@ class ChromiumCrawler { } catch (e) { console.debug("Error getting links: ", e); console.debug( - `Setting 'useChromiumForDocsCrawling' to 'false' in config.json`, + "Setting 'useChromiumForDocsCrawling' to 'false' in config.json", ); ChromiumCrawler.setUseChromiumForDocsCrawling(false); @@ -382,32 +385,18 @@ class ChromiumCrawler { page: Page, curUrl: URL, visitedLinks: Set = new Set(), - curRequestCount: number = 0, ): AsyncGenerator { const urlStr = curUrl.toString(); - if (curRequestCount >= this.maxRequestsPerCrawl) { - console.warn( - `[${ - (this.constructor as any).name - }] Max requests per crawl reached. Stopping crawler.`, - ); - return; - } - if (visitedLinks.has(urlStr)) { return; } - console.debug( - `[${(this.constructor as any).name}] Crawling page: ${urlStr}`, - ); - await this.gotoPageAndHandleRedirects(page, urlStr); const htmlContent = await page.content(); const linkGroups = await this.getLinkGroupsFromPage(page, curUrl); - const requestCount = curRequestCount + 1; + this.curCrawlCount++; visitedLinks.add(urlStr); @@ -418,13 +407,14 @@ class ChromiumCrawler { }; for (const linkGroup of linkGroups) { + let enqueuedLinkCount = this.curCrawlCount; + for (const link of linkGroup) { - yield* this.crawlSitePages( - page, - new URL(link), - visitedLinks, - requestCount, - ); + enqueuedLinkCount++; + console.log({ enqueuedLinkCount, url: this.startUrl }); + if (enqueuedLinkCount <= this.maxRequestsPerCrawl) { + yield* this.crawlSitePages(page, new URL(link), visitedLinks); + } } } } @@ -491,7 +481,7 @@ class ChromiumInstaller { ) { if (this.shouldInstallOnStartup()) { console.log("Installing Chromium"); - this.install(); + void this.install(); } } @@ -524,7 +514,7 @@ class ChromiumInstaller { } } - private async install() { + async install() { try { await PCR(ChromiumInstaller.PCR_CONFIG); @@ -534,12 +524,12 @@ class ChromiumInstaller { } catch (error) { console.debug("Error installing Chromium : ", error); console.debug( - `Setting 'useChromiumForDocsCrawling' to 'false' in config.json`, + "Setting 'useChromiumForDocsCrawling' to 'false' in config.json", ); ChromiumCrawler.setUseChromiumForDocsCrawling(false); - this.ide.showToast("error", "Failed to install Chromium"); + await this.ide.showToast("error", "Failed to install Chromium"); return false; }