-
Notifications
You must be signed in to change notification settings - Fork 292
Expand file tree
/
Copy pathdemo_test.js
More file actions
320 lines (277 loc) · 12.3 KB
/
demo_test.js
File metadata and controls
320 lines (277 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
// import * as drpyS from '../../libs/drpyS.js'; // REMOVED: Static import causes logs to print before we can intercept
import path from 'path';
import {fileURLToPath} from 'url';
import {existsSync} from 'fs';
import { fastify } from '../../controllers/fastlogger.js';
import { format } from 'util';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
// Mock server constants
const PORT = 5757;
const WsPORT = 57575;
const protocol = 'http';
const hostname = 'localhost:5757';
// Helper for clean output (bypassing fastify logger for report)
const print = (...args) => {
process.stdout.write(format(...args) + '\n');
};
// Override console and global log to use fastify to suppress interference logs
// This ensures that logs from imported modules (drpyS, etc.) are redirected to fastify log
globalThis.log = (...args) => fastify.log.info(args.join(' '));
console.log = (...args) => fastify.log.info(args.join(' '));
console.info = (...args) => fastify.log.info(args.join(' '));
console.debug = (...args) => fastify.log.debug(args.join(' '));
console.warn = (...args) => fastify.log.warn(args.join(' '));
console.error = (...args) => fastify.log.error(args.join(' '));
// Global drpyS variable to be initialized dynamically
let drpyS;
function getEnv(moduleName, query = {}) {
const moduleExt = query.extend || '';
const requestHost = `${protocol}://${hostname}`;
const publicUrl = `${protocol}://${hostname}/public/`;
const jsonUrl = `${protocol}://${hostname}/json/`;
const httpUrl = `${protocol}://${hostname}/http`;
const imageApi = `${protocol}://${hostname}/image`;
const mediaProxyUrl = `${protocol}://${hostname}/mediaProxy`;
const webdavProxyUrl = `${protocol}://${hostname}/webdav/`;
const ftpProxyUrl = `${protocol}://${hostname}/ftp/`;
const hostUrl = `${hostname.split(':')[0]}`;
const wsName = hostname.replace(`:${PORT}`, `:${WsPORT}`);
const fServer = null;
const proxyUrl = `${protocol}://${hostname}/proxy/${moduleName}/?do=${query.do || 'ds'}&extend=${encodeURIComponent(moduleExt)}`;
const getProxyUrl = function () {
return proxyUrl
};
const env = {
requestHost,
proxyUrl,
publicUrl,
jsonUrl,
httpUrl,
imageApi,
mediaProxyUrl,
webdavProxyUrl,
ftpProxyUrl,
hostUrl,
hostname,
wsName,
fServer,
getProxyUrl,
ext: moduleExt
};
env.getRule = async function (_moduleName) {
const _modulePath = path.join(__dirname, '../js', `${_moduleName}.js`);
if (!existsSync(_modulePath)) {
return null;
}
const _env = getEnv(_moduleName);
const RULE = await drpyS.getRuleObject(_modulePath, _env);
RULE.callRuleFn = async function (_method, _args) {
let invokeMethod = null;
switch (_method) {
case 'class_parse': invokeMethod = 'home'; break;
case '推荐': invokeMethod = 'homeVod'; break;
case '一级': invokeMethod = 'category'; break;
case '二级': invokeMethod = 'detail'; break;
case '搜索': invokeMethod = 'search'; break;
case 'lazy': invokeMethod = 'play'; break;
case 'proxy_rule': invokeMethod = 'proxy'; break;
case 'action': invokeMethod = 'action'; break;
}
if (!invokeMethod) {
if (typeof RULE[_method] !== 'function') {
return null
} else {
return await RULE[_method](..._args);
}
}
return await drpyS[invokeMethod](_modulePath, _env, ..._args);
};
return RULE;
}
return env;
}
// Test Status Reporter
const stats = {
results: [],
pass(name) { this.results.push({name, status: 'PASS'}); },
fail(name, err) { this.results.push({name, status: 'FAIL', error: err}); },
skip(name, reason) { this.results.push({name, status: 'SKIP', reason}); },
summary() {
const total = this.results.length;
const passed = this.results.filter(r => r.status === 'PASS').length;
const failed = this.results.filter(r => r.status === 'FAIL').length;
const skipped = this.results.filter(r => r.status === 'SKIP').length;
print('\n\n==============================================');
print(' TEST SUMMARY REPORT ');
print('==============================================');
print(`Total Steps : ${total}`);
print(`Passed : ${passed}`);
print(`Failed : ${failed}`);
print(`Skipped : ${skipped}`);
print('----------------------------------------------');
this.results.forEach(r => {
let statusIcon = r.status === 'PASS' ? '✅' : (r.status === 'FAIL' ? '❌' : '⚠️');
let msg = `${statusIcon} [${r.status}] ${r.name}`;
if (r.error) msg += ` - Error: ${r.error}`;
if (r.reason) msg += ` - Reason: ${r.reason}`;
print(msg);
});
print('==============================================\n');
}
};
(async () => {
// Dynamic import to ensure logs are intercepted
drpyS = await import('../../libs/drpyS.js');
// Parse command line arguments
const args = process.argv.slice(2);
const params = {};
for (let i = 0; i < args.length; i++) {
if (args[i] === '-m' || args[i] === '--module') {
params.module = args[i + 1];
i++;
} else if (args[i] === '-e' || args[i] === '--extend') {
params.extend = args[i + 1];
i++;
}
}
if (!params.module) {
print('Usage: node demo_test.js -m <module_name> [-e <extend_params>]');
print('Example: node demo_test.js -m "七猫小说[书]" -e "token=123"');
process.exit(1);
}
// 设置目标模块路径
const moduleName = params.module;
const modulePath = path.join(__dirname, `../js/${moduleName}.js`);
// Create environment
const env = getEnv(moduleName, { extend: params.extend });
// Shared variables for test dependencies
let homeResult;
let cateResult;
let searchResult;
let detailResult;
let detailUrl = '';
try {
fastify.log.info('Initializing module...'); // Changed from print to fastify.log.info
await drpyS.init(modulePath);
// 1. 测试 Home/Category (分类列表)
try {
print('\n=== Testing Home/Category ===');
homeResult = await drpyS.home(modulePath, env);
print('Home Result:', JSON.stringify(homeResult.class.slice(0, 3))); // 只打印前3个分类
if (homeResult && homeResult.class && homeResult.class.length > 0) {
stats.pass('Home/Category');
} else {
throw new Error('No classes returned');
}
} catch (e) {
stats.fail('Home/Category', e.message);
// If home fails, we can't test category, but maybe search works?
}
// 2. 测试 Category Content (一级 - 分类内容)
if (homeResult && homeResult.class && homeResult.class.length > 0) {
try {
// 使用第一个分类的 ID
const classId = homeResult.class[0].type_id;
print(`\n=== Testing Category Content (class_id=${classId}) ===`);
// category(filePath, env, tid, pg, filter, extend)
cateResult = await drpyS.category(modulePath, env, classId, 1);
print('Category Result Count:', cateResult.list.length);
if (cateResult.list.length > 0) {
print('First Item:', cateResult.list[0]);
stats.pass('Category Content');
} else {
stats.fail('Category Content', 'No items in category');
}
} catch (e) {
stats.fail('Category Content', e.message);
}
} else {
stats.skip('Category Content', 'Dependency failed: Home/Category');
}
// 3. 测试 Search (搜索)
try {
const keyword = '剑来';
print(`\n=== Testing Search (keyword=${keyword}) ===`);
searchResult = await drpyS.search(modulePath, env, keyword);
print('Search Result Count:', searchResult.list.length);
if (searchResult.list.length > 0) {
print('First Search Item:', searchResult.list[0]);
stats.pass('Search');
} else {
stats.fail('Search', 'No search results found');
}
} catch (e) {
stats.fail('Search', e.message);
}
// 4. 测试 Detail (二级 - 详情)
// 优先使用搜索结果中的 URL (vod_id),如果没有则尝试分类结果
if (searchResult && searchResult.list && searchResult.list.length > 0) {
detailUrl = searchResult.list[0].vod_id;
} else if (cateResult && cateResult.list && cateResult.list.length > 0) {
detailUrl = cateResult.list[0].vod_id;
}
if (detailUrl) {
try {
print(`\n=== Testing Detail (url=${detailUrl}) ===`);
const detailOrList = await drpyS.detail(modulePath, env, [detailUrl]);
if (detailOrList.list && Array.isArray(detailOrList.list)) {
detailResult = detailOrList.list[0];
} else if (Array.isArray(detailOrList)) {
detailResult = detailOrList[0];
} else {
detailResult = detailOrList;
}
if (!detailResult) {
throw new Error('Detail result is empty or invalid');
}
print('Detail Result:', {
vod_name: detailResult.vod_name,
vod_play_from: detailResult.vod_play_from,
// 截取 play_url 防止日志过长
vod_play_url: detailResult.vod_play_url ? (detailResult.vod_play_url.slice(0, 100) + '...') : 'N/A'
});
stats.pass('Detail');
} catch (e) {
stats.fail('Detail', e.message);
}
} else {
stats.skip('Detail', 'No valid URL found from Search or Category results');
}
// 5. 测试 Play (播放/阅读)
if (detailResult && detailResult.vod_play_url) {
try {
print('\n=== Testing Play ===');
// 解析 vod_play_url 获取播放链接
const flags = detailResult.vod_play_from.split('$$$');
const urls = detailResult.vod_play_url.split('$$$');
// 取第一个播放源的第一个章节
const firstFlagUrlList = urls[0].split('#');
const firstChapter = firstFlagUrlList[0];
// 格式: "章节名$参数" -> "第一章$1747899@@123456@@第一章"
const playUrl = firstChapter.split('$')[1];
print(`Playing Chapter: ${firstChapter.split('$')[0]}`);
print(`Play URL Params: ${playUrl}`);
const playResult = await drpyS.play(modulePath, env, flags[0], playUrl);
const logResult = {...playResult};
if (logResult.url && logResult.url.startsWith('novel://')) {
logResult.url = logResult.url.slice(0, 100) + '... (truncated content)';
}
print('Play Result:', logResult);
if (playResult.url || playResult.parse === 0) {
stats.pass('Play');
} else {
stats.fail('Play', 'No play URL or content returned');
}
} catch (e) {
stats.fail('Play', e.message);
}
} else {
const reason = !detailResult ? 'Dependency failed: Detail' : 'No vod_play_url in detail';
stats.skip('Play', reason);
}
} catch (error) {
print('Critical Error during test initialization:', error);
} finally {
stats.summary();
}
})();