Upload folder using huggingface_hub
Browse files- app/config.py +3 -0
- app/validator/engine.py +94 -42
- app/validator/validation_cache.py +128 -0
- tests/conftest.py +25 -0
- tests/test_engine_batch.py +26 -6
- tests/test_engine_cache.py +228 -0
- tests/test_validation_cache.py +174 -0
app/config.py
CHANGED
|
@@ -91,6 +91,9 @@ class Settings(BaseSettings):
|
|
| 91 |
# Catch-all is a domain property — cache the verdict for 72h so a bulk list
|
| 92 |
# does not re-probe the same domain for every address.
|
| 93 |
catch_all_ttl_seconds: int = 72 * 3600
|
|
|
|
|
|
|
|
|
|
| 94 |
# Per-MX-host SMTP session cap and global concurrency for bulk runs.
|
| 95 |
max_connections_per_host: int = 2
|
| 96 |
bulk_concurrency: int = 20
|
|
|
|
| 91 |
# Catch-all is a domain property — cache the verdict for 72h so a bulk list
|
| 92 |
# does not re-probe the same domain for every address.
|
| 93 |
catch_all_ttl_seconds: int = 72 * 3600
|
| 94 |
+
# DNS/MX answers change slowly; a definitive mailbox verdict is stable for
|
| 95 |
+
# about a day. Transient failures are never cached regardless of TTL.
|
| 96 |
+
dns_cache_ttl_seconds: int = 24 * 3600
|
| 97 |
# Per-MX-host SMTP session cap and global concurrency for bulk runs.
|
| 98 |
max_connections_per_host: int = 2
|
| 99 |
bulk_concurrency: int = 20
|
app/validator/engine.py
CHANGED
|
@@ -119,12 +119,23 @@ class EmailValidationEngine:
|
|
| 119 |
7. Deterministic heuristic deliverability scoring
|
| 120 |
"""
|
| 121 |
|
| 122 |
-
def __init__(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 123 |
self.use_proxies = settings.use_proxies
|
| 124 |
# Layers 5 (catch-all) and 6 (SMTP) run through a mailbox provider. On
|
| 125 |
# hosts that block port 25 (HF Spaces), this resolves to the verification
|
| 126 |
# API; elsewhere it is direct SMTP. Injectable for tests.
|
| 127 |
self.mailbox = mailbox if mailbox is not None else resolve_provider()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
async def validate(self, email: str, deep: bool = True) -> ValidationResult:
|
| 130 |
start_time = time.monotonic()
|
|
@@ -346,24 +357,36 @@ class EmailValidationEngine:
|
|
| 346 |
continue
|
| 347 |
domain_index.setdefault(syntax.domain, []).append(idx)
|
| 348 |
|
| 349 |
-
# ---- Layers 2 & 3: DNS + MX once per domain ---------
|
| 350 |
domains = list(domain_index.keys())
|
| 351 |
-
dns_list = await asyncio.gather(
|
| 352 |
-
*[check_dns(d, settings.dns_timeout) for d in domains],
|
| 353 |
-
return_exceptions=True,
|
| 354 |
-
)
|
| 355 |
domain_dns: dict[str, DNSResult] = {}
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
|
|
|
|
|
|
|
| 366 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 367 |
|
| 368 |
pending: list[tuple[int, str, SyntaxResult, str, DNSResult]] = []
|
| 369 |
for domain, idxs in domain_index.items():
|
|
@@ -433,40 +456,69 @@ class EmailValidationEngine:
|
|
| 433 |
pending = []
|
| 434 |
|
| 435 |
# ---- Layers 5 & 6: ONE batched mailbox call ------------------
|
|
|
|
|
|
|
| 436 |
if pending:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 437 |
pairs = [
|
| 438 |
(normalized, dns.mx_records[0]["host"])
|
| 439 |
-
for _, normalized, _, _, dns in
|
| 440 |
]
|
| 441 |
-
|
| 442 |
-
|
| 443 |
-
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 447 |
-
|
| 448 |
-
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
|
|
|
| 463 |
|
| 464 |
# ---- Layer 7: score each row -----------------------------
|
| 465 |
for idx, normalized, syntax, domain, dns in pending:
|
| 466 |
-
|
| 467 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 468 |
)
|
| 469 |
-
ca_value = catch_all_map.get(domain)
|
| 470 |
catch_all = CatchAllResult(
|
| 471 |
is_catch_all=ca_value,
|
| 472 |
confidence=0.9 if ca_value is not None else 0.0,
|
|
|
|
| 119 |
7. Deterministic heuristic deliverability scoring
|
| 120 |
"""
|
| 121 |
|
| 122 |
+
def __init__(
|
| 123 |
+
self,
|
| 124 |
+
mailbox: MailboxProvider | None = None,
|
| 125 |
+
cache=None,
|
| 126 |
+
):
|
| 127 |
self.use_proxies = settings.use_proxies
|
| 128 |
# Layers 5 (catch-all) and 6 (SMTP) run through a mailbox provider. On
|
| 129 |
# hosts that block port 25 (HF Spaces), this resolves to the verification
|
| 130 |
# API; elsewhere it is direct SMTP. Injectable for tests.
|
| 131 |
self.mailbox = mailbox if mailbox is not None else resolve_provider()
|
| 132 |
+
# DNS/MX and definitive mailbox verdicts are cached across runs — the
|
| 133 |
+
# same domain (and often the same address) recurs constantly in bulk
|
| 134 |
+
# lists. Transient failures are never cached; see validation_cache.py.
|
| 135 |
+
if cache is None:
|
| 136 |
+
from .validation_cache import validation_cache as cache
|
| 137 |
+
|
| 138 |
+
self.cache = cache
|
| 139 |
|
| 140 |
async def validate(self, email: str, deep: bool = True) -> ValidationResult:
|
| 141 |
start_time = time.monotonic()
|
|
|
|
| 357 |
continue
|
| 358 |
domain_index.setdefault(syntax.domain, []).append(idx)
|
| 359 |
|
| 360 |
+
# ---- Layers 2 & 3: DNS + MX once per domain (cached) ---------
|
| 361 |
domains = list(domain_index.keys())
|
|
|
|
|
|
|
|
|
|
|
|
|
| 362 |
domain_dns: dict[str, DNSResult] = {}
|
| 363 |
+
misses: list[str] = []
|
| 364 |
+
for domain in domains:
|
| 365 |
+
cached_dns = await self.cache.get_dns(domain)
|
| 366 |
+
if cached_dns is not None:
|
| 367 |
+
domain_dns[domain] = cached_dns
|
| 368 |
+
else:
|
| 369 |
+
misses.append(domain)
|
| 370 |
+
|
| 371 |
+
if misses:
|
| 372 |
+
resolved = await asyncio.gather(
|
| 373 |
+
*[check_dns(d, settings.dns_timeout) for d in misses],
|
| 374 |
+
return_exceptions=True,
|
| 375 |
)
|
| 376 |
+
for domain, dns in zip(misses, resolved):
|
| 377 |
+
result = (
|
| 378 |
+
dns
|
| 379 |
+
if isinstance(dns, DNSResult)
|
| 380 |
+
else DNSResult(
|
| 381 |
+
domain_exists=False,
|
| 382 |
+
has_mx_records=False,
|
| 383 |
+
error=str(dns),
|
| 384 |
+
error_code="resolver_error",
|
| 385 |
+
)
|
| 386 |
+
)
|
| 387 |
+
domain_dns[domain] = result
|
| 388 |
+
# put_dns ignores transient failures internally.
|
| 389 |
+
await self.cache.put_dns(domain, result)
|
| 390 |
|
| 391 |
pending: list[tuple[int, str, SyntaxResult, str, DNSResult]] = []
|
| 392 |
for domain, idxs in domain_index.items():
|
|
|
|
| 456 |
pending = []
|
| 457 |
|
| 458 |
# ---- Layers 5 & 6: ONE batched mailbox call ------------------
|
| 459 |
+
cached_verdicts: dict[str, tuple[SMTPResult, Optional[bool]]] = {}
|
| 460 |
+
catch_all_map: dict[str, Optional[bool]] = {}
|
| 461 |
if pending:
|
| 462 |
+
# Serve anything already answered (definitive verdicts only) so we
|
| 463 |
+
# never re-probe an address we already know the answer to.
|
| 464 |
+
to_probe: list[tuple[int, str, SyntaxResult, str, DNSResult]] = []
|
| 465 |
+
for item in pending:
|
| 466 |
+
_idx, normalized, _syntax, _domain, _dns = item
|
| 467 |
+
hit = await self.cache.get_verdict(normalized, deep)
|
| 468 |
+
if hit is None:
|
| 469 |
+
to_probe.append(item)
|
| 470 |
+
else:
|
| 471 |
+
cached_verdicts[normalized] = hit
|
| 472 |
+
if hit[1] is not None:
|
| 473 |
+
catch_all_map[item[3]] = hit[1]
|
| 474 |
+
|
| 475 |
pairs = [
|
| 476 |
(normalized, dns.mx_records[0]["host"])
|
| 477 |
+
for _, normalized, _, _, dns in to_probe
|
| 478 |
]
|
| 479 |
+
smtp_map: dict[str, SMTPResult] = {}
|
| 480 |
+
if pairs:
|
| 481 |
+
try:
|
| 482 |
+
if hasattr(self.mailbox, "verify_many"):
|
| 483 |
+
smtp_map, caught = await self.mailbox.verify_many(pairs)
|
| 484 |
+
for domain, value in (caught or {}).items():
|
| 485 |
+
catch_all_map.setdefault(domain, value)
|
| 486 |
+
else:
|
| 487 |
+
# Provider cannot batch: per-address fallback.
|
| 488 |
+
for email, mx in pairs:
|
| 489 |
+
smtp_map[email] = await self.mailbox.verify(email, mx)
|
| 490 |
+
for domain in {e.rsplit("@", 1)[-1].lower() for e, _ in pairs}:
|
| 491 |
+
mx = next(
|
| 492 |
+
m for e, m in pairs
|
| 493 |
+
if e.rsplit("@", 1)[-1].lower() == domain
|
| 494 |
+
)
|
| 495 |
+
value, _conf = await self.mailbox.catch_all(domain, mx)
|
| 496 |
+
catch_all_map.setdefault(domain, value)
|
| 497 |
+
except Exception as exc: # one bad stage must not abort the batch
|
| 498 |
+
smtp_map = {
|
| 499 |
+
e: SMTPResult(verified=None, error=f"mailbox_stage_error: {exc}")
|
| 500 |
+
for e, _ in pairs
|
| 501 |
+
}
|
| 502 |
|
| 503 |
# ---- Layer 7: score each row -----------------------------
|
| 504 |
for idx, normalized, syntax, domain, dns in pending:
|
| 505 |
+
cached = cached_verdicts.get(normalized)
|
| 506 |
+
if cached is not None:
|
| 507 |
+
smtp, ca_cached = cached
|
| 508 |
+
else:
|
| 509 |
+
smtp = smtp_map.get(normalized) or SMTPResult(
|
| 510 |
+
verified=None, error="engine returned no result"
|
| 511 |
+
)
|
| 512 |
+
ca_cached = None
|
| 513 |
+
# Persist only definitive answers (verified verdict or a
|
| 514 |
+
# confirmed catch-all); transient failures are never cached.
|
| 515 |
+
await self.cache.put_verdict(
|
| 516 |
+
normalized, deep, smtp, catch_all_map.get(domain)
|
| 517 |
+
)
|
| 518 |
+
|
| 519 |
+
ca_value = (
|
| 520 |
+
ca_cached if ca_cached is not None else catch_all_map.get(domain)
|
| 521 |
)
|
|
|
|
| 522 |
catch_all = CatchAllResult(
|
| 523 |
is_catch_all=ca_value,
|
| 524 |
confidence=0.9 if ca_value is not None else 0.0,
|
app/validator/validation_cache.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Result caching for the verification engine.
|
| 2 |
+
|
| 3 |
+
Two things are expensive and highly reusable in bulk verification:
|
| 4 |
+
|
| 5 |
+
- **DNS/MX** for a domain (every address at that domain needs the same answer)
|
| 6 |
+
- **the mailbox verdict** for an address (lists overlap; users re-run lists)
|
| 7 |
+
|
| 8 |
+
Both are cached here, with one hard correctness rule: **only definitive results
|
| 9 |
+
are cached**. Transient failures — a DNS timeout, a greylist 4xx, an unreachable
|
| 10 |
+
MX — are never stored, because remembering them would freeze a temporary
|
| 11 |
+
condition into a 24h "verdict" and suppress a later successful probe.
|
| 12 |
+
|
| 13 |
+
A cache outage degrades to "no cache"; it must never break validation.
|
| 14 |
+
"""
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
from typing import Any, Callable, Coroutine, Optional
|
| 19 |
+
|
| 20 |
+
from ..config import settings
|
| 21 |
+
from ..models import DNSResult, SMTPResult
|
| 22 |
+
from ..utils.cache import get_cache as _default_get, set_cache as _default_set
|
| 23 |
+
|
| 24 |
+
# A DNS timeout/resolver error is inconclusive — never a cacheable fact.
|
| 25 |
+
_UNRESOLVED_DNS_CODES = frozenset({"timeout", "resolver_error"})
|
| 26 |
+
|
| 27 |
+
DNS_TTL = 24 * 3600 # MX/SPF/DMARC change slowly
|
| 28 |
+
VERDICT_TTL = 24 * 3600 # a mailbox verdict is stable within a day
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class ValidationCache:
|
| 32 |
+
"""Thin typed layer over the shared Redis/memory cache."""
|
| 33 |
+
|
| 34 |
+
def __init__(
|
| 35 |
+
self,
|
| 36 |
+
get: Optional[Callable[[str], Coroutine[Any, Any, Optional[str]]]] = None,
|
| 37 |
+
set: Optional[Callable[..., Coroutine[Any, Any, None]]] = None,
|
| 38 |
+
ttl_seconds: int = DNS_TTL,
|
| 39 |
+
):
|
| 40 |
+
self._get = get or _default_get
|
| 41 |
+
self._set = set or _default_set
|
| 42 |
+
self.ttl_seconds = ttl_seconds
|
| 43 |
+
|
| 44 |
+
# ---- keys ------------------------------------------------------
|
| 45 |
+
@staticmethod
|
| 46 |
+
def dns_key(domain: str) -> str:
|
| 47 |
+
return f"vx:dns:{domain.strip().lower()}"
|
| 48 |
+
|
| 49 |
+
@staticmethod
|
| 50 |
+
def verdict_key(email: str, deep: bool) -> str:
|
| 51 |
+
# `deep` is part of the identity: a fast-mode result carries no mailbox
|
| 52 |
+
# proof and must never satisfy a deep request.
|
| 53 |
+
return f"vx:v:{'d' if deep else 'f'}:{email.strip().lower()}"
|
| 54 |
+
|
| 55 |
+
# ---- low level -------------------------------------------------
|
| 56 |
+
async def _read_json(self, key: str) -> Optional[dict]:
|
| 57 |
+
try:
|
| 58 |
+
raw = await self._get(key)
|
| 59 |
+
except Exception:
|
| 60 |
+
return None # cache outage -> treat as a miss
|
| 61 |
+
if not raw:
|
| 62 |
+
return None
|
| 63 |
+
try:
|
| 64 |
+
data = json.loads(raw)
|
| 65 |
+
except Exception:
|
| 66 |
+
return None # corrupt payload -> miss, never raise
|
| 67 |
+
return data if isinstance(data, dict) else None
|
| 68 |
+
|
| 69 |
+
async def _write_json(self, key: str, payload: dict, ttl: int) -> None:
|
| 70 |
+
try:
|
| 71 |
+
await self._set(key, json.dumps(payload), ttl)
|
| 72 |
+
except Exception:
|
| 73 |
+
pass # a cache write failure must not break validation
|
| 74 |
+
|
| 75 |
+
# ---- DNS -------------------------------------------------------
|
| 76 |
+
async def get_dns(self, domain: str) -> Optional[DNSResult]:
|
| 77 |
+
data = await self._read_json(self.dns_key(domain))
|
| 78 |
+
if not data:
|
| 79 |
+
return None
|
| 80 |
+
try:
|
| 81 |
+
return DNSResult(**data)
|
| 82 |
+
except Exception:
|
| 83 |
+
return None
|
| 84 |
+
|
| 85 |
+
async def put_dns(self, domain: str, result: DNSResult) -> None:
|
| 86 |
+
if result.error_code in _UNRESOLVED_DNS_CODES:
|
| 87 |
+
return # transient -> never cache
|
| 88 |
+
await self._write_json(
|
| 89 |
+
self.dns_key(domain), result.model_dump(), self.ttl_seconds
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
# ---- mailbox verdict ------------------------------------------
|
| 93 |
+
async def get_verdict(
|
| 94 |
+
self, email: str, deep: bool
|
| 95 |
+
) -> Optional[tuple[SMTPResult, Optional[bool]]]:
|
| 96 |
+
data = await self._read_json(self.verdict_key(email, deep))
|
| 97 |
+
if not data:
|
| 98 |
+
return None
|
| 99 |
+
try:
|
| 100 |
+
smtp = SMTPResult(**data["smtp"])
|
| 101 |
+
catch_all = data.get("catch_all")
|
| 102 |
+
return smtp, catch_all
|
| 103 |
+
except Exception:
|
| 104 |
+
return None
|
| 105 |
+
|
| 106 |
+
async def put_verdict(
|
| 107 |
+
self,
|
| 108 |
+
email: str,
|
| 109 |
+
deep: bool,
|
| 110 |
+
smtp: SMTPResult,
|
| 111 |
+
catch_all: Optional[bool],
|
| 112 |
+
) -> None:
|
| 113 |
+
# Cacheable only when the mailbox question was actually answered, or the
|
| 114 |
+
# domain is definitively catch-all (a domain fact, not a probe failure).
|
| 115 |
+
definitive = smtp.verified is not None or catch_all is True
|
| 116 |
+
if not definitive:
|
| 117 |
+
return
|
| 118 |
+
await self._write_json(
|
| 119 |
+
self.verdict_key(email, deep),
|
| 120 |
+
{"smtp": smtp.model_dump(), "catch_all": catch_all},
|
| 121 |
+
VERDICT_TTL,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
# Shared instance used by the engine.
|
| 126 |
+
validation_cache = ValidationCache(
|
| 127 |
+
ttl_seconds=getattr(settings, "dns_cache_ttl_seconds", DNS_TTL)
|
| 128 |
+
)
|
tests/conftest.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared pytest fixtures.
|
| 2 |
+
|
| 3 |
+
The validation engine defaults to a process-global Redis/in-memory cache so
|
| 4 |
+
results are reused across runs. That is correct in production but leaks state
|
| 5 |
+
between tests — one test's cached DNS/MX then satisfies the next test's
|
| 6 |
+
"resolution happened" assertion.
|
| 7 |
+
|
| 8 |
+
Clearing the in-memory tier between tests keeps the suite hermetic without
|
| 9 |
+
every test having to inject its own cache. Tests that assert on caching still
|
| 10 |
+
inject a recording cache explicitly.
|
| 11 |
+
"""
|
| 12 |
+
import pytest
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@pytest.fixture(autouse=True)
|
| 16 |
+
def _clear_global_cache():
|
| 17 |
+
try:
|
| 18 |
+
from app.utils import cache as cache_mod
|
| 19 |
+
except Exception: # pragma: no cover - import guard
|
| 20 |
+
yield
|
| 21 |
+
return
|
| 22 |
+
|
| 23 |
+
cache_mod._memory_cache.clear()
|
| 24 |
+
yield
|
| 25 |
+
cache_mod._memory_cache.clear()
|
tests/test_engine_batch.py
CHANGED
|
@@ -25,6 +25,26 @@ def _disposable_clean():
|
|
| 25 |
)
|
| 26 |
|
| 27 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
class FakeBatchProvider:
|
| 29 |
"""Provider exposing the bulk capability the engine should exploit.
|
| 30 |
|
|
@@ -65,7 +85,7 @@ class EngineBatchTests(unittest.IsolatedAsyncioTestCase):
|
|
| 65 |
},
|
| 66 |
catch_all={"corp.test": False, "other.test": False},
|
| 67 |
)
|
| 68 |
-
engine = EmailValidationEngine(mailbox=provider)
|
| 69 |
with (
|
| 70 |
patch(
|
| 71 |
"app.validator.engine.check_dns",
|
|
@@ -92,7 +112,7 @@ class EngineBatchTests(unittest.IsolatedAsyncioTestCase):
|
|
| 92 |
},
|
| 93 |
catch_all={"corp.test": False},
|
| 94 |
)
|
| 95 |
-
engine = EmailValidationEngine(mailbox=provider)
|
| 96 |
with (
|
| 97 |
patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns_ok())),
|
| 98 |
patch("app.validator.engine.check_disposable", return_value=_disposable_clean()),
|
|
@@ -112,7 +132,7 @@ class EngineBatchTests(unittest.IsolatedAsyncioTestCase):
|
|
| 112 |
results={"a@corp.test": SMTPResult(verified=True, smtp_code=250)},
|
| 113 |
catch_all={"corp.test": False},
|
| 114 |
)
|
| 115 |
-
engine = EmailValidationEngine(mailbox=provider)
|
| 116 |
with (
|
| 117 |
patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns_ok())),
|
| 118 |
patch("app.validator.engine.check_disposable", return_value=_disposable_clean()),
|
|
@@ -137,7 +157,7 @@ class EngineBatchTests(unittest.IsolatedAsyncioTestCase):
|
|
| 137 |
},
|
| 138 |
catch_all={"catchall.test": True},
|
| 139 |
)
|
| 140 |
-
engine = EmailValidationEngine(mailbox=provider)
|
| 141 |
with (
|
| 142 |
patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns_ok())),
|
| 143 |
patch("app.validator.engine.check_disposable", return_value=_disposable_clean()),
|
|
@@ -152,7 +172,7 @@ class EngineBatchTests(unittest.IsolatedAsyncioTestCase):
|
|
| 152 |
results={"ok@corp.test": SMTPResult(verified=True, smtp_code=250)},
|
| 153 |
catch_all={"corp.test": False},
|
| 154 |
)
|
| 155 |
-
engine = EmailValidationEngine(mailbox=provider)
|
| 156 |
with (
|
| 157 |
patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns_ok())),
|
| 158 |
patch("app.validator.engine.check_disposable", return_value=_disposable_clean()),
|
|
@@ -180,7 +200,7 @@ class EngineBatchTests(unittest.IsolatedAsyncioTestCase):
|
|
| 180 |
return (False, 0.9)
|
| 181 |
|
| 182 |
provider = SingleOnlyProvider()
|
| 183 |
-
engine = EmailValidationEngine(mailbox=provider)
|
| 184 |
with (
|
| 185 |
patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns_ok())),
|
| 186 |
patch("app.validator.engine.check_disposable", return_value=_disposable_clean()),
|
|
|
|
| 25 |
)
|
| 26 |
|
| 27 |
|
| 28 |
+
class NullCache:
|
| 29 |
+
"""Hermetic no-op cache.
|
| 30 |
+
|
| 31 |
+
The engine defaults to a process-global cache for cross-run reuse; tests
|
| 32 |
+
must inject this so one test's cached DNS/MX cannot leak into the next.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
async def get_dns(self, domain):
|
| 36 |
+
return None
|
| 37 |
+
|
| 38 |
+
async def put_dns(self, domain, result):
|
| 39 |
+
return None
|
| 40 |
+
|
| 41 |
+
async def get_verdict(self, email, deep):
|
| 42 |
+
return None
|
| 43 |
+
|
| 44 |
+
async def put_verdict(self, email, deep, smtp, catch_all):
|
| 45 |
+
return None
|
| 46 |
+
|
| 47 |
+
|
| 48 |
class FakeBatchProvider:
|
| 49 |
"""Provider exposing the bulk capability the engine should exploit.
|
| 50 |
|
|
|
|
| 85 |
},
|
| 86 |
catch_all={"corp.test": False, "other.test": False},
|
| 87 |
)
|
| 88 |
+
engine = EmailValidationEngine(mailbox=provider, cache=NullCache())
|
| 89 |
with (
|
| 90 |
patch(
|
| 91 |
"app.validator.engine.check_dns",
|
|
|
|
| 112 |
},
|
| 113 |
catch_all={"corp.test": False},
|
| 114 |
)
|
| 115 |
+
engine = EmailValidationEngine(mailbox=provider, cache=NullCache())
|
| 116 |
with (
|
| 117 |
patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns_ok())),
|
| 118 |
patch("app.validator.engine.check_disposable", return_value=_disposable_clean()),
|
|
|
|
| 132 |
results={"a@corp.test": SMTPResult(verified=True, smtp_code=250)},
|
| 133 |
catch_all={"corp.test": False},
|
| 134 |
)
|
| 135 |
+
engine = EmailValidationEngine(mailbox=provider, cache=NullCache())
|
| 136 |
with (
|
| 137 |
patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns_ok())),
|
| 138 |
patch("app.validator.engine.check_disposable", return_value=_disposable_clean()),
|
|
|
|
| 157 |
},
|
| 158 |
catch_all={"catchall.test": True},
|
| 159 |
)
|
| 160 |
+
engine = EmailValidationEngine(mailbox=provider, cache=NullCache())
|
| 161 |
with (
|
| 162 |
patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns_ok())),
|
| 163 |
patch("app.validator.engine.check_disposable", return_value=_disposable_clean()),
|
|
|
|
| 172 |
results={"ok@corp.test": SMTPResult(verified=True, smtp_code=250)},
|
| 173 |
catch_all={"corp.test": False},
|
| 174 |
)
|
| 175 |
+
engine = EmailValidationEngine(mailbox=provider, cache=NullCache())
|
| 176 |
with (
|
| 177 |
patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns_ok())),
|
| 178 |
patch("app.validator.engine.check_disposable", return_value=_disposable_clean()),
|
|
|
|
| 200 |
return (False, 0.9)
|
| 201 |
|
| 202 |
provider = SingleOnlyProvider()
|
| 203 |
+
engine = EmailValidationEngine(mailbox=provider, cache=NullCache())
|
| 204 |
with (
|
| 205 |
patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns_ok())),
|
| 206 |
patch("app.validator.engine.check_disposable", return_value=_disposable_clean()),
|
tests/test_engine_cache.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
from unittest.mock import AsyncMock, patch
|
| 3 |
+
|
| 4 |
+
from app.models import DNSResult, DisposableResult, SMTPResult, ValidationStatus
|
| 5 |
+
from app.validator.engine import EmailValidationEngine
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _dns(host="mx.example.test"):
|
| 9 |
+
return DNSResult(
|
| 10 |
+
domain_exists=True,
|
| 11 |
+
has_mx_records=True,
|
| 12 |
+
mx_records=[{"host": host, "priority": 10}],
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _clean():
|
| 17 |
+
return DisposableResult(
|
| 18 |
+
is_disposable=False, is_free_provider=False, is_role_based=False
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class RecordingCache:
|
| 23 |
+
"""In-memory stand-in for ValidationCache that records interactions."""
|
| 24 |
+
|
| 25 |
+
def __init__(self):
|
| 26 |
+
self.dns: dict[str, DNSResult] = {}
|
| 27 |
+
self.verdicts: dict[tuple[str, bool], tuple[SMTPResult, object]] = {}
|
| 28 |
+
self.dns_puts: list[str] = []
|
| 29 |
+
self.verdict_puts: list[str] = []
|
| 30 |
+
|
| 31 |
+
async def get_dns(self, domain):
|
| 32 |
+
return self.dns.get(domain.lower())
|
| 33 |
+
|
| 34 |
+
async def put_dns(self, domain, result):
|
| 35 |
+
if result.error_code in {"timeout", "resolver_error"}:
|
| 36 |
+
return
|
| 37 |
+
self.dns_puts.append(domain)
|
| 38 |
+
self.dns[domain.lower()] = result
|
| 39 |
+
|
| 40 |
+
async def get_verdict(self, email, deep):
|
| 41 |
+
return self.verdicts.get((email.lower(), deep))
|
| 42 |
+
|
| 43 |
+
async def put_verdict(self, email, deep, smtp, catch_all):
|
| 44 |
+
if smtp.verified is None and catch_all is not True:
|
| 45 |
+
return
|
| 46 |
+
self.verdict_puts.append(email)
|
| 47 |
+
self.verdicts[(email.lower(), deep)] = (smtp, catch_all)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class CountingProvider:
|
| 51 |
+
def __init__(self, smtp_map=None):
|
| 52 |
+
self._smtp = smtp_map or {}
|
| 53 |
+
self.batch_calls = 0
|
| 54 |
+
self.pairs_seen: list[tuple[str, str]] = []
|
| 55 |
+
|
| 56 |
+
async def verify_many(self, pairs):
|
| 57 |
+
self.batch_calls += 1
|
| 58 |
+
self.pairs_seen.extend(pairs)
|
| 59 |
+
return (
|
| 60 |
+
{e: self._smtp.get(e, SMTPResult(verified=True, smtp_code=250)) for e, _ in pairs},
|
| 61 |
+
{},
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
async def verify(self, email, mx_host):
|
| 65 |
+
return self._smtp.get(email, SMTPResult(verified=True, smtp_code=250))
|
| 66 |
+
|
| 67 |
+
async def catch_all(self, domain, mx_host):
|
| 68 |
+
return (False, 0.9)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class EngineCacheTests(unittest.IsolatedAsyncioTestCase):
|
| 72 |
+
"""The batch pipeline must consult and populate the cache."""
|
| 73 |
+
|
| 74 |
+
async def test_dns_cache_hit_skips_resolution(self):
|
| 75 |
+
cache = RecordingCache()
|
| 76 |
+
cache.dns["corp.test"] = _dns()
|
| 77 |
+
engine = EmailValidationEngine(mailbox=CountingProvider(), cache=cache)
|
| 78 |
+
|
| 79 |
+
with (
|
| 80 |
+
patch(
|
| 81 |
+
"app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())
|
| 82 |
+
) as dns_mock,
|
| 83 |
+
patch("app.validator.engine.check_disposable", return_value=_clean()),
|
| 84 |
+
):
|
| 85 |
+
results = await engine.validate_batch(["a@corp.test"], deep=True)
|
| 86 |
+
|
| 87 |
+
self.assertEqual(dns_mock.await_count, 0, "cache hit should skip DNS")
|
| 88 |
+
self.assertEqual(results[0].status, ValidationStatus.VALID)
|
| 89 |
+
|
| 90 |
+
async def test_dns_miss_is_populated_for_next_run(self):
|
| 91 |
+
cache = RecordingCache()
|
| 92 |
+
engine = EmailValidationEngine(mailbox=CountingProvider(), cache=cache)
|
| 93 |
+
|
| 94 |
+
with (
|
| 95 |
+
patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())),
|
| 96 |
+
patch("app.validator.engine.check_disposable", return_value=_clean()),
|
| 97 |
+
):
|
| 98 |
+
await engine.validate_batch(["a@corp.test"], deep=True)
|
| 99 |
+
|
| 100 |
+
self.assertIn("corp.test", cache.dns_puts)
|
| 101 |
+
|
| 102 |
+
async def test_dns_result_is_reused_across_addresses_in_one_run(self):
|
| 103 |
+
cache = RecordingCache()
|
| 104 |
+
engine = EmailValidationEngine(mailbox=CountingProvider(), cache=cache)
|
| 105 |
+
|
| 106 |
+
with (
|
| 107 |
+
patch(
|
| 108 |
+
"app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())
|
| 109 |
+
) as dns_mock,
|
| 110 |
+
patch("app.validator.engine.check_disposable", return_value=_clean()),
|
| 111 |
+
):
|
| 112 |
+
await engine.validate_batch(
|
| 113 |
+
["a@corp.test", "b@corp.test", "c@corp.test"], deep=True
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
self.assertEqual(dns_mock.await_count, 1)
|
| 117 |
+
|
| 118 |
+
async def test_cached_verdict_skips_the_mailbox_probe(self):
|
| 119 |
+
cache = RecordingCache()
|
| 120 |
+
cache.dns["corp.test"] = _dns()
|
| 121 |
+
cache.verdicts[("a@corp.test", True)] = (
|
| 122 |
+
SMTPResult(verified=True, smtp_code=250),
|
| 123 |
+
False,
|
| 124 |
+
)
|
| 125 |
+
provider = CountingProvider()
|
| 126 |
+
engine = EmailValidationEngine(mailbox=provider, cache=cache)
|
| 127 |
+
|
| 128 |
+
with (
|
| 129 |
+
patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())),
|
| 130 |
+
patch("app.validator.engine.check_disposable", return_value=_clean()),
|
| 131 |
+
):
|
| 132 |
+
results = await engine.validate_batch(["a@corp.test"], deep=True)
|
| 133 |
+
|
| 134 |
+
self.assertEqual(provider.batch_calls, 0, "cached verdict should skip the probe")
|
| 135 |
+
self.assertEqual(results[0].status, ValidationStatus.VALID)
|
| 136 |
+
self.assertTrue(results[0].smtp.verified)
|
| 137 |
+
|
| 138 |
+
async def test_only_uncached_addresses_are_probed(self):
|
| 139 |
+
cache = RecordingCache()
|
| 140 |
+
cache.dns["corp.test"] = _dns()
|
| 141 |
+
cache.verdicts[("a@corp.test", True)] = (
|
| 142 |
+
SMTPResult(verified=True, smtp_code=250),
|
| 143 |
+
False,
|
| 144 |
+
)
|
| 145 |
+
provider = CountingProvider()
|
| 146 |
+
engine = EmailValidationEngine(mailbox=provider, cache=cache)
|
| 147 |
+
|
| 148 |
+
with (
|
| 149 |
+
patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())),
|
| 150 |
+
patch("app.validator.engine.check_disposable", return_value=_clean()),
|
| 151 |
+
):
|
| 152 |
+
await engine.validate_batch(["a@corp.test", "b@corp.test"], deep=True)
|
| 153 |
+
|
| 154 |
+
self.assertEqual(provider.pairs_seen, [("b@corp.test", "mx.example.test")])
|
| 155 |
+
|
| 156 |
+
async def test_definitive_verdict_is_cached(self):
|
| 157 |
+
cache = RecordingCache()
|
| 158 |
+
engine = EmailValidationEngine(
|
| 159 |
+
mailbox=CountingProvider(
|
| 160 |
+
{"a@corp.test": SMTPResult(verified=False, smtp_code=550,
|
| 161 |
+
smtp_message="550 no such user")}
|
| 162 |
+
),
|
| 163 |
+
cache=cache,
|
| 164 |
+
)
|
| 165 |
+
with (
|
| 166 |
+
patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())),
|
| 167 |
+
patch("app.validator.engine.check_disposable", return_value=_clean()),
|
| 168 |
+
):
|
| 169 |
+
await engine.validate_batch(["a@corp.test"], deep=True)
|
| 170 |
+
|
| 171 |
+
self.assertIn("a@corp.test", cache.verdict_puts)
|
| 172 |
+
|
| 173 |
+
async def test_inconclusive_verdict_is_not_cached(self):
|
| 174 |
+
cache = RecordingCache()
|
| 175 |
+
engine = EmailValidationEngine(
|
| 176 |
+
mailbox=CountingProvider(
|
| 177 |
+
{"a@corp.test": SMTPResult(verified=None, error="transport_error")}
|
| 178 |
+
),
|
| 179 |
+
cache=cache,
|
| 180 |
+
)
|
| 181 |
+
with (
|
| 182 |
+
patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())),
|
| 183 |
+
patch("app.validator.engine.check_disposable", return_value=_clean()),
|
| 184 |
+
):
|
| 185 |
+
await engine.validate_batch(["a@corp.test"], deep=True)
|
| 186 |
+
|
| 187 |
+
self.assertNotIn("a@corp.test", cache.verdict_puts)
|
| 188 |
+
|
| 189 |
+
async def test_cached_row_still_reports_all_seven_layers(self):
|
| 190 |
+
cache = RecordingCache()
|
| 191 |
+
cache.dns["corp.test"] = _dns()
|
| 192 |
+
cache.verdicts[("a@corp.test", True)] = (
|
| 193 |
+
SMTPResult(verified=True, smtp_code=250),
|
| 194 |
+
False,
|
| 195 |
+
)
|
| 196 |
+
engine = EmailValidationEngine(mailbox=CountingProvider(), cache=cache)
|
| 197 |
+
with (
|
| 198 |
+
patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())),
|
| 199 |
+
patch("app.validator.engine.check_disposable", return_value=_clean()),
|
| 200 |
+
):
|
| 201 |
+
results = await engine.validate_batch(["a@corp.test"], deep=True)
|
| 202 |
+
|
| 203 |
+
self.assertEqual(
|
| 204 |
+
results[0].checks_run,
|
| 205 |
+
["syntax", "dns", "mx", "disposable", "catch_all", "smtp", "scoring"],
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
async def test_fast_mode_does_not_read_deep_verdicts(self):
|
| 209 |
+
cache = RecordingCache()
|
| 210 |
+
cache.dns["corp.test"] = _dns()
|
| 211 |
+
cache.verdicts[("a@corp.test", True)] = (
|
| 212 |
+
SMTPResult(verified=True, smtp_code=250),
|
| 213 |
+
False,
|
| 214 |
+
)
|
| 215 |
+
engine = EmailValidationEngine(mailbox=CountingProvider(), cache=cache)
|
| 216 |
+
with (
|
| 217 |
+
patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())),
|
| 218 |
+
patch("app.validator.engine.check_disposable", return_value=_clean()),
|
| 219 |
+
):
|
| 220 |
+
results = await engine.validate_batch(["a@corp.test"], deep=False)
|
| 221 |
+
|
| 222 |
+
# Fast mode skips the mailbox layers entirely, so it must not surface a
|
| 223 |
+
# deep verdict as if it had probed.
|
| 224 |
+
self.assertIsNone(results[0].smtp)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
if __name__ == "__main__":
|
| 228 |
+
unittest.main()
|
tests/test_validation_cache.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
from app.models import DNSResult, SMTPResult
|
| 4 |
+
from app.validator.validation_cache import ValidationCache
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class FakeBackend:
|
| 8 |
+
"""Dict-backed stand-in for the Redis/memory cache."""
|
| 9 |
+
|
| 10 |
+
def __init__(self):
|
| 11 |
+
self.store: dict[str, str] = {}
|
| 12 |
+
self.puts = 0
|
| 13 |
+
|
| 14 |
+
async def get(self, key):
|
| 15 |
+
return self.store.get(key)
|
| 16 |
+
|
| 17 |
+
async def set(self, key, value, ttl=0):
|
| 18 |
+
self.puts += 1
|
| 19 |
+
self.store[key] = value
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def make_cache():
|
| 23 |
+
backend = FakeBackend()
|
| 24 |
+
return ValidationCache(get=backend.get, set=backend.set, ttl_seconds=3600), backend
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class DomainDnsCacheTests(unittest.IsolatedAsyncioTestCase):
|
| 28 |
+
async def test_definitive_dns_result_round_trips(self):
|
| 29 |
+
cache, _ = make_cache()
|
| 30 |
+
dns = DNSResult(
|
| 31 |
+
domain_exists=True,
|
| 32 |
+
has_mx_records=True,
|
| 33 |
+
mx_records=[{"host": "mx.google.com", "priority": 5}],
|
| 34 |
+
has_spf=True,
|
| 35 |
+
spf_record="v=spf1 include:_spf.google.com ~all",
|
| 36 |
+
has_dmarc=True,
|
| 37 |
+
)
|
| 38 |
+
await cache.put_dns("gmail.com", dns)
|
| 39 |
+
got = await cache.get_dns("gmail.com")
|
| 40 |
+
|
| 41 |
+
self.assertIsNotNone(got)
|
| 42 |
+
self.assertTrue(got.domain_exists)
|
| 43 |
+
self.assertTrue(got.has_mx_records)
|
| 44 |
+
self.assertEqual(got.mx_records[0]["host"], "mx.google.com")
|
| 45 |
+
self.assertTrue(got.has_spf)
|
| 46 |
+
|
| 47 |
+
async def test_keys_are_case_insensitive(self):
|
| 48 |
+
cache, _ = make_cache()
|
| 49 |
+
await cache.put_dns("Gmail.COM", DNSResult(domain_exists=True, has_mx_records=True))
|
| 50 |
+
self.assertIsNotNone(await cache.get_dns("gmail.com"))
|
| 51 |
+
|
| 52 |
+
async def test_dns_timeout_is_never_cached(self):
|
| 53 |
+
# A transient resolver failure must not be remembered as a verdict —
|
| 54 |
+
# otherwise one timeout would mark a domain dead for a full day.
|
| 55 |
+
cache, backend = make_cache()
|
| 56 |
+
await cache.put_dns(
|
| 57 |
+
"flaky.test",
|
| 58 |
+
DNSResult(domain_exists=False, has_mx_records=False, error_code="timeout"),
|
| 59 |
+
)
|
| 60 |
+
self.assertIsNone(await cache.get_dns("flaky.test"))
|
| 61 |
+
self.assertEqual(backend.puts, 0)
|
| 62 |
+
|
| 63 |
+
async def test_resolver_error_is_never_cached(self):
|
| 64 |
+
cache, _ = make_cache()
|
| 65 |
+
await cache.put_dns(
|
| 66 |
+
"flaky.test",
|
| 67 |
+
DNSResult(domain_exists=False, has_mx_records=False, error_code="resolver_error"),
|
| 68 |
+
)
|
| 69 |
+
self.assertIsNone(await cache.get_dns("flaky.test"))
|
| 70 |
+
|
| 71 |
+
async def test_missing_key_returns_none(self):
|
| 72 |
+
cache, _ = make_cache()
|
| 73 |
+
self.assertIsNone(await cache.get_dns("never-seen.test"))
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class AddressVerdictCacheTests(unittest.IsolatedAsyncioTestCase):
|
| 77 |
+
async def test_verified_mailbox_is_cached(self):
|
| 78 |
+
cache, _ = make_cache()
|
| 79 |
+
await cache.put_verdict(
|
| 80 |
+
"a@gmail.com", deep=True, smtp=SMTPResult(verified=True, smtp_code=250),
|
| 81 |
+
catch_all=False,
|
| 82 |
+
)
|
| 83 |
+
got = await cache.get_verdict("a@gmail.com", deep=True)
|
| 84 |
+
self.assertIsNotNone(got)
|
| 85 |
+
smtp, catch_all = got
|
| 86 |
+
self.assertTrue(smtp.verified)
|
| 87 |
+
self.assertIs(catch_all, False)
|
| 88 |
+
|
| 89 |
+
async def test_rejected_mailbox_is_cached(self):
|
| 90 |
+
cache, _ = make_cache()
|
| 91 |
+
await cache.put_verdict(
|
| 92 |
+
"ghost@gmail.com", deep=True,
|
| 93 |
+
smtp=SMTPResult(verified=False, smtp_code=550, smtp_message="550 no such user"),
|
| 94 |
+
catch_all=False,
|
| 95 |
+
)
|
| 96 |
+
smtp, _ = await cache.get_verdict("ghost@gmail.com", deep=True)
|
| 97 |
+
self.assertFalse(smtp.verified)
|
| 98 |
+
self.assertEqual(smtp.smtp_code, 550)
|
| 99 |
+
|
| 100 |
+
async def test_inconclusive_verdict_is_never_cached(self):
|
| 101 |
+
# verified=None means "we could not tell" — caching it would freeze an
|
| 102 |
+
# unknown for 24h and suppress a later successful probe.
|
| 103 |
+
cache, backend = make_cache()
|
| 104 |
+
await cache.put_verdict(
|
| 105 |
+
"a@gmail.com", deep=True,
|
| 106 |
+
smtp=SMTPResult(verified=None, error="SMTP verification timed out"),
|
| 107 |
+
catch_all=None,
|
| 108 |
+
)
|
| 109 |
+
self.assertIsNone(await cache.get_verdict("a@gmail.com", deep=True))
|
| 110 |
+
self.assertEqual(backend.puts, 0)
|
| 111 |
+
|
| 112 |
+
async def test_catch_all_flag_is_preserved(self):
|
| 113 |
+
cache, _ = make_cache()
|
| 114 |
+
await cache.put_verdict(
|
| 115 |
+
"x@catchall.test", deep=True,
|
| 116 |
+
smtp=SMTPResult(verified=None, error="catch_all"), catch_all=True,
|
| 117 |
+
)
|
| 118 |
+
got = await cache.get_verdict("x@catchall.test", deep=True)
|
| 119 |
+
# A catch-all row IS a definitive domain fact, so it is cacheable.
|
| 120 |
+
self.assertIsNotNone(got)
|
| 121 |
+
self.assertIs(got[1], True)
|
| 122 |
+
|
| 123 |
+
async def test_deep_and_fast_verdicts_do_not_collide(self):
|
| 124 |
+
# The UI flags unsaved demo runs by `deep`; a fast-mode (no mailbox
|
| 125 |
+
# proof) verdict must never be served to a deep request.
|
| 126 |
+
cache, _ = make_cache()
|
| 127 |
+
await cache.put_verdict(
|
| 128 |
+
"a@gmail.com", deep=False, smtp=SMTPResult(verified=None, error="skipped"),
|
| 129 |
+
catch_all=None,
|
| 130 |
+
)
|
| 131 |
+
self.assertIsNone(await cache.get_verdict("a@gmail.com", deep=True))
|
| 132 |
+
|
| 133 |
+
async def test_emails_are_case_insensitive(self):
|
| 134 |
+
cache, _ = make_cache()
|
| 135 |
+
await cache.put_verdict(
|
| 136 |
+
"A@Gmail.com", deep=True, smtp=SMTPResult(verified=True, smtp_code=250),
|
| 137 |
+
catch_all=False,
|
| 138 |
+
)
|
| 139 |
+
self.assertIsNotNone(await cache.get_verdict("a@gmail.com", deep=True))
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
class CacheFailureToleranceTests(unittest.IsolatedAsyncioTestCase):
|
| 143 |
+
"""A cache outage must degrade to "no cache", never break validation."""
|
| 144 |
+
|
| 145 |
+
async def test_get_errors_return_none(self):
|
| 146 |
+
async def boom(key):
|
| 147 |
+
raise RuntimeError("redis down")
|
| 148 |
+
|
| 149 |
+
cache = ValidationCache(get=boom, set=boom, ttl_seconds=60)
|
| 150 |
+
self.assertIsNone(await cache.get_dns("gmail.com"))
|
| 151 |
+
self.assertIsNone(await cache.get_verdict("a@gmail.com", deep=True))
|
| 152 |
+
|
| 153 |
+
async def test_set_errors_do_not_raise(self):
|
| 154 |
+
async def boom(*a, **k):
|
| 155 |
+
raise RuntimeError("redis down")
|
| 156 |
+
|
| 157 |
+
cache = ValidationCache(get=boom, set=boom, ttl_seconds=60)
|
| 158 |
+
await cache.put_dns("gmail.com", DNSResult(domain_exists=True, has_mx_records=True))
|
| 159 |
+
await cache.put_verdict(
|
| 160 |
+
"a@gmail.com", deep=True, smtp=SMTPResult(verified=True, smtp_code=250),
|
| 161 |
+
catch_all=False,
|
| 162 |
+
) # must not raise
|
| 163 |
+
|
| 164 |
+
async def test_corrupt_payload_returns_none(self):
|
| 165 |
+
async def bad_get(key):
|
| 166 |
+
return "{not json"
|
| 167 |
+
|
| 168 |
+
cache = ValidationCache(get=bad_get, set=bad_get, ttl_seconds=60)
|
| 169 |
+
self.assertIsNone(await cache.get_dns("gmail.com"))
|
| 170 |
+
self.assertIsNone(await cache.get_verdict("a@gmail.com", deep=True))
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
if __name__ == "__main__":
|
| 174 |
+
unittest.main()
|