test: add comprehensive unit tests for all public APIs

Python (75 new tests):
- launch_context(): viewport, timezone bypass, geoip, close cleanup, error cleanup
- launch_persistent_context(): sync + async, args, proxy, close/pw.stop()
- config: binary paths, archive names, cache dir, stealth args profiles
- extract: tar/zip with path traversal protection, .app bundle preservation
- ensure_binary(), clear_cache(), check_for_update(), version markers
- geoip: private IP detection

JavaScript (26 new tests):
- puppeteer wrapper: stealth args, proxy string/dict, auth monkey-patch
- launchContext/launchPersistentContext: viewport, timezone, proxy, close
- ensureBinary, clearCache, checkForUpdate, archive helpers

Total: 169 Python + 88 JS tests (was 59 + 47)
This commit is contained in:
Cloak-HQ
2026-03-05 03:02:46 +01:00
parent 05fa1a052a
commit 0719f750ef
10 changed files with 1311 additions and 2 deletions
+24
View File
@@ -1,11 +1,13 @@
import { describe, it, expect } from "vitest";
import {
CHROMIUM_VERSION,
getArchiveExt,
getChromiumVersion,
getDefaultStealthArgs,
getCacheDir,
getBinaryDir,
getDownloadUrl,
getFallbackDownloadUrl,
} from "../src/config.js";
import { _buildArgsForTest, migrateTimezoneId } from "../src/playwright.js";
@@ -68,6 +70,28 @@ describe("config", () => {
});
});
describe("archive helpers", () => {
it("getArchiveExt returns correct extension for platform", () => {
const ext = getArchiveExt();
if (process.platform === "win32") {
expect(ext).toBe(".zip");
} else {
expect(ext).toBe(".tar.gz");
}
});
it("getFallbackDownloadUrl uses GitHub Releases", () => {
const url = getFallbackDownloadUrl("145.0.0.0");
expect(url).toContain("github.com/CloakHQ/cloakbrowser/releases/download");
expect(url).toContain("chromium-v145.0.0.0");
});
it("getFallbackDownloadUrl uses default version", () => {
const url = getFallbackDownloadUrl();
expect(url).toContain(`chromium-v${getChromiumVersion()}`);
});
});
describe("buildArgs timezone/locale", () => {
it("injects --fingerprint-timezone when timezone is set", () => {
const args = _buildArgsForTest({ timezone: "America/New_York" });
+172 -2
View File
@@ -1,6 +1,6 @@
import { describe, it, expect } from "vitest";
import { describe, it, expect, vi, afterEach, beforeEach } from "vitest";
import { binaryInfo } from "../src/download.js";
import { getChromiumVersion } from "../src/config.js";
import { DEFAULT_VIEWPORT, getChromiumVersion } from "../src/config.js";
describe("binaryInfo", () => {
it("returns correct structure", () => {
@@ -37,3 +37,173 @@ describe.skipIf(!process.env.CLOAKBROWSER_BINARY_PATH)(
}, 30_000);
}
);
// ---------------------------------------------------------------------------
// launchContext / launchPersistentContext unit tests (mock playwright-core)
// ---------------------------------------------------------------------------
describe("launchContext (unit)", () => {
let mockContext: any;
let mockBrowser: any;
let mockChromium: any;
const origEnv = process.env.CLOAKBROWSER_BINARY_PATH;
beforeEach(() => {
process.env.CLOAKBROWSER_BINARY_PATH = "/fake/chrome";
const origClose = vi.fn();
mockContext = { close: origClose, _origClose: origClose };
mockBrowser = {
newContext: vi.fn().mockResolvedValue(mockContext),
close: vi.fn(),
};
mockChromium = { launch: vi.fn().mockResolvedValue(mockBrowser) };
vi.doMock("playwright-core", () => ({ chromium: mockChromium }));
});
afterEach(() => {
vi.restoreAllMocks();
vi.resetModules();
if (origEnv) {
process.env.CLOAKBROWSER_BINARY_PATH = origEnv;
} else {
delete process.env.CLOAKBROWSER_BINARY_PATH;
}
});
it("applies DEFAULT_VIEWPORT when no viewport given", async () => {
const { launchContext } = await import("../src/playwright.js");
await launchContext();
const ctxArgs = mockBrowser.newContext.mock.calls[0][0];
expect(ctxArgs.viewport).toEqual(DEFAULT_VIEWPORT);
});
it("uses custom viewport when provided", async () => {
const { launchContext } = await import("../src/playwright.js");
const custom = { width: 1280, height: 720 };
await launchContext({ viewport: custom });
const ctxArgs = mockBrowser.newContext.mock.calls[0][0];
expect(ctxArgs.viewport).toEqual(custom);
});
it("forwards userAgent to newContext", async () => {
const { launchContext } = await import("../src/playwright.js");
await launchContext({ userAgent: "Custom/1.0" });
const ctxArgs = mockBrowser.newContext.mock.calls[0][0];
expect(ctxArgs.userAgent).toBe("Custom/1.0");
});
it("passes timezone to context timezoneId, not to launch", async () => {
const { launchContext } = await import("../src/playwright.js");
await launchContext({ timezone: "America/New_York" });
// launch() called with timezone: undefined (skipped for binary flag)
const launchArgs = mockChromium.launch.mock.calls[0][0];
const hasTimezoneFlag = launchArgs.args.some((a: string) =>
a.startsWith("--fingerprint-timezone=")
);
expect(hasTimezoneFlag).toBe(false);
// newContext() gets timezoneId
const ctxArgs = mockBrowser.newContext.mock.calls[0][0];
expect(ctxArgs.timezoneId).toBe("America/New_York");
});
it("forwards colorScheme to newContext", async () => {
const { launchContext } = await import("../src/playwright.js");
await launchContext({ colorScheme: "dark" });
const ctxArgs = mockBrowser.newContext.mock.calls[0][0];
expect(ctxArgs.colorScheme).toBe("dark");
});
it("close() also closes browser", async () => {
const { launchContext } = await import("../src/playwright.js");
const ctx = await launchContext();
await ctx.close();
// Original context close called
expect(mockContext._origClose).toHaveBeenCalledOnce();
// Browser also closed
expect(mockBrowser.close).toHaveBeenCalledOnce();
});
});
describe("launchPersistentContext (unit)", () => {
let mockContext: any;
let mockChromium: any;
const origEnv = process.env.CLOAKBROWSER_BINARY_PATH;
beforeEach(() => {
process.env.CLOAKBROWSER_BINARY_PATH = "/fake/chrome";
mockContext = { close: vi.fn(), pages: vi.fn().mockReturnValue([]) };
mockChromium = {
launchPersistentContext: vi.fn().mockResolvedValue(mockContext),
};
vi.doMock("playwright-core", () => ({ chromium: mockChromium }));
});
afterEach(() => {
vi.restoreAllMocks();
vi.resetModules();
if (origEnv) {
process.env.CLOAKBROWSER_BINARY_PATH = origEnv;
} else {
delete process.env.CLOAKBROWSER_BINARY_PATH;
}
});
it("applies DEFAULT_VIEWPORT", async () => {
const { launchPersistentContext } = await import("../src/playwright.js");
await launchPersistentContext({ userDataDir: "/tmp/profile" });
const args = mockChromium.launchPersistentContext.mock.calls[0][1];
expect(args.viewport).toEqual(DEFAULT_VIEWPORT);
});
it("passes timezone and locale to context", async () => {
const { launchPersistentContext } = await import("../src/playwright.js");
await launchPersistentContext({
userDataDir: "/tmp/profile",
timezone: "Asia/Tokyo",
locale: "ja-JP",
});
const args = mockChromium.launchPersistentContext.mock.calls[0][1];
expect(args.timezoneId).toBe("Asia/Tokyo");
expect(args.locale).toBe("ja-JP");
// Also in binary args
expect(args.args).toContain("--fingerprint-timezone=Asia/Tokyo");
expect(args.args).toContain("--lang=ja-JP");
});
it("forwards proxy string", async () => {
const { launchPersistentContext } = await import("../src/playwright.js");
await launchPersistentContext({
userDataDir: "/tmp/profile",
proxy: "http://user:pass@proxy:8080",
});
const args = mockChromium.launchPersistentContext.mock.calls[0][1];
expect(args.proxy.server).toBe("http://proxy:8080");
expect(args.proxy.username).toBe("user");
expect(args.proxy.password).toBe("pass");
});
it("forwards userAgent and colorScheme", async () => {
const { launchPersistentContext } = await import("../src/playwright.js");
await launchPersistentContext({
userDataDir: "/tmp/profile",
userAgent: "Custom/1.0",
colorScheme: "dark",
});
const args = mockChromium.launchPersistentContext.mock.calls[0][1];
expect(args.userAgent).toBe("Custom/1.0");
expect(args.colorScheme).toBe("dark");
});
});
+113
View File
@@ -0,0 +1,113 @@
import { describe, it, expect, vi, afterEach, beforeEach } from "vitest";
// Mock puppeteer-core and download before importing the module under test
vi.mock("puppeteer-core", () => ({
default: {
launch: vi.fn(),
},
}));
vi.mock("../src/download.js", () => ({
ensureBinary: vi.fn().mockResolvedValue("/fake/chrome"),
}));
vi.mock("../src/geoip.js", () => ({
resolveProxyGeo: vi.fn().mockResolvedValue({ timezone: null, locale: null }),
}));
describe("puppeteer launch", () => {
let puppeteerMock: any;
let mockBrowser: any;
beforeEach(async () => {
puppeteerMock = await import("puppeteer-core");
mockBrowser = {
newPage: vi.fn().mockResolvedValue({
authenticate: vi.fn(),
}),
close: vi.fn(),
};
vi.mocked(puppeteerMock.default.launch).mockResolvedValue(mockBrowser);
});
afterEach(() => {
vi.restoreAllMocks();
});
it("calls ensureBinary and launches with binary path", async () => {
const { launch } = await import("../src/puppeteer.js");
await launch();
expect(puppeteerMock.default.launch).toHaveBeenCalledWith(
expect.objectContaining({
executablePath: "/fake/chrome",
})
);
});
it("includes stealth args by default", async () => {
const { launch } = await import("../src/puppeteer.js");
await launch();
const callArgs = vi.mocked(puppeteerMock.default.launch).mock.calls[0][0];
expect(callArgs.args.some((a: string) => a.startsWith("--fingerprint="))).toBe(true);
expect(callArgs.args).toContain("--no-sandbox");
});
it("excludes stealth args when stealthArgs=false", async () => {
const { launch } = await import("../src/puppeteer.js");
await launch({ stealthArgs: false });
const callArgs = vi.mocked(puppeteerMock.default.launch).mock.calls[0][0];
expect(callArgs.args.some((a: string) => a.startsWith("--fingerprint="))).toBe(false);
});
it("adds --proxy-server for string proxy", async () => {
const { launch } = await import("../src/puppeteer.js");
await launch({ proxy: "http://proxy:8080" });
const callArgs = vi.mocked(puppeteerMock.default.launch).mock.calls[0][0];
expect(callArgs.args).toContain("--proxy-server=http://proxy:8080");
});
it("adds --proxy-bypass-list for dict proxy with bypass", async () => {
const { launch } = await import("../src/puppeteer.js");
await launch({
proxy: { server: "http://proxy:8080", bypass: ".google.com,localhost" },
});
const callArgs = vi.mocked(puppeteerMock.default.launch).mock.calls[0][0];
expect(callArgs.args).toContain("--proxy-server=http://proxy:8080");
expect(callArgs.args).toContain("--proxy-bypass-list=.google.com,localhost");
});
it("monkey-patches newPage for proxy auth", async () => {
const { launch } = await import("../src/puppeteer.js");
const browser = await launch({ proxy: "http://user:pass@proxy:8080" });
// newPage should auto-authenticate
const page = await browser.newPage();
expect(page.authenticate).toHaveBeenCalledWith({
username: "user",
password: "pass",
});
});
it("injects timezone and locale as binary flags", async () => {
const { launch } = await import("../src/puppeteer.js");
await launch({ timezone: "Asia/Tokyo", locale: "ja-JP" });
const callArgs = vi.mocked(puppeteerMock.default.launch).mock.calls[0][0];
expect(callArgs.args).toContain("--fingerprint-timezone=Asia/Tokyo");
expect(callArgs.args).toContain("--lang=ja-JP");
});
it("merges extra args", async () => {
const { launch } = await import("../src/puppeteer.js");
await launch({ args: ["--disable-gpu", "--no-first-run"] });
const callArgs = vi.mocked(puppeteerMock.default.launch).mock.calls[0][0];
expect(callArgs.args).toContain("--disable-gpu");
expect(callArgs.args).toContain("--no-first-run");
});
});
+54
View File
@@ -9,7 +9,11 @@ import {
versionNewer,
} from "../src/config.js";
import {
binaryInfo,
checkForUpdate,
checkWrapperUpdate,
clearCache,
ensureBinary,
getLatestChromiumVersion,
parseChecksums,
resetWrapperUpdateChecked,
@@ -271,3 +275,53 @@ describe("effective version", () => {
expect(getEffectiveVersion()).toBe(getChromiumVersion());
});
});
describe("ensureBinary", () => {
afterEach(() => {
delete process.env.CLOAKBROWSER_BINARY_PATH;
});
it("returns local override when set", async () => {
// Use this test file as a "binary" that exists
process.env.CLOAKBROWSER_BINARY_PATH = __filename;
const result = await ensureBinary();
expect(result).toBe(__filename);
});
it("throws when local override path missing", async () => {
process.env.CLOAKBROWSER_BINARY_PATH = "/nonexistent/chrome";
await expect(ensureBinary()).rejects.toThrow("does not exist");
});
});
describe("clearCache", () => {
it("does not throw when cache dir missing", () => {
const orig = process.env.CLOAKBROWSER_CACHE_DIR;
process.env.CLOAKBROWSER_CACHE_DIR = "/tmp/cloakbrowser-test-nonexistent";
expect(() => clearCache()).not.toThrow();
if (orig) {
process.env.CLOAKBROWSER_CACHE_DIR = orig;
} else {
delete process.env.CLOAKBROWSER_CACHE_DIR;
}
});
});
describe("checkForUpdate", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it("returns null when no newer version", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValue({
ok: true,
json: async () => [],
} as Response);
expect(await checkForUpdate()).toBeNull();
});
it("returns null on network error", async () => {
vi.spyOn(globalThis, "fetch").mockRejectedValue(new Error("timeout"));
expect(await checkForUpdate()).toBeNull();
});
});