File size: 3,056 Bytes
5ca3c16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Isolated JavaScript protocol checks, separate from real-browser acceptance."""
import json
import shutil
import subprocess
import unittest
from pathlib import Path

ROOT=Path(__file__).resolve().parents[3]
HARNESS=r'''
const assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm');
const mode=process.argv[2],requests=[],status={textContent:'正在打开应用。'};
let now=0,target=null,reads=0;
const state=id=>({id,status:reads>=4?'ready':'starting',kind:'run',reference:'run-real-reference'});
const context={URLSearchParams,Date:{now:()=>now},encodeURIComponent,
 crypto:require('node:crypto').webcrypto,addEventListener:()=>{},setInterval:()=>1,clearInterval:()=>{},
 location:{search:'?kind=run&reference=run-real-reference',replace:url=>target=url},
 document:{getElementById:()=>status},setTimeout:fn=>{now+=101000;fn();},
 fetch:async(url,options={})=>{
  requests.push([url,options.method||'GET']);
  if(url==='/api/session')return {json:async()=>({authenticated:true,csrf:'test-only-csrf'})};
  if(options.method==='POST')return {ok:true,json:async()=>state('lease-one')};
  assert.equal(url,'/api/preview?preview_id=lease-one');reads++;
  return {ok:true,json:async()=>state(mode==='switched'?'another-lease':'lease-one')};
 }};
const sandbox=vm.createContext(context);
(async()=>{
 const entry=new vm.SourceTextModule(fs.readFileSync(process.argv[1],'utf8'),{context:sandbox});
 await entry.link(async name=>{
  assert.equal(name,'./lifecycle.js');
  return new vm.SourceTextModule(fs.readFileSync(require('node:path').join(require('node:path').dirname(process.argv[1]),'lifecycle.js'),'utf8'),{context:sandbox});
 });
 await entry.evaluate();
setImmediate(()=>{
 assert.equal(requests.filter(r=>r[1]==='POST'&&r[0]==='/api/preview').length,1);
 assert.equal(requests.filter(r=>r[1]==='POST'&&r[0]==='/api/preview/client').length,1);
 if(mode==='switched'){
  assert.equal(reads,1);assert.equal(target,null);
  assert.match(status.textContent,/暂未就绪/);
 }else{
  assert.equal(reads,4);assert.equal(now,404000);
  assert.equal(target,'/preview-site/?lease=lease-one');
  assert.match(status.textContent,/核验/);
 }
 console.log(JSON.stringify({mode,reads,target}));
});
})().catch(error=>{console.error(error);process.exitCode=1;});
'''


@unittest.skipUnless(shutil.which('node'),'Node required for platform JavaScript protocol checks')
class PreviewLauncherTests(unittest.TestCase):
    def check_mode(self,mode):
        result=subprocess.run(['node','--experimental-vm-modules','-e',HARNESS,str(ROOT/'src/apps/workbench/preview_site/launch.js'),mode],
            capture_output=True,text=True,timeout=10)
        self.assertEqual(result.returncode,0,result.stderr)
        return json.loads(result.stdout)

    def test_waiting_beyond_five_minutes_uses_short_reads_and_exact_lease(self):
        self.assertEqual(self.check_mode('normal')['reads'],4)

    def test_switched_lease_stops_without_restarting_or_opening_another_app(self):
        self.assertIsNone(self.check_mode('switched')['target'])