first commit
This commit is contained in:
1 parent
18d31d5dcf
commit
77a5f5248c
31 files changed
+6637
-30
No files matched your search
@@ -0,0 +1,104 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { AutoReservationService } from '../electron/main/auto-reservation'
|
||||
import { CLOCK_CALIBRATION_DEFAULTS, type AutoReservationConfig, type ClockEstimate, type ReservationResult } from '../src/type/reservation'
|
||||
|
||||
function estimate(): ClockEstimate {
|
||||
const now = Date.now()
|
||||
return {
|
||||
monitoring: true,
|
||||
observedAtMs: now,
|
||||
estimatedServerTimeMs: now,
|
||||
offsetMs: 0,
|
||||
driftPpm: 0,
|
||||
minRttMs: 80,
|
||||
p50RttMs: 82,
|
||||
p95RttMs: 90,
|
||||
oneWayMs: 40,
|
||||
uncertaintyMs: 540,
|
||||
sampleAgeMs: 0,
|
||||
acceptedSamples: 8,
|
||||
rawOffsetMs: 0,
|
||||
boundaryCount: 5,
|
||||
boundaryOffsetMs: 0,
|
||||
boundaryUncertaintyMs: 50,
|
||||
boundarySpreadMs: 20,
|
||||
recommendedCorrectionMs: 0,
|
||||
calibrationReady: true,
|
||||
calibrationApplied: true,
|
||||
calibrationSettings: CLOCK_CALIBRATION_DEFAULTS,
|
||||
remoteIp: '13.125.18.86',
|
||||
quality: 'fair',
|
||||
samples: [],
|
||||
}
|
||||
}
|
||||
|
||||
function config(targetServerTimeMs: number): AutoReservationConfig {
|
||||
return {
|
||||
targetServerTimeMs,
|
||||
userOffsetMs: 0,
|
||||
captchaPastedAtMs: Date.now(),
|
||||
request: {
|
||||
branchNum: 22, themeNum: 66, themeInfoNum: 44,
|
||||
date: '2026-08-18', timeNum: 2309, timeLabel: '14:25', themeName: '내 방',
|
||||
totalPrice: 60_000, person: 2, name: '테스트', phone: '010-1234-5678',
|
||||
captchaToken: 'x'.repeat(100),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
describe('single-shot auto reservation scheduler', () => {
|
||||
afterEach(() => vi.useRealTimers())
|
||||
|
||||
it('consumes one token and submits exactly once', async () => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-08-12T06:00:00.000Z'))
|
||||
const execute = vi.fn<() => Promise<ReservationResult>>().mockResolvedValue({
|
||||
success: true, message: '완료', reservationNum: 'R-1',
|
||||
transport: {
|
||||
sentAtMs: Date.now(), receivedAtMs: Date.now() + 80, rttMs: 80,
|
||||
httpStatus: 200, remoteIp: '13.125.18.86', reusedSocket: true,
|
||||
},
|
||||
})
|
||||
const clock = { ensureSample: async () => estimate(), getEstimate: estimate, setAutoTarget: vi.fn() }
|
||||
const service = new AutoReservationService(clock, execute, vi.fn())
|
||||
|
||||
await service.arm(config(Date.now() + 1_000))
|
||||
await vi.advanceTimersByTimeAsync(1_500)
|
||||
|
||||
expect(execute).toHaveBeenCalledTimes(1)
|
||||
expect(service.getState().status).toBe('succeeded')
|
||||
expect(service.getState().tokenStatus).toBe('consumed')
|
||||
await vi.advanceTimersByTimeAsync(5_000)
|
||||
expect(execute).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('disarming clears the schedule and prevents submission', async () => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-08-12T06:00:00.000Z'))
|
||||
const execute = vi.fn<() => Promise<ReservationResult>>()
|
||||
const clock = { ensureSample: async () => estimate(), getEstimate: estimate, setAutoTarget: vi.fn() }
|
||||
const service = new AutoReservationService(clock, execute, vi.fn())
|
||||
|
||||
await service.arm(config(Date.now() + 1_000))
|
||||
service.disarm()
|
||||
await vi.advanceTimersByTimeAsync(2_000)
|
||||
|
||||
expect(execute).not.toHaveBeenCalled()
|
||||
expect(service.getState().tokenStatus).toBe('empty')
|
||||
})
|
||||
|
||||
it('does not fire when the target is already missed by more than one second', async () => {
|
||||
vi.useFakeTimers()
|
||||
vi.setSystemTime(new Date('2026-08-12T06:00:00.000Z'))
|
||||
const execute = vi.fn<() => Promise<ReservationResult>>()
|
||||
const clock = { ensureSample: async () => estimate(), getEstimate: estimate, setAutoTarget: vi.fn() }
|
||||
const service = new AutoReservationService(clock, execute, vi.fn())
|
||||
await service.arm(config(Date.now() + 500))
|
||||
|
||||
vi.setSystemTime(Date.now() + 2_000)
|
||||
await vi.runOnlyPendingTimersAsync()
|
||||
|
||||
expect(execute).not.toHaveBeenCalled()
|
||||
expect(service.getState().status).toBe('failed')
|
||||
})
|
||||
})
|
||||
+59
-15
@@ -40,7 +40,7 @@ test.beforeAll(async () => {
|
||||
await startXvfbOnLinux()
|
||||
|
||||
electronApp = await electron.launch({
|
||||
args: ['.', '--no-sandbox'],
|
||||
args: ['.', '--no-sandbox', `--user-data-dir=${path.join(root, 'test-results', `electron-${process.pid}`)}`],
|
||||
cwd: root,
|
||||
env: { ...process.env, NODE_ENV: 'development' },
|
||||
})
|
||||
@@ -68,28 +68,72 @@ test.afterAll(async () => {
|
||||
}
|
||||
})
|
||||
|
||||
test.describe('[electron-vite-react] e2e tests', () => {
|
||||
test.describe('[escape-reserve] e2e tests', () => {
|
||||
test('startup', async () => {
|
||||
const title = await page.title()
|
||||
expect(title).toBe('Electron + Vite + React')
|
||||
expect(title).toBe('ESCAPE / RESERVE')
|
||||
})
|
||||
|
||||
test('should be home page is load correctly', async () => {
|
||||
const h1 = await page.$('h1')
|
||||
const title = await h1?.textContent()
|
||||
expect(title).toBe('A sharp starter with Tailwind-first styling.')
|
||||
test('loads the reservation desk', async () => {
|
||||
await expect(page.locator('h1')).toHaveText('방을 고르고, 탈출을 예약하세요.')
|
||||
})
|
||||
|
||||
test('should be count button can click', async () => {
|
||||
const countButton = await page.$('button:has-text("Increment counter")')
|
||||
const countValue = await page.$('div.text-5xl')
|
||||
test('exposes the reservation bridge', async () => {
|
||||
const methods = await page.evaluate(() => Object.keys(window.reservationApi).sort())
|
||||
expect(methods).toEqual([
|
||||
'armAutoReservation', 'configureClock', 'disarmAutoReservation', 'getAutoReservationState',
|
||||
'getBranches', 'getClockState', 'getThemeDetail', 'getThemes', 'getTimes',
|
||||
'openCaptcha', 'prepare', 'runTimingTest', 'startClockMonitor',
|
||||
'stopClockMonitor', 'submit', 'subscribeAutoState', 'subscribeClock',
|
||||
])
|
||||
})
|
||||
|
||||
const valueBeforeClick = await countValue?.textContent()
|
||||
expect(valueBeforeClick).toBe('0')
|
||||
test('loads live branches and themes without submitting', async () => {
|
||||
const branch = page.getByLabel('지점')
|
||||
await expect.poll(() => branch.locator('option').count()).toBeGreaterThan(1)
|
||||
await branch.selectOption({ label: 'STATION' })
|
||||
|
||||
await countButton?.click()
|
||||
const theme = page.getByLabel('테마')
|
||||
await expect.poll(() => theme.locator('option').count(), {
|
||||
timeout: 15_000,
|
||||
}).toBeGreaterThan(1)
|
||||
})
|
||||
|
||||
const valueAfterClick = await countValue?.textContent()
|
||||
expect(valueAfterClick).toBe('1')
|
||||
test('monitors live server time and runs a safe timing probe', async () => {
|
||||
await page.getByRole('button', { name: '자동 예약' }).click()
|
||||
await page.getByRole('button', { name: '모니터 시작' }).click()
|
||||
await expect(page.getByRole('button', { name: '모니터 중지' })).toBeVisible({ timeout: 10_000 })
|
||||
await expect(page.getByLabel('관측 서버시간 값')).toContainText(':')
|
||||
|
||||
await page.getByRole('button', { name: '정밀 보정 설정' }).click()
|
||||
await expect(page.getByText('경계 측정 간격 (ms)')).toBeVisible()
|
||||
await page.getByRole('button', { name: '기본값' }).click()
|
||||
await page.getByRole('button', { name: '설정 적용' }).click()
|
||||
|
||||
await page.getByRole('button', { name: '3초 테스트' }).click()
|
||||
await expect(page.getByText('arrival error')).toBeVisible({ timeout: 10_000 })
|
||||
})
|
||||
|
||||
test('arms and disarms an automatic reservation without submitting', async () => {
|
||||
const theme = page.getByLabel('테마')
|
||||
await theme.selectOption({ index: 1 })
|
||||
await expect(page.locator('button.time-slot').first()).toBeVisible({ timeout: 15_000 })
|
||||
await page.locator('button.time-slot').first().click()
|
||||
|
||||
await page.getByPlaceholder('홍길동').fill('테스트')
|
||||
await page.getByPlaceholder('010-0000-0000').fill('010-1234-5678')
|
||||
await page.getByLabel('캡차 토큰').fill('x'.repeat(100))
|
||||
await page.getByRole('checkbox').check()
|
||||
|
||||
const target = await page.evaluate(() => {
|
||||
const value = new Date(Date.now() + 30_000 + 9 * 60 * 60 * 1_000)
|
||||
return value.toISOString().slice(0, -1)
|
||||
})
|
||||
await page.getByLabel('실행 시각 (KST, ms)').fill(target)
|
||||
await page.getByRole('button', { name: '자동 예약 무장' }).click()
|
||||
await expect(page.getByText('armed', { exact: true })).toBeVisible({ timeout: 10_000 })
|
||||
|
||||
await page.getByRole('button', { name: '자동 예약 해제' }).click()
|
||||
await expect(page.getByText('cancelled', { exact: true })).toBeVisible()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,33 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { EDGE_USER_AGENT, edgeBrowserHeaders, encodeMultipart } from '../electron/main/keyescape-http'
|
||||
|
||||
describe('Edge-compatible Keyescape request metadata', () => {
|
||||
it('matches the captured Edge client hints and XHR metadata', () => {
|
||||
const headers = edgeBrowserHeaders({
|
||||
accept: 'application/json, text/javascript, */*; q=0.01',
|
||||
referer: 'https://www.keyescape.com/reservation2.php',
|
||||
xhr: true,
|
||||
})
|
||||
|
||||
expect(headers['User-Agent']).toBe(EDGE_USER_AGENT)
|
||||
expect(headers['Sec-CH-UA']).toContain('Microsoft Edge')
|
||||
expect(headers['Sec-CH-UA']).toContain('v="151"')
|
||||
expect(headers['Sec-CH-UA-Mobile']).toBe('?0')
|
||||
expect(headers['Sec-CH-UA-Platform']).toBe('"Windows"')
|
||||
expect(headers['Sec-Fetch-Mode']).toBe('cors')
|
||||
expect(headers['Sec-Fetch-Dest']).toBe('empty')
|
||||
expect(headers['X-Requested-With']).toBe('XMLHttpRequest')
|
||||
expect(headers.Referer).toBe('https://www.keyescape.com/reservation2.php')
|
||||
})
|
||||
|
||||
it('uses a fresh WebKit-style multipart boundary', () => {
|
||||
const first = encodeMultipart({ device: 'pc', t: 'ins_rev' })
|
||||
const second = encodeMultipart({ device: 'pc' })
|
||||
|
||||
expect(first.boundary).toMatch(/^----WebKitFormBoundary[A-Za-z0-9_-]{16}$/)
|
||||
expect(second.boundary).not.toBe(first.boundary)
|
||||
expect(first.body.toString('utf8')).toContain(`--${first.boundary}\r\n`)
|
||||
expect(first.body.toString('utf8')).toContain('Content-Disposition: form-data; name="device"')
|
||||
expect(first.body.toString('utf8')).toMatch(/--\r\n$/)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseBranches, parsePriceOptions } from '../electron/main/reservation'
|
||||
|
||||
describe('reservation response parsers', () => {
|
||||
it('returns only public room branch fields', () => {
|
||||
const html = `<script>
|
||||
const originalZizumData = [
|
||||
{"num":22,"name":"STATION","phone":"010-4445-6082","category":"room","pass":"secret"},
|
||||
{"num":25,"name":"무비무드","phone":"010-0000-0000","category":"movie"}
|
||||
];
|
||||
</script>`
|
||||
|
||||
expect(parseBranches(html)).toEqual([
|
||||
{ num: 22, name: 'STATION', phone: '010-4445-6082' },
|
||||
])
|
||||
})
|
||||
|
||||
it('parses server-calculated per-person prices', () => {
|
||||
const html = `<select name="person" id="person">
|
||||
<option value='2' data-rev_price='60000' data-price='60000'>2명</option>
|
||||
<option value='4' data-rev_price='120000' data-price='120000'>4명</option>
|
||||
</select>`
|
||||
|
||||
expect(parsePriceOptions(html)).toEqual([
|
||||
{ person: 2, totalPrice: 60_000 },
|
||||
{ person: 4, totalPrice: 120_000 },
|
||||
])
|
||||
})
|
||||
})
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 87 KiB After Width: | Height: | Size: 295 KiB |
@@ -0,0 +1,118 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { appendClockSample, computePlannedSendAtMs, estimateBoundaryOffset, estimateClock, observationToSample, quantile } from '../electron/main/server-clock-core'
|
||||
import { CLOCK_CALIBRATION_DEFAULTS, type ClockSample } from '../src/type/reservation'
|
||||
|
||||
function boundarySamples(offsets: number[]): ClockSample[] {
|
||||
const base = 1_800_000_000_000
|
||||
return offsets.flatMap((offset, index) => {
|
||||
const serverBoundary = base + index * 2_000
|
||||
const beforeMidpoint = serverBoundary - offset - 25
|
||||
const afterMidpoint = serverBoundary - offset + 25
|
||||
return [
|
||||
{
|
||||
id: index * 2 + 1, sentAtMs: beforeMidpoint - 20, receivedAtMs: beforeMidpoint + 20,
|
||||
midpointMs: beforeMidpoint, serverDateMs: serverBoundary - 1_000, rttMs: 40,
|
||||
offsetEstimateMs: serverBoundary - 500 - beforeMidpoint,
|
||||
offsetMinMs: 0, offsetMaxMs: 0, remoteIp: '10.0.0.1', reusedSocket: true, accepted: true,
|
||||
},
|
||||
{
|
||||
id: index * 2 + 2, sentAtMs: afterMidpoint - 20, receivedAtMs: afterMidpoint + 20,
|
||||
midpointMs: afterMidpoint, serverDateMs: serverBoundary, rttMs: 40,
|
||||
offsetEstimateMs: serverBoundary + 500 - afterMidpoint,
|
||||
offsetMinMs: 0, offsetMaxMs: 0, remoteIp: '10.0.0.1', reusedSocket: true, accepted: true,
|
||||
},
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
describe('server clock estimator', () => {
|
||||
it('rejects cached and high-RTT observations', () => {
|
||||
const cached = observationToSample({
|
||||
id: 1, sentAtMs: 1_000, receivedAtMs: 1_080, rttMs: 80,
|
||||
serverDateHeader: new Date(1_000).toUTCString(), remoteIp: '127.0.0.1',
|
||||
reusedSocket: true, ageHeader: '2', statusCode: 200,
|
||||
})
|
||||
const slow = observationToSample({
|
||||
id: 2, sentAtMs: 1_000, receivedAtMs: 4_000, rttMs: 3_000,
|
||||
serverDateHeader: new Date(1_000).toUTCString(), remoteIp: '127.0.0.1',
|
||||
reusedSocket: false, statusCode: 200,
|
||||
})
|
||||
expect(cached.accepted).toBe(false)
|
||||
expect(slow.accepted).toBe(false)
|
||||
})
|
||||
|
||||
it('uses low-latency samples and reports distribution metrics', () => {
|
||||
const base = 1_800_000_000_000
|
||||
const trueOffset = 240
|
||||
const rtts = [82, 78, 85, 81, 900, 79, 84, 80]
|
||||
const samples = rtts.map((rtt, index) => {
|
||||
const sentAtMs = base + index * 237
|
||||
const receivedAtMs = sentAtMs + rtt
|
||||
const midpoint = (sentAtMs + receivedAtMs) / 2
|
||||
const serverDateMs = Math.floor((midpoint + trueOffset) / 1_000) * 1_000
|
||||
return observationToSample({
|
||||
id: index + 1, sentAtMs, receivedAtMs, rttMs: rtt,
|
||||
serverDateHeader: new Date(serverDateMs).toUTCString(), remoteIp: '13.125.18.86',
|
||||
reusedSocket: index > 0, statusCode: 200,
|
||||
})
|
||||
})
|
||||
const estimate = estimateClock(samples, base + 2_000, true)
|
||||
expect(estimate.acceptedSamples).toBe(7)
|
||||
expect(estimate.minRttMs).toBe(78)
|
||||
expect(estimate.p95RttMs).toBeGreaterThan(80)
|
||||
expect(Math.abs(estimate.offsetMs - trueOffset)).toBeLessThan(550)
|
||||
expect(estimate.remoteIp).toBe('13.125.18.86')
|
||||
})
|
||||
|
||||
it('computes a server-arrival-based send time', () => {
|
||||
expect(computePlannedSendAtMs(10_000, -25, { offsetMs: 200, oneWayMs: 40 })).toBe(9_735)
|
||||
expect(quantile([1, 2, 3, 4], 0.5)).toBe(2.5)
|
||||
})
|
||||
|
||||
it('resets the estimator window when the L4/L7 route address changes', () => {
|
||||
const first = observationToSample({
|
||||
id: 1, sentAtMs: 1_000, receivedAtMs: 1_080, rttMs: 80,
|
||||
serverDateHeader: new Date(1_000).toUTCString(), remoteIp: '10.0.0.1', reusedSocket: false, statusCode: 200,
|
||||
})
|
||||
const second = observationToSample({
|
||||
id: 2, sentAtMs: 2_000, receivedAtMs: 2_080, rttMs: 80,
|
||||
serverDateHeader: new Date(2_000).toUTCString(), remoteIp: '10.0.0.2', reusedSocket: false, statusCode: 200,
|
||||
})
|
||||
expect(appendClockSample([first], second)).toEqual([second])
|
||||
})
|
||||
|
||||
it('marks old estimates as poor quality', () => {
|
||||
const sample = observationToSample({
|
||||
id: 1, sentAtMs: 1_000, receivedAtMs: 1_080, rttMs: 80,
|
||||
serverDateHeader: new Date(1_000).toUTCString(), remoteIp: '10.0.0.1', reusedSocket: false, statusCode: 200,
|
||||
})
|
||||
expect(estimateClock([sample], 20_000).quality).toBe('poor')
|
||||
})
|
||||
|
||||
it('combines multiple second boundaries and rejects a phase outlier', () => {
|
||||
const samples = boundarySamples([240, 245, 235, 242, 238, 610])
|
||||
const boundary = estimateBoundaryOffset(samples)
|
||||
expect(boundary?.count).toBe(5)
|
||||
expect(boundary?.offsetMs).toBeGreaterThanOrEqual(235)
|
||||
expect(boundary?.offsetMs).toBeLessThanOrEqual(245)
|
||||
expect(boundary?.spreadMs).toBeLessThan(10)
|
||||
|
||||
const estimate = estimateClock(samples, samples.at(-1)!.receivedAtMs, true)
|
||||
expect(estimate.calibrationReady).toBe(true)
|
||||
expect(estimate.calibrationApplied).toBe(true)
|
||||
expect(estimate.offsetMs).toBe(boundary?.offsetMs)
|
||||
expect(estimate.uncertaintyMs).toBeLessThan(50)
|
||||
})
|
||||
|
||||
it('reports a recommendation but does not apply it when auto apply is disabled', () => {
|
||||
const samples = boundarySamples([240, 245, 235, 242, 238])
|
||||
const estimate = estimateClock(samples, samples.at(-1)!.receivedAtMs, true, {
|
||||
...CLOCK_CALIBRATION_DEFAULTS,
|
||||
autoApply: false,
|
||||
})
|
||||
expect(estimate.calibrationReady).toBe(true)
|
||||
expect(estimate.calibrationApplied).toBe(false)
|
||||
expect(estimate.offsetMs).toBe(estimate.rawOffsetMs)
|
||||
expect(estimate.recommendedCorrectionMs).not.toBe(0)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user