"""Bot identification tests (Chapter 07/12).""" from __future__ import annotations from app.services import bot_identifier def test_classify_bot_detects_googlebot(): ua = "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" assert bot_identifier.classify_bot(ua) == "Googlebot" def test_classify_bot_returns_none_for_ordinary_browser(): ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0" assert bot_identifier.classify_bot(ua) is None def test_classify_bot_returns_none_for_empty_ua(): assert bot_identifier.classify_bot(None) is None def test_verify_bot_ip_rejects_when_ptr_lookup_fails(monkeypatch): def fake_gethostbyaddr(ip): raise OSError("no PTR record") monkeypatch.setattr("socket.gethostbyaddr", fake_gethostbyaddr) assert bot_identifier.verify_bot_ip("203.0.113.5", "Googlebot") is False def test_verify_bot_ip_accepts_matching_forward_and_reverse(monkeypatch): monkeypatch.setattr("socket.gethostbyaddr", lambda ip: ("crawl-1-2-3-4.googlebot.com", [], [])) monkeypatch.setattr("socket.gethostbyname_ex", lambda host: (host, [], ["1.2.3.4"])) assert bot_identifier.verify_bot_ip("1.2.3.4", "Googlebot") is True