import socket
from datetime import datetime, timedelta, timezone
import pytest
from hunter.db import connect, now
from hunter.monitor import acquire_run, collect, collect_companies, parse_feed, scheduler
from hunter.network import fetch, public_url
MOCK_RSS = b"""Mock- AI discoveryhttps://example.com/articleTue, 17 Nov 2026 03:00:00 GMTArtificial intelligence research
"""
def test_repeat_collection_deduplicates_and_isolates_failed_sources(app, monkeypatch):
monkeypatch.setattr("hunter.monitor.public_url", lambda url: (url, "93.184.216.34"))
def mock_fetcher(url):
if "nasa" in url:
raise TimeoutError("mock-timeout")
return MOCK_RSS
result = collect(app.config["DATABASE"], fetcher=mock_fetcher, analyze=False)
assert result == {"status": "partial", "added": 1}
second = collect(app.config["DATABASE"], fetcher=mock_fetcher, analyze=False)
assert second["added"] == 0
with connect(app.config["DATABASE"]) as db:
assert db.execute("SELECT count(*) FROM signals").fetchone()[0] == 1
assert db.execute("SELECT count(*) FROM sources WHERE status='ok'").fetchone()[0] == 4
assert db.execute("SELECT count(*) FROM sources WHERE status='error'").fetchone()[0] == 1
assert db.execute("SELECT published FROM signals").fetchone()[0].startswith("2026-11-17")
def test_feed_validation_and_untrusted_html():
with pytest.raises(ValueError):
parse_feed(b"invalid")
body = MOCK_RSS.replace(b"AI discovery", b"<script>steal()</script>Research")
assert parse_feed(body)[0]["title"] == "Research"
@pytest.mark.parametrize(
"url",
[
"http://127.0.0.1",
"http://169.254.169.254/",
"http://[::1]/",
"file:///etc/passwd",
"http://user:password@example.com",
"http://example.com:8080",
],
)
def test_private_and_invalid_addresses_are_rejected(url):
with pytest.raises(ValueError):
public_url(url)
def test_dns_rebinding_defense_pins_public_address(monkeypatch):
calls = []
monkeypatch.setattr(
socket,
"getaddrinfo",
lambda *args, **kwargs: [
(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("93.184.216.34", 443))
],
)
class MockResponse:
status = 200
def read(self, count):
return b"mock-body"
def close(self):
pass
class MockPool:
def __init__(self, host, **kwargs):
calls.append((host, kwargs))
def request(self, method, path, **kwargs):
assert kwargs["redirect"] is False
assert kwargs["headers"]["Host"] == "example.com"
return MockResponse()
def close(self):
pass
monkeypatch.setattr("hunter.network.urllib3.HTTPSConnectionPool", MockPool)
assert fetch("https://example.com/feed") == b"mock-body"
assert calls[0][0] == "93.184.216.34"
assert calls[0][1]["server_hostname"] == "example.com"
def test_changed_company_snapshot_creates_cited_record(app):
path = app.config["DATABASE"]
with connect(path) as db:
db.execute(
"INSERT INTO companies(name,url) VALUES(?,?)", ("Mock Telecom", "https://example.com")
)
collect_companies(path, lambda url: b"Tariff 1000 KZT")
collect_companies(path, lambda url: b"Tariff 1000 KZT")
with connect(path) as db:
assert db.execute("SELECT count(*) FROM changes").fetchone()[0] == 0
collect_companies(path, lambda url: b"Tariff 1200 KZT")
with connect(path) as db:
row = db.execute("SELECT * FROM changes").fetchone()
assert row["previous"] == "Tariff 1000 KZT"
assert row["current"] == "Tariff 1200 KZT"
assert row["created"]
def test_scheduler_respects_interval_and_run_lease(app, monkeypatch):
path = app.config["DATABASE"]
calls = []
monkeypatch.setattr("hunter.monitor.collect", lambda path: calls.append(path))
scheduler(path, once=True)
assert len(calls) == 1
with connect(path) as db:
db.execute("INSERT INTO runs(started,finished,status) VALUES(?,?,?)", (now(), now(), "ok"))
scheduler(path, once=True)
assert len(calls) == 1
assert acquire_run(path)
assert acquire_run(path) is None
with connect(path) as db:
db.execute(
"UPDATE runs SET started=? WHERE status='running'",
((datetime.now(timezone.utc) - timedelta(hours=2)).isoformat(),),
)
assert acquire_run(path)
def test_analyst_can_add_company_but_user_cannot_and_private_is_rejected(admin, monkeypatch):
monkeypatch.setattr(
"hunter.web.public_url", lambda url: (_ for _ in ()).throw(ValueError("private_address"))
)
response = admin.post(
"/competitors",
data={"csrf": "mock-csrf", "name": "Bad", "url": "http://127.0.0.1"},
follow_redirects=True,
)
assert "Не удалось сохранить".encode() in response.data