// 날씨 유형 테스트의 데이터(seo/weather_type.json)와 계산 함수 검증. 실행: frontend 폴더에서 npm test import assert from 'node:assert/strict' import { readFileSync } from 'node:fs' import { test } from 'node:test' import data from '../seo/weather_type.json' with { type: 'json' } import { QUESTIONS, TYPES, dateKey, isSlug, loadMine, matchOf, pickGaks, resultOf, saveMine, seasonCodes, showTypeDot, typeOf } from '../src/b/weatherType.ts' const seed = JSON.parse(readFileSync(new URL('../../backend/seed/index_definition.json', import.meta.url), 'utf8')) const gakByCode = new Map(seed.map((g) => [g.code, g])) const slugs = data.types.map((t) => t.slug) /** 모든 답 조합 (보기 수가 질문마다 달라도 됨) */ function* allAnswers(questions, head = []) { if (head.length === questions.length) return yield head for (let i = 0; i < questions[head.length].options.length; i++) yield* allAnswers(questions, [...head, i]) } /** 테스트용 localStorage: 메모리에 담는다 */ function memoryStorage() { const items = new Map() return { getItem: (k) => (items.has(k) ? items.get(k) : null), setItem: (k, v) => void items.set(k, String(v)) } } function withStorage(storage, run) { const had = Object.getOwnPropertyDescriptor(globalThis, 'localStorage') Object.defineProperty(globalThis, 'localStorage', { value: storage, configurable: true, writable: true }) try { return run() } finally { if (had) Object.defineProperty(globalThis, 'localStorage', had) else delete globalThis.localStorage } } // ---------- 데이터 ---------- test('유형은 8개이고 slug 가 겹치지 않는다', () => { assert.equal(TYPES.length, 8) assert.equal(new Set(slugs).size, 8) }) test('질문은 8개, 보기는 2~4개, 점수의 slug 는 모두 실제 유형이다', () => { assert.equal(QUESTIONS.length, 8) for (const q of QUESTIONS) { assert.ok(q.options.length >= 2 && q.options.length <= 4, q.text) for (const o of q.options) for (const s of Object.keys(o.scores)) assert.ok(slugs.includes(s), `${q.text}: ${s}`) } }) test('유형마다 특징 3개, 각 풀 6개', () => { for (const t of TYPES) { assert.equal(t.traits.length, 3, t.slug) assert.equal(t.gaks.length, 6, t.slug) assert.equal(new Set(t.gaks.map((g) => g.code)).size, 6, `${t.slug}: 풀 안에 같은 각`) } }) test('각 풀의 code 는 모두 backend/seed/index_definition.json 에 있고 name 도 그 파일과 같다', () => { for (const t of TYPES) for (const g of t.gaks) assert.equal(gakByCode.get(g.code)?.name, g.name, `${t.slug}: ${g.code}`) }) test('유형마다 months 제한 없는 각이 4개 이상이다', () => { for (const t of TYPES) { const free = t.gaks.filter((g) => gakByCode.get(g.code).months.length === 0) assert.ok(free.length >= 4, `${t.slug}: ${free.length}개`) } }) test('궁합은 36쌍이고 빠진 쌍·겹친 쌍이 없다', () => { const key = (a, b) => [a, b].sort().join('+') const seen = data.matches.map((m) => key(...m.pair)) const want = slugs.flatMap((a, i) => slugs.slice(i).map((b) => key(a, b))) assert.equal(seen.length, 36) assert.deepEqual([...new Set(seen)].sort(), want.sort()) }) test('궁합 단계는 이름이 있는 4단계 중 하나다', () => { assert.deepEqual(Object.keys(data.levelNames).sort(), ['bad', 'best', 'fun', 'good']) for (const m of data.matches) assert.ok(m.level in data.levelNames, m.pair.join('+')) }) test('유형마다 찰떡(best)과 삐걱삐걱(bad)이 적어도 하나씩 있다', () => { for (const a of slugs) { const levels = slugs.map((b) => matchOf(a, b).level) assert.ok(levels.includes('best'), `${a}: 찰떡 없음`) assert.ok(levels.includes('bad'), `${a}: 삐걱삐걱 없음`) } }) // ---------- 결과 계산 ---------- test('8개 유형이 모두 결과로 나올 수 있다', () => { const got = new Set() for (const answers of allAnswers(QUESTIONS)) got.add(resultOf(answers)) assert.deepEqual([...got].sort(), [...slugs].sort()) }) test('점수 합이 가장 큰 유형이 결과다', () => { const questions = [ { text: 'q1', options: [{ text: 'a', scores: { gureum: 2, angae: 1 } }] }, { text: 'q2', options: [{ text: 'a', scores: { angae: 2 } }] }, ] assert.equal(resultOf([0, 0], questions), 'angae') }) test('동점이면 마지막 질문에서 고른 보기의 점수가 높은 유형이다', () => { const questions = [ { text: 'q1', options: [{ text: 'a', scores: { sonagi: 2 } }] }, { text: 'q2', options: [{ text: 'a', scores: { bombyeot: 2 } }] }, ] assert.equal(resultOf([0, 0], questions), 'bombyeot') }) test('마지막 질문으로 안 갈리면 그 앞 질문으로 거슬러 올라간다', () => { const questions = [ { text: 'q1', options: [{ text: 'a', scores: { sonagi: 2 } }] }, { text: 'q2', options: [{ text: 'a', scores: { angae: 2 } }] }, { text: 'q3', options: [{ text: 'a', scores: { gureum: 1 } }] }, ] assert.equal(resultOf([0, 0, 0], questions), 'angae') }) test('끝까지 같으면 표의 위쪽 유형이다', () => { const questions = [{ text: 'q1', options: [{ text: 'a', scores: { angae: 1, bombyeot: 1 } }] }] assert.equal(resultOf([0], questions), 'bombyeot') }) test('isSlug: 실제 유형만 true', () => { assert.equal(isSlug('sonagi'), true) for (const s of ['abc', 'SONAGI', '', undefined, 'toString']) assert.equal(isSlug(s), false, String(s)) }) test('typeOf 는 그 유형의 글을 돌려준다', () => { assert.equal(typeOf('sonagi').name, '소나기형') }) // ---------- 궁합 ---------- test('matchOf(a, b) 와 matchOf(b, a) 는 같다', () => { for (const a of slugs) for (const b of slugs) assert.deepEqual(matchOf(a, b), matchOf(b, a), `${a}+${b}`) }) test('matchOf 는 데이터에 적힌 단계와 글을 돌려준다', () => { assert.deepEqual(matchOf('beongae', 'gureum'), { level: 'bad', text: data.matches.find((m) => m.pair.includes('gureum') && m.pair.includes('beongae')).text }) }) // ---------- 각 뽑기 ---------- const poolOf = (slug) => typeOf(slug).gaks.map((g) => g.code) test('같은 slug·같은 날이면 같은 3개', () => { for (const slug of slugs) { const picked = pickGaks(slug, '2026-11-23', null) assert.equal(picked.length, 3, slug) assert.equal(new Set(picked).size, 3, slug) assert.ok(picked.every((c) => poolOf(slug).includes(c)), slug) assert.deepEqual(pickGaks(slug, '2026-11-23', null), picked, slug) } }) test('날이 바뀌면 다시 뽑는다', () => { for (const slug of slugs) { const combos = new Set() for (let d = 1; d <= 30; d++) combos.add([...pickGaks(slug, `2026-11-${String(d).padStart(2, '0')}`, null)].sort().join(',')) assert.ok(combos.size >= 2, `${slug}: 30일 동안 조합 ${combos.size}가지`) } }) test('제철이 아닌 각은 뽑히지 않는다', () => { const inSeason = new Set(poolOf('cheonnun').slice(0, 4)) for (let d = 1; d <= 30; d++) { const picked = pickGaks('cheonnun', `2026-07-${String(d).padStart(2, '0')}`, inSeason) assert.equal(picked.length, 3) assert.ok(picked.every((c) => inSeason.has(c)), picked.join(',')) } }) test('제철인 각이 2개뿐이면 2개만 돌려준다', () => { const inSeason = new Set(poolOf('gureum').slice(0, 2)) assert.deepEqual([...pickGaks('gureum', '2026-11-23', inSeason)].sort(), [...inSeason].sort()) }) test('제철인 각이 하나도 없으면 빈 목록이다', () => { assert.deepEqual(pickGaks('gureum', '2026-11-23', new Set()), []) }) test('뽑힌 3개가 모두 제철이면, 제철 정보를 받은 뒤에도 같은 3개다 (화면의 각이 바뀌어 보이지 않게)', () => { for (const slug of slugs) { for (let d = 1; d <= 30; d++) { const day = `2026-11-${String(d).padStart(2, '0')}` const before = pickGaks(slug, day, null) const inSeason = new Set(poolOf(slug).filter((c) => before.includes(c) || c !== poolOf(slug).find((x) => !before.includes(x)))) assert.equal(inSeason.size, 5, '풀에서 안 뽑힌 각 하나만 제철에서 뺀다') assert.deepEqual(pickGaks(slug, day, inSeason), before, `${slug} ${day}`) } } }) test('seasonCodes: 각 목록에서 제철인 code 만 모은다 (in_season 이 없으면 제철)', () => { const codes = seasonCodes([{ code: 'walk' }, { code: 'picnic', in_season: false }, { code: 'drive', in_season: true }]) assert.deepEqual([...codes].sort(), ['drive', 'walk']) }) test('seasonCodes: 목록을 못 받았거나 비어 있으면 null (제철을 모르니 풀 전체에서 뽑게)', () => { assert.equal(seasonCodes(undefined), null) assert.equal(seasonCodes([]), null) }) test('dateKey 는 한국 시간 날짜다', () => { assert.equal(dateKey(new Date('2026-11-23T14:59:00Z')), '2026-11-23') assert.equal(dateKey(new Date('2026-11-23T15:30:00Z')), '2026-11-24') }) // ---------- 내 결과 저장 ---------- test('저장한 내 결과를 다시 읽는다', () => { withStorage(memoryStorage(), () => { assert.equal(loadMine(), null) saveMine('gureum') assert.equal(loadMine(), 'gureum') }) }) test('저장된 값이 유형이 아니면 null 이다', () => { const storage = memoryStorage() withStorage({ ...storage, getItem: () => 'abc' }, () => assert.equal(loadMine(), null)) }) test('localStorage 가 없어도 loadMine 은 null, saveMine 은 던지지 않고 경고를 남긴다', (t) => { const warn = t.mock.method(console, 'warn', () => {}) withStorage(undefined, () => { assert.equal(loadMine(), null) assert.doesNotThrow(() => saveMine('gureum')) }) assert.equal(warn.mock.callCount(), 1) }) test('localStorage 가 던져도 loadMine 은 null, saveMine 은 던지지 않고 경고를 남긴다', (t) => { const warn = t.mock.method(console, 'warn', () => {}) const broken = { getItem() { throw new Error('blocked') }, setItem() { throw new Error('blocked') }, } withStorage(broken, () => { assert.equal(loadMine(), null) assert.doesNotThrow(() => saveMine('gureum')) }) assert.equal(warn.mock.callCount(), 1) }) test('빨간 점: 아직 안 해 봤으면 보이고, 해 봤으면 안 보인다', () => { withStorage(memoryStorage(), () => { assert.equal(showTypeDot(), true) saveMine('gureum') assert.equal(showTypeDot(), false) }) }) test('빨간 점: 저장소를 못 쓰면 보이지 않는다 (영영 안 꺼지는 점이 되지 않게)', () => { withStorage(undefined, () => assert.equal(showTypeDot(), false)) withStorage({ getItem() { throw new Error('blocked') } }, () => assert.equal(showTypeDot(), false)) })