test: refactor tests (#22677)

* test: refactor tests

* test: run *.worker.ts unit tests inside workerd
This commit is contained in:
Tony
2026-07-10 23:26:43 +08:00
committed by GitHub
parent b7e706df81
commit 0ab18ff80e
51 changed files with 1714 additions and 1986 deletions
+2
View File
@@ -50,6 +50,8 @@ jobs:
run: pnpm run vitest:coverage --reporter=github-actions
env:
REDIS_URL: redis://localhost:${{ job.services.redis.ports['6379'] }}/
- name: Test worker runtime (workerd)
run: pnpm run vitest:workerd
- name: Upload coverage to Codecov
if: ${{ matrix.node-version == 'lts/*' }}
uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0
+22
View File
@@ -0,0 +1,22 @@
import type { Next } from 'hono';
import { describe, expect, it } from 'vitest';
import { handler as allHandler } from '@/api/namespace/all';
import { namespaces } from '@/registry';
const noopNext: Next = () => Promise.resolve();
const createCtx = (param: Record<string, string> = {}) =>
({
req: {
valid: () => param,
},
json: (data: unknown) => data,
}) as any;
describe('api/namespace/all', () => {
it('returns all namespaces', async () => {
const result = await allHandler(createCtx(), noopNext);
expect(result).toBe(namespaces);
});
});
@@ -2,7 +2,6 @@ import type { Next } from 'hono';
import { describe, expect, it } from 'vitest';
import api from '@/api';
import { handler as allHandler } from '@/api/namespace/all';
import { handler as oneHandler } from '@/api/namespace/one';
import { namespaces } from '@/registry';
@@ -16,14 +15,9 @@ const createCtx = (param: Record<string, string> = {}) =>
json: (data: unknown) => data,
}) as any;
describe('api/namespace', () => {
describe('api/namespace/one', () => {
const nestedKey = Object.keys(namespaces).find((key) => key.includes('/')) as string;
it('returns all namespaces', async () => {
const result = await allHandler(createCtx(), noopNext);
expect(result).toBe(namespaces);
});
it('returns a single namespace', async () => {
const result = await oneHandler(createCtx({ namespace: 'test' }), noopNext);
expect(result).toBe(namespaces.test);
+87
View File
@@ -1,9 +1,15 @@
import Parser from 'rss-parser';
import undici from 'undici';
import { describe, expect, it, vi } from 'vitest';
import app from '@/app';
import { config } from '@/config';
describe('index', () => {
it('exports app entrypoint', () => {
expect(typeof app.request).toBe('function');
});
it('serve index', async () => {
const res = await app.request('/');
expect(res.status).toBe(200);
@@ -21,3 +27,84 @@ describe('request-rewriter', () => {
expect(headers.get('user-agent')).toMatch(/Chrome/);
});
});
const parser = new Parser();
process.env.ALLOW_USER_SUPPLY_UNSAFE_DOMAIN = 'true';
const routes = {
'/test/:id': '/test/1',
};
if (process.env.FULL_ROUTES_TEST) {
const { namespaces } = await import('@/registry');
for (const namespace in namespaces) {
for (const route in namespaces[namespace].routes) {
const requireConfig = namespaces[namespace].routes[route].features?.requireConfig;
let configs;
if (typeof requireConfig !== 'boolean') {
configs = requireConfig
?.filter((config) => !config.optional)
.map((config) => config.name)
.filter((name) => name !== 'ALLOW_USER_SUPPLY_UNSAFE_DOMAIN');
}
if (namespaces[namespace].routes[route].example && !configs?.length) {
routes[`/${namespace}${route}`] = namespaces[namespace].routes[route].example;
}
}
}
}
async function checkRSS(response) {
const checkDate = (date) => {
expect(date).toEqual(expect.any(String));
expect(Date.parse(date)).toEqual(expect.any(Number));
expect(Date.now() - +new Date(date)).toBeGreaterThan(-1000 * 60 * 60 * 24 * 5);
expect(Date.now() - +new Date(date)).toBeLessThan(1000 * 60 * 60 * 24 * 30 * 12 * 10);
};
const parsed = await parser.parseString(await response.text());
expect(parsed).toEqual(expect.any(Object));
expect(parsed.title).toEqual(expect.any(String));
expect(parsed.title).not.toBe('RSSHub');
expect(parsed.description).toEqual(expect.any(String));
expect(parsed.link).toEqual(expect.any(String));
expect(parsed.lastBuildDate).toEqual(expect.any(String));
expect(parsed.ttl).toEqual(Math.trunc(config.cache.routeExpire / 60) + '');
expect(parsed.items).toEqual(expect.any(Array));
checkDate(parsed.lastBuildDate);
// check items
const guids: Array<string | undefined> = [];
for (const item of parsed.items) {
expect(item).toEqual(expect.any(Object));
expect(item.title).toEqual(expect.any(String));
expect(item.link).toEqual(expect.any(String));
expect(item.content).toEqual(expect.any(String));
expect(item.guid).toEqual(expect.any(String));
if (item.pubDate) {
expect(item.pubDate).toEqual(expect.any(String));
checkDate(item.pubDate);
}
// guid must be unique
expect(guids).not.toContain(item.guid);
guids.push(item.guid);
}
}
describe('routes', () => {
for (const route in routes) {
it.concurrent(
route,
{
timeout: 60000,
},
async () => {
const response = await app.request(routes[route]);
expect(response.status).toBe(200);
await checkRSS(response);
}
);
}
});
-185
View File
@@ -1,185 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
const cacheMock = {
getCookie: vi.fn(),
getConfiguredCookie: vi.fn(),
getUsernameAndFaceFromUID: vi.fn(),
getVideoSubtitleAttachment: vi.fn(),
};
const destroy = vi.fn();
const getPlaywrightPage = vi.fn();
const goto = vi.fn();
const on = vi.fn();
const pageRoute = vi.fn();
const waitForResponse = vi.fn();
const page = {
goto,
on,
route: pageRoute,
waitForResponse,
};
vi.mock('@/routes/bilibili/cache', () => ({
default: cacheMock,
}));
vi.mock('@/utils/playwright', () => ({
getPlaywrightPage,
}));
vi.mock('@/utils/logger', () => ({
default: {
error: vi.fn(),
info: vi.fn(),
warn: vi.fn(),
},
}));
const createContext = () =>
({
req: {
param: (name: string) => {
if (name === 'uid') {
return '646730844';
}
},
query: (name: string) => {
if (name === 'format') {
return 'json';
}
},
},
}) as any;
describe('/bilibili/user/video/:uid', () => {
beforeEach(() => {
vi.resetModules();
cacheMock.getCookie.mockReset();
cacheMock.getConfiguredCookie.mockReset();
cacheMock.getUsernameAndFaceFromUID.mockReset();
cacheMock.getVideoSubtitleAttachment.mockReset();
destroy.mockReset();
getPlaywrightPage.mockReset();
goto.mockReset();
on.mockReset();
pageRoute.mockReset();
waitForResponse.mockReset();
});
it('falls back to browser mode by opening the video page and reading a single video list response', async () => {
cacheMock.getCookie.mockRejectedValueOnce(new Error('cookie unavailable'));
cacheMock.getConfiguredCookie.mockReturnValue(undefined);
cacheMock.getUsernameAndFaceFromUID.mockResolvedValue(['雷军', 'https://example.com/face.jpg']);
cacheMock.getVideoSubtitleAttachment.mockResolvedValue([]);
waitForResponse.mockResolvedValue({
headers: () => ({ 'content-type': 'application/json; charset=utf-8' }),
json: () => ({
code: 0,
data: {
list: {
vlist: [
{
aid: 1,
author: '雷军',
bvid: 'BV1xx411c7mD',
comment: 10,
created: 1_700_000_000,
description: 'video description',
length: '01:02',
pic: 'https://example.com/cover.jpg',
title: 'Video title',
},
],
},
},
}),
request: () => ({
method: () => 'GET',
resourceType: () => 'fetch',
}),
status: () => 200,
url: () => 'https://api.bilibili.com/x/space/wbi/arc/search',
});
goto.mockResolvedValue(undefined);
getPlaywrightPage.mockImplementation(async (_url, options) => {
await options.onBeforeLoad?.(page);
return {
context: {},
destroy,
page,
};
});
const { route } = await import('@/routes/bilibili/video');
const data = await route.handler(createContext());
expect(getPlaywrightPage).toHaveBeenCalledWith(
'https://space.bilibili.com/646730844/video',
expect.objectContaining({
closeTimeout: 90000,
gotoConfig: { waitUntil: 'domcontentloaded' },
noGoto: true,
})
);
expect(waitForResponse.mock.invocationCallOrder[0]).toBeLessThan(goto.mock.invocationCallOrder[0]);
expect(waitForResponse).toHaveBeenCalledWith(expect.any(Function), { timeout: 45000 });
const isVideoListResponse = waitForResponse.mock.calls[0][0];
expect(
isVideoListResponse({
headers: () => ({ 'content-type': 'application/json; charset=utf-8' }),
request: () => ({
method: () => 'GET',
resourceType: () => 'fetch',
}),
url: () => 'https://api.bilibili.com/x/space/wbi/arc/search',
})
).toBe(true);
expect(
isVideoListResponse({
headers: () => ({ 'content-type': 'text/html' }),
request: () => ({
method: () => 'GET',
resourceType: () => 'fetch',
}),
url: () => 'https://api.bilibili.com/x/space/wbi/arc/search',
})
).toBe(true);
expect(goto).toHaveBeenCalledTimes(1);
expect(goto).toHaveBeenCalledWith('https://space.bilibili.com/646730844/video', { timeout: 45000, waitUntil: 'domcontentloaded' });
expect(cacheMock.getCookie).toHaveBeenCalledTimes(1);
expect(data.item).toHaveLength(1);
expect(data.item[0].title).toBe('Video title');
});
it('throws when the single video list response returns 412', async () => {
cacheMock.getCookie.mockRejectedValueOnce(new Error('cookie unavailable'));
cacheMock.getConfiguredCookie.mockReturnValue(undefined);
waitForResponse.mockResolvedValue({
headers: () => ({ 'content-type': 'text/html' }),
request: () => ({
method: () => 'GET',
resourceType: () => 'fetch',
}),
status: () => 412,
url: () => 'https://api.bilibili.com/x/space/wbi/arc/search',
});
goto.mockResolvedValue(undefined);
getPlaywrightPage.mockImplementation(async (_url, options) => {
await options.onBeforeLoad?.(page);
return {
context: {},
destroy,
page,
};
});
const { route } = await import('@/routes/bilibili/video');
await expect(route.handler(createContext())).rejects.toThrow('Bilibili browser mode returned unexpected video list API status 412');
expect(goto).toHaveBeenCalledTimes(1);
expect(waitForResponse).toHaveBeenCalledTimes(1);
expect(destroy).toHaveBeenCalledTimes(1);
});
});
-52
View File
@@ -1,52 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
const errorSpy = vi.fn();
const infoSpy = vi.fn();
const ofetchMock = vi.fn();
const setupMocks = () => {
vi.resetModules();
vi.doMock('@/utils/logger', () => ({
default: {
error: errorSpy,
info: infoSpy,
},
}));
vi.doMock('ofetch', () => ({
ofetch: ofetchMock,
}));
};
afterEach(() => {
vi.clearAllMocks();
vi.unmock('@/utils/logger');
vi.unmock('ofetch');
ofetchMock.mockReset();
});
describe('config remote errors', () => {
it('logs when remote config returns empty', async () => {
process.env.REMOTE_CONFIG = 'http://rsshub.test/empty';
setupMocks();
ofetchMock.mockResolvedValueOnce(null);
await import('@/config');
await vi.waitFor(() => {
expect(errorSpy).toHaveBeenCalledWith('Remote config load failed.');
});
delete process.env.REMOTE_CONFIG;
});
it('logs when remote config throws', async () => {
process.env.REMOTE_CONFIG = 'http://rsshub.test/fail';
const error = new Error('boom');
setupMocks();
ofetchMock.mockRejectedValueOnce(error);
await import('@/config');
await vi.waitFor(() => {
expect(errorSpy).toHaveBeenCalledWith('Remote config load failed.', error);
});
delete process.env.REMOTE_CONFIG;
});
});
+51
View File
@@ -115,3 +115,54 @@ describe('config', () => {
delete process.env.REMOTE_CONFIG;
});
});
const errorSpy = vi.fn();
const infoSpy = vi.fn();
const ofetchMock = vi.fn();
const setupRemoteMocks = () => {
vi.resetModules();
vi.doMock('@/utils/logger', () => ({
default: {
error: errorSpy,
info: infoSpy,
},
}));
vi.doMock('ofetch', () => ({
ofetch: ofetchMock,
}));
};
describe('config remote errors', () => {
afterEach(() => {
vi.clearAllMocks();
vi.unmock('@/utils/logger');
vi.unmock('ofetch');
ofetchMock.mockReset();
});
it('logs when remote config returns empty', async () => {
process.env.REMOTE_CONFIG = 'http://rsshub.test/empty';
setupRemoteMocks();
ofetchMock.mockResolvedValueOnce(null);
await import('@/config');
await vi.waitFor(() => {
expect(errorSpy).toHaveBeenCalledWith('Remote config load failed.');
});
delete process.env.REMOTE_CONFIG;
});
it('logs when remote config throws', async () => {
process.env.REMOTE_CONFIG = 'http://rsshub.test/fail';
const error = new Error('boom');
setupRemoteMocks();
ofetchMock.mockRejectedValueOnce(error);
await import('@/config');
await vi.waitFor(() => {
expect(errorSpy).toHaveBeenCalledWith('Remote config load failed.', error);
});
delete process.env.REMOTE_CONFIG;
});
});
-79
View File
@@ -1,79 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
const notify = vi.fn();
vi.mock('@honeybadger-io/js', () => ({
default: { notify },
}));
vi.mock('@sentry/node', () => ({
withScope: vi.fn(),
captureException: vi.fn(),
}));
vi.mock('hono/route', () => ({
routePath: () => '/test/path',
}));
vi.mock('@/utils/logger', () => ({
default: {
error: vi.fn(),
},
}));
vi.mock('@/utils/otel', () => ({
requestMetric: {
error: vi.fn(),
},
}));
describe('error handler honeybadger', () => {
it('sends errors to honeybadger when enabled', async () => {
process.env.HONEYBADGER_API_KEY = 'hbp_test_key';
vi.resetModules();
// Re-mock after resetModules
vi.doMock('@honeybadger-io/js', () => ({
default: { notify },
}));
vi.doMock('@sentry/node', () => ({
withScope: vi.fn(),
captureException: vi.fn(),
}));
vi.doMock('hono/route', () => ({
routePath: () => '/test/path',
}));
vi.doMock('@/utils/logger', () => ({
default: { error: vi.fn() },
}));
vi.doMock('@/utils/otel', () => ({
requestMetric: { error: vi.fn() },
}));
const { errorHandler } = await import('@/errors');
const ctx = {
req: {
path: '/test/path',
method: 'GET',
query: () => 'json',
},
res: {
status: 500,
headers: new Headers(),
},
status: vi.fn(),
header: vi.fn(),
json: (payload: unknown) => payload,
html: (payload: unknown) => payload,
};
errorHandler(new Error('boom'), ctx as any);
expect(notify).toHaveBeenCalledWith(expect.any(Error), {
context: { name: 'test' },
});
delete process.env.HONEYBADGER_API_KEY;
});
});
+119 -1
View File
@@ -1,5 +1,5 @@
import { load } from 'cheerio';
import { describe, expect, it } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import app from '@/app';
import { config } from '@/config';
@@ -97,3 +97,121 @@ describe('route throws an error', () => {
});
});
});
describe('error handler honeybadger', () => {
const notify = vi.fn();
afterEach(() => {
vi.doUnmock('@honeybadger-io/js');
vi.doUnmock('@sentry/node');
vi.doUnmock('hono/route');
vi.doUnmock('@/utils/logger');
vi.doUnmock('@/utils/otel');
vi.resetModules();
});
it('sends errors to honeybadger when enabled', async () => {
process.env.HONEYBADGER_API_KEY = 'hbp_test_key';
vi.resetModules();
vi.doMock('@honeybadger-io/js', () => ({
default: { notify },
}));
vi.doMock('@sentry/node', () => ({
withScope: vi.fn(),
captureException: vi.fn(),
}));
vi.doMock('hono/route', () => ({
routePath: () => '/test/path',
}));
vi.doMock('@/utils/logger', () => ({
default: { error: vi.fn() },
}));
vi.doMock('@/utils/otel', () => ({
requestMetric: { error: vi.fn() },
}));
const { errorHandler } = await import('@/errors');
const ctx = {
req: {
path: '/test/path',
method: 'GET',
query: () => 'json',
},
res: {
status: 500,
headers: new Headers(),
},
status: vi.fn(),
header: vi.fn(),
json: (payload: unknown) => payload,
html: (payload: unknown) => payload,
};
errorHandler(new Error('boom'), ctx as any);
expect(notify).toHaveBeenCalledWith(expect.any(Error), {
context: { name: 'test' },
});
delete process.env.HONEYBADGER_API_KEY;
});
});
describe('error handler sentry', () => {
const captureException = vi.fn();
const setTag = vi.fn();
afterEach(() => {
vi.doUnmock('@sentry/node');
vi.doUnmock('hono/route');
vi.doUnmock('@/utils/logger');
vi.doUnmock('@/utils/otel');
vi.resetModules();
});
it('sends errors to sentry when enabled', async () => {
process.env.SENTRY = 'dsn';
vi.resetModules();
vi.doMock('@sentry/node', () => ({
withScope: (cb: (scope: { setTag: typeof setTag }) => void) => cb({ setTag }),
captureException,
}));
vi.doMock('hono/route', () => ({
routePath: () => '/test/path',
}));
vi.doMock('@/utils/logger', () => ({
default: { error: vi.fn() },
}));
vi.doMock('@/utils/otel', () => ({
requestMetric: { error: vi.fn() },
}));
const { errorHandler } = await import('@/errors');
const ctx = {
req: {
path: '/test/path',
method: 'GET',
query: () => 'json',
},
res: {
status: 500,
headers: new Headers(),
},
status: vi.fn(),
header: vi.fn(),
json: (payload: unknown) => payload,
html: (payload: unknown) => payload,
};
errorHandler(new Error('boom'), ctx as any);
expect(setTag).toHaveBeenCalledWith('name', 'test');
expect(captureException).toHaveBeenCalled();
delete process.env.SENTRY;
});
});
-57
View File
@@ -1,57 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
const captureException = vi.fn();
const setTag = vi.fn();
vi.mock('@sentry/node', () => ({
withScope: (cb: (scope: { setTag: typeof setTag }) => void) => cb({ setTag }),
captureException,
}));
vi.mock('hono/route', () => ({
routePath: () => '/test/path',
}));
vi.mock('@/utils/logger', () => ({
default: {
error: vi.fn(),
},
}));
vi.mock('@/utils/otel', () => ({
requestMetric: {
error: vi.fn(),
},
}));
describe('error handler sentry', () => {
it('sends errors to sentry when enabled', async () => {
process.env.SENTRY = 'dsn';
vi.resetModules();
const { errorHandler } = await import('@/errors');
const ctx = {
req: {
path: '/test/path',
method: 'GET',
query: () => 'json',
},
res: {
status: 500,
headers: new Headers(),
},
status: vi.fn(),
header: vi.fn(),
json: (payload: unknown) => payload,
html: (payload: unknown) => payload,
};
errorHandler(new Error('boom'), ctx as any);
expect(setTag).toHaveBeenCalledWith('name', 'test');
expect(captureException).toHaveBeenCalled();
delete process.env.SENTRY;
});
});
-63
View File
@@ -1,63 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
import { config } from '@/config';
const errorSpy = vi.fn();
vi.mock('@/utils/logger', () => ({
default: {
error: errorSpy,
warn: vi.fn(),
info: vi.fn(),
debug: vi.fn(),
},
}));
const createCtx = (query: Record<string, string | undefined>, data: any) => {
const store = new Map<string, unknown>([['data', data]]);
return {
req: {
path: '/test/path',
query: (key: string) => query[key],
},
get: (key: string) => store.get(key),
set: (key: string, value: unknown) => store.set(key, value),
};
};
describe('anti-hotlink edge cases', () => {
it('logs parse errors and keeps invalid urls', async () => {
const originalAllow = config.feature.allow_user_hotlink_template;
config.feature.allow_user_hotlink_template = true;
const { default: antiHotlink } = await import('@/middleware/anti-hotlink');
const data = {
image: 'http://invalid url',
};
const ctx = createCtx({ image_hotlink_template: 'https://img.test/${href}' }, data);
await antiHotlink(ctx as any, async () => {});
expect(data.image).toBe('http://invalid url');
expect(errorSpy).toHaveBeenCalled();
config.feature.allow_user_hotlink_template = originalAllow;
});
it('returns original url when template is missing', async () => {
const originalAllow = config.feature.allow_user_hotlink_template;
config.feature.allow_user_hotlink_template = true;
const { default: antiHotlink } = await import('@/middleware/anti-hotlink');
const data = {
image: 'https://example.com/img.jpg',
};
const ctx = createCtx({ multimedia_hotlink_template: 'https://media.test/${href}' }, data);
await antiHotlink(ctx as any, async () => {});
expect(data.image).toBe('https://example.com/img.jpg');
config.feature.allow_user_hotlink_template = originalAllow;
});
});
+63 -1
View File
@@ -1,5 +1,5 @@
import Parser from 'rss-parser';
import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
const parser = new Parser();
@@ -438,3 +438,65 @@ describe('anti-hotlink', () => {
expect(await response.text()).toContain('Error: Invalid URL property: createObjectURL');
});
});
describe('anti-hotlink edge cases', () => {
const errorSpy = vi.fn();
const createCtx = (query: Record<string, string | undefined>, data: any) => {
const store = new Map<string, unknown>([['data', data]]);
return {
req: {
path: '/test/path',
query: (key: string) => query[key],
},
get: (key: string) => store.get(key),
set: (key: string, value: unknown) => store.set(key, value),
};
};
beforeAll(() => {
vi.doMock('@/utils/logger', () => ({
default: {
error: errorSpy,
warn: vi.fn(),
info: vi.fn(),
debug: vi.fn(),
},
}));
});
afterAll(() => {
vi.doUnmock('@/utils/logger');
});
it('logs parse errors and keeps invalid urls', async () => {
const { config } = await import('@/config');
config.feature.allow_user_hotlink_template = true;
const { default: antiHotlink } = await import('@/middleware/anti-hotlink');
const data = {
image: 'http://invalid url',
};
const ctx = createCtx({ image_hotlink_template: 'https://img.test/${href}' }, data);
await antiHotlink(ctx as any, async () => {});
expect(data.image).toBe('http://invalid url');
expect(errorSpy).toHaveBeenCalled();
});
it('returns original url when template is missing', async () => {
const { config } = await import('@/config');
config.feature.allow_user_hotlink_template = true;
const { default: antiHotlink } = await import('@/middleware/anti-hotlink');
const data = {
image: 'https://example.com/img.jpg',
};
const ctx = createCtx({ multimedia_hotlink_template: 'https://media.test/${href}' }, data);
await antiHotlink(ctx as any, async () => {});
expect(data.image).toBe('https://example.com/img.jpg');
});
});
-50
View File
@@ -1,50 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
const setSpy = vi.fn(() => null);
const getSpy = vi.fn(() => null);
vi.mock('xxhash-wasm', () => ({
default: () =>
Promise.resolve({
h64ToString: () => 'hash',
}),
}));
vi.mock('@/utils/cache/index', () => ({
default: {
status: { available: true },
globalCache: {
get: getSpy,
set: setSpy,
claim: vi.fn(() => true),
},
},
}));
describe('cache middleware', () => {
it('clears control key when downstream throws', async () => {
const { default: cacheMiddleware } = await import('@/middleware/cache');
const ctx = {
req: {
path: '/test',
query: () => null,
},
res: {
headers: new Headers(),
},
status: vi.fn(),
header: vi.fn(),
set: vi.fn(),
get: vi.fn(),
};
await expect(
cacheMiddleware(ctx as any, () => {
throw new Error('boom');
})
).rejects.toThrow('boom');
expect(setSpy.mock.calls.some(([, value]) => value === '0')).toBe(true);
});
});
+55 -1
View File
@@ -1,5 +1,5 @@
import Parser from 'rss-parser';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';
import wait from '@/utils/wait';
@@ -188,3 +188,57 @@ describe('cache', () => {
expect(parsed.ttl).toEqual('10');
});
});
describe('cache middleware error handling', () => {
const setSpy = vi.fn(() => null);
const getSpy = vi.fn(() => null);
afterAll(() => {
vi.doUnmock('xxhash-wasm');
vi.doUnmock('@/utils/cache/index');
vi.resetModules();
});
it('clears control key when downstream throws', async () => {
vi.doMock('xxhash-wasm', () => ({
default: () =>
Promise.resolve({
h64ToString: () => 'hash',
}),
}));
vi.doMock('@/utils/cache/index', () => ({
default: {
status: { available: true },
globalCache: {
get: getSpy,
set: setSpy,
claim: vi.fn(() => true),
},
},
}));
const { default: cacheMiddleware } = await import('@/middleware/cache');
const ctx = {
req: {
path: '/test',
query: () => null,
},
res: {
headers: new Headers(),
},
status: vi.fn(),
header: vi.fn(),
set: vi.fn(),
get: vi.fn(),
};
await expect(
cacheMiddleware(ctx as any, () => {
throw new Error('boom');
})
).rejects.toThrow('boom');
expect(setSpy.mock.calls.some(([, value]) => value === '0')).toBe(true);
});
});
-39
View File
@@ -1,39 +0,0 @@
import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';
afterAll(() => {
delete process.env.FILTER_REGEX_ENGINE;
});
afterEach(() => {
delete process.env.FILTER_REGEX_ENGINE;
vi.resetModules();
});
describe('filter-engine', () => {
it('filter RE2 engine ReDoS attack', async () => {
const app = (await import('@/app')).default;
const response = await app.request('/test/1?filter=abc(%3F%3Ddef)');
expect(response.status).toBe(503);
expect(await response.text()).toMatch(/RE2JSSyntaxException/);
});
it('filter Regexp engine backward compatibility', async () => {
process.env.FILTER_REGEX_ENGINE = 'regexp';
const app = (await import('@/app')).default;
const response = await app.request('/test/1?filter=abc(%3F%3Ddef)');
expect(response.status).toBe(200);
});
it('filter Regexp engine test config', async () => {
process.env.FILTER_REGEX_ENGINE = 'somethingelse';
const app = (await import('@/app')).default;
const response = await app.request('/test/1?filter=abc(%3F%3Ddef)');
expect(response.status).toBe(503);
expect(await response.text()).toMatch(/somethingelse/);
});
});
-157
View File
@@ -1,157 +0,0 @@
import { describe, expect, it } from 'vitest';
process.env.OPENAI_API_KEY = 'sk-1234567890';
process.env.OPENAI_API_ENDPOINT = 'https://api.openai.mock/v1';
const { config } = await import('@/config');
const { default: parameter } = await import('@/middleware/parameter');
const runMiddleware = async (data: any, query: Record<string, string | undefined>) => {
const store = new Map<string, unknown>([['data', data]]);
const ctx = {
req: {
query: (key: string) => query[key],
},
get: (key: string) => store.get(key),
set: (key: string, value: unknown) => store.set(key, value),
};
await parameter(ctx as any, async () => {});
return store.get('data') as any;
};
describe('parameter middleware branches', () => {
it('normalizes base urls and updates quote links', async () => {
const data = {
link: 'example.com/base',
item: [
{
title: 'Item 1',
link: '/relative',
description: '<div class="rsshub-quote">Quote</div><a href="/foo">Foo</a>',
_extra: {
links: [{ href: 'https://example.com' }],
},
},
{
title: 'Item 2',
description: '<img src="/img.png" />',
},
],
allowEmpty: true,
};
const result = await runMiddleware(data, {});
expect(result.item[0].link).toBe('http://example.com/relative');
expect(result.item[1].description).toContain('http://example.com/img.png');
expect(result.item[0]._extra.links[0].content_html).toContain('rsshub-quote');
});
it('filters with RegExp engine', async () => {
const originalEngine = config.feature.filter_regex_engine;
config.feature.filter_regex_engine = 'regexp';
const data = {
link: 'https://example.com',
item: [
{ title: 'Keep', description: 'A' },
{ title: 'Drop', description: 'B' },
],
};
const result = await runMiddleware(data, { filter: 'Keep' });
expect(result.item).toHaveLength(1);
expect(result.item[0].title).toBe('Keep');
config.feature.filter_regex_engine = originalEngine;
});
it('filters by category when title and description do not match', async () => {
const originalEngine = config.feature.filter_regex_engine;
config.feature.filter_regex_engine = 'regexp';
const data = {
link: 'https://example.com',
item: [
{
title: 'Nope',
description: 'Also nope',
author: 'Still nope',
category: ['Match'],
},
],
};
const result = await runMiddleware(data, { filter: 'Match' });
expect(result.item).toHaveLength(1);
expect(result.item[0].category).toContain('Match');
config.feature.filter_regex_engine = originalEngine;
});
it('keeps items without link in tgiv mode', async () => {
const data = {
link: 'https://example.com',
item: [{ title: 'NoLink' }],
};
const result = await runMiddleware(data, { tgiv: 'hash' });
expect(result.item[0].link).toBeUndefined();
});
it('rewrites links for scihub', async () => {
const data = {
link: 'https://example.com',
item: [
{ title: 'With DOI', doi: '10.1000/xyz' },
{ title: 'With link', link: 'https://example.com/paper' },
],
};
const result = await runMiddleware(data, { scihub: '1' });
expect(result.item[0].link).toBe(`${config.scihub.host}10.1000/xyz`);
expect(result.item[1].link).toBe(`${config.scihub.host}https://example.com/paper`);
});
it('throws on invalid brief value', async () => {
const data = {
link: 'https://example.com',
item: [{ title: 'Item', description: 'Desc' }],
};
await expect(runMiddleware(data, { brief: '10' })).rejects.toThrow('Invalid parameter brief');
});
it('processes openai description and title', async () => {
const originalInput = config.openai.inputOption;
const descriptionData = {
link: 'https://example.com',
item: [
{
title: 'Title',
description: 'Description',
link: `https://example.com/${Date.now()}/desc`,
},
],
};
config.openai.inputOption = 'description';
const descriptionResult = await runMiddleware(descriptionData, { chatgpt: 'true' });
expect(descriptionResult.item[0].description).toContain('AI processed content.');
const titleData = {
link: 'https://example.com',
item: [
{
title: 'Title',
description: 'Description',
link: `https://example.com/${Date.now()}/title`,
},
],
};
config.openai.inputOption = 'title';
const titleResult = await runMiddleware(titleData, { chatgpt: 'true' });
expect(titleResult.item[0].title).toContain('AI processed content.');
config.openai.inputOption = originalInput;
});
});
-86
View File
@@ -1,86 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
class FakeRE2 {
static CASE_INSENSITIVE = 1;
static compile(pattern: string) {
return new FakeRE2(pattern);
}
private pattern: string;
constructor(pattern: string) {
this.pattern = pattern;
}
matcher(text: string) {
return {
find: () => text.includes(this.pattern),
};
}
}
// Ensure instanceof checks behave as expected.
vi.mock('re2js', () => ({
RE2JS: FakeRE2,
}));
const { config } = await import('@/config');
const { default: parameter } = await import('@/middleware/parameter');
const runMiddleware = async (data: any, query: Record<string, string | undefined>) => {
const store = new Map<string, unknown>([['data', data]]);
const ctx = {
req: {
query: (key: string) => query[key],
},
get: (key: string) => store.get(key),
set: (key: string, value: unknown) => store.set(key, value),
};
await parameter(ctx as any, async () => {});
return store.get('data') as any;
};
describe('parameter middleware with RE2 engine', () => {
it('filters items using re2 matcher', async () => {
const originalEngine = config.feature.filter_regex_engine;
config.feature.filter_regex_engine = 're2';
const data = {
link: 'https://example.com',
item: [
{ title: 'Hit', description: 'Match' },
{ title: 'Miss', description: 'Nope' },
],
};
const result = await runMiddleware(data, { filter: 'Hit' });
expect(result.item).toHaveLength(1);
expect(result.item[0].title).toBe('Hit');
config.feature.filter_regex_engine = originalEngine;
});
it('matches categories when other fields do not match', async () => {
const originalEngine = config.feature.filter_regex_engine;
config.feature.filter_regex_engine = 're2';
const data = {
link: 'https://example.com',
item: [
{
title: 'Nope',
description: 'Also nope',
author: 'Still nope',
category: ['OnlyCategory'],
},
],
};
const result = await runMiddleware(data, { filter: 'OnlyCategory' });
expect(result.item).toHaveLength(1);
expect(result.item[0].category).toContain('OnlyCategory');
config.feature.filter_regex_engine = originalEngine;
});
});
+234 -1
View File
@@ -1,5 +1,5 @@
import Parser from 'rss-parser';
import { describe, expect, it, vi } from 'vitest';
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
process.env.OPENAI_API_KEY = 'sk-1234567890';
process.env.OPENAI_API_ENDPOINT = 'https://api.openai.mock/v1';
@@ -7,9 +7,23 @@ process.env.OPENAI_API_ENDPOINT = 'https://api.openai.mock/v1';
vi.mock('@/utils/request-rewriter', () => ({ default: null }));
const { config } = await import('@/config');
const { default: app } = await import('@/app');
const { default: parameter } = await import('@/middleware/parameter');
const parser = new Parser();
const runMiddleware = async (data: any, query: Record<string, string | undefined>, middleware = parameter) => {
const store = new Map<string, unknown>([['data', data]]);
const ctx = {
req: {
query: (key: string) => query[key],
},
get: (key: string) => store.get(key),
set: (key: string, value: unknown) => store.set(key, value),
};
await middleware(ctx as any, async () => {});
return store.get('data') as any;
};
describe('filter', () => {
it('filter', async () => {
const response = await app.request('/test/1?filter=Description4|Title5');
@@ -460,3 +474,222 @@ describe('openai', () => {
expect(parsedDescriptionOnly.items[0].content).toContain('AI processed content.');
});
});
describe('parameter middleware branches', () => {
it('normalizes base urls and updates quote links', async () => {
const data = {
link: 'example.com/base',
item: [
{
title: 'Item 1',
link: '/relative',
description: '<div class="rsshub-quote">Quote</div><a href="/foo">Foo</a>',
_extra: {
links: [{ href: 'https://example.com' }],
},
},
{
title: 'Item 2',
description: '<img src="/img.png" />',
},
],
allowEmpty: true,
};
const result = await runMiddleware(data, {});
expect(result.item[0].link).toBe('http://example.com/relative');
expect(result.item[1].description).toContain('http://example.com/img.png');
expect(result.item[0]._extra.links[0].content_html).toContain('rsshub-quote');
});
it('keeps items without link in tgiv mode', async () => {
const data = {
link: 'https://example.com',
item: [{ title: 'NoLink' }],
};
const result = await runMiddleware(data, { tgiv: 'hash' });
expect(result.item[0].link).toBeUndefined();
});
it('rewrites links for scihub', async () => {
const data = {
link: 'https://example.com',
item: [
{ title: 'With DOI', doi: '10.1000/xyz' },
{ title: 'With link', link: 'https://example.com/paper' },
],
};
const result = await runMiddleware(data, { scihub: '1' });
expect(result.item[0].link).toBe(`${config.scihub.host}10.1000/xyz`);
expect(result.item[1].link).toBe(`${config.scihub.host}https://example.com/paper`);
});
it('throws on invalid brief value', async () => {
const data = {
link: 'https://example.com',
item: [{ title: 'Item', description: 'Desc' }],
};
await expect(runMiddleware(data, { brief: '10' })).rejects.toThrow('Invalid parameter brief');
});
it('processes openai description and title', async () => {
const originalInput = config.openai.inputOption;
const descriptionData = {
link: 'https://example.com',
item: [
{
title: 'Title',
description: 'Description',
link: `https://example.com/${Date.now()}/desc`,
},
],
};
config.openai.inputOption = 'description';
const descriptionResult = await runMiddleware(descriptionData, { chatgpt: 'true' });
expect(descriptionResult.item[0].description).toContain('AI processed content.');
const titleData = {
link: 'https://example.com',
item: [
{
title: 'Title',
description: 'Description',
link: `https://example.com/${Date.now()}/title`,
},
],
};
config.openai.inputOption = 'title';
const titleResult = await runMiddleware(titleData, { chatgpt: 'true' });
expect(titleResult.item[0].title).toContain('AI processed content.');
config.openai.inputOption = originalInput;
});
});
class FakeRE2 {
static CASE_INSENSITIVE = 1;
static compile(pattern: string) {
return new FakeRE2(pattern);
}
private pattern: string;
constructor(pattern: string) {
this.pattern = pattern;
}
matcher(text: string) {
return {
find: () => text.includes(this.pattern),
};
}
}
describe.each([{ engine: 'regexp' as const }, { engine: 're2' as const }])('parameter middleware filtering with $engine engine', ({ engine }) => {
let engineConfig = config;
let engineParameter = parameter;
beforeAll(async () => {
if (engine !== 're2') {
return;
}
vi.resetModules();
// Ensure instanceof checks behave as expected.
vi.doMock('re2js', () => ({
RE2JS: FakeRE2,
}));
const configModule = await import('@/config');
engineConfig = configModule.config;
const parameterModule = await import('@/middleware/parameter');
engineParameter = parameterModule.default;
});
afterAll(() => {
if (engine !== 're2') {
return;
}
vi.doUnmock('re2js');
vi.resetModules();
});
it('filters items', async () => {
const originalEngine = engineConfig.feature.filter_regex_engine;
engineConfig.feature.filter_regex_engine = engine;
const data = {
link: 'https://example.com',
item: [
{ title: 'Keep', description: 'A' },
{ title: 'Drop', description: 'B' },
],
};
const result = await runMiddleware(data, { filter: 'Keep' }, engineParameter);
expect(result.item).toHaveLength(1);
expect(result.item[0].title).toBe('Keep');
engineConfig.feature.filter_regex_engine = originalEngine;
});
it('matches categories when other fields do not match', async () => {
const originalEngine = engineConfig.feature.filter_regex_engine;
engineConfig.feature.filter_regex_engine = engine;
const data = {
link: 'https://example.com',
item: [
{
title: 'Nope',
description: 'Also nope',
author: 'Still nope',
category: ['Match'],
},
],
};
const result = await runMiddleware(data, { filter: 'Match' }, engineParameter);
expect(result.item).toHaveLength(1);
expect(result.item[0].category).toContain('Match');
engineConfig.feature.filter_regex_engine = originalEngine;
});
});
describe('filter-engine', () => {
afterEach(() => {
delete process.env.FILTER_REGEX_ENGINE;
vi.resetModules();
});
it('filter RE2 engine ReDoS attack', async () => {
const freshApp = (await import('@/app')).default;
const response = await freshApp.request('/test/1?filter=abc(%3F%3Ddef)');
expect(response.status).toBe(503);
expect(await response.text()).toMatch(/RE2JSSyntaxException/);
});
it('filter Regexp engine backward compatibility', async () => {
process.env.FILTER_REGEX_ENGINE = 'regexp';
const freshApp = (await import('@/app')).default;
const response = await freshApp.request('/test/1?filter=abc(%3F%3Ddef)');
expect(response.status).toBe(200);
});
it('filter Regexp engine test config', async () => {
process.env.FILTER_REGEX_ENGINE = 'somethingelse';
const freshApp = (await import('@/app')).default;
const response = await freshApp.request('/test/1?filter=abc(%3F%3Ddef)');
expect(response.status).toBe(503);
expect(await response.text()).toMatch(/somethingelse/);
});
});
-122
View File
@@ -1,122 +0,0 @@
import { http, HttpResponse } from 'msw';
import { describe, expect, it } from 'vitest';
import { route as pluginsRoute } from './routes/obsidian/plugins';
import { route as themesRoute } from './routes/obsidian/themes';
const searchConfigHtml = '<script>{"config":{"apiKey":"test-search-key","url":"https://community.obsidian.md/api/search"}}</script>';
describe('/obsidian', () => {
it('builds the plugins feed from the community search API sorted by creation time', async () => {
const { default: server } = await import('@/setup.test');
server.use(
http.get('https://community.obsidian.md/search', ({ request }) => {
const url = new URL(request.url);
expect(url.searchParams.get('type')).toBe('plugin');
expect(url.searchParams.get('sort')).toBe('created');
return HttpResponse.html(searchConfigHtml);
}),
http.get('https://community.obsidian.md/api/search/collections/entries/documents/search', ({ request }) => {
const url = new URL(request.url);
expect(request.headers.get('x-typesense-api-key')).toBe('test-search-key');
expect(url.searchParams.get('q')).toBe('*');
expect(url.searchParams.get('query_by')).toBe('name,authors,short_desc');
expect(url.searchParams.get('filter_by')).toBe('type:=plugin');
expect(url.searchParams.get('sort_by')).toBe('github_created_at:desc');
expect(url.searchParams.get('per_page')).toBe('54');
return HttpResponse.json({
hits: [
{
document: {
authors: ['slaymish'],
downloads: 2,
github_created_at: '2026-05-14T05:08:50Z',
id: '5757',
name: 'Synod',
short_desc: 'Run a council of LLM value agents over your journal.',
slug: 'synod',
tags: ['ai', 'import'],
type: 'plugin',
},
},
],
});
})
);
const feed = await pluginsRoute.handler();
expect(feed.title).toBe('Obsidian Plugins');
expect(feed.link).toBe('https://community.obsidian.md/search?type=plugin&sort=created');
expect(feed.item).toHaveLength(1);
expect(feed.item[0]).toMatchObject({
title: 'Synod',
description: 'Run a council of LLM value agents over your journal.',
link: 'https://community.obsidian.md/plugins/synod',
guid: 'plugin:5757',
author: 'slaymish',
category: ['ai', 'import'],
});
expect(feed.item[0].pubDate?.toISOString()).toBe('2026-05-14T05:08:50.000Z');
});
it('builds the themes feed from the community search API sorted by creation time', async () => {
const { default: server } = await import('@/setup.test');
server.use(
http.get('https://community.obsidian.md/search', ({ request }) => {
const url = new URL(request.url);
expect(url.searchParams.get('type')).toBe('theme');
expect(url.searchParams.get('sort')).toBe('created');
return HttpResponse.html(searchConfigHtml);
}),
http.get('https://community.obsidian.md/api/search/collections/entries/documents/search', ({ request }) => {
const url = new URL(request.url);
expect(request.headers.get('x-typesense-api-key')).toBe('test-search-key');
expect(url.searchParams.get('filter_by')).toBe('type:=theme');
expect(url.searchParams.get('sort_by')).toBe('github_created_at:desc');
return HttpResponse.json({
hits: [
{
document: {
authors: ['jshuntley'],
downloads: 0,
github_created_at: '2026-05-14T00:28:26Z',
id: '5749',
name: 'Fjord',
short_desc: 'Fjord colorscheme for Obsidian.',
slug: 'fjord',
tags: [],
type: 'theme',
},
},
],
});
})
);
const feed = await themesRoute.handler();
expect(feed.title).toBe('Obsidian Themes');
expect(feed.link).toBe('https://community.obsidian.md/search?type=theme&sort=created');
expect(feed.item).toHaveLength(1);
expect(feed.item[0]).toMatchObject({
title: 'Fjord',
description: 'Fjord colorscheme for Obsidian.',
link: 'https://community.obsidian.md/themes/fjord',
guid: 'theme:5749',
author: 'jshuntley',
category: [],
});
expect(feed.item[0].pubDate?.toISOString()).toBe('2026-05-14T00:28:26.000Z');
});
});
-212
View File
@@ -1,212 +0,0 @@
import type fs from 'node:fs';
import path from 'node:path';
import { Hono } from 'hono';
import { describe, expect, it, vi } from 'vitest';
// The dev registry lists lib/routes at startup; expose the fixture directory names there
const fakeTopDirectories = vi.hoisted(() => ({ names: [] as string[] }));
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof fs>();
const readdirSync = ((target: unknown, options: unknown) => {
if (fakeTopDirectories.names.length > 0 && String(target).endsWith(path.join('lib', 'routes'))) {
return fakeTopDirectories.names.map((name) => ({ name, isDirectory: () => true }));
}
return actual.readdirSync(target as never, options as never);
}) as typeof actual.readdirSync;
return { ...actual, readdirSync, default: { ...actual, readdirSync } };
});
const perDirectoryMock = (fakeDirectories: Record<string, Record<string, unknown>>) => {
fakeTopDirectories.names = Object.keys(fakeDirectories);
return vi.fn(({ targetDirectoryPath }: { targetDirectoryPath: string }) => {
const name = targetDirectoryPath.split(/[/\\]/).findLast(Boolean) as string;
return Promise.resolve(fakeDirectories[name]);
});
};
const wrap = (registry: Hono) => {
const app = new Hono();
app.use(async (ctx, next) => {
const response = await next();
const apiData = ctx.get('apiData');
if (apiData) {
return ctx.json(apiData);
}
const data = ctx.get('data');
if (data) {
return ctx.json(data);
}
return response;
});
app.route('/', registry);
return app;
};
describe('registry dynamic loading', () => {
it('loads production namespaces from build', async () => {
const originalEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'production';
vi.resetModules();
const { namespaces } = await import('@/registry');
expect(Object.keys(namespaces).length).toBeGreaterThan(0);
process.env.NODE_ENV = originalEnv;
});
it('lazily builds namespaces from directory import on first request', async () => {
const originalEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'development';
const directoryImportMock = perDirectoryMock({
nsRoute: {
'/route-array.ts': {
route: {
path: ['/a', '/b'],
name: 'Array',
handler: () => ({ title: 'array', link: 'https://example.com', item: [], allowEmpty: true }),
},
},
'/route-single.ts': {
route: {
path: '/single',
name: 'Single',
handler: () => ({ title: 'ok', link: 'https://example.com', item: [], allowEmpty: true }),
},
},
},
nsModule: {
'/route-module.ts': {
route: {
path: '/module',
name: 'Module',
module: () =>
Promise.resolve({
route: {
handler: () => new Response('module'),
},
}),
},
},
},
nsApi: {
'/api-single.ts': {
apiRoute: {
path: '/single',
name: 'ApiSingle',
handler: () => ({ ok: true }),
},
},
'/api-module.ts': {
apiRoute: {
path: '/module',
name: 'ApiModule',
module: () =>
Promise.resolve({
apiRoute: {
handler: () => ({ ok: true }),
},
}),
},
},
},
test: {
'/api-index.ts': {
apiRoute: {
path: '/',
name: 'ApiIndex',
},
},
},
});
vi.doMock('@/utils/directory-import', () => ({
directoryImport: directoryImportMock,
}));
vi.resetModules();
const { namespaces, default: registry } = await import('@/registry');
// The cold-start guarantee: importing the registry imports no route modules
expect(directoryImportMock).not.toHaveBeenCalled();
const app = wrap(registry);
const routeResponse = await app.request('/nsModule/module');
expect(await routeResponse.text()).toBe('module');
expect(directoryImportMock).toHaveBeenCalledTimes(1);
const singleResponse = await app.request('/nsRoute/single');
const singleBody = await singleResponse.json();
expect(singleBody.title).toBe('ok');
expect(namespaces.nsRoute.routes['/single']).toBeDefined();
expect(namespaces.nsRoute.routes['/a']).toBeDefined();
const apiResponse = await app.request('/api/nsApi/module');
const apiBody = await apiResponse.json();
expect(apiBody).toEqual({ ok: true });
expect(namespaces.nsApi.apiRoutes['/single']).toBeDefined();
// Handler resolution from disk in test env (real file lib/routes/test/api-index.ts)
process.env.NODE_ENV = 'test';
const apiTestResponse = await app.request('/api/test');
expect(await apiTestResponse.json()).toEqual({ code: 0 });
process.env.NODE_ENV = originalEnv;
vi.doUnmock('@/utils/directory-import');
});
// https://github.com/DIYgod/RSSHub/pull/18002
it('prioritizes literal segments over parameter segments in route matching', async () => {
const originalEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'development';
const directoryImportMock = perDirectoryMock({
specificity: {
'/param-route.ts': {
route: {
path: '/:category',
name: 'ParamRoute',
handler: () => ({ title: 'param', link: 'https://example.com', item: [], allowEmpty: true }),
},
},
'/literal-route.ts': {
route: {
path: '/news/:channel',
name: 'LiteralRoute',
handler: () => ({ title: 'literal', link: 'https://example.com', item: [], allowEmpty: true }),
},
},
'/news-route.ts': {
route: {
path: '/news',
name: 'NewsRoute',
handler: () => ({ title: 'news', link: 'https://example.com', item: [], allowEmpty: true }),
},
},
},
});
vi.doMock('@/utils/directory-import', () => ({
directoryImport: directoryImportMock,
}));
vi.resetModules();
const { default: registry } = await import('@/registry');
const app = wrap(registry);
// /news/sports should match /news/:channel (literal "news" wins over :category)
const literalResponse = await app.request('/specificity/news/sports');
expect((await literalResponse.json()).title).toBe('literal');
// /news should match /news (literal wins over :category)
const newsResponse = await app.request('/specificity/news');
expect((await newsResponse.json()).title).toBe('news');
// /products should match /:category
const paramResponse = await app.request('/specificity/products');
expect((await paramResponse.json()).title).toBe('param');
process.env.NODE_ENV = originalEnv;
vi.doUnmock('@/utils/directory-import');
});
});
+216 -1
View File
@@ -1,10 +1,28 @@
import { describe, expect, it, vi } from 'vitest';
import type fs from 'node:fs';
import path from 'node:path';
import { Hono } from 'hono';
import { afterEach, describe, expect, it, vi } from 'vitest';
import app from '@/app';
import { config } from '@/config';
import registryApp, { collectNamespaceRoots, namespaces, resolveModuleNamespace, sortRoutes } from '@/registry';
import type { Route } from '@/types';
// The dev registry lists lib/routes at startup; expose the fixture directory names there
const fakeTopDirectories = vi.hoisted(() => ({ names: [] as string[] }));
vi.mock('node:fs', async (importOriginal) => {
const actual = await importOriginal<typeof fs>();
const readdirSync = ((target: unknown, options: unknown) => {
if (fakeTopDirectories.names.length > 0 && String(target).endsWith(path.join('lib', 'routes'))) {
return fakeTopDirectories.names.map((name) => ({ name, isDirectory: () => true }));
}
return actual.readdirSync(target as never, options as never);
}) as typeof actual.readdirSync;
return { ...actual, readdirSync, default: { ...actual, readdirSync } };
});
describe('registry', () => {
// root
it('/', async () => {
@@ -137,3 +155,200 @@ describe('nested namespace mounting', () => {
expect(sorted.map(([path]) => path)).toEqual(['/static', '/:id{[0-9]+}', '/:category?']);
});
});
const perDirectoryMock = (fakeDirectories: Record<string, Record<string, unknown>>) => {
fakeTopDirectories.names = Object.keys(fakeDirectories);
return vi.fn(({ targetDirectoryPath }: { targetDirectoryPath: string }) => {
const name = targetDirectoryPath.split(/[/\\]/).findLast(Boolean) as string;
return Promise.resolve(fakeDirectories[name]);
});
};
const wrap = (registry: Hono) => {
const app = new Hono();
app.use(async (ctx, next) => {
const response = await next();
const apiData = ctx.get('apiData');
if (apiData) {
return ctx.json(apiData);
}
const data = ctx.get('data');
if (data) {
return ctx.json(data);
}
return response;
});
app.route('/', registry);
return app;
};
describe('registry dynamic loading', () => {
afterEach(() => {
fakeTopDirectories.names = [];
});
it('loads production namespaces from build', async () => {
const originalEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'production';
vi.resetModules();
const { namespaces } = await import('@/registry');
expect(Object.keys(namespaces).length).toBeGreaterThan(0);
process.env.NODE_ENV = originalEnv;
});
it('lazily builds namespaces from directory import on first request', async () => {
const originalEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'development';
const directoryImportMock = perDirectoryMock({
nsRoute: {
'/route-array.ts': {
route: {
path: ['/a', '/b'],
name: 'Array',
handler: () => ({ title: 'array', link: 'https://example.com', item: [], allowEmpty: true }),
},
},
'/route-single.ts': {
route: {
path: '/single',
name: 'Single',
handler: () => ({ title: 'ok', link: 'https://example.com', item: [], allowEmpty: true }),
},
},
},
nsModule: {
'/route-module.ts': {
route: {
path: '/module',
name: 'Module',
module: () =>
Promise.resolve({
route: {
handler: () => new Response('module'),
},
}),
},
},
},
nsApi: {
'/api-single.ts': {
apiRoute: {
path: '/single',
name: 'ApiSingle',
handler: () => ({ ok: true }),
},
},
'/api-module.ts': {
apiRoute: {
path: '/module',
name: 'ApiModule',
module: () =>
Promise.resolve({
apiRoute: {
handler: () => ({ ok: true }),
},
}),
},
},
},
test: {
'/api-index.ts': {
apiRoute: {
path: '/',
name: 'ApiIndex',
},
},
},
});
vi.doMock('@/utils/directory-import', () => ({
directoryImport: directoryImportMock,
}));
vi.resetModules();
const { namespaces, default: registry } = await import('@/registry');
// The cold-start guarantee: importing the registry imports no route modules
expect(directoryImportMock).not.toHaveBeenCalled();
const app = wrap(registry);
const routeResponse = await app.request('/nsModule/module');
expect(await routeResponse.text()).toBe('module');
expect(directoryImportMock).toHaveBeenCalledTimes(1);
const singleResponse = await app.request('/nsRoute/single');
const singleBody = await singleResponse.json();
expect(singleBody.title).toBe('ok');
expect(namespaces.nsRoute.routes['/single']).toBeDefined();
expect(namespaces.nsRoute.routes['/a']).toBeDefined();
const apiResponse = await app.request('/api/nsApi/module');
const apiBody = await apiResponse.json();
expect(apiBody).toEqual({ ok: true });
expect(namespaces.nsApi.apiRoutes['/single']).toBeDefined();
// Handler resolution from disk in test env (real file lib/routes/test/api-index.ts)
process.env.NODE_ENV = 'test';
const apiTestResponse = await app.request('/api/test');
expect(await apiTestResponse.json()).toEqual({ code: 0 });
process.env.NODE_ENV = originalEnv;
vi.doUnmock('@/utils/directory-import');
});
// https://github.com/DIYgod/RSSHub/pull/18002
it('prioritizes literal segments over parameter segments in route matching', async () => {
const originalEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'development';
const directoryImportMock = perDirectoryMock({
specificity: {
'/param-route.ts': {
route: {
path: '/:category',
name: 'ParamRoute',
handler: () => ({ title: 'param', link: 'https://example.com', item: [], allowEmpty: true }),
},
},
'/literal-route.ts': {
route: {
path: '/news/:channel',
name: 'LiteralRoute',
handler: () => ({ title: 'literal', link: 'https://example.com', item: [], allowEmpty: true }),
},
},
'/news-route.ts': {
route: {
path: '/news',
name: 'NewsRoute',
handler: () => ({ title: 'news', link: 'https://example.com', item: [], allowEmpty: true }),
},
},
},
});
vi.doMock('@/utils/directory-import', () => ({
directoryImport: directoryImportMock,
}));
vi.resetModules();
const { default: registry } = await import('@/registry');
const app = wrap(registry);
// /news/sports should match /news/:channel (literal "news" wins over :category)
const literalResponse = await app.request('/specificity/news/sports');
expect((await literalResponse.json()).title).toBe('literal');
// /news should match /news (literal wins over :category)
const newsResponse = await app.request('/specificity/news');
expect((await newsResponse.json()).title).toBe('news');
// /products should match /:category
const paramResponse = await app.request('/specificity/products');
expect((await paramResponse.json()).title).toBe('param');
process.env.NODE_ENV = originalEnv;
vi.doUnmock('@/utils/directory-import');
});
});
-86
View File
@@ -1,86 +0,0 @@
import Parser from 'rss-parser';
import { describe, expect, it } from 'vitest';
import app from '@/app';
import { config } from '@/config';
const parser = new Parser();
process.env.ALLOW_USER_SUPPLY_UNSAFE_DOMAIN = 'true';
const routes = {
'/test/:id': '/test/1',
};
if (process.env.FULL_ROUTES_TEST) {
const { namespaces } = await import('@/registry');
for (const namespace in namespaces) {
for (const route in namespaces[namespace].routes) {
const requireConfig = namespaces[namespace].routes[route].features?.requireConfig;
let configs;
if (typeof requireConfig !== 'boolean') {
configs = requireConfig
?.filter((config) => !config.optional)
.map((config) => config.name)
.filter((name) => name !== 'ALLOW_USER_SUPPLY_UNSAFE_DOMAIN');
}
if (namespaces[namespace].routes[route].example && !configs?.length) {
routes[`/${namespace}${route}`] = namespaces[namespace].routes[route].example;
}
}
}
}
async function checkRSS(response) {
const checkDate = (date) => {
expect(date).toEqual(expect.any(String));
expect(Date.parse(date)).toEqual(expect.any(Number));
expect(Date.now() - +new Date(date)).toBeGreaterThan(-1000 * 60 * 60 * 24 * 5);
expect(Date.now() - +new Date(date)).toBeLessThan(1000 * 60 * 60 * 24 * 30 * 12 * 10);
};
const parsed = await parser.parseString(await response.text());
expect(parsed).toEqual(expect.any(Object));
expect(parsed.title).toEqual(expect.any(String));
expect(parsed.title).not.toBe('RSSHub');
expect(parsed.description).toEqual(expect.any(String));
expect(parsed.link).toEqual(expect.any(String));
expect(parsed.lastBuildDate).toEqual(expect.any(String));
expect(parsed.ttl).toEqual(Math.trunc(config.cache.routeExpire / 60) + '');
expect(parsed.items).toEqual(expect.any(Array));
checkDate(parsed.lastBuildDate);
// check items
const guids: Array<string | undefined> = [];
for (const item of parsed.items) {
expect(item).toEqual(expect.any(Object));
expect(item.title).toEqual(expect.any(String));
expect(item.link).toEqual(expect.any(String));
expect(item.content).toEqual(expect.any(String));
expect(item.guid).toEqual(expect.any(String));
if (item.pubDate) {
expect(item.pubDate).toEqual(expect.any(String));
checkDate(item.pubDate);
}
// guid must be unique
expect(guids).not.toContain(item.guid);
guids.push(item.guid);
}
}
describe('routes', () => {
for (const route in routes) {
it.concurrent(
route,
{
timeout: 60000,
},
async () => {
const response = await app.request(routes[route]);
expect(response.status).toBe(200);
await checkRSS(response);
}
);
}
});
@@ -1,11 +1,6 @@
import { describe, expect, it } from 'vitest';
describe('entrypoints', () => {
it('exports app entrypoint', async () => {
const app = (await import('@/app')).default;
expect(typeof app.request).toBe('function');
});
describe('server', () => {
it('exports server entrypoint', async () => {
const server = (await import('@/server')).default;
expect(typeof server.request).toBe('function');
-156
View File
@@ -1,156 +0,0 @@
import { http, HttpResponse } from 'msw';
import { describe, expect, it } from 'vitest';
import { route as indexRoute } from './routes/techflowpost';
import { route as expressRoute } from './routes/techflowpost/express';
import { route as featuredRoute } from './routes/techflowpost/featured';
const challengeArg = '7FC0A515A247CA56A8EE791EF40FF1CAEB93AAA6';
const expectedCookie = 'acw_sc__v2=69fef11a2a690097fa41a9b697a798108d4fb906';
const challenge = `<html><script>var arg1='${challengeArg}';</script></html>`;
function createCtx({ category, limit = '1' }: { category?: string; limit?: string } = {}) {
return {
req: {
param: (name: string) => (name === 'category' ? category : undefined),
query: (name: string) => (name === 'limit' ? limit : undefined),
},
};
}
describe('/techflowpost', () => {
it('builds the article feed from the current client API after acw challenge', async () => {
const { default: server } = await import('@/setup.test');
server.use(
http.post('https://www.techflowpost.com/ashx/index.ashx', () => HttpResponse.json({ message: 'gone' }, { status: 410 })),
http.get('https://www.techflowpost.com/api/client/articles', ({ request }) => {
const url = new URL(request.url);
expect(url.searchParams.get('page')).toBe('1');
expect(url.searchParams.get('page_size')).toBe('1');
if (!request.headers.get('cookie')?.includes(expectedCookie)) {
return HttpResponse.html(challenge);
}
return HttpResponse.json({
data: [
{
id: 31495,
title: 'Article title',
abstract: 'Article abstract',
picture: '/upload/images/article.png',
author: { name: 'TechFlow' },
category: { name: 'Trading' },
labels: [{ label: 'AI' }],
created_at: '2026-05-09T06:40:11.209Z',
updated_at: '2026-05-09T08:31:01.272Z',
},
],
});
}),
http.get('https://www.techflowpost.com/api/client/articles/31495', ({ request }) => {
expect(request.headers.get('cookie')).toContain(expectedCookie);
return HttpResponse.json({
article: {
content: '<p>Full article content</p>',
},
});
})
);
const feed = await indexRoute.handler(createCtx());
expect(feed.item).toHaveLength(1);
expect(feed.item[0].title).toBe('Article title');
expect(feed.item[0].link).toBe('https://www.techflowpost.com/zh-CN/article/31495');
expect(feed.item[0].description).toContain('Full article content');
expect(feed.item[0].category).toEqual(['Trading', 'AI']);
});
it('passes category_id for featured article feeds', async () => {
const { default: server } = await import('@/setup.test');
server.use(
http.post('https://www.techflowpost.com/ashx/index.ashx', () => HttpResponse.json({ message: 'gone' }, { status: 410 })),
http.get('https://www.techflowpost.com/api/client/articles', ({ request }) => {
const url = new URL(request.url);
expect(url.searchParams.get('category_id')).toBe('2043');
if (!request.headers.get('cookie')?.includes(expectedCookie)) {
return HttpResponse.html(challenge);
}
return HttpResponse.json({
data: [
{
id: 31496,
title: 'Featured article',
abstract: 'Featured abstract',
author: { name: 'TechFlow' },
category: { name: 'Trading' },
labels: [],
created_at: '2026-05-09T07:27:22.240Z',
updated_at: '2026-05-09T08:32:09.789Z',
},
],
});
}),
http.get('https://www.techflowpost.com/api/client/articles/31496', () =>
HttpResponse.json({
article: {
content: '<p>Featured content</p>',
},
})
)
);
const feed = await featuredRoute.handler(createCtx({ category: '2043' }));
expect(feed.item[0].title).toBe('Featured article');
expect(feed.item[0].description).toContain('Featured content');
});
it('builds the express feed from the current newsflash API', async () => {
const { default: server } = await import('@/setup.test');
server.use(
http.post('https://www.techflowpost.com/ashx/newflash_index.ashx', () => HttpResponse.json({ message: 'gone' }, { status: 410 })),
http.get('https://www.techflowpost.com/api/client/newsflashes', ({ request }) => {
const url = new URL(request.url);
expect(url.searchParams.get('page')).toBe('1');
expect(url.searchParams.get('page_size')).toBe('1');
if (!request.headers.get('cookie')?.includes(expectedCookie)) {
return HttpResponse.html(challenge);
}
return HttpResponse.json({
data: [
{
id: 122059,
title: 'Newsflash title',
abstract: 'Newsflash abstract',
url: 'https://example.com/source',
created_at: '2026-05-09T08:21:45.537Z',
updated_at: '2026-05-09T08:33:21.834Z',
},
],
});
}),
http.get('https://www.techflowpost.com/api/client/newsflashes/122059', ({ request }) => {
expect(request.headers.get('cookie')).toContain(expectedCookie);
return HttpResponse.json({
content: '<p>Newsflash content</p>',
});
})
);
const feed = await expressRoute.handler(createCtx());
expect(feed.item).toHaveLength(1);
expect(feed.item[0].title).toBe('Newsflash title');
expect(feed.item[0].link).toBe('https://www.techflowpost.com/zh-CN/newsletter/122059');
expect(feed.item[0].description).toContain('Newsflash content');
});
});
+77
View File
@@ -0,0 +1,77 @@
/// <reference types="@cloudflare/vitest-pool-workers" />
import { env } from 'cloudflare:test';
import { describe, expect, it, vi } from 'vitest';
import cache, { setKVNamespace } from '@/utils/cache/index.worker';
import kv from '@/utils/cache/kv';
describe('worker cache before KV binding', () => {
it('is unavailable and always calls the value function', async () => {
expect(cache.status.available).toBe(false);
const getValue = vi.fn().mockResolvedValue({ fresh: 1 });
const first = await cache.tryGet('worker:fallback', getValue);
const second = await cache.tryGet('worker:fallback', getValue);
expect(first).toEqual({ fresh: 1 });
expect(second).toEqual({ fresh: 1 });
expect(getValue).toHaveBeenCalledTimes(2);
expect(await cache.globalCache.get('worker:fallback')).toBeNull();
});
});
// The binding is module-global state, so these run after the unavailable tests above
describe('worker cache with KV binding', () => {
it('becomes available once the KV namespace is bound', () => {
setKVNamespace(env.CACHE);
expect(cache.status.available).toBe(true);
});
it('round-trips strings and serializes objects', async () => {
await kv.set('worker:string', 'value');
expect(await kv.get('worker:string')).toBe('value');
await kv.set('worker:object', { a: 1 });
expect(await kv.get('worker:object')).toBe('{"a":1}');
expect(await kv.has('worker:object')).toBe(true);
expect(await kv.has('worker:missing')).toBe(false);
});
it('tryGet caches the computed value and parses JSON on the next hit', async () => {
const getValue = vi.fn().mockResolvedValue({ cached: true });
const miss = await cache.tryGet('worker:tryget', getValue);
expect(miss).toEqual({ cached: true });
// tryGet writes the cache without awaiting the KV put
await vi.waitFor(async () => {
expect(await kv.has('worker:tryget')).toBe(true);
});
const hit = await cache.tryGet('worker:tryget', getValue);
expect(hit).toEqual({ cached: true });
expect(getValue).toHaveBeenCalledTimes(1);
});
it('stores a ttl sidecar key for non-default expiry', async () => {
await kv.set('worker:custom-ttl', 'v', 120);
expect(await env.CACHE.get('rsshub:cacheTtl:worker:custom-ttl')).toBe('120');
await kv.set('worker:default-ttl', 'v');
expect(await env.CACHE.get('rsshub:cacheTtl:worker:default-ttl')).toBeNull();
});
it('rejects keys using the reserved ttl prefix', async () => {
await expect(kv.get('rsshub:cacheTtl:foo')).rejects.toThrow('reserved');
});
it('claims a key only once', async () => {
expect(await cache.globalCache.claim('worker:claim', 60)).toBe(true);
expect(await cache.globalCache.claim('worker:claim', 60)).toBe(false);
});
it('exposes get/set through globalCache', async () => {
await cache.globalCache.set('worker:global', { b: 2 }, 60);
expect(await cache.globalCache.get('worker:global')).toBe('{"b":2}');
});
});
-49
View File
@@ -1,49 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
const html = `<div class="content">
<ul>
<li>
<a href="/1">1</a>
<div class="description">RSSHub1</div>
<div class="date">2025-01-01</div>
</li>
</ul>
</div>`;
const rawSpy = vi.fn(() =>
Promise.resolve({
headers: new Headers({
'content-type': 'text/html; charset=gbk',
}),
_data: html,
})
);
const ofetchSpy = vi.fn(() => Promise.resolve(Buffer.from(html)));
vi.mock('@/utils/ofetch', () => ({
default: Object.assign(ofetchSpy, { raw: rawSpy }),
}));
describe('common-config charset', () => {
it('parses charset from content-type', async () => {
const buildData = (await import('@/utils/common-config')).default;
const data = await buildData({
link: 'http://rsshub.test/buildData',
url: 'http://rsshub.test/buildData',
title: '%title%',
params: {
title: 'buildData',
},
item: {
item: '.content li',
title: `$('a').text() + ' - %title%'`,
link: `$('a').attr('href')`,
description: `$('.description').html()`,
pubDate: `timezone(parseDate($('.date').text(), 'YYYY-MM-DD'), 0)`,
},
});
expect(data.title).toBe('buildData');
expect(data.item[0].title).toBe('1 - buildData');
});
});
+57 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import configUtils, { getProp, replaceParams, transElemText } from '@/utils/common-config';
@@ -78,3 +78,59 @@ describe('index', () => {
});
});
});
describe('charset', () => {
const html = `<div class="content">
<ul>
<li>
<a href="/1">1</a>
<div class="description">RSSHub1</div>
<div class="date">2025-01-01</div>
</li>
</ul>
</div>`;
const rawSpy = vi.fn(() =>
Promise.resolve({
headers: new Headers({
'content-type': 'text/html; charset=gbk',
}),
_data: html,
})
);
const ofetchSpy = vi.fn(() => Promise.resolve(Buffer.from(html)));
beforeAll(() => {
vi.doMock('@/utils/ofetch', () => ({
default: Object.assign(ofetchSpy, { raw: rawSpy }),
}));
vi.resetModules();
});
afterAll(() => {
vi.doUnmock('@/utils/ofetch');
vi.resetModules();
});
it('parses charset from content-type', async () => {
const buildData = (await import('@/utils/common-config')).default;
const data = await buildData({
link: 'http://rsshub.test/buildData',
url: 'http://rsshub.test/buildData',
title: '%title%',
params: {
title: 'buildData',
},
item: {
item: '.content li',
title: `$('a').text() + ' - %title%'`,
link: `$('a').attr('href')`,
description: `$('.description').html()`,
pubDate: `timezone(parseDate($('.date').text(), 'YYYY-MM-DD'), 0)`,
},
});
expect(data.title).toBe('buildData');
expect(data.item[0].title).toBe('1 - buildData');
});
});
-50
View File
@@ -1,50 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
afterEach(() => {
vi.resetModules();
vi.clearAllMocks();
vi.unmock('header-generator');
});
describe('header-generator (mocked)', () => {
it('retries invalid safari user agents', async () => {
const headersQueue = [{ 'user-agent': 'Mozilla/5.0 Applebot Safari' }, { 'user-agent': 'Mozilla/5.0 Safari' }];
vi.doMock('header-generator', () => ({
HeaderGenerator: class {
getHeaders() {
return headersQueue.shift() ?? { 'user-agent': 'Mozilla/5.0 Safari' };
}
},
PRESETS: {
MODERN_MACOS_CHROME: { mock: true },
},
}));
const { generateHeaders } = await import('@/utils/header-generator');
const headers = generateHeaders({ preset: 'safari' } as any);
expect(headers['user-agent']).toContain('Safari');
expect(headersQueue.length).toBe(0);
});
it('accepts firefox user agents', async () => {
const headersQueue = [{ 'user-agent': 'Mozilla/5.0 Firefox' }];
vi.doMock('header-generator', () => ({
HeaderGenerator: class {
getHeaders() {
return headersQueue.shift() ?? { 'user-agent': 'Mozilla/5.0 Firefox' };
}
},
PRESETS: {
MODERN_MACOS_CHROME: { mock: true },
},
}));
const { generateHeaders } = await import('@/utils/header-generator');
const headers = generateHeaders();
expect(headers['user-agent']).toContain('Firefox');
});
});
+52 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { generateHeaders, PRESETS } from '@/utils/header-generator';
import ofetch from '@/utils/ofetch';
@@ -62,3 +62,54 @@ describe('header-generator', () => {
expect(headers['user-agent']).toMatch(/Chrome/);
});
});
describe('header-generator (mocked)', () => {
afterEach(() => {
vi.resetModules();
vi.clearAllMocks();
vi.unmock('header-generator');
});
it('retries invalid safari user agents', async () => {
const headersQueue = [{ 'user-agent': 'Mozilla/5.0 Applebot Safari' }, { 'user-agent': 'Mozilla/5.0 Safari' }];
vi.doMock('header-generator', () => ({
HeaderGenerator: class {
getHeaders() {
return headersQueue.shift() ?? { 'user-agent': 'Mozilla/5.0 Safari' };
}
},
PRESETS: {
MODERN_MACOS_CHROME: { mock: true },
},
}));
vi.resetModules();
const { generateHeaders: generateMockedHeaders } = await import('@/utils/header-generator');
const headers = generateMockedHeaders({ preset: 'safari' } as any);
expect(headers['user-agent']).toContain('Safari');
expect(headersQueue.length).toBe(0);
});
it('accepts firefox user agents', async () => {
const headersQueue = [{ 'user-agent': 'Mozilla/5.0 Firefox' }];
vi.doMock('header-generator', () => ({
HeaderGenerator: class {
getHeaders() {
return headersQueue.shift() ?? { 'user-agent': 'Mozilla/5.0 Firefox' };
}
},
PRESETS: {
MODERN_MACOS_CHROME: { mock: true },
},
}));
vi.resetModules();
const { generateHeaders: generateMockedHeaders } = await import('@/utils/header-generator');
const headers = generateMockedHeaders();
expect(headers['user-agent']).toContain('Firefox');
});
});
-22
View File
@@ -1,22 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
const errorSpy = vi.fn();
const warnSpy = vi.fn();
const infoSpy = vi.fn();
vi.mock('@/utils/logger', () => ({
default: {
error: errorSpy,
warn: warnSpy,
info: infoSpy,
},
}));
describe('pac-proxy', () => {
it('logs error when PAC_SCRIPT is not a string', async () => {
const pacProxy = (await import('@/utils/proxy/pac-proxy')).default;
pacProxy(undefined, { invalid: true } as any, {});
expect(errorSpy).toHaveBeenCalledWith('Invalid PAC_SCRIPT, use PAC_URI instead');
});
});
+28 -1
View File
@@ -1,4 +1,4 @@
import { describe, expect, it } from 'vitest';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
import pacProxy from '@/utils/proxy/pac-proxy';
@@ -79,3 +79,30 @@ describe('pac-proxy', () => {
effectiveExpect(pacProxy(httpsAuthUri, '', httpsAuthObj), httpsAuthUri, httpsObj);
});
});
describe('pac-proxy error handling', () => {
const errorSpy = vi.fn();
beforeAll(() => {
vi.doMock('@/utils/logger', () => ({
default: {
error: errorSpy,
warn: vi.fn(),
info: vi.fn(),
},
}));
vi.resetModules();
});
afterAll(() => {
vi.doUnmock('@/utils/logger');
vi.resetModules();
});
it('logs error when PAC_SCRIPT is not a string', async () => {
const freshPacProxy = (await import('@/utils/proxy/pac-proxy')).default;
freshPacProxy(undefined, { invalid: true } as any, {});
expect(errorSpy).toHaveBeenCalledWith('Invalid PAC_SCRIPT, use PAC_URI instead');
});
});
+16
View File
@@ -0,0 +1,16 @@
import { describe, expect, it } from 'vitest';
import { Atom as RenderAtom, json as renderJson, RSS as RenderRSS, rss3 as renderRss3 } from '@/utils/render';
import Atom from '@/views/atom';
import jsonView from '@/views/json';
import RSS from '@/views/rss';
import rss3View from '@/views/rss3';
describe('view exports', () => {
it('re-exports view helpers from render', () => {
expect(RenderAtom).toBe(Atom);
expect(RenderRSS).toBe(RSS);
expect(renderJson).toBe(jsonView);
expect(renderRss3).toBe(rss3View);
});
});
@@ -1,118 +0,0 @@
import undici from 'undici';
import { afterEach, describe, expect, it, vi } from 'vitest';
const buildProxyState = () => [
{
uri: 'http://proxy1.test',
isActive: true,
failureCount: 0,
urlHandler: new URL('http://proxy1.test'),
},
{
uri: 'http://proxy2.test',
isActive: true,
failureCount: 0,
urlHandler: new URL('http://proxy2.test'),
},
];
const loadWrappedFetch = async (proxyMock: any) => {
vi.resetModules();
vi.doMock('@/utils/logger', () => ({
default: {
debug: vi.fn(),
warn: vi.fn(),
info: vi.fn(),
error: vi.fn(),
http: vi.fn(),
},
}));
vi.doMock('@/utils/proxy', () => ({
default: proxyMock,
}));
return (await import('@/utils/request-rewriter/fetch')).default;
};
afterEach(() => {
vi.restoreAllMocks();
vi.resetModules();
vi.unmock('@/utils/logger');
vi.unmock('@/utils/proxy');
});
describe('request-rewriter fetch retry', () => {
it('retries with the next proxy when prefer-proxy header is set', async () => {
const proxies = buildProxyState();
let index = 0;
const proxyMock = {
proxyObj: {
strategy: 'on_retry',
url_regex: 'example.com',
},
proxyUrlHandler: null,
multiProxy: {
allProxies: proxies,
},
getCurrentProxy: vi.fn(() => proxies[index]),
markProxyFailed: vi.fn(() => {
index = 1;
}),
getDispatcherForProxy: vi.fn((proxyState) => ({
proxy: proxyState.uri,
})),
};
const wrappedFetch = await loadWrappedFetch(proxyMock);
const fetchSpy = vi.spyOn(undici, 'fetch');
fetchSpy.mockRejectedValueOnce(new Error('boom'));
fetchSpy.mockResolvedValueOnce(new Response('ok'));
const response = await wrappedFetch('http://example.com/resource', {
headers: new Headers({
'x-prefer-proxy': '1',
}),
});
expect(response).toBeInstanceOf(Response);
expect(fetchSpy).toHaveBeenCalledTimes(2);
expect(proxyMock.markProxyFailed).toHaveBeenCalledWith('http://proxy1.test');
expect(proxyMock.getDispatcherForProxy).toHaveBeenCalledWith(proxies[1]);
const requestArg = fetchSpy.mock.calls[0][0] as Request;
expect(requestArg.headers.get('x-prefer-proxy')).toBeNull();
});
it('drops dispatcher when no next proxy is available', async () => {
const proxies = buildProxyState();
const proxyMock = {
proxyObj: {
strategy: 'on_retry',
url_regex: 'example.com',
},
proxyUrlHandler: null,
multiProxy: {
allProxies: proxies,
},
getCurrentProxy: vi.fn(() => proxies[0]),
markProxyFailed: vi.fn(),
getDispatcherForProxy: vi.fn((proxyState) => ({
proxy: proxyState.uri,
})),
};
const wrappedFetch = await loadWrappedFetch(proxyMock);
const fetchSpy = vi.spyOn(undici, 'fetch');
fetchSpy.mockRejectedValueOnce(new Error('boom'));
fetchSpy.mockResolvedValueOnce(new Response('ok'));
await wrappedFetch('http://example.com/resource', {
headers: {
'x-prefer-proxy': '1',
},
});
expect(fetchSpy).toHaveBeenCalledTimes(2);
expect(fetchSpy.mock.calls[1][1]?.dispatcher).toBeUndefined();
});
});
+116
View File
@@ -105,3 +105,119 @@ describe('wrappedFetch', () => {
fetchSpy.mockRestore();
});
});
describe('request-rewriter fetch retry', () => {
const buildProxyState = () => [
{
uri: 'http://proxy1.test',
isActive: true,
failureCount: 0,
urlHandler: new URL('http://proxy1.test'),
},
{
uri: 'http://proxy2.test',
isActive: true,
failureCount: 0,
urlHandler: new URL('http://proxy2.test'),
},
];
const loadWrappedFetch = async (proxyMock: any) => {
vi.resetModules();
vi.doMock('@/utils/logger', () => ({
default: {
debug: vi.fn(),
warn: vi.fn(),
info: vi.fn(),
error: vi.fn(),
http: vi.fn(),
},
}));
vi.doMock('@/utils/proxy', () => ({
default: proxyMock,
}));
return (await import('@/utils/request-rewriter/fetch')).default;
};
afterEach(() => {
vi.restoreAllMocks();
vi.resetModules();
vi.unmock('@/utils/logger');
vi.unmock('@/utils/proxy');
});
test('retries with the next proxy when prefer-proxy header is set', async () => {
const proxies = buildProxyState();
let index = 0;
const proxyMock = {
proxyObj: {
strategy: 'on_retry',
url_regex: 'example.com',
},
proxyUrlHandler: null,
multiProxy: {
allProxies: proxies,
},
getCurrentProxy: vi.fn(() => proxies[index]),
markProxyFailed: vi.fn(() => {
index = 1;
}),
getDispatcherForProxy: vi.fn((proxyState) => ({
proxy: proxyState.uri,
})),
};
const wrappedFetch = await loadWrappedFetch(proxyMock);
const fetchSpy = vi.spyOn(undici, 'fetch');
fetchSpy.mockRejectedValueOnce(new Error('boom'));
fetchSpy.mockResolvedValueOnce(new Response('ok'));
const response = await wrappedFetch('http://example.com/resource', {
headers: new Headers({
'x-prefer-proxy': '1',
}),
});
expect(response).toBeInstanceOf(Response);
expect(fetchSpy).toHaveBeenCalledTimes(2);
expect(proxyMock.markProxyFailed).toHaveBeenCalledWith('http://proxy1.test');
expect(proxyMock.getDispatcherForProxy).toHaveBeenCalledWith(proxies[1]);
const requestArg = fetchSpy.mock.calls[0][0] as Request;
expect(requestArg.headers.get('x-prefer-proxy')).toBeNull();
});
test('drops dispatcher when no next proxy is available', async () => {
const proxies = buildProxyState();
const proxyMock = {
proxyObj: {
strategy: 'on_retry',
url_regex: 'example.com',
},
proxyUrlHandler: null,
multiProxy: {
allProxies: proxies,
},
getCurrentProxy: vi.fn(() => proxies[0]),
markProxyFailed: vi.fn(),
getDispatcherForProxy: vi.fn((proxyState) => ({
proxy: proxyState.uri,
})),
};
const wrappedFetch = await loadWrappedFetch(proxyMock);
const fetchSpy = vi.spyOn(undici, 'fetch');
fetchSpy.mockRejectedValueOnce(new Error('boom'));
fetchSpy.mockResolvedValueOnce(new Response('ok'));
await wrappedFetch('http://example.com/resource', {
headers: {
'x-prefer-proxy': '1',
},
});
expect(fetchSpy).toHaveBeenCalledTimes(2);
expect(fetchSpy.mock.calls[1][1]?.dispatcher).toBeUndefined();
});
});
@@ -0,0 +1,72 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
const fetchMock = vi.fn(() => Promise.resolve(new Response('ok')));
// The module captures the global fetch at import time, so stub before importing
const loadWrappedFetch = async () => {
vi.stubGlobal('fetch', fetchMock);
vi.resetModules();
return (await import('@/utils/request-rewriter/fetch.worker')).default;
};
const lastRequest = () => fetchMock.mock.lastCall?.[0] as unknown as Request;
afterEach(() => {
vi.unstubAllGlobals();
vi.clearAllMocks();
});
describe('worker fetch wrapper', () => {
it('applies a browser fingerprint when no user-agent is set', async () => {
const wrappedFetch = await loadWrappedFetch();
await wrappedFetch('https://example.com/page');
const request = lastRequest();
expect(request.headers.get('user-agent')).toContain('Chrome');
expect(request.headers.get('sec-ch-ua-platform')).toBe('"macOS"');
expect(request.headers.get('accept-language')).toBe('en-US,en;q=0.9');
});
it('keeps a caller-provided user-agent and headers', async () => {
const wrappedFetch = await loadWrappedFetch();
await wrappedFetch('https://example.com/page', {
headers: {
'user-agent': 'custom-ua',
'sec-fetch-site': 'same-origin',
},
});
const request = lastRequest();
expect(request.headers.get('user-agent')).toBe('custom-ua');
expect(request.headers.get('sec-fetch-site')).toBe('same-origin');
});
it('sets the referer to the request origin when absent', async () => {
const wrappedFetch = await loadWrappedFetch();
await wrappedFetch('https://example.com/deep/page?q=1');
expect(lastRequest().headers.get('referer')).toBe('https://example.com');
});
it('keeps a caller-provided referer', async () => {
const wrappedFetch = await loadWrappedFetch();
await wrappedFetch('https://example.com/page', {
headers: {
referer: 'https://referrer.test/',
},
});
expect(lastRequest().headers.get('referer')).toBe('https://referrer.test/');
});
it('strips the x-prefer-proxy header', async () => {
const wrappedFetch = await loadWrappedFetch();
await wrappedFetch('https://example.com/page', {
headers: {
'x-prefer-proxy': '1',
},
});
expect(lastRequest().headers.has('x-prefer-proxy')).toBe(false);
});
});
@@ -0,0 +1,10 @@
import { describe, expect, it } from 'vitest';
describe('worker request-rewriter', () => {
it('replaces globalThis.fetch with the wrapped fetch', async () => {
const { default: wrappedFetch } = await import('@/utils/request-rewriter/fetch.worker');
await import('@/utils/request-rewriter/index.worker');
expect(fetch).toBe(wrappedFetch);
});
});
+57
View File
@@ -0,0 +1,57 @@
import { renderToString } from 'hono/jsx/dom/server';
import { describe, expect, it } from 'vitest';
import Atom from '@/views/atom';
describe('Atom view', () => {
it('renders optional fields and media extensions', () => {
const html = renderToString(
<Atom
data={{
title: 'Atom Feed',
link: 'https://example.com',
description: 'Atom Description',
language: 'zh',
lastBuildDate: '2024-01-01T00:00:00Z',
icon: 'https://example.com/icon.png',
logo: 'https://example.com/logo.png',
item: [
{
title: 'Item One',
link: 'https://example.com/one',
description: 'Entry One',
pubDate: '2024-01-01T00:00:00Z',
updated: '2024-01-02T00:00:00Z',
author: 'Author One',
category: 'News',
media: {
content: {
url: 'https://example.com/video.mp4',
},
},
upvotes: 12,
downvotes: 1,
comments: 3,
},
{
title: 'Item Two',
link: 'https://example.com/two',
description: 'Entry Two',
category: ['Tech', 'AI'],
guid: 'guid-2',
},
],
}}
/>
);
expect(html).toContain('<icon>https://example.com/icon.png</icon>');
expect(html).toContain('<logo>https://example.com/logo.png</logo>');
expect(html).toContain('media:content');
expect(html).toContain('term="News"');
expect(html).toContain('term="Tech"');
expect(html).toContain('rsshub:upvotes');
expect(html).toContain('rsshub:downvotes');
expect(html).toContain('rsshub:comments');
});
});
+74
View File
@@ -0,0 +1,74 @@
import { renderToString } from 'hono/jsx/dom/server';
import { afterEach, describe, expect, it, vi } from 'vitest';
afterEach(() => {
vi.resetModules();
vi.unmock('@/config');
vi.unmock('@/utils/debug-info');
vi.unmock('@/utils/git-hash');
});
describe('Index view', () => {
const renderIndex = async (debugInfo: string | undefined, debugQuery: string | undefined) => {
const debugData = {
hitCache: 2,
request: 10,
etag: 3,
error: 1,
routes: {
'/foo': 5,
'/bar': 2,
},
paths: {
'/foo?x=1': 4,
'/bar?x=2': 1,
},
errorRoutes: {
'/error': 2,
'/fail': 1,
},
errorPaths: {
'/error?x=1': 1,
'/fail?x=2': 1,
},
};
vi.doMock('@/config', () => ({
config: {
debugInfo,
disallowRobot: true,
nodeName: 'TestNode',
cache: {
routeExpire: 120,
},
},
}));
vi.doMock('@/utils/debug-info', () => ({
getDebugInfo: () => debugData,
}));
vi.doMock('@/utils/git-hash', () => ({
gitHash: 'abc123',
gitDate: new Date('2020-01-01T00:00:00Z'),
}));
const { default: Index } = await import('@/views/index');
return renderToString(<Index debugQuery={debugQuery} />);
};
it('shows debug info when enabled', async () => {
const html = await renderIndex('secret', 'secret');
expect(html).toContain('Debug Info');
expect(html).toContain('TestNode');
expect(html).toContain('abc123');
expect(html).toContain('5 /foo');
expect(html).toContain('2 /error');
});
it('hides debug info when disabled', async () => {
const html = await renderIndex('false', 'secret');
expect(html).not.toContain('Debug Info');
});
});
+75
View File
@@ -0,0 +1,75 @@
import { describe, expect, it } from 'vitest';
import jsonView from '@/views/json';
describe('JSON view', () => {
it('renders summary, authors, tags, attachments, and extras', () => {
const jsonOutput = jsonView({
title: 'JSON Feed',
link: 'https://example.com',
feedLink: 'https://example.com/feed.json',
description: 'JSON Description',
language: 'en',
author: 'Feed Author',
image: 'https://example.com/icon.png',
item: [
{
title: 'Item One',
link: 'https://example.com/one',
description: 'Entry One',
guid: 'guid-1',
content: {
html: '<p>hello</p>',
text: 'hello',
},
image: 'https://example.com/image.jpg',
banner: 'https://example.com/banner.jpg',
pubDate: '2024-01-01T00:00:00Z',
updated: '2024-01-02T00:00:00Z',
author: 'Item Author',
category: ['Tech', 'AI'],
enclosure_url: 'https://example.com/audio.mp3',
enclosure_type: 'audio/mpeg',
enclosure_title: 'Audio Title',
enclosure_length: 123,
itunes_duration: 321,
_extra: { foo: 'bar' },
},
],
});
const feed = JSON.parse(jsonOutput);
expect(feed.version).toBe('https://jsonfeed.org/version/1.1');
expect(feed.title).toBe('JSON Feed');
expect(feed.home_page_url).toBe('https://example.com');
expect(feed.feed_url).toBe('https://example.com/feed.json');
expect(feed.description).toBe('JSON Description - Powered by RSSHub');
expect(feed.authors).toEqual([{ name: 'Feed Author' }]);
expect(feed.items).toHaveLength(1);
expect(feed.items[0]).toMatchObject({
id: 'guid-1',
url: 'https://example.com/one',
title: 'Item One',
content_html: '<p>hello</p>',
content_text: 'hello',
summary: 'Entry One',
image: 'https://example.com/image.jpg',
banner_image: 'https://example.com/banner.jpg',
date_published: '2024-01-01T00:00:00Z',
date_modified: '2024-01-02T00:00:00Z',
authors: [{ name: 'Item Author' }],
tags: ['Tech', 'AI'],
attachments: [
{
url: 'https://example.com/audio.mp3',
mime_type: 'audio/mpeg',
title: 'Audio Title',
size_in_bytes: 123,
duration_in_seconds: 321,
},
],
});
expect(feed.items[0]._extra).toEqual({ foo: 'bar' });
});
});
+67
View File
@@ -0,0 +1,67 @@
import { renderToString } from 'hono/jsx/dom/server';
import { describe, expect, it } from 'vitest';
import RSS from '@/views/rss';
describe('RSS view', () => {
it('renders itunes, media, and telegram image variants', () => {
const html = renderToString(
<RSS
data={{
title: 'RSS Feed',
link: 'https://t.me/s/rsshub',
atomlink: 'https://example.com/feed.xml',
description: 'RSS Description',
language: 'en',
lastBuildDate: '2024-01-01T00:00:00Z',
ttl: 60,
itunes_author: 'Podcast Author',
itunes_category: 'Tech',
itunes_explicit: 'true',
image: 'https://example.com/image.jpg',
item: [
{
title: 'Episode One',
link: 'https://example.com/one',
description: 'Episode One',
guid: 'episode-1',
pubDate: '2024-01-01T00:00:00Z',
author: 'Host',
image: 'https://example.com/episode.jpg',
itunes_item_image: 'https://example.com/itunes.jpg',
itunes_duration: '01:02:03',
enclosure_url: 'https://example.com/audio.mp3',
enclosure_length: '123',
enclosure_type: 'audio/mpeg',
category: 'Podcast',
media: {
content: {
url: 'https://example.com/media.mp4',
},
},
},
{
title: 'Episode Two',
link: 'https://example.com/two',
description: 'Episode Two',
category: ['News', 'Updates'],
},
],
}}
/>
);
expect(html).toContain('xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"');
expect(html).toContain('xmlns:media="http://search.yahoo.com/mrss/"');
expect(html).toContain('<itunes:author>Podcast Author</itunes:author>');
expect(html).toContain('itunes:category text="Tech"');
expect(html).toContain('<itunes:explicit>true</itunes:explicit>');
expect(html).toContain('<height>31</height>');
expect(html).toContain('<width>88</width>');
expect(html).toContain('media:content');
expect(html).toContain('<itunes:image href="https://example.com/itunes.jpg"');
expect(html).toContain('<enclosure url="https://example.com/audio.mp3"');
expect(html).toContain('<category>Podcast</category>');
expect(html).toContain('<category>News</category>');
});
});
-277
View File
@@ -1,277 +0,0 @@
import { renderToString } from 'hono/jsx/dom/server';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { Atom as RenderAtom, json as renderJson, RSS as RenderRSS, rss3 as renderRss3 } from '@/utils/render';
import Atom from '@/views/atom';
import jsonView from '@/views/json';
import RSS from '@/views/rss';
import rss3View from '@/views/rss3';
afterEach(() => {
vi.resetModules();
vi.unmock('@/config');
vi.unmock('@/utils/debug-info');
vi.unmock('@/utils/git-hash');
});
describe('view exports', () => {
it('re-exports view helpers from render', () => {
expect(RenderAtom).toBe(Atom);
expect(RenderRSS).toBe(RSS);
expect(renderJson).toBe(jsonView);
expect(renderRss3).toBe(rss3View);
});
});
describe('Atom view', () => {
it('renders optional fields and media extensions', () => {
const html = renderToString(
<Atom
data={{
title: 'Atom Feed',
link: 'https://example.com',
description: 'Atom Description',
language: 'zh',
lastBuildDate: '2024-01-01T00:00:00Z',
icon: 'https://example.com/icon.png',
logo: 'https://example.com/logo.png',
item: [
{
title: 'Item One',
link: 'https://example.com/one',
description: 'Entry One',
pubDate: '2024-01-01T00:00:00Z',
updated: '2024-01-02T00:00:00Z',
author: 'Author One',
category: 'News',
media: {
content: {
url: 'https://example.com/video.mp4',
},
},
upvotes: 12,
downvotes: 1,
comments: 3,
},
{
title: 'Item Two',
link: 'https://example.com/two',
description: 'Entry Two',
category: ['Tech', 'AI'],
guid: 'guid-2',
},
],
}}
/>
);
expect(html).toContain('<icon>https://example.com/icon.png</icon>');
expect(html).toContain('<logo>https://example.com/logo.png</logo>');
expect(html).toContain('media:content');
expect(html).toContain('term="News"');
expect(html).toContain('term="Tech"');
expect(html).toContain('rsshub:upvotes');
expect(html).toContain('rsshub:downvotes');
expect(html).toContain('rsshub:comments');
});
});
describe('RSS view', () => {
it('renders itunes, media, and telegram image variants', () => {
const html = renderToString(
<RSS
data={{
title: 'RSS Feed',
link: 'https://t.me/s/rsshub',
atomlink: 'https://example.com/feed.xml',
description: 'RSS Description',
language: 'en',
lastBuildDate: '2024-01-01T00:00:00Z',
ttl: 60,
itunes_author: 'Podcast Author',
itunes_category: 'Tech',
itunes_explicit: 'true',
image: 'https://example.com/image.jpg',
item: [
{
title: 'Episode One',
link: 'https://example.com/one',
description: 'Episode One',
guid: 'episode-1',
pubDate: '2024-01-01T00:00:00Z',
author: 'Host',
image: 'https://example.com/episode.jpg',
itunes_item_image: 'https://example.com/itunes.jpg',
itunes_duration: '01:02:03',
enclosure_url: 'https://example.com/audio.mp3',
enclosure_length: '123',
enclosure_type: 'audio/mpeg',
category: 'Podcast',
media: {
content: {
url: 'https://example.com/media.mp4',
},
},
},
{
title: 'Episode Two',
link: 'https://example.com/two',
description: 'Episode Two',
category: ['News', 'Updates'],
},
],
}}
/>
);
expect(html).toContain('xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"');
expect(html).toContain('xmlns:media="http://search.yahoo.com/mrss/"');
expect(html).toContain('<itunes:author>Podcast Author</itunes:author>');
expect(html).toContain('itunes:category text="Tech"');
expect(html).toContain('<itunes:explicit>true</itunes:explicit>');
expect(html).toContain('<height>31</height>');
expect(html).toContain('<width>88</width>');
expect(html).toContain('media:content');
expect(html).toContain('<itunes:image href="https://example.com/itunes.jpg"');
expect(html).toContain('<enclosure url="https://example.com/audio.mp3"');
expect(html).toContain('<category>Podcast</category>');
expect(html).toContain('<category>News</category>');
});
});
describe('JSON view', () => {
it('renders summary, authors, tags, attachments, and extras', () => {
const jsonOutput = jsonView({
title: 'JSON Feed',
link: 'https://example.com',
feedLink: 'https://example.com/feed.json',
description: 'JSON Description',
language: 'en',
author: 'Feed Author',
image: 'https://example.com/icon.png',
item: [
{
title: 'Item One',
link: 'https://example.com/one',
description: 'Entry One',
guid: 'guid-1',
content: {
html: '<p>hello</p>',
text: 'hello',
},
image: 'https://example.com/image.jpg',
banner: 'https://example.com/banner.jpg',
pubDate: '2024-01-01T00:00:00Z',
updated: '2024-01-02T00:00:00Z',
author: 'Item Author',
category: ['Tech', 'AI'],
enclosure_url: 'https://example.com/audio.mp3',
enclosure_type: 'audio/mpeg',
enclosure_title: 'Audio Title',
enclosure_length: 123,
itunes_duration: 321,
_extra: { foo: 'bar' },
},
],
});
const feed = JSON.parse(jsonOutput);
expect(feed.version).toBe('https://jsonfeed.org/version/1.1');
expect(feed.title).toBe('JSON Feed');
expect(feed.home_page_url).toBe('https://example.com');
expect(feed.feed_url).toBe('https://example.com/feed.json');
expect(feed.description).toBe('JSON Description - Powered by RSSHub');
expect(feed.authors).toEqual([{ name: 'Feed Author' }]);
expect(feed.items).toHaveLength(1);
expect(feed.items[0]).toMatchObject({
id: 'guid-1',
url: 'https://example.com/one',
title: 'Item One',
content_html: '<p>hello</p>',
content_text: 'hello',
summary: 'Entry One',
image: 'https://example.com/image.jpg',
banner_image: 'https://example.com/banner.jpg',
date_published: '2024-01-01T00:00:00Z',
date_modified: '2024-01-02T00:00:00Z',
authors: [{ name: 'Item Author' }],
tags: ['Tech', 'AI'],
attachments: [
{
url: 'https://example.com/audio.mp3',
mime_type: 'audio/mpeg',
title: 'Audio Title',
size_in_bytes: 123,
duration_in_seconds: 321,
},
],
});
expect(feed.items[0]._extra).toEqual({ foo: 'bar' });
});
});
describe('Index view', () => {
const renderIndex = async (debugInfo: string | undefined, debugQuery: string | undefined) => {
const debugData = {
hitCache: 2,
request: 10,
etag: 3,
error: 1,
routes: {
'/foo': 5,
'/bar': 2,
},
paths: {
'/foo?x=1': 4,
'/bar?x=2': 1,
},
errorRoutes: {
'/error': 2,
'/fail': 1,
},
errorPaths: {
'/error?x=1': 1,
'/fail?x=2': 1,
},
};
vi.doMock('@/config', () => ({
config: {
debugInfo,
disallowRobot: true,
nodeName: 'TestNode',
cache: {
routeExpire: 120,
},
},
}));
vi.doMock('@/utils/debug-info', () => ({
getDebugInfo: () => debugData,
}));
vi.doMock('@/utils/git-hash', () => ({
gitHash: 'abc123',
gitDate: new Date('2020-01-01T00:00:00Z'),
}));
const { default: Index } = await import('@/views/index');
return renderToString(<Index debugQuery={debugQuery} />);
};
it('shows debug info when enabled', async () => {
const html = await renderIndex('secret', 'secret');
expect(html).toContain('Debug Info');
expect(html).toContain('TestNode');
expect(html).toContain('abc123');
expect(html).toContain('5 /foo');
expect(html).toContain('2 /error');
});
it('hides debug info when disabled', async () => {
const html = await renderIndex('false', 'secret');
expect(html).not.toContain('Debug Info');
});
});
-101
View File
@@ -1,101 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
const createDeferred = <T>() => {
const { promise, reject, resolve } = Promise.withResolvers<T>();
return { promise, reject, resolve };
};
const loadWeiboUtils = async ({ pageReady = Promise.resolve() } = {}) => {
vi.resetModules();
const store = new Map<string, string>();
const cache = {
get: vi.fn((key: string) => store.get(key) || null),
has: vi.fn((key: string) => store.has(key)),
set: vi.fn((key: string, value?: string | Record<string, unknown>) => {
store.set(key, typeof value === 'object' ? JSON.stringify(value) : value || '');
}),
tryGet: vi.fn(async (key: string, getValue: () => Promise<string>) => {
const cached = store.get(key);
if (cached) {
return cached;
}
const value = await getValue();
store.set(key, JSON.stringify(value));
return value;
}),
};
const destroy = vi.fn();
const page = {
route: vi.fn((_pattern: string, handler: (route: any) => void) => {
for (const requestUrl of ['https://m.weibo.cn/', 'https://m.weibo.cn/']) {
handler({
abort: vi.fn(),
continue: vi.fn(),
request: () => ({
resourceType: () => 'document',
url: () => requestUrl,
}),
});
}
}),
setExtraHTTPHeaders: vi.fn(),
url: vi.fn(() => 'https://m.weibo.cn/'),
};
const getPlaywrightPage = vi.fn(async (_url: string, options: any) => {
await pageReady;
await options.onBeforeLoad(page);
return { destroy, page };
});
const getCookies = vi.fn(() => Promise.resolve('SUB=mock'));
vi.doMock('@/config', () => ({
config: {
cache: {
contentExpire: 3600,
routeExpire: 300,
},
weibo: {},
},
}));
vi.doMock('@/utils/cache', () => ({ default: cache }));
vi.doMock('@/utils/logger', () => ({
default: {
info: vi.fn(),
warn: vi.fn(),
},
}));
vi.doMock('@/utils/playwright', () => ({ getPlaywrightPage }));
vi.doMock('@/utils/playwright-utils', () => ({ getCookies }));
const { default: weiboUtils } = await import('./routes/weibo/utils');
return {
cache,
getCookies,
getPlaywrightPage,
weiboUtils,
};
};
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
vi.resetModules();
});
describe('weibo utils', () => {
it('shares an in-flight visitor cookie fetch across concurrent callers', async () => {
vi.useFakeTimers();
const pageReady = createDeferred<void>();
const { getPlaywrightPage, weiboUtils } = await loadWeiboUtils({ pageReady: pageReady.promise });
const first = weiboUtils.getCookies();
const second = weiboUtils.getCookies();
pageReady.resolve();
await expect(Promise.all([first, second])).resolves.toEqual(['SUB=mock', 'SUB=mock']);
expect(getPlaywrightPage).toHaveBeenCalledTimes(1);
});
});
+4 -2
View File
@@ -50,12 +50,13 @@
"vercel-build": "npm run build:routes && tsdown --config ./tsdown-vercel.config.ts",
"vitest": "cross-env NODE_ENV=test vitest",
"vitest:coverage": "cross-env NODE_ENV=test vitest --coverage.enabled --reporter=junit",
"vitest:fullroutes": "cross-env NODE_ENV=test FULL_ROUTES_TEST=true vitest --reporter=json --reporter=default --outputFile=\"./assets/build/test-full-routes.json\" routes",
"vitest:fullroutes": "cross-env NODE_ENV=test FULL_ROUTES_TEST=true vitest --reporter=json --reporter=default --outputFile=\"./assets/build/test-full-routes.json\" lib/app.test.ts",
"vitest:watch": "cross-env NODE_ENV=test vitest --watch",
"vitest:workerd": "cross-env NODE_ENV=test vitest run --config vitest.workers.config.ts",
"worker-build": "npm run build:routes:worker && tsdown --config ./tsdown-worker.config.ts",
"worker-deploy": "npm run worker-build && wrangler deploy",
"worker-dev": "npm run worker-build && wrangler dev",
"worker-test": "npm run worker-build && vitest run lib/worker.worker.test.ts"
"worker-test": "npm run worker-build && vitest run lib/worker.test.ts"
},
"dependencies": {
"@bbob/html": "4.3.1",
@@ -147,6 +148,7 @@
"@bbob/types": "4.3.1",
"@cloudflare/containers": "0.3.7",
"@cloudflare/playwright": "1.3.0",
"@cloudflare/vitest-pool-workers": "0.18.4",
"@cloudflare/workers-types": "5.20260710.1",
"@eslint/eslintrc": "3.3.5",
"@eslint/js": "10.0.1",
+36 -1
View File
@@ -293,6 +293,9 @@ importers:
'@cloudflare/playwright':
specifier: 1.3.0
version: 1.3.0
'@cloudflare/vitest-pool-workers':
specifier: 0.18.4
version: 0.18.4(@cloudflare/workers-types@5.20260710.1)(@vitest/runner@4.1.10)(@vitest/snapshot@4.1.10)(bufferutil@4.1.0)(utf-8-validate@5.0.10)(vitest@4.1.10)
'@cloudflare/workers-types':
specifier: 5.20260710.1
version: 5.20260710.1
@@ -601,6 +604,13 @@ packages:
workerd:
optional: true
'@cloudflare/vitest-pool-workers@0.18.4':
resolution: {integrity: sha512-jOXvyLoR2b8jFvo3tX+mWxXXwcZ+PbId3d7vGFtZsuKakmDjKSeIq4o/sQjkqNv6q3XacIKSCAvfM8TfkPyrEw==}
peerDependencies:
'@vitest/runner': ^4.1.0
'@vitest/snapshot': ^4.1.0
vitest: ^4.1.0
'@cloudflare/workerd-darwin-64@1.20260708.1':
resolution: {integrity: sha512-HXFCvhS1wpg3uXO0CLUwmwC41i2loM5FSK69EUchOBpmYBAXxT1oHLm6EOA5lqhTk5Mu9kjRiQYxa1GwKPwfJg==}
engines: {node: '>=16'}
@@ -3342,6 +3352,9 @@ packages:
city-timezones@1.3.4:
resolution: {integrity: sha512-yLmtCxU4y5HLAw9XGIMcGEXO+R2KH1sb595wEQC/E9BxSDpazCD7v9ZQRySO7367IXWsWqt3z2xFVh3OkZdgEQ==}
cjs-module-lexer@1.2.3:
resolution: {integrity: sha512-0TNiGstbQmCFwt4akjjBg5pLRTSyj/PkWQ1ZoO2zntmg9yLqSRxwEa4iCfQLGjqhiqBfOJa7W/E8wfGrTDmlZQ==}
cjs-module-lexer@2.2.0:
resolution: {integrity: sha512-4bHTS2YuzUvtoLjdy+98ykbNB5jS0+07EvFNXerqZQJ89F7DI6ET7OQo/HJuW6K0aVsKA9hj9/RVb2kQVOrPDQ==}
@@ -3593,7 +3606,7 @@ packages:
engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}
difflib@https://codeload.github.com/postlight/difflib.js/tar.gz/32e8e38c7fcd935241b9baab71bb432fd9b166ed:
resolution: {gitHosted: true, tarball: https://codeload.github.com/postlight/difflib.js/tar.gz/32e8e38c7fcd935241b9baab71bb432fd9b166ed}
resolution: {tarball: https://codeload.github.com/postlight/difflib.js/tar.gz/32e8e38c7fcd935241b9baab71bb432fd9b166ed}
version: 0.2.6
discord-api-types@0.38.49:
@@ -6349,6 +6362,9 @@ packages:
yuku-parser@0.5.44:
resolution: {integrity: sha512-mAhpQZ/bXjxZmKiGUqEWskC9mZTcTBv6/fdzVdzdjM6XuD1DP3IavdLVWdM39L9ewK9vS9OtJmaKNeWgRzpy0w==}
zod@3.25.76:
resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==}
zod@4.4.3:
resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==}
@@ -6514,6 +6530,21 @@ snapshots:
optionalDependencies:
workerd: 1.20260708.1
'@cloudflare/vitest-pool-workers@0.18.4(@cloudflare/workers-types@5.20260710.1)(@vitest/runner@4.1.10)(@vitest/snapshot@4.1.10)(bufferutil@4.1.0)(utf-8-validate@5.0.10)(vitest@4.1.10)':
dependencies:
'@vitest/runner': 4.1.10
'@vitest/snapshot': 4.1.10
cjs-module-lexer: 1.2.3
esbuild: 0.28.1
miniflare: 4.20260708.1(bufferutil@4.1.0)(utf-8-validate@5.0.10)
vitest: 4.1.10(@edge-runtime/vm@3.2.0)(@opentelemetry/api@1.9.1)(@types/node@26.1.1)(@vitest/coverage-v8@4.1.10)(jsdom@29.1.1(@noble/hashes@2.2.0))(msw@2.15.0(@types/node@26.1.1)(@typescript/typescript6@6.0.2))(vite@7.3.1(@types/node@26.1.1)(jiti@2.6.1)(tsx@4.23.0)(yaml@2.9.0))
wrangler: 4.110.0(@cloudflare/workers-types@5.20260710.1)(bufferutil@4.1.0)(utf-8-validate@5.0.10)
zod: 3.25.76
transitivePeerDependencies:
- '@cloudflare/workers-types'
- bufferutil
- utf-8-validate
'@cloudflare/workerd-darwin-64@1.20260708.1':
optional: true
@@ -8632,6 +8663,8 @@ snapshots:
city-timezones@1.3.4: {}
cjs-module-lexer@1.2.3: {}
cjs-module-lexer@2.2.0: {}
class-transformer@0.3.1: {}
@@ -12113,6 +12146,8 @@ snapshots:
'@yuku-parser/binding-win32-arm64': 0.5.44
'@yuku-parser/binding-win32-x64': 0.5.44
zod@3.25.76: {}
zod@4.4.3: {}
zwitch@2.0.4: {}
+6
View File
@@ -6,9 +6,15 @@ import toSource from 'tosource';
import type { RadarItem } from '../../lib/types';
import { getCurrentPath } from '../../lib/utils/helpers';
import { findOrphanFiles } from './check-orphan-files';
const __dirname = getCurrentPath(import.meta.url);
const orphanTests = await findOrphanFiles();
if (orphanTests.length) {
throw new Error(`Test files without a corresponding source file:\n${orphanTests.join('\n')}`);
}
// Check if building for Worker environment
const isWorkerBuild = process.env.WORKER_BUILD === 'true';
+40
View File
@@ -0,0 +1,40 @@
import fs from 'node:fs/promises';
import path from 'node:path';
import { getCurrentPath } from '../../lib/utils/helpers';
const __dirname = getCurrentPath(import.meta.url);
const repoRoot = path.join(__dirname, '../..');
const fileExists = async (filePath: string) => {
try {
await fs.access(filePath);
return true;
} catch {
return false;
}
};
export const findOrphanFiles = async (): Promise<string[]> => {
const excludedDirs = ['lib/routes', 'lib/routes-deprecated'].map((dir) => path.join(repoRoot, dir) + path.sep);
const entries = await fs.readdir(path.join(repoRoot, 'lib'), { recursive: true, withFileTypes: true });
const candidates = entries
.filter((entry) => excludedDirs.every((dir) => !`${entry.parentPath}${path.sep}`.startsWith(dir)))
.filter((entry) => entry.isFile() && /\.test\.tsx?$/.test(entry.name))
.map((entry) => {
const absolute = path.join(entry.parentPath, entry.name);
return { absolute, relative: path.relative(repoRoot, absolute).replaceAll('\\', '/') };
})
.filter(({ relative }) => relative !== 'lib/setup.test.ts');
const orphans = await Promise.all(
candidates.map(async ({ absolute, relative }) => {
const base = absolute.replace(/\.test\.tsx?$/, '');
const [tsExists, tsxExists] = await Promise.all([fileExists(`${base}.ts`), fileExists(`${base}.tsx`)]);
return tsExists || tsxExists ? null : relative;
})
);
return orphans.filter((relative) => relative !== null).toSorted((a, b) => a.localeCompare(b));
};
+1 -1
View File
@@ -11,6 +11,6 @@ export default defineConfig({
},
testTimeout: 10000,
setupFiles: ['./lib/setup.test.ts'],
exclude: [...configDefaults.exclude, './lib/setup.test.ts'],
exclude: [...configDefaults.exclude, './lib/setup.test.ts', '**/*.worker.test.ts'],
},
});
+75
View File
@@ -0,0 +1,75 @@
import fs from 'node:fs';
import path from 'node:path';
import { cloudflareTest } from '@cloudflare/vitest-pool-workers';
import type { Plugin } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';
import { defineConfig } from 'vitest/config';
// Resolve .worker.ts files instead of .ts files, same as tsdown-worker.config.ts
function workerAliasPlugin(): Plugin {
return {
name: 'worker-alias',
enforce: 'pre',
resolveId(source, importer) {
// Skip if no importer (entry point) or already a .worker file
if (!importer || source.includes('.worker')) {
return null;
}
// Handle relative imports
if (source.startsWith('.')) {
const importerDir = path.dirname(importer);
const resolved = path.resolve(importerDir, source);
for (const ext of ['.worker.ts', '.worker.tsx']) {
const workerPath = resolved + ext;
if (fs.existsSync(workerPath)) {
return workerPath;
}
const withoutExt = resolved.replace(/\.(ts|tsx)$/, '');
const workerPathAlt = withoutExt + ext;
if (fs.existsSync(workerPathAlt)) {
return workerPathAlt;
}
}
}
// Handle @/ alias imports
if (source.startsWith('@/')) {
const libPath = path.resolve('./lib', source.slice(2));
for (const ext of ['.worker.ts', '.worker.tsx']) {
const workerPath = libPath + ext;
if (fs.existsSync(workerPath)) {
return workerPath;
}
}
}
return null;
},
};
}
export default defineConfig({
plugins: [
cloudflareTest({
miniflare: {
compatibilityDate: '2025-06-17',
compatibilityFlags: ['nodejs_compat'],
kvNamespaces: ['CACHE'],
},
}),
workerAliasPlugin(),
tsconfigPaths({ root: '.' }),
],
resolve: {
alias: {
'dotenv/config': path.resolve('./lib/shims/dotenv-config.ts'),
},
},
test: {
include: ['lib/**/*.worker.test.ts'],
},
});