import asyncio import uuid from urllib.parse import quote import pytest from sqlalchemy import text from services.track_service import TrackService OAI = "Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko); compatible; OAI-SearchBot/1.3; +https://openai.com/searchbot" CHROME = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" FB = "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)" @pytest.fixture(autouse=True) def _fresh_slug_cache(): # 슬러그 표는 프로세스 캐시다 — 테스트마다 DB 를 비우므로 캐시도 비운다. TrackService.reset_cache() yield TrackService.reset_cache() async def _place(client, auth_headers, name): owner = await auth_headers(f"o{uuid.uuid4().hex[:8]}") r = await client.post("/v1/place", headers=owner, json={"name": name, "category": 2}) return r.json()["place"]["place_id"] async def _site(db_engine, place_id, domain): async with db_engine.begin() as conn: await conn.execute( text("INSERT INTO sites (site_id, place_id) VALUES (gen_random_uuid(), :p) ON CONFLICT DO NOTHING"), {"p": place_id}, ) await conn.execute(text("UPDATE sites SET domain = :d WHERE place_id = :p AND deleted = false"), {"d": domain, "p": place_id}) row = (await conn.execute(text("SELECT site_id FROM sites WHERE place_id = :p AND deleted = false"), {"p": place_id})).first() return str(row[0]) async def _hits(db_engine): async with db_engine.begin() as conn: rows = (await conn.execute(text( "SELECT site_id::text, path, kind, bot, vendor, purpose, user_agent, ip FROM site_crawler_hits ORDER BY created_at" ))).mappings().all() return [dict(r) for r in rows] async def _send(client, uri, ua, xff="203.0.113.7"): return await client.get("/internal/track/hit", headers={"X-Original-URI": uri, "User-Agent": ua, "X-Forwarded-For": xff}) async def test_봇_요청을_사이트에_묶어_저장한다(client, auth_headers, db_engine): pid = await _place(client, auth_headers, "머뭄") site_id = await _site(db_engine, pid, "mermum") r = await _send(client, "/s/mermum", OAI, "203.0.113.7, 10.0.0.1") assert r.status_code == 204 [hit] = await _hits(db_engine) assert hit["site_id"] == site_id assert (hit["kind"], hit["bot"], hit["vendor"], hit["purpose"]) == ("page", "OAI-SearchBot", "OpenAI", "search") assert hit["path"] == "/s/mermum" assert hit["ip"] == "203.0.113.7" async def test_사람_요청은_저장하지_않는다(client, db_engine): r = await _send(client, "/s/mermum", CHROME) assert r.status_code == 204 assert await _hits(db_engine) == [] async def test_한글_슬러그와_하위경로를_같은_사이트로_묶는다(client, auth_headers, db_engine): pid = await _place(client, auth_headers, "스테이머뭄") site_id = await _site(db_engine, pid, "스테이머뭄") await _send(client, "/s/%EC%8A%A4%ED%85%8C%EC%9D%B4%EB%A8%B8%EB%AD%84/", OAI) await _send(client, "/s/%EC%8A%A4%ED%85%8C%EC%9D%B4%EB%A8%B8%EB%AD%84/blog/1?utm_source=x", OAI) hits = await _hits(db_engine) assert [h["site_id"] for h in hits] == [site_id, site_id] assert hits[1]["path"] == "/s/스테이머뭄/blog/1?utm_source=x" async def test_domain_없는_사이트는_이름_슬러그로_찾는다(client, auth_headers, db_engine): pid = await _place(client, auth_headers, "검색 카페") site_id = await _site(db_engine, pid, None) # 헤더는 ASCII 만 실린다(httpx 도 nginx 의 $request_uri 도) — 한글 슬러그는 퍼센트 인코딩으로 온다. await _send(client, "/s/" + quote(f"검색-카페-{pid[:8]}"), OAI) [hit] = await _hits(db_engine) assert hit["site_id"] == site_id async def test_없는_슬러그는_사이트_없이_남긴다(client, db_engine): await _send(client, "/s/no-such-site", OAI) [hit] = await _hits(db_engine) assert hit["site_id"] is None assert hit["kind"] == "page" async def test_robots_sitemap_은_kind_로_가른다(client, db_engine): await _send(client, "/robots.txt", OAI) await _send(client, "/sitemap.xml", OAI) assert [(h["kind"], h["site_id"]) for h in await _hits(db_engine)] == [("robots", None), ("sitemap", None)] async def test_확장자_붙은_요청과_범위_밖_경로는_버린다(client, db_engine): await _send(client, "/s/mermum/img/abc.jpg", OAI) await _send(client, "/s/mermum/assets/x.js?v=1", OAI) await _send(client, "/builder", OAI) await _send(client, "/s", OAI) assert await _hits(db_engine) == [] async def test_기타_봇은_UA는_남기고_IP는_남기지_않는다(client, db_engine): await _send(client, "/s/mermum", FB) [hit] = await _hits(db_engine) assert (hit["bot"], hit["purpose"], hit["ip"]) == (None, "other", None) assert hit["user_agent"] == FB async def test_DB_오류여도_204(client, monkeypatch): async def boom(*args, **kwargs): raise RuntimeError("db down") monkeypatch.setattr(TrackService, "record_hit", boom) r = await _send(client, "/s/mermum", OAI) assert r.status_code == 204 async def test_응답은_기록이_끝나기_전에_나간다(monkeypatch): # nginx 는 mirror 하위 요청이 끝나기 전까지 같은 연결의 다음 요청을 읽지 않는다 — # 저장(DB)을 기다렸다 204 를 주면 DB 가 느릴 때 그 연결의 다른 요청까지 같이 늦어진다. from router.router import app done = asyncio.Event() response_sent_before_done = [] async def slow_record_hit(self, uri, user_agent, xff): await asyncio.sleep(0.2) done.set() monkeypatch.setattr(TrackService, "record_hit", slow_record_hit) async def receive(): return {"type": "http.request", "body": b"", "more_body": False} async def send(message): if message["type"] == "http.response.body" and not message.get("more_body"): response_sent_before_done.append(not done.is_set()) scope = { "type": "http", "asgi": {"version": "3.0"}, "http_version": "1.1", "method": "GET", "scheme": "http", "path": "/internal/track/hit", "raw_path": b"/internal/track/hit", "query_string": b"", "headers": [(b"x-original-uri", b"/robots.txt"), (b"user-agent", b"OAI-SearchBot/1.3")], "client": ("127.0.0.1", 1), "server": ("test", 80), } await app(scope, receive, send) assert response_sent_before_done == [True] assert done.is_set() # 응답 뒤에도 기록은 끝까지 돈다 async def test_HEAD_요청도_받는다(client, db_engine): r = await client.head("/internal/track/hit", headers={"X-Original-URI": "/robots.txt", "User-Agent": OAI}) assert r.status_code == 204 assert len(await _hits(db_engine)) == 1