| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- import { test } from 'node:test';
- import assert from 'node:assert/strict';
- import { readFileSync } from 'node:fs';
- import vm from 'node:vm';
- import { PGlite } from '@electric-sql/pglite';
- const source = readFileSync(new URL('../deploy-admin-functions.mjs', import.meta.url), 'utf8');
- const gateway = source.match(/const appGatewayCode = String.raw`([\s\S]*?)\n`;/)?.[1];
- assert.ok(gateway, 'app gateway source must be available');
- async function setup(t) {
- const db = new PGlite();
- t.after(() => db.close());
- await db.exec(`
- CREATE TABLE "PracticeRecord" (id double precision, company text, yhid text, scid text, kcid text, xxcs text, jrscb text, "updatedAt" timestamptz);
- CREATE TABLE "CommonModel" (company text, "modelId" numeric, "generalId" numeric, "itemId" numeric, title text);
- CREATE TABLE "VocabularyWord" (company text, id numeric, sy text);
- INSERT INTO "CommonModel" VALUES
- ('7pIbDBJmKx',52,101,1,'apple'), ('7pIbDBJmKx',52,102,2,'banana'),
- ('7pIbDBJmKx',52,103,3,'orange'), ('7pIbDBJmKx',53,901,11,'practice'),
- ('other',52,101,1,'foreign');
- INSERT INTO "VocabularyWord" VALUES ('7pIbDBJmKx',1,'苹果');
- INSERT INTO "PracticeRecord" VALUES
- (11,'7pIbDBJmKx','42','101','100',NULL,'1','2026-10-14'),
- (12,'7pIbDBJmKx','42','102','100','1','true','2026-10-13'),
- (13,'7pIbDBJmKx','42','103','100','2.0','1','2026-10-12'),
- (14,'7pIbDBJmKx','42','103','100','0','0','2026-10-11'),
- (15,'7pIbDBJmKx','99','101','100','0','1','2026-10-14'),
- (16,'other','42','101','100','0','1','2026-10-14'),
- (17,'7pIbDBJmKx','42','999','100','0','1','2026-10-14');
- `);
- let queries = 0;const calls=[];
- const context = vm.createContext({
- Psql: {
- one: async (sql, values) => { queries++;calls.push({sql,values}); return (await db.query(sql, values)).rows[0]; },
- query: async (sql, values) => { queries++;calls.push({sql,values}); return (await db.query(sql, values)).rows; },
- },
- });
- // Execute the actual app scope without injecting helpers from the admin gateway.
- vm.runInContext(gateway, context);
- context.authorizeRequestedUser = async (_current, uid) => {
- if (uid !== 42) throw new Error('无权访问该学员');
- return uid;
- };
- return { read: input => context.newWordPage({ uid: 42, ...input }, { get: () => 1 }), queryCount: () => queries, db, calls };
- }
- test('生词本未学分页保留全量状态计数,并隔离其他学员和帐套', async t => {
- const { read } = await setup(t);
- const first = await read({ learningStatus: ' pending ', psize: 1, cpage: 1 });
- assert.deepEqual(JSON.parse(JSON.stringify(first.page)), { itemCount: 2, pageCount: 2, pageIndex: 1, pageSize: 1, pendingCount: 2, completedCount: 1 });
- assert.equal(first.rows[0].Title, 'apple');
- assert.equal(first.rows[0].GeneralID, 901);
- assert.equal(first.rows[0].detail[0].sy, '苹果');
- const second = await read({ learningStatus: 'pending', psize: 1, cpage: 2 });
- assert.equal(second.rows[0].Title, 'banana');
- });
- test('生词本已学及旧版混合列表均可读取', async t => {
- const { read } = await setup(t);
- const completed = await read({ learningStatus: 'completed' });
- assert.equal(completed.page.itemCount, 1);
- assert.equal(completed.rows[0].Title, 'orange');
- const mixed = await read({});
- assert.equal(mixed.page.itemCount, 3);
- assert.equal(mixed.rows.length, 3);
- });
- test('生词本越界页返回空列表并保留正确计数', async t => {
- const { read } = await setup(t);
- const result = await read({ learningStatus: 'pending', psize: 30, cpage: 2 });
- assert.equal(result.rows.length, 0);
- assert.equal(result.page.itemCount, 2);
- });
- test('生词本拒绝非法状态和越权访问,不执行查询', async t => {
- const { read, queryCount } = await setup(t);
- await assert.rejects(read({ learningStatus: 'invalid' }), /生词学习状态无效/);
- await assert.rejects(read({ uid: 99 }), /无权访问/);
- assert.equal(queryCount(), 0);
- });
- test('生词分页使用公司、模型和词条编号完整索引键,而非逐词扫描全部记录',async t=>{
- const {read,db,calls}=await setup(t);
- await db.exec('INSERT INTO "CommonModel" SELECT \'7pIbDBJmKx\',52,i,i,\'extra-word\' FROM generate_series(10000,20000) i;CREATE INDEX wordbook_word_lookup ON "CommonModel"(company,"modelId","generalId");CREATE INDEX wordbook_practice_lookup ON "PracticeRecord"(company,yhid);ANALYZE;SET enable_seqscan=off;SET enable_hashjoin=off;SET enable_mergejoin=off;');
- await read({learningStatus:'pending'});
- const {sql,values}=calls.find(call=>call.sql.startsWith('SELECT p.*'));
- const result=await db.query('EXPLAIN (FORMAT JSON) '+sql,values),conditions=[];
- const walk=node=>{if(node['Index Name']==='wordbook_word_lookup'&&node.Alias==='c')conditions.push(node['Index Cond']||'');for(const child of node.Plans||[])walk(child);};
- walk(result.rows[0]['QUERY PLAN'][0].Plan);
- assert.ok(conditions.some(condition=>condition.includes('modelId')&&condition.includes('generalId')),'词条查找必须使用索引中的模型和编号,避免随词库规模逐词扫描');
- });
- test('索引优化保留原文本编号匹配,不把带前导零或小数的历史键误配成单词',async t=>{
- const {read,db}=await setup(t);
- await db.exec(`INSERT INTO "PracticeRecord" VALUES (21,'7pIbDBJmKx','42','00101','100','0','1',now()),(22,'7pIbDBJmKx','42','101.0','100','0','1',now()),(23,'7pIbDBJmKx','42','invalid','100','0','1',now());`);
- const result=await read({learningStatus:'pending'});assert.equal(result.page.itemCount,2);assert.deepEqual(result.rows.map(row=>row.Title),['apple','banana']);
- });
- test('生词本精简响应保留教学字段、词汇身份及分页,兼容旧完整响应',async t=>{
- const {read,db}=await setup(t);
- await db.exec(`ALTER TABLE "CommonModel" ADD COLUMN body text;UPDATE "CommonModel" SET body=repeat('metadata',400);ALTER TABLE "VocabularyWord" ADD COLUMN yb text,ADD COLUMN yp text,ADD COLUMN lj text;UPDATE "VocabularyWord" SET yb='/ˈæpəl/',yp='apple.mp3',lj='an apple' WHERE id=1;`);
- const full=await read({learningStatus:'pending'}),compact=await read({learningStatus:'pending',compact:true});
- assert.equal(full.rows[0].detail[0].body.length,3200);
- assert.equal(compact.rows[0].detail[0].body,undefined);
- assert.deepEqual(JSON.parse(JSON.stringify(compact.page)),JSON.parse(JSON.stringify(full.page)));
- for(let i=0;i<full.rows.length;i++){
- for(const key of ['id','kcid','scid','xxcs','yhid','jrscb','GeneralID','Title'])assert.deepEqual(compact.rows[i][key],full.rows[i][key],key);
- for(const key of ['GeneralID','NodeID','Title','sy','yb','yp','lj'])assert.deepEqual(compact.rows[i].detail[0][key],full.rows[i].detail[0][key],key);
- }
- assert.ok(JSON.stringify(compact).length<JSON.stringify(full).length/2);
- assert.equal((await read({compact:'true'})).rows[0].detail[0].body.length,3200);
- });
|