vomebook commited on
Commit
a2b3337
·
1 Parent(s): 9fa3d76

Expand frontend reader and download regression coverage

Browse files
tests/reader/chapter-search/test_reader_chapter_worker.mjs CHANGED
@@ -78,14 +78,20 @@ assert.match((await search()).error, /索引无效/);
78
  const before = messages.length;
79
  await send(null); await send({type:"cancel"});
80
  assert.equal(messages.length, before);
81
- await send({type:"page", id:++id, session:null, offset:"bad"});
82
- assert.match(latest().error, /索引无效/);
 
 
 
 
 
 
83
  await send({type:"unknown", id:++id});
84
  assert.match(latest().error, /索引无效/);
85
  for (const index of [
86
  {...config.index, url:"https://evil.example/api/reader-content"},
87
  {...config.index, bytes:0}, {...config.index, bytes:64*1024*1024+1},
88
- {...config.index, sha256:"bad"},
89
  {...config.index, url:proxyOrigin+"/api/reader-bucket-resource?path=../bad"}
90
  ]) {
91
  await send({type:"init", configuration:{...config,index}});
@@ -100,6 +106,12 @@ for (const [mode, expected] of [["http",/HTTP 503/],["null",/索引无效/],
100
  assert.match((await search()).error, expected, mode);
101
  }
102
  assert.equal(streamCancelled, true);
 
 
 
 
 
 
103
  // Abort while the response stream is blocked in read(): the Worker must cancel
104
  // the underlying stream and a subsequent fetch must still be possible.
105
  responseMode = "held-stream"; streamCancelled = false;
 
78
  const before = messages.length;
79
  await send(null); await send({type:"cancel"});
80
  assert.equal(messages.length, before);
81
+ const invalidPagingRequests = requests.length;
82
+ for (const page of [{session:null, offset:"bad"}, {session:1, offset:"0"}]) {
83
+ const invalidId = ++id;
84
+ await send({type:"page", id:invalidId, ...page});
85
+ assert.equal(latest().id, invalidId);
86
+ assert.match(latest().error, /索引无效/);
87
+ }
88
+ assert.equal(requests.length, invalidPagingRequests);
89
  await send({type:"unknown", id:++id});
90
  assert.match(latest().error, /索引无效/);
91
  for (const index of [
92
  {...config.index, url:"https://evil.example/api/reader-content"},
93
  {...config.index, bytes:0}, {...config.index, bytes:64*1024*1024+1},
94
+ {...config.index, sha256:"bad"}, {...config.index, text_profile:42},
95
  {...config.index, url:proxyOrigin+"/api/reader-bucket-resource?path=../bad"}
96
  ]) {
97
  await send({type:"init", configuration:{...config,index}});
 
106
  assert.match((await search()).error, expected, mode);
107
  }
108
  assert.equal(streamCancelled, true);
109
+ responseMode = "valid";
110
+ // A response of exactly the expected length must still match the SHA-256.
111
+ const actualHash = config.index.sha256;
112
+ const otherHash = (actualHash[0] === "0" ? "1" : "0") + actualHash.slice(1);
113
+ await send({type:"init", configuration:{...config,index:{...config.index,sha256:otherHash}}});
114
+ assert.match((await search()).error, /校验失败/);
115
  // Abort while the response stream is blocked in read(): the Worker must cancel
116
  // the underlying stream and a subsequent fetch must still be possible.
117
  responseMode = "held-stream"; streamCancelled = false;
tests/reader/pdf-search/test_pdf_search_stream.mjs CHANGED
@@ -37,4 +37,12 @@ test('cancellation rejection is swallowed while abort still settles',async()=>{
37
  const body=new ReadableStream({pull(){ready();return new Promise(()=>{});},cancel(){throw new Error('cancel failed');}});
38
  const owner=new AbortController();const pending=readPdfSearchText(body,owner.signal,10);
39
  await waiting;owner.abort();await assert.rejects(pending,{name:'AbortError'});assert.equal(body.locked,false);
 
 
 
 
 
 
 
 
40
  });
 
37
  const body=new ReadableStream({pull(){ready();return new Promise(()=>{});},cancel(){throw new Error('cancel failed');}});
38
  const owner=new AbortController();const pending=readPdfSearchText(body,owner.signal,10);
39
  await waiting;owner.abort();await assert.rejects(pending,{name:'AbortError'});assert.equal(body.locked,false);
40
+
41
+ // A size-limit failure also owns stream cleanup; a failed cancellation must
42
+ // not mask the size error or leave the body locked.
43
+ let cancellations=0;
44
+ const oversized=new ReadableStream({start(controller){controller.enqueue(Uint8Array.of(1,2));},
45
+ cancel(){cancellations++;throw new Error('cancel failed after limit');}});
46
+ await assert.rejects(readPdfSearchBytes(oversized,signal(),1,1),/READER_RESOURCE_LIMIT/);
47
+ assert.equal(cancellations,1);assert.equal(oversized.locked,false);
48
  });
tests/reader/text/test_reader_text_baseline.mjs CHANGED
@@ -51,6 +51,8 @@ test('encoding detection handles BOMs, valid UTF-8, UTF-16 heuristics and legacy
51
  assert.equal(detect(Uint8Array.of(0xff),'Русский'),'windows-1251');
52
  assert.equal(detect(Uint8Array.of(0xc4,0xe3,0xba,0xc3),'中文'),'gb18030');
53
  assert.equal(detect(Uint8Array.of(0xa4,0xa4,0xa4,0xe5),'中文'),'big5');
 
 
54
  // Compare the original two-filter heuristic on random bytes, BOMs and
55
  // threshold edges. Only the zero scan is replaced; decoder scoring stays.
56
  const oldHeuristic=bytes=>{
@@ -108,6 +110,20 @@ test('stream handles split UTF-8 BOM and codepoints and releases its resource',a
108
  await f.context.renderPlainText(responseChunks([]));
109
  assert.deepEqual(samples,[[]]);assert.equal(f.context.content.textContent,'');
110
  assert.deepEqual(f.events.filter(event=>event==='track'||event==='untrack'),['track','untrack']);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  } finally {f.restore();}
112
  });
113
 
@@ -160,6 +176,14 @@ test('block boundaries preserve surrogate pairs and CRLF without creating oversi
160
  const last=block.textContent.charCodeAt(block.textContent.length-1);
161
  assert.ok(!(last>=0xd800&&last<=0xdbff));assert.notEqual(last,13);
162
  }
 
 
 
 
 
 
 
 
163
  } finally {f.restore();}
164
  });
165
 
 
51
  assert.equal(detect(Uint8Array.of(0xff),'Русский'),'windows-1251');
52
  assert.equal(detect(Uint8Array.of(0xc4,0xe3,0xba,0xc3),'中文'),'gb18030');
53
  assert.equal(detect(Uint8Array.of(0xa4,0xa4,0xa4,0xe5),'中文'),'big5');
54
+ assert.equal(detect(Uint8Array.of(0xcf,0xf0,0xe8,0xe2,0xe5,0xf2,0x21)),'windows-1251',
55
+ 'legacy Cyrillic text can be detected without a language hint in the title');
56
  // Compare the original two-filter heuristic on random bytes, BOMs and
57
  // threshold edges. Only the zero scan is replaced; decoder scoring stays.
58
  const oldHeuristic=bytes=>{
 
110
  await f.context.renderPlainText(responseChunks([]));
111
  assert.deepEqual(samples,[[]]);assert.equal(f.context.content.textContent,'');
112
  assert.deepEqual(f.events.filter(event=>event==='track'||event==='untrack'),['track','untrack']);
113
+
114
+ for (const [encoding, bom, a, b] of [
115
+ ['utf-16le', [0xff,0xfe], [0x41,0], [0x42,0]],
116
+ ['utf-16be', [0xfe,0xff], [0,0x41], [0,0x42]]
117
+ ]) {
118
+ f.context.content.children.length=0;f.events.length=0;samples.length=0;
119
+ const response=responseChunks([Uint8Array.of(bom[0]),Uint8Array.of(),Uint8Array.of(bom[1]),
120
+ Uint8Array.of(a[0]),Uint8Array.of(a[1],b[0]),Uint8Array.of(b[1])]);
121
+ await f.context.renderPlainText(response);
122
+ assert.equal(f.context.content.textContent,'AB',encoding);
123
+ assert.deepEqual(samples,[bom],`${encoding} decoder selected at the split BOM`);
124
+ assert.equal(response.body.locked,false);
125
+ assert.deepEqual(f.events.filter(event=>event==='track'||event==='untrack'),['track','untrack']);
126
+ }
127
  } finally {f.restore();}
128
  });
129
 
 
176
  const last=block.textContent.charCodeAt(block.textContent.length-1);
177
  assert.ok(!(last>=0xd800&&last<=0xdbff));assert.notEqual(last,13);
178
  }
179
+
180
+ f.context.content.children.length=0;
181
+ const before='x'.repeat(32767), after='\r\n'+'y'.repeat(32763)+'\nend';
182
+ const encode=text=>new TextEncoder().encode(text);
183
+ await f.context.renderPlainText(responseChunks([encode('\ufeff'+before),encode(after)]));
184
+ assert.equal(f.context.content.textContent,before+after);
185
+ const streamed=f.context.content.children[0].children.map(block=>block.textContent);
186
+ assert.deepEqual(streamed,[before,after.slice(0,-3),'end']);
187
  } finally {f.restore();}
188
  });
189
 
tests/reader/text/test_reader_text_faults.mjs CHANGED
@@ -6,7 +6,8 @@ import {createReaderTextFormat} from '../../../static/reader/formats/reader-text
6
  test('reader errors preserve the original reason and release the reader lock', async () => {
7
  const old={document:globalThis.document,security:globalThis.VoiceOfMLReaderSecurity};
8
  const failure=new Error('source failed'), events=[], reader={read:async()=>{throw failure;},
9
- cancel:async reason=>events.push(['cancel',reason]),releaseLock:()=>events.push('release')};
 
10
  globalThis.document={createElement:()=>({className:'',appendChild(){}})};
11
  globalThis.VoiceOfMLReaderSecurity={LIMITS:{documentBytes:32},assertResponseSize(){}};
12
  const context={content:{appendChild(){}},documentState:{title:''},assertReaderActive(){},
 
6
  test('reader errors preserve the original reason and release the reader lock', async () => {
7
  const old={document:globalThis.document,security:globalThis.VoiceOfMLReaderSecurity};
8
  const failure=new Error('source failed'), events=[], reader={read:async()=>{throw failure;},
9
+ cancel:async reason=>{events.push(['cancel',reason]);throw new Error('cancel also failed');},
10
+ releaseLock:()=>events.push('release')};
11
  globalThis.document={createElement:()=>({className:'',appendChild(){}})};
12
  globalThis.VoiceOfMLReaderSecurity={LIMITS:{documentBytes:32},assertResponseSize(){}};
13
  const context={content:{appendChild(){}},documentState:{title:''},assertReaderActive(){},
tests/search/download/test_download_controller_contract.js CHANGED
@@ -85,9 +85,26 @@ test("shared checks preserve independent cancellation, cached success and expira
85
  });
86
 
87
  test("two active checks bound the queue and abandoned work never starts", async () => {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
  const {controller: c, requests} = fixture();
89
  const thirdOwner = new AbortController();
90
  const first = c.checkDownload("a"), second = c.checkDownload("b");
 
91
  const third = c.checkDownload("c", false, thirdOwner.signal);
92
  assert.equal(c.activeDownloadChecks, 2);
93
  assert.equal(c.downloadCheckQueue.length, 1);
@@ -98,6 +115,7 @@ test("two active checks bound the queue and abandoned work never starts", async
98
  assert.equal(c.downloadChecks.has("c"), false);
99
  requests[0].resolve(response({ok: true}));
100
  assert.equal(await first, true);
 
101
  assert.equal(requests.length, 2);
102
  assert.equal(c.downloadCheckQueue.length, 0);
103
  requests[1].resolve(response({ok: true}));
 
85
  });
86
 
87
  test("two active checks bound the queue and abandoned work never starts", async () => {
88
+ let allowSpeculation = false, batchActive = false;
89
+ const guarded = fixture({
90
+ isSpeculativeAllowed: () => allowSpeculation, isBatchActive: () => batchActive,
91
+ });
92
+ assert.equal(await guarded.controller.checkDownload("opted-out", true), false);
93
+ allowSpeculation = true;
94
+ batchActive = true;
95
+ assert.equal(await guarded.controller.checkDownload("batch-active", true), false);
96
+ const aborted = new AbortController();
97
+ aborted.abort();
98
+ assert.equal(await guarded.controller.checkDownload("already-aborted", false, aborted.signal), false);
99
+ assert.equal(guarded.requests.length, 0);
100
+ assert.equal(guarded.timers.size, 0);
101
+ assert.equal(guarded.controller.downloadChecks.size, 0);
102
+ assert.equal(guarded.controller.downloadCheckQueue.length, 0);
103
+
104
  const {controller: c, requests} = fixture();
105
  const thirdOwner = new AbortController();
106
  const first = c.checkDownload("a"), second = c.checkDownload("b");
107
+ const shared = c.checkDownload("a", true); // Join an existing check despite busy slots.
108
  const third = c.checkDownload("c", false, thirdOwner.signal);
109
  assert.equal(c.activeDownloadChecks, 2);
110
  assert.equal(c.downloadCheckQueue.length, 1);
 
115
  assert.equal(c.downloadChecks.has("c"), false);
116
  requests[0].resolve(response({ok: true}));
117
  assert.equal(await first, true);
118
+ assert.equal(await shared, true);
119
  assert.equal(requests.length, 2);
120
  assert.equal(c.downloadCheckQueue.length, 0);
121
  requests[1].resolve(response({ok: true}));