o2o-site-AEO/solution/backend/tests/test_verify_candidates.py
Mina Choi 11d30bb3d1 [chore] solution,admin,ontology: 코드 주석을 한 줄로 — 히스토리 주석 삭제
여러 줄 주석이 설명보다 경위(예전·실측·지적)를 적고 있어 읽는 사람이 결론을 찾기 어려웠다.

- ts·tsx·js·mjs·css·py 478개: 여러 줄 주석은 첫 문장 한 줄로, 과거형·날짜 문장은 삭제
- 주석 위치는 TypeScript 파서·파이썬 tokenize/ast 로 찾는다 — 문자열 안의 # · /* 는 건드리지 않는다
- eslint·ts·noqa·type: ignore 같은 지시 주석은 그대로 둔다

파이썬 275개 정리 전후 AST 동일, TS 298개 주석 뺀 토큰 동일(빈 JSX 주석 10곳만 차이).
site·frontend·admin tsc, site vitest 105 passed

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-28 16:05:19 +09:00

182 lines
8.2 KiB
Python

"""동일 업소 후보 조회 — ★ 서버가 자동 확정하지 않고 사람이 고르게 한다."""
from common.enums import ErrorType
from services.external import kakao as kakao_client
from services.external import naver as naver_client
def _np(name, addr, url=None):
return naver_client.NaverPlace(
name=name, road_address=addr, address=None, phone=None,
latitude=38.0, longitude=128.7, category_name="숙박>펜션",
place_url=url, naver_place_id=None,
)
def _match(outcome, place=None, candidates=None, reason=None):
return naver_client.MatchResult(
outcome=outcome, place=place, candidates=candidates or [], reason=reason, detail=None,
)
async def _place(client, h, name="핑크비치펜션"):
return (await client.post("/v1/place", headers=h, json={"name": name, "category": 1})).json()["place"]["place_id"]
def _patch_naver(monkeypatch, result):
"""네이버 판정을 고정값으로 바꾼다."""
monkeypatch.setattr(kakao_client.KakaoLocalClient, "enabled", property(lambda self: False))
monkeypatch.setattr(naver_client.NaverLocalClient, "enabled", property(lambda self: True))
seen: dict = {}
async def _verify(self, name, address_hint=None, *, search_query=None):
seen["name"] = name
seen["search_query"] = search_query
return result
async def _close(self):
return None
monkeypatch.setattr(naver_client.NaverLocalClient, "verify_place", _verify)
monkeypatch.setattr(naver_client.NaverLocalClient, "aclose", _close)
return seen
async def test_single_match_is_auto_selectable(auth_headers, client, monkeypatch):
"""검증: 정확히 1건 일치하는 상호명."""
only = _np("핑크비치펜션", "강원특별자치도 양양군 현북면 하조대3길 11", "http://pinkbeach.kr")
_patch_naver(monkeypatch, _match(kakao_client.MatchOutcome.MATCHED, only, [only], "name_exact"))
h = await auth_headers("u1")
pid = await _place(client, h)
body = (await client.get(f"/v1/place/{pid}/verify/candidates", headers=h)).json()
assert body["result"]["success"] is True
assert body["outcome"] == "matched"
assert body["auto_selectable"] is True
assert len(body["candidates"]) == 1
assert body["candidates"][0]["place_url"] == "http://pinkbeach.kr"
async def test_ambiguous_returns_all_candidates_for_ui(auth_headers, client, monkeypatch):
"""검증: 동명 업소가 여러 건이라 자동 판정이 안 된다."""
rows = [
_np("하조대펜션", "강원특별자치도 양양군 현북면 하조대3길 11"),
_np("하조대펜션", "강원특별자치도 양양군 현북면 하조대2길 48"),
_np("하조대펜션", "강원특별자치도 양양군 손양면 동명로 5"),
]
_patch_naver(monkeypatch, _match(kakao_client.MatchOutcome.AMBIGUOUS, None, rows, "name_duplicate"))
h = await auth_headers("u1")
pid = await _place(client, h, "하조대펜션")
body = (await client.get(f"/v1/place/{pid}/verify/candidates", headers=h)).json()
assert body["outcome"] == "ambiguous"
assert body["auto_selectable"] is False
assert len(body["candidates"]) == 3
assert body["reason"] == "name_duplicate"
# 사람이 고를 수 있게 주소가 다 실려 있어야 한다
assert len({c["road_address"] for c in body["candidates"]}) == 3
async def test_no_candidate_is_reported(auth_headers, client, monkeypatch):
"""검증: 외부 장소 DB 에 후보가 하나도 없다."""
_patch_naver(monkeypatch, _match(kakao_client.MatchOutcome.NO_CANDIDATE, None, [], "empty"))
h = await auth_headers("u1")
pid = await _place(client, h, "존재하지않는가게")
body = (await client.get(f"/v1/place/{pid}/verify/candidates", headers=h)).json()
assert body["result"]["code"] == ErrorType.PLACE_VERIFY_NO_CANDIDATE.value
async def test_picked_candidate_can_be_confirmed(auth_headers, client, monkeypatch):
"""검증: 후보 목록에서 하나를 골라 확정한다(UI 흐름 전체)."""
rows = [
_np("하조대펜션", "강원특별자치도 양양군 현북면 하조대3길 11", "http://hajodae-a.kr"),
_np("하조대펜션", "강원특별자치도 양양군 손양면 동명로 5", "http://hajodae-b.kr"),
]
_patch_naver(monkeypatch, _match(kakao_client.MatchOutcome.AMBIGUOUS, None, rows, "name_duplicate"))
h = await auth_headers("u1")
pid = await _place(client, h, "하조대펜션")
cands = (await client.get(f"/v1/place/{pid}/verify/candidates", headers=h)).json()["candidates"]
picked = cands[1]
r = (await client.post(f"/v1/place/{pid}/verify", headers=h, json={
"source": 2, "road_address": picked["road_address"],
"latitude": picked["latitude"], "longitude": picked["longitude"],
"place_url": picked["place_url"],
})).json()
assert r["result"]["success"] is True
assert r["place"]["road_address"] == "강원특별자치도 양양군 손양면 동명로 5"
links = (await client.get(f"/v1/place/{pid}/link/list", headers=h)).json()["links"]
official = [l for l in links if l["url"] == "http://hajodae-b.kr"]
assert official, "고른 후보의 홈페이지가 공식 채널로 등록되지 않았다"
assert official[0].get("confirmed_at") is None, "등록만 하고 확정은 따로다"
async def test_candidates_require_configured_source(auth_headers, client, monkeypatch):
"""검증: 카카오도 네이버도 키가 없다."""
monkeypatch.setattr(kakao_client.KakaoLocalClient, "enabled", property(lambda self: False))
monkeypatch.setattr(naver_client.NaverLocalClient, "enabled", property(lambda self: False))
h = await auth_headers("u1")
pid = await _place(client, h)
body = (await client.get(f"/v1/place/{pid}/verify/candidates", headers=h)).json()
assert body["result"]["code"] == ErrorType.LOCAL_NOT_CONFIGURED.value
async def test_candidates_scoped_to_owner(auth_headers, client, monkeypatch):
"""검증: 다른 사장님 계정으로 남의 사업장 후보를 조회한다."""
_patch_naver(monkeypatch, _match(kakao_client.MatchOutcome.MATCHED, _np("a", "b"), [], "x"))
h1 = await auth_headers("o1")
pid = await _place(client, h1)
h2 = await auth_headers("o2")
body = (await client.get(f"/v1/place/{pid}/verify/candidates", headers=h2)).json()
assert body["result"]["code"] == ErrorType.PLACE_NOT_FOUND.value
async def test_region_stays_in_query_and_out_of_the_match_name(auth_headers, client, monkeypatch):
"""검증: 화면이 '상호명 + 위치'를 합쳐 query 로 보낸다."""
only = _np("보사노바 커피로스터스 강릉점", "강원 강릉시 창해로14번길 28")
seen = _patch_naver(
monkeypatch, _match(kakao_client.MatchOutcome.MATCHED, only, [only], "name_exact")
)
h = await auth_headers("u1")
pid = await _place(client, h, name="보사노바 커피로스터스 강릉점")
body = (
await client.get(
f"/v1/place/{pid}/verify/candidates",
headers=h,
params={"query": "보사노바 커피로스터스 강릉점 강릉 견소동"},
)
).json()
assert body["result"]["success"] is True
assert seen["search_query"] == "보사노바 커피로스터스 강릉점 강릉 견소동"
assert seen["name"] == "보사노바 커피로스터스 강릉점"
async def test_match_name_falls_back_to_query_when_place_has_no_name(auth_headers, client, monkeypatch):
"""검증: 사업장 상호가 비어 있다(직접 입력 등으로 이름 없이 만들어진 경우)."""
only = _np("핑크비치펜션", "강원특별자치도 양양군")
seen = _patch_naver(
monkeypatch, _match(kakao_client.MatchOutcome.MATCHED, only, [only], "name_exact")
)
h = await auth_headers("u1")
pid = await _place(client, h, name="핑크비치펜션")
# 상호를 비운다 — places.name 이 빈 문자열인 상태를 만든다.
await client.patch(f"/v1/place/{pid}", headers=h, json={"name": ""})
body = (
await client.get(
f"/v1/place/{pid}/verify/candidates", headers=h, params={"query": "핑크비치펜션 양양"}
)
).json()
assert body["result"]["success"] is True
assert seen["name"] == "핑크비치펜션 양양"