Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .env.example+38-18
- .pytest_cache/.gitignoreAdded+2
- .pytest_cache/CACHEDIR.TAGAdded+4
- .pytest_cache/README.mdAdded+8
- .pytest_cache/v/cache/lastfailedAdded+6
- .pytest_cache/v/cache/nodeidsAdded+63
- .ruff_cache/.gitignoreAdded+2
- .ruff_cache/0.16.9/16425691590624931606Added
- .ruff_cache/0.16.9/3813915841381071652Added
- .ruff_cache/0.16.9/4599002183323651371Added
- .ruff_cache/0.16.9/5957269552066581026Added
- .ruff_cache/0.16.9/6488544497621898133Added
- .ruff_cache/0.16.9/6758043911225637996Added
- .ruff_cache/0.16.9/8632362223362502010Added
- .ruff_cache/0.16.9/9797602248524197306Added
- .ruff_cache/CACHEDIR.TAGAdded+1
- Dockerfile+2-4
- Dockerfile.hf+1-2
- README.md+60
- app/api/routes.py+12-7
- app/config.py+61-7
- app/models.py+19-1
- app/tasks/celery_tasks.py+13-15
- app/utils/cache.py+4-30
- app/validator/catch_all.py-1
- app/validator/dns_check.py+50-11
- app/validator/engine.py+173-23
- app/validator/mailbox_provider.pyAdded+196
- app/validator/scoring.py+95-28
- app/validator/smtp_verify.py+1-1
- pytest.iniAdded+3
- requirements-dev.txtAdded+4
- ruff.tomlAdded+4
- test_connections.py+14-6
- tests/test_bulk_depth.pyAdded+132
- tests/test_cache_config.pyAdded+49
- tests/test_dns_correctness.pyAdded+95
- tests/test_engine_dns_failures.pyAdded+185
- tests/test_engine_metadata.pyAdded+318
- tests/test_mailbox_provider.pyAdded+151
- tests/test_production_config.pyAdded+49
- tests/test_scoring_claims.pyAdded+162
- venv/Lib/site-packages/_pytest/__init__.pyAdded+13
- venv/Lib/site-packages/_pytest/_argcomplete.pyAdded+117
- venv/Lib/site-packages/_pytest/_code/__init__.pyAdded+26
- venv/Lib/site-packages/_pytest/_code/code.pyAdded+1632
- venv/Lib/site-packages/_pytest/_code/source.pyAdded+228
- venv/Lib/site-packages/_pytest/_io/__init__.pyAdded+10
- venv/Lib/site-packages/_pytest/_io/pprint.pyAdded+673
- venv/Lib/site-packages/_pytest/_io/saferepr.pyAdded+155
1234567891011121314151617181920212223242526272829303132333435# Copy to .env and adjust for your environmentAPP_NAME="EmailValidator Pro"APP_VERSION="2.0.0"DEBUG=trueSECRET_KEY=change-me-in-productionHOST=0.0.0.0PORT=8000WORKERS=4# --- Supabase (Postgres + PostgREST) ---SUPABASE_URL=https://YOUR_PROJECT_REF.supabase.coSUPABASE_ANON_KEY=your-public-anon-key # safe for browser (RLS governs access)SUPABASE_SERVICE_ROLE_KEY=your-service-role-key # server-only, bypasses RLSENABLE_DB_PERSISTENCE=true# Local dev DB fallback (not used when Supabase is configured)DATABASE_URL=sqlite+aiosqlite:///./emailval.dbREDIS_URL=redis://localhost:6379/0REDIS_CACHE_TTL=86400# Upstash rediss:// URLs need ?ssl_cert_reqs=none (Celery requires the param):# rediss://default:TOKEN@host.upstash.io:6379/0?ssl_cert_reqs=none# Free-tier (/start-redis) databases support ONLY db 0 — use one database per# logical store (cache, celery broker, celery result backend).# --- Upstash Developer API (provision Redis databases) ---# Create a key at: https://console.upstash.com/account/apiUPSTASH_MANAGEMENT_KEY=UPSTASH_ACCOUNT_EMAIL=CORS_ORIGINS=["http://localhost:5173","http://localhost:3000","http://127.0.0.1:5173"]SMTP_TIMEOUT=10DNS_TIMEOUT=5MAX_BULK_EMAILS=10000RATE_LIMIT_PER_MINUTE=60USE_PROXIES=falseCELERY_BROKER_URL=redis://localhost:6379/1CELERY_RESULT_BACKEND=redis://localhost:6379/212345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455# Copy to .env and adjust for your environment.APP_ENVIRONMENT=developmentAPP_NAME="BRIDGE Modul - X"APP_VERSION="2.1.0"DEBUG=trueSECRET_KEY=replace-with-a-random-secretHOST=0.0.0.0PORT=8000WORKERS=4# Supabase (server-side service-role key; never expose it to the browser)SUPABASE_URL=https://YOUR_PROJECT_REF.supabase.coSUPABASE_ANON_KEY=your-public-anon-keySUPABASE_SERVICE_ROLE_KEY=your-server-only-service-role-keyENABLE_DB_PERSISTENCE=trueLICENSE_ENFORCEMENT=false# Local development defaultsDATABASE_URL=sqlite+aiosqlite:///./emailval.dbREDIS_URL=redis://localhost:6379/0REDIS_CACHE_TTL=86400CELERY_BROKER_URL=redis://localhost:6379/1CELERY_RESULT_BACKEND=redis://localhost:6379/2# For Upstash, use TLS and database index /0:# REDIS_URL=rediss://default:YOUR_REDIS_TOKEN@YOUR_ENDPOINT:6379/0# CELERY_BROKER_URL=rediss://default:YOUR_REDIS_TOKEN@YOUR_ENDPOINT:6379/0# CELERY_RESULT_BACKEND=rediss://default:YOUR_REDIS_TOKEN@YOUR_ENDPOINT:6379/0# Never disable TLS certificate verification. Upstash Free has one database;# prove Celery key-prefix isolation and compatibility before sharing it, or# use separate provisioned databases/a suitable paid plan for production jobs.# The app does not need the Upstash Developer API key. Keep it out of runtime# environment variables; use it only from a restricted operator workflow.CORS_ORIGINS=["http://localhost:5173","http://localhost:3000","http://127.0.0.1:5173"]SMTP_TIMEOUT=10DNS_TIMEOUT=5MAX_BULK_EMAILS=10000RATE_LIMIT_PER_MINUTE=60USE_PROXIES=false# --- Mailbox verification provider (Layers 5 + 6) ---# Hugging Face Spaces blocks outbound port 25, so direct SMTP + catch-all# cannot run there. Set MV_API_KEY to delegate those layers to MillionVerifier.# auto (default): use the API when MV_API_KEY is set, else direct SMTP# api : force the verification API# local : force direct SMTP (requires port-25 egress)MAILBOX_PROVIDER=autoMV_API_KEY=MV_TIMEOUT=10# Circuit breaker for direct SMTP on a blocked host: after N consecutive# connection failures, fail fast for the cooldown instead of burning timeout# per address.SMTP_FAIL_THRESHOLD=3SMTP_COOLDOWN_SECONDS=300
12# Created by pytest automatically.
*1234Signature: 8a477f597d28d172789f06886806bc55# This file is a cache directory tag created by pytest.# For information about cache directory tags, see:# https://bford.info/cachedir/spec.html12345678# pytest cache directory #
This directory contains data from the pytest's cache plugin,
which provides the `--lf` and `--ff` options, as well as the `cache` fixture.
**Do not** commit this to version control.
See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information.123456{
"test_connections.py::test_supabase": true,
"test_connections.py::test_redis": true,
"test_connections.py::test_celery": true,
"test_connections.py::test_validation_engine": true
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263[
"test_connections.py::test_celery",
"test_connections.py::test_redis",
"test_connections.py::test_supabase",
"test_connections.py::test_validation_engine",
"tests/test_bulk_depth.py::BulkDepthTests::test_engine_deep_runs_catch_all_and_smtp",
"tests/test_bulk_depth.py::BulkDepthTests::test_injected_mailbox_provider_is_used_for_deep",
"tests/test_bulk_depth.py::BulkDepthTests::test_process_bulk_sync_runs_deep_layers",
"tests/test_bulk_depth.py::BulkRequestDeepFieldTests::test_bulk_request_accepts_deep_flag",
"tests/test_bulk_depth.py::BulkRequestDeepFieldTests::test_bulk_request_defaults_deep_true",
"tests/test_cache_config.py::RedisConfigurationTests::test_explicit_upstash_tls_url_is_used",
"tests/test_cache_config.py::RedisConfigurationTests::test_missing_redis_does_not_create_cloud_database",
"tests/test_dns_correctness.py::DNSCheckTests::test_a_record_fallback_is_preserved",
"tests/test_dns_correctness.py::DNSCheckTests::test_no_mx_or_address_is_distinct_from_transient_dns_error",
"tests/test_dns_correctness.py::DNSCheckTests::test_no_nameservers_is_reported_as_transient",
"tests/test_dns_correctness.py::DNSCheckTests::test_nxdomain_is_reported_as_definitive",
"tests/test_dns_correctness.py::DNSCheckTests::test_timeout_is_reported_as_transient",
"tests/test_engine_dns_failures.py::EngineDNSFailureTests::test_a_record_fallback_is_risky_even_if_smtp_accepts",
"tests/test_engine_dns_failures.py::EngineDNSFailureTests::test_domain_without_mail_routes_is_invalid",
"tests/test_engine_dns_failures.py::EngineDNSFailureTests::test_fast_mode_does_not_claim_mailbox_validity",
"tests/test_engine_dns_failures.py::EngineDNSFailureTests::test_logs_mask_local_part",
"tests/test_engine_dns_failures.py::EngineDNSFailureTests::test_status_thresholds_match_risk_score_bands",
"tests/test_engine_dns_failures.py::EngineDNSFailureTests::test_transient_dns_failure_is_risky_without_smtp",
"tests/test_engine_dns_failures.py::EngineDNSFailureTests::test_transient_dns_failure_is_unknown_without_smtp",
"tests/test_engine_metadata.py::CatchAllUnknownTests::test_catch_all_exception_is_unknown_not_false",
"tests/test_engine_metadata.py::CatchAllUnknownTests::test_catch_all_probe_unavailable_is_unknown_not_false",
"tests/test_engine_metadata.py::EngineMetadataTests::test_deep_result_emits_provenance_fields",
"tests/test_engine_metadata.py::EngineMetadataTests::test_fast_mode_checks_run_excludes_mailbox_layers",
"tests/test_engine_metadata.py::EngineMetadataTests::test_reason_code_catch_all",
"tests/test_engine_metadata.py::EngineMetadataTests::test_reason_code_dns_timeout",
"tests/test_engine_metadata.py::EngineMetadataTests::test_reason_code_nxdomain",
"tests/test_engine_metadata.py::EngineMetadataTests::test_reason_code_smtp_timeout",
"tests/test_engine_metadata.py::ScoreCoherenceTests::test_smtp_verified_can_reach_high_score",
"tests/test_engine_metadata.py::ScoreCoherenceTests::test_unverified_mailbox_never_scores_100",
"tests/test_mailbox_provider.py::CircuitBreakerTests::test_circuit_closes_after_cooldown",
"tests/test_mailbox_provider.py::CircuitBreakerTests::test_local_provider_opens_circuit_after_threshold",
"tests/test_mailbox_provider.py::CircuitBreakerTests::test_open_circuit_returns_immediately_unavailable",
"tests/test_mailbox_provider.py::CircuitBreakerTests::test_zero_cooldown_never_stays_open",
"tests/test_mailbox_provider.py::MapMVResultTests::test_catch_all_maps_to_inconclusive",
"tests/test_mailbox_provider.py::MapMVResultTests::test_error_maps_to_inconclusive_with_error",
"tests/test_mailbox_provider.py::MapMVResultTests::test_invalid_maps_to_rejected_5xx",
"tests/test_mailbox_provider.py::MapMVResultTests::test_ok_maps_to_verified",
"tests/test_mailbox_provider.py::MapMVResultTests::test_unknown_maps_to_inconclusive",
"tests/test_mailbox_provider.py::MillionVerifierProviderTests::test_catch_all_probe_gibberish_not_real_address",
"tests/test_mailbox_provider.py::MillionVerifierProviderTests::test_verify_calls_api_with_email_and_key",
"tests/test_mailbox_provider.py::ResolveProviderTests::test_api_forced",
"tests/test_mailbox_provider.py::ResolveProviderTests::test_auto_with_key_uses_api",
"tests/test_mailbox_provider.py::ResolveProviderTests::test_auto_without_key_uses_local",
"tests/test_mailbox_provider.py::ResolveProviderTests::test_local_forced",
"tests/test_mailbox_provider.py::ResolveProviderTests::test_provider_satisfies_protocol",
"tests/test_production_config.py::ProductionSettingsTests::test_development_keeps_demo_configuration_available",
"tests/test_production_config.py::ProductionSettingsTests::test_production_accepts_explicit_secure_configuration",
"tests/test_production_config.py::ProductionSettingsTests::test_production_rejects_demo_or_insecure_configuration",
"tests/test_scoring_claims.py::ScoringClaimTests::test_catch_all_never_receives_a_low_risk_score",
"tests/test_scoring_claims.py::ScoringClaimTests::test_disposable_domain_is_invalid",
"tests/test_scoring_claims.py::ScoringClaimTests::test_explicit_mailbox_unknown_is_a_zero_score_hard_failure",
"tests/test_scoring_claims.py::ScoringClaimTests::test_generic_smtp_550_does_not_claim_mailbox_is_nonexistent",
"tests/test_scoring_claims.py::ScoringClaimTests::test_inconclusive_smtp_is_medium_risk_not_an_implicit_pass",
"tests/test_scoring_claims.py::ScoringClaimTests::test_legacy_user_unknown_rejection_is_detected_without_enhanced_code",
"tests/test_scoring_claims.py::ScoringClaimTests::test_missing_mail_routes_is_a_zero_score_hard_failure",
"tests/test_scoring_claims.py::ScoringClaimTests::test_role_based_address_never_receives_a_low_risk_score",
"tests/test_scoring_claims.py::ScoringClaimTests::test_transient_dns_has_fixed_medium_risk_score_and_audit_code"
]12# Automatically created by ruff.*1Signature: 8a477f597d28d172789f06886806bc555 unmodified lines6789101112131415161718192021225 unmodified linesRUN apt-get update && apt-get install -y --no-install-recommends \curl \build-essential \redis-server \&& rm -rf /var/lib/apt/lists/*# Install Python dependenciesCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt# Copy app source + container entrypoint (local Redis sidecar, supervises worker)COPY app/ ./app/COPY entrypoint.py .EXPOSE 7860CMD ["python", "entrypoint.py"]5 unmodified lines678910111213141516171819205 unmodified linesRUN apt-get update && apt-get install -y --no-install-recommends \curl \build-essential \&& rm -rf /var/lib/apt/lists/*# Install Python dependenciesCOPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt# Copy app sourceCOPY app/ ./app/EXPOSE 7860CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
5 unmodified lines67891011124 unmodified lines171819205 unmodified linesRUN apt-get update && apt-get install -y --no-install-recommends \curl \build-essential \redis-server \&& rm -rf /var/lib/apt/lists/*# Install Python dependencies4 unmodified linesEXPOSE 7860CMD ["python", "entrypoint.py"]5 unmodified lines678910114 unmodified lines161718195 unmodified linesRUN apt-get update && apt-get install -y --no-install-recommends \curl \build-essential \&& rm -rf /var/lib/apt/lists/*# Install Python dependencies4 unmodified linesEXPOSE 7860CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
10 unmodified lines11121310 unmodified lines# BRIDGE Modul X — Email Validation API7-layer email validation engine powered by FastAPI.10 unmodified lines11121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727310 unmodified lines# BRIDGE Modul X — Email Validation API7-layer email validation engine powered by FastAPI.## Runtime configurationCopy `.env.example` to `.env` for local development and replace placeholdervalues locally. Redis is optional for the API cache: the application does notcreate or claim cloud databases automatically. If no Redis URL is configuredor Redis is unavailable, cache operations use the in-memory TTL fallback.For Upstash, use the database's TLS `rediss://` connection URL with databaseindex `/0`; do not disable certificate verification. The Upstash Developer APIkey manages resources and is not needed by the app runtime. Keep it out of`.env` files and deployment secrets unless an isolated operator tool explicitlyneeds it. Upstash Free's single-database limit does not imply Celery broker andresult-backend compatibility; verify key-prefix isolation and real workerround-trips before enabling production bulk jobs.`Dockerfile.hf` starts the FastAPI web process only. A Celery worker must bedeployed and supervised separately before asynchronous bulk processing isconsidered available. A Redis ping alone is not a worker readiness check.## Scoring contractScores use `0-39` for high risk/invalid, `40-74` for medium risk/risky, and`75-100` for low risk/valid. A transient DNS lookup returns a fixed score of`50` and `DNS_TRANSIENT_FAILURE: -50`; fast mode applies`FAST_MODE_SKIPPED_MAILBOX_CHECK: -30` and caps the result at `70`. Missing mailroutes, disposable domains, syntax failures, and a specific SMTP `550 5.1.1`mailbox-not-found response (or an explicit legacy `550 User Unknown` response)score `0`. Catch-all and role-based results are capped at `74`. A generic SMTP`550`, SMTP connection failure, or other inconclusive probe is not treated asproof that a mailbox does not exist; inconclusive SMTP is capped at `70`.## Production configuration gateSet `APP_ENVIRONMENT=production` in the live deployment. Startup then failsclosed unless `DEBUG=false`, `LICENSE_ENFORCEMENT=true`, Supabase URL andservice-role credentials are configured, and every `CORS_ORIGINS` entry is anHTTPS origin. Keep service-role credentials in the platform's secret store,never in source control or frontend variables. Keep development settings(`APP_ENVIRONMENT=development`, localhost CORS, demo licensing) local only.## Backend checksFrom this directory, install the development dependencies into the projectvirtual environment and run the test, lint, and compile checks:```powershell.\venv\Scripts\python.exe -m pip install -r requirements-dev.txt.\venv\Scripts\python.exe -m pytest --collect-only -q.\venv\Scripts\python.exe -m pytest -q.\venv\Scripts\python.exe -m ruff check app tests.\venv\Scripts\python.exe -m compileall -q app tests```Use the project virtual environment for these commands. Running tests with adifferent system Python can fail during collection even when the backenddependencies are installed in `venv`. `pytest.ini` limits collection to theunit-test directory so `test_connections.py` remains a manually invoked,environment-dependent integration diagnostic and does not contact liveservices during CI.
1234569 unmodified lines16171819202122232425262728293031323385 unmodified lines1191201211221231241258 unmodified lines134135136137138139140from fastapi import APIRouter, HTTPException, Request, Query, BackgroundTasksfrom fastapi.responses import JSONResponseimport json, timeimport asynciofrom ..models import (9 unmodified linesrouter = APIRouter()async def process_bulk_sync(emails: list, webhook_url: str = None) -> dict:"""Process bulk validation synchronously in chunks.Used when Celery is unavailable."""results = []total = len(emails)chunk_size = settings.bulk_sync_chunk_size # Configurable chunk sizefor i in range(0, total, chunk_size):chunk = emails[i:i + chunk_size]tasks = [engine.validate(email, deep=False) for email in chunk]chunk_results = await asyncio.gather(*tasks, return_exceptions=True)for email, result in zip(chunk, chunk_results):85 unmodified linesif use_celery:try:from ..tasks.celery_tasks import bulk_validate_tasktask = bulk_validate_task.delay(request.emails, request.webhook_url)# Record the job in Supabase so it can be tracked across restartsif settings.enable_db_persistence:repo.create_bulk_job(task.id, request.emails)8 unmodified lines# Synchronous fallback for any size list (removed ≤100 limit)print(f"[BULK] Processing {len(request.emails)} emails synchronously (Celery unavailable)")results = await process_bulk_sync(request.emails, request.webhook_url)if settings.enable_db_persistence:repo.finish_bulk_job("sync", results)12345679 unmodified lines1718192021222324252627282930313233343536373885 unmodified lines1241251261271281291308 unmodified lines139140141142143144145from fastapi import APIRouter, HTTPException, Queryfrom fastapi.responses import JSONResponseimport jsonimport timeimport asynciofrom ..models import (9 unmodified linesrouter = APIRouter()async def process_bulk_sync(emails: list, webhook_url: str = None, deep: bool = True) -> dict:"""Process bulk validation synchronously in chunks.Used when Celery is unavailable.`deep` defaults to True so bulk runs the full 7-layer pipeline (catch-all +SMTP) exactly like single verification — the product charges 1 credit/emailand must not silently degrade to a syntax+DNS-only check."""results = []total = len(emails)chunk_size = settings.bulk_sync_chunk_size # Configurable chunk sizefor i in range(0, total, chunk_size):chunk = emails[i:i + chunk_size]tasks = [engine.validate(email, deep=deep) for email in chunk]chunk_results = await asyncio.gather(*tasks, return_exceptions=True)for email, result in zip(chunk, chunk_results):85 unmodified linesif use_celery:try:from ..tasks.celery_tasks import bulk_validate_tasktask = bulk_validate_task.delay(request.emails, request.webhook_url, request.deep)# Record the job in Supabase so it can be tracked across restartsif settings.enable_db_persistence:repo.create_bulk_job(task.id, request.emails)8 unmodified lines# Synchronous fallback for any size list (removed ≤100 limit)print(f"[BULK] Processing {len(request.emails)} emails synchronously (Celery unavailable)")results = await process_bulk_sync(request.emails, request.webhook_url, deep=request.deep)if settings.enable_db_persistence:repo.finish_bulk_job("sync", results)
12345673 unmodified lines1112131415161718198 unmodified lines2829303132333435363738394041427 unmodified lines5051525354559 unmodified lines656667686970from pydantic_settings import BaseSettings, SettingsConfigDictfrom typing import Listclass Settings(BaseSettings):model_config = SettingsConfigDict(env_file=".env",3 unmodified lines)# Appapp_name: str = "BRIDGE Modul - X"app_version: str = "2.1.0"debug: bool = Truesecret_key: str = "change-me-in-production"# Server8 unmodified linesredis_url: str = "redis://localhost:6379/0"redis_cache_ttl: int = 86400 # 24 hours# Upstash Developer API (for provisioning/managing Redis databases)upstash_management_key: str = ""upstash_account_email: str = ""# CORScors_origins: List[str] = ["http://localhost:5173","http://localhost:3000","http://127.0.0.1:5173"]# Validation7 unmodified linesuse_proxies: bool = Falseproxy_list: List[str] = []# Celerycelery_broker_url: str = "redis://localhost:6379/1"celery_result_backend: str = "redis://localhost:6379/2"9 unmodified lines# on every paid API route. Anything else = open demo mode.license_enforcement: str = ""@propertydef supabase_configured(self) -> bool:return bool(self.supabase_url and self.supabase_service_role_key)1234567891011121314151617181920212223242526273 unmodified lines313233343536373839408 unmodified lines49505152535455565758597 unmodified lines67686970717273747576777879808182838485869 unmodified lines96979899100101102103104105106107108109110111112113114115116117118119120121122123124from urllib.parse import urlsplitfrom pydantic import model_validatorfrom pydantic_settings import BaseSettings, SettingsConfigDictfrom typing import Listdef _is_https_origin(value: str) -> bool:try:parsed = urlsplit(value)_ = parsed.portexcept ValueError:return Falsereturn (parsed.scheme == "https"and bool(parsed.hostname)and parsed.username is Noneand parsed.password is Noneand parsed.path in {"", "/"}and not parsed.queryand not parsed.fragment)class Settings(BaseSettings):model_config = SettingsConfigDict(env_file=".env",3 unmodified lines)# Appapp_environment: str = "development"app_name: str = "BRIDGE Modul - X"app_version: str = "2.2.0"debug: bool = Falsesecret_key: str = "change-me-in-production"# Server8 unmodified linesredis_url: str = "redis://localhost:6379/0"redis_cache_ttl: int = 86400 # 24 hours# CORScors_origins: List[str] = ["http://localhost:5173","http://localhost:3000","http://127.0.0.1:5173",]# Validation7 unmodified linesuse_proxies: bool = Falseproxy_list: List[str] = []# Mailbox verification provider (Layer 5 catch-all + Layer 6 SMTP).# On hosts that block outbound port 25 (Hugging Face Spaces, most cloud),# direct SMTP cannot run — so the mailbox verdict is delegated to a# third-party verification API instead. "auto" uses the API when an API key# is present, else falls back to direct SMTP. "local"/"api" force a provider.mailbox_provider: str = "auto" # auto | local | apimv_api_key: str = "" # MillionVerifier real-time API keymv_timeout: int = 10 # per-check provider timeout (seconds)# Circuit breaker: after this many consecutive direct-SMTP connection# failures (blocked egress), fail fast for `smtp_cooldown_seconds` instead# of burning the full timeout on every address.smtp_fail_threshold: int = 3smtp_cooldown_seconds: int = 300# Celerycelery_broker_url: str = "redis://localhost:6379/1"celery_result_backend: str = "redis://localhost:6379/2"9 unmodified lines# on every paid API route. Anything else = open demo mode.license_enforcement: str = ""@model_validator(mode="after")def validate_production_settings(self) -> "Settings":if self.app_environment.strip().casefold() != "production":return selfproblems = []if self.debug:problems.append("DEBUG must be false")if self.license_enforcement.strip().casefold() != "true":problems.append("LICENSE_ENFORCEMENT must be true")if not self.supabase_configured:problems.append("SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY are required")elif not _is_https_origin(self.supabase_url):problems.append("SUPABASE_URL must be an HTTPS URL")if not self.cors_origins or not all(_is_https_origin(origin) for origin in self.cors_origins):problems.append("CORS_ORIGINS must contain only HTTPS origins")if problems:raise ValueError("Unsafe production configuration: " + "; ".join(problems))return self@propertydef supabase_configured(self) -> bool:return bool(self.supabase_url and self.supabase_service_role_key)
29 unmodified lines3031323334353637383940414 unmodified lines4647484950515227 unmodified lines8081828384858 unmodified lines94959697989929 unmodified linesdomain_exists: boolhas_mx_records: boolmx_records: List[Dict[str, Any]] = []has_spf: bool = Falsespf_record: Optional[str] = Nonehas_dmarc: bool = Falsedmarc_record: Optional[str] = Nonehas_dkim: bool = Falseerror: Optional[str] = Noneclass DisposableResult(BaseModel):4 unmodified linesclass CatchAllResult(BaseModel):is_catch_all: boolconfidence: float = 0.0error: Optional[str] = None27 unmodified linesscoring: ScoringResultprocessing_time_ms: floatvalidated_at: strclass SingleEmailRequest(BaseModel):8 unmodified linesclass BulkEmailRequest(BaseModel):emails: List[str]webhook_url: Optional[str] = None@field_validator("emails")@classmethod29 unmodified lines30313233343536373839404142434 unmodified lines4849505152535455565727 unmodified lines85868788899091929394959697988 unmodified lines10710810911011111211311411511611729 unmodified linesdomain_exists: boolhas_mx_records: boolmx_records: List[Dict[str, Any]] = []a_fallback: bool = Falsehas_spf: bool = Falsespf_record: Optional[str] = Nonehas_dmarc: bool = Falsedmarc_record: Optional[str] = Nonehas_dkim: bool = Falseerror: Optional[str] = Noneerror_code: Optional[str] = Noneclass DisposableResult(BaseModel):4 unmodified linesclass CatchAllResult(BaseModel):# None = the catch-all probe could not run (e.g. port-25 egress blocked on# this host). It must NEVER be coerced to False, which would falsely claim# "domain rejects unknown recipients".is_catch_all: Optional[bool] = Noneconfidence: float = 0.0error: Optional[str] = None27 unmodified linesscoring: ScoringResultprocessing_time_ms: floatvalidated_at: str# Provenance the frontend contract expects (src/lib/verifier.ts classify()).# checks_run lists the 7-layer taxonomy keys that actually executed; an# unchecked layer must never read as a pass. reason_code is a machine cause# for Unknown/risky rows. run_id correlates a single + its bulk chunk.checks_run: List[str] = []reason_code: Optional[str] = Nonerun_id: Optional[str] = Nonevalidator_version: Optional[str] = Noneclass SingleEmailRequest(BaseModel):8 unmodified linesclass BulkEmailRequest(BaseModel):emails: List[str]webhook_url: Optional[str] = None# Product promise: bulk runs the SAME 7-layer pipeline as single (1 credit# per email). deep=False skips catch-all + SMTP, which collapsed every bulk# row to "Unknown / insufficient depth" — so it defaults to True and is only# flipped off by an explicit caller that accepts the reduced verdict.deep: bool = True@field_validator("emails")@classmethod
18 unmodified lines192021222324252627285 unmodified lines34353637383940414243444546474849505152536 unmodified lines606162636465661 unmodified line6869707172737418 unmodified linesworker_concurrency=10,task_soft_time_limit=300,task_time_limit=600,# Survive a broker that is still coming up (local sidecar cold start):# retry the connection at startup instead of exiting and crash-looping.broker_connection_max_retries=None,broker_connection_retry_on_startup=True,task_publish_retry=False,task_publish_retry_policy={"max_retries": 1},result_backend_transport_options={5 unmodified linestask_reject_on_worker_lost=True,)# Hosted Redis (Upstash) arrives over rediss:// — always verify the server# certificate. Explicit CERT_REQUIRED so Celery never silently downgrades.import ssl as _sslif settings.celery_broker_url.startswith("rediss"):celery_app.conf.broker_use_ssl = {"ssl_cert_reqs": _ssl.CERT_REQUIRED}if settings.celery_result_backend.startswith("rediss"):celery_app.conf.redis_backend_use_ssl = {"ssl_cert_reqs": _ssl.CERT_REQUIRED}@celery_app.task(bind=True, max_retries=3, rate_limit="100/m")def bulk_validate_task(self, emails: list, webhook_url: str = None):"""Celery task for async bulk email validation.Runs synchronously inside Celery worker."""from ..validator.engine import EmailValidationEnginefrom ..db import repo6 unmodified linesfor i, email in enumerate(emails):try:result = await eng.validate(email, deep=False)results.append(result.model_dump())# Update progressself.update_state(1 unmodified linemeta={"current": i + 1, "total": total})except Exception as e:print(f"[CELERY TASK] Error validating {email}: {str(e)}", file=sys.stderr)results.append({"email": email,"error": str(e),18 unmodified lines1920212223242526275 unmodified lines3334353637383940414243444546476 unmodified lines545556575859601 unmodified line626364656667686970717218 unmodified linesworker_concurrency=10,task_soft_time_limit=300,task_time_limit=600,# Fail fast when Redis/broker is down instead of retrying foreverbroker_connection_max_retries=2,broker_connection_retry_on_startup=False,task_publish_retry=False,task_publish_retry_policy={"max_retries": 1},result_backend_transport_options={5 unmodified linestask_reject_on_worker_lost=True,)@celery_app.task(bind=True, max_retries=3, rate_limit="100/m")def bulk_validate_task(self, emails: list, webhook_url: str = None, deep: bool = True):"""Celery task for async bulk email validation.Runs synchronously inside Celery worker.`deep` defaults to True: bulk must run the full 7-layer pipeline (catch-all+ SMTP) to produce a real verdict, matching single verification."""from ..validator.engine import EmailValidationEnginefrom ..db import repo6 unmodified linesfor i, email in enumerate(emails):try:result = await eng.validate(email, deep=deep)results.append(result.model_dump())# Update progressself.update_state(1 unmodified linemeta={"current": i + 1, "total": total})except Exception as e:print(f"[CELERY TASK] Validation failed for item {i + 1}/{total}: "f"{e.__class__.__name__}",file=sys.stderr,)results.append({"email": email,"error": str(e),
11 unmodified lines1213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596011 unmodified lines_HAS_REDIS = False_redis_client: Optional[object] = None_free_tier_provisioned: Optional[str] = None # db id if we self-provisioned# In-memory TTL fallback cache: {key: (value, expires_at)}_memory_cache: dict = {}async def provision_free_tier() -> Optional[str]:"""Create a free-tier Upstash database when no REDIS_URL is configured.Returns the connection string on success, or None on failure.Free databases last 3 days unless claimed at the returned console URL.Idempotent: caches the db id so repeated calls re-fetch, not duplicate."""global _free_tier_provisionedtry:from .upstash_free import create_databasedb = create_database(db_id=_free_tier_provisioned or "")_free_tier_provisioned = db.db_idprint(f"[REDIS] Free-tier database provisioned: {db.endpoint} "f"(expires {db.expires})")print(f"[REDIS] Claim it at: {db.console_url}")return db.connection_string(0)except Exception as e:print(f"[REDIS] Free-tier provisioning failed: {e}")return Noneasync def get_redis():"""Lazily create a shared Redis client (returns None if unavailable).If REDIS_URL is set, uses it. Otherwise attempts to self-provision afree-tier Upstash database (no account/key required)."""global _redis_clientif not _HAS_REDIS:return Noneif _redis_client is None:url = settings.redis_urlif not url or "localhost" in url:url = await provision_free_tier()if not url:return Nonetry:11 unmodified lines121314151617181920212223242526272829303132333411 unmodified lines_HAS_REDIS = False_redis_client: Optional[object] = None# In-memory TTL fallback cache: {key: (value, expires_at)}_memory_cache: dict = {}async def get_redis():"""Lazily create a shared Redis client (returns None if unavailable).Redis connections must be configured explicitly. Missing or unreachableRedis leaves the API on its bounded in-memory cache instead of silentlyprovisioning a temporary external database."""global _redis_clientif not _HAS_REDIS:return Noneif _redis_client is None:url = (settings.redis_url or "").strip()if not url:return Nonetry:
4 unmodified lines5678910114 unmodified linesthis module provides a thin convenience wrapper plus a cached in-memorycache so repeated probes of the same domain are avoided."""from typing import Tupleimport asynciofrom ..models import CatchAllResultfrom .smtp_verify import smtp_verifier4 unmodified lines56789104 unmodified linesthis module provides a thin convenience wrapper plus a cached in-memorycache so repeated probes of the same domain are avoided."""import asynciofrom ..models import CatchAllResultfrom .smtp_verify import smtp_verifier
18 unmodified lines1920212223248 unmodified lines33343536373839404142434445464748495051525354555657585960616245 unmodified lines10810911011111211318 unmodified linesmx_records = []domain_exists = Falsehas_mx = Falsetry:mx_answers = await resolver.resolve(domain, 'MX')8 unmodified linesreturn DNSResult(domain_exists=False,has_mx_records=False,error="Domain does not exist (NXDOMAIN)")except dns.resolver.NoAnswer:# No MX -> try A/AAAA fallback per RFCtry:await resolver.resolve(domain, 'A')domain_exists = Trueexcept Exception:try:await resolver.resolve(domain, 'AAAA')domain_exists = Trueexcept Exception:passexcept dns.exception.Timeout:return DNSResult(domain_exists=False,has_mx_records=False,error="DNS timeout")except Exception as e:return DNSResult(domain_exists=False,has_mx_records=False,error=str(e))# ---- SPF Record ---------------------------------------------------45 unmodified linesdomain_exists=domain_exists,has_mx_records=has_mx,mx_records=mx_records,has_spf=has_spf,spf_record=spf_record,has_dmarc=has_dmarc,18 unmodified lines192021222324258 unmodified lines34353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910045 unmodified lines14614714814915015115218 unmodified linesmx_records = []domain_exists = Falsehas_mx = Falsea_fallback = Falsetry:mx_answers = await resolver.resolve(domain, 'MX')8 unmodified linesreturn DNSResult(domain_exists=False,has_mx_records=False,error="Domain does not exist (NXDOMAIN)",error_code="nxdomain",)except dns.resolver.NoAnswer:# No MX -> try A/AAAA fallback per RFCtry:for record_type in ('A', 'AAAA'):try:await resolver.resolve(domain, record_type)domain_exists = Truea_fallback = Truemx_records.append({"host": domain, "priority": 0})breakexcept dns.resolver.NoAnswer:continueexcept dns.resolver.NXDOMAIN:return DNSResult(domain_exists=False,has_mx_records=False,error="Domain does not exist (NXDOMAIN)",error_code="nxdomain",)except dns.exception.Timeout:return DNSResult(domain_exists=False,has_mx_records=False,error="DNS address lookup timed out",error_code="timeout",)except dns.exception.DNSException as e:return DNSResult(domain_exists=False,has_mx_records=False,error=f"DNS address lookup failed: {e.__class__.__name__}",error_code="resolver_error",)if not domain_exists:# An MX NODATA response confirms the owner name exists, even when# it has no address record to which SMTP can be routed.domain_exists = Trueexcept dns.exception.Timeout:return DNSResult(domain_exists=False,has_mx_records=False,error="DNS timeout",error_code="timeout",)except dns.exception.DNSException as e:return DNSResult(domain_exists=False,has_mx_records=False,error=f"DNS lookup failed: {e.__class__.__name__}",error_code="resolver_error",)if not has_mx and not a_fallback:return DNSResult(domain_exists=True,has_mx_records=False,error="Domain has no MX, A, or AAAA records",error_code="no_mail_records",)# ---- SPF Record ---------------------------------------------------45 unmodified linesdomain_exists=domain_exists,has_mx_records=has_mx,mx_records=mx_records,a_fallback=a_fallback,has_spf=has_spf,spf_record=spf_record,has_dmarc=has_dmarc,
12345678910111213141516171819202122235 unmodified lines293031323334353637383940414243449 unmodified lines545556575859602 unmodified lines636465666768694 unmodified lines747576777879802 unmodified lines838485868788893 unmodified lines9394959697989910010110210310410510610710810911011111211311411511611711811910 unmodified lines1301311321331341351361375 unmodified lines143144145146147148149150151152153154155156157158import asyncioimport timefrom datetime import datetime, timezonefrom typing import Optionalimport structlogfrom ..models import (ValidationResult, ValidationStatus,ScoringResult, RiskLevel, CatchAllResult, SMTPResult)from ..config import settingsfrom .syntax import validate_syntaxfrom .dns_check import check_dnsfrom .disposable import check_disposablefrom .smtp_verify import smtp_verifierfrom .scoring import calculate_scorelogger = structlog.get_logger()class EmailValidationEngine:"""Master 7-Layer Email Validation Orchestrator.5 unmodified lines4. Disposable / Role-based / Free provider detection5. Catch-all domain detection6. SMTP mailbox verification7. AI/Heuristic deliverability scoring"""def __init__(self):self.use_proxies = settings.use_proxiesasync def validate(self, email: str, deep: bool = True) -> ValidationResult:start_time = time.monotonic()log = logger.bind(email=email)log.info("validation_started")# ---- Layer 1: Syntax -----------------------------------------9 unmodified linessyntax=syntax,scoring=scoring,processing_time_ms=round(elapsed, 2),validated_at=datetime.now(timezone.utc).isoformat())domain = syntax.domain2 unmodified lines# ---- Layers 2 & 3: DNS + MX ---------------------------------dns_result = await check_dns(domain, settings.dns_timeout)if not dns_result.domain_exists or not dns_result.has_mx_records:elapsed = (time.monotonic() - start_time) * 1000scoring = calculate_score(syntax, dns_result, None, None, None)log.warning("dns_failed", domain=domain)4 unmodified linesdns=dns_result,scoring=scoring,processing_time_ms=round(elapsed, 2),validated_at=datetime.now(timezone.utc).isoformat())# ---- Layer 4: Disposable Detection ---------------------------2 unmodified linesif not deep:# Fast path: skip SMTP for quick validationelapsed = (time.monotonic() - start_time) * 1000scoring = calculate_score(syntax, dns_result, disposable, None, None)status = self._determine_status(scoring)return ValidationResult(email=normalized_email,3 unmodified linesdisposable=disposable,scoring=scoring,processing_time_ms=round(elapsed, 2),validated_at=datetime.now(timezone.utc).isoformat())# ---- Layers 5 & 6: Catch-All + SMTP --------------------------mx_host = dns_result.mx_records[0]["host"]# Run catch-all and SMTP in parallel for speedcatch_all_task = asyncio.create_task(smtp_verifier.check_catch_all(domain, mx_host))smtp_task = asyncio.create_task(smtp_verifier.verify(normalized_email, mx_host, self.use_proxies))catch_all_raw, smtp_result = await asyncio.gather(catch_all_task, smtp_task, return_exceptions=True)# Handle catch-all resultif isinstance(catch_all_raw, Exception):catch_all = CatchAllResult(is_catch_all=False, error=str(catch_all_raw))else:is_catch_all, confidence = catch_all_rawcatch_all = CatchAllResult(is_catch_all=is_catch_all, confidence=confidence)10 unmodified linesstatus = self._determine_status(scoring)elapsed = (time.monotonic() - start_time) * 1000log.info("validation_complete", status=status, score=scoring.score,time_ms=round(elapsed, 2))return ValidationResult(email=normalized_email,5 unmodified linessmtp=smtp_result,scoring=scoring,processing_time_ms=round(elapsed, 2),validated_at=datetime.now(timezone.utc).isoformat())def _determine_status(self, scoring: ScoringResult) -> ValidationStatus:if scoring.score >= 75:return ValidationStatus.VALIDelif scoring.score >= 45:return ValidationStatus.RISKYelif scoring.score > 0:return ValidationStatus.UNKNOWNelse:return ValidationStatus.INVALID1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081095 unmodified lines1151161171181191201211221231241251261271281291301311321331341359 unmodified lines1451461471481491501511521531541552 unmodified lines1581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871884 unmodified lines1931941951961971981992002012022032042052 unmodified lines2082092102112122132142152162172182192202213 unmodified lines22522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026110 unmodified lines2722732742752762772782792802812822835 unmodified lines289290291292293294295296297298299300301302303304305306307308import asyncioimport reimport timeimport uuidfrom datetime import datetime, timezoneimport structlogfrom ..models import (ValidationResult,ValidationStatus,ScoringResult,CatchAllResult,DNSResult,DisposableResult,SMTPResult,SyntaxResult,)from ..config import settingsfrom .syntax import validate_syntaxfrom .dns_check import check_dnsfrom .disposable import check_disposablefrom .mailbox_provider import MailboxProvider, resolve_providerfrom .scoring import calculate_scorelogger = structlog.get_logger()def _mask_email_for_log(email: str) -> str:local_part, separator, domain = email.rpartition("@")if not separator or not domain:return "[invalid-email]"return f"{local_part[:1]}***@{domain}"def _build_checks_run(syntax: SyntaxResult | None,dns: DNSResult | None,disposable: DisposableResult | None,catch_all: CatchAllResult | None,smtp: SMTPResult | None,scoring: ScoringResult | None,) -> list[str]:"""Which of the 7-layer taxonomy keys actually executed for this result.Mirrors the frontend fallback in src/lib/verifier.ts classify() so a layerthe engine did not run is never reported as a pass. DNS without an errorclaims both `dns` and `mx`; a DNS error claims only `dns`."""checks: list[str] = []if syntax is not None:checks.append("syntax")if dns is not None:if dns.error:checks.append("dns")else:checks.extend(["dns", "mx"])if disposable is not None:checks.append("disposable")if catch_all is not None:checks.append("catch_all")if smtp is not None:checks.append("smtp")if scoring is not None:checks.append("scoring")return checksdef _build_reason_code(dns: DNSResult | None,disposable: DisposableResult | None,catch_all: CatchAllResult | None,smtp: SMTPResult | None,*,early: str | None = None,) -> str | None:"""Machine cause for the verdict. Ordered most-specific/actionable first.disposable outranks everything (frontend classifies it as Disposable);a catch-all or a dead-A-only route outranks a raw SMTP code so the reasonmatches the Unknown verdict the frontend assigns for those rows."""if early:return earlyif disposable is not None and disposable.is_disposable:return "disposable"if dns is not None and dns.a_fallback and not dns.has_mx_records:return "a_fallback_only"if catch_all is not None and catch_all.is_catch_all:return "catch_all_detected"if smtp is not None:if smtp.verified is False and smtp.smtp_code:if smtp.smtp_code >= 500:return "rcpt_5xx"if smtp.smtp_code >= 400:return "rcpt_4xx"if smtp.smtp_code >= 200:return "rcpt_2xx"if smtp.verified is None and smtp.error:return ("smtp_timeout"if re.search(r"timed?\s*out", smtp.error, re.IGNORECASE)else "smtp_unavailable")return Noneclass EmailValidationEngine:"""Master 7-Layer Email Validation Orchestrator.5 unmodified lines4. Disposable / Role-based / Free provider detection5. Catch-all domain detection6. SMTP mailbox verification7. Deterministic heuristic deliverability scoring"""def __init__(self, mailbox: MailboxProvider | None = None):self.use_proxies = settings.use_proxies# Layers 5 (catch-all) and 6 (SMTP) run through a mailbox provider. On# hosts that block port 25 (HF Spaces), this resolves to the verification# API; elsewhere it is direct SMTP. Injectable for tests.self.mailbox = mailbox if mailbox is not None else resolve_provider()async def validate(self, email: str, deep: bool = True) -> ValidationResult:start_time = time.monotonic()run_id = uuid.uuid4().hex[:12]log = logger.bind(email=_mask_email_for_log(email), run_id=run_id)log.info("validation_started")# ---- Layer 1: Syntax -----------------------------------------9 unmodified linessyntax=syntax,scoring=scoring,processing_time_ms=round(elapsed, 2),validated_at=datetime.now(timezone.utc).isoformat(),checks_run=_build_checks_run(syntax, None, None, None, None, scoring),reason_code=_build_reason_code(None, None, None, None),run_id=run_id,validator_version=settings.app_version,)domain = syntax.domain2 unmodified lines# ---- Layers 2 & 3: DNS + MX ---------------------------------dns_result = await check_dns(domain, settings.dns_timeout)if dns_result.error_code in {"timeout", "resolver_error"}:elapsed = (time.monotonic() - start_time) * 1000scoring = calculate_score(syntax, dns_result, None, None, None)log.warning("dns_inconclusive", domain=domain, error_code=dns_result.error_code)return ValidationResult(email=normalized_email,status=self._determine_status(scoring),syntax=syntax,dns=dns_result,scoring=scoring,processing_time_ms=round(elapsed, 2),validated_at=datetime.now(timezone.utc).isoformat(),checks_run=_build_checks_run(syntax, dns_result, None, None, None, scoring),reason_code=_build_reason_code(dns_result, None, None, None, early="dns_timeout"),run_id=run_id,validator_version=settings.app_version,)if (not dns_result.domain_existsor dns_result.error_code == "nxdomain"or (not dns_result.has_mx_records and not dns_result.a_fallback)):elapsed = (time.monotonic() - start_time) * 1000scoring = calculate_score(syntax, dns_result, None, None, None)log.warning("dns_failed", domain=domain)4 unmodified linesdns=dns_result,scoring=scoring,processing_time_ms=round(elapsed, 2),validated_at=datetime.now(timezone.utc).isoformat(),checks_run=_build_checks_run(syntax, dns_result, None, None, None, scoring),reason_code=_build_reason_code(dns_result, None, None, None, early="nxdomain"),run_id=run_id,validator_version=settings.app_version,)# ---- Layer 4: Disposable Detection ---------------------------2 unmodified linesif not deep:# Fast path: skip SMTP for quick validationelapsed = (time.monotonic() - start_time) * 1000scoring = calculate_score(syntax,dns_result,disposable,None,None,mailbox_verification_skipped=True,)status = self._determine_status(scoring)return ValidationResult(email=normalized_email,3 unmodified linesdisposable=disposable,scoring=scoring,processing_time_ms=round(elapsed, 2),validated_at=datetime.now(timezone.utc).isoformat(),checks_run=_build_checks_run(syntax, dns_result, disposable, None, None, scoring),reason_code=_build_reason_code(dns_result, disposable, None, None),run_id=run_id,validator_version=settings.app_version,)# ---- Layers 5 & 6: Catch-All + SMTP --------------------------mx_host = dns_result.mx_records[0]["host"]# Run catch-all and SMTP in parallel for speed, via the mailbox# provider (direct SMTP or the verification API, per configuration).catch_all_task = asyncio.create_task(self.mailbox.catch_all(domain, mx_host))smtp_task = asyncio.create_task(self.mailbox.verify(normalized_email, mx_host))catch_all_raw, smtp_result = await asyncio.gather(catch_all_task, smtp_task, return_exceptions=True)# Handle catch-all result. An exception means the probe could not run# (e.g. port-25 egress blocked) — that is UNKNOWN, not "not catch-all".if isinstance(catch_all_raw, Exception):catch_all = CatchAllResult(is_catch_all=None, confidence=0.0, error=str(catch_all_raw))else:is_catch_all, confidence = catch_all_rawcatch_all = CatchAllResult(is_catch_all=is_catch_all, confidence=confidence)10 unmodified linesstatus = self._determine_status(scoring)elapsed = (time.monotonic() - start_time) * 1000log.info("validation_complete",status=status,score=scoring.score,time_ms=round(elapsed, 2),)return ValidationResult(email=normalized_email,5 unmodified linessmtp=smtp_result,scoring=scoring,processing_time_ms=round(elapsed, 2),validated_at=datetime.now(timezone.utc).isoformat(),checks_run=_build_checks_run(syntax, dns_result, disposable, catch_all, smtp_result, scoring),reason_code=_build_reason_code(dns_result, disposable, catch_all, smtp_result),run_id=run_id,validator_version=settings.app_version,)def _determine_status(self, scoring: ScoringResult) -> ValidationStatus:if scoring.score >= 75:return ValidationStatus.VALIDelif scoring.score >= 40:return ValidationStatus.RISKYelse:return ValidationStatus.INVALID
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196"""Mailbox verification providers (Layer 5 catch-all + Layer 6 SMTP).
Direct SMTP to the recipient MX on port 25 is the classic mailbox probe, butmost cloud hosts — Hugging Face Spaces included — block outbound port 25. Whendirect SMTP cannot run, the mailbox verdict is delegated to a third-partyverification API (MillionVerifier) whose status strings map 1:1 onto thisproduct's taxonomy.
resolve_provider() picks the provider from settings: mailbox_provider = "auto" → API when mv_api_key is set, else local SMTP mailbox_provider = "api" → force the verification API mailbox_provider = "local" → force direct SMTP
The circuit breaker on LocalSmtpProvider stops a blocked host from burning thefull SMTP timeout on every address in a bulk job: after `fail_threshold`consecutive connection failures it fails fast for `cooldown_seconds`."""from __future__ import annotations
import asyncioimport randomimport timefrom typing import Optional, Tuple
import httpx
from ..config import settingsfrom ..models import CatchAllResult, SMTPResultfrom .smtp_verify import GIBBERISH_LOCAL, smtp_verifier
def map_mv_result(payload: dict) -> SMTPResult: """Map one MillionVerifier real-time response into our SMTPResult contract.
Live schema (verified 2026-10-11 against API_KEY_FOR_TEST): {"result": "ok"|"catch_all"|"invalid"|"disposable"|"unknown"|"error", "quality": "good"|"risky"|"bad", "resultcode": <int>, "free": bool, "role": bool, "error": str} """ result = (payload.get("result") or "").lower() error = payload.get("error") or ""
if result == "ok": return SMTPResult(verified=True, smtp_code=250, smtp_message="provider: ok") if result == "invalid": # A provider-confirmed dead mailbox is a permanent (5xx-class) reject. return SMTPResult( verified=False, smtp_code=550, smtp_message=error or "provider: invalid" ) if result in {"catch_all", "unknown", "disposable"}: # None of these proves the specific mailbox exists. catch_all accepts # everything; unknown is the provider's own inconclusive bucket. return SMTPResult( verified=None, error=f"provider: {result}" + (f" ({error})" if error else "") ) # "error" or anything unexpected → inconclusive, surfaced as an error. return SMTPResult(verified=None, error=f"provider: {result or 'error'} {error}".strip())
class MailboxProvider: """Common interface every mailbox provider implements."""
name = "base"
async def verify(self, email: str, mx_host: str) -> SMTPResult: raise NotImplementedError
async def catch_all(self, domain: str, mx_host: str) -> Tuple[Optional[bool], float]: raise NotImplementedError
class MillionVerifierProvider(MailboxProvider): name = "millionverifier"
def __init__(self, api_key: Optional[str] = None, timeout: Optional[int] = None): self.api_key = api_key if api_key is not None else settings.mv_api_key self.timeout = timeout if timeout is not None else settings.mv_timeout self.endpoint = "https://api.millionverifier.com/api/v3/"
async def _call(self, email: str) -> dict: async with httpx.AsyncClient(timeout=self.timeout + 5) as client: resp = await client.get( self.endpoint, params={"api": self.api_key, "email": email, "timeout": self.timeout}, ) resp.raise_for_status() return resp.json()
async def verify(self, email: str, mx_host: str) -> SMTPResult: try: payload = await self._call(email) except Exception as exc: # network / HTTP failure → inconclusive return SMTPResult(verified=None, error=f"provider unavailable: {exc}") return map_mv_result(payload)
async def catch_all(self, domain: str, mx_host: str) -> Tuple[Optional[bool], float]: # Domain property: probe a high-entropy gibberish local part. A 250 on # gibberish ⇒ catch-all; a reject ⇒ not. The real address must never be # used here (it would always "accept", a false negative). gibberish = f"{GIBBERISH_LOCAL}{random.getrandbits(32):08x}@{domain}" try: payload = await self._call(gibberish) except Exception: return None, 0.0 result = (payload.get("result") or "").lower() if result == "catch_all": return True, 0.95 if result == "invalid": return False, 0.9 # "ok" on gibberish would itself indicate catch-all; unknown/error → None if result == "ok": return True, 0.8 return None, 0.0
class LocalSmtpProvider(MailboxProvider): """Direct port-25 SMTP with a circuit breaker for blocked egress."""
name = "local"
def __init__( self, fail_threshold: Optional[int] = None, cooldown_seconds: Optional[int] = None, ): self.fail_threshold = ( fail_threshold if fail_threshold is not None else settings.smtp_fail_threshold ) self.cooldown = ( cooldown_seconds if cooldown_seconds is not None else settings.smtp_cooldown_seconds ) self._consecutive_failures = 0 self._open_until = 0.0
@property def circuit_open(self) -> bool: return time.monotonic() < self._open_until
def circuit_open_after_cooldown(self) -> bool: """True only while still within the cooldown window (0s ⇒ closed).""" return time.monotonic() < self._open_until
def record_failure(self) -> None: self._consecutive_failures += 1 if self._consecutive_failures >= self.fail_threshold: self._open_until = time.monotonic() + self.cooldown
def record_success(self) -> None: self._consecutive_failures = 0 self._open_until = 0.0
async def verify(self, email: str, mx_host: str) -> SMTPResult: if self.circuit_open: return SMTPResult( verified=None, error="SMTP unavailable (egress circuit open)" ) result = await smtp_verifier.verify(email, mx_host, settings.use_proxies) # A connection-class failure (timeout/refused/unreachable) counts toward # opening the circuit; a real SMTP dialogue does not. if result.verified is None and result.error and any( k in result.error.lower() for k in ("timeout", "timed out", "refused", "unreachable", "unavailable") ): self.record_failure() elif result.smtp_code is not None or result.verified is not None: self.record_success() return result
async def catch_all(self, domain: str, mx_host: str) -> Tuple[Optional[bool], float]: if self.circuit_open: return None, 0.0 try: is_catch_all, confidence = await smtp_verifier.check_catch_all(domain, mx_host) except Exception: return None, 0.0 # check_catch_all returns (False, 0.0) when the probe is inconclusive — # that means UNKNOWN, not "not catch-all". Confidence 0.0 is the signal. if confidence == 0.0: self.record_failure() return None, 0.0 self.record_success() return is_catch_all, confidence
def resolve_provider() -> MailboxProvider: mode = (settings.mailbox_provider or "auto").strip().lower() if mode == "api": return MillionVerifierProvider() if mode == "local": return LocalSmtpProvider() # auto if settings.mv_api_key: return MillionVerifierProvider() return LocalSmtpProvider()12345678910111213141516171819202122232425262728293031323334353637383940414215 unmodified lines585960616263646566676869707172737475767778794 unmodified lines84858687888990919293949596979899100101102103104105106107108109110111112113from typing import Optionalfrom ..models import (SyntaxResult, DNSResult, DisposableResult,CatchAllResult, SMTPResult, ScoringResult, RiskLevel)def calculate_score(syntax: SyntaxResult,dns: Optional[DNSResult],disposable: Optional[DisposableResult],catch_all: Optional[CatchAllResult],smtp: Optional[SMTPResult]) -> ScoringResult:"""Layer 7: Comprehensive deliverability scoring.Score: 0-100 (higher = better deliverability)"""score = 100breakdown = {}warnings = []# ---- Syntax (hard fail → score 0) --------------------------------if not syntax.passed:breakdown["syntax"] = -100score -= 100else:breakdown["syntax"] = 0# ---- Domain/MX (hard fail → near zero) ------------------------------if dns:if not dns.domain_exists:breakdown["domain"] = -75score -= 75warnings.append("Domain does not exist")elif not dns.has_mx_records:breakdown["mx_records"] = -70score -= 70warnings.append("No MX records found — domain cannot receive email")else:breakdown["domain"] = 0breakdown["mx_records"] = 015 unmodified linesbreakdown["dkim"] = 2score += 2# ---- Disposable (-40) --------------------------------------------if disposable:if disposable.is_disposable:breakdown["disposable"] = -40score -= 40warnings.append("Disposable/temporary email domain detected")elif disposable.is_role_based:breakdown["role_based"] = -10score -= 10warnings.append("Role-based email (admin@, info@, etc.) — low engagement risk")elif disposable.is_free_provider:breakdown["free_provider"] = -5score -= 5# ---- Catch-All (-20) ---------------------------------------------if catch_all and catch_all.is_catch_all:breakdown["catch_all"] = -20score -= 20warnings.append("Catch-all domain — cannot verify specific mailbox")4 unmodified linesbreakdown["smtp"] = 10score += 10elif smtp.verified is False:breakdown["smtp"] = -30score -= 30warnings.append(f"Mailbox does not exist (SMTP {smtp.smtp_code})")else:# Unknown / blockedbreakdown["smtp"] = -5score -= 5if smtp.error:warnings.append(f"SMTP check inconclusive: {smtp.error}")# Clamp score between 0 and 100score = max(0, min(100, score))# Determine risk levelif score >= 75:risk = RiskLevel.LOWelif score >= 45:risk = RiskLevel.MEDIUMelse:risk = RiskLevel.HIGHreturn ScoringResult(score=score,risk_level=risk,breakdown=breakdown,warnings=warnings)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838415 unmodified lines1001011021031041051061071081091101111121131141151161171181191201211221231241254 unmodified lines130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180import refrom typing import Optionalfrom ..models import (SyntaxResult,DNSResult,DisposableResult,CatchAllResult,SMTPResult,ScoringResult,RiskLevel,)def _is_explicit_mailbox_rejection(smtp: SMTPResult) -> bool:if smtp.smtp_code != 550 or not smtp.smtp_message:return Falsemessage = smtp.smtp_message.casefold()enhanced_status = re.search(r"(?<![\d.])5\.1\.1(?![\d.])", message)mailbox_rejection_phrases = ("user unknown","no such user","mailbox does not exist","mailbox not found","recipient does not exist","recipient not found","account does not exist",)return bool(enhanced_status) or any(phrase in message for phrase in mailbox_rejection_phrases)def calculate_score(syntax: SyntaxResult,dns: Optional[DNSResult],disposable: Optional[DisposableResult],catch_all: Optional[CatchAllResult],smtp: Optional[SMTPResult],*,mailbox_verification_skipped: bool = False,) -> ScoringResult:"""Layer 7: Comprehensive deliverability scoring.Score: 0-100 (higher = better deliverability)"""score = 100risk_cap = 100breakdown = {}warnings = []# ---- Syntax (hard fail → score 0) --------------------------------if not syntax.passed:breakdown["SYNTAX_INVALID"] = -100warnings.append("Email syntax is invalid")return _scoring_result(0, breakdown, warnings)breakdown["syntax"] = 0# ---- Domain/MX -------------------------------------------------------if dns:if dns.error_code in {"timeout", "resolver_error"}:breakdown["DNS_TRANSIENT_FAILURE"] = -50warnings.append("DNS lookup was inconclusive")return _scoring_result(50, breakdown, warnings)elif not dns.domain_exists:breakdown["DNS_MX_MISSING"] = -100warnings.append("Domain does not exist")return _scoring_result(0, breakdown, warnings)elif dns.error_code == "nxdomain" or (not dns.has_mx_records and not dns.a_fallback):breakdown["DNS_MX_MISSING"] = -100warnings.append("Domain has no valid mail route")return _scoring_result(0, breakdown, warnings)elif dns.a_fallback:risk_cap = min(risk_cap, 74)breakdown["mx_records"] = -45score -= 45warnings.append("No MX records — using A/AAAA fallback; mailbox result is limited")else:breakdown["domain"] = 0breakdown["mx_records"] = 015 unmodified linesbreakdown["dkim"] = 2score += 2# ---- Disposable ---------------------------------------------------if disposable:if disposable.is_disposable:breakdown["DISPOSABLE_DOMAIN"] = -100warnings.append("Disposable/temporary email domain detected")return _scoring_result(0, breakdown, warnings)elif disposable.is_role_based:risk_cap = min(risk_cap, 74)breakdown["role_based"] = -10score -= 10warnings.append("Role-based email (admin@, info@, etc.) — low engagement risk")elif disposable.is_free_provider:breakdown["free_provider"] = -5score -= 5# ---- Catch-All (-20) ---------------------------------------------if catch_all and catch_all.is_catch_all:risk_cap = min(risk_cap, 74)breakdown["catch_all"] = -20score -= 20warnings.append("Catch-all domain — cannot verify specific mailbox")4 unmodified linesbreakdown["smtp"] = 10score += 10elif smtp.verified is False:if _is_explicit_mailbox_rejection(smtp):breakdown["SMTP_MAILBOX_NOT_FOUND"] = -100warnings.append("SMTP explicitly reported the mailbox as not found")return _scoring_result(0, breakdown, warnings)breakdown["smtp"] = -30score -= 30warnings.append(f"SMTP rejected the recipient (code {smtp.smtp_code}); ""provider policy may make the result inconclusive")else:risk_cap = min(risk_cap, 70)breakdown["SMTP_CHECK_INCONCLUSIVE"] = -30score -= 30if smtp.error:warnings.append(f"SMTP check inconclusive: {smtp.error}")if mailbox_verification_skipped:risk_cap = min(risk_cap, 70)breakdown["FAST_MODE_SKIPPED_MAILBOX_CHECK"] = -30score -= 30warnings.append("Mailbox verification was not performed")# Clamp score between 0 and 100score = max(0, min(100, score))if score > risk_cap:breakdown["RISK_CONTEXT_CAP"] = risk_cap - scorescore = risk_capreturn _scoring_result(score, breakdown, warnings)def _scoring_result(score: int,breakdown: dict[str, int],warnings: list[str],) -> ScoringResult:# Determine risk levelif score >= 75:risk = RiskLevel.LOWelif score >= 40:risk = RiskLevel.MEDIUMelse:risk = RiskLevel.HIGHreturn ScoringResult(score=score, risk_level=risk, breakdown=breakdown, warnings=warnings)
2 unmodified lines34567892 unmodified linesimport smtplibimport socksimport randomfrom typing import Optional, Tuplefrom ..models import SMTPResultfrom ..config import settingsfrom .proxy_engine import proxy_pool2 unmodified lines34567892 unmodified linesimport smtplibimport socksimport randomfrom typing import Tuplefrom ..models import SMTPResultfrom ..config import settingsfrom .proxy_engine import proxy_pool
123[pytest]
testpaths = tests
python_files = test_*.py1234-r requirements.txt
pytest>=8.3
ruff>=0.11.01234target-version = "py311"
[lint]
select = ["E4", "E7", "E9", "F"]5 unmodified lines678910111 unmodified line13141516171851 unmodified lines7071727374757636 unmodified lines11311411511611711811912013 unmodified lines13413513613713813914014127 unmodified lines1691701711721731741755 unmodified linesimport asyncioimport sysimport os# Add backend to pathsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))1 unmodified linefrom app.config import settingsasync def test_supabase():"""Test Supabase connectivity and schema."""print("\n" + "=" * 60)51 unmodified linesif "YOUR_UPSTASH_PASSWORD" in settings.redis_url or "YOUR_ENDPOINT" in settings.redis_url:print("[FAIL] Redis URL not configured (still using placeholder values)")print(f" Current: {settings.redis_url}")return Falsetry:36 unmodified linesreturn Trueexcept Exception as e:print(f"[FAIL] Redis: Connection failed - {e}")print(f" URL: {settings.redis_url}")print(" → Check: Password, Endpoint, TLS (rediss://), IP Allowlist (0.0.0.0/0)")return False13 unmodified linesfrom app.tasks.celery_tasks import celery_app# Check configurationprint(f"Broker: {celery_app.conf.broker_url}")print(f"Backend: {celery_app.conf.result_backend}")# Test connection by inspectinginsp = celery_app.control.inspect()27 unmodified lines# Quick validation (no SMTP)result = await engine.validate("test@example.com", deep=False)print(f"[PASS] Validation: {result.email} → {result.status.value} (score: {result.scoring.score})")print(f" Layers: Syntax={result.syntax.passed}, DNS={result.dns.domain_exists}, MX={result.dns.has_mx_records}")return True5 unmodified lines67891011121 unmodified line141516171819202122232425262751 unmodified lines79808182838436 unmodified lines12112212312412512612712813 unmodified lines14214314414514614714814927 unmodified lines1771781791801811821835 unmodified linesimport asyncioimport sysimport osfrom urllib.parse import urlsplit# Add backend to pathsys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))1 unmodified linefrom app.config import settingsdef endpoint_label(url: str) -> str:parsed = urlsplit(url)if not parsed.hostname:return "not configured"database = parsed.path.strip("/") or "default"return f"{parsed.scheme}://{parsed.hostname}/db-{database}"async def test_supabase():"""Test Supabase connectivity and schema."""print("\n" + "=" * 60)51 unmodified linesif "YOUR_UPSTASH_PASSWORD" in settings.redis_url or "YOUR_ENDPOINT" in settings.redis_url:print("[FAIL] Redis URL not configured (still using placeholder values)")return Falsetry:36 unmodified linesreturn Trueexcept Exception as e:print(f"[FAIL] Redis: Connection failed - {e.__class__.__name__}")print(f" Endpoint: {endpoint_label(settings.redis_url)}")print(" → Check: Password, Endpoint, TLS (rediss://), IP Allowlist (0.0.0.0/0)")return False13 unmodified linesfrom app.tasks.celery_tasks import celery_app# Check configurationprint(f"Broker: {endpoint_label(celery_app.conf.broker_url)}")print(f"Backend: {endpoint_label(celery_app.conf.result_backend)}")# Test connection by inspectinginsp = celery_app.control.inspect()27 unmodified lines# Quick validation (no SMTP)result = await engine.validate("test@example.com", deep=False)print(f"[PASS] Validation: {result.status.value} (score: {result.scoring.score})")print(f" Layers: Syntax={result.syntax.passed}, DNS={result.dns.domain_exists}, MX={result.dns.has_mx_records}")return True
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132import unittestfrom unittest.mock import AsyncMock, patch
from app.models import ( CatchAllResult, DNSResult, DisposableResult, SMTPResult, SyntaxResult,)from app.api.routes import process_bulk_syncfrom app.validator.engine import EmailValidationEngine
def _syntax(**kw): base = dict( passed=True, normalized_email="person@example.test", domain="example.test", local_part="person", ) base.update(kw) return SyntaxResult(**base)
def _dns(**kw): base = dict( domain_exists=True, has_mx_records=True, mx_records=[{"host": "mx.example.test", "priority": 10}], ) base.update(kw) return DNSResult(**base)
class BulkDepthTests(unittest.IsolatedAsyncioTestCase): """RC1: the bulk path hard-coded deep=False, skipping catch-all + SMTP, so every bulk row collapsed to Unknown/risky/insufficient_depth in the UI. Bulk must run the same deep pipeline as single verification."""
async def test_process_bulk_sync_runs_deep_layers(self): captured = []
async def fake_validate(email, deep=True): captured.append(deep) from app.models import ValidationStatus, ScoringResult, RiskLevel
return type("R", (), {"model_dump": lambda self: {"email": email}})()
with ( patch("app.api.routes.engine.validate", new=AsyncMock(side_effect=lambda e, deep=True: fake_validate(e, deep))), patch("app.api.routes.settings.bulk_sync_chunk_size", 50), ): # patch engine.validate directly to capture the deep flag async def capture_validate(email, deep=True): captured.append(deep)
class FakeResult: def model_dump(self): return {"email": email}
return FakeResult()
with patch("app.api.routes.engine") as eng: eng.validate = AsyncMock(side_effect=capture_validate) await process_bulk_sync(["a@example.com", "b@example.com"])
self.assertTrue(len(captured) >= 1) self.assertTrue(all(d is True for d in captured), f"bulk ran with deep flags: {captured}")
async def test_engine_deep_runs_catch_all_and_smtp(self): engine = EmailValidationEngine() with ( patch("app.validator.engine.validate_syntax", return_value=_syntax()), patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())), patch("app.validator.engine.check_disposable", return_value=DisposableResult( is_disposable=False, is_free_provider=False, is_role_based=False )), patch( "app.validator.engine.resolve_provider", return_value=None, ), ): pass # covered by mailbox-injected tests below
async def test_injected_mailbox_provider_is_used_for_deep(self): """The engine must call the injected provider's catch_all + verify.""" calls = {"verify": 0, "catch_all": 0}
class FakeProvider: async def verify(self, email, mx_host): calls["verify"] += 1 return SMTPResult(verified=True, smtp_code=250)
async def catch_all(self, domain, mx_host): calls["catch_all"] += 1 return (False, 0.9)
engine = EmailValidationEngine(mailbox=FakeProvider()) with ( patch("app.validator.engine.validate_syntax", return_value=_syntax()), patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())), patch("app.validator.engine.check_disposable", return_value=DisposableResult( is_disposable=False, is_free_provider=False, is_role_based=False )), ): result = await engine.validate("person@example.test", deep=True)
self.assertEqual(calls["verify"], 1) self.assertEqual(calls["catch_all"], 1) self.assertTrue(result.smtp.verified) self.assertIn("smtp", result.checks_run) self.assertIn("catch_all", result.checks_run)
class BulkRequestDeepFieldTests(unittest.TestCase): def test_bulk_request_accepts_deep_flag(self): from app.models import BulkEmailRequest
req = BulkEmailRequest(emails=["a@example.com"], deep=True) self.assertTrue(req.deep)
def test_bulk_request_defaults_deep_true(self): # Product promise: bulk runs the full 7-layer pipeline (1 credit/email). from app.models import BulkEmailRequest
req = BulkEmailRequest(emails=["a@example.com"]) self.assertTrue(req.deep)
if __name__ == "__main__": unittest.main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import unittest
from unittest.mock import AsyncMock, patch
from app.utils import cache
class RedisConfigurationTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.previous_url = cache.settings.redis_url
cache._redis_client = None
async def asyncTearDown(self):
cache.settings.redis_url = self.previous_url
cache._redis_client = None
async def test_missing_redis_does_not_create_cloud_database(self):
cache.settings.redis_url = ""
with (
patch("app.utils.cache._HAS_REDIS", True),
patch("app.utils.cache.aioredis.from_url") as from_url,
patch(
"app.utils.cache.provision_free_tier",
new=AsyncMock(return_value=None),
create=True,
) as provision,
):
result = await cache.get_redis()
self.assertIsNone(result)
from_url.assert_not_called()
provision.assert_not_awaited()
async def test_explicit_upstash_tls_url_is_used(self):
url = "rediss://default:placeholder@redis.example.test:6379/0"
cache.settings.redis_url = url
client = type("RedisClient", (), {"ping": AsyncMock(return_value=True)})()
with (
patch("app.utils.cache._HAS_REDIS", True),
patch("app.utils.cache.aioredis.from_url", return_value=client) as from_url,
):
result = await cache.get_redis()
self.assertIs(result, client)
from_url.assert_called_once()
self.assertEqual(from_url.call_args.args[0], url)
if __name__ == "__main__":
unittest.main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495import unittest
from unittest.mock import patch
import dns.exception
import dns.resolver
from app.validator.dns_check import check_dns
class ResolverStub:
timeout = 0
lifetime = 0
def __init__(self, responses):
self.responses = responses
async def resolve(self, name, record_type):
response = self.responses.get((name, record_type))
if isinstance(response, Exception):
raise response
if response is None:
raise dns.resolver.NoAnswer()
return response
class DNSCheckTests(unittest.IsolatedAsyncioTestCase):
async def test_timeout_is_reported_as_transient(self):
resolver = ResolverStub({("example.test", "MX"): dns.exception.Timeout()})
with patch(
"app.validator.dns_check.dns.asyncresolver.Resolver", return_value=resolver
):
result = await check_dns("example.test")
self.assertEqual(result.error_code, "timeout")
self.assertFalse(result.domain_exists)
async def test_no_nameservers_is_reported_as_transient(self):
resolver = ResolverStub(
{("unavailable.test", "MX"): dns.resolver.NoNameservers()}
)
with patch(
"app.validator.dns_check.dns.asyncresolver.Resolver", return_value=resolver
):
result = await check_dns("unavailable.test")
self.assertEqual(result.error_code, "resolver_error")
async def test_nxdomain_is_reported_as_definitive(self):
resolver = ResolverStub({("missing.test", "MX"): dns.resolver.NXDOMAIN()})
with patch(
"app.validator.dns_check.dns.asyncresolver.Resolver", return_value=resolver
):
result = await check_dns("missing.test")
self.assertEqual(result.error_code, "nxdomain")
self.assertFalse(result.domain_exists)
async def test_a_record_fallback_is_preserved(self):
resolver = ResolverStub(
{
("mail.example.test", "MX"): dns.resolver.NoAnswer(),
("mail.example.test", "A"): ["192.0.2.10"],
}
)
with patch(
"app.validator.dns_check.dns.asyncresolver.Resolver", return_value=resolver
):
result = await check_dns("mail.example.test")
self.assertTrue(result.domain_exists)
self.assertFalse(result.has_mx_records)
self.assertTrue(result.a_fallback)
self.assertEqual(result.mx_records[0]["host"], "mail.example.test")
async def test_no_mx_or_address_is_distinct_from_transient_dns_error(self):
resolver = ResolverStub(
{
("no-mail.example.test", "MX"): dns.resolver.NoAnswer(),
("no-mail.example.test", "A"): dns.resolver.NoAnswer(),
("no-mail.example.test", "AAAA"): dns.resolver.NoAnswer(),
}
)
with patch(
"app.validator.dns_check.dns.asyncresolver.Resolver", return_value=resolver
):
result = await check_dns("no-mail.example.test")
self.assertEqual(result.error_code, "no_mail_records")
self.assertTrue(result.domain_exists)
self.assertFalse(result.has_mx_records)
self.assertFalse(result.a_fallback)
if __name__ == "__main__":
unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185import unittest
from unittest.mock import AsyncMock, patch
from app.models import (
DNSResult,
DisposableResult,
RiskLevel,
ScoringResult,
SMTPResult,
SyntaxResult,
ValidationStatus,
)
from app.validator.engine import EmailValidationEngine, _mask_email_for_log
class EngineDNSFailureTests(unittest.IsolatedAsyncioTestCase):
def test_status_thresholds_match_risk_score_bands(self):
engine = EmailValidationEngine()
self.assertEqual(
engine._determine_status(
ScoringResult(score=40, risk_level=RiskLevel.MEDIUM)
),
ValidationStatus.RISKY,
)
self.assertEqual(
engine._determine_status(
ScoringResult(score=39, risk_level=RiskLevel.HIGH)
),
ValidationStatus.INVALID,
)
def test_logs_mask_local_part(self):
self.assertEqual(
_mask_email_for_log("person@example.test"), "p***@example.test"
)
self.assertEqual(_mask_email_for_log("not-an-address"), "[invalid-email]")
async def test_transient_dns_failure_is_risky_without_smtp(self):
dns_result = DNSResult(
domain_exists=False,
has_mx_records=False,
error="DNS timeout",
error_code="timeout",
)
engine = EmailValidationEngine()
with (
patch(
"app.validator.engine.validate_syntax",
return_value=SyntaxResult(
passed=True,
normalized_email="person@example.test",
domain="example.test",
local_part="person",
),
),
patch(
"app.validator.engine.check_dns", new=AsyncMock(return_value=dns_result)
),
patch.object(engine, "use_proxies", False),
patch(
"app.validator.mailbox_provider.smtp_verifier.verify", new=AsyncMock()
) as smtp_verify,
):
result = await engine.validate("person@example.test", deep=True)
self.assertEqual(result.status, ValidationStatus.RISKY)
self.assertEqual(result.dns.error_code, "timeout")
self.assertEqual(result.scoring.score, 50)
self.assertEqual(result.scoring.risk_level.value, "medium")
self.assertEqual(result.scoring.breakdown["DNS_TRANSIENT_FAILURE"], -50)
smtp_verify.assert_not_awaited()
async def test_a_record_fallback_is_risky_even_if_smtp_accepts(self):
dns_result = DNSResult(
domain_exists=True,
has_mx_records=False,
mx_records=[{"host": "example.test", "priority": 0}],
a_fallback=True,
)
engine = EmailValidationEngine()
with (
patch(
"app.validator.engine.validate_syntax",
return_value=SyntaxResult(
passed=True,
normalized_email="person@example.test",
domain="example.test",
local_part="person",
),
),
patch(
"app.validator.engine.check_dns", new=AsyncMock(return_value=dns_result)
),
patch("app.validator.engine.check_disposable", return_value=None),
patch(
"app.validator.mailbox_provider.smtp_verifier.verify",
new=AsyncMock(return_value=SMTPResult(verified=True)),
),
patch(
"app.validator.mailbox_provider.smtp_verifier.check_catch_all",
new=AsyncMock(return_value=(False, 0.9)),
),
):
result = await engine.validate("person@example.test", deep=True)
self.assertEqual(result.status, ValidationStatus.RISKY)
self.assertTrue(result.dns.a_fallback)
async def test_fast_mode_does_not_claim_mailbox_validity(self):
engine = EmailValidationEngine()
with (
patch(
"app.validator.engine.validate_syntax",
return_value=SyntaxResult(
passed=True,
normalized_email="person@example.test",
domain="example.test",
local_part="person",
),
),
patch(
"app.validator.engine.check_dns",
new=AsyncMock(
return_value=DNSResult(
domain_exists=True,
has_mx_records=True,
mx_records=[{"host": "mx.example.test", "priority": 10}],
)
),
),
patch(
"app.validator.engine.check_disposable",
return_value=DisposableResult(
is_disposable=False,
is_free_provider=False,
is_role_based=False,
),
),
):
result = await engine.validate("person@example.test", deep=False)
self.assertEqual(result.status, ValidationStatus.RISKY)
self.assertIsNone(result.smtp)
self.assertEqual(result.scoring.score, 70)
self.assertEqual(result.scoring.risk_level.value, "medium")
self.assertEqual(
result.scoring.breakdown["FAST_MODE_SKIPPED_MAILBOX_CHECK"], -30
)
self.assertIn("Mailbox verification was not performed", result.scoring.warnings)
async def test_domain_without_mail_routes_is_invalid(self):
dns_result = DNSResult(
domain_exists=True,
has_mx_records=False,
error="Domain has no MX, A, or AAAA records",
error_code="no_mail_records",
)
engine = EmailValidationEngine()
with (
patch(
"app.validator.engine.validate_syntax",
return_value=SyntaxResult(
passed=True,
normalized_email="person@example.test",
domain="example.test",
local_part="person",
),
),
patch(
"app.validator.engine.check_dns", new=AsyncMock(return_value=dns_result)
),
patch(
"app.validator.mailbox_provider.smtp_verifier.verify", new=AsyncMock()
) as smtp_verify,
):
result = await engine.validate("person@example.test", deep=True)
self.assertEqual(result.status, ValidationStatus.INVALID)
self.assertEqual(result.scoring.score, 0)
smtp_verify.assert_not_awaited()
if __name__ == "__main__":
unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318import unittestfrom unittest.mock import AsyncMock, patch
from app.models import ( CatchAllResult, DNSResult, DisposableResult, ScoringResult, SMTPResult, SyntaxResult, ValidationStatus,)from app.config import settingsfrom app.validator.engine import EmailValidationEngine
def _syntax(**kw): base = dict( passed=True, normalized_email="person@example.test", domain="example.test", local_part="person", ) base.update(kw) return SyntaxResult(**base)
def _dns(**kw): base = dict( domain_exists=True, has_mx_records=True, mx_records=[{"host": "mx.example.test", "priority": 10}], ) base.update(kw) return DNSResult(**base)
def _disposable(**kw): base = dict(is_disposable=False, is_free_provider=False, is_role_based=False) base.update(kw) return DisposableResult(**base)
class EngineMetadataTests(unittest.IsolatedAsyncioTestCase): """The engine must emit the provenance fields the frontend contract expects: checks_run, reason_code, validator_version, run_id (RC5)."""
async def test_deep_result_emits_provenance_fields(self): engine = EmailValidationEngine() with ( patch("app.validator.engine.validate_syntax", return_value=_syntax()), patch( "app.validator.engine.check_dns", new=AsyncMock(return_value=_dns()), ), patch( "app.validator.engine.check_disposable", return_value=_disposable(), ), patch( "app.validator.mailbox_provider.smtp_verifier.verify", new=AsyncMock(return_value=SMTPResult(verified=True, smtp_code=250)), ), patch( "app.validator.mailbox_provider.smtp_verifier.check_catch_all", new=AsyncMock(return_value=(False, 0.9)), ), ): result = await engine.validate("person@example.test", deep=True)
# Provenance: which layers ran, engine version, a correlation id. self.assertEqual( result.checks_run, ["syntax", "dns", "mx", "disposable", "catch_all", "smtp", "scoring"], ) self.assertEqual(result.validator_version, settings.app_version) self.assertTrue(result.run_id) self.assertGreater(len(result.run_id), 5)
async def test_fast_mode_checks_run_excludes_mailbox_layers(self): engine = EmailValidationEngine() with ( patch("app.validator.engine.validate_syntax", return_value=_syntax()), patch( "app.validator.engine.check_dns", new=AsyncMock(return_value=_dns()), ), patch( "app.validator.engine.check_disposable", return_value=_disposable(), ), ): result = await engine.validate("person@example.test", deep=False)
# deep=False never runs catch_all/smtp, so those layers must be absent. self.assertEqual( result.checks_run, ["syntax", "dns", "mx", "disposable", "scoring"] ) self.assertIsNone(result.smtp) self.assertIsNone(result.catch_all)
async def test_reason_code_dns_timeout(self): engine = EmailValidationEngine() with ( patch("app.validator.engine.validate_syntax", return_value=_syntax()), patch( "app.validator.engine.check_dns", new=AsyncMock( return_value=_dns( domain_exists=False, has_mx_records=False, error="DNS timeout", error_code="timeout", ) ), ), ): result = await engine.validate("person@example.test", deep=True)
self.assertEqual(result.reason_code, "dns_timeout")
async def test_reason_code_nxdomain(self): engine = EmailValidationEngine() with ( patch("app.validator.engine.validate_syntax", return_value=_syntax()), patch( "app.validator.engine.check_dns", new=AsyncMock( return_value=_dns( domain_exists=False, has_mx_records=False, error="Domain not found", error_code="nxdomain", ) ), ), ): result = await engine.validate("person@example.test", deep=True)
self.assertEqual(result.reason_code, "nxdomain")
async def test_reason_code_catch_all(self): engine = EmailValidationEngine() with ( patch("app.validator.engine.validate_syntax", return_value=_syntax()), patch( "app.validator.engine.check_dns", new=AsyncMock(return_value=_dns()), ), patch( "app.validator.engine.check_disposable", return_value=_disposable(), ), patch( "app.validator.mailbox_provider.smtp_verifier.verify", new=AsyncMock(return_value=SMTPResult(verified=True, smtp_code=250)), ), patch( "app.validator.mailbox_provider.smtp_verifier.check_catch_all", new=AsyncMock(return_value=(True, 0.95)), ), ): result = await engine.validate("person@example.test", deep=True)
self.assertEqual(result.reason_code, "catch_all_detected") self.assertEqual(result.status, ValidationStatus.RISKY)
async def test_reason_code_smtp_timeout(self): engine = EmailValidationEngine() with ( patch("app.validator.engine.validate_syntax", return_value=_syntax()), patch( "app.validator.engine.check_dns", new=AsyncMock(return_value=_dns()), ), patch( "app.validator.engine.check_disposable", return_value=_disposable(), ), patch( "app.validator.mailbox_provider.smtp_verifier.verify", new=AsyncMock( return_value=SMTPResult(verified=None, error="SMTP verification timed out") ), ), patch( "app.validator.mailbox_provider.smtp_verifier.check_catch_all", new=AsyncMock(return_value=(None, 0.0)), ), ): result = await engine.validate("person@example.test", deep=True)
self.assertEqual(result.reason_code, "smtp_timeout")
class CatchAllUnknownTests(unittest.IsolatedAsyncioTestCase): """An unreachable catch-all probe must read as UNKNOWN (None), never as False ("domain rejects unknown recipients"). RC6."""
async def test_catch_all_probe_unavailable_is_unknown_not_false(self): engine = EmailValidationEngine() with ( patch("app.validator.engine.validate_syntax", return_value=_syntax()), patch( "app.validator.engine.check_dns", new=AsyncMock(return_value=_dns()), ), patch( "app.validator.engine.check_disposable", return_value=_disposable(), ), patch( "app.validator.mailbox_provider.smtp_verifier.verify", new=AsyncMock( return_value=SMTPResult(verified=None, error="SMTP verification timed out") ), ), # Probe returned "unknown" (None, 0.0) — the blocked-host case. patch( "app.validator.mailbox_provider.smtp_verifier.check_catch_all", new=AsyncMock(return_value=(None, 0.0)), ), ): result = await engine.validate("person@example.test", deep=True)
self.assertIsNone(result.catch_all.is_catch_all) self.assertEqual(result.catch_all.confidence, 0.0)
async def test_catch_all_exception_is_unknown_not_false(self): engine = EmailValidationEngine() with ( patch("app.validator.engine.validate_syntax", return_value=_syntax()), patch( "app.validator.engine.check_dns", new=AsyncMock(return_value=_dns()), ), patch( "app.validator.engine.check_disposable", return_value=_disposable(), ), patch( "app.validator.mailbox_provider.smtp_verifier.verify", new=AsyncMock(return_value=SMTPResult(verified=True, smtp_code=250)), ), patch( "app.validator.mailbox_provider.smtp_verifier.check_catch_all", new=AsyncMock(side_effect=RuntimeError("port 25 unreachable")), ), ): result = await engine.validate("person@example.test", deep=True)
self.assertIsNone(result.catch_all.is_catch_all)
class ScoreCoherenceTests(unittest.IsolatedAsyncioTestCase): """A perfect score (100/low) must only appear when a mailbox verdict exists. Unverified-but-plausible rows are capped and marked medium. RC4."""
async def test_smtp_verified_can_reach_high_score(self): engine = EmailValidationEngine() with ( patch("app.validator.engine.validate_syntax", return_value=_syntax()), patch( "app.validator.engine.check_dns", new=AsyncMock(return_value=_dns()), ), patch( "app.validator.engine.check_disposable", return_value=_disposable(is_free_provider=False), ), patch( "app.validator.mailbox_provider.smtp_verifier.verify", new=AsyncMock(return_value=SMTPResult(verified=True, smtp_code=250)), ), patch( "app.validator.mailbox_provider.smtp_verifier.check_catch_all", new=AsyncMock(return_value=(False, 0.9)), ), ): result = await engine.validate("person@example.test", deep=True)
# Definitive mailbox acceptance + clean domain → low risk, high score. self.assertGreaterEqual(result.scoring.score, 75) self.assertEqual(result.scoring.risk_level.value, "low") self.assertEqual(result.status, ValidationStatus.VALID)
async def test_unverified_mailbox_never_scores_100(self): engine = EmailValidationEngine() with ( patch("app.validator.engine.validate_syntax", return_value=_syntax()), patch( "app.validator.engine.check_dns", new=AsyncMock(return_value=_dns()), ), patch( "app.validator.engine.check_disposable", return_value=_disposable(), ), patch( "app.validator.mailbox_provider.smtp_verifier.verify", new=AsyncMock( return_value=SMTPResult(verified=None, error="SMTP verification timed out") ), ), patch( "app.validator.mailbox_provider.smtp_verifier.check_catch_all", new=AsyncMock(return_value=(None, 0.0)), ), ): result = await engine.validate("person@example.test", deep=True)
# Inconclusive SMTP caps the score below "low risk" territory. self.assertLess(result.scoring.score, 75) self.assertNotEqual(result.scoring.risk_level.value, "low")
if __name__ == "__main__": unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151import unittestfrom unittest.mock import AsyncMock, patch
from app.config import settingsfrom app.models import SMTPResultfrom app.validator.mailbox_provider import ( MailboxProvider, MillionVerifierProvider, LocalSmtpProvider, resolve_provider, map_mv_result,)
class MapMVResultTests(unittest.TestCase): """MillionVerifier live schema (verified 2026-10-11 against API_KEY_FOR_TEST): {"result": "ok"|"catch_all"|"invalid"|"disposable"|"unknown"|"error", "quality": "good"|"risky"|"bad", "resultcode": 1..4, "free": bool, "role": bool} The mapping must translate that into our SMTPResult taxonomy."""
def test_ok_maps_to_verified(self): r = map_mv_result({"result": "ok", "quality": "good", "resultcode": 1, "free": False, "role": False}) self.assertTrue(r.verified)
def test_invalid_maps_to_rejected_5xx(self): r = map_mv_result({"result": "invalid", "quality": "bad", "resultcode": 4, "free": False, "role": False}) self.assertFalse(r.verified) self.assertEqual(r.smtp_code, 550)
def test_catch_all_maps_to_inconclusive(self): # A catch-all domain accepts the probe but proves nothing about the # specific mailbox — it must NOT read as verified. r = map_mv_result({"result": "catch_all", "quality": "risky", "resultcode": 2, "free": False, "role": False}) self.assertIsNone(r.verified)
def test_unknown_maps_to_inconclusive(self): r = map_mv_result({"result": "unknown", "quality": "risky", "resultcode": 5, "free": False, "role": False}) self.assertIsNone(r.verified)
def test_error_maps_to_inconclusive_with_error(self): r = map_mv_result({"result": "error", "error": "rate limited"}) self.assertIsNone(r.verified) self.assertIn("rate limited", r.error)
class MillionVerifierProviderTests(unittest.IsolatedAsyncioTestCase): async def test_verify_calls_api_with_email_and_key(self): provider = MillionVerifierProvider(api_key="test-key", timeout=5) fake = {"result": "ok", "quality": "good", "resultcode": 1, "free": False, "role": False} with patch("app.validator.mailbox_provider.httpx.AsyncClient") as client_cls: resp = AsyncMock() resp.raise_for_status = lambda: None resp.json = lambda: fake client_cls.return_value.__aenter__ = AsyncMock(return_value=AsyncMock(get=AsyncMock(return_value=resp))) client_cls.return_value.__aexit__ = AsyncMock(return_value=False) result = await provider.verify("a@example.com", "mx.example.com") self.assertTrue(result.verified)
async def test_catch_all_probe_gibberish_not_real_address(self): # catch-all must be detected with a gibberish local part, never the # real address (that would be a false negative). provider = MillionVerifierProvider(api_key="test-key", timeout=5) captured = {}
with patch("app.validator.mailbox_provider.httpx.AsyncClient") as client_cls: async def fake_get(url, params=None, timeout=None): captured["params"] = params resp = AsyncMock() resp.raise_for_status = lambda: None resp.json = lambda: {"result": "catch_all", "quality": "risky", "resultcode": 2} return resp client_cls.return_value.__aenter__ = AsyncMock(return_value=AsyncMock(get=fake_get)) client_cls.return_value.__aexit__ = AsyncMock(return_value=False) is_catch_all, confidence = await provider.catch_all("example.com", "mx.example.com")
self.assertNotIn("example.com", captured["params"]["email"].split("@")[0]) self.assertTrue(is_catch_all) self.assertGreater(confidence, 0.5)
class ResolveProviderTests(unittest.TestCase): def test_api_forced(self): with patch.object(settings, "mailbox_provider", "api"), patch.object( settings, "mv_api_key", "k" ): self.assertIsInstance(resolve_provider(), MillionVerifierProvider)
def test_local_forced(self): with patch.object(settings, "mailbox_provider", "local"): self.assertIsInstance(resolve_provider(), LocalSmtpProvider)
def test_auto_with_key_uses_api(self): with patch.object(settings, "mailbox_provider", "auto"), patch.object( settings, "mv_api_key", "k" ): self.assertIsInstance(resolve_provider(), MillionVerifierProvider)
def test_auto_without_key_uses_local(self): with patch.object(settings, "mailbox_provider", "auto"), patch.object( settings, "mv_api_key", "" ): self.assertIsInstance(resolve_provider(), LocalSmtpProvider)
def test_provider_satisfies_protocol(self): # Structural check: both providers expose verify + catch_all. self.assertTrue(hasattr(MillionVerifierProvider, "verify")) self.assertTrue(hasattr(MillionVerifierProvider, "catch_all")) self.assertTrue(hasattr(LocalSmtpProvider, "verify")) self.assertTrue(hasattr(LocalSmtpProvider, "catch_all"))
class CircuitBreakerTests(unittest.TestCase): """Blocked egress must fail fast instead of burning smtp_timeout per row."""
def test_local_provider_opens_circuit_after_threshold(self): p = LocalSmtpProvider(fail_threshold=2, cooldown_seconds=60) p.record_failure() self.assertFalse(p.circuit_open) p.record_failure() self.assertTrue(p.circuit_open)
def test_open_circuit_returns_immediately_unavailable(self): import asyncio
p = LocalSmtpProvider(fail_threshold=1, cooldown_seconds=60) p.record_failure() result = asyncio.run(p.verify("a@example.com", "mx.example.com")) self.assertIsNone(result.verified) self.assertIn("unavailable", (result.error or "").lower())
def test_circuit_closes_after_cooldown(self): import time as _t
p = LocalSmtpProvider(fail_threshold=1, cooldown_seconds=60) p.record_failure() self.assertTrue(p.circuit_open) # Simulate the cooldown elapsing: the open-window is now in the past. p._open_until = _t.monotonic() - 1 self.assertFalse(p.circuit_open) self.assertFalse(p.circuit_open_after_cooldown())
def test_zero_cooldown_never_stays_open(self): # cooldown_seconds=0 opens and closes in the same instant — there is no # window, so it must not read as open on the next call. p = LocalSmtpProvider(fail_threshold=1, cooldown_seconds=0) p.record_failure() self.assertFalse(p.circuit_open)
if __name__ == "__main__": unittest.main()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import unittest
from pydantic import ValidationError
from app.config import Settings
class ProductionSettingsTests(unittest.TestCase):
def test_production_accepts_explicit_secure_configuration(self):
settings = Settings(
_env_file=None,
app_environment="production",
debug=False,
license_enforcement="true",
supabase_url="https://project.example",
supabase_service_role_key="server-only-key",
cors_origins=["https://app.example.com"],
)
self.assertEqual(settings.app_environment, "production")
def test_production_rejects_demo_or_insecure_configuration(self):
with self.assertRaisesRegex(
ValidationError,
"DEBUG must be false.*LICENSE_ENFORCEMENT must be true.*"
"SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY are required.*"
"CORS_ORIGINS must contain only HTTPS origins",
):
Settings(
_env_file=None,
app_environment="production",
debug=True,
license_enforcement="false",
cors_origins=["http://localhost:5173"],
)
def test_development_keeps_demo_configuration_available(self):
settings = Settings(
_env_file=None,
app_environment="development",
license_enforcement="false",
cors_origins=["http://localhost:5173"],
)
self.assertEqual(settings.license_enforcement, "false")
if __name__ == "__main__":
unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162import unittest
from app.models import (
CatchAllResult,
DNSResult,
DisposableResult,
SMTPResult,
SyntaxResult,
)
from app.validator.scoring import calculate_score
class ScoringClaimTests(unittest.TestCase):
def test_transient_dns_has_fixed_medium_risk_score_and_audit_code(self):
result = calculate_score(
SyntaxResult(passed=True),
DNSResult(
domain_exists=False,
has_mx_records=False,
error_code="timeout",
),
None,
None,
None,
)
self.assertEqual(result.score, 50)
self.assertEqual(result.risk_level.value, "medium")
self.assertEqual(result.breakdown["DNS_TRANSIENT_FAILURE"], -50)
def test_missing_mail_routes_is_a_zero_score_hard_failure(self):
result = calculate_score(
SyntaxResult(passed=True),
DNSResult(
domain_exists=True,
has_mx_records=False,
error_code="no_mail_records",
),
None,
None,
None,
)
self.assertEqual(result.score, 0)
self.assertEqual(result.risk_level.value, "high")
self.assertEqual(result.breakdown["DNS_MX_MISSING"], -100)
def test_explicit_mailbox_unknown_is_a_zero_score_hard_failure(self):
result = calculate_score(
SyntaxResult(passed=True),
DNSResult(domain_exists=True, has_mx_records=True),
None,
None,
SMTPResult(
verified=False,
smtp_code=550,
smtp_message="550 5.1.1 The recipient does not exist",
),
)
self.assertEqual(result.score, 0)
self.assertEqual(result.risk_level.value, "high")
self.assertEqual(result.breakdown["SMTP_MAILBOX_NOT_FOUND"], -100)
def test_legacy_user_unknown_rejection_is_detected_without_enhanced_code(self):
result = calculate_score(
SyntaxResult(passed=True),
DNSResult(domain_exists=True, has_mx_records=True),
None,
None,
SMTPResult(
verified=False,
smtp_code=550,
smtp_message="550 User Unknown",
),
)
self.assertEqual(result.score, 0)
self.assertIn("SMTP_MAILBOX_NOT_FOUND", result.breakdown)
def test_inconclusive_smtp_is_medium_risk_not_an_implicit_pass(self):
result = calculate_score(
SyntaxResult(passed=True),
DNSResult(domain_exists=True, has_mx_records=True),
None,
None,
SMTPResult(verified=None, error="SMTP connection refused"),
)
self.assertEqual(result.score, 70)
self.assertEqual(result.risk_level.value, "medium")
self.assertEqual(result.breakdown["SMTP_CHECK_INCONCLUSIVE"], -30)
def test_disposable_domain_is_invalid(self):
result = calculate_score(
SyntaxResult(passed=True),
DNSResult(domain_exists=True, has_mx_records=True),
DisposableResult(
is_disposable=True,
is_free_provider=False,
is_role_based=False,
),
None,
None,
)
self.assertEqual(result.score, 0)
self.assertEqual(result.risk_level.value, "high")
self.assertEqual(result.breakdown["DISPOSABLE_DOMAIN"], -100)
def test_catch_all_never_receives_a_low_risk_score(self):
result = calculate_score(
SyntaxResult(passed=True),
DNSResult(domain_exists=True, has_mx_records=True),
None,
CatchAllResult(is_catch_all=True, confidence=0.95),
SMTPResult(verified=True, smtp_code=250),
)
self.assertEqual(result.score, 74)
self.assertEqual(result.risk_level.value, "medium")
def test_role_based_address_never_receives_a_low_risk_score(self):
result = calculate_score(
SyntaxResult(passed=True),
DNSResult(domain_exists=True, has_mx_records=True),
DisposableResult(
is_disposable=False,
is_free_provider=False,
is_role_based=True,
),
None,
SMTPResult(verified=True, smtp_code=250),
)
self.assertEqual(result.score, 74)
self.assertEqual(result.risk_level.value, "medium")
def test_generic_smtp_550_does_not_claim_mailbox_is_nonexistent(self):
result = calculate_score(
SyntaxResult(passed=True),
DNSResult(domain_exists=True, has_mx_records=True),
None,
None,
SMTPResult(verified=False, smtp_code=550),
)
self.assertTrue(
any(
"provider policy may make the result inconclusive" in warning
for warning in result.warnings
)
)
self.assertFalse(
any("Mailbox does not exist" in warning for warning in result.warnings)
)
self.assertGreater(result.score, 0)
self.assertNotIn("SMTP_MAILBOX_NOT_FOUND", result.breakdown)
if __name__ == "__main__":
unittest.main()12345678910111213from __future__ import annotations
__all__ = ["__version__", "version_tuple"]
try: from ._version import version as __version__ from ._version import version_tupleexcept ImportError: # pragma: no cover # broken installation, we don't even try # unknown only works because we do poor mans version compare __version__ = "unknown" version_tuple = (0, 0, "unknown")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117"""Allow bash-completion for argparse with argcomplete if installed.
Needs argcomplete>=0.5.6 for python 3.2/3.3 (older versions failto find the magic string, so _ARGCOMPLETE env. var is never set, andthis does not need special code).
Function try_argcomplete(parser) should be called directly beforethe call to ArgumentParser.parse_args().
The filescompleter is what you normally would use on the positionalarguments specification, in order to get "dirname/" after "dirn<TAB>"instead of the default "dirname ":
optparser.add_argument(Config._file_or_dir, nargs='*').completer=filescompleter
Other, application specific, completers should go in the filedoing the add_argument calls as they need to be specified as .completerattributes as well. (If argcomplete is not installed, the function theattribute points to will not be used).
SPEEDUP=======
The generic argcomplete script for bash-completion(/etc/bash_completion.d/python-argcomplete.sh)uses a python program to determine startup script generated by pip.You can speed up completion somewhat by changing this script to include # PYTHON_ARGCOMPLETE_OKso the python-argcomplete-check-easy-install-script does notneed to be called to find the entry point of the code and see if that ismarked with PYTHON_ARGCOMPLETE_OK.
INSTALL/DEBUGGING=================
To include this support in another application that has setup.py generatedscripts:
- Add the line: # PYTHON_ARGCOMPLETE_OK near the top of the main python entry point.
- Include in the file calling parse_args(): from _argcomplete import try_argcomplete, filescompleter Call try_argcomplete just before parse_args(), and optionally add filescompleter to the positional arguments' add_argument().
If things do not work right away:
- Switch on argcomplete debugging with (also helpful when doing custom completers): export _ARC_DEBUG=1
- Run: python-argcomplete-check-easy-install-script $(which appname) echo $? will echo 0 if the magic line has been found, 1 if not.
- Sometimes it helps to find early on errors using: _ARGCOMPLETE=1 _ARC_DEBUG=1 appname which should throw a KeyError: 'COMPLINE' (which is properly set by the global argcomplete script)."""
from __future__ import annotations
import argparsefrom glob import globimport osimport sysfrom typing import Any
class FastFilesCompleter: """Fast file completer class."""
def __init__(self, directories: bool = True) -> None: self.directories = directories
def __call__(self, prefix: str, **kwargs: Any) -> list[str]: # Only called on non option completions. if os.sep in prefix[1:]: prefix_dir = len(os.path.dirname(prefix) + os.sep) else: prefix_dir = 0 completion = [] globbed = [] if "*" not in prefix and "?" not in prefix: # We are on unix, otherwise no bash. if not prefix or prefix[-1] == os.sep: globbed.extend(glob(prefix + ".*")) prefix += "*" globbed.extend(glob(prefix)) for x in sorted(globbed): if os.path.isdir(x): x += "/" # Append stripping the prefix (like bash, not like compgen). completion.append(x[prefix_dir:]) return completion
if os.environ.get("_ARGCOMPLETE"): try: import argcomplete.completers except ImportError: sys.exit(-1) filescompleter: FastFilesCompleter | None = FastFilesCompleter()
def try_argcomplete(parser: argparse.ArgumentParser) -> None: argcomplete.autocomplete(parser, always_complete_options=False)
else:
def try_argcomplete(parser: argparse.ArgumentParser) -> None: pass
filescompleter = None1234567891011121314151617181920212223242526"""Python inspection/code generation API."""
from __future__ import annotations
from .code import Codefrom .code import ExceptionInfofrom .code import filter_tracebackfrom .code import Framefrom .code import getfslinenofrom .code import Tracebackfrom .code import TracebackEntryfrom .source import getrawcodefrom .source import Source
__all__ = [ "Code", "ExceptionInfo", "Frame", "Source", "Traceback", "TracebackEntry", "filter_traceback", "getfslineno", "getrawcode",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632# mypy: allow-untyped-defsfrom __future__ import annotations
import astfrom collections.abc import Callablefrom collections.abc import Iterablefrom collections.abc import Mappingfrom collections.abc import Sequenceimport dataclassesimport inspectfrom io import StringIOimport osfrom pathlib import Pathimport reimport sysfrom traceback import extract_tbfrom traceback import format_exceptionfrom traceback import format_exception_onlyfrom traceback import FrameSummaryfrom types import CodeTypefrom types import FrameTypefrom types import TracebackTypefrom typing import Anyfrom typing import ClassVarfrom typing import Finalfrom typing import finalfrom typing import Genericfrom typing import Literalfrom typing import overloadfrom typing import SupportsIndexfrom typing import TypeAliasfrom typing import TypeVar
import pluggy
import _pytestfrom _pytest._code.source import findsourcefrom _pytest._code.source import getrawcodefrom _pytest._code.source import getstatementrange_astfrom _pytest._code.source import Sourcefrom _pytest._io import TerminalWriterfrom _pytest._io.saferepr import safeformatfrom _pytest._io.saferepr import safereprfrom _pytest.compat import get_real_funcfrom _pytest.deprecated import check_ispytestfrom _pytest.pathlib import absolutepathfrom _pytest.pathlib import bestrelpath
if sys.version_info < (3, 11): from exceptiongroup import BaseExceptionGroup
TracebackStyle = Literal["long", "short", "line", "no", "native", "value", "auto"]
EXCEPTION_OR_MORE = type[BaseException] | tuple[type[BaseException], ...]
class Code: """Wrapper around Python code objects."""
__slots__ = ("raw",)
def __init__(self, obj: CodeType) -> None: self.raw = obj
@classmethod def from_function(cls, obj: object) -> Code: return cls(getrawcode(obj))
def __eq__(self, other): return self.raw == other.raw
# Ignore type because of https://github.com/python/mypy/issues/4266. __hash__ = None # type: ignore
@property def firstlineno(self) -> int: return self.raw.co_firstlineno - 1
@property def name(self) -> str: return self.raw.co_name
@property def path(self) -> Path | str: """Return a path object pointing to source code, or an ``str`` in case of ``OSError`` / non-existing file.""" filename = inspect.getfile(self.raw) if not filename: return "" try: p = absolutepath(filename) # maybe don't try this checking if not p.exists(): raise OSError("path check failed.") return p except OSError: # XXX maybe try harder like the weird logic # in the standard lib [linecache.updatecache] does? return filename
@property def fullsource(self) -> Source | None: """Return a _pytest._code.Source object for the full source file of the code.""" full, _ = findsource(self.raw) return full
def source(self) -> Source: """Return a _pytest._code.Source object for the code object's source only.""" # return source only for that part of code return Source(self.raw)
def getargs(self, var: bool = False) -> tuple[str, ...]: """Return a tuple with the argument names for the code object.
If 'var' is set True also return the names of the variable and keyword arguments when present. """ # inspect.getargs merges positional and kwonly into a single list; # co_argcount is needed to exclude kwonly when var=False. args, varargs, varkw = inspect.getargs(self.raw) if not var: return tuple(args[: self.raw.co_argcount]) result = list(args) if varargs is not None: result.append(varargs) if varkw is not None: result.append(varkw) return tuple(result)
class Frame: """Wrapper around a Python frame holding f_locals and f_globals in which expressions can be evaluated."""
__slots__ = ("raw",)
def __init__(self, frame: FrameType) -> None: self.raw = frame
@property def lineno(self) -> int: return self.raw.f_lineno - 1
@property def f_globals(self) -> dict[str, Any]: return self.raw.f_globals
@property def f_locals(self) -> dict[str, Any]: return self.raw.f_locals
@property def code(self) -> Code: return Code(self.raw.f_code)
@property def statement(self) -> Source: """Statement this frame is at.""" if self.code.fullsource is None: return Source("") return self.code.fullsource.getstatement(self.lineno)
def eval(self, code, **vars): """Evaluate 'code' in the frame.
'vars' are optional additional local variables.
Returns the result of the evaluation. """ f_locals = self.f_locals.copy() f_locals.update(vars) return eval(code, self.f_globals, f_locals)
def repr(self, object: object) -> str: """Return a 'safe' (non-recursive, one-line) string repr for 'object'.""" return saferepr(object)
def getargs(self, var: bool = False): """Return a list of tuples (name, value) for all arguments.
If 'var' is set True, also include the variable and keyword arguments when present. """ retval = [] for arg in self.code.getargs(var): try: retval.append((arg, self.f_locals[arg])) except KeyError: pass # this can occur when using Psyco return retval
class TracebackEntry: """A single entry in a Traceback."""
__slots__ = ("_rawentry", "_repr_style")
def __init__( self, rawentry: TracebackType, repr_style: Literal["short", "long"] | None = None, ) -> None: self._rawentry: Final = rawentry self._repr_style: Final = repr_style
def with_repr_style( self, repr_style: Literal["short", "long"] | None ) -> TracebackEntry: return TracebackEntry(self._rawentry, repr_style)
@property def lineno(self) -> int: return self._rawentry.tb_lineno - 1
def get_python_framesummary(self) -> FrameSummary: # Python's built-in traceback module implements all the nitty gritty # details to get column numbers of out frames. stack_summary = extract_tb(self._rawentry, limit=1) return stack_summary[0]
# Column and end line numbers introduced in python 3.11 if sys.version_info < (3, 11):
@property def end_lineno_relative(self) -> int | None: return None
@property def colno(self) -> int | None: return None
@property def end_colno(self) -> int | None: return None else:
@property def end_lineno_relative(self) -> int | None: frame_summary = self.get_python_framesummary() if frame_summary.end_lineno is None: # pragma: no cover return None return frame_summary.end_lineno - 1 - self.frame.code.firstlineno
@property def colno(self) -> int | None: """Starting byte offset of the expression in the traceback entry.""" return self.get_python_framesummary().colno
@property def end_colno(self) -> int | None: """Ending byte offset of the expression in the traceback entry.""" return self.get_python_framesummary().end_colno
@property def frame(self) -> Frame: return Frame(self._rawentry.tb_frame)
@property def relline(self) -> int: return self.lineno - self.frame.code.firstlineno
def __repr__(self) -> str: return f"<TracebackEntry {self.frame.code.path}:{self.lineno + 1}>"
@property def statement(self) -> Source: """_pytest._code.Source object for the current statement.""" source = self.frame.code.fullsource assert source is not None return source.getstatement(self.lineno)
@property def path(self) -> Path | str: """Path to the source code.""" return self.frame.code.path
@property def locals(self) -> dict[str, Any]: """Locals of underlying frame.""" return self.frame.f_locals
def getfirstlinesource(self) -> int: return self.frame.code.firstlineno
def getsource( self, astcache: dict[str | Path, ast.AST] | None = None ) -> Source | None: """Return failing source code.""" # we use the passed in astcache to not reparse asttrees # within exception info printing source = self.frame.code.fullsource if source is None: return None key = astnode = None if astcache is not None: key = self.frame.code.path if key is not None: astnode = astcache.get(key, None) start = self.getfirstlinesource() try: astnode, _, end = getstatementrange_ast( self.lineno, source, astnode=astnode ) except SyntaxError: end = self.lineno + 1 else: if key is not None and astcache is not None: astcache[key] = astnode return source[start:end]
source = property(getsource)
def ishidden(self, excinfo: ExceptionInfo[BaseException] | None) -> bool: """Return True if the current frame has a var __tracebackhide__ resolving to True.
If __tracebackhide__ is a callable, it gets called with the ExceptionInfo instance and can decide whether to hide the traceback.
Mostly for internal use. """ tbh: bool | Callable[[ExceptionInfo[BaseException] | None], bool] = False for maybe_ns_dct in (self.frame.f_locals, self.frame.f_globals): # in normal cases, f_locals and f_globals are dictionaries # however via `exec(...)` / `eval(...)` they can be other types # (even incorrect types!). # as such, we suppress all exceptions while accessing __tracebackhide__ try: tbh = maybe_ns_dct["__tracebackhide__"] except Exception: pass else: break if tbh and callable(tbh): return tbh(excinfo) return tbh
def __str__(self) -> str: name = self.frame.code.name try: line = str(self.statement).lstrip() except KeyboardInterrupt: raise except BaseException: line = "???" # This output does not quite match Python's repr for traceback entries, # but changing it to do so would break certain plugins. See # https://github.com/pytest-dev/pytest/pull/7535/ for details. return f" File '{self.path}':{self.lineno + 1} in {name}\n {line}\n"
@property def name(self) -> str: """co_name of underlying code.""" return self.frame.code.raw.co_name
class Traceback(list[TracebackEntry]): """Traceback objects encapsulate and offer higher level access to Traceback entries."""
def __init__( self, tb: TracebackType | Iterable[TracebackEntry], ) -> None: """Initialize from given python traceback object and ExceptionInfo.""" if isinstance(tb, TracebackType):
def f(cur: TracebackType) -> Iterable[TracebackEntry]: cur_: TracebackType | None = cur while cur_ is not None: yield TracebackEntry(cur_) cur_ = cur_.tb_next
super().__init__(f(tb)) else: super().__init__(tb)
def cut( self, path: os.PathLike[str] | str | None = None, lineno: int | None = None, firstlineno: int | None = None, excludepath: os.PathLike[str] | None = None, ) -> Traceback: """Return a Traceback instance wrapping part of this Traceback.
By providing any combination of path, lineno and firstlineno, the first frame to start the to-be-returned traceback is determined.
This allows cutting the first part of a Traceback instance e.g. for formatting reasons (removing some uninteresting bits that deal with handling of the exception/traceback). """ path_ = None if path is None else os.fspath(path) excludepath_ = None if excludepath is None else os.fspath(excludepath) for x in self: code = x.frame.code codepath = code.path if path is not None and str(codepath) != path_: continue if ( excludepath is not None and isinstance(codepath, Path) and excludepath_ in (str(p) for p in codepath.parents) # type: ignore[operator] ): continue if lineno is not None and x.lineno != lineno: continue if firstlineno is not None and x.frame.code.firstlineno != firstlineno: continue return Traceback(x._rawentry) return self
@overload def __getitem__(self, key: SupportsIndex) -> TracebackEntry: ...
@overload def __getitem__(self, key: slice) -> Traceback: ...
def __getitem__(self, key: SupportsIndex | slice) -> TracebackEntry | Traceback: if isinstance(key, slice): return self.__class__(super().__getitem__(key)) else: return super().__getitem__(key)
def filter( self, excinfo_or_fn: ExceptionInfo[BaseException] | Callable[[TracebackEntry], bool], /, ) -> Traceback: """Return a Traceback instance with certain items removed.
If the filter is an `ExceptionInfo`, removes all the ``TracebackEntry``s which are hidden (see ishidden() above).
Otherwise, the filter is a function that gets a single argument, a ``TracebackEntry`` instance, and should return True when the item should be added to the ``Traceback``, False when not. """ if isinstance(excinfo_or_fn, ExceptionInfo): fn = lambda x: not x.ishidden(excinfo_or_fn) # noqa: E731 else: fn = excinfo_or_fn return Traceback(filter(fn, self))
def recursionindex(self) -> int | None: """Return the index of the frame/TracebackEntry where recursion originates if appropriate, None if no recursion occurred.""" cache: dict[tuple[Any, int, int], list[dict[str, Any]]] = {} for i, entry in enumerate(self): # id for the code.raw is needed to work around # the strange metaprogramming in the decorator lib from pypi # which generates code objects that have hash/value equality # XXX needs a test key = entry.frame.code.path, id(entry.frame.code.raw), entry.lineno values = cache.setdefault(key, []) # Since Python 3.13 f_locals is a proxy, freeze it. loc = dict(entry.frame.f_locals) if values: for otherloc in values: if otherloc == loc: return i values.append(loc) return None
def stringify_exception( exc: BaseException, include_subexception_msg: bool = True) -> str: try: notes = getattr(exc, "__notes__", []) except KeyError: # Workaround for https://github.com/python/cpython/issues/98778 on # some 3.10 and 3.11 patch versions. HTTPError = getattr(sys.modules.get("urllib.error", None), "HTTPError", ()) if sys.version_info < (3, 12) and isinstance(exc, HTTPError): notes = [] else: # pragma: no cover # exception not related to above bug, reraise raise if not include_subexception_msg and isinstance(exc, BaseExceptionGroup): message = exc.message else: message = str(exc)
return "\n".join( [ message, *notes, ] )
E = TypeVar("E", bound=BaseException, covariant=True)
@final@dataclasses.dataclassclass ExceptionInfo(Generic[E]): """Wraps sys.exc_info() objects and offers help for navigating the traceback."""
_assert_start_repr: ClassVar = "AssertionError('assert "
_excinfo: tuple[type[E], E, TracebackType] | None _striptext: str _traceback: Traceback | None
def __init__( self, excinfo: tuple[type[E], E, TracebackType] | None, striptext: str = "", traceback: Traceback | None = None, *, _ispytest: bool = False, ) -> None: check_ispytest(_ispytest) self._excinfo = excinfo self._striptext = striptext self._traceback = traceback
@classmethod def from_exception( cls, # Ignoring error: "Cannot use a covariant type variable as a parameter". # This is OK to ignore because this class is (conceptually) readonly. # See https://github.com/python/mypy/issues/7049. exception: E, # type: ignore[misc] exprinfo: str | None = None, ) -> ExceptionInfo[E]: """Return an ExceptionInfo for an existing exception.
The exception must have a non-``None`` ``__traceback__`` attribute, otherwise this function fails with an assertion error. This means that the exception must have been raised, or added a traceback with the :py:meth:`~BaseException.with_traceback()` method.
:param exprinfo: A text string helping to determine if we should strip ``AssertionError`` from the output. Defaults to the exception message/``__str__()``.
.. versionadded:: 7.4 """ assert exception.__traceback__, ( "Exceptions passed to ExcInfo.from_exception(...)" " must have a non-None __traceback__." ) exc_info = (type(exception), exception, exception.__traceback__) return cls.from_exc_info(exc_info, exprinfo)
@classmethod def from_exc_info( cls, exc_info: tuple[type[E], E, TracebackType], exprinfo: str | None = None, ) -> ExceptionInfo[E]: """Like :func:`from_exception`, but using old-style exc_info tuple.""" _striptext = "" if exprinfo is None and isinstance(exc_info[1], AssertionError): exprinfo = getattr(exc_info[1], "msg", None) if exprinfo is None: exprinfo = saferepr(exc_info[1]) if exprinfo and exprinfo.startswith(cls._assert_start_repr): _striptext = "AssertionError: "
return cls(exc_info, _striptext, _ispytest=True)
@classmethod def from_current(cls, exprinfo: str | None = None) -> ExceptionInfo[BaseException]: """Return an ExceptionInfo matching the current traceback.
.. warning::
Experimental API
:param exprinfo: A text string helping to determine if we should strip ``AssertionError`` from the output. Defaults to the exception message/``__str__()``. """ tup = sys.exc_info() assert tup[0] is not None, "no current exception" assert tup[1] is not None, "no current exception" assert tup[2] is not None, "no current exception" exc_info = (tup[0], tup[1], tup[2]) return ExceptionInfo.from_exc_info(exc_info, exprinfo)
@classmethod def for_later(cls) -> ExceptionInfo[E]: """Return an unfilled ExceptionInfo.""" return cls(None, _ispytest=True)
def fill_unfilled(self, exc_info: tuple[type[E], E, TracebackType]) -> None: """Fill an unfilled ExceptionInfo created with ``for_later()``.""" assert self._excinfo is None, "ExceptionInfo was already filled" self._excinfo = exc_info
@property def type(self) -> type[E]: """The exception class.""" assert self._excinfo is not None, ( ".type can only be used after the context manager exits" ) return self._excinfo[0]
@property def value(self) -> E: """The exception value.""" assert self._excinfo is not None, ( ".value can only be used after the context manager exits" ) return self._excinfo[1]
@property def tb(self) -> TracebackType: """The exception raw traceback.""" assert self._excinfo is not None, ( ".tb can only be used after the context manager exits" ) return self._excinfo[2]
@property def typename(self) -> str: """The type name of the exception.""" assert self._excinfo is not None, ( ".typename can only be used after the context manager exits" ) return self.type.__name__
@property def traceback(self) -> Traceback: """The traceback.""" if self._traceback is None: self._traceback = Traceback(self.tb) return self._traceback
@traceback.setter def traceback(self, value: Traceback) -> None: self._traceback = value
def __repr__(self) -> str: if self._excinfo is None: return "<ExceptionInfo for raises contextmanager>" return f"<{self.__class__.__name__} {saferepr(self._excinfo[1])} tblen={len(self.traceback)}>"
def exconly(self, tryshort: bool = False) -> str: """Return the exception as a string.
This is usually a single line "<exception type>: <exception str>", but may also include additional lines for the exception notes, and detailed information for SyntaxError's.
:param tryshort: If true, and the exception is an AssertionError, strip 'AssertionError: ' from the beginning. """
def _get_single_subexc( eg: BaseExceptionGroup[BaseException], ) -> BaseException | None: if len(eg.exceptions) != 1: return None if isinstance(e := eg.exceptions[0], BaseExceptionGroup): return _get_single_subexc(e) return e
if ( tryshort and isinstance(self.value, BaseExceptionGroup) and (subexc := _get_single_subexc(self.value)) is not None ): return f"{subexc!r} [single exception in {type(self.value).__name__}]"
lines = format_exception_only(self.value) # The lines already include line separators. text = "".join(lines) text = text.rstrip() if tryshort: if text.startswith(self._striptext): text = text[len(self._striptext) :] return text
def errisinstance(self, exc: EXCEPTION_OR_MORE) -> bool: """Return True if the exception is an instance of exc.
Consider using ``isinstance(excinfo.value, exc)`` instead. """ return isinstance(self.value, exc)
def _getreprcrash(self) -> ReprFileLocation | None: # Find last non-hidden traceback entry that led to the exception of the # traceback, or None if all hidden. for i in range(-1, -len(self.traceback) - 1, -1): entry = self.traceback[i] if not entry.ishidden(self): path, lineno = entry.frame.code.raw.co_filename, entry.lineno exconly = self.exconly(tryshort=True) return ReprFileLocation(path, lineno + 1, exconly) return None
def getrepr( self, showlocals: bool = False, style: TracebackStyle = "long", abspath: bool = False, tbfilter: bool | Callable[[ExceptionInfo[BaseException]], Traceback] = True, funcargs: bool = False, truncate_locals: bool = True, truncate_args: bool = True, chain: bool = True, ) -> ReprExceptionInfo | ExceptionChainRepr: """Return str()able representation of this exception info.
The formatting parameters are ineffective if ``style="native"``, since in this case the native formatting is used.
:param bool showlocals: Show locals per traceback entry.
:param str style: long|short|line|no|native|value traceback style.
:param bool abspath: If paths should be changed to absolute or left unchanged.
:param tbfilter: A filter for traceback entries.
* If false, don't hide any entries. * If true, hide internal entries and entries that contain a local variable ``__tracebackhide__ = True``. * If a callable, delegates the filtering to the callable.
:param bool funcargs: Show function arguments per traceback entry.
:param bool truncate_locals: Whether to show a size-limited `repr()` of locals, or a full pretty-printing.
:param bool truncate_args: Whether to show a size-limited truncated `repr()` of function arguments, or a full pretty-printing.
:param bool chain: If chained exceptions should be shown.
.. versionchanged:: 3.9
Added the ``chain`` parameter. """ if style == "native": return ReprExceptionInfo( reprtraceback=ReprTracebackNative( format_exception( self.type, self.value, self.traceback[0]._rawentry if self.traceback else None, ) ), reprcrash=self._getreprcrash(), )
fmt = ExceptionInfoFormatter( showlocals=showlocals, style=style, abspath=abspath, tbfilter=tbfilter, funcargs=funcargs, truncate_locals=truncate_locals, truncate_args=truncate_args, chain=chain, ) return fmt.repr_excinfo(self)
def match(self, regexp: str | re.Pattern[str]) -> Literal[True]: """Check whether the regular expression `regexp` matches the string representation of the exception using :func:`python:re.search`.
If it matches `True` is returned, otherwise an `AssertionError` is raised. """ __tracebackhide__ = True value = stringify_exception(self.value) msg = ( f"Regex pattern did not match.\n" f" Expected regex: {regexp!r}\n" f" Actual message: {value!r}" ) if regexp == value: msg += "\n Did you mean to `re.escape()` the regex?" assert re.search(regexp, value), msg # Return True to allow for "assert excinfo.match()". return True
def _group_contains( self, exc_group: BaseExceptionGroup[BaseException], expected_exception: EXCEPTION_OR_MORE, match: str | re.Pattern[str] | None, target_depth: int | None = None, current_depth: int = 1, ) -> bool: """Return `True` if a `BaseExceptionGroup` contains a matching exception.""" if (target_depth is not None) and (current_depth > target_depth): # already descended past the target depth return False for exc in exc_group.exceptions: if isinstance(exc, BaseExceptionGroup): if self._group_contains( exc, expected_exception, match, target_depth, current_depth + 1 ): return True if (target_depth is not None) and (current_depth != target_depth): # not at the target depth, no match continue if not isinstance(exc, expected_exception): continue if match is not None: value = stringify_exception(exc) if not re.search(match, value): continue return True return False
def group_contains( self, expected_exception: EXCEPTION_OR_MORE, *, match: str | re.Pattern[str] | None = None, depth: int | None = None, ) -> bool: """Check whether a captured exception group contains a matching exception.
:param Type[BaseException] | Tuple[Type[BaseException]] expected_exception: The expected exception type, or a tuple if one of multiple possible exception types are expected.
:param str | re.Pattern[str] | None match: If specified, a string containing a regular expression, or a regular expression object, that is tested against the string representation of the exception and its `PEP-678 <https://peps.python.org/pep-0678/>` `__notes__` using :func:`re.search`.
To match a literal string that may contain :ref:`special characters <re-syntax>`, the pattern can first be escaped with :func:`re.escape`.
:param Optional[int] depth: If `None`, will search for a matching exception at any nesting depth. If >= 1, will only match an exception if it's at the specified depth (depth = 1 being the exceptions contained within the topmost exception group).
.. versionadded:: 8.0
.. warning:: This helper makes it easy to check for the presence of specific exceptions, but it is very bad for checking that the group does *not* contain *any other exceptions*. You should instead consider using :class:`pytest.RaisesGroup`
""" msg = "Captured exception is not an instance of `BaseExceptionGroup`" assert isinstance(self.value, BaseExceptionGroup), msg msg = "`depth` must be >= 1 if specified" assert (depth is None) or (depth >= 1), msg return self._group_contains(self.value, expected_exception, match, depth)
# Type alias for the `tbfilter` setting:# bool: If True, it should be filtered using Traceback.filter()# callable: A callable that takes an ExceptionInfo and returns the filtered traceback.TracebackFilter: TypeAlias = bool | Callable[[ExceptionInfo[BaseException]], Traceback]
@dataclasses.dataclassclass ExceptionInfoFormatter: """Helper object to format ExceptionInfo's and individual exception parts into TerminalRepr's.
See :func:`ExceptionInfo.getrepr` for parameters. """
# for traceback entries flow_marker: ClassVar = ">" fail_marker: ClassVar = "E"
showlocals: bool = False # Note: "native" is handled outside of ExceptionInfoFormatter. style: TracebackStyle = "long" abspath: bool = True tbfilter: TracebackFilter = True funcargs: bool = False truncate_locals: bool = True truncate_args: bool = True chain: bool = True
astcache: dict[str | Path, ast.AST] = dataclasses.field( default_factory=dict, init=False, repr=False )
def _getindent(self, source: Source) -> int: # Figure out indent for the given source. try: s = str(source.getstatement(len(source) - 1)) except KeyboardInterrupt: raise except BaseException: try: s = str(source[-1]) except KeyboardInterrupt: raise except BaseException: return 0 return 4 + (len(s) - len(s.lstrip()))
def _getentrysource(self, entry: TracebackEntry) -> Source | None: source = entry.getsource(self.astcache) if source is not None: source = source.deindent() return source
def repr_args(self, entry: TracebackEntry) -> ReprFuncArgs | None: if self.funcargs: args = [] for argname, argvalue in entry.frame.getargs(var=True): if self.truncate_args: str_repr = saferepr(argvalue) else: str_repr = saferepr(argvalue, maxsize=None) args.append((argname, str_repr)) return ReprFuncArgs(args) return None
def get_source( self, source: Source | None, line_index: int = -1, excinfo: ExceptionInfo[BaseException] | None = None, short: bool = False, end_line_index: int | None = None, colno: int | None = None, end_colno: int | None = None, ) -> list[str]: """Return formatted and marked up source lines.""" lines = [] if source is not None and line_index < 0: line_index += len(source) if source is None or line_index >= len(source.lines) or line_index < 0: # `line_index` could still be outside `range(len(source.lines))` if # we're processing AST with pathological position attributes. source = Source("???") line_index = 0 space_prefix = " " if short: lines.append(space_prefix + source.lines[line_index].strip()) lines.extend( self.get_highlight_arrows_for_line( raw_line=source.raw_lines[line_index], line=source.lines[line_index].strip(), lineno=line_index, end_lineno=end_line_index, colno=colno, end_colno=end_colno, ) ) else: for line in source.lines[:line_index]: lines.append(space_prefix + line) lines.append(self.flow_marker + " " + source.lines[line_index]) lines.extend( self.get_highlight_arrows_for_line( raw_line=source.raw_lines[line_index], line=source.lines[line_index], lineno=line_index, end_lineno=end_line_index, colno=colno, end_colno=end_colno, ) ) for line in source.lines[line_index + 1 :]: lines.append(space_prefix + line) if excinfo is not None: indent = 4 if short else self._getindent(source) lines.extend(self.get_exconly(excinfo, indent=indent, markall=True)) return lines
def get_highlight_arrows_for_line( self, line: str, raw_line: str, lineno: int | None, end_lineno: int | None, colno: int | None, end_colno: int | None, ) -> list[str]: """Return characters highlighting a source line.
Example with colno and end_colno pointing to the bar expression: "foo() + bar()" returns " ^^^^^" """ if lineno != end_lineno: # Don't handle expressions that span multiple lines. return [] if colno is None or end_colno is None: # Can't do anything without column information. return []
num_stripped_chars = len(raw_line) - len(line)
start_char_offset = _byte_offset_to_character_offset(raw_line, colno) end_char_offset = _byte_offset_to_character_offset(raw_line, end_colno) num_carets = end_char_offset - start_char_offset # If the highlight would span the whole line, it is redundant, don't # show it. if num_carets >= len(line.strip()): return []
highlights = " " highlights += " " * (start_char_offset - num_stripped_chars + 1) highlights += "^" * num_carets return [highlights]
def get_exconly( self, excinfo: ExceptionInfo[BaseException], indent: int = 4, markall: bool = False, ) -> list[str]: lines = [] indentstr = " " * indent # Get the real exception information out. exlines = excinfo.exconly(tryshort=True).split("\n") failindent = self.fail_marker + indentstr[1:] for line in exlines: lines.append(failindent + line) if not markall: failindent = indentstr return lines
def repr_locals(self, locals: Mapping[str, object]) -> ReprLocals | None: if self.showlocals: lines = [] # Variables starting with `@` are helpers injected by assertion # rewriting, not user variables, so hide them. keys = [loc for loc in locals if loc[0] != "@"] keys.sort() for name in keys: value = locals[name] if name == "__builtins__": lines.append("__builtins__ = <builtins>") else: # This formatting could all be handled by the # _repr() function, which is only reprlib.Repr in # disguise, so is very configurable. if self.truncate_locals: str_repr = saferepr(value) else: str_repr = safeformat(value) # if len(str_repr) < 70 or not isinstance(value, (list, tuple, dict)): lines.append(f"{name:<10} = {str_repr}") # else: # self._line("%-10s =\\" % (name,)) # # XXX # pprint.pprint(value, stream=self.excinfowriter) return ReprLocals(lines) return None
def repr_traceback_entry( self, entry: TracebackEntry | None, excinfo: ExceptionInfo[BaseException] | None = None, ) -> ReprEntry: lines: list[str] = [] style = ( entry._repr_style if entry is not None and entry._repr_style is not None else self.style ) if style in ("short", "long") and entry is not None: source = self._getentrysource(entry) if source is None: source = Source("???") line_index = 0 end_line_index, colno, end_colno = None, None, None else: line_index = entry.relline end_line_index = entry.end_lineno_relative colno = entry.colno end_colno = entry.end_colno short = style == "short" reprargs = self.repr_args(entry) if not short else None s = self.get_source( source=source, line_index=line_index, excinfo=excinfo, short=short, end_line_index=end_line_index, colno=colno, end_colno=end_colno, ) lines.extend(s) if short: message = f"in {entry.name}" else: message = (excinfo and excinfo.typename) or "" entry_path = entry.path path = self._makepath(entry_path) reprfileloc = ReprFileLocation(path, entry.lineno + 1, message) localsrepr = self.repr_locals(entry.locals) return ReprEntry(lines, reprargs, localsrepr, reprfileloc, style) elif style == "value": if excinfo: lines.extend(str(excinfo.value).split("\n")) return ReprEntry(lines, None, None, None, style) else: if excinfo: lines.extend(self.get_exconly(excinfo, indent=4)) return ReprEntry(lines, None, None, None, style)
def _makepath(self, path: Path | str) -> str: if not self.abspath and isinstance(path, Path): try: np = bestrelpath(Path.cwd(), path) except OSError: return str(path) if len(np) < len(str(path)): return np return str(path)
def repr_traceback(self, excinfo: ExceptionInfo[BaseException]) -> ReprTraceback: traceback = filter_excinfo_traceback(self.tbfilter, excinfo)
if isinstance(excinfo.value, RecursionError): traceback, extraline = self._truncate_recursive_traceback(traceback) else: extraline = None
if not traceback: if extraline is None: extraline = "All traceback entries are hidden. Pass `--full-trace` to see hidden and internal frames." entries = [self.repr_traceback_entry(None, excinfo)] return ReprTraceback(entries, extraline, style=self.style)
last = traceback[-1] if self.style == "value": entries = [self.repr_traceback_entry(last, excinfo)] return ReprTraceback(entries, None, style=self.style)
entries = [ self.repr_traceback_entry(entry, excinfo if last == entry else None) for entry in traceback ] return ReprTraceback(entries, extraline, style=self.style)
def _truncate_recursive_traceback( self, traceback: Traceback ) -> tuple[Traceback, str | None]: """Truncate the given recursive traceback trying to find the starting point of the recursion.
The detection is done by going through each traceback entry and finding the point in which the locals of the frame are equal to the locals of a previous frame (see ``recursionindex()``).
Handle the situation where the recursion process might raise an exception (for example comparing numpy arrays using equality raises a TypeError), in which case we do our best to warn the user of the error and show a limited traceback. """ try: recursionindex = traceback.recursionindex() except Exception as e: max_frames = 10 extraline: str | None = ( "!!! Recursion error detected, but an error occurred locating the origin of recursion.\n" " The following exception happened when comparing locals in the stack frame:\n" f" {type(e).__name__}: {e!s}\n" f" Displaying first and last {max_frames} stack frames out of {len(traceback)}." ) # Type ignored because adding two instances of a List subtype # currently incorrectly has type List instead of the subtype. traceback = traceback[:max_frames] + traceback[-max_frames:] # type: ignore else: if recursionindex is not None: extraline = "!!! Recursion detected (same locals & position)" traceback = traceback[: recursionindex + 1] else: extraline = None
return traceback, extraline
def repr_excinfo(self, excinfo: ExceptionInfo[BaseException]) -> ExceptionChainRepr: repr_chain: list[tuple[ReprTraceback, ReprFileLocation | None, str | None]] = [] e: BaseException | None = excinfo.value excinfo_: ExceptionInfo[BaseException] | None = excinfo description = None seen: set[int] = set() while e is not None and id(e) not in seen: seen.add(id(e))
if excinfo_: # Fall back to native traceback as a temporary workaround until # full support for exception groups added to ExceptionInfo. # See https://github.com/pytest-dev/pytest/issues/9159 reprtraceback: ReprTraceback | ReprTracebackNative if isinstance(e, BaseExceptionGroup): # don't filter any sub-exceptions since they shouldn't have any internal frames traceback = filter_excinfo_traceback(self.tbfilter, excinfo) extraline = ( "All traceback entries are hidden. Pass `--full-trace` to see hidden and internal frames." if not traceback else None ) reprtraceback = ReprTracebackNative( format_exception( type(excinfo.value), excinfo.value, traceback[0]._rawentry if traceback else None, ), extraline=extraline, )
else: reprtraceback = self.repr_traceback(excinfo_) reprcrash = excinfo_._getreprcrash() else: # Fallback to native repr if the exception doesn't have a traceback: # ExceptionInfo objects require a full traceback to work. reprtraceback = ReprTracebackNative(format_exception(type(e), e, None)) reprcrash = None repr_chain.append((reprtraceback, reprcrash, description))
if e.__cause__ is not None and self.chain: e = e.__cause__ excinfo_ = ExceptionInfo.from_exception(e) if e.__traceback__ else None description = "The above exception was the direct cause of the following exception:" elif ( e.__context__ is not None and not e.__suppress_context__ and self.chain ): e = e.__context__ excinfo_ = ExceptionInfo.from_exception(e) if e.__traceback__ else None description = "During handling of the above exception, another exception occurred:" else: e = None repr_chain.reverse() return ExceptionChainRepr(repr_chain)
@dataclasses.dataclass(eq=False)class TerminalRepr: """Base class for terminal representations -- pieces of data that display themselves to a terminal."""
def __str__(self) -> str: # FYI this is called from pytest-xdist's serialization of exception # information. io = StringIO() tw = TerminalWriter(file=io) self.toterminal(tw) return io.getvalue().strip()
def __repr__(self) -> str: return f"<{self.__class__} instance at {id(self):0x}>"
def toterminal(self, tw: TerminalWriter) -> None: raise NotImplementedError()
@dataclasses.dataclass(eq=False)class ExceptionRepr(TerminalRepr): """Base class for exception terminal representations.
The representation generally contains: - The exception traceback (`reprtraceback`) - The exception message and location (`reprcrash`) - Separated, titled sections with additional data (pytest core doesn't use this currently). """
reprtraceback: ReprTraceback reprcrash: ReprFileLocation | None sections: list[tuple[str, str, str]] = dataclasses.field( init=False, default_factory=list )
def addsection(self, name: str, content: str, sep: str = "-") -> None: self.sections.append((name, content, sep))
def toterminal(self, tw: TerminalWriter) -> None: for name, content, sep in self.sections: tw.sep(sep, name) tw.line(content)
@dataclasses.dataclass(eq=False)class ExceptionChainRepr(ExceptionRepr): """A chain of exceptions, separated by descriptions (e.g. "The above exception was the direct cause of the following exception")."""
chain: Sequence[tuple[ReprTraceback, ReprFileLocation | None, str | None]]
def __init__( self, chain: Sequence[tuple[ReprTraceback, ReprFileLocation | None, str | None]], ) -> None: # reprcrash and reprtraceback of the outermost (the newest) exception # in the chain. super().__init__( reprtraceback=chain[-1][0], reprcrash=chain[-1][1], ) self.chain = chain
def toterminal(self, tw: TerminalWriter) -> None: for reprtraceback, reprcrash, description in self.chain: reprtraceback.toterminal(tw) if description is not None: tw.line("") tw.line(description, yellow=True) super().toterminal(tw)
@dataclasses.dataclass(eq=False)class ReprExceptionInfo(ExceptionRepr): """A single exception with optional extra details (function arguments, function locals, file location) and possible extra line and sections emitted at the end."""
def toterminal(self, tw: TerminalWriter) -> None: self.reprtraceback.toterminal(tw) super().toterminal(tw)
@dataclasses.dataclass(eq=False)class ReprTraceback(TerminalRepr): """A traceback with optional extra details (function arguments, function locals, file location) and possible extra line emitted at the end."""
reprentries: Sequence[ReprEntry | ReprEntryNative] extraline: str | None style: TracebackStyle
entrysep: ClassVar = "_ "
def toterminal(self, tw: TerminalWriter) -> None: # The entries might have different styles. for i, entry in enumerate(self.reprentries): if entry.style == "long": tw.line("") entry.toterminal(tw) if i < len(self.reprentries) - 1: next_entry = self.reprentries[i + 1] if entry.style == "long" or ( entry.style == "short" and next_entry.style == "long" ): tw.sep(self.entrysep)
if self.extraline: tw.line(self.extraline)
class ReprTracebackNative(ReprTraceback): """A traceback in native style.
The lines are emitted as is; uses a single entry for the entire native traceback. """
def __init__(self, tblines: Sequence[str], *, extraline: str | None = None) -> None: self.reprentries = [ReprEntryNative(tblines)] self.extraline = extraline self.style = "native"
@dataclasses.dataclass(eq=False)class ReprEntryNative(TerminalRepr): """An entry in a traceback in native style.
Emits the lines as is. The lines are assumed to include the line separators.
[Note that we currently use a single "entry" for the entire native traceback, so this is a bit misleading, but there's no point trying to parse or split a native traceback.] """
lines: Sequence[str]
style: ClassVar[TracebackStyle] = "native"
def toterminal(self, tw: TerminalWriter) -> None: tw.write("".join(self.lines))
@dataclasses.dataclass(eq=False)class ReprEntry(TerminalRepr): """An entry in a traceback with possible extra details (function arguments, function locals, source snippet, function's file and line)."""
lines: Sequence[str] reprfuncargs: ReprFuncArgs | None reprlocals: ReprLocals | None reprfileloc: ReprFileLocation | None style: TracebackStyle
def _write_entry_lines(self, tw: TerminalWriter) -> None: """Write the source code portions of a list of traceback entries with syntax highlighting.
Usually entries are lines like these:
" x = 1" "> assert x == 2" "E assert 1 == 2"
This function takes care of rendering the "source" portions of it (the lines without the "E" prefix) using syntax highlighting, taking care to not highlighting the ">" character, as doing so might break line continuations. """ if not self.lines: return
if self.style == "value": # Using tw.write instead of tw.line for testing purposes due to TWMock implementation; # lines written with TWMock.line and TWMock._write_source cannot be distinguished # from each other, whereas lines written with TWMock.write are marked with TWMock.WRITE for line in self.lines: tw.write(line) tw.write("\n") return
# separate indents and source lines that are not failures: we want to # highlight the code but not the indentation, which may contain markers # such as "> assert 0" fail_marker = f"{ExceptionInfoFormatter.fail_marker} " indent_size = len(fail_marker) indents: list[str] = [] source_lines: list[str] = [] failure_lines: list[str] = [] for index, line in enumerate(self.lines): is_failure_line = line.startswith(fail_marker) if is_failure_line: # from this point on all lines are considered part of the failure failure_lines.extend(self.lines[index:]) break else: indents.append(line[:indent_size]) source_lines.append(line[indent_size:])
tw._write_source(source_lines, indents)
# failure lines are always completely red and bold for line in failure_lines: tw.line(line, bold=True, red=True)
def toterminal(self, tw: TerminalWriter) -> None: if self.style == "short": if self.reprfileloc: self.reprfileloc.toterminal(tw) self._write_entry_lines(tw) if self.reprlocals: self.reprlocals.toterminal(tw, indent=" " * 8) return
if self.reprfuncargs: self.reprfuncargs.toterminal(tw)
self._write_entry_lines(tw)
if self.reprlocals: tw.line("") self.reprlocals.toterminal(tw) if self.reprfileloc: if self.lines: tw.line("") self.reprfileloc.toterminal(tw)
def __str__(self) -> str: return "{}\n{}\n{}".format( "\n".join(self.lines), self.reprlocals, self.reprfileloc )
@dataclasses.dataclass(eq=False)class ReprFileLocation(TerminalRepr): """A message at a file location, using the `<path>:<lineno>: <message>` format that most editors understand.
Only the first line of the message is emitted. """
path: str lineno: int message: str
def __post_init__(self) -> None: self.path = str(self.path)
def toterminal(self, tw: TerminalWriter) -> None: msg = self.message i = msg.find("\n") if i != -1: msg = msg[:i] tw.write(self.path, bold=True, red=True) tw.line(f":{self.lineno}: {msg}")
@dataclasses.dataclass(eq=False)class ReprLocals(TerminalRepr): """Function local variables (pre-formatted)."""
lines: Sequence[str]
def toterminal(self, tw: TerminalWriter, indent: str = "") -> None: for line in self.lines: tw.line(indent + line)
@dataclasses.dataclass(eq=False)class ReprFuncArgs(TerminalRepr): """Function arguments - name = value, comma separated."""
args: Sequence[tuple[str, object]]
def toterminal(self, tw: TerminalWriter) -> None: if self.args: linesofar = "" for name, value in self.args: ns = f"{name} = {value}" if len(ns) + len(linesofar) + 2 > tw.fullwidth: if linesofar: tw.line(linesofar) linesofar = ns else: if linesofar: linesofar += ", " + ns else: linesofar = ns if linesofar: tw.line(linesofar) tw.line("")
def getfslineno(obj: object) -> tuple[str | Path, int]: """Return source location (path, lineno) for the given object.
If the source cannot be determined return ("", -1).
The line number is 0-based. """ # xxx let decorators etc specify a sane ordering # NOTE: this used to be done in _pytest.compat.getfslineno, initially added # in 6ec13a2b9. It ("place_as") appears to be something very custom. obj = get_real_func(obj) if hasattr(obj, "place_as"): obj = obj.place_as
try: code = Code.from_function(obj) except TypeError: try: fn = inspect.getsourcefile(obj) or inspect.getfile(obj) # type: ignore[arg-type] except TypeError: return "", -1
fspath = (fn and absolutepath(fn)) or "" lineno = -1 if fspath: try: _, lineno = findsource(obj) except OSError: pass return fspath, lineno
return code.path, code.firstlineno
def _byte_offset_to_character_offset(str, offset): """Converts a byte based offset in a string to a code-point.""" as_utf8 = str.encode("utf-8") return len(as_utf8[:offset].decode("utf-8", errors="replace"))
# Relative paths that we use to filter traceback entries from appearing to the user;# see filter_traceback.# note: if we need to add more paths than what we have now we should probably use a list# for better maintenance.
_PLUGGY_DIR = Path(pluggy.__file__.rstrip("oc"))# pluggy is either a package or a single module depending on the versionif _PLUGGY_DIR.name == "__init__.py": _PLUGGY_DIR = _PLUGGY_DIR.parent_PYTEST_DIR = Path(_pytest.__file__).parent
def filter_traceback(entry: TracebackEntry) -> bool: """Return True if a TracebackEntry instance should be included in tracebacks.
We hide traceback entries of:
* dynamically generated code (no code to show up for it); * internal traceback from pytest or its internal libraries, py and pluggy. """ # entry.path might sometimes return a str object when the entry # points to dynamically generated code. # See https://bitbucket.org/pytest-dev/py/issues/71. raw_filename = entry.frame.code.raw.co_filename is_generated = "<" in raw_filename and ">" in raw_filename if is_generated: return False
# entry.path might point to a non-existing file, in which case it will # also return a str object. See #1133. p = Path(entry.path)
parents = p.parents if _PLUGGY_DIR in parents: return False if _PYTEST_DIR in parents: return False
return True
def filter_excinfo_traceback( tbfilter: TracebackFilter, excinfo: ExceptionInfo[BaseException]) -> Traceback: """Filter the exception traceback in ``excinfo`` according to ``tbfilter``.""" if callable(tbfilter): return tbfilter(excinfo) elif tbfilter: return excinfo.traceback.filter(excinfo) else: return excinfo.traceback123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228# mypy: allow-untyped-defsfrom __future__ import annotations
import astfrom bisect import bisect_rightfrom collections.abc import Iterablefrom collections.abc import Iteratorimport inspectimport textwrapimport tokenizeimport typesfrom typing import overloadimport warnings
class Source: """An immutable object holding a source code fragment.
When using Source(...), the source lines are deindented. """
def __init__(self, obj: object = None) -> None: if not obj: self.lines: list[str] = [] self.raw_lines: list[str] = [] elif isinstance(obj, Source): self.lines = obj.lines self.raw_lines = obj.raw_lines elif isinstance(obj, tuple | list): self.lines = deindent(x.rstrip("\n") for x in obj) self.raw_lines = list(x.rstrip("\n") for x in obj) elif isinstance(obj, str): self.lines = deindent(obj.split("\n")) self.raw_lines = obj.split("\n") else: try: rawcode = getrawcode(obj) src = inspect.getsource(rawcode) except TypeError: src = inspect.getsource(obj) # type: ignore[arg-type] self.lines = deindent(src.split("\n")) self.raw_lines = src.split("\n")
def __eq__(self, other: object) -> bool: if not isinstance(other, Source): return NotImplemented return self.lines == other.lines
# Ignore type because of https://github.com/python/mypy/issues/4266. __hash__ = None # type: ignore
@overload def __getitem__(self, key: int) -> str: ...
@overload def __getitem__(self, key: slice) -> Source: ...
def __getitem__(self, key: int | slice) -> str | Source: if isinstance(key, int): return self.lines[key] else: if key.step not in (None, 1): raise IndexError("cannot slice a Source with a step") newsource = Source() newsource.lines = self.lines[key.start : key.stop] newsource.raw_lines = self.raw_lines[key.start : key.stop] return newsource
def __iter__(self) -> Iterator[str]: return iter(self.lines)
def __len__(self) -> int: return len(self.lines)
def strip(self) -> Source: """Return new Source object with trailing and leading blank lines removed.""" start, end = 0, len(self) while start < end and not self.lines[start].strip(): start += 1 while end > start and not self.lines[end - 1].strip(): end -= 1 source = Source() source.raw_lines = self.raw_lines source.lines[:] = self.lines[start:end] return source
def indent(self, indent: str = " " * 4) -> Source: """Return a copy of the source object with all lines indented by the given indent-string.""" newsource = Source() newsource.raw_lines = self.raw_lines newsource.lines = [(indent + line) for line in self.lines] return newsource
def getstatement(self, lineno: int) -> Source: """Return Source statement which contains the given linenumber (counted from 0).""" start, end = self.getstatementrange(lineno) return self[start:end]
def getstatementrange(self, lineno: int) -> tuple[int, int]: """Return (start, end) tuple which spans the minimal statement region which containing the given lineno.""" if not (0 <= lineno < len(self)): raise IndexError("lineno out of range") _ast, start, end = getstatementrange_ast(lineno, self) return start, end
def deindent(self) -> Source: """Return a new Source object deindented.""" newsource = Source() newsource.lines[:] = deindent(self.lines) newsource.raw_lines = self.raw_lines return newsource
def __str__(self) -> str: return "\n".join(self.lines)
## helper functions#
def findsource(obj) -> tuple[Source | None, int]: try: sourcelines, lineno = inspect.findsource(obj) except Exception: return None, -1 source = Source() source.lines = [line.rstrip() for line in sourcelines] source.raw_lines = sourcelines return source, lineno
def getrawcode(obj: object, trycall: bool = True) -> types.CodeType: """Return code object for given function.""" try: return obj.__code__ # type: ignore[attr-defined,no-any-return] except AttributeError: pass if trycall: call = getattr(obj, "__call__", None) if call and not isinstance(obj, type): return getrawcode(call, trycall=False) raise TypeError(f"could not get code object for {obj!r}")
def deindent(lines: Iterable[str]) -> list[str]: return textwrap.dedent("\n".join(lines)).splitlines()
def get_statement_startend2(lineno: int, node: ast.AST) -> tuple[int, int | None]: # Flatten all statements and except handlers into one lineno-list. # AST's line numbers start indexing at 1. values: list[int] = [] for x in ast.walk(node): if isinstance(x, ast.stmt | ast.ExceptHandler): # The lineno points to the class/def, so need to include the decorators. if isinstance(x, ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef): for d in x.decorator_list: values.append(d.lineno - 1) values.append(x.lineno - 1) for name in ("finalbody", "orelse"): val: list[ast.stmt] | None = getattr(x, name, None) if val: # Treat the finally/orelse part as its own statement. values.append(val[0].lineno - 1 - 1) values.sort() insert_index = bisect_right(values, lineno) if insert_index == 0: return 0, None start = values[insert_index - 1] if insert_index >= len(values): end = None else: end = values[insert_index] return start, end
def getstatementrange_ast( lineno: int, source: Source, assertion: bool = False, astnode: ast.AST | None = None,) -> tuple[ast.AST, int, int]: if astnode is None: content = str(source) # See #4260: # Don't produce duplicate warnings when compiling source to find AST. with warnings.catch_warnings(): warnings.simplefilter("ignore") astnode = ast.parse(content, "source", "exec")
start, end = get_statement_startend2(lineno, astnode) # We need to correct the end: # - ast-parsing strips comments # - there might be empty lines # - we might have lesser indented code blocks at the end if end is None: end = len(source.lines)
if end > start + 1: # Make sure we don't span differently indented code blocks # by using the BlockFinder helper used which inspect.getsource() uses itself. block_finder = inspect.BlockFinder() # If we start with an indented line, put blockfinder to "started" mode. block_finder.started = ( bool(source.lines[start]) and source.lines[start][0].isspace() ) it = ((x + "\n") for x in source.lines[start:end]) try: for tok in tokenize.generate_tokens(lambda: next(it)): block_finder.tokeneater(*tok) except (inspect.EndOfBlock, IndentationError): end = block_finder.last + start except Exception: pass
# The end might still point to a comment or empty line, correct it. end = min(end, len(source.lines)) while end: line = source.lines[end - 1].lstrip() if line.startswith("#") or not line: end -= 1 else: break return astnode, start, end12345678910from __future__ import annotations
from .terminalwriter import get_terminal_widthfrom .terminalwriter import TerminalWriter
__all__ = [ "TerminalWriter", "get_terminal_width",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673# mypy: allow-untyped-defs# This module was imported from the cpython standard library# (https://github.com/python/cpython/) at commit# c5140945c723ae6c4b7ee81ff720ac8ea4b52cfd (python3.12).### Original Author: Fred L. Drake, Jr.# fdrake@acm.org## This is a simple little module I wrote to make life easier. I didn't# see anything quite like it in the library, though I may have overlooked# something. I wrote this when I was trying to read some heavily nested# tuples with fairly non-descriptive content. This is modeled very much# after Lisp/Scheme - style pretty-printing of lists. If you find it# useful, thank small children who sleep at night.from __future__ import annotations
import collections as _collectionsfrom collections.abc import Callablefrom collections.abc import Iteratorimport dataclasses as _dataclassesfrom io import StringIO as _StringIOimport reimport types as _typesfrom typing import Anyfrom typing import IO
class _safe_key: """Helper function for key functions when sorting unorderable objects.
The wrapped-object will fallback to a Py2.x style comparison for unorderable types (sorting first comparing the type name and then by the obj ids). Does not work recursively, so dict.items() must have _safe_key applied to both the key and the value.
"""
__slots__ = ["obj"]
def __init__(self, obj): self.obj = obj
def __lt__(self, other): try: return self.obj < other.obj except TypeError: return (str(type(self.obj)), id(self.obj)) < ( str(type(other.obj)), id(other.obj), )
def _safe_tuple(t): """Helper function for comparing 2-tuples""" return _safe_key(t[0]), _safe_key(t[1])
class PrettyPrinter: def __init__( self, indent: int = 4, width: int = 80, depth: int | None = None, ) -> None: """Handle pretty printing operations onto a stream using a set of configured parameters.
indent Number of spaces to indent for each level of nesting.
width Attempted maximum number of columns in the output.
depth The maximum depth to print out nested structures.
""" if indent < 0: raise ValueError("indent must be >= 0") if depth is not None and depth <= 0: raise ValueError("depth must be > 0") if not width: raise ValueError("width must be != 0") self._depth = depth self._indent_per_level = indent self._width = width
def pformat(self, object: Any) -> str: sio = _StringIO() self._format(object, sio, 0, 0, set(), 0) return sio.getvalue()
def _format( self, object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: objid = id(object) if objid in context: stream.write(_recursion(object)) return
p = self._dispatch.get(type(object).__repr__, None) if p is not None: context.add(objid) p(self, object, stream, indent, allowance, context, level + 1) context.remove(objid) elif ( _dataclasses.is_dataclass(object) and not isinstance(object, type) and object.__dataclass_params__.repr # type:ignore[attr-defined] and # Check dataclass has generated repr method. hasattr(object.__repr__, "__wrapped__") and "__create_fn__" in object.__repr__.__wrapped__.__qualname__ ): context.add(objid) self._pprint_dataclass( object, stream, indent, allowance, context, level + 1 ) context.remove(objid) else: stream.write(self._repr(object, context, level))
def _pprint_dataclass( self, object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: cls_name = object.__class__.__name__ items = [ (f.name, getattr(object, f.name)) for f in _dataclasses.fields(object) if f.repr ] stream.write(cls_name + "(") self._format_namespace_items(items, stream, indent, allowance, context, level) stream.write(")")
_dispatch: dict[ Callable[..., str], Callable[[PrettyPrinter, Any, IO[str], int, int, set[int], int], None], ] = {}
def _pprint_dict( self, object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: write = stream.write write("{") items = object.items() self._format_dict_items(items, stream, indent, allowance, context, level) write("}")
_dispatch[dict.__repr__] = _pprint_dict
def _pprint_ordered_dict( self, object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: if not len(object): stream.write(repr(object)) return cls = object.__class__ stream.write(cls.__name__ + "(") self._pprint_dict(object, stream, indent, allowance, context, level) stream.write(")")
_dispatch[_collections.OrderedDict.__repr__] = _pprint_ordered_dict
def _pprint_list( self, object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: stream.write("[") self._format_items(object, stream, indent, allowance, context, level) stream.write("]")
_dispatch[list.__repr__] = _pprint_list
def _pprint_tuple( self, object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: stream.write("(") self._format_items(object, stream, indent, allowance, context, level) stream.write(")")
_dispatch[tuple.__repr__] = _pprint_tuple
def _pprint_set( self, object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: if not len(object): stream.write(repr(object)) return typ = object.__class__ if typ is set: stream.write("{") endchar = "}" else: stream.write(typ.__name__ + "({") endchar = "})" object = sorted(object, key=_safe_key) self._format_items(object, stream, indent, allowance, context, level) stream.write(endchar)
_dispatch[set.__repr__] = _pprint_set _dispatch[frozenset.__repr__] = _pprint_set
def _pprint_str( self, object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: write = stream.write if not len(object): write(repr(object)) return chunks = [] lines = object.splitlines(True) if level == 1: indent += 1 allowance += 1 max_width1 = max_width = self._width - indent for i, line in enumerate(lines): rep = repr(line) if i == len(lines) - 1: max_width1 -= allowance if len(rep) <= max_width1: chunks.append(rep) else: # A list of alternating (non-space, space) strings parts = re.findall(r"\S*\s*", line) assert parts assert not parts[-1] parts.pop() # drop empty last part max_width2 = max_width current = "" for j, part in enumerate(parts): candidate = current + part if j == len(parts) - 1 and i == len(lines) - 1: max_width2 -= allowance if len(repr(candidate)) > max_width2: if current: chunks.append(repr(current)) current = part else: current = candidate if current: chunks.append(repr(current)) if len(chunks) == 1: write(rep) return if level == 1: write("(") for i, rep in enumerate(chunks): if i > 0: write("\n" + " " * indent) write(rep) if level == 1: write(")")
_dispatch[str.__repr__] = _pprint_str
def _pprint_bytes( self, object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: write = stream.write if len(object) <= 4: write(repr(object)) return parens = level == 1 if parens: indent += 1 allowance += 1 write("(") delim = "" for rep in _wrap_bytes_repr(object, self._width - indent, allowance): write(delim) write(rep) if not delim: delim = "\n" + " " * indent if parens: write(")")
_dispatch[bytes.__repr__] = _pprint_bytes
def _pprint_bytearray( self, object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: write = stream.write write("bytearray(") self._pprint_bytes( bytes(object), stream, indent + 10, allowance + 1, context, level + 1 ) write(")")
_dispatch[bytearray.__repr__] = _pprint_bytearray
def _pprint_mappingproxy( self, object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: stream.write("mappingproxy(") self._format(object.copy(), stream, indent, allowance, context, level) stream.write(")")
_dispatch[_types.MappingProxyType.__repr__] = _pprint_mappingproxy
def _pprint_simplenamespace( self, object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: if type(object) is _types.SimpleNamespace: # The SimpleNamespace repr is "namespace" instead of the class # name, so we do the same here. For subclasses; use the class name. cls_name = "namespace" else: cls_name = object.__class__.__name__ items = object.__dict__.items() stream.write(cls_name + "(") self._format_namespace_items(items, stream, indent, allowance, context, level) stream.write(")")
_dispatch[_types.SimpleNamespace.__repr__] = _pprint_simplenamespace
def _format_dict_items( self, items: list[tuple[Any, Any]], stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: if not items: return
write = stream.write item_indent = indent + self._indent_per_level delimnl = "\n" + " " * item_indent for key, ent in items: write(delimnl) write(self._repr(key, context, level)) write(": ") self._format(ent, stream, item_indent, 1, context, level) write(",")
write("\n" + " " * indent)
def _format_namespace_items( self, items: list[tuple[Any, Any]], stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: if not items: return
write = stream.write item_indent = indent + self._indent_per_level delimnl = "\n" + " " * item_indent for key, ent in items: write(delimnl) write(key) write("=") if id(ent) in context: # Special-case representation of recursion to match standard # recursive dataclass repr. write("...") else: self._format( ent, stream, item_indent + len(key) + 1, 1, context, level, )
write(",")
write("\n" + " " * indent)
def _format_items( self, items: list[Any], stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: if not items: return
write = stream.write item_indent = indent + self._indent_per_level delimnl = "\n" + " " * item_indent
for item in items: write(delimnl) self._format(item, stream, item_indent, 1, context, level) write(",")
write("\n" + " " * indent)
def _repr(self, object: Any, context: set[int], level: int) -> str: return self._safe_repr(object, context.copy(), self._depth, level)
def _pprint_default_dict( self, object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: rdf = self._repr(object.default_factory, context, level) stream.write(f"{object.__class__.__name__}({rdf}, ") self._pprint_dict(object, stream, indent, allowance, context, level) stream.write(")")
_dispatch[_collections.defaultdict.__repr__] = _pprint_default_dict
def _pprint_counter( self, object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: stream.write(object.__class__.__name__ + "(")
if object: stream.write("{") items = object.most_common() self._format_dict_items(items, stream, indent, allowance, context, level) stream.write("}")
stream.write(")")
_dispatch[_collections.Counter.__repr__] = _pprint_counter
def _pprint_chain_map( self, object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: if not len(object.maps) or (len(object.maps) == 1 and not len(object.maps[0])): stream.write(repr(object)) return
stream.write(object.__class__.__name__ + "(") self._format_items(object.maps, stream, indent, allowance, context, level) stream.write(")")
_dispatch[_collections.ChainMap.__repr__] = _pprint_chain_map
def _pprint_deque( self, object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: stream.write(object.__class__.__name__ + "(") if object.maxlen is not None: stream.write(f"maxlen={object.maxlen}, ") stream.write("[")
self._format_items(object, stream, indent, allowance + 1, context, level) stream.write("])")
_dispatch[_collections.deque.__repr__] = _pprint_deque
def _pprint_user_dict( self, object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: self._format(object.data, stream, indent, allowance, context, level - 1)
_dispatch[_collections.UserDict.__repr__] = _pprint_user_dict
def _pprint_user_list( self, object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: self._format(object.data, stream, indent, allowance, context, level - 1)
_dispatch[_collections.UserList.__repr__] = _pprint_user_list
def _pprint_user_string( self, object: Any, stream: IO[str], indent: int, allowance: int, context: set[int], level: int, ) -> None: self._format(object.data, stream, indent, allowance, context, level - 1)
_dispatch[_collections.UserString.__repr__] = _pprint_user_string
def _safe_repr( self, object: Any, context: set[int], maxlevels: int | None, level: int ) -> str: typ = type(object) if typ in _builtin_scalars: return repr(object)
r = getattr(typ, "__repr__", None)
if issubclass(typ, dict) and r is dict.__repr__: if not object: return "{}" objid = id(object) if maxlevels and level >= maxlevels: return "{...}" if objid in context: return _recursion(object) context.add(objid) components: list[str] = [] append = components.append level += 1 for k, v in object.items(): krepr = self._safe_repr(k, context, maxlevels, level) vrepr = self._safe_repr(v, context, maxlevels, level) append(f"{krepr}: {vrepr}") context.remove(objid) return "{{{}}}".format(", ".join(components))
if (issubclass(typ, list) and r is list.__repr__) or ( issubclass(typ, tuple) and r is tuple.__repr__ ): if issubclass(typ, list): if not object: return "[]" format = "[%s]" elif len(object) == 1: format = "(%s,)" else: if not object: return "()" format = "(%s)" objid = id(object) if maxlevels and level >= maxlevels: return format % "..." if objid in context: return _recursion(object) context.add(objid) components = [] append = components.append level += 1 for o in object: orepr = self._safe_repr(o, context, maxlevels, level) append(orepr) context.remove(objid) return format % ", ".join(components)
return repr(object)
_builtin_scalars = frozenset( {str, bytes, bytearray, float, complex, bool, type(None), int})
def _recursion(object: Any) -> str: return f"<Recursion on {type(object).__name__} with id={id(object)}>"
def _wrap_bytes_repr(object: Any, width: int, allowance: int) -> Iterator[str]: current = b"" last = len(object) // 4 * 4 for i in range(0, len(object), 4): part = object[i : i + 4] candidate = current + part if i == last: width -= allowance if len(repr(candidate)) > width: if current: yield repr(current) current = part else: current = candidate if current: yield repr(current)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155from __future__ import annotations
from itertools import isliceimport pprintimport reprlib
def _try_repr_or_str(obj: object) -> str: try: return repr(obj) except (KeyboardInterrupt, SystemExit): raise except BaseException: return f'{type(obj).__name__}("{obj}")'
def _format_repr_exception(exc: BaseException, obj: object) -> str: try: exc_info = _try_repr_or_str(exc) except (KeyboardInterrupt, SystemExit): raise except BaseException as inner_exc: exc_info = f"unpresentable exception ({_try_repr_or_str(inner_exc)})" return ( f"<[{exc_info} raised in repr()] {type(obj).__name__} object at 0x{id(obj):x}>" )
def _ellipsize(s: str, maxsize: int) -> str: if len(s) > maxsize: i = max(0, (maxsize - 3) // 2) j = max(0, maxsize - 3 - i) return s[:i] + "..." + s[len(s) - j :] return s
class SafeRepr(reprlib.Repr): """ repr.Repr that limits the resulting size of repr() and includes information on exceptions raised during the call. """
def __init__(self, maxsize: int | None, use_ascii: bool = False) -> None: """ :param maxsize: If not None, will truncate the resulting repr to that specific size, using ellipsis somewhere in the middle to hide the extra text. If None, will not impose any size limits on the returning repr. """ super().__init__() # ``maxstring`` is used by the superclass, and needs to be an int; using a # very large number in case maxsize is None, meaning we want to disable # truncation. self.maxstring = maxsize if maxsize is not None else 1_000_000_000 self.maxsize = maxsize self.use_ascii = use_ascii
def repr(self, x: object) -> str: try: if self.use_ascii: s = ascii(x) else: s = super().repr(x) except (KeyboardInterrupt, SystemExit): raise except BaseException as exc: s = _format_repr_exception(exc, x) if self.maxsize is not None: s = _ellipsize(s, self.maxsize) return s
def repr_instance(self, x: object, level: int) -> str: try: s = repr(x) except (KeyboardInterrupt, SystemExit): raise except BaseException as exc: s = _format_repr_exception(exc, x) if self.maxsize is not None: s = _ellipsize(s, self.maxsize)
return s
def repr_dict(self, x: dict[object, object], level: int) -> str: """Represent a dict while preserving its insertion order.
Differs from ``reprlib.Repr.repr_dict`` by iterating directly over ``x`` rather than using the stdlib's sorting helper. """ fillvalue = "..." n = len(x) if n == 0: return "{}" if level <= 0: return "{" + fillvalue + "}" newlevel = level - 1 repr1 = self.repr1 pieces = [] for key in islice(x, self.maxdict): keyrepr = repr1(key, newlevel) valrepr = repr1(x[key], newlevel) pieces.append(f"{keyrepr}: {valrepr}") if n > self.maxdict: pieces.append(fillvalue) return "{" + ", ".join(pieces) + "}"
def safeformat(obj: object) -> str: """Return a pretty printed string for the given object.
Failing __repr__ functions of user instances will be represented with a short exception info. """ try: return pprint.pformat(obj) except Exception as exc: return _format_repr_exception(exc, obj)
# Maximum size of overall repr of objects to display during assertion errors.DEFAULT_REPR_MAX_SIZE = 240
def saferepr( obj: object, maxsize: int | None = DEFAULT_REPR_MAX_SIZE, use_ascii: bool = False) -> str: """Return a size-limited safe repr-string for the given object.
Failing __repr__ functions of user instances will be represented with a short exception info and 'saferepr' generally takes care to never raise exceptions itself.
This function is a wrapper around the Repr/reprlib functionality of the stdlib. """ return SafeRepr(maxsize, use_ascii).repr(obj)
def saferepr_unlimited(obj: object, use_ascii: bool = True) -> str: """Return an unlimited-size safe repr-string for the given object.
As with saferepr, failing __repr__ functions of user instances will be represented with a short exception info.
This function is a wrapper around simple repr.
Note: a cleaner solution would be to alter ``saferepr``this way when maxsize=None, but that might affect some other code. """ try: if use_ascii: return ascii(obj) return repr(obj) except Exception as exc: return _format_repr_exception(exc, obj).env.example+38-18
.pytest_cache/.gitignoreAdded+2
.pytest_cache/CACHEDIR.TAGAdded+4
.pytest_cache/README.mdAdded+8
.pytest_cache/v/cache/lastfailedAdded+6
.pytest_cache/v/cache/nodeidsAdded+63
.ruff_cache/.gitignoreAdded+2
.ruff_cache/0.16.9/16425691590624931606Added
.ruff_cache/0.16.9/3813915841381071652Added
.ruff_cache/0.16.9/4599002183323651371Added
.ruff_cache/0.16.9/5957269552066581026Added
.ruff_cache/0.16.9/6488544497621898133Added
.ruff_cache/0.16.9/6758043911225637996Added
.ruff_cache/0.16.9/8632362223362502010Added
.ruff_cache/0.16.9/9797602248524197306Added
.ruff_cache/CACHEDIR.TAGAdded+1
Dockerfile+2-4
Dockerfile.hf+1-2
README.md+60
app/api/routes.py+12-7
app/config.py+61-7
app/models.py+19-1
app/tasks/celery_tasks.py+13-15
app/utils/cache.py+4-30
app/validator/catch_all.py-1
app/validator/dns_check.py+50-11
app/validator/engine.py+173-23
app/validator/mailbox_provider.pyAdded+196
app/validator/scoring.py+95-28
app/validator/smtp_verify.py+1-1
pytest.iniAdded+3
requirements-dev.txtAdded+4
ruff.tomlAdded+4
test_connections.py+14-6
tests/test_bulk_depth.pyAdded+132
tests/test_cache_config.pyAdded+49
tests/test_dns_correctness.pyAdded+95
tests/test_engine_dns_failures.pyAdded+185
tests/test_engine_metadata.pyAdded+318
tests/test_mailbox_provider.pyAdded+151
tests/test_production_config.pyAdded+49
tests/test_scoring_claims.pyAdded+162
venv/Lib/site-packages/_pytest/__init__.pyAdded+13
venv/Lib/site-packages/_pytest/_argcomplete.pyAdded+117
venv/Lib/site-packages/_pytest/_code/__init__.pyAdded+26
venv/Lib/site-packages/_pytest/_code/code.pyAdded+1632
venv/Lib/site-packages/_pytest/_code/source.pyAdded+228
venv/Lib/site-packages/_pytest/_io/__init__.pyAdded+10
venv/Lib/site-packages/_pytest/_io/pprint.pyAdded+673
venv/Lib/site-packages/_pytest/_io/saferepr.pyAdded+155