File size: 7,257 Bytes
5c08c9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Real bundled routes + real UI selection. Only auth/location/API user state is mocked.
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const { chromium } = require(process.env.PLAYWRIGHT_MODULE || 'playwright');
const root = path.resolve(__dirname, '..');
const files = ['demo-sample-runs.json','approved-road-runs.json','tshirt-sample-runs.json','heart-sample-runs.json'];
const samples = files.flatMap(file => JSON.parse(fs.readFileSync(path.join(root,'main/public',file),'utf8')));
const orientations = JSON.parse(fs.readFileSync(path.join(root,'main/app/_data/sampleRouteOrientations.json'),'utf8'));
assert.equal(samples.length, 232);
assert.equal(Object.keys(orientations).length, samples.length, 'every sample needs metadata');
const base = process.env.MAP_TEST_BASE || 'http://127.0.0.1:3113';

(async () => {
  const browser = await chromium.launch({headless:true,channel:'chrome'});
  try {
    const context = await browser.newContext({viewport:{width:1280,height:1000},serviceWorkers:'block',
      permissions:['geolocation'],geolocation:{latitude:37.51,longitude:127.03}});
    await context.addInitScript(() => {
      let leaflet;
      window.__testMaps=[];
      Object.defineProperty(window,'L',{configurable:true,get:()=>leaflet,set(value){
        leaflet=value;
        value.Map.addInitHook(function(){window.__testMaps.push(this);});
      }});
      const token=`${btoa(JSON.stringify({alg:'none'}))}.${btoa(JSON.stringify({sub:'1',exp:Math.floor(Date.now()/1000)+3600}))}.fixture`;
      localStorage.setItem('access_token',token);
      document.cookie=`access_token=${token}; path=/`;
      sessionStorage.setItem('tranimal:ui-flow-permits',JSON.stringify({'route-search':{token:'sample-qa',expiresAt:Date.now()+3600000}}));
    });
    const page=await context.newPage();
    const errors=[];
    page.on('pageerror',e=>errors.push(e.message));
    await page.route('**/api/**',route=>route.fulfill({json:{nickname:'테스트',username:'테스트',routes:[],posts:[],items:[]}}));
    // Do not bulk-download OSM tiles while selecting hundreds of routes.
    const tilePattern='https://*.tile.openstreetmap.org/**';
    const stubTile=route=>route.fulfill({contentType:'image/png',body:Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j4uoAAAAASUVORK5CYII=','base64')});
    let checked=0;
    for(const [label,tab] of [['dog','강아지 코스'],['symbol_star','별 코스'],['t_shirt','티셔츠 코스'],['heart','하트 코스']]) {
      await page.route(tilePattern,stubTile);
      await page.goto(`${base}/saved-routes`);
      await page.getByRole('tab',{name:tab,exact:true}).click();
      const group=samples.filter(s=>s.label===label);
      await page.getByRole('button',{name:`더보기 (${group.length-4}개)`,exact:true}).click();
      const articles=page.getByRole('tabpanel').locator('article');
      assert.equal(await articles.count(),group.length,`${label}: actual sample list`);
      for(let index=0;index<group.length;index++) {
        const sample=group[index];
        const expected=(orientations[sample.id].degrees%360+360)%360;
        await articles.nth(index).getByRole('button',{name:'지도',exact:true}).click();
        await page.waitForFunction(({expected,coords})=>{
          const map=window.__testMaps.find(m=>m._loaded&&m.getContainer().isConnected);
          if(!map||Math.abs(map.getBearing()-expected)>.001)return false;
          let found=false;
          map.eachLayer(layer=>{if(layer instanceof window.L.Polyline){
            found=JSON.stringify(layer.getLatLngs().map(p=>[p.lat,p.lng]))===JSON.stringify(coords);
          }});
          const pixels=coords.map(p=>map.latLngToContainerPoint(p));
          const xs=pixels.map(p=>p.x),ys=pixels.map(p=>p.y),size=map.getSize();
          const minX=Math.min(...xs),maxX=Math.max(...xs),minY=Math.min(...ys),maxY=Math.max(...ys);
          const fits=minX>=-1&&minY>=-1&&maxX<=size.x+1&&maxY<=size.y+1;
          const fills=Math.max((maxX-minX)/(size.x-40),(maxY-minY)/(size.y-40))>.45;
          return found&&fits&&fills;
        },{expected,coords:sample.route});
        const toggle=page.getByRole('button',{name:'도안 방향에 맞춰 보기',exact:true});
        assert.equal(await toggle.getAttribute('aria-pressed'),'true',sample.id);
        if(index===0) {
          // Selecting the next sample must restore its own template orientation.
          await toggle.click();
          await toggle.click();
        }
        checked++;
      }
      // This button opens course detail, not an actual running session.
      await page.unroute(tilePattern,stubTile);
      await articles.nth(0).getByRole('button',{name:'달리기',exact:true}).click();
      await page.waitForURL('**/route-results/**');
      // Routed one-pixel test tiles must not leak into evidence screenshots.
      const cdp=await context.newCDPSession(page);
      await cdp.send('Network.clearBrowserCache');
      await cdp.detach();
      await page.reload();
      const expected=(orientations[group[0].id].degrees%360+360)%360;
      await page.waitForFunction(expected=>window.__testMaps.some(m=>m._loaded&&m.getContainer().isConnected&&Math.abs(m.getBearing()-expected)<.001),expected);
      if(process.env.SAMPLE_SCREENSHOT_DIR){
        await page.waitForFunction(()=>{
          const tiles=Array.from(document.querySelectorAll('.leaflet-tile'));
          return tiles.length>0&&tiles.every(t=>t.complete&&t.naturalWidth>1);
        });
        await page.screenshot({path:path.join(process.env.SAMPLE_SCREENSHOT_DIR,`actual-${label}-detail.png`)});
      }
      console.log(`PASS ${label}: ${group.length} actual sample selections + detail handoff`);
    }
    assert.equal(checked,232);
    await page.route(tilePattern,stubTile);
    for(const [label,name] of [['dog','강아지'],['symbol_star','별'],['t_shirt','티셔츠'],['heart','하트']]) {
      await page.goto(`${base}/route-search?flowToken=sample-qa`);
      const sample=samples.find(s=>s.label===label&&!s.id.startsWith('approved-'));
      await page.getByRole('button',{name:new RegExp(`${name} 샘플 .*개 보기`)}).click();
      await page.locator('[aria-label="AI 샘플 전체 목록"]').getByRole('button').filter({hasText:sample.title}).first().click();
      const expected=(orientations[sample.id].degrees%360+360)%360;
      await page.waitForFunction(expected=>window.__testMaps.some(m=>m._loaded&&m.getContainer().isConnected&&Math.abs(m.getBearing()-expected)<.001),expected);
      await page.getByRole('button',{name:'이 루트로 달리기',exact:true}).click();
      await page.waitForURL('**/route-results/**');
      await page.waitForFunction(expected=>window.__testMaps.some(m=>m._loaded&&m.getContainer().isConnected&&Math.abs(m.getBearing()-expected)<.001),expected);
      console.log(`PASS route-search ${label}: real gallery selection + detail handoff`);
    }
    assert.deepEqual(errors,[],'browser errors');
    console.log(`PASS all ${checked} real sample GPS polylines unchanged; all displayed with per-sample orientation`);
  } finally {await browser.close();}
})().catch(e=>{console.error(e);process.exitCode=1;});