feat(tests): add comprehensive unit tests for various utility functions and views (#20779)

* feat(tests): add comprehensive unit tests for various utility functions and views

- Implement tests for cache utility to ensure proper behavior with no cache and TTL keys.
- Add tests for common utilities including string manipulation and path handling.
- Introduce tests for directory import functionality to validate file imports and pattern matching.
- Create tests for git hash retrieval to handle fallback scenarios.
- Develop tests for deprecated got utility to verify response handling and retry logic.
- Enhance got utility tests to include request hooks and search parameter handling.
- Mock header generator tests to validate user agent handling.
- Expand helpers tests to cover current path retrieval and duration parsing.
- Implement tests for ofetch utility to ensure proper proxy handling and logging.
- Add OpenTelemetry metric tests to validate metric serialization.
- Create proxy tests to verify multi-proxy selection and failure handling.
- Introduce request rewriter tests to validate fetch and get wrapper functionality.
- Add timezone utility tests to handle various input types.
- Implement view tests for Atom and RSS rendering to ensure correct output.
- Create index view tests to validate debug information display based on configuration.

* refactor: remove deprecated got implementation and associated tests

* test: expand coverage for api, middleware, and utils
This commit is contained in:
DIYgod
2025-12-29 17:34:48 +08:00
committed by GitHub
parent 626626a394
commit 81ff849337
54 changed files with 2550 additions and 261 deletions
+75
View File
@@ -0,0 +1,75 @@
import { describe, expect, it } from 'vitest';
import { handler, route } from '@/api/category/one';
import { namespaces } from '@/registry';
const createCtx = (param: Record<string, string>, query: Record<string, any> = {}) =>
({
req: {
valid: (type: string) => (type === 'param' ? param : query),
},
json: (data: unknown) => data,
}) as any;
const findCategory = (requireLang = false) => {
for (const [namespace, data] of Object.entries(namespaces)) {
for (const route of Object.values(data.routes)) {
const categories = route.categories || [];
if (categories.length > 0) {
if (requireLang && !data.lang) {
continue;
}
return { namespace, categories, lang: data.lang };
}
}
}
throw new Error('No categories found in registry data');
};
describe('api/category/one', () => {
it('returns namespaces that match a category', () => {
const { categories } = findCategory();
const category = categories[0];
const result = handler(createCtx({ category }, {}));
expect(Object.keys(result)).not.toHaveLength(0);
for (const namespace of Object.values(result)) {
for (const route of Object.values((namespace as { routes: Record<string, { categories?: string[] }> }).routes)) {
expect(route.categories || []).toContain(category);
}
}
});
it('intersects categories and filters by lang', () => {
const { namespace, categories, lang } = findCategory(true);
const [primary, secondary] = categories.length > 1 ? categories : [categories[0], categories[0]];
const selectedLang = lang || namespaces[namespace].lang;
const result = handler(
createCtx(
{ category: primary },
{
categories: [secondary],
lang: selectedLang,
}
)
);
expect(Object.keys(result)).toContain(namespace);
for (const ns of Object.values(result)) {
expect((ns as { lang?: string }).lang).toBe(selectedLang);
}
});
it('parses categories query string into array', () => {
const parsed = route.request?.query?.parse({ categories: 'a,b', lang: 'en' });
expect(parsed?.categories).toEqual(['a', 'b']);
expect(parsed?.lang).toBe('en');
});
it('returns empty result for unknown categories', () => {
const result = handler(createCtx({ category: 'rsshub-unknown-category' }, {}));
expect(result).toEqual({});
});
});
+33
View File
@@ -0,0 +1,33 @@
import { describe, expect, it, vi } from 'vitest';
describe('api/follow/config', () => {
it('returns follow config payload', async () => {
process.env.FOLLOW_OWNER_USER_ID = 'owner';
process.env.FOLLOW_DESCRIPTION = 'desc';
process.env.FOLLOW_PRICE = '123';
process.env.FOLLOW_USER_LIMIT = '10';
vi.resetModules();
const { handler } = await import('@/api/follow/config');
const ctx = {
json: (data: unknown) => data,
};
const result = handler(ctx as any) as Record<string, unknown>;
expect(result).toMatchObject({
ownerUserId: 'owner',
description: 'desc',
price: 123,
userLimit: 10,
});
expect(typeof result.cacheTime).toBe('number');
expect(typeof result.gitHash).toBe('string');
delete process.env.FOLLOW_OWNER_USER_ID;
delete process.env.FOLLOW_DESCRIPTION;
delete process.env.FOLLOW_PRICE;
delete process.env.FOLLOW_USER_LIMIT;
});
});
+14
View File
@@ -0,0 +1,14 @@
import { describe, expect, it } from 'vitest';
import api from '@/api';
describe('api index', () => {
it('serves openapi document', async () => {
const response = await api.request('/openapi.json');
expect(response.status).toBe(200);
const data = await response.json();
expect(data.openapi).toBe('3.1.0');
expect(data.info?.title).toBe('RSSHub API');
});
});
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest';
import { handler as allHandler } from '@/api/namespace/all';
import { handler as oneHandler } from '@/api/namespace/one';
import { namespaces } from '@/registry';
const createCtx = (param: Record<string, string> = {}) =>
({
req: {
valid: () => param,
},
json: (data: unknown) => data,
}) as any;
describe('api/namespace', () => {
it('returns all namespaces', () => {
const result = allHandler(createCtx());
expect(result).toBe(namespaces);
});
it('returns a single namespace', () => {
const result = oneHandler(createCtx({ namespace: 'test' }));
expect(result).toBe(namespaces.test);
});
});
+13
View File
@@ -0,0 +1,13 @@
import { describe, expect, it } from 'vitest';
import api from '@/api';
describe('api/radar/rules/all', () => {
it('returns radar rules payload', async () => {
const response = await api.request('/radar/rules');
expect(response.status).toBe(200);
const data = await response.json();
expect(typeof data).toBe('object');
});
});
+20
View File
@@ -0,0 +1,20 @@
import { describe, expect, it, vi } from 'vitest';
import { handler } from '@/api/radar/rules/one';
describe('api/radar/rules/one', () => {
it('returns radar data for a domain param', () => {
const ctx = {
req: {
valid: vi.fn(() => ({ domain: 'unknown.invalid' })),
},
json: vi.fn((value) => value),
};
const result = handler(ctx as any);
expect(ctx.req.valid).toHaveBeenCalledWith('param');
expect(ctx.json).toHaveBeenCalledWith(undefined);
expect(result).toBeUndefined();
});
});
+26
View File
@@ -0,0 +1,26 @@
import { describe, expect, it, vi } from 'vitest';
const errorSpy = vi.fn();
vi.mock('@/utils/logger', () => ({
default: {
error: errorSpy,
},
}));
describe('app-bootstrap', () => {
it('logs uncaught exceptions', async () => {
const before = new Set(process.listeners('uncaughtException'));
await import('@/app-bootstrap');
const after = process.listeners('uncaughtException');
const listener = after.find((fn) => !before.has(fn));
expect(listener).toBeDefined();
listener?.(new Error('boom'));
expect(errorSpy).toHaveBeenCalled();
if (listener) {
process.removeListener('uncaughtException', listener);
}
});
});
+52
View File
@@ -0,0 +1,52 @@
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;
});
});
+4 -2
View File
@@ -93,7 +93,9 @@ describe('config', () => {
process.env.REMOTE_CONFIG = 'http://rsshub.test/config';
const { config } = await import('./config');
await new Promise((resolve) => setTimeout(resolve, 100));
expect(config.ua).toBe('test');
await vi.waitFor(() => {
expect(config.ua).toBe('test');
});
delete process.env.REMOTE_CONFIG;
});
});
+13
View File
@@ -0,0 +1,13 @@
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');
});
it('exports server entrypoint', async () => {
const server = (await import('@/server')).default;
expect(typeof server.request).toBe('function');
});
});
+57
View File
@@ -0,0 +1,57 @@
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;
});
});
+96
View File
@@ -0,0 +1,96 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
const serve = vi.fn(() => ({ close: vi.fn() }));
const logger = {
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn(),
http: vi.fn(),
};
const fork = vi.fn();
const clusterState = { isPrimary: true };
const clusterMock = {
get isPrimary() {
return clusterState.isPrimary;
},
fork,
};
const availableParallelism = vi.fn(() => 2);
vi.mock('@hono/node-server', () => ({
serve,
}));
vi.mock('@/utils/logger', () => ({
default: logger,
}));
vi.mock('@/utils/common-utils', () => ({
getLocalhostAddress: () => ['192.0.2.1'],
}));
vi.mock('@/app', () => ({
default: { fetch: vi.fn() },
}));
vi.mock('node:cluster', () => ({
__esModule: true,
default: clusterMock,
}));
vi.mock('node:os', () => ({
__esModule: true,
default: {
availableParallelism,
},
}));
describe('index', () => {
afterEach(() => {
vi.resetModules();
vi.unstubAllEnvs();
serve.mockClear();
fork.mockClear();
availableParallelism.mockClear();
logger.info.mockClear();
clusterState.isPrimary = true;
});
it('starts a server when cluster is disabled', async () => {
vi.stubEnv('ENABLE_CLUSTER', '');
vi.stubEnv('LISTEN_INADDR_ANY', '');
vi.stubEnv('PORT', '12345');
const module = await import('@/index');
expect(module.default).toBeDefined();
expect(serve).toHaveBeenCalledTimes(1);
expect(serve.mock.calls[0][0]).toMatchObject({
hostname: '127.0.0.1',
port: 12345,
});
});
it('forks workers when cluster is enabled and primary', async () => {
clusterState.isPrimary = true;
vi.stubEnv('ENABLE_CLUSTER', 'true');
vi.stubEnv('LISTEN_INADDR_ANY', 'true');
vi.stubEnv('PORT', '12346');
availableParallelism.mockReturnValue(2);
await import('@/index');
expect(fork).toHaveBeenCalledTimes(2);
expect(serve).not.toHaveBeenCalled();
});
it('starts a worker server when cluster is enabled and not primary', async () => {
clusterState.isPrimary = false;
vi.stubEnv('ENABLE_CLUSTER', 'true');
vi.stubEnv('LISTEN_INADDR_ANY', '');
vi.stubEnv('PORT', '12347');
await import('@/index');
expect(serve).toHaveBeenCalledTimes(1);
expect(serve.mock.calls[0][0]).toMatchObject({
hostname: '127.0.0.1',
port: 12347,
});
});
});
+63
View File
@@ -0,0 +1,63 @@
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;
});
});
+49
View File
@@ -0,0 +1,49 @@
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,
},
},
}));
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);
});
});
+2 -2
View File
@@ -145,8 +145,8 @@ describe('cache', () => {
process.env.REDIS_URL = 'redis://wrongpath:6379';
await noCacheTestFunc();
const cache = (await import('@/utils/cache')).default;
await cache.clients.redisClient!.quit();
});
cache.clients.redisClient?.disconnect();
}, 20000);
it('no cache', async () => {
process.env.CACHE_TYPE = 'NO';
+2 -3
View File
@@ -37,9 +37,8 @@ const middleware: MiddlewareHandler = async (ctx, next) => {
return;
}
const lastBuildDate = data.lastBuildDate;
delete data.lastBuildDate;
const etag = etagCalculate(JSON.stringify(data));
const { lastBuildDate, ...etagData } = data;
const etag = etagCalculate(JSON.stringify(etagData));
ctx.header('ETag', etag);
+157
View File
@@ -0,0 +1,157 @@
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;
});
});
+85
View File
@@ -0,0 +1,85 @@
import { describe, expect, it, vi } from 'vitest';
class FakeRE2 {
static CASE_INSENSITIVE = 1;
private pattern: string;
constructor(pattern: string) {
this.pattern = pattern;
}
static compile(pattern: string) {
return new FakeRE2(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;
});
});
+69
View File
@@ -0,0 +1,69 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
type Scope = { setTag: ReturnType<typeof vi.fn> };
afterEach(() => {
vi.resetModules();
vi.restoreAllMocks();
vi.unmock('@/config');
vi.unmock('@/utils/helpers');
vi.unmock('@/utils/logger');
vi.unmock('@sentry/node');
});
describe('sentry middleware', () => {
const loadMiddleware = async () => {
const scope: Scope = { setTag: vi.fn() };
const sentry = {
init: vi.fn(),
getCurrentScope: vi.fn(() => scope),
withScope: vi.fn((cb: (scope: Scope) => void) => cb(scope)),
captureException: vi.fn(),
};
const logger = {
info: vi.fn(),
};
const getRouteNameFromPath = vi.fn((path: string) => `route:${path}`);
vi.doMock('@sentry/node', () => sentry);
vi.doMock('@/utils/logger', () => ({
default: logger,
}));
vi.doMock('@/utils/helpers', () => ({
getRouteNameFromPath,
}));
vi.doMock('@/config', () => ({
config: {
sentry: {
dsn: 'https://sentry.example/123',
routeTimeout: 50,
},
nodeName: 'node-a',
},
}));
const { default: middleware } = await import('@/middleware/sentry');
return { middleware, sentry, logger, scope, getRouteNameFromPath };
};
it('initializes sentry and captures slow routes', async () => {
const { middleware, sentry, logger, scope, getRouteNameFromPath } = await loadMiddleware();
expect(sentry.init).toHaveBeenCalledWith({
dsn: 'https://sentry.example/123',
});
expect(sentry.getCurrentScope).toHaveBeenCalledTimes(1);
expect(scope.setTag).toHaveBeenCalledWith('node_name', 'node-a');
expect(logger.info).toHaveBeenCalledWith('Sentry inited.');
const nowSpy = vi.spyOn(Date, 'now');
nowSpy.mockReturnValueOnce(0).mockReturnValueOnce(100);
await middleware({ req: { path: '/test/slow' } } as any, async () => {});
expect(getRouteNameFromPath).toHaveBeenCalledWith('/test/slow');
expect(scope.setTag).toHaveBeenCalledWith('name', 'route:/test/slow');
expect(sentry.captureException).toHaveBeenCalledTimes(1);
});
});
+114 -98
View File
@@ -1,126 +1,142 @@
import Parser from 'rss-parser';
import { describe, expect, it } from 'vitest';
import { describe, expect, it, vi } from 'vitest';
import app from '@/app';
import { config } from '@/config';
import template from '@/middleware/template';
const parser = new Parser();
const createCtx = (query: Record<string, string | undefined>, data: any, extra: Record<string, unknown> = {}) => {
const store = new Map<string, unknown>([['data', data], ...Object.entries(extra)]);
return {
req: {
query: (key: string) => query[key],
url: 'http://localhost/rss',
},
get: (key: string) => store.get(key),
set: (key: string, value: unknown) => store.set(key, value),
json: vi.fn((payload) => payload),
html: vi.fn((payload) => payload),
render: vi.fn((payload) => payload),
body: vi.fn((payload) => payload),
redirect: vi.fn((url: string, status: number) => ({ url, status })),
header: vi.fn(),
res: { headers: new Headers() },
};
};
describe('template', () => {
const expectPubDate = new Date(1_546_272_000_000 - 10 * 1000);
describe('template middleware', () => {
it('returns debug json when requested', async () => {
const originalDebug = config.debugInfo;
config.debugInfo = true;
it(`.rss`, async () => {
const response1 = await app.request('/test/1?format=rss');
const parsed1 = await parser.parseString(await response1.text());
const ctx = createCtx({ format: 'debug.json' }, { item: [] }, { json: { ok: true } });
const result = await template(ctx as any, async () => {});
expect(parsed1).toEqual(expect.any(Object));
expect(parsed1.title).toEqual(expect.any(String));
expect(parsed1.description).toEqual(expect.any(String));
expect(parsed1.link).toEqual(expect.any(String));
expect(parsed1.lastBuildDate).toEqual(expect.any(String));
expect(parsed1.ttl).toEqual(expect.any(String));
expect(parsed1.items).toEqual(expect.any(Array));
expect(result).toEqual({ ok: true });
expect(ctx.json).toHaveBeenCalled();
expect(parsed1.items[0]).toEqual(expect.any(Object));
expect(parsed1.items[0].title).toEqual(expect.any(String));
expect(parsed1.items[0].link).toEqual(expect.any(String));
expect(parsed1.items[0].pubDate).toBe(expectPubDate.toUTCString());
expect(parsed1.items[0].author).toEqual(expect.any(String));
expect(parsed1.items[0].content).toEqual(expect.any(String));
expect(parsed1.items[0].guid).toEqual(expect.any(String));
const response2 = await app.request('/test/1');
const parsed2 = await parser.parseString(await response2.text());
delete parsed1.lastBuildDate;
delete parsed2.lastBuildDate;
delete parsed1.feedUrl;
delete parsed2.feedUrl;
delete parsed1.paginationLinks;
delete parsed2.paginationLinks;
expect(parsed2).toMatchObject(parsed1);
config.debugInfo = originalDebug;
});
it(`.atom`, async () => {
const response = await app.request('/test/1?format=atom');
const parsed = await parser.parseString(await response.text());
it('returns api data without rendering', async () => {
const ctx = createCtx({}, null, { apiData: { ok: true } });
const result = await template(ctx as any, async () => {});
expect(parsed).toEqual(expect.any(Object));
expect(parsed.title).toEqual(expect.any(String));
expect(parsed.link).toEqual(expect.any(String));
expect(parsed.lastBuildDate).toEqual(expect.any(String));
expect(parsed.items).toEqual(expect.any(Array));
expect(parsed.items[0]).toEqual(expect.any(Object));
expect(parsed.items[0].title).toEqual(expect.any(String));
expect(parsed.items[0].link).toEqual(expect.any(String));
expect(parsed.items[0].pubDate).toBe(expectPubDate.toISOString());
expect(parsed.items[0].author).toEqual(expect.any(String));
expect(parsed.items[0].content).toEqual(expect.any(String));
expect(parsed.items[0].id).toEqual(expect.any(String));
expect(result).toEqual({ ok: true });
expect(ctx.json).toHaveBeenCalledWith({ ok: true });
});
it(`.json`, async () => {
const jsonResponse = await app.request('/test/1?format=json');
const rssResponse = await app.request('/test/1?format=rss');
const jsonParsed = JSON.parse(await jsonResponse.text());
const rssParsed = await parser.parseString(await rssResponse.text());
it('renders debug html snippet when requested', async () => {
const originalDebug = config.debugInfo;
config.debugInfo = true;
expect(jsonResponse.headers.get('content-type')).toBe('application/feed+json; charset=UTF-8');
const ctx = createCtx({ format: '0.debug.html' }, { item: [{ description: 'Hello' }] });
const result = await template(ctx as any, async () => {});
expect(jsonParsed.items[0].title).toEqual(rssParsed.items[0].title);
expect(jsonParsed.items[0].url).toEqual(rssParsed.items[0].link);
expect(jsonParsed.items[0].id).toEqual(rssParsed.items[0].guid);
expect(jsonParsed.items[0].date_published).toEqual(expectPubDate.toISOString());
expect(jsonParsed.items[0].content_html).toEqual(rssParsed.items[0].content);
expect(jsonParsed.items[0].authors[0].name).toEqual(rssParsed.items[0].author);
expect(jsonParsed.items.every((item) => item.authors.every((author) => author.name.includes(' ')))).toBe(false);
expect(result).toBe('Hello');
expect(ctx.html).toHaveBeenCalled();
config.debugInfo = originalDebug;
});
it('.debug.html', async () => {
const jsonResponse = await app.request('/test/1?format=json');
const jsonParsed = JSON.parse(await jsonResponse.text());
it('trims long titles and normalizes authors', async () => {
const originalLimit = config.titleLengthLimit;
config.titleLengthLimit = 3;
const debugHTMLResponse0 = await app.request('/test/1?format=0.debug.html');
expect(debugHTMLResponse0.headers.get('content-type')).toBe('text/html; charset=UTF-8');
expect(await debugHTMLResponse0.text()).toBe(jsonParsed.items[0].content_html);
const data = {
title: 'Feed',
item: [
{
title: 'ABCDE',
author: [{ name: ' Alice ' }, { name: 'Bob ' }],
itunes_duration: '65',
},
],
};
const ctx = createCtx({ format: 'rss' }, data);
await template(ctx as any, async () => {});
const debugHTMLResponseNotExist = await app.request(`/test/1?format=${jsonParsed.items.length}.debug.html`);
expect(await debugHTMLResponseNotExist.text()).toBe(`data.item[${jsonParsed.items.length}].description not found`);
expect(data.item[0].title).toBe('ABC...');
expect(data.item[0].author).toBe('Alice, Bob');
expect(data.item[0].itunes_duration).toBe('0:01:05');
config.titleLengthLimit = originalLimit;
});
it('flatten author object', async () => {
const response = await app.request('/test/json');
const parsed = await parser.parseString(await response.text());
expect(parsed.items[2].author).toBe(['DIYgod1', 'DIYgod2'].map((name) => name).join(', '));
expect(parsed.items[3].author).toBe(['DIYgod3', 'DIYgod4', 'DIYgod5'].map((name) => name).join(', '));
expect(parsed.items[4].author).toBeUndefined();
it('clears invalid dates for non-rss formats', async () => {
const data = {
title: 'Test',
item: [
{
title: 'Item',
pubDate: 'invalid-date',
updated: 'invalid-updated',
},
],
};
const ctx = createCtx({ format: 'json' }, data);
await template(ctx as any, async () => {});
expect(data.item[0].pubDate).toBe('');
expect(data.item[0].updated).toBe('');
});
it(`long title`, async () => {
const response = await app.request('/test/long');
const parsed = await parser.parseString(await response.text());
expect(parsed.items[0].title?.length).toBe(153);
it('returns redirect response when redirect is set', async () => {
const ctx = createCtx({}, { item: [] }, { redirect: 'https://example.com' });
const result = await template(ctx as any, async () => {});
expect(result).toEqual({ url: 'https://example.com', status: 301 });
expect(ctx.redirect).toHaveBeenCalledWith('https://example.com', 301);
});
it(`enclosure`, async () => {
const response = await app.request('/test/enclosure');
const parsed = await parser.parseString(await response.text());
expect(parsed.itunes?.author).toBe('DIYgod');
expect(parsed.items[0].enclosure?.url).toBe('https://github.com/DIYgod/RSSHub/issues/1');
expect(parsed.items[0].enclosure?.length).toBe('3661');
expect(parsed.items[0].itunes.duration).toBe('10:10:10');
it('renders rss3 output', async () => {
const data = {
title: 'Test',
item: [
{
title: 'Item',
link: 'https://example.com/item',
},
],
};
const ctx = createCtx({ format: 'rss3' }, data);
const result = await template(ctx as any, async () => {});
expect(ctx.json).toHaveBeenCalled();
expect(result).toHaveProperty('data');
});
it(`redirect`, async () => {
const response = await app.request('/test/redirect');
expect(response.status).toBe(301);
expect(response.headers.get('location')).toBe('/test/1');
});
it('renders atom output', async () => {
const data = {
title: 'Test',
item: [
{
title: 'Item',
link: 'https://example.com/item',
},
],
};
const ctx = createCtx({ format: 'atom' }, data);
await template(ctx as any, async () => {});
it(`api`, async () => {
const response = await app.request('/api/test');
expect(response.status).toBe(200);
expect(await response.json()).toEqual({
code: 0,
});
expect(ctx.render).toHaveBeenCalled();
});
});
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, it } from 'vitest';
import { config } from '@/config';
import trace from '@/middleware/trace';
describe('trace middleware', () => {
it('skips tracing when debugInfo is disabled', async () => {
const originalDebug = config.debugInfo;
config.debugInfo = false;
let called = false;
const ctx = {
req: {
method: 'GET',
raw: new Request('http://localhost/test'),
},
};
const next = () => {
called = true;
};
await trace(ctx as any, next);
expect(called).toBe(true);
config.debugInfo = originalDebug;
});
});
+71 -3
View File
@@ -1,9 +1,22 @@
import { describe, expect, it } from 'vitest';
import { init, request } from './pkg';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
describe('pkg', () => {
beforeEach(() => {
vi.resetModules();
});
afterEach(() => {
delete process.env.IS_PACKAGE;
delete process.env.UA;
});
it('requires init before request', async () => {
const { request } = await import('./pkg');
await expect(request('/test/1')).rejects.toThrow('RSSHub not initialized. Please call init() first.');
});
it('config', async () => {
const { init } = await import('./pkg');
await init({
UA: 'mock',
});
@@ -12,6 +25,8 @@ describe('pkg', () => {
});
it('request', async () => {
const { init, request } = await import('./pkg');
await init();
const data = await request('/test/1');
expect(data).toMatchObject({
atomlink: 'http://localhost/test/1',
@@ -61,9 +76,62 @@ describe('pkg', () => {
it('error', async () => {
try {
const { init, request } = await import('./pkg');
await init();
await request('/test/error');
} catch (error) {
expect(error).toBe('Error test');
}
});
it('registerRoute adds custom routes and namespaces', async () => {
const { init, registerRoute, request } = await import('./pkg');
await init();
await registerRoute(
'custom',
{
path: '/hello',
name: 'Custom Hello',
handler: () => ({
title: 'Custom',
link: 'https://example.com',
item: [
{
title: 'Entry',
link: 'https://example.com/entry',
},
],
allowEmpty: true,
}),
},
{
name: 'Custom Namespace',
url: 'https://example.com',
lang: 'en',
}
);
const data = await request('/custom/hello');
expect(data.title).toBe('Custom');
const { namespaces } = await import('./registry');
expect(namespaces.custom?.name).toBe('Custom Namespace');
expect(namespaces.custom?.routes['/hello']).toBeDefined();
});
it('registerRoute supports handlers that return Response', async () => {
const { init, registerRoute } = await import('./pkg');
await init();
await registerRoute('custom-response', {
path: '/hello',
name: 'Custom Response',
handler: () => new Response('ok'),
});
const app = (await import('@/app')).default;
const response = await app.request('/custom-response/hello');
expect(await response.text()).toBe('ok');
});
});
+127
View File
@@ -0,0 +1,127 @@
import { Hono } from 'hono';
import { describe, expect, it, vi } from 'vitest';
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('builds namespaces from directory import and resolves module handlers', async () => {
const originalEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'development';
const modules = {
'/nsEmpty/namespace.ts': {
namespace: {
name: 'Empty',
routes: null,
},
},
'/nsRoute/route-array.ts': {
route: {
path: ['/a', '/b'],
name: 'Array',
},
},
'/nsRoute/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-array.ts': {
apiRoute: {
path: ['/a1', '/a2'],
name: 'ApiArray',
handler: () => ({ ok: true }),
},
},
'/nsApi/api-single.ts': {
apiRoute: {
path: '/single',
name: 'ApiSingle',
handler: () => ({ ok: true }),
},
},
'/nsApi/api-module.ts': {
apiRoute: {
path: '/module',
name: 'ApiModule',
module: () =>
Promise.resolve({
apiRoute: {
handler: () => ({ ok: true }),
},
}),
},
},
'/test/api-index.ts': {
apiRoute: {
path: '/',
name: 'ApiIndex',
},
},
};
const directoryImportMock = vi.fn(() => modules);
vi.doMock('@/utils/directory-import', () => ({
directoryImport: directoryImportMock,
}));
vi.resetModules();
const { namespaces, default: registry } = await import('@/registry');
expect(directoryImportMock).toHaveBeenCalled();
expect(namespaces.nsRoute.routes['/single']).toBeDefined();
expect(namespaces.nsApi.apiRoutes['/single']).toBeDefined();
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);
const routeResponse = await app.request('/nsModule/module');
expect(await routeResponse.text()).toBe('module');
await app.request('/api/nsApi/module');
process.env.NODE_ENV = 'test';
const apiTestResponse = await app.request('/api/test');
expect(await apiTestResponse.json()).toEqual({ code: 0 });
process.env.NODE_ENV = originalEnv;
});
});
+7 -1
View File
@@ -44,6 +44,9 @@ describe('registry', () => {
vi.stubEnv('DISABLE_NSFW', 'true');
const { namespaces } = await import('./registry');
const routesModule = await import('../assets/build/routes.json');
const rawNamespaces = (routesModule.default ?? routesModule) as Record<string, { routes?: Record<string, { features?: { nsfw?: boolean } }> }>;
const nsfwNamespaces = Object.entries(rawNamespaces).filter(([, namespace]) => Object.values(namespace.routes ?? {}).some((route) => route.features?.nsfw));
// All routes in all namespaces should not have nsfw features
for (const ns of Object.values(namespaces)) {
@@ -51,7 +54,10 @@ describe('registry', () => {
expect(route.features?.nsfw).not.toBe(true);
}
}
expect(namespaces['2048']).toBeUndefined();
expect(nsfwNamespaces.length).toBeGreaterThan(0);
for (const [key] of nsfwNamespaces) {
expect(namespaces[key]).toBeUndefined();
}
});
it('namespaces includes NSFW routes when DISABLE_NSFW=false', async () => {
+45
View File
@@ -83,6 +83,51 @@ window.ip_wording = {
)
)
),
http.get(`https://mp.weixin.qq.com/rsshub_test/original_empty`, () =>
HttpResponse.text(
`<meta name="description" content="summary" />
<meta name="author" content="author" />
<meta property="og:title" content="title" />
<meta property="og:image" content="https://mmbiz.qpic.cn/rsshub_test/og_img_1/0?wx_fmt=jpeg" />
<meta property="twitter:card" content="summary" />
<div class="rich_media_content" id="js_content" style="visibility: hidden;"></div>
<div id="js_share_source" data-url="https://mp.weixin.qq.com/rsshub_test/original_source"></div>
<div class="wx_follow_nickname">mpName</div>
<script type="text/javascript" nonce="000000000">
var item_show_type = "0";
var real_item_show_type = "0";
var appmsg_type = "9";
var ct = "${1_636_626_300}";
var msg_source_url = "https://mp.weixin.qq.com/rsshub_test/fake";
</script>`
)
),
http.get(`https://mp.weixin.qq.com/rsshub_test/original_source`, () =>
HttpResponse.text(
genWeChatMpPage(
`original content`,
`
var item_show_type = "0";
var real_item_show_type = "0";
var appmsg_type = "9";
var ct = "${1_636_626_300}";
var msg_source_url = "https://mp.weixin.qq.com/rsshub_test/fake";`
)
)
),
http.get(`https://mp.weixin.qq.com/rsshub_test/original_long`, () =>
HttpResponse.text(
genWeChatMpPage(
'long-content-'.repeat(10),
`
var item_show_type = "0";
var real_item_show_type = "0";
var appmsg_type = "9";
var ct = "${1_636_626_300}";
var msg_source_url = "https://mp.weixin.qq.com/rsshub_test/fake";`
)
)
),
http.get(`https://mp.weixin.qq.com/rsshub_test/img`, () =>
HttpResponse.text(
genWeChatMpPage('fake_description', [
+9 -1
View File
@@ -34,6 +34,11 @@ describe('cache', () => {
expect(await cache.globalCache.get('mock')).toBe('{"mock":1}');
}, 10000);
it('memory get returns null before init', async () => {
const memory = (await import('@/utils/cache/memory')).default;
expect(await memory.get('missing')).toBeNull();
});
it('redis', async () => {
process.env.CACHE_TYPE = 'redis';
const cache = (await import('@/utils/cache')).default;
@@ -67,14 +72,17 @@ describe('cache', () => {
const cache = (await import('@/utils/cache')).default;
await cache.set('mock2', '2');
expect(await cache.get('mock2')).toBe(null);
await cache.clients.redisClient?.quit();
cache.clients.redisClient?.disconnect();
});
it('no cache', async () => {
process.env.CACHE_TYPE = 'NO';
const cache = (await import('@/utils/cache')).default;
await cache.init();
await cache.set('mock2', '2');
expect(await cache.get('mock2')).toBe(null);
expect(await cache.globalCache.get('mock2')).toBeNull();
expect(cache.globalCache.set('mock2', '2')).toBeNull();
});
it('throws TTL key', async () => {
+69
View File
@@ -0,0 +1,69 @@
import { describe, expect, it, vi } from 'vitest';
const errorSpy = vi.fn();
const infoSpy = vi.fn();
vi.mock('@/utils/logger', () => ({
default: {
error: errorSpy,
info: infoSpy,
},
}));
class RedisMock extends EventTarget {
mget = vi.fn();
expire = vi.fn();
set = vi.fn();
on(event: string, listener: (...args: any[]) => void) {
this.addEventListener(event, (evt) => {
listener((evt as Event & { detail?: unknown }).detail);
});
return this;
}
emit(event: string, detail?: unknown) {
const evt = new Event(event) as Event & { detail?: unknown };
evt.detail = detail;
this.dispatchEvent(evt);
return true;
}
}
vi.mock('ioredis', () => ({
default: RedisMock,
}));
describe('redis cache module', () => {
it('throws on reserved cache ttl key', async () => {
const redisCache = (await import('@/utils/cache/redis')).default;
redisCache.status.available = true;
redisCache.clients.redisClient = new RedisMock() as any;
await expect(redisCache.get('rsshub:cacheTtl:bad')).rejects.toThrow('reserved for the internal usage');
});
it('expires cache ttl key when present', async () => {
const redisCache = (await import('@/utils/cache/redis')).default;
const client = new RedisMock() as any;
client.mget.mockResolvedValue(['value', '30']);
redisCache.status.available = true;
redisCache.clients.redisClient = client;
const value = await redisCache.get('mock', true);
expect(value).toBe('value');
expect(client.expire).toHaveBeenCalledWith('rsshub:cacheTtl:mock', '30');
expect(client.expire).toHaveBeenCalledWith('mock', '30');
});
it('marks redis unavailable on error', async () => {
const redisCache = (await import('@/utils/cache/redis')).default;
redisCache.init();
const client = redisCache.clients.redisClient as RedisMock;
client.emit('error', new Error('boom'));
expect(redisCache.status.available).toBe(false);
expect(errorSpy).toHaveBeenCalled();
});
});
+49
View File
@@ -0,0 +1,49 @@
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');
});
});
+6 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import { collapseWhitespace, convertDateToISO8601, getLocalhostAddress, toTitleCase } from '@/utils/common-utils';
import { collapseWhitespace, convertDateToISO8601, getLocalhostAddress, getSubPath, toTitleCase } from '@/utils/common-utils';
describe('common-utils', () => {
it('toTitleCase', () => {
@@ -39,4 +39,9 @@ describe('common-utils', () => {
it('getLocalhostAddress', () => {
expect(getLocalhostAddress()).toBeInstanceOf(Array);
});
it('getSubPath', () => {
expect(getSubPath({ req: { path: '/test/abc' } })).toBe('/abc');
expect(getSubPath({ req: { path: '/test' } })).toBe('/');
});
});
+68
View File
@@ -0,0 +1,68 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { afterEach, describe, expect, it } from 'vitest';
import { directoryImport } from '@/utils/directory-import';
const createTempDir = () => fs.mkdtempSync(path.join(os.tmpdir(), 'rsshub-dir-import-'));
const writeFile = (filePath: string, content: string) => {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, content, 'utf8');
};
describe('directory-import', () => {
let tempDir = '';
afterEach(() => {
if (tempDir) {
fs.rmSync(tempDir, { recursive: true, force: true });
tempDir = '';
}
});
it('imports valid files and skips invalid ones', () => {
tempDir = createTempDir();
const rootModule = path.join(tempDir, 'valid.cjs');
const jsonModule = path.join(tempDir, 'data.json');
const ignoredText = path.join(tempDir, 'note.txt');
const declaration = path.join(tempDir, 'types.d.ts');
const nestedModule = path.join(tempDir, 'sub', 'child.cjs');
writeFile(rootModule, "module.exports = { value: 'root' };");
writeFile(jsonModule, JSON.stringify({ value: 'json' }));
writeFile(ignoredText, 'ignore');
writeFile(declaration, 'export {};');
writeFile(nestedModule, "module.exports = { value: 'child' };");
const modules = directoryImport({ targetDirectoryPath: tempDir });
const keyFor = (filePath: string) => filePath.slice(tempDir.length);
expect(modules).toHaveProperty(keyFor(rootModule));
expect(modules).toHaveProperty(keyFor(jsonModule));
expect(modules).toHaveProperty(keyFor(nestedModule));
expect(modules).not.toHaveProperty(keyFor(ignoredText));
expect(modules).not.toHaveProperty(keyFor(declaration));
});
it('can skip subdirectories and apply patterns', () => {
tempDir = createTempDir();
const rootModule = path.join(tempDir, 'keep.cjs');
const nestedModule = path.join(tempDir, 'sub', 'skip.cjs');
writeFile(rootModule, "module.exports = { value: 'keep' };");
writeFile(nestedModule, "module.exports = { value: 'skip' };");
const modules = directoryImport({
targetDirectoryPath: tempDir,
includeSubdirectories: false,
importPattern: /keep/,
});
const keyFor = (filePath: string) => filePath.slice(tempDir.length);
expect(modules).toHaveProperty(keyFor(rootModule));
expect(modules).not.toHaveProperty(keyFor(nestedModule));
});
});
+39
View File
@@ -0,0 +1,39 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
const originalEnv = {
HEROKU_SLUG_COMMIT: process.env.HEROKU_SLUG_COMMIT,
VERCEL_GIT_COMMIT_SHA: process.env.VERCEL_GIT_COMMIT_SHA,
};
afterEach(() => {
vi.resetModules();
vi.clearAllMocks();
vi.unmock('node:child_process');
if (originalEnv.HEROKU_SLUG_COMMIT === undefined) {
delete process.env.HEROKU_SLUG_COMMIT;
} else {
process.env.HEROKU_SLUG_COMMIT = originalEnv.HEROKU_SLUG_COMMIT;
}
if (originalEnv.VERCEL_GIT_COMMIT_SHA === undefined) {
delete process.env.VERCEL_GIT_COMMIT_SHA;
} else {
process.env.VERCEL_GIT_COMMIT_SHA = originalEnv.VERCEL_GIT_COMMIT_SHA;
}
});
describe('git-hash', () => {
it('falls back to unknown when git commands fail', async () => {
delete process.env.HEROKU_SLUG_COMMIT;
delete process.env.VERCEL_GIT_COMMIT_SHA;
vi.doMock('node:child_process', () => ({
execSync: () => {
throw new Error('git failure');
},
}));
const { gitHash } = await import('@/utils/git-hash');
expect(gitHash).toBe('unknown');
});
});
-81
View File
@@ -1,81 +0,0 @@
import type { CancelableRequest, Got, Options, OptionsInit, Response as GotResponse } from 'got';
import got from 'got';
import { config } from '@/config';
import logger from '@/utils/logger';
type Response<T> = GotResponse<string> & {
data: T;
status: number;
};
type GotRequestFunction = {
(url: string | URL, options?: Options): CancelableRequest<Response<Record<string, any>>>;
<T>(url: string | URL, options?: Options): CancelableRequest<Response<T>>;
(options: Options): CancelableRequest<Response<Record<string, any>>>;
<T>(options: Options): CancelableRequest<Response<T>>;
};
// @ts-expect-error got instance with custom response type
const custom: {
all?: <T>(list: Array<Promise<T>>) => Promise<Array<T>>;
get: GotRequestFunction;
post: GotRequestFunction;
put: GotRequestFunction;
patch: GotRequestFunction;
head: GotRequestFunction;
delete: GotRequestFunction;
} & GotRequestFunction &
Got = got.extend({
retry: {
limit: config.requestRetry,
statusCodes: [400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 421, 422, 423, 424, 426, 428, 429, 431, 451, 500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511, 521, 522, 524],
},
hooks: {
beforeRetry: [
(err, count) => {
logger.error(`Request ${err.options.url} fail, retry attempt #${count}: ${err}`);
},
],
beforeRedirect: [
(options, response) => {
logger.http(`Redirecting to ${options.url} for ${response.requestUrl}`);
},
],
afterResponse: [
// @ts-expect-error custom response type
(response: Response<Record<string, any>>) => {
try {
response.data = typeof response.body === 'string' ? JSON.parse(response.body) : response.body;
} catch {
// @ts-expect-error for compatibility
response.data = response.body;
}
response.status = response.statusCode;
return response;
},
],
init: [
(
options: OptionsInit & {
data?: string;
}
) => {
// compatible with axios api
if (options && options.data) {
options.body = options.body || options.data;
}
},
],
},
headers: {
'user-agent': config.ua,
},
timeout: {
request: config.requestTimeout,
},
});
custom.all = (list) => Promise.all(list);
export default custom;
export type { Options, Response } from 'got';
+75
View File
@@ -75,4 +75,79 @@ describe('got', () => {
expect(data.cookie).toBe('cookie=test; Domain=rsshub.test; Path=/');
});
it('runs beforeRequest hooks', async () => {
const hook = vi.fn((options) => {
options.headers = {
...options.headers,
'x-before-request': '1',
};
});
const { data } = await got('http://rsshub.test/headers', {
hooks: {
beforeRequest: [hook],
},
});
expect(hook).toHaveBeenCalledTimes(1);
expect(data['x-before-request']).toBe('1');
});
it('appends search params', async () => {
const { default: server } = await import('@/setup.test');
server.use(
http.get('http://rsshub.test/query', ({ request }) => {
const url = new URL(request.url);
return HttpResponse.json({
query: Object.fromEntries(url.searchParams.entries()),
});
})
);
const { data } = await got('http://rsshub.test/query', {
searchParams: {
foo: 'bar',
baz: 'qux',
},
});
expect(data.query).toEqual({
foo: 'bar',
baz: 'qux',
});
});
it('supports additional http verbs and extend', async () => {
const { default: server } = await import('@/setup.test');
server.use(
http.all('http://rsshub.test/method', ({ request }) =>
HttpResponse.json({
method: request.method,
})
)
);
const putResponse = await got.put('http://rsshub.test/method');
expect(putResponse.data.method).toBe('PUT');
const patchResponse = await got.patch('http://rsshub.test/method');
expect(patchResponse.data.method).toBe('PATCH');
const deleteResponse = await got.delete('http://rsshub.test/method');
expect(deleteResponse.data.method).toBe('DELETE');
const headResponse = await got.head('http://rsshub.test/method', {
responseType: 'text',
});
expect(headResponse).toBeUndefined();
const extended = got.extend({
headers: {
'x-extended': '1',
},
});
const extendedResponse = await extended.get('http://rsshub.test/headers');
expect(extendedResponse.data['x-extended']).toBe('1');
});
});
+50
View File
@@ -0,0 +1,50 @@
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');
});
});
+15 -1
View File
@@ -1,10 +1,16 @@
import { describe, expect, it } from 'vitest';
import { getRouteNameFromPath, getSearchParamsString, parseDuration } from '@/utils/helpers';
import { getCurrentPath, getRouteNameFromPath, getSearchParamsString, parseDuration } from '@/utils/helpers';
describe('helpers', () => {
it('getRouteNameFromPath', () => {
expect(getRouteNameFromPath('/test/1')).toBe('test');
expect(getRouteNameFromPath('/')).toBeNull();
});
it('getCurrentPath', () => {
const expected = import.meta.dirname;
expect(getCurrentPath(import.meta.url)).toBe(expected);
});
it('getSearchParamsString', () => {
@@ -24,5 +30,13 @@ describe('helpers', () => {
expect(parseDuration('01:01')).toBe(61);
expect(parseDuration('00:01')).toBe(1);
expect(parseDuration('59')).toBe(59);
expect(parseDuration(null)).toBeUndefined();
expect(parseDuration('1:xx')).toBe(60);
const invalid: any = {
trim: () => ({
replaceAll: () => 'NaN:1',
}),
};
expect(() => parseDuration(invalid)).toThrow('Invalid segment');
});
});
+27
View File
@@ -0,0 +1,27 @@
import { describe, expect, it, vi } from 'vitest';
describe('logger', () => {
it('formats console transport output', async () => {
const originalEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'development';
process.env.SHOW_LOGGER_TIMESTAMP = 'true';
vi.resetModules();
const logger = (await import('@/utils/logger')).default;
const consoleTransport = logger.transports.find((transport) => transport.constructor.name === 'Console') as any;
const format = consoleTransport?.format;
const info = {
level: 'info',
message: 'hello',
timestamp: '2024-01-01 00:00:00.000',
};
const transformed = format?.transform ? format.transform(info) : info;
expect(transformed).toBeDefined();
expect(transformed.message).toBe('hello');
process.env.NODE_ENV = originalEnv;
delete process.env.SHOW_LOGGER_TIMESTAMP;
});
});
+55 -41
View File
@@ -1,52 +1,66 @@
import { http, HttpResponse } from 'msw';
import { describe, expect, it, vi } from 'vitest';
import http from 'node:http';
import { config } from '@/config';
import ofetch from '@/utils/ofetch';
import { http as mswHttp, HttpResponse } from 'msw';
import { afterEach, describe, expect, it, vi } from 'vitest';
const loadOfetchWithLogger = async () => {
vi.resetModules();
const { default: logger } = await import('@/utils/logger');
const { default: ofetch } = await import('@/utils/ofetch');
return { logger, ofetch };
};
afterEach(() => {
vi.restoreAllMocks();
vi.unstubAllGlobals();
});
describe('ofetch', () => {
it('headers', async () => {
const data = await ofetch('http://rsshub.test/headers');
expect(data['user-agent']).toBeUndefined();
it('marks prefer-proxy header on retryable responses', async () => {
const { default: server } = await import('@/setup.test');
server.use(mswHttp.get('http://rsshub.test/fail-500', () => HttpResponse.text('fail', { status: 500 })));
const { logger, ofetch } = await loadOfetchWithLogger();
const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(() => logger);
await expect(
ofetch('http://rsshub.test/fail-500', {
retry: 1,
retryDelay: 0,
onResponse({ options }) {
options.headers = null as unknown as Headers;
},
})
).rejects.toBeDefined();
expect(warnSpy).toHaveBeenCalled();
});
it('retry', async () => {
const requestRun = vi.fn();
const { default: server } = await import('@/setup.test');
server.use(
http.get(`http://rsshub.test/retry-test`, () => {
requestRun();
return HttpResponse.error();
})
);
it('logs redirected responses', async () => {
const { logger, ofetch } = await loadOfetchWithLogger();
const httpSpy = vi.spyOn(logger, 'http').mockImplementation(() => logger);
const server = http.createServer((req, res) => {
if (req.url === '/redirect') {
res.statusCode = 302;
res.setHeader('Location', '/target');
res.end();
return;
}
res.statusCode = 200;
res.end('ok');
});
await new Promise<void>((resolve) => server.listen(0, resolve));
const address = server.address();
const port = typeof address === 'object' && address ? address.port : 0;
try {
await ofetch('http://rsshub.test/retry-test');
} catch (error: any) {
expect(error.name).toBe('FetchError');
await ofetch(`http://127.0.0.1:${port}/redirect`);
} finally {
server.close();
}
// retries
expect(requestRun).toHaveBeenCalledTimes(config.requestRetry + 1);
});
it('form-post', async () => {
const body = new FormData();
body.append('test', 'rsshub');
const response = await ofetch('http://rsshub.test/form-post', {
method: 'POST',
body,
});
expect(response.test).toBe('rsshub');
});
it('json-post', async () => {
const response = await ofetch('http://rsshub.test/json-post', {
method: 'POST',
body: {
test: 'rsshub',
},
});
expect(response.test).toBe('rsshub');
expect(httpSpy).toHaveBeenCalled();
});
});
+23
View File
@@ -0,0 +1,23 @@
import { describe, expect, it } from 'vitest';
import { getContext, requestMetric } from '@/utils/otel/metric';
describe('otel metrics', () => {
it('serializes prometheus metrics', async () => {
requestMetric.success(150, {
method: 'GET',
path: '/test',
status: 200,
});
requestMetric.error({
method: 'GET',
path: '/test',
status: 500,
});
const output = await getContext();
expect(output).toContain('rsshub_request_total');
expect(output).toContain('rsshub_request_error_total');
});
});
+89
View File
@@ -0,0 +1,89 @@
import { PacProxyAgent } from 'pac-proxy-agent';
import { SocksProxyAgent } from 'socks-proxy-agent';
import { ProxyAgent } from 'undici';
import { afterEach, describe, expect, it, vi } from 'vitest';
const loadProxy = async (env: Record<string, string>) => {
vi.resetModules();
for (const [key, value] of Object.entries(env)) {
vi.stubEnv(key, value);
}
return (await import('@/utils/proxy')).default;
};
describe('proxy', () => {
afterEach(() => {
vi.clearAllTimers();
vi.useRealTimers();
vi.unstubAllEnvs();
});
it('uses PAC proxy when PAC_URI is set', async () => {
const proxy = await loadProxy({
PAC_URI: 'http://example.com/proxy.pac',
PROXY_URIS: '',
PROXY_URI: '',
});
expect(proxy.agent).toBeInstanceOf(PacProxyAgent);
expect(proxy.dispatcher).toBeNull();
expect(proxy.proxyUri).toBe('http://example.com/proxy.pac');
const current = proxy.getCurrentProxy();
expect(current?.uri).toBe('http://example.com/proxy.pac');
});
it('handles multi-proxy selection and updates after failures', async () => {
const proxy = await loadProxy({
PROXY_URIS: 'http://proxy1.local:8080,http://proxy2.local:8081',
PAC_URI: '',
PROXY_URI: '',
});
expect(proxy.multiProxy).toBeDefined();
const current = proxy.getCurrentProxy();
expect(current).not.toBeNull();
expect(proxy.getDispatcherForProxy(current!)).toBeInstanceOf(ProxyAgent);
expect(proxy.getAgentForProxy({ uri: 'socks5://proxy.local:1080' } as any)).toBeInstanceOf(SocksProxyAgent);
proxy.markProxyFailed(current!.uri);
const next = proxy.getCurrentProxy();
expect(next).not.toBeNull();
});
it('clears proxy when multi-proxy has no valid entries', async () => {
const proxy = await loadProxy({
PROXY_URIS: 'http://inv lid.test',
PAC_URI: '',
PROXY_URI: '',
});
expect(proxy.getCurrentProxy()).toBeNull();
proxy.markProxyFailed('http://inv lid.test');
expect(proxy.agent).toBeNull();
expect(proxy.dispatcher).toBeNull();
expect(proxy.proxyUri).toBeUndefined();
});
it('creates a socks proxy agent for single proxy settings', async () => {
const proxy = await loadProxy({
PROXY_URI: 'socks5://proxy.local:1080',
PROXY_URIS: '',
PAC_URI: '',
});
expect(proxy.agent).toBeInstanceOf(SocksProxyAgent);
expect(proxy.dispatcher).toBeNull();
expect(proxy.getCurrentProxy()?.uri).toBe('socks5://proxy.local:1080');
});
it('returns null agent for unsupported proxy protocol', async () => {
const proxy = await loadProxy({
PROXY_URI: '',
PROXY_URIS: '',
PAC_URI: '',
});
expect(proxy.getAgentForProxy({ uri: 'ftp://proxy.local:21' } as any)).toBeNull();
});
});
+76
View File
@@ -0,0 +1,76 @@
import { describe, expect, it, vi } from 'vitest';
import createMultiProxy from '@/utils/proxy/multi-proxy';
const baseProxyObj = {
protocol: undefined,
host: undefined,
port: undefined,
auth: undefined,
url_regex: '.*',
strategy: 'all',
};
describe('multi-proxy', () => {
it('returns empty results when no valid proxy is provided', () => {
const result = createMultiProxy(['http://inv lid.test'], baseProxyObj);
expect(result.allProxies).toHaveLength(0);
expect(result.getNextProxy()).toBeNull();
expect(() => result.resetProxy('http://inv lid.test')).not.toThrow();
});
it('rotates proxies, marks inactive, and reactivates after health checks', () => {
vi.useFakeTimers();
try {
const result = createMultiProxy(['http://proxy1.local:8080', 'http://proxy2.local:8081'], {
...baseProxyObj,
healthCheckInterval: 20,
});
const first = result.getNextProxy();
expect(first).not.toBeNull();
const firstUri = first!.uri;
const secondUri = result.allProxies.find((proxy) => proxy.uri !== firstUri)!.uri;
result.markProxyFailed(firstUri);
result.markProxyFailed(firstUri);
result.markProxyFailed(firstUri);
const firstState = result.allProxies.find((proxy) => proxy.uri === firstUri)!;
expect(firstState.isActive).toBe(false);
result.markProxyFailed(secondUri);
result.markProxyFailed(secondUri);
result.markProxyFailed(secondUri);
expect(result.getNextProxy()).toBeNull();
vi.advanceTimersByTime(45);
expect(firstState.isActive).toBe(true);
result.resetProxy(firstUri);
expect(firstState.failureCount).toBe(0);
} finally {
vi.clearAllTimers();
vi.useRealTimers();
}
});
it('returns null when proxies become inactive during selection', () => {
const result = createMultiProxy(['http://proxy1.local:8080', 'http://proxy2.local:8081'], baseProxyObj);
for (const proxy of result.allProxies) {
let calls = 0;
Object.defineProperty(proxy, 'isActive', {
configurable: true,
get() {
calls += 1;
return calls === 1;
},
});
}
expect(result.getNextProxy()).toBeNull();
});
});
+22
View File
@@ -0,0 +1,22 @@
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');
});
});
+7 -1
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
import unifyProxy from '@/utils/proxy/unify-proxy';
import unifyProxy, { unifyProxies } from '@/utils/proxy/unify-proxy';
const emptyProxyObj = {
protocol: undefined,
@@ -139,4 +139,10 @@ describe('unify-proxy', () => {
it('proxy-uri user@pass override proxy-obj auth', () => {
effectiveExpect(unifyProxy(httpsAuthUri, httpsAuthObj), httpsAuthUri, httpsObj);
});
it('unifyProxies filters invalid proxy uris', () => {
const results = unifyProxies(['http://rsshub.proxy:2333', 'http://inv lid.test'], emptyProxyObj);
expect(results).toHaveLength(1);
expect(results[0].proxyUri).toBe('http://rsshub.proxy:2333');
});
});
+108
View File
@@ -0,0 +1,108 @@
import { describe, expect, it, vi } from 'vitest';
const connect = vi.fn();
const launch = vi.fn();
const page = {
goto: vi.fn(),
authenticate: vi.fn(),
};
const browser = {
newPage: vi.fn(() => Promise.resolve(page)),
close: vi.fn(),
};
const proxyMock = {
proxyObj: { url_regex: '.*' },
proxyUrlHandler: new URL('http://proxy.local'),
multiProxy: undefined as any,
getCurrentProxy: vi.fn(),
markProxyFailed: vi.fn(),
getDispatcherForProxy: vi.fn(),
};
vi.mock('rebrowser-puppeteer', () => ({
default: {
connect,
launch,
},
}));
vi.mock('@/utils/proxy', () => ({
default: proxyMock,
}));
vi.mock('@/utils/logger', () => ({
default: {
warn: vi.fn(),
debug: vi.fn(),
},
}));
const loadPuppeteer = async () => {
vi.resetModules();
const mod = await import('@/utils/puppeteer');
return mod.getPuppeteerPage;
};
describe('getPuppeteerPage (mocked)', () => {
it('connects via ws endpoint and runs onBeforeLoad', async () => {
connect.mockResolvedValue(browser);
launch.mockResolvedValue(browser);
page.goto.mockResolvedValue(undefined);
page.authenticate.mockResolvedValue(undefined);
browser.close.mockResolvedValue(undefined);
process.env.PUPPETEER_WS_ENDPOINT = 'ws://localhost:3000/?token=abc';
proxyMock.getCurrentProxy.mockReturnValue(null);
const getPuppeteerPage = await loadPuppeteer();
const onBeforeLoad = vi.fn();
const result = await getPuppeteerPage('https://example.com', {
noGoto: true,
onBeforeLoad,
});
const endpoint = connect.mock.calls[0][0].browserWSEndpoint as string;
expect(endpoint).toContain('launch=');
expect(endpoint).toContain('stealth=true');
expect(onBeforeLoad).toHaveBeenCalled();
await result.destory();
expect(browser.close).toHaveBeenCalled();
delete process.env.PUPPETEER_WS_ENDPOINT;
});
it('marks proxy failed when navigation throws with multi-proxy', async () => {
connect.mockResolvedValue(browser);
launch.mockResolvedValue(browser);
page.goto.mockRejectedValueOnce(new Error('fail'));
page.authenticate.mockResolvedValue(undefined);
const currentProxy = {
uri: 'http://user:pass@proxy.local:8080',
urlHandler: new URL('http://user:pass@proxy.local:8080'),
};
proxyMock.multiProxy = {};
proxyMock.getCurrentProxy.mockReturnValue(currentProxy);
const getPuppeteerPage = await loadPuppeteer();
await expect(getPuppeteerPage('https://example.com')).rejects.toThrow('fail');
expect(proxyMock.markProxyFailed).toHaveBeenCalledWith(currentProxy.uri);
});
it('rethrows navigation errors without multi-proxy', async () => {
connect.mockResolvedValue(browser);
launch.mockResolvedValue(browser);
page.goto.mockRejectedValueOnce(new Error('fail'));
proxyMock.multiProxy = undefined;
proxyMock.getCurrentProxy.mockReturnValue(null);
const getPuppeteerPage = await loadPuppeteer();
await expect(getPuppeteerPage('https://example.com')).rejects.toThrow('fail');
});
});
+15
View File
@@ -25,6 +25,12 @@ describe('queryToBoolean', () => {
expect(queryToBoolean('0')).toBe(false);
expect(queryToBoolean('false')).toBe(false);
});
test('should handle undefined and array inputs', () => {
expect(queryToBoolean(undefined)).toBeUndefined();
expect(queryToBoolean([])).toBeUndefined();
expect(queryToBoolean(['false', 'true'])).toBe(false);
});
});
describe('queryToInteger', () => {
@@ -37,6 +43,11 @@ describe('queryToInteger', () => {
expect(queryToInteger(null)).toBeNull();
expect(queryToInteger('abc')).toBeNaN();
});
test('should handle array inputs', () => {
expect(queryToInteger([])).toBeUndefined();
expect(queryToInteger(['7'])).toBe(7);
});
});
describe('queryToFloat', () => {
@@ -56,6 +67,10 @@ describe('queryToFloat', () => {
expect(queryToFloat(['3.14'])).toBe(3.14);
});
test('should handle empty array', () => {
expect(queryToFloat([])).toBeUndefined();
});
test('should convert numeric string', () => {
expect(queryToFloat('9.8')).toBe(9.8);
});
+88 -17
View File
@@ -1,11 +1,33 @@
import http from 'node:http';
import https from 'node:https';
import got from 'got';
import undici from 'undici';
import { describe, expect, it, vi } from 'vitest';
import { afterAll, afterEach, describe, expect, it, vi } from 'vitest';
import { PRESETS } from '@/utils/header-generator';
const originalGlobals = {
fetch: globalThis.fetch,
Headers: globalThis.Headers,
FormData: globalThis.FormData,
Request: globalThis.Request,
Response: globalThis.Response,
};
const originalHttp = {
get: http.get,
request: http.request,
};
const originalHttps = {
get: https.get,
request: https.request,
};
const originalEnv = {
PROXY_URI: process.env.PROXY_URI,
PROXY_AUTH: process.env.PROXY_AUTH,
PROXY_URL_REGEX: process.env.PROXY_URL_REGEX,
};
process.env.PROXY_URI = 'http://rsshub.proxy:2333/';
process.env.PROXY_AUTH = 'rsshubtest';
process.env.PROXY_URL_REGEX = 'headers';
@@ -14,9 +36,52 @@ await import('@/utils/request-rewriter');
const { config } = await import('@/config');
const { default: ofetch } = await import('@/utils/ofetch');
const createJsonResponse = () =>
Response.json(
{ ok: true },
{
headers: {
'content-type': 'application/json',
},
}
);
describe('request-rewriter', () => {
afterAll(() => {
globalThis.fetch = originalGlobals.fetch;
globalThis.Headers = originalGlobals.Headers;
globalThis.FormData = originalGlobals.FormData;
globalThis.Request = originalGlobals.Request;
globalThis.Response = originalGlobals.Response;
http.get = originalHttp.get;
http.request = originalHttp.request;
https.get = originalHttps.get;
https.request = originalHttps.request;
if (originalEnv.PROXY_URI === undefined) {
delete process.env.PROXY_URI;
} else {
process.env.PROXY_URI = originalEnv.PROXY_URI;
}
if (originalEnv.PROXY_AUTH === undefined) {
delete process.env.PROXY_AUTH;
} else {
process.env.PROXY_AUTH = originalEnv.PROXY_AUTH;
}
if (originalEnv.PROXY_URL_REGEX === undefined) {
delete process.env.PROXY_URL_REGEX;
} else {
process.env.PROXY_URL_REGEX = originalEnv.PROXY_URL_REGEX;
}
});
afterEach(() => {
vi.restoreAllMocks();
});
it('fetch', async () => {
const fetchSpy = vi.spyOn(undici, 'fetch');
const fetchSpy = vi.spyOn(undici, 'fetch').mockImplementation(() => Promise.resolve(createJsonResponse()));
try {
await (await fetch('http://rsshub.test/headers')).json();
@@ -61,7 +126,7 @@ describe('request-rewriter', () => {
});
it('ofetch', async () => {
const fetchSpy = vi.spyOn(undici, 'fetch');
const fetchSpy = vi.spyOn(undici, 'fetch').mockImplementation(() => Promise.resolve(createJsonResponse()));
try {
await ofetch('http://rsshub.test/headers', {
@@ -110,7 +175,7 @@ describe('request-rewriter', () => {
});
it('ofetch custom ua', async () => {
const fetchSpy = vi.spyOn(undici, 'fetch');
const fetchSpy = vi.spyOn(undici, 'fetch').mockImplementation(() => Promise.resolve(createJsonResponse()));
const userAgent = config.trueUA;
try {
@@ -130,7 +195,7 @@ describe('request-rewriter', () => {
});
it('ofetch header preset', async () => {
const fetchSpy = vi.spyOn(undici, 'fetch');
const fetchSpy = vi.spyOn(undici, 'fetch').mockImplementation(() => Promise.resolve(createJsonResponse()));
try {
await ofetch('http://rsshub.test/headers', {
@@ -199,16 +264,22 @@ describe('request-rewriter', () => {
});
it('rate limiter', async () => {
const time = Date.now();
await Promise.all(
Array.from({ length: 20 }).map(async () => {
try {
await fetch('http://rsshub.test/headers');
} catch {
// ignore
}
})
);
expect(Date.now() - time).toBeGreaterThan(1500);
});
vi.useFakeTimers();
const fetchSpy = vi.spyOn(undici, 'fetch').mockImplementation(() => Promise.resolve(createJsonResponse()));
try {
const { default: wrappedFetch } = await import('@/utils/request-rewriter/fetch');
const time = Date.now();
const tasks = Array.from({ length: 20 }).map(() => wrappedFetch('http://rsshub.test/headers'));
await vi.advanceTimersByTimeAsync(3000);
await Promise.all(tasks);
expect(fetchSpy).toHaveBeenCalledTimes(20);
expect(Date.now() - time).toBeGreaterThan(1500);
} finally {
vi.useRealTimers();
fetchSpy.mockRestore();
}
}, 20000);
});
@@ -0,0 +1,118 @@
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();
});
});
+13 -1
View File
@@ -1,5 +1,6 @@
import { getCurrentCell, setCurrentCell } from 'node-network-devtools';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
import undici from 'undici';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { useCustomHeader } from './fetch';
@@ -93,3 +94,14 @@ describe('useCustomHeader', () => {
expect(req.requestHeaders[headerText]).toBeUndefined();
});
});
describe('wrappedFetch', () => {
test('throws when fetch fails without proxy retry', async () => {
const fetchSpy = vi.spyOn(undici, 'fetch').mockRejectedValueOnce(new Error('boom'));
const { default: wrappedFetch } = await import('./fetch');
await expect(wrappedFetch('http://example.com')).rejects.toThrow('boom');
fetchSpy.mockRestore();
});
});
+29
View File
@@ -0,0 +1,29 @@
import { describe, expect, it, vi } from 'vitest';
import getWrappedGet from '@/utils/request-rewriter/get';
describe('request-rewriter get wrapper', () => {
it('passes callback when url and callback are provided', () => {
const origin = vi.fn(() => 'ok');
const wrapped = getWrappedGet(origin as any);
const callback = vi.fn();
const result = wrapped('http://example.com/test', callback);
expect(result).toBe('ok');
expect(origin).toHaveBeenCalledTimes(1);
expect(origin.mock.calls[0][2]).toBe(callback);
});
it('falls back to origin when url parsing fails', () => {
const origin = vi.fn(() => 'fallback');
const wrapped = getWrappedGet(origin as any);
const callback = vi.fn();
const options = { href: 'http://' } as any;
const result = wrapped(options, callback);
expect(result).toBe('fallback');
expect(origin).toHaveBeenCalledWith(options, callback);
});
});
+5 -5
View File
@@ -7,11 +7,11 @@ import fetch from '@/utils/request-rewriter/fetch';
import getWrappedGet from '@/utils/request-rewriter/get';
Object.defineProperties(globalThis, {
fetch: { value: fetch },
Headers: { value: Headers },
FormData: { value: FormData },
Request: { value: Request },
Response: { value: Response },
fetch: { value: fetch, writable: true, configurable: true },
Headers: { value: Headers, writable: true, configurable: true },
FormData: { value: FormData, writable: true, configurable: true },
Request: { value: Request, writable: true, configurable: true },
Response: { value: Response, writable: true, configurable: true },
});
http.get = getWrappedGet(http.get);
+5
View File
@@ -7,4 +7,9 @@ describe('timezone', () => {
const serverTimezone = -new Date().getTimezoneOffset() / 60;
expect(timezone(new Date('2024-01-01T01:01:01Z'), serverTimezone - 1).toISOString()).toEqual('2024-01-01T02:01:01.000Z');
});
it('timezone with string input', () => {
const serverTimezone = -new Date().getTimezoneOffset() / 60;
expect(timezone('2024-01-01T01:01:01Z', serverTimezone).toISOString()).toEqual('2024-01-01T01:01:01.000Z');
});
});
+17 -3
View File
@@ -135,6 +135,10 @@ describe('wechat-mp', () => {
createTime: '1713009660',
});
});
it('ExtractMetadata.common rethrows unexpected errors', () => {
expect(() => ExtractMetadata.common('not-cheerio' as any)).toThrow(TypeError);
});
it('ExtractMetadata.img', () => {
expect(ExtractMetadata.img(load(''))).toStrictEqual({});
@@ -370,6 +374,16 @@ describe('wechat-mp', () => {
expect(fetchArticleItem.description).toContain('🔗️ 阅读原文');
});
it('fetches original article when content is empty', async () => {
const item = await fetchArticle('https://mp.weixin.qq.com/rsshub_test/original_empty');
expect(item.description).toContain('original content');
});
it('skips original article when content is long', async () => {
const item = await fetchArticle('https://mp.weixin.qq.com/rsshub_test/original_long');
expect(item.description).toContain('long-content-');
});
it('fetchArticle_&_finishArticleItem_img', async () => {
const fetchArticleItem = await testFetchArticleFinishArticleItem('/img');
const $ = load(fetchArticleItem.description);
@@ -473,9 +487,9 @@ describe('wechat-mp', () => {
}
});
it('redirect', () => {
expect(fetchArticle('https://mp.weixin.qq.com/s/rsshub_test_redirect_no_location')).rejects.toThrow('redirect without location');
expect(fetchArticle('https://mp.weixin.qq.com/s/rsshub_test_recursive_redirect')).rejects.toThrow('too many redirects');
it('redirect', async () => {
await expect(fetchArticle('https://mp.weixin.qq.com/s/rsshub_test_redirect_no_location')).rejects.toThrow('redirect without location');
await expect(fetchArticle('https://mp.weixin.qq.com/s/rsshub_test_recursive_redirect')).rejects.toThrow('too many redirects');
});
it('route_test', async () => {
+1
View File
@@ -543,6 +543,7 @@ class PageParsers {
} else {
error('unknown page, probably due to WAF', pageTextShort, url);
}
/* v8 ignore next */
return {}; // just to make TypeScript happy, actually UNREACHABLE
default:
warn('new showType, trying fallback method', `showType=${commonMetadata.showType}`, url);
+21
View File
@@ -98,4 +98,25 @@ describe('rss3', () => {
};
expect(result).toStrictEqual(expected);
});
it('falls back to raw link when URL parsing fails', () => {
const data = {
item: [
{
link: 'not-a-url',
author: 'Author',
description: 'Desc',
pubDate: '2024-01-01T00:00:00Z',
category: 'Category',
title: 'Title',
updated: '2024-01-02T00:00:00Z',
},
],
};
const result = rss3(data);
expect(result.data[0].owner).toBe('not-a-url');
expect(result.data[0].from).toBe('not-a-url');
expect(result.data[0].to).toBe('not-a-url');
});
});
+205
View File
@@ -0,0 +1,205 @@
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('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');
});
});