from datetime import date, timedelta import pytest from httpx import ASGITransport, AsyncClient from common.utils.kma_time import now_kst from router.router import app from services.fortune_service import DECK, clean_log, hours_text, streak REGION = "1144000000" D = date(2026, 10, 28) def client(): return AsyncClient(transport=ASGITransport(app=app), base_url="http://test") async def _login(c, login_id: str) -> dict: body = (await c.post("/v1/auth/signup", json={"login_id": login_id, "password": "password1", "nickname": login_id})).json() return {"Authorization": f"Bearer {body['access_token']}"} def _days(*back: int) -> set[date]: return {D - timedelta(days=b) for b in back} def test_deck_is_22_cards_with_reading_and_color(): assert len(DECK) == 22 assert all(c["reading"] and c["color"] and c["hex"].startswith("#") for c in DECK.values()) def test_streak_counts_back_from_today_or_yesterday(): assert streak(set(), D) == 0 assert streak(_days(0, 1, 2), D) == 3 # 오늘 아직 안 뽑았으면 어제까지 센다 assert streak(_days(1, 2), D) == 2 def test_streak_forgives_one_rest_day_a_week(): # 하루 빠진 날(2일 전)은 쉬는 날로 봐준다 assert streak(_days(0, 1, 3, 4), D) == 4 # 이틀 연속 빠지면 끊긴다 assert streak(_days(0, 3, 4), D) == 1 # 쉬는 날이 7일 안에 두 번이면 두 번째에서 끊긴다 assert streak(_days(0, 2, 4, 5), D) == 2 # 7일 넘게 떨어져 있으면 두 번 다 봐준다 assert streak(_days(0, 2, 3, 4, 5, 6, 7, 8, 10), D) == 9 def test_hours_text(): assert hours_text({16, 17, 18}) == "오후 4~7시" assert hours_text({11, 12, 13, 14}) == "오전 11시~오후 3시" assert hours_text(set(range(19, 29))) == "오후 7시~새벽 5시" def test_clean_log_drops_place_when_stayed_home_and_rejects_bad_ref(): v = clean_log(2, False, "하늘공원", "spot:3", True, REGION) assert v["place_name"] is None and v["place_ref"] is None and v["card_hit"] is True assert clean_log(2, True, " 하늘 공원 ", "spot:3", None, REGION)["place_name"] == "하늘 공원" assert clean_log(2, True, "하늘공원", "../x", None, REGION) is None assert clean_log(6, True, None, None, None, REGION) is None @pytest.mark.anyio async def test_anon_draw_keeps_device_card_and_counts_device_days(offline): today = now_kst().date() async with client() as c: first = (await c.post("/v1/fortune/draw", json={"region_code": REGION})).json() assert first["card"]["code"] in DECK and first["card"]["name"].endswith("각") assert first["luck"]["time"] and first["luck"]["top_gak"] assert first["streak"] == 1 # 기기에 있는 오늘 카드를 넘기면 그 카드 그대로, 기기에 남은 뽑은 날로 연속 기록 again = (await c.post("/v1/fortune/draw", json={"region_code": REGION, "card_code": first["card"]["code"], "days": [str(today - timedelta(days=1)), str(today - timedelta(days=2))]})).json() assert again["card"]["code"] == first["card"]["code"] and again["streak"] == 3 # 덱에 없는 카드면 새로 뽑는다 assert (await c.post("/v1/fortune/draw", json={"region_code": REGION, "card_code": "laundry"})).json()["card"]["code"] in DECK # 로그인 안 했으면 오늘 보기는 카드 없이, 체크인은 못 한다 assert "card" not in (await c.get("/v1/fortune/today", params={"region": REGION})).json() assert (await c.put("/v1/fortune/log", json={"region_code": REGION, "mood": 1, "went_out": False})).status_code == 401 @pytest.mark.anyio async def test_login_draws_one_card_a_day_and_saves_checkin(offline): async with client() as c: h = await _login(c, "fortune_01") assert "card" not in (await c.get("/v1/fortune/today", params={"region": REGION}, headers=h)).json() first = (await c.post("/v1/fortune/draw", json={"region_code": REGION}, headers=h)).json()["card"]["code"] # 다시 뽑아도, 기기 카드를 넘겨도 그날 처음 카드 other = next(k for k in DECK if k != first) assert (await c.post("/v1/fortune/draw", json={"region_code": REGION, "card_code": other}, headers=h)).json()["card"]["code"] == first today = (await c.get("/v1/fortune/today", params={"region": REGION}, headers=h)).json() assert today["card"]["code"] == first and today["streak"] == 1 and "log" not in today saved = (await c.put("/v1/fortune/log", json={"region_code": REGION, "mood": 2, "went_out": True, "place_name": "하늘공원", "place_ref": "spot:2", "card_hit": True}, headers=h)).json() assert saved["log"]["place_name"] == "하늘공원" and saved["log"]["card_hit"] is True # 다시 보내면 고친다 fixed = (await c.put("/v1/fortune/log", json={"region_code": REGION, "mood": 4, "went_out": False}, headers=h)).json()["log"] assert fixed["mood"] == 4 and "place_name" not in fixed assert (await c.get("/v1/fortune/today", params={"region": REGION}, headers=h)).json()["log"]["mood"] == 4 assert (await c.put("/v1/fortune/log", json={"region_code": REGION, "mood": 9, "went_out": False}, headers=h)).status_code == 422 @pytest.mark.anyio async def test_import_moves_device_records_but_keeps_account_days(offline): today = now_kst().date() async with client() as c: h = await _login(c, "fortune_02") mine = (await c.post("/v1/fortune/draw", json={"region_code": REGION}, headers=h)).json()["card"]["code"] other = next(k for k in DECK if k != mine) body = { "draws": [{"day": str(today), "card_code": other}, {"day": str(today - timedelta(days=1)), "card_code": other}, {"day": str(today - timedelta(days=90)), "card_code": other}], "logs": [{"day": str(today - timedelta(days=1)), "region_code": REGION, "mood": 1, "went_out": False}], } assert (await c.post("/v1/fortune/import", json=body, headers=h)).json()["result"]["success"] is True t = (await c.get("/v1/fortune/today", params={"region": REGION}, headers=h)).json() # 오늘은 계정에서 뽑은 카드 그대로, 어제 기록이 더해져 2일째. 60일보다 오래된 날은 받지 않는다 assert t["card"]["code"] == mine and t["streak"] == 2 assert (await c.post("/v1/fortune/import", json=body)).status_code == 401 @pytest.mark.anyio async def test_place_search_finds_spots_by_name(): async with client() as c: items = (await c.get("/v1/fortune/places", params={"region": REGION, "q": "하늘공원"})).json()["items"] assert any(i["name"] == "하늘공원" and i["ref"].startswith("spot:") for i in items) # LIKE 기호는 글자 그대로 찾는다 assert (await c.get("/v1/fortune/places", params={"region": REGION, "q": "%"})).json()["items"] == [] assert (await c.get("/v1/fortune/places", params={"region": REGION, "q": " "})).json()["items"] == []