sitcod3 commited on
Commit
fd7800b
·
verified ·
1 Parent(s): fdadce4

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .env.example +38 -18
  2. .pytest_cache/.gitignore +2 -0
  3. .pytest_cache/CACHEDIR.TAG +4 -0
  4. .pytest_cache/README.md +8 -0
  5. .pytest_cache/v/cache/lastfailed +6 -0
  6. .pytest_cache/v/cache/nodeids +63 -0
  7. .ruff_cache/.gitignore +2 -0
  8. .ruff_cache/0.16.9/16425691590624931606 +0 -0
  9. .ruff_cache/0.16.9/3813915841381071652 +0 -0
  10. .ruff_cache/0.16.9/4599002183323651371 +0 -0
  11. .ruff_cache/0.16.9/5957269552066581026 +0 -0
  12. .ruff_cache/0.16.9/6488544497621898133 +0 -0
  13. .ruff_cache/0.16.9/6758043911225637996 +0 -0
  14. .ruff_cache/0.16.9/8632362223362502010 +0 -0
  15. .ruff_cache/0.16.9/9797602248524197306 +0 -0
  16. .ruff_cache/CACHEDIR.TAG +1 -0
  17. Dockerfile +2 -4
  18. Dockerfile.hf +1 -2
  19. README.md +60 -0
  20. app/api/routes.py +12 -7
  21. app/config.py +61 -7
  22. app/models.py +19 -1
  23. app/tasks/celery_tasks.py +13 -15
  24. app/utils/cache.py +4 -30
  25. app/validator/catch_all.py +0 -1
  26. app/validator/dns_check.py +50 -11
  27. app/validator/engine.py +173 -23
  28. app/validator/mailbox_provider.py +196 -0
  29. app/validator/scoring.py +95 -28
  30. app/validator/smtp_verify.py +1 -1
  31. pytest.ini +3 -0
  32. requirements-dev.txt +4 -0
  33. ruff.toml +4 -0
  34. test_connections.py +14 -6
  35. tests/test_bulk_depth.py +132 -0
  36. tests/test_cache_config.py +49 -0
  37. tests/test_dns_correctness.py +95 -0
  38. tests/test_engine_dns_failures.py +185 -0
  39. tests/test_engine_metadata.py +318 -0
  40. tests/test_mailbox_provider.py +151 -0
  41. tests/test_production_config.py +49 -0
  42. tests/test_scoring_claims.py +162 -0
  43. venv/Lib/site-packages/_pytest/__init__.py +13 -0
  44. venv/Lib/site-packages/_pytest/_argcomplete.py +117 -0
  45. venv/Lib/site-packages/_pytest/_code/__init__.py +26 -0
  46. venv/Lib/site-packages/_pytest/_code/code.py +1632 -0
  47. venv/Lib/site-packages/_pytest/_code/source.py +228 -0
  48. venv/Lib/site-packages/_pytest/_io/__init__.py +10 -0
  49. venv/Lib/site-packages/_pytest/_io/pprint.py +673 -0
  50. venv/Lib/site-packages/_pytest/_io/saferepr.py +155 -0
.env.example CHANGED
@@ -1,35 +1,55 @@
1
- # Copy to .env and adjust for your environment
2
- APP_NAME="EmailValidator Pro"
3
- APP_VERSION="2.0.0"
 
4
  DEBUG=true
5
- SECRET_KEY=change-me-in-production
6
  HOST=0.0.0.0
7
  PORT=8000
8
  WORKERS=4
9
- # --- Supabase (Postgres + PostgREST) ---
 
10
  SUPABASE_URL=https://YOUR_PROJECT_REF.supabase.co
11
- SUPABASE_ANON_KEY=your-public-anon-key # safe for browser (RLS governs access)
12
- SUPABASE_SERVICE_ROLE_KEY=your-service-role-key # server-only, bypasses RLS
13
  ENABLE_DB_PERSISTENCE=true
 
14
 
15
- # Local dev DB fallback (not used when Supabase is configured)
16
  DATABASE_URL=sqlite+aiosqlite:///./emailval.db
17
  REDIS_URL=redis://localhost:6379/0
18
  REDIS_CACHE_TTL=86400
19
- # Upstash rediss:// URLs need ?ssl_cert_reqs=none (Celery requires the param):
20
- # rediss://default:TOKEN@host.upstash.io:6379/0?ssl_cert_reqs=none
21
- # Free-tier (/start-redis) databases support ONLY db 0 — use one database per
22
- # logical store (cache, celery broker, celery result backend).
 
 
 
 
 
 
 
 
23
 
24
- # --- Upstash Developer API (provision Redis databases) ---
25
- # Create a key at: https://console.upstash.com/account/api
26
- UPSTASH_MANAGEMENT_KEY=
27
- UPSTASH_ACCOUNT_EMAIL=
28
  CORS_ORIGINS=["http://localhost:5173","http://localhost:3000","http://127.0.0.1:5173"]
29
  SMTP_TIMEOUT=10
30
  DNS_TIMEOUT=5
31
  MAX_BULK_EMAILS=10000
32
  RATE_LIMIT_PER_MINUTE=60
33
  USE_PROXIES=false
34
- CELERY_BROKER_URL=redis://localhost:6379/1
35
- CELERY_RESULT_BACKEND=redis://localhost:6379/2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copy to .env and adjust for your environment.
2
+ APP_ENVIRONMENT=development
3
+ APP_NAME="BRIDGE Modul - X"
4
+ APP_VERSION="2.1.0"
5
  DEBUG=true
6
+ SECRET_KEY=replace-with-a-random-secret
7
  HOST=0.0.0.0
8
  PORT=8000
9
  WORKERS=4
10
+
11
+ # Supabase (server-side service-role key; never expose it to the browser)
12
  SUPABASE_URL=https://YOUR_PROJECT_REF.supabase.co
13
+ SUPABASE_ANON_KEY=your-public-anon-key
14
+ SUPABASE_SERVICE_ROLE_KEY=your-server-only-service-role-key
15
  ENABLE_DB_PERSISTENCE=true
16
+ LICENSE_ENFORCEMENT=false
17
 
18
+ # Local development defaults
19
  DATABASE_URL=sqlite+aiosqlite:///./emailval.db
20
  REDIS_URL=redis://localhost:6379/0
21
  REDIS_CACHE_TTL=86400
22
+ CELERY_BROKER_URL=redis://localhost:6379/1
23
+ CELERY_RESULT_BACKEND=redis://localhost:6379/2
24
+
25
+ # For Upstash, use TLS and database index /0:
26
+ # REDIS_URL=rediss://default:YOUR_REDIS_TOKEN@YOUR_ENDPOINT:6379/0
27
+ # CELERY_BROKER_URL=rediss://default:YOUR_REDIS_TOKEN@YOUR_ENDPOINT:6379/0
28
+ # CELERY_RESULT_BACKEND=rediss://default:YOUR_REDIS_TOKEN@YOUR_ENDPOINT:6379/0
29
+ # Never disable TLS certificate verification. Upstash Free has one database;
30
+ # prove Celery key-prefix isolation and compatibility before sharing it, or
31
+ # use separate provisioned databases/a suitable paid plan for production jobs.
32
+ # The app does not need the Upstash Developer API key. Keep it out of runtime
33
+ # environment variables; use it only from a restricted operator workflow.
34
 
 
 
 
 
35
  CORS_ORIGINS=["http://localhost:5173","http://localhost:3000","http://127.0.0.1:5173"]
36
  SMTP_TIMEOUT=10
37
  DNS_TIMEOUT=5
38
  MAX_BULK_EMAILS=10000
39
  RATE_LIMIT_PER_MINUTE=60
40
  USE_PROXIES=false
41
+
42
+ # --- Mailbox verification provider (Layers 5 + 6) ---
43
+ # Hugging Face Spaces blocks outbound port 25, so direct SMTP + catch-all
44
+ # cannot run there. Set MV_API_KEY to delegate those layers to MillionVerifier.
45
+ # auto (default): use the API when MV_API_KEY is set, else direct SMTP
46
+ # api : force the verification API
47
+ # local : force direct SMTP (requires port-25 egress)
48
+ MAILBOX_PROVIDER=auto
49
+ MV_API_KEY=
50
+ MV_TIMEOUT=10
51
+ # Circuit breaker for direct SMTP on a blocked host: after N consecutive
52
+ # connection failures, fail fast for the cooldown instead of burning timeout
53
+ # per address.
54
+ SMTP_FAIL_THRESHOLD=3
55
+ SMTP_COOLDOWN_SECONDS=300
.pytest_cache/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Created by pytest automatically.
2
+ *
.pytest_cache/CACHEDIR.TAG ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Signature: 8a477f597d28d172789f06886806bc55
2
+ # This file is a cache directory tag created by pytest.
3
+ # For information about cache directory tags, see:
4
+ # https://bford.info/cachedir/spec.html
.pytest_cache/README.md ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ # pytest cache directory #
2
+
3
+ This directory contains data from the pytest's cache plugin,
4
+ which provides the `--lf` and `--ff` options, as well as the `cache` fixture.
5
+
6
+ **Do not** commit this to version control.
7
+
8
+ See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information.
.pytest_cache/v/cache/lastfailed ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ {
2
+ "test_connections.py::test_supabase": true,
3
+ "test_connections.py::test_redis": true,
4
+ "test_connections.py::test_celery": true,
5
+ "test_connections.py::test_validation_engine": true
6
+ }
.pytest_cache/v/cache/nodeids ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ "test_connections.py::test_celery",
3
+ "test_connections.py::test_redis",
4
+ "test_connections.py::test_supabase",
5
+ "test_connections.py::test_validation_engine",
6
+ "tests/test_bulk_depth.py::BulkDepthTests::test_engine_deep_runs_catch_all_and_smtp",
7
+ "tests/test_bulk_depth.py::BulkDepthTests::test_injected_mailbox_provider_is_used_for_deep",
8
+ "tests/test_bulk_depth.py::BulkDepthTests::test_process_bulk_sync_runs_deep_layers",
9
+ "tests/test_bulk_depth.py::BulkRequestDeepFieldTests::test_bulk_request_accepts_deep_flag",
10
+ "tests/test_bulk_depth.py::BulkRequestDeepFieldTests::test_bulk_request_defaults_deep_true",
11
+ "tests/test_cache_config.py::RedisConfigurationTests::test_explicit_upstash_tls_url_is_used",
12
+ "tests/test_cache_config.py::RedisConfigurationTests::test_missing_redis_does_not_create_cloud_database",
13
+ "tests/test_dns_correctness.py::DNSCheckTests::test_a_record_fallback_is_preserved",
14
+ "tests/test_dns_correctness.py::DNSCheckTests::test_no_mx_or_address_is_distinct_from_transient_dns_error",
15
+ "tests/test_dns_correctness.py::DNSCheckTests::test_no_nameservers_is_reported_as_transient",
16
+ "tests/test_dns_correctness.py::DNSCheckTests::test_nxdomain_is_reported_as_definitive",
17
+ "tests/test_dns_correctness.py::DNSCheckTests::test_timeout_is_reported_as_transient",
18
+ "tests/test_engine_dns_failures.py::EngineDNSFailureTests::test_a_record_fallback_is_risky_even_if_smtp_accepts",
19
+ "tests/test_engine_dns_failures.py::EngineDNSFailureTests::test_domain_without_mail_routes_is_invalid",
20
+ "tests/test_engine_dns_failures.py::EngineDNSFailureTests::test_fast_mode_does_not_claim_mailbox_validity",
21
+ "tests/test_engine_dns_failures.py::EngineDNSFailureTests::test_logs_mask_local_part",
22
+ "tests/test_engine_dns_failures.py::EngineDNSFailureTests::test_status_thresholds_match_risk_score_bands",
23
+ "tests/test_engine_dns_failures.py::EngineDNSFailureTests::test_transient_dns_failure_is_risky_without_smtp",
24
+ "tests/test_engine_dns_failures.py::EngineDNSFailureTests::test_transient_dns_failure_is_unknown_without_smtp",
25
+ "tests/test_engine_metadata.py::CatchAllUnknownTests::test_catch_all_exception_is_unknown_not_false",
26
+ "tests/test_engine_metadata.py::CatchAllUnknownTests::test_catch_all_probe_unavailable_is_unknown_not_false",
27
+ "tests/test_engine_metadata.py::EngineMetadataTests::test_deep_result_emits_provenance_fields",
28
+ "tests/test_engine_metadata.py::EngineMetadataTests::test_fast_mode_checks_run_excludes_mailbox_layers",
29
+ "tests/test_engine_metadata.py::EngineMetadataTests::test_reason_code_catch_all",
30
+ "tests/test_engine_metadata.py::EngineMetadataTests::test_reason_code_dns_timeout",
31
+ "tests/test_engine_metadata.py::EngineMetadataTests::test_reason_code_nxdomain",
32
+ "tests/test_engine_metadata.py::EngineMetadataTests::test_reason_code_smtp_timeout",
33
+ "tests/test_engine_metadata.py::ScoreCoherenceTests::test_smtp_verified_can_reach_high_score",
34
+ "tests/test_engine_metadata.py::ScoreCoherenceTests::test_unverified_mailbox_never_scores_100",
35
+ "tests/test_mailbox_provider.py::CircuitBreakerTests::test_circuit_closes_after_cooldown",
36
+ "tests/test_mailbox_provider.py::CircuitBreakerTests::test_local_provider_opens_circuit_after_threshold",
37
+ "tests/test_mailbox_provider.py::CircuitBreakerTests::test_open_circuit_returns_immediately_unavailable",
38
+ "tests/test_mailbox_provider.py::CircuitBreakerTests::test_zero_cooldown_never_stays_open",
39
+ "tests/test_mailbox_provider.py::MapMVResultTests::test_catch_all_maps_to_inconclusive",
40
+ "tests/test_mailbox_provider.py::MapMVResultTests::test_error_maps_to_inconclusive_with_error",
41
+ "tests/test_mailbox_provider.py::MapMVResultTests::test_invalid_maps_to_rejected_5xx",
42
+ "tests/test_mailbox_provider.py::MapMVResultTests::test_ok_maps_to_verified",
43
+ "tests/test_mailbox_provider.py::MapMVResultTests::test_unknown_maps_to_inconclusive",
44
+ "tests/test_mailbox_provider.py::MillionVerifierProviderTests::test_catch_all_probe_gibberish_not_real_address",
45
+ "tests/test_mailbox_provider.py::MillionVerifierProviderTests::test_verify_calls_api_with_email_and_key",
46
+ "tests/test_mailbox_provider.py::ResolveProviderTests::test_api_forced",
47
+ "tests/test_mailbox_provider.py::ResolveProviderTests::test_auto_with_key_uses_api",
48
+ "tests/test_mailbox_provider.py::ResolveProviderTests::test_auto_without_key_uses_local",
49
+ "tests/test_mailbox_provider.py::ResolveProviderTests::test_local_forced",
50
+ "tests/test_mailbox_provider.py::ResolveProviderTests::test_provider_satisfies_protocol",
51
+ "tests/test_production_config.py::ProductionSettingsTests::test_development_keeps_demo_configuration_available",
52
+ "tests/test_production_config.py::ProductionSettingsTests::test_production_accepts_explicit_secure_configuration",
53
+ "tests/test_production_config.py::ProductionSettingsTests::test_production_rejects_demo_or_insecure_configuration",
54
+ "tests/test_scoring_claims.py::ScoringClaimTests::test_catch_all_never_receives_a_low_risk_score",
55
+ "tests/test_scoring_claims.py::ScoringClaimTests::test_disposable_domain_is_invalid",
56
+ "tests/test_scoring_claims.py::ScoringClaimTests::test_explicit_mailbox_unknown_is_a_zero_score_hard_failure",
57
+ "tests/test_scoring_claims.py::ScoringClaimTests::test_generic_smtp_550_does_not_claim_mailbox_is_nonexistent",
58
+ "tests/test_scoring_claims.py::ScoringClaimTests::test_inconclusive_smtp_is_medium_risk_not_an_implicit_pass",
59
+ "tests/test_scoring_claims.py::ScoringClaimTests::test_legacy_user_unknown_rejection_is_detected_without_enhanced_code",
60
+ "tests/test_scoring_claims.py::ScoringClaimTests::test_missing_mail_routes_is_a_zero_score_hard_failure",
61
+ "tests/test_scoring_claims.py::ScoringClaimTests::test_role_based_address_never_receives_a_low_risk_score",
62
+ "tests/test_scoring_claims.py::ScoringClaimTests::test_transient_dns_has_fixed_medium_risk_score_and_audit_code"
63
+ ]
.ruff_cache/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # Automatically created by ruff.
2
+ *
.ruff_cache/0.16.9/16425691590624931606 ADDED
Binary file (412 Bytes). View file
 
.ruff_cache/0.16.9/3813915841381071652 ADDED
Binary file (1.72 kB). View file
 
.ruff_cache/0.16.9/4599002183323651371 ADDED
Binary file (1.72 kB). View file
 
.ruff_cache/0.16.9/5957269552066581026 ADDED
Binary file (1.72 kB). View file
 
.ruff_cache/0.16.9/6488544497621898133 ADDED
Binary file (412 Bytes). View file
 
.ruff_cache/0.16.9/6758043911225637996 ADDED
Binary file (332 Bytes). View file
 
.ruff_cache/0.16.9/8632362223362502010 ADDED
Binary file (412 Bytes). View file
 
.ruff_cache/0.16.9/9797602248524197306 ADDED
Binary file (468 Bytes). View file
 
.ruff_cache/CACHEDIR.TAG ADDED
@@ -0,0 +1 @@
 
 
1
+ Signature: 8a477f597d28d172789f06886806bc55
Dockerfile CHANGED
@@ -6,17 +6,15 @@ WORKDIR /app
6
  RUN apt-get update && apt-get install -y --no-install-recommends \
7
  curl \
8
  build-essential \
9
- redis-server \
10
  && rm -rf /var/lib/apt/lists/*
11
 
12
  # Install Python dependencies
13
  COPY requirements.txt .
14
  RUN pip install --no-cache-dir -r requirements.txt
15
 
16
- # Copy app source + container entrypoint (local Redis sidecar, supervises worker)
17
  COPY app/ ./app/
18
- COPY entrypoint.py .
19
 
20
  EXPOSE 7860
21
 
22
- CMD ["python", "entrypoint.py"]
 
6
  RUN apt-get update && apt-get install -y --no-install-recommends \
7
  curl \
8
  build-essential \
 
9
  && rm -rf /var/lib/apt/lists/*
10
 
11
  # Install Python dependencies
12
  COPY requirements.txt .
13
  RUN pip install --no-cache-dir -r requirements.txt
14
 
15
+ # Copy app source
16
  COPY app/ ./app/
 
17
 
18
  EXPOSE 7860
19
 
20
+ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
Dockerfile.hf CHANGED
@@ -6,7 +6,6 @@ WORKDIR /app
6
  RUN apt-get update && apt-get install -y --no-install-recommends \
7
  curl \
8
  build-essential \
9
- redis-server \
10
  && rm -rf /var/lib/apt/lists/*
11
 
12
  # Install Python dependencies
@@ -17,4 +16,4 @@ COPY . .
17
 
18
  EXPOSE 7860
19
 
20
- CMD ["python", "entrypoint.py"]
 
6
  RUN apt-get update && apt-get install -y --no-install-recommends \
7
  curl \
8
  build-essential \
 
9
  && rm -rf /var/lib/apt/lists/*
10
 
11
  # Install Python dependencies
 
16
 
17
  EXPOSE 7860
18
 
19
+ CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"]
README.md CHANGED
@@ -11,3 +11,63 @@ pinned: false
11
  # BRIDGE Modul X — Email Validation API
12
 
13
  7-layer email validation engine powered by FastAPI.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  # BRIDGE Modul X — Email Validation API
12
 
13
  7-layer email validation engine powered by FastAPI.
14
+
15
+ ## Runtime configuration
16
+
17
+ Copy `.env.example` to `.env` for local development and replace placeholder
18
+ values locally. Redis is optional for the API cache: the application does not
19
+ create or claim cloud databases automatically. If no Redis URL is configured
20
+ or Redis is unavailable, cache operations use the in-memory TTL fallback.
21
+
22
+ For Upstash, use the database's TLS `rediss://` connection URL with database
23
+ index `/0`; do not disable certificate verification. The Upstash Developer API
24
+ key manages resources and is not needed by the app runtime. Keep it out of
25
+ `.env` files and deployment secrets unless an isolated operator tool explicitly
26
+ needs it. Upstash Free's single-database limit does not imply Celery broker and
27
+ result-backend compatibility; verify key-prefix isolation and real worker
28
+ round-trips before enabling production bulk jobs.
29
+
30
+ `Dockerfile.hf` starts the FastAPI web process only. A Celery worker must be
31
+ deployed and supervised separately before asynchronous bulk processing is
32
+ considered available. A Redis ping alone is not a worker readiness check.
33
+
34
+ ## Scoring contract
35
+
36
+ Scores use `0-39` for high risk/invalid, `40-74` for medium risk/risky, and
37
+ `75-100` for low risk/valid. A transient DNS lookup returns a fixed score of
38
+ `50` and `DNS_TRANSIENT_FAILURE: -50`; fast mode applies
39
+ `FAST_MODE_SKIPPED_MAILBOX_CHECK: -30` and caps the result at `70`. Missing mail
40
+ routes, disposable domains, syntax failures, and a specific SMTP `550 5.1.1`
41
+ mailbox-not-found response (or an explicit legacy `550 User Unknown` response)
42
+ score `0`. Catch-all and role-based results are capped at `74`. A generic SMTP
43
+ `550`, SMTP connection failure, or other inconclusive probe is not treated as
44
+ proof that a mailbox does not exist; inconclusive SMTP is capped at `70`.
45
+
46
+ ## Production configuration gate
47
+
48
+ Set `APP_ENVIRONMENT=production` in the live deployment. Startup then fails
49
+ closed unless `DEBUG=false`, `LICENSE_ENFORCEMENT=true`, Supabase URL and
50
+ service-role credentials are configured, and every `CORS_ORIGINS` entry is an
51
+ HTTPS origin. Keep service-role credentials in the platform's secret store,
52
+ never in source control or frontend variables. Keep development settings
53
+ (`APP_ENVIRONMENT=development`, localhost CORS, demo licensing) local only.
54
+
55
+ ## Backend checks
56
+
57
+ From this directory, install the development dependencies into the project
58
+ virtual environment and run the test, lint, and compile checks:
59
+
60
+ ```powershell
61
+ .\venv\Scripts\python.exe -m pip install -r requirements-dev.txt
62
+ .\venv\Scripts\python.exe -m pytest --collect-only -q
63
+ .\venv\Scripts\python.exe -m pytest -q
64
+ .\venv\Scripts\python.exe -m ruff check app tests
65
+ .\venv\Scripts\python.exe -m compileall -q app tests
66
+ ```
67
+
68
+ Use the project virtual environment for these commands. Running tests with a
69
+ different system Python can fail during collection even when the backend
70
+ dependencies are installed in `venv`. `pytest.ini` limits collection to the
71
+ unit-test directory so `test_connections.py` remains a manually invoked,
72
+ environment-dependent integration diagnostic and does not contact live
73
+ services during CI.
app/api/routes.py CHANGED
@@ -1,6 +1,7 @@
1
- from fastapi import APIRouter, HTTPException, Request, Query, BackgroundTasks
2
  from fastapi.responses import JSONResponse
3
- import json, time
 
4
  import asyncio
5
 
6
  from ..models import (
@@ -16,18 +17,22 @@ from ..db import repo
16
  router = APIRouter()
17
 
18
 
19
- async def process_bulk_sync(emails: list, webhook_url: str = None) -> dict:
20
  """
21
  Process bulk validation synchronously in chunks.
22
  Used when Celery is unavailable.
 
 
 
 
23
  """
24
  results = []
25
  total = len(emails)
26
  chunk_size = settings.bulk_sync_chunk_size # Configurable chunk size
27
-
28
  for i in range(0, total, chunk_size):
29
  chunk = emails[i:i + chunk_size]
30
- tasks = [engine.validate(email, deep=False) for email in chunk]
31
  chunk_results = await asyncio.gather(*tasks, return_exceptions=True)
32
 
33
  for email, result in zip(chunk, chunk_results):
@@ -119,7 +124,7 @@ async def validate_bulk(request: BulkEmailRequest):
119
  if use_celery:
120
  try:
121
  from ..tasks.celery_tasks import bulk_validate_task
122
- task = bulk_validate_task.delay(request.emails, request.webhook_url)
123
  # Record the job in Supabase so it can be tracked across restarts
124
  if settings.enable_db_persistence:
125
  repo.create_bulk_job(task.id, request.emails)
@@ -134,7 +139,7 @@ async def validate_bulk(request: BulkEmailRequest):
134
 
135
  # Synchronous fallback for any size list (removed ≤100 limit)
136
  print(f"[BULK] Processing {len(request.emails)} emails synchronously (Celery unavailable)")
137
- results = await process_bulk_sync(request.emails, request.webhook_url)
138
 
139
  if settings.enable_db_persistence:
140
  repo.finish_bulk_job("sync", results)
 
1
+ from fastapi import APIRouter, HTTPException, Query
2
  from fastapi.responses import JSONResponse
3
+ import json
4
+ import time
5
  import asyncio
6
 
7
  from ..models import (
 
17
  router = APIRouter()
18
 
19
 
20
+ async def process_bulk_sync(emails: list, webhook_url: str = None, deep: bool = True) -> dict:
21
  """
22
  Process bulk validation synchronously in chunks.
23
  Used when Celery is unavailable.
24
+
25
+ `deep` defaults to True so bulk runs the full 7-layer pipeline (catch-all +
26
+ SMTP) exactly like single verification — the product charges 1 credit/email
27
+ and must not silently degrade to a syntax+DNS-only check.
28
  """
29
  results = []
30
  total = len(emails)
31
  chunk_size = settings.bulk_sync_chunk_size # Configurable chunk size
32
+
33
  for i in range(0, total, chunk_size):
34
  chunk = emails[i:i + chunk_size]
35
+ tasks = [engine.validate(email, deep=deep) for email in chunk]
36
  chunk_results = await asyncio.gather(*tasks, return_exceptions=True)
37
 
38
  for email, result in zip(chunk, chunk_results):
 
124
  if use_celery:
125
  try:
126
  from ..tasks.celery_tasks import bulk_validate_task
127
+ task = bulk_validate_task.delay(request.emails, request.webhook_url, request.deep)
128
  # Record the job in Supabase so it can be tracked across restarts
129
  if settings.enable_db_persistence:
130
  repo.create_bulk_job(task.id, request.emails)
 
139
 
140
  # Synchronous fallback for any size list (removed ≤100 limit)
141
  print(f"[BULK] Processing {len(request.emails)} emails synchronously (Celery unavailable)")
142
+ results = await process_bulk_sync(request.emails, request.webhook_url, deep=request.deep)
143
 
144
  if settings.enable_db_persistence:
145
  repo.finish_bulk_job("sync", results)
app/config.py CHANGED
@@ -1,7 +1,27 @@
 
 
 
1
  from pydantic_settings import BaseSettings, SettingsConfigDict
2
  from typing import List
3
 
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  class Settings(BaseSettings):
6
  model_config = SettingsConfigDict(
7
  env_file=".env",
@@ -11,9 +31,10 @@ class Settings(BaseSettings):
11
  )
12
 
13
  # App
 
14
  app_name: str = "BRIDGE Modul - X"
15
- app_version: str = "2.1.0"
16
- debug: bool = True
17
  secret_key: str = "change-me-in-production"
18
 
19
  # Server
@@ -28,15 +49,11 @@ class Settings(BaseSettings):
28
  redis_url: str = "redis://localhost:6379/0"
29
  redis_cache_ttl: int = 86400 # 24 hours
30
 
31
- # Upstash Developer API (for provisioning/managing Redis databases)
32
- upstash_management_key: str = ""
33
- upstash_account_email: str = ""
34
-
35
  # CORS
36
  cors_origins: List[str] = [
37
  "http://localhost:5173",
38
  "http://localhost:3000",
39
- "http://127.0.0.1:5173"
40
  ]
41
 
42
  # Validation
@@ -50,6 +67,20 @@ class Settings(BaseSettings):
50
  use_proxies: bool = False
51
  proxy_list: List[str] = []
52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  # Celery
54
  celery_broker_url: str = "redis://localhost:6379/1"
55
  celery_result_backend: str = "redis://localhost:6379/2"
@@ -65,6 +96,29 @@ class Settings(BaseSettings):
65
  # on every paid API route. Anything else = open demo mode.
66
  license_enforcement: str = ""
67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
  @property
69
  def supabase_configured(self) -> bool:
70
  return bool(self.supabase_url and self.supabase_service_role_key)
 
1
+ from urllib.parse import urlsplit
2
+
3
+ from pydantic import model_validator
4
  from pydantic_settings import BaseSettings, SettingsConfigDict
5
  from typing import List
6
 
7
 
8
+ def _is_https_origin(value: str) -> bool:
9
+ try:
10
+ parsed = urlsplit(value)
11
+ _ = parsed.port
12
+ except ValueError:
13
+ return False
14
+ return (
15
+ parsed.scheme == "https"
16
+ and bool(parsed.hostname)
17
+ and parsed.username is None
18
+ and parsed.password is None
19
+ and parsed.path in {"", "/"}
20
+ and not parsed.query
21
+ and not parsed.fragment
22
+ )
23
+
24
+
25
  class Settings(BaseSettings):
26
  model_config = SettingsConfigDict(
27
  env_file=".env",
 
31
  )
32
 
33
  # App
34
+ app_environment: str = "development"
35
  app_name: str = "BRIDGE Modul - X"
36
+ app_version: str = "2.2.0"
37
+ debug: bool = False
38
  secret_key: str = "change-me-in-production"
39
 
40
  # Server
 
49
  redis_url: str = "redis://localhost:6379/0"
50
  redis_cache_ttl: int = 86400 # 24 hours
51
 
 
 
 
 
52
  # CORS
53
  cors_origins: List[str] = [
54
  "http://localhost:5173",
55
  "http://localhost:3000",
56
+ "http://127.0.0.1:5173",
57
  ]
58
 
59
  # Validation
 
67
  use_proxies: bool = False
68
  proxy_list: List[str] = []
69
 
70
+ # Mailbox verification provider (Layer 5 catch-all + Layer 6 SMTP).
71
+ # On hosts that block outbound port 25 (Hugging Face Spaces, most cloud),
72
+ # direct SMTP cannot run — so the mailbox verdict is delegated to a
73
+ # third-party verification API instead. "auto" uses the API when an API key
74
+ # is present, else falls back to direct SMTP. "local"/"api" force a provider.
75
+ mailbox_provider: str = "auto" # auto | local | api
76
+ mv_api_key: str = "" # MillionVerifier real-time API key
77
+ mv_timeout: int = 10 # per-check provider timeout (seconds)
78
+ # Circuit breaker: after this many consecutive direct-SMTP connection
79
+ # failures (blocked egress), fail fast for `smtp_cooldown_seconds` instead
80
+ # of burning the full timeout on every address.
81
+ smtp_fail_threshold: int = 3
82
+ smtp_cooldown_seconds: int = 300
83
+
84
  # Celery
85
  celery_broker_url: str = "redis://localhost:6379/1"
86
  celery_result_backend: str = "redis://localhost:6379/2"
 
96
  # on every paid API route. Anything else = open demo mode.
97
  license_enforcement: str = ""
98
 
99
+ @model_validator(mode="after")
100
+ def validate_production_settings(self) -> "Settings":
101
+ if self.app_environment.strip().casefold() != "production":
102
+ return self
103
+
104
+ problems = []
105
+ if self.debug:
106
+ problems.append("DEBUG must be false")
107
+ if self.license_enforcement.strip().casefold() != "true":
108
+ problems.append("LICENSE_ENFORCEMENT must be true")
109
+ if not self.supabase_configured:
110
+ problems.append("SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY are required")
111
+ elif not _is_https_origin(self.supabase_url):
112
+ problems.append("SUPABASE_URL must be an HTTPS URL")
113
+ if not self.cors_origins or not all(
114
+ _is_https_origin(origin) for origin in self.cors_origins
115
+ ):
116
+ problems.append("CORS_ORIGINS must contain only HTTPS origins")
117
+
118
+ if problems:
119
+ raise ValueError("Unsafe production configuration: " + "; ".join(problems))
120
+ return self
121
+
122
  @property
123
  def supabase_configured(self) -> bool:
124
  return bool(self.supabase_url and self.supabase_service_role_key)
app/models.py CHANGED
@@ -30,12 +30,14 @@ class DNSResult(BaseModel):
30
  domain_exists: bool
31
  has_mx_records: bool
32
  mx_records: List[Dict[str, Any]] = []
 
33
  has_spf: bool = False
34
  spf_record: Optional[str] = None
35
  has_dmarc: bool = False
36
  dmarc_record: Optional[str] = None
37
  has_dkim: bool = False
38
  error: Optional[str] = None
 
39
 
40
 
41
  class DisposableResult(BaseModel):
@@ -46,7 +48,10 @@ class DisposableResult(BaseModel):
46
 
47
 
48
  class CatchAllResult(BaseModel):
49
- is_catch_all: bool
 
 
 
50
  confidence: float = 0.0
51
  error: Optional[str] = None
52
 
@@ -80,6 +85,14 @@ class ValidationResult(BaseModel):
80
  scoring: ScoringResult
81
  processing_time_ms: float
82
  validated_at: str
 
 
 
 
 
 
 
 
83
 
84
 
85
  class SingleEmailRequest(BaseModel):
@@ -94,6 +107,11 @@ class SingleEmailRequest(BaseModel):
94
  class BulkEmailRequest(BaseModel):
95
  emails: List[str]
96
  webhook_url: Optional[str] = None
 
 
 
 
 
97
 
98
  @field_validator("emails")
99
  @classmethod
 
30
  domain_exists: bool
31
  has_mx_records: bool
32
  mx_records: List[Dict[str, Any]] = []
33
+ a_fallback: bool = False
34
  has_spf: bool = False
35
  spf_record: Optional[str] = None
36
  has_dmarc: bool = False
37
  dmarc_record: Optional[str] = None
38
  has_dkim: bool = False
39
  error: Optional[str] = None
40
+ error_code: Optional[str] = None
41
 
42
 
43
  class DisposableResult(BaseModel):
 
48
 
49
 
50
  class CatchAllResult(BaseModel):
51
+ # None = the catch-all probe could not run (e.g. port-25 egress blocked on
52
+ # this host). It must NEVER be coerced to False, which would falsely claim
53
+ # "domain rejects unknown recipients".
54
+ is_catch_all: Optional[bool] = None
55
  confidence: float = 0.0
56
  error: Optional[str] = None
57
 
 
85
  scoring: ScoringResult
86
  processing_time_ms: float
87
  validated_at: str
88
+ # Provenance the frontend contract expects (src/lib/verifier.ts classify()).
89
+ # checks_run lists the 7-layer taxonomy keys that actually executed; an
90
+ # unchecked layer must never read as a pass. reason_code is a machine cause
91
+ # for Unknown/risky rows. run_id correlates a single + its bulk chunk.
92
+ checks_run: List[str] = []
93
+ reason_code: Optional[str] = None
94
+ run_id: Optional[str] = None
95
+ validator_version: Optional[str] = None
96
 
97
 
98
  class SingleEmailRequest(BaseModel):
 
107
  class BulkEmailRequest(BaseModel):
108
  emails: List[str]
109
  webhook_url: Optional[str] = None
110
+ # Product promise: bulk runs the SAME 7-layer pipeline as single (1 credit
111
+ # per email). deep=False skips catch-all + SMTP, which collapsed every bulk
112
+ # row to "Unknown / insufficient depth" — so it defaults to True and is only
113
+ # flipped off by an explicit caller that accepts the reduced verdict.
114
+ deep: bool = True
115
 
116
  @field_validator("emails")
117
  @classmethod
app/tasks/celery_tasks.py CHANGED
@@ -19,10 +19,9 @@ celery_app.conf.update(
19
  worker_concurrency=10,
20
  task_soft_time_limit=300,
21
  task_time_limit=600,
22
- # Survive a broker that is still coming up (local sidecar cold start):
23
- # retry the connection at startup instead of exiting and crash-looping.
24
- broker_connection_max_retries=None,
25
- broker_connection_retry_on_startup=True,
26
  task_publish_retry=False,
27
  task_publish_retry_policy={"max_retries": 1},
28
  result_backend_transport_options={
@@ -34,20 +33,15 @@ celery_app.conf.update(
34
  task_reject_on_worker_lost=True,
35
  )
36
 
37
- # Hosted Redis (Upstash) arrives over rediss:// — always verify the server
38
- # certificate. Explicit CERT_REQUIRED so Celery never silently downgrades.
39
- import ssl as _ssl
40
- if settings.celery_broker_url.startswith("rediss"):
41
- celery_app.conf.broker_use_ssl = {"ssl_cert_reqs": _ssl.CERT_REQUIRED}
42
- if settings.celery_result_backend.startswith("rediss"):
43
- celery_app.conf.redis_backend_use_ssl = {"ssl_cert_reqs": _ssl.CERT_REQUIRED}
44
-
45
 
46
  @celery_app.task(bind=True, max_retries=3, rate_limit="100/m")
47
- def bulk_validate_task(self, emails: list, webhook_url: str = None):
48
  """
49
  Celery task for async bulk email validation.
50
  Runs synchronously inside Celery worker.
 
 
 
51
  """
52
  from ..validator.engine import EmailValidationEngine
53
  from ..db import repo
@@ -60,7 +54,7 @@ def bulk_validate_task(self, emails: list, webhook_url: str = None):
60
 
61
  for i, email in enumerate(emails):
62
  try:
63
- result = await eng.validate(email, deep=False)
64
  results.append(result.model_dump())
65
  # Update progress
66
  self.update_state(
@@ -68,7 +62,11 @@ def bulk_validate_task(self, emails: list, webhook_url: str = None):
68
  meta={"current": i + 1, "total": total}
69
  )
70
  except Exception as e:
71
- print(f"[CELERY TASK] Error validating {email}: {str(e)}", file=sys.stderr)
 
 
 
 
72
  results.append({
73
  "email": email,
74
  "error": str(e),
 
19
  worker_concurrency=10,
20
  task_soft_time_limit=300,
21
  task_time_limit=600,
22
+ # Fail fast when Redis/broker is down instead of retrying forever
23
+ broker_connection_max_retries=2,
24
+ broker_connection_retry_on_startup=False,
 
25
  task_publish_retry=False,
26
  task_publish_retry_policy={"max_retries": 1},
27
  result_backend_transport_options={
 
33
  task_reject_on_worker_lost=True,
34
  )
35
 
 
 
 
 
 
 
 
 
36
 
37
  @celery_app.task(bind=True, max_retries=3, rate_limit="100/m")
38
+ def bulk_validate_task(self, emails: list, webhook_url: str = None, deep: bool = True):
39
  """
40
  Celery task for async bulk email validation.
41
  Runs synchronously inside Celery worker.
42
+
43
+ `deep` defaults to True: bulk must run the full 7-layer pipeline (catch-all
44
+ + SMTP) to produce a real verdict, matching single verification.
45
  """
46
  from ..validator.engine import EmailValidationEngine
47
  from ..db import repo
 
54
 
55
  for i, email in enumerate(emails):
56
  try:
57
+ result = await eng.validate(email, deep=deep)
58
  results.append(result.model_dump())
59
  # Update progress
60
  self.update_state(
 
62
  meta={"current": i + 1, "total": total}
63
  )
64
  except Exception as e:
65
+ print(
66
+ f"[CELERY TASK] Validation failed for item {i + 1}/{total}: "
67
+ f"{e.__class__.__name__}",
68
+ file=sys.stderr,
69
+ )
70
  results.append({
71
  "email": email,
72
  "error": str(e),
app/utils/cache.py CHANGED
@@ -12,49 +12,23 @@ except Exception: # pragma: no cover - redis not installed
12
  _HAS_REDIS = False
13
 
14
  _redis_client: Optional[object] = None
15
- _free_tier_provisioned: Optional[str] = None # db id if we self-provisioned
16
 
17
  # In-memory TTL fallback cache: {key: (value, expires_at)}
18
  _memory_cache: dict = {}
19
 
20
 
21
- async def provision_free_tier() -> Optional[str]:
22
- """
23
- Create a free-tier Upstash database when no REDIS_URL is configured.
24
- Returns the connection string on success, or None on failure.
25
-
26
- Free databases last 3 days unless claimed at the returned console URL.
27
- Idempotent: caches the db id so repeated calls re-fetch, not duplicate.
28
- """
29
- global _free_tier_provisioned
30
- try:
31
- from .upstash_free import create_database
32
- db = create_database(db_id=_free_tier_provisioned or "")
33
- _free_tier_provisioned = db.db_id
34
- print(
35
- f"[REDIS] Free-tier database provisioned: {db.endpoint} "
36
- f"(expires {db.expires})"
37
- )
38
- print(f"[REDIS] Claim it at: {db.console_url}")
39
- return db.connection_string(0)
40
- except Exception as e:
41
- print(f"[REDIS] Free-tier provisioning failed: {e}")
42
- return None
43
-
44
-
45
  async def get_redis():
46
  """Lazily create a shared Redis client (returns None if unavailable).
47
 
48
- If REDIS_URL is set, uses it. Otherwise attempts to self-provision a
49
- free-tier Upstash database (no account/key required).
 
50
  """
51
  global _redis_client
52
  if not _HAS_REDIS:
53
  return None
54
  if _redis_client is None:
55
- url = settings.redis_url
56
- if not url or "localhost" in url:
57
- url = await provision_free_tier()
58
  if not url:
59
  return None
60
  try:
 
12
  _HAS_REDIS = False
13
 
14
  _redis_client: Optional[object] = None
 
15
 
16
  # In-memory TTL fallback cache: {key: (value, expires_at)}
17
  _memory_cache: dict = {}
18
 
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  async def get_redis():
21
  """Lazily create a shared Redis client (returns None if unavailable).
22
 
23
+ Redis connections must be configured explicitly. Missing or unreachable
24
+ Redis leaves the API on its bounded in-memory cache instead of silently
25
+ provisioning a temporary external database.
26
  """
27
  global _redis_client
28
  if not _HAS_REDIS:
29
  return None
30
  if _redis_client is None:
31
+ url = (settings.redis_url or "").strip()
 
 
32
  if not url:
33
  return None
34
  try:
app/validator/catch_all.py CHANGED
@@ -5,7 +5,6 @@ The heavy lifting lives in smtp_verify.AsyncSMTPVerifier.check_catch_all;
5
  this module provides a thin convenience wrapper plus a cached in-memory
6
  cache so repeated probes of the same domain are avoided.
7
  """
8
- from typing import Tuple
9
  import asyncio
10
  from ..models import CatchAllResult
11
  from .smtp_verify import smtp_verifier
 
5
  this module provides a thin convenience wrapper plus a cached in-memory
6
  cache so repeated probes of the same domain are avoided.
7
  """
 
8
  import asyncio
9
  from ..models import CatchAllResult
10
  from .smtp_verify import smtp_verifier
app/validator/dns_check.py CHANGED
@@ -19,6 +19,7 @@ async def check_dns(domain: str, timeout: int = 5) -> DNSResult:
19
  mx_records = []
20
  domain_exists = False
21
  has_mx = False
 
22
 
23
  try:
24
  mx_answers = await resolver.resolve(domain, 'MX')
@@ -33,30 +34,67 @@ async def check_dns(domain: str, timeout: int = 5) -> DNSResult:
33
  return DNSResult(
34
  domain_exists=False,
35
  has_mx_records=False,
36
- error="Domain does not exist (NXDOMAIN)"
 
37
  )
38
  except dns.resolver.NoAnswer:
39
  # No MX -> try A/AAAA fallback per RFC
40
  try:
41
- await resolver.resolve(domain, 'A')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  domain_exists = True
43
- except Exception:
44
- try:
45
- await resolver.resolve(domain, 'AAAA')
46
- domain_exists = True
47
- except Exception:
48
- pass
49
  except dns.exception.Timeout:
50
  return DNSResult(
51
  domain_exists=False,
52
  has_mx_records=False,
53
- error="DNS timeout"
 
54
  )
55
- except Exception as e:
56
  return DNSResult(
57
  domain_exists=False,
58
  has_mx_records=False,
59
- error=str(e)
 
 
 
 
 
 
 
 
 
60
  )
61
 
62
  # ---- SPF Record ---------------------------------------------------
@@ -108,6 +146,7 @@ async def check_dns(domain: str, timeout: int = 5) -> DNSResult:
108
  domain_exists=domain_exists,
109
  has_mx_records=has_mx,
110
  mx_records=mx_records,
 
111
  has_spf=has_spf,
112
  spf_record=spf_record,
113
  has_dmarc=has_dmarc,
 
19
  mx_records = []
20
  domain_exists = False
21
  has_mx = False
22
+ a_fallback = False
23
 
24
  try:
25
  mx_answers = await resolver.resolve(domain, 'MX')
 
34
  return DNSResult(
35
  domain_exists=False,
36
  has_mx_records=False,
37
+ error="Domain does not exist (NXDOMAIN)",
38
+ error_code="nxdomain",
39
  )
40
  except dns.resolver.NoAnswer:
41
  # No MX -> try A/AAAA fallback per RFC
42
  try:
43
+ for record_type in ('A', 'AAAA'):
44
+ try:
45
+ await resolver.resolve(domain, record_type)
46
+ domain_exists = True
47
+ a_fallback = True
48
+ mx_records.append({"host": domain, "priority": 0})
49
+ break
50
+ except dns.resolver.NoAnswer:
51
+ continue
52
+ except dns.resolver.NXDOMAIN:
53
+ return DNSResult(
54
+ domain_exists=False,
55
+ has_mx_records=False,
56
+ error="Domain does not exist (NXDOMAIN)",
57
+ error_code="nxdomain",
58
+ )
59
+ except dns.exception.Timeout:
60
+ return DNSResult(
61
+ domain_exists=False,
62
+ has_mx_records=False,
63
+ error="DNS address lookup timed out",
64
+ error_code="timeout",
65
+ )
66
+ except dns.exception.DNSException as e:
67
+ return DNSResult(
68
+ domain_exists=False,
69
+ has_mx_records=False,
70
+ error=f"DNS address lookup failed: {e.__class__.__name__}",
71
+ error_code="resolver_error",
72
+ )
73
+ if not domain_exists:
74
+ # An MX NODATA response confirms the owner name exists, even when
75
+ # it has no address record to which SMTP can be routed.
76
  domain_exists = True
 
 
 
 
 
 
77
  except dns.exception.Timeout:
78
  return DNSResult(
79
  domain_exists=False,
80
  has_mx_records=False,
81
+ error="DNS timeout",
82
+ error_code="timeout",
83
  )
84
+ except dns.exception.DNSException as e:
85
  return DNSResult(
86
  domain_exists=False,
87
  has_mx_records=False,
88
+ error=f"DNS lookup failed: {e.__class__.__name__}",
89
+ error_code="resolver_error",
90
+ )
91
+
92
+ if not has_mx and not a_fallback:
93
+ return DNSResult(
94
+ domain_exists=True,
95
+ has_mx_records=False,
96
+ error="Domain has no MX, A, or AAAA records",
97
+ error_code="no_mail_records",
98
  )
99
 
100
  # ---- SPF Record ---------------------------------------------------
 
146
  domain_exists=domain_exists,
147
  has_mx_records=has_mx,
148
  mx_records=mx_records,
149
+ a_fallback=a_fallback,
150
  has_spf=has_spf,
151
  spf_record=spf_record,
152
  has_dmarc=has_dmarc,
app/validator/engine.py CHANGED
@@ -1,23 +1,109 @@
1
  import asyncio
 
2
  import time
 
3
  from datetime import datetime, timezone
4
- from typing import Optional
5
  import structlog
6
 
7
  from ..models import (
8
- ValidationResult, ValidationStatus,
9
- ScoringResult, RiskLevel, CatchAllResult, SMTPResult
 
 
 
 
 
 
10
  )
11
  from ..config import settings
12
  from .syntax import validate_syntax
13
  from .dns_check import check_dns
14
  from .disposable import check_disposable
15
- from .smtp_verify import smtp_verifier
16
  from .scoring import calculate_score
17
 
18
  logger = structlog.get_logger()
19
 
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  class EmailValidationEngine:
22
  """
23
  Master 7-Layer Email Validation Orchestrator.
@@ -29,16 +115,21 @@ class EmailValidationEngine:
29
  4. Disposable / Role-based / Free provider detection
30
  5. Catch-all domain detection
31
  6. SMTP mailbox verification
32
- 7. AI/Heuristic deliverability scoring
33
  """
34
 
35
- def __init__(self):
36
  self.use_proxies = settings.use_proxies
 
 
 
 
37
 
38
  async def validate(self, email: str, deep: bool = True) -> ValidationResult:
39
  start_time = time.monotonic()
 
40
 
41
- log = logger.bind(email=email)
42
  log.info("validation_started")
43
 
44
  # ---- Layer 1: Syntax -----------------------------------------
@@ -54,7 +145,11 @@ class EmailValidationEngine:
54
  syntax=syntax,
55
  scoring=scoring,
56
  processing_time_ms=round(elapsed, 2),
57
- validated_at=datetime.now(timezone.utc).isoformat()
 
 
 
 
58
  )
59
 
60
  domain = syntax.domain
@@ -63,7 +158,31 @@ class EmailValidationEngine:
63
  # ---- Layers 2 & 3: DNS + MX ---------------------------------
64
  dns_result = await check_dns(domain, settings.dns_timeout)
65
 
66
- if not dns_result.domain_exists or not dns_result.has_mx_records:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  elapsed = (time.monotonic() - start_time) * 1000
68
  scoring = calculate_score(syntax, dns_result, None, None, None)
69
  log.warning("dns_failed", domain=domain)
@@ -74,7 +193,13 @@ class EmailValidationEngine:
74
  dns=dns_result,
75
  scoring=scoring,
76
  processing_time_ms=round(elapsed, 2),
77
- validated_at=datetime.now(timezone.utc).isoformat()
 
 
 
 
 
 
78
  )
79
 
80
  # ---- Layer 4: Disposable Detection ---------------------------
@@ -83,7 +208,14 @@ class EmailValidationEngine:
83
  if not deep:
84
  # Fast path: skip SMTP for quick validation
85
  elapsed = (time.monotonic() - start_time) * 1000
86
- scoring = calculate_score(syntax, dns_result, disposable, None, None)
 
 
 
 
 
 
 
87
  status = self._determine_status(scoring)
88
  return ValidationResult(
89
  email=normalized_email,
@@ -93,27 +225,37 @@ class EmailValidationEngine:
93
  disposable=disposable,
94
  scoring=scoring,
95
  processing_time_ms=round(elapsed, 2),
96
- validated_at=datetime.now(timezone.utc).isoformat()
 
 
 
 
 
 
97
  )
98
 
99
  # ---- Layers 5 & 6: Catch-All + SMTP --------------------------
100
  mx_host = dns_result.mx_records[0]["host"]
101
 
102
- # Run catch-all and SMTP in parallel for speed
 
103
  catch_all_task = asyncio.create_task(
104
- smtp_verifier.check_catch_all(domain, mx_host)
105
  )
106
  smtp_task = asyncio.create_task(
107
- smtp_verifier.verify(normalized_email, mx_host, self.use_proxies)
108
  )
109
 
110
  catch_all_raw, smtp_result = await asyncio.gather(
111
  catch_all_task, smtp_task, return_exceptions=True
112
  )
113
 
114
- # Handle catch-all result
 
115
  if isinstance(catch_all_raw, Exception):
116
- catch_all = CatchAllResult(is_catch_all=False, error=str(catch_all_raw))
 
 
117
  else:
118
  is_catch_all, confidence = catch_all_raw
119
  catch_all = CatchAllResult(is_catch_all=is_catch_all, confidence=confidence)
@@ -130,8 +272,12 @@ class EmailValidationEngine:
130
  status = self._determine_status(scoring)
131
  elapsed = (time.monotonic() - start_time) * 1000
132
 
133
- log.info("validation_complete", status=status, score=scoring.score,
134
- time_ms=round(elapsed, 2))
 
 
 
 
135
 
136
  return ValidationResult(
137
  email=normalized_email,
@@ -143,16 +289,20 @@ class EmailValidationEngine:
143
  smtp=smtp_result,
144
  scoring=scoring,
145
  processing_time_ms=round(elapsed, 2),
146
- validated_at=datetime.now(timezone.utc).isoformat()
 
 
 
 
 
 
147
  )
148
 
149
  def _determine_status(self, scoring: ScoringResult) -> ValidationStatus:
150
  if scoring.score >= 75:
151
  return ValidationStatus.VALID
152
- elif scoring.score >= 45:
153
  return ValidationStatus.RISKY
154
- elif scoring.score > 0:
155
- return ValidationStatus.UNKNOWN
156
  else:
157
  return ValidationStatus.INVALID
158
 
 
1
  import asyncio
2
+ import re
3
  import time
4
+ import uuid
5
  from datetime import datetime, timezone
 
6
  import structlog
7
 
8
  from ..models import (
9
+ ValidationResult,
10
+ ValidationStatus,
11
+ ScoringResult,
12
+ CatchAllResult,
13
+ DNSResult,
14
+ DisposableResult,
15
+ SMTPResult,
16
+ SyntaxResult,
17
  )
18
  from ..config import settings
19
  from .syntax import validate_syntax
20
  from .dns_check import check_dns
21
  from .disposable import check_disposable
22
+ from .mailbox_provider import MailboxProvider, resolve_provider
23
  from .scoring import calculate_score
24
 
25
  logger = structlog.get_logger()
26
 
27
 
28
+ def _mask_email_for_log(email: str) -> str:
29
+ local_part, separator, domain = email.rpartition("@")
30
+ if not separator or not domain:
31
+ return "[invalid-email]"
32
+ return f"{local_part[:1]}***@{domain}"
33
+
34
+
35
+ def _build_checks_run(
36
+ syntax: SyntaxResult | None,
37
+ dns: DNSResult | None,
38
+ disposable: DisposableResult | None,
39
+ catch_all: CatchAllResult | None,
40
+ smtp: SMTPResult | None,
41
+ scoring: ScoringResult | None,
42
+ ) -> list[str]:
43
+ """Which of the 7-layer taxonomy keys actually executed for this result.
44
+
45
+ Mirrors the frontend fallback in src/lib/verifier.ts classify() so a layer
46
+ the engine did not run is never reported as a pass. DNS without an error
47
+ claims both `dns` and `mx`; a DNS error claims only `dns`.
48
+ """
49
+ checks: list[str] = []
50
+ if syntax is not None:
51
+ checks.append("syntax")
52
+ if dns is not None:
53
+ if dns.error:
54
+ checks.append("dns")
55
+ else:
56
+ checks.extend(["dns", "mx"])
57
+ if disposable is not None:
58
+ checks.append("disposable")
59
+ if catch_all is not None:
60
+ checks.append("catch_all")
61
+ if smtp is not None:
62
+ checks.append("smtp")
63
+ if scoring is not None:
64
+ checks.append("scoring")
65
+ return checks
66
+
67
+
68
+ def _build_reason_code(
69
+ dns: DNSResult | None,
70
+ disposable: DisposableResult | None,
71
+ catch_all: CatchAllResult | None,
72
+ smtp: SMTPResult | None,
73
+ *,
74
+ early: str | None = None,
75
+ ) -> str | None:
76
+ """Machine cause for the verdict. Ordered most-specific/actionable first.
77
+
78
+ disposable outranks everything (frontend classifies it as Disposable);
79
+ a catch-all or a dead-A-only route outranks a raw SMTP code so the reason
80
+ matches the Unknown verdict the frontend assigns for those rows.
81
+ """
82
+ if early:
83
+ return early
84
+ if disposable is not None and disposable.is_disposable:
85
+ return "disposable"
86
+ if dns is not None and dns.a_fallback and not dns.has_mx_records:
87
+ return "a_fallback_only"
88
+ if catch_all is not None and catch_all.is_catch_all:
89
+ return "catch_all_detected"
90
+ if smtp is not None:
91
+ if smtp.verified is False and smtp.smtp_code:
92
+ if smtp.smtp_code >= 500:
93
+ return "rcpt_5xx"
94
+ if smtp.smtp_code >= 400:
95
+ return "rcpt_4xx"
96
+ if smtp.smtp_code >= 200:
97
+ return "rcpt_2xx"
98
+ if smtp.verified is None and smtp.error:
99
+ return (
100
+ "smtp_timeout"
101
+ if re.search(r"timed?\s*out", smtp.error, re.IGNORECASE)
102
+ else "smtp_unavailable"
103
+ )
104
+ return None
105
+
106
+
107
  class EmailValidationEngine:
108
  """
109
  Master 7-Layer Email Validation Orchestrator.
 
115
  4. Disposable / Role-based / Free provider detection
116
  5. Catch-all domain detection
117
  6. SMTP mailbox verification
118
+ 7. Deterministic heuristic deliverability scoring
119
  """
120
 
121
+ def __init__(self, mailbox: MailboxProvider | None = None):
122
  self.use_proxies = settings.use_proxies
123
+ # Layers 5 (catch-all) and 6 (SMTP) run through a mailbox provider. On
124
+ # hosts that block port 25 (HF Spaces), this resolves to the verification
125
+ # API; elsewhere it is direct SMTP. Injectable for tests.
126
+ self.mailbox = mailbox if mailbox is not None else resolve_provider()
127
 
128
  async def validate(self, email: str, deep: bool = True) -> ValidationResult:
129
  start_time = time.monotonic()
130
+ run_id = uuid.uuid4().hex[:12]
131
 
132
+ log = logger.bind(email=_mask_email_for_log(email), run_id=run_id)
133
  log.info("validation_started")
134
 
135
  # ---- Layer 1: Syntax -----------------------------------------
 
145
  syntax=syntax,
146
  scoring=scoring,
147
  processing_time_ms=round(elapsed, 2),
148
+ validated_at=datetime.now(timezone.utc).isoformat(),
149
+ checks_run=_build_checks_run(syntax, None, None, None, None, scoring),
150
+ reason_code=_build_reason_code(None, None, None, None),
151
+ run_id=run_id,
152
+ validator_version=settings.app_version,
153
  )
154
 
155
  domain = syntax.domain
 
158
  # ---- Layers 2 & 3: DNS + MX ---------------------------------
159
  dns_result = await check_dns(domain, settings.dns_timeout)
160
 
161
+ if dns_result.error_code in {"timeout", "resolver_error"}:
162
+ elapsed = (time.monotonic() - start_time) * 1000
163
+ scoring = calculate_score(syntax, dns_result, None, None, None)
164
+ log.warning(
165
+ "dns_inconclusive", domain=domain, error_code=dns_result.error_code
166
+ )
167
+ return ValidationResult(
168
+ email=normalized_email,
169
+ status=self._determine_status(scoring),
170
+ syntax=syntax,
171
+ dns=dns_result,
172
+ scoring=scoring,
173
+ processing_time_ms=round(elapsed, 2),
174
+ validated_at=datetime.now(timezone.utc).isoformat(),
175
+ checks_run=_build_checks_run(syntax, dns_result, None, None, None, scoring),
176
+ reason_code=_build_reason_code(dns_result, None, None, None, early="dns_timeout"),
177
+ run_id=run_id,
178
+ validator_version=settings.app_version,
179
+ )
180
+
181
+ if (
182
+ not dns_result.domain_exists
183
+ or dns_result.error_code == "nxdomain"
184
+ or (not dns_result.has_mx_records and not dns_result.a_fallback)
185
+ ):
186
  elapsed = (time.monotonic() - start_time) * 1000
187
  scoring = calculate_score(syntax, dns_result, None, None, None)
188
  log.warning("dns_failed", domain=domain)
 
193
  dns=dns_result,
194
  scoring=scoring,
195
  processing_time_ms=round(elapsed, 2),
196
+ validated_at=datetime.now(timezone.utc).isoformat(),
197
+ checks_run=_build_checks_run(syntax, dns_result, None, None, None, scoring),
198
+ reason_code=_build_reason_code(
199
+ dns_result, None, None, None, early="nxdomain"
200
+ ),
201
+ run_id=run_id,
202
+ validator_version=settings.app_version,
203
  )
204
 
205
  # ---- Layer 4: Disposable Detection ---------------------------
 
208
  if not deep:
209
  # Fast path: skip SMTP for quick validation
210
  elapsed = (time.monotonic() - start_time) * 1000
211
+ scoring = calculate_score(
212
+ syntax,
213
+ dns_result,
214
+ disposable,
215
+ None,
216
+ None,
217
+ mailbox_verification_skipped=True,
218
+ )
219
  status = self._determine_status(scoring)
220
  return ValidationResult(
221
  email=normalized_email,
 
225
  disposable=disposable,
226
  scoring=scoring,
227
  processing_time_ms=round(elapsed, 2),
228
+ validated_at=datetime.now(timezone.utc).isoformat(),
229
+ checks_run=_build_checks_run(
230
+ syntax, dns_result, disposable, None, None, scoring
231
+ ),
232
+ reason_code=_build_reason_code(dns_result, disposable, None, None),
233
+ run_id=run_id,
234
+ validator_version=settings.app_version,
235
  )
236
 
237
  # ---- Layers 5 & 6: Catch-All + SMTP --------------------------
238
  mx_host = dns_result.mx_records[0]["host"]
239
 
240
+ # Run catch-all and SMTP in parallel for speed, via the mailbox
241
+ # provider (direct SMTP or the verification API, per configuration).
242
  catch_all_task = asyncio.create_task(
243
+ self.mailbox.catch_all(domain, mx_host)
244
  )
245
  smtp_task = asyncio.create_task(
246
+ self.mailbox.verify(normalized_email, mx_host)
247
  )
248
 
249
  catch_all_raw, smtp_result = await asyncio.gather(
250
  catch_all_task, smtp_task, return_exceptions=True
251
  )
252
 
253
+ # Handle catch-all result. An exception means the probe could not run
254
+ # (e.g. port-25 egress blocked) — that is UNKNOWN, not "not catch-all".
255
  if isinstance(catch_all_raw, Exception):
256
+ catch_all = CatchAllResult(
257
+ is_catch_all=None, confidence=0.0, error=str(catch_all_raw)
258
+ )
259
  else:
260
  is_catch_all, confidence = catch_all_raw
261
  catch_all = CatchAllResult(is_catch_all=is_catch_all, confidence=confidence)
 
272
  status = self._determine_status(scoring)
273
  elapsed = (time.monotonic() - start_time) * 1000
274
 
275
+ log.info(
276
+ "validation_complete",
277
+ status=status,
278
+ score=scoring.score,
279
+ time_ms=round(elapsed, 2),
280
+ )
281
 
282
  return ValidationResult(
283
  email=normalized_email,
 
289
  smtp=smtp_result,
290
  scoring=scoring,
291
  processing_time_ms=round(elapsed, 2),
292
+ validated_at=datetime.now(timezone.utc).isoformat(),
293
+ checks_run=_build_checks_run(
294
+ syntax, dns_result, disposable, catch_all, smtp_result, scoring
295
+ ),
296
+ reason_code=_build_reason_code(dns_result, disposable, catch_all, smtp_result),
297
+ run_id=run_id,
298
+ validator_version=settings.app_version,
299
  )
300
 
301
  def _determine_status(self, scoring: ScoringResult) -> ValidationStatus:
302
  if scoring.score >= 75:
303
  return ValidationStatus.VALID
304
+ elif scoring.score >= 40:
305
  return ValidationStatus.RISKY
 
 
306
  else:
307
  return ValidationStatus.INVALID
308
 
app/validator/mailbox_provider.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Mailbox verification providers (Layer 5 catch-all + Layer 6 SMTP).
2
+
3
+ Direct SMTP to the recipient MX on port 25 is the classic mailbox probe, but
4
+ most cloud hosts — Hugging Face Spaces included — block outbound port 25. When
5
+ direct SMTP cannot run, the mailbox verdict is delegated to a third-party
6
+ verification API (MillionVerifier) whose status strings map 1:1 onto this
7
+ product's taxonomy.
8
+
9
+ resolve_provider() picks the provider from settings:
10
+ mailbox_provider = "auto" → API when mv_api_key is set, else local SMTP
11
+ mailbox_provider = "api" → force the verification API
12
+ mailbox_provider = "local" → force direct SMTP
13
+
14
+ The circuit breaker on LocalSmtpProvider stops a blocked host from burning the
15
+ full SMTP timeout on every address in a bulk job: after `fail_threshold`
16
+ consecutive connection failures it fails fast for `cooldown_seconds`.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import asyncio
21
+ import random
22
+ import time
23
+ from typing import Optional, Tuple
24
+
25
+ import httpx
26
+
27
+ from ..config import settings
28
+ from ..models import CatchAllResult, SMTPResult
29
+ from .smtp_verify import GIBBERISH_LOCAL, smtp_verifier
30
+
31
+
32
+ def map_mv_result(payload: dict) -> SMTPResult:
33
+ """Map one MillionVerifier real-time response into our SMTPResult contract.
34
+
35
+ Live schema (verified 2026-10-11 against API_KEY_FOR_TEST):
36
+ {"result": "ok"|"catch_all"|"invalid"|"disposable"|"unknown"|"error",
37
+ "quality": "good"|"risky"|"bad", "resultcode": <int>,
38
+ "free": bool, "role": bool, "error": str}
39
+ """
40
+ result = (payload.get("result") or "").lower()
41
+ error = payload.get("error") or ""
42
+
43
+ if result == "ok":
44
+ return SMTPResult(verified=True, smtp_code=250, smtp_message="provider: ok")
45
+ if result == "invalid":
46
+ # A provider-confirmed dead mailbox is a permanent (5xx-class) reject.
47
+ return SMTPResult(
48
+ verified=False, smtp_code=550, smtp_message=error or "provider: invalid"
49
+ )
50
+ if result in {"catch_all", "unknown", "disposable"}:
51
+ # None of these proves the specific mailbox exists. catch_all accepts
52
+ # everything; unknown is the provider's own inconclusive bucket.
53
+ return SMTPResult(
54
+ verified=None, error=f"provider: {result}" + (f" ({error})" if error else "")
55
+ )
56
+ # "error" or anything unexpected → inconclusive, surfaced as an error.
57
+ return SMTPResult(verified=None, error=f"provider: {result or 'error'} {error}".strip())
58
+
59
+
60
+ class MailboxProvider:
61
+ """Common interface every mailbox provider implements."""
62
+
63
+ name = "base"
64
+
65
+ async def verify(self, email: str, mx_host: str) -> SMTPResult:
66
+ raise NotImplementedError
67
+
68
+ async def catch_all(self, domain: str, mx_host: str) -> Tuple[Optional[bool], float]:
69
+ raise NotImplementedError
70
+
71
+
72
+ class MillionVerifierProvider(MailboxProvider):
73
+ name = "millionverifier"
74
+
75
+ def __init__(self, api_key: Optional[str] = None, timeout: Optional[int] = None):
76
+ self.api_key = api_key if api_key is not None else settings.mv_api_key
77
+ self.timeout = timeout if timeout is not None else settings.mv_timeout
78
+ self.endpoint = "https://api.millionverifier.com/api/v3/"
79
+
80
+ async def _call(self, email: str) -> dict:
81
+ async with httpx.AsyncClient(timeout=self.timeout + 5) as client:
82
+ resp = await client.get(
83
+ self.endpoint,
84
+ params={"api": self.api_key, "email": email, "timeout": self.timeout},
85
+ )
86
+ resp.raise_for_status()
87
+ return resp.json()
88
+
89
+ async def verify(self, email: str, mx_host: str) -> SMTPResult:
90
+ try:
91
+ payload = await self._call(email)
92
+ except Exception as exc: # network / HTTP failure → inconclusive
93
+ return SMTPResult(verified=None, error=f"provider unavailable: {exc}")
94
+ return map_mv_result(payload)
95
+
96
+ async def catch_all(self, domain: str, mx_host: str) -> Tuple[Optional[bool], float]:
97
+ # Domain property: probe a high-entropy gibberish local part. A 250 on
98
+ # gibberish ⇒ catch-all; a reject ⇒ not. The real address must never be
99
+ # used here (it would always "accept", a false negative).
100
+ gibberish = f"{GIBBERISH_LOCAL}{random.getrandbits(32):08x}@{domain}"
101
+ try:
102
+ payload = await self._call(gibberish)
103
+ except Exception:
104
+ return None, 0.0
105
+ result = (payload.get("result") or "").lower()
106
+ if result == "catch_all":
107
+ return True, 0.95
108
+ if result == "invalid":
109
+ return False, 0.9
110
+ # "ok" on gibberish would itself indicate catch-all; unknown/error → None
111
+ if result == "ok":
112
+ return True, 0.8
113
+ return None, 0.0
114
+
115
+
116
+ class LocalSmtpProvider(MailboxProvider):
117
+ """Direct port-25 SMTP with a circuit breaker for blocked egress."""
118
+
119
+ name = "local"
120
+
121
+ def __init__(
122
+ self,
123
+ fail_threshold: Optional[int] = None,
124
+ cooldown_seconds: Optional[int] = None,
125
+ ):
126
+ self.fail_threshold = (
127
+ fail_threshold if fail_threshold is not None else settings.smtp_fail_threshold
128
+ )
129
+ self.cooldown = (
130
+ cooldown_seconds
131
+ if cooldown_seconds is not None
132
+ else settings.smtp_cooldown_seconds
133
+ )
134
+ self._consecutive_failures = 0
135
+ self._open_until = 0.0
136
+
137
+ @property
138
+ def circuit_open(self) -> bool:
139
+ return time.monotonic() < self._open_until
140
+
141
+ def circuit_open_after_cooldown(self) -> bool:
142
+ """True only while still within the cooldown window (0s ⇒ closed)."""
143
+ return time.monotonic() < self._open_until
144
+
145
+ def record_failure(self) -> None:
146
+ self._consecutive_failures += 1
147
+ if self._consecutive_failures >= self.fail_threshold:
148
+ self._open_until = time.monotonic() + self.cooldown
149
+
150
+ def record_success(self) -> None:
151
+ self._consecutive_failures = 0
152
+ self._open_until = 0.0
153
+
154
+ async def verify(self, email: str, mx_host: str) -> SMTPResult:
155
+ if self.circuit_open:
156
+ return SMTPResult(
157
+ verified=None, error="SMTP unavailable (egress circuit open)"
158
+ )
159
+ result = await smtp_verifier.verify(email, mx_host, settings.use_proxies)
160
+ # A connection-class failure (timeout/refused/unreachable) counts toward
161
+ # opening the circuit; a real SMTP dialogue does not.
162
+ if result.verified is None and result.error and any(
163
+ k in result.error.lower()
164
+ for k in ("timeout", "timed out", "refused", "unreachable", "unavailable")
165
+ ):
166
+ self.record_failure()
167
+ elif result.smtp_code is not None or result.verified is not None:
168
+ self.record_success()
169
+ return result
170
+
171
+ async def catch_all(self, domain: str, mx_host: str) -> Tuple[Optional[bool], float]:
172
+ if self.circuit_open:
173
+ return None, 0.0
174
+ try:
175
+ is_catch_all, confidence = await smtp_verifier.check_catch_all(domain, mx_host)
176
+ except Exception:
177
+ return None, 0.0
178
+ # check_catch_all returns (False, 0.0) when the probe is inconclusive —
179
+ # that means UNKNOWN, not "not catch-all". Confidence 0.0 is the signal.
180
+ if confidence == 0.0:
181
+ self.record_failure()
182
+ return None, 0.0
183
+ self.record_success()
184
+ return is_catch_all, confidence
185
+
186
+
187
+ def resolve_provider() -> MailboxProvider:
188
+ mode = (settings.mailbox_provider or "auto").strip().lower()
189
+ if mode == "api":
190
+ return MillionVerifierProvider()
191
+ if mode == "local":
192
+ return LocalSmtpProvider()
193
+ # auto
194
+ if settings.mv_api_key:
195
+ return MillionVerifierProvider()
196
+ return LocalSmtpProvider()
app/validator/scoring.py CHANGED
@@ -1,42 +1,84 @@
 
1
  from typing import Optional
2
  from ..models import (
3
- SyntaxResult, DNSResult, DisposableResult,
4
- CatchAllResult, SMTPResult, ScoringResult, RiskLevel
 
 
 
 
 
5
  )
6
 
7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  def calculate_score(
9
  syntax: SyntaxResult,
10
  dns: Optional[DNSResult],
11
  disposable: Optional[DisposableResult],
12
  catch_all: Optional[CatchAllResult],
13
- smtp: Optional[SMTPResult]
 
 
14
  ) -> ScoringResult:
15
  """
16
  Layer 7: Comprehensive deliverability scoring.
17
  Score: 0-100 (higher = better deliverability)
18
  """
19
  score = 100
 
20
  breakdown = {}
21
  warnings = []
22
 
23
  # ---- Syntax (hard fail → score 0) --------------------------------
24
  if not syntax.passed:
25
- breakdown["syntax"] = -100
26
- score -= 100
27
- else:
28
- breakdown["syntax"] = 0
29
 
30
- # ---- Domain/MX (hard fail → near zero) ------------------------------
31
  if dns:
32
- if not dns.domain_exists:
33
- breakdown["domain"] = -75
34
- score -= 75
 
 
 
35
  warnings.append("Domain does not exist")
36
- elif not dns.has_mx_records:
37
- breakdown["mx_records"] = -70
38
- score -= 70
39
- warnings.append("No MX records found — domain cannot receive email")
 
 
 
 
 
 
 
 
 
 
40
  else:
41
  breakdown["domain"] = 0
42
  breakdown["mx_records"] = 0
@@ -58,22 +100,26 @@ def calculate_score(
58
  breakdown["dkim"] = 2
59
  score += 2
60
 
61
- # ---- Disposable (-40) --------------------------------------------
62
  if disposable:
63
  if disposable.is_disposable:
64
- breakdown["disposable"] = -40
65
- score -= 40
66
  warnings.append("Disposable/temporary email domain detected")
 
67
  elif disposable.is_role_based:
 
68
  breakdown["role_based"] = -10
69
  score -= 10
70
- warnings.append("Role-based email (admin@, info@, etc.) — low engagement risk")
 
 
71
  elif disposable.is_free_provider:
72
  breakdown["free_provider"] = -5
73
  score -= 5
74
 
75
  # ---- Catch-All (-20) ---------------------------------------------
76
  if catch_all and catch_all.is_catch_all:
 
77
  breakdown["catch_all"] = -20
78
  score -= 20
79
  warnings.append("Catch-all domain — cannot verify specific mailbox")
@@ -84,30 +130,51 @@ def calculate_score(
84
  breakdown["smtp"] = 10
85
  score += 10
86
  elif smtp.verified is False:
 
 
 
 
87
  breakdown["smtp"] = -30
88
  score -= 30
89
- warnings.append(f"Mailbox does not exist (SMTP {smtp.smtp_code})")
 
 
 
90
  else:
91
- # Unknown / blocked
92
- breakdown["smtp"] = -5
93
- score -= 5
94
  if smtp.error:
95
  warnings.append(f"SMTP check inconclusive: {smtp.error}")
96
 
 
 
 
 
 
 
97
  # Clamp score between 0 and 100
98
  score = max(0, min(100, score))
 
 
 
99
 
 
 
 
 
 
 
 
 
100
  # Determine risk level
101
  if score >= 75:
102
  risk = RiskLevel.LOW
103
- elif score >= 45:
104
  risk = RiskLevel.MEDIUM
105
  else:
106
  risk = RiskLevel.HIGH
107
 
108
  return ScoringResult(
109
- score=score,
110
- risk_level=risk,
111
- breakdown=breakdown,
112
- warnings=warnings
113
  )
 
1
+ import re
2
  from typing import Optional
3
  from ..models import (
4
+ SyntaxResult,
5
+ DNSResult,
6
+ DisposableResult,
7
+ CatchAllResult,
8
+ SMTPResult,
9
+ ScoringResult,
10
+ RiskLevel,
11
  )
12
 
13
 
14
+ def _is_explicit_mailbox_rejection(smtp: SMTPResult) -> bool:
15
+ if smtp.smtp_code != 550 or not smtp.smtp_message:
16
+ return False
17
+
18
+ message = smtp.smtp_message.casefold()
19
+ enhanced_status = re.search(r"(?<![\d.])5\.1\.1(?![\d.])", message)
20
+ mailbox_rejection_phrases = (
21
+ "user unknown",
22
+ "no such user",
23
+ "mailbox does not exist",
24
+ "mailbox not found",
25
+ "recipient does not exist",
26
+ "recipient not found",
27
+ "account does not exist",
28
+ )
29
+ return bool(enhanced_status) or any(
30
+ phrase in message for phrase in mailbox_rejection_phrases
31
+ )
32
+
33
+
34
  def calculate_score(
35
  syntax: SyntaxResult,
36
  dns: Optional[DNSResult],
37
  disposable: Optional[DisposableResult],
38
  catch_all: Optional[CatchAllResult],
39
+ smtp: Optional[SMTPResult],
40
+ *,
41
+ mailbox_verification_skipped: bool = False,
42
  ) -> ScoringResult:
43
  """
44
  Layer 7: Comprehensive deliverability scoring.
45
  Score: 0-100 (higher = better deliverability)
46
  """
47
  score = 100
48
+ risk_cap = 100
49
  breakdown = {}
50
  warnings = []
51
 
52
  # ---- Syntax (hard fail → score 0) --------------------------------
53
  if not syntax.passed:
54
+ breakdown["SYNTAX_INVALID"] = -100
55
+ warnings.append("Email syntax is invalid")
56
+ return _scoring_result(0, breakdown, warnings)
57
+ breakdown["syntax"] = 0
58
 
59
+ # ---- Domain/MX -------------------------------------------------------
60
  if dns:
61
+ if dns.error_code in {"timeout", "resolver_error"}:
62
+ breakdown["DNS_TRANSIENT_FAILURE"] = -50
63
+ warnings.append("DNS lookup was inconclusive")
64
+ return _scoring_result(50, breakdown, warnings)
65
+ elif not dns.domain_exists:
66
+ breakdown["DNS_MX_MISSING"] = -100
67
  warnings.append("Domain does not exist")
68
+ return _scoring_result(0, breakdown, warnings)
69
+ elif dns.error_code == "nxdomain" or (
70
+ not dns.has_mx_records and not dns.a_fallback
71
+ ):
72
+ breakdown["DNS_MX_MISSING"] = -100
73
+ warnings.append("Domain has no valid mail route")
74
+ return _scoring_result(0, breakdown, warnings)
75
+ elif dns.a_fallback:
76
+ risk_cap = min(risk_cap, 74)
77
+ breakdown["mx_records"] = -45
78
+ score -= 45
79
+ warnings.append(
80
+ "No MX records — using A/AAAA fallback; mailbox result is limited"
81
+ )
82
  else:
83
  breakdown["domain"] = 0
84
  breakdown["mx_records"] = 0
 
100
  breakdown["dkim"] = 2
101
  score += 2
102
 
103
+ # ---- Disposable ---------------------------------------------------
104
  if disposable:
105
  if disposable.is_disposable:
106
+ breakdown["DISPOSABLE_DOMAIN"] = -100
 
107
  warnings.append("Disposable/temporary email domain detected")
108
+ return _scoring_result(0, breakdown, warnings)
109
  elif disposable.is_role_based:
110
+ risk_cap = min(risk_cap, 74)
111
  breakdown["role_based"] = -10
112
  score -= 10
113
+ warnings.append(
114
+ "Role-based email (admin@, info@, etc.) — low engagement risk"
115
+ )
116
  elif disposable.is_free_provider:
117
  breakdown["free_provider"] = -5
118
  score -= 5
119
 
120
  # ---- Catch-All (-20) ---------------------------------------------
121
  if catch_all and catch_all.is_catch_all:
122
+ risk_cap = min(risk_cap, 74)
123
  breakdown["catch_all"] = -20
124
  score -= 20
125
  warnings.append("Catch-all domain — cannot verify specific mailbox")
 
130
  breakdown["smtp"] = 10
131
  score += 10
132
  elif smtp.verified is False:
133
+ if _is_explicit_mailbox_rejection(smtp):
134
+ breakdown["SMTP_MAILBOX_NOT_FOUND"] = -100
135
+ warnings.append("SMTP explicitly reported the mailbox as not found")
136
+ return _scoring_result(0, breakdown, warnings)
137
  breakdown["smtp"] = -30
138
  score -= 30
139
+ warnings.append(
140
+ f"SMTP rejected the recipient (code {smtp.smtp_code}); "
141
+ "provider policy may make the result inconclusive"
142
+ )
143
  else:
144
+ risk_cap = min(risk_cap, 70)
145
+ breakdown["SMTP_CHECK_INCONCLUSIVE"] = -30
146
+ score -= 30
147
  if smtp.error:
148
  warnings.append(f"SMTP check inconclusive: {smtp.error}")
149
 
150
+ if mailbox_verification_skipped:
151
+ risk_cap = min(risk_cap, 70)
152
+ breakdown["FAST_MODE_SKIPPED_MAILBOX_CHECK"] = -30
153
+ score -= 30
154
+ warnings.append("Mailbox verification was not performed")
155
+
156
  # Clamp score between 0 and 100
157
  score = max(0, min(100, score))
158
+ if score > risk_cap:
159
+ breakdown["RISK_CONTEXT_CAP"] = risk_cap - score
160
+ score = risk_cap
161
 
162
+ return _scoring_result(score, breakdown, warnings)
163
+
164
+
165
+ def _scoring_result(
166
+ score: int,
167
+ breakdown: dict[str, int],
168
+ warnings: list[str],
169
+ ) -> ScoringResult:
170
  # Determine risk level
171
  if score >= 75:
172
  risk = RiskLevel.LOW
173
+ elif score >= 40:
174
  risk = RiskLevel.MEDIUM
175
  else:
176
  risk = RiskLevel.HIGH
177
 
178
  return ScoringResult(
179
+ score=score, risk_level=risk, breakdown=breakdown, warnings=warnings
 
 
 
180
  )
app/validator/smtp_verify.py CHANGED
@@ -3,7 +3,7 @@ import socket
3
  import smtplib
4
  import socks
5
  import random
6
- from typing import Optional, Tuple
7
  from ..models import SMTPResult
8
  from ..config import settings
9
  from .proxy_engine import proxy_pool
 
3
  import smtplib
4
  import socks
5
  import random
6
+ from typing import Tuple
7
  from ..models import SMTPResult
8
  from ..config import settings
9
  from .proxy_engine import proxy_pool
pytest.ini ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ [pytest]
2
+ testpaths = tests
3
+ python_files = test_*.py
requirements-dev.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ -r requirements.txt
2
+
3
+ pytest>=8.3
4
+ ruff>=0.11.0
ruff.toml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ target-version = "py311"
2
+
3
+ [lint]
4
+ select = ["E4", "E7", "E9", "F"]
test_connections.py CHANGED
@@ -6,6 +6,7 @@ Run this after configuring .env with your Supabase and Upstash credentials.
6
  import asyncio
7
  import sys
8
  import os
 
9
 
10
  # Add backend to path
11
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
@@ -13,6 +14,14 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
13
  from app.config import settings
14
 
15
 
 
 
 
 
 
 
 
 
16
  async def test_supabase():
17
  """Test Supabase connectivity and schema."""
18
  print("\n" + "=" * 60)
@@ -70,7 +79,6 @@ async def test_redis():
70
 
71
  if "YOUR_UPSTASH_PASSWORD" in settings.redis_url or "YOUR_ENDPOINT" in settings.redis_url:
72
  print("[FAIL] Redis URL not configured (still using placeholder values)")
73
- print(f" Current: {settings.redis_url}")
74
  return False
75
 
76
  try:
@@ -113,8 +121,8 @@ async def test_redis():
113
  return True
114
 
115
  except Exception as e:
116
- print(f"[FAIL] Redis: Connection failed - {e}")
117
- print(f" URL: {settings.redis_url}")
118
  print(" → Check: Password, Endpoint, TLS (rediss://), IP Allowlist (0.0.0.0/0)")
119
  return False
120
 
@@ -134,8 +142,8 @@ async def test_celery():
134
  from app.tasks.celery_tasks import celery_app
135
 
136
  # Check configuration
137
- print(f"Broker: {celery_app.conf.broker_url}")
138
- print(f"Backend: {celery_app.conf.result_backend}")
139
 
140
  # Test connection by inspecting
141
  insp = celery_app.control.inspect()
@@ -169,7 +177,7 @@ async def test_validation_engine():
169
 
170
  # Quick validation (no SMTP)
171
  result = await engine.validate("test@example.com", deep=False)
172
- print(f"[PASS] Validation: {result.email} → {result.status.value} (score: {result.scoring.score})")
173
  print(f" Layers: Syntax={result.syntax.passed}, DNS={result.dns.domain_exists}, MX={result.dns.has_mx_records}")
174
  return True
175
 
 
6
  import asyncio
7
  import sys
8
  import os
9
+ from urllib.parse import urlsplit
10
 
11
  # Add backend to path
12
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
 
14
  from app.config import settings
15
 
16
 
17
+ def endpoint_label(url: str) -> str:
18
+ parsed = urlsplit(url)
19
+ if not parsed.hostname:
20
+ return "not configured"
21
+ database = parsed.path.strip("/") or "default"
22
+ return f"{parsed.scheme}://{parsed.hostname}/db-{database}"
23
+
24
+
25
  async def test_supabase():
26
  """Test Supabase connectivity and schema."""
27
  print("\n" + "=" * 60)
 
79
 
80
  if "YOUR_UPSTASH_PASSWORD" in settings.redis_url or "YOUR_ENDPOINT" in settings.redis_url:
81
  print("[FAIL] Redis URL not configured (still using placeholder values)")
 
82
  return False
83
 
84
  try:
 
121
  return True
122
 
123
  except Exception as e:
124
+ print(f"[FAIL] Redis: Connection failed - {e.__class__.__name__}")
125
+ print(f" Endpoint: {endpoint_label(settings.redis_url)}")
126
  print(" → Check: Password, Endpoint, TLS (rediss://), IP Allowlist (0.0.0.0/0)")
127
  return False
128
 
 
142
  from app.tasks.celery_tasks import celery_app
143
 
144
  # Check configuration
145
+ print(f"Broker: {endpoint_label(celery_app.conf.broker_url)}")
146
+ print(f"Backend: {endpoint_label(celery_app.conf.result_backend)}")
147
 
148
  # Test connection by inspecting
149
  insp = celery_app.control.inspect()
 
177
 
178
  # Quick validation (no SMTP)
179
  result = await engine.validate("test@example.com", deep=False)
180
+ print(f"[PASS] Validation: {result.status.value} (score: {result.scoring.score})")
181
  print(f" Layers: Syntax={result.syntax.passed}, DNS={result.dns.domain_exists}, MX={result.dns.has_mx_records}")
182
  return True
183
 
tests/test_bulk_depth.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ from unittest.mock import AsyncMock, patch
3
+
4
+ from app.models import (
5
+ CatchAllResult,
6
+ DNSResult,
7
+ DisposableResult,
8
+ SMTPResult,
9
+ SyntaxResult,
10
+ )
11
+ from app.api.routes import process_bulk_sync
12
+ from app.validator.engine import EmailValidationEngine
13
+
14
+
15
+ def _syntax(**kw):
16
+ base = dict(
17
+ passed=True,
18
+ normalized_email="person@example.test",
19
+ domain="example.test",
20
+ local_part="person",
21
+ )
22
+ base.update(kw)
23
+ return SyntaxResult(**base)
24
+
25
+
26
+ def _dns(**kw):
27
+ base = dict(
28
+ domain_exists=True,
29
+ has_mx_records=True,
30
+ mx_records=[{"host": "mx.example.test", "priority": 10}],
31
+ )
32
+ base.update(kw)
33
+ return DNSResult(**base)
34
+
35
+
36
+ class BulkDepthTests(unittest.IsolatedAsyncioTestCase):
37
+ """RC1: the bulk path hard-coded deep=False, skipping catch-all + SMTP, so
38
+ every bulk row collapsed to Unknown/risky/insufficient_depth in the UI.
39
+ Bulk must run the same deep pipeline as single verification."""
40
+
41
+ async def test_process_bulk_sync_runs_deep_layers(self):
42
+ captured = []
43
+
44
+ async def fake_validate(email, deep=True):
45
+ captured.append(deep)
46
+ from app.models import ValidationStatus, ScoringResult, RiskLevel
47
+
48
+ return type("R", (), {"model_dump": lambda self: {"email": email}})()
49
+
50
+ with (
51
+ patch("app.api.routes.engine.validate", new=AsyncMock(side_effect=lambda e, deep=True: fake_validate(e, deep))),
52
+ patch("app.api.routes.settings.bulk_sync_chunk_size", 50),
53
+ ):
54
+ # patch engine.validate directly to capture the deep flag
55
+ async def capture_validate(email, deep=True):
56
+ captured.append(deep)
57
+
58
+ class FakeResult:
59
+ def model_dump(self):
60
+ return {"email": email}
61
+
62
+ return FakeResult()
63
+
64
+ with patch("app.api.routes.engine") as eng:
65
+ eng.validate = AsyncMock(side_effect=capture_validate)
66
+ await process_bulk_sync(["a@example.com", "b@example.com"])
67
+
68
+ self.assertTrue(len(captured) >= 1)
69
+ self.assertTrue(all(d is True for d in captured), f"bulk ran with deep flags: {captured}")
70
+
71
+ async def test_engine_deep_runs_catch_all_and_smtp(self):
72
+ engine = EmailValidationEngine()
73
+ with (
74
+ patch("app.validator.engine.validate_syntax", return_value=_syntax()),
75
+ patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())),
76
+ patch("app.validator.engine.check_disposable", return_value=DisposableResult(
77
+ is_disposable=False, is_free_provider=False, is_role_based=False
78
+ )),
79
+ patch(
80
+ "app.validator.engine.resolve_provider",
81
+ return_value=None,
82
+ ),
83
+ ):
84
+ pass # covered by mailbox-injected tests below
85
+
86
+ async def test_injected_mailbox_provider_is_used_for_deep(self):
87
+ """The engine must call the injected provider's catch_all + verify."""
88
+ calls = {"verify": 0, "catch_all": 0}
89
+
90
+ class FakeProvider:
91
+ async def verify(self, email, mx_host):
92
+ calls["verify"] += 1
93
+ return SMTPResult(verified=True, smtp_code=250)
94
+
95
+ async def catch_all(self, domain, mx_host):
96
+ calls["catch_all"] += 1
97
+ return (False, 0.9)
98
+
99
+ engine = EmailValidationEngine(mailbox=FakeProvider())
100
+ with (
101
+ patch("app.validator.engine.validate_syntax", return_value=_syntax()),
102
+ patch("app.validator.engine.check_dns", new=AsyncMock(return_value=_dns())),
103
+ patch("app.validator.engine.check_disposable", return_value=DisposableResult(
104
+ is_disposable=False, is_free_provider=False, is_role_based=False
105
+ )),
106
+ ):
107
+ result = await engine.validate("person@example.test", deep=True)
108
+
109
+ self.assertEqual(calls["verify"], 1)
110
+ self.assertEqual(calls["catch_all"], 1)
111
+ self.assertTrue(result.smtp.verified)
112
+ self.assertIn("smtp", result.checks_run)
113
+ self.assertIn("catch_all", result.checks_run)
114
+
115
+
116
+ class BulkRequestDeepFieldTests(unittest.TestCase):
117
+ def test_bulk_request_accepts_deep_flag(self):
118
+ from app.models import BulkEmailRequest
119
+
120
+ req = BulkEmailRequest(emails=["a@example.com"], deep=True)
121
+ self.assertTrue(req.deep)
122
+
123
+ def test_bulk_request_defaults_deep_true(self):
124
+ # Product promise: bulk runs the full 7-layer pipeline (1 credit/email).
125
+ from app.models import BulkEmailRequest
126
+
127
+ req = BulkEmailRequest(emails=["a@example.com"])
128
+ self.assertTrue(req.deep)
129
+
130
+
131
+ if __name__ == "__main__":
132
+ unittest.main()
tests/test_cache_config.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ from unittest.mock import AsyncMock, patch
3
+
4
+ from app.utils import cache
5
+
6
+
7
+ class RedisConfigurationTests(unittest.IsolatedAsyncioTestCase):
8
+ async def asyncSetUp(self):
9
+ self.previous_url = cache.settings.redis_url
10
+ cache._redis_client = None
11
+
12
+ async def asyncTearDown(self):
13
+ cache.settings.redis_url = self.previous_url
14
+ cache._redis_client = None
15
+
16
+ async def test_missing_redis_does_not_create_cloud_database(self):
17
+ cache.settings.redis_url = ""
18
+ with (
19
+ patch("app.utils.cache._HAS_REDIS", True),
20
+ patch("app.utils.cache.aioredis.from_url") as from_url,
21
+ patch(
22
+ "app.utils.cache.provision_free_tier",
23
+ new=AsyncMock(return_value=None),
24
+ create=True,
25
+ ) as provision,
26
+ ):
27
+ result = await cache.get_redis()
28
+
29
+ self.assertIsNone(result)
30
+ from_url.assert_not_called()
31
+ provision.assert_not_awaited()
32
+
33
+ async def test_explicit_upstash_tls_url_is_used(self):
34
+ url = "rediss://default:placeholder@redis.example.test:6379/0"
35
+ cache.settings.redis_url = url
36
+ client = type("RedisClient", (), {"ping": AsyncMock(return_value=True)})()
37
+ with (
38
+ patch("app.utils.cache._HAS_REDIS", True),
39
+ patch("app.utils.cache.aioredis.from_url", return_value=client) as from_url,
40
+ ):
41
+ result = await cache.get_redis()
42
+
43
+ self.assertIs(result, client)
44
+ from_url.assert_called_once()
45
+ self.assertEqual(from_url.call_args.args[0], url)
46
+
47
+
48
+ if __name__ == "__main__":
49
+ unittest.main()
tests/test_dns_correctness.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ from unittest.mock import patch
3
+
4
+ import dns.exception
5
+ import dns.resolver
6
+
7
+ from app.validator.dns_check import check_dns
8
+
9
+
10
+ class ResolverStub:
11
+ timeout = 0
12
+ lifetime = 0
13
+
14
+ def __init__(self, responses):
15
+ self.responses = responses
16
+
17
+ async def resolve(self, name, record_type):
18
+ response = self.responses.get((name, record_type))
19
+ if isinstance(response, Exception):
20
+ raise response
21
+ if response is None:
22
+ raise dns.resolver.NoAnswer()
23
+ return response
24
+
25
+
26
+ class DNSCheckTests(unittest.IsolatedAsyncioTestCase):
27
+ async def test_timeout_is_reported_as_transient(self):
28
+ resolver = ResolverStub({("example.test", "MX"): dns.exception.Timeout()})
29
+ with patch(
30
+ "app.validator.dns_check.dns.asyncresolver.Resolver", return_value=resolver
31
+ ):
32
+ result = await check_dns("example.test")
33
+
34
+ self.assertEqual(result.error_code, "timeout")
35
+ self.assertFalse(result.domain_exists)
36
+
37
+ async def test_no_nameservers_is_reported_as_transient(self):
38
+ resolver = ResolverStub(
39
+ {("unavailable.test", "MX"): dns.resolver.NoNameservers()}
40
+ )
41
+ with patch(
42
+ "app.validator.dns_check.dns.asyncresolver.Resolver", return_value=resolver
43
+ ):
44
+ result = await check_dns("unavailable.test")
45
+
46
+ self.assertEqual(result.error_code, "resolver_error")
47
+
48
+ async def test_nxdomain_is_reported_as_definitive(self):
49
+ resolver = ResolverStub({("missing.test", "MX"): dns.resolver.NXDOMAIN()})
50
+ with patch(
51
+ "app.validator.dns_check.dns.asyncresolver.Resolver", return_value=resolver
52
+ ):
53
+ result = await check_dns("missing.test")
54
+
55
+ self.assertEqual(result.error_code, "nxdomain")
56
+ self.assertFalse(result.domain_exists)
57
+
58
+ async def test_a_record_fallback_is_preserved(self):
59
+ resolver = ResolverStub(
60
+ {
61
+ ("mail.example.test", "MX"): dns.resolver.NoAnswer(),
62
+ ("mail.example.test", "A"): ["192.0.2.10"],
63
+ }
64
+ )
65
+ with patch(
66
+ "app.validator.dns_check.dns.asyncresolver.Resolver", return_value=resolver
67
+ ):
68
+ result = await check_dns("mail.example.test")
69
+
70
+ self.assertTrue(result.domain_exists)
71
+ self.assertFalse(result.has_mx_records)
72
+ self.assertTrue(result.a_fallback)
73
+ self.assertEqual(result.mx_records[0]["host"], "mail.example.test")
74
+
75
+ async def test_no_mx_or_address_is_distinct_from_transient_dns_error(self):
76
+ resolver = ResolverStub(
77
+ {
78
+ ("no-mail.example.test", "MX"): dns.resolver.NoAnswer(),
79
+ ("no-mail.example.test", "A"): dns.resolver.NoAnswer(),
80
+ ("no-mail.example.test", "AAAA"): dns.resolver.NoAnswer(),
81
+ }
82
+ )
83
+ with patch(
84
+ "app.validator.dns_check.dns.asyncresolver.Resolver", return_value=resolver
85
+ ):
86
+ result = await check_dns("no-mail.example.test")
87
+
88
+ self.assertEqual(result.error_code, "no_mail_records")
89
+ self.assertTrue(result.domain_exists)
90
+ self.assertFalse(result.has_mx_records)
91
+ self.assertFalse(result.a_fallback)
92
+
93
+
94
+ if __name__ == "__main__":
95
+ unittest.main()
tests/test_engine_dns_failures.py ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ from unittest.mock import AsyncMock, patch
3
+
4
+ from app.models import (
5
+ DNSResult,
6
+ DisposableResult,
7
+ RiskLevel,
8
+ ScoringResult,
9
+ SMTPResult,
10
+ SyntaxResult,
11
+ ValidationStatus,
12
+ )
13
+ from app.validator.engine import EmailValidationEngine, _mask_email_for_log
14
+
15
+
16
+ class EngineDNSFailureTests(unittest.IsolatedAsyncioTestCase):
17
+ def test_status_thresholds_match_risk_score_bands(self):
18
+ engine = EmailValidationEngine()
19
+
20
+ self.assertEqual(
21
+ engine._determine_status(
22
+ ScoringResult(score=40, risk_level=RiskLevel.MEDIUM)
23
+ ),
24
+ ValidationStatus.RISKY,
25
+ )
26
+ self.assertEqual(
27
+ engine._determine_status(
28
+ ScoringResult(score=39, risk_level=RiskLevel.HIGH)
29
+ ),
30
+ ValidationStatus.INVALID,
31
+ )
32
+
33
+ def test_logs_mask_local_part(self):
34
+ self.assertEqual(
35
+ _mask_email_for_log("person@example.test"), "p***@example.test"
36
+ )
37
+ self.assertEqual(_mask_email_for_log("not-an-address"), "[invalid-email]")
38
+
39
+ async def test_transient_dns_failure_is_risky_without_smtp(self):
40
+ dns_result = DNSResult(
41
+ domain_exists=False,
42
+ has_mx_records=False,
43
+ error="DNS timeout",
44
+ error_code="timeout",
45
+ )
46
+ engine = EmailValidationEngine()
47
+ with (
48
+ patch(
49
+ "app.validator.engine.validate_syntax",
50
+ return_value=SyntaxResult(
51
+ passed=True,
52
+ normalized_email="person@example.test",
53
+ domain="example.test",
54
+ local_part="person",
55
+ ),
56
+ ),
57
+ patch(
58
+ "app.validator.engine.check_dns", new=AsyncMock(return_value=dns_result)
59
+ ),
60
+ patch.object(engine, "use_proxies", False),
61
+ patch(
62
+ "app.validator.mailbox_provider.smtp_verifier.verify", new=AsyncMock()
63
+ ) as smtp_verify,
64
+ ):
65
+ result = await engine.validate("person@example.test", deep=True)
66
+
67
+ self.assertEqual(result.status, ValidationStatus.RISKY)
68
+ self.assertEqual(result.dns.error_code, "timeout")
69
+ self.assertEqual(result.scoring.score, 50)
70
+ self.assertEqual(result.scoring.risk_level.value, "medium")
71
+ self.assertEqual(result.scoring.breakdown["DNS_TRANSIENT_FAILURE"], -50)
72
+ smtp_verify.assert_not_awaited()
73
+
74
+ async def test_a_record_fallback_is_risky_even_if_smtp_accepts(self):
75
+ dns_result = DNSResult(
76
+ domain_exists=True,
77
+ has_mx_records=False,
78
+ mx_records=[{"host": "example.test", "priority": 0}],
79
+ a_fallback=True,
80
+ )
81
+ engine = EmailValidationEngine()
82
+ with (
83
+ patch(
84
+ "app.validator.engine.validate_syntax",
85
+ return_value=SyntaxResult(
86
+ passed=True,
87
+ normalized_email="person@example.test",
88
+ domain="example.test",
89
+ local_part="person",
90
+ ),
91
+ ),
92
+ patch(
93
+ "app.validator.engine.check_dns", new=AsyncMock(return_value=dns_result)
94
+ ),
95
+ patch("app.validator.engine.check_disposable", return_value=None),
96
+ patch(
97
+ "app.validator.mailbox_provider.smtp_verifier.verify",
98
+ new=AsyncMock(return_value=SMTPResult(verified=True)),
99
+ ),
100
+ patch(
101
+ "app.validator.mailbox_provider.smtp_verifier.check_catch_all",
102
+ new=AsyncMock(return_value=(False, 0.9)),
103
+ ),
104
+ ):
105
+ result = await engine.validate("person@example.test", deep=True)
106
+
107
+ self.assertEqual(result.status, ValidationStatus.RISKY)
108
+ self.assertTrue(result.dns.a_fallback)
109
+
110
+ async def test_fast_mode_does_not_claim_mailbox_validity(self):
111
+ engine = EmailValidationEngine()
112
+ with (
113
+ patch(
114
+ "app.validator.engine.validate_syntax",
115
+ return_value=SyntaxResult(
116
+ passed=True,
117
+ normalized_email="person@example.test",
118
+ domain="example.test",
119
+ local_part="person",
120
+ ),
121
+ ),
122
+ patch(
123
+ "app.validator.engine.check_dns",
124
+ new=AsyncMock(
125
+ return_value=DNSResult(
126
+ domain_exists=True,
127
+ has_mx_records=True,
128
+ mx_records=[{"host": "mx.example.test", "priority": 10}],
129
+ )
130
+ ),
131
+ ),
132
+ patch(
133
+ "app.validator.engine.check_disposable",
134
+ return_value=DisposableResult(
135
+ is_disposable=False,
136
+ is_free_provider=False,
137
+ is_role_based=False,
138
+ ),
139
+ ),
140
+ ):
141
+ result = await engine.validate("person@example.test", deep=False)
142
+
143
+ self.assertEqual(result.status, ValidationStatus.RISKY)
144
+ self.assertIsNone(result.smtp)
145
+ self.assertEqual(result.scoring.score, 70)
146
+ self.assertEqual(result.scoring.risk_level.value, "medium")
147
+ self.assertEqual(
148
+ result.scoring.breakdown["FAST_MODE_SKIPPED_MAILBOX_CHECK"], -30
149
+ )
150
+ self.assertIn("Mailbox verification was not performed", result.scoring.warnings)
151
+
152
+ async def test_domain_without_mail_routes_is_invalid(self):
153
+ dns_result = DNSResult(
154
+ domain_exists=True,
155
+ has_mx_records=False,
156
+ error="Domain has no MX, A, or AAAA records",
157
+ error_code="no_mail_records",
158
+ )
159
+ engine = EmailValidationEngine()
160
+ with (
161
+ patch(
162
+ "app.validator.engine.validate_syntax",
163
+ return_value=SyntaxResult(
164
+ passed=True,
165
+ normalized_email="person@example.test",
166
+ domain="example.test",
167
+ local_part="person",
168
+ ),
169
+ ),
170
+ patch(
171
+ "app.validator.engine.check_dns", new=AsyncMock(return_value=dns_result)
172
+ ),
173
+ patch(
174
+ "app.validator.mailbox_provider.smtp_verifier.verify", new=AsyncMock()
175
+ ) as smtp_verify,
176
+ ):
177
+ result = await engine.validate("person@example.test", deep=True)
178
+
179
+ self.assertEqual(result.status, ValidationStatus.INVALID)
180
+ self.assertEqual(result.scoring.score, 0)
181
+ smtp_verify.assert_not_awaited()
182
+
183
+
184
+ if __name__ == "__main__":
185
+ unittest.main()
tests/test_engine_metadata.py ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ from unittest.mock import AsyncMock, patch
3
+
4
+ from app.models import (
5
+ CatchAllResult,
6
+ DNSResult,
7
+ DisposableResult,
8
+ ScoringResult,
9
+ SMTPResult,
10
+ SyntaxResult,
11
+ ValidationStatus,
12
+ )
13
+ from app.config import settings
14
+ from app.validator.engine import EmailValidationEngine
15
+
16
+
17
+ def _syntax(**kw):
18
+ base = dict(
19
+ passed=True,
20
+ normalized_email="person@example.test",
21
+ domain="example.test",
22
+ local_part="person",
23
+ )
24
+ base.update(kw)
25
+ return SyntaxResult(**base)
26
+
27
+
28
+ def _dns(**kw):
29
+ base = dict(
30
+ domain_exists=True,
31
+ has_mx_records=True,
32
+ mx_records=[{"host": "mx.example.test", "priority": 10}],
33
+ )
34
+ base.update(kw)
35
+ return DNSResult(**base)
36
+
37
+
38
+ def _disposable(**kw):
39
+ base = dict(is_disposable=False, is_free_provider=False, is_role_based=False)
40
+ base.update(kw)
41
+ return DisposableResult(**base)
42
+
43
+
44
+ class EngineMetadataTests(unittest.IsolatedAsyncioTestCase):
45
+ """The engine must emit the provenance fields the frontend contract expects:
46
+ checks_run, reason_code, validator_version, run_id (RC5)."""
47
+
48
+ async def test_deep_result_emits_provenance_fields(self):
49
+ engine = EmailValidationEngine()
50
+ with (
51
+ patch("app.validator.engine.validate_syntax", return_value=_syntax()),
52
+ patch(
53
+ "app.validator.engine.check_dns",
54
+ new=AsyncMock(return_value=_dns()),
55
+ ),
56
+ patch(
57
+ "app.validator.engine.check_disposable",
58
+ return_value=_disposable(),
59
+ ),
60
+ patch(
61
+ "app.validator.mailbox_provider.smtp_verifier.verify",
62
+ new=AsyncMock(return_value=SMTPResult(verified=True, smtp_code=250)),
63
+ ),
64
+ patch(
65
+ "app.validator.mailbox_provider.smtp_verifier.check_catch_all",
66
+ new=AsyncMock(return_value=(False, 0.9)),
67
+ ),
68
+ ):
69
+ result = await engine.validate("person@example.test", deep=True)
70
+
71
+ # Provenance: which layers ran, engine version, a correlation id.
72
+ self.assertEqual(
73
+ result.checks_run,
74
+ ["syntax", "dns", "mx", "disposable", "catch_all", "smtp", "scoring"],
75
+ )
76
+ self.assertEqual(result.validator_version, settings.app_version)
77
+ self.assertTrue(result.run_id)
78
+ self.assertGreater(len(result.run_id), 5)
79
+
80
+ async def test_fast_mode_checks_run_excludes_mailbox_layers(self):
81
+ engine = EmailValidationEngine()
82
+ with (
83
+ patch("app.validator.engine.validate_syntax", return_value=_syntax()),
84
+ patch(
85
+ "app.validator.engine.check_dns",
86
+ new=AsyncMock(return_value=_dns()),
87
+ ),
88
+ patch(
89
+ "app.validator.engine.check_disposable",
90
+ return_value=_disposable(),
91
+ ),
92
+ ):
93
+ result = await engine.validate("person@example.test", deep=False)
94
+
95
+ # deep=False never runs catch_all/smtp, so those layers must be absent.
96
+ self.assertEqual(
97
+ result.checks_run, ["syntax", "dns", "mx", "disposable", "scoring"]
98
+ )
99
+ self.assertIsNone(result.smtp)
100
+ self.assertIsNone(result.catch_all)
101
+
102
+ async def test_reason_code_dns_timeout(self):
103
+ engine = EmailValidationEngine()
104
+ with (
105
+ patch("app.validator.engine.validate_syntax", return_value=_syntax()),
106
+ patch(
107
+ "app.validator.engine.check_dns",
108
+ new=AsyncMock(
109
+ return_value=_dns(
110
+ domain_exists=False,
111
+ has_mx_records=False,
112
+ error="DNS timeout",
113
+ error_code="timeout",
114
+ )
115
+ ),
116
+ ),
117
+ ):
118
+ result = await engine.validate("person@example.test", deep=True)
119
+
120
+ self.assertEqual(result.reason_code, "dns_timeout")
121
+
122
+ async def test_reason_code_nxdomain(self):
123
+ engine = EmailValidationEngine()
124
+ with (
125
+ patch("app.validator.engine.validate_syntax", return_value=_syntax()),
126
+ patch(
127
+ "app.validator.engine.check_dns",
128
+ new=AsyncMock(
129
+ return_value=_dns(
130
+ domain_exists=False,
131
+ has_mx_records=False,
132
+ error="Domain not found",
133
+ error_code="nxdomain",
134
+ )
135
+ ),
136
+ ),
137
+ ):
138
+ result = await engine.validate("person@example.test", deep=True)
139
+
140
+ self.assertEqual(result.reason_code, "nxdomain")
141
+
142
+ async def test_reason_code_catch_all(self):
143
+ engine = EmailValidationEngine()
144
+ with (
145
+ patch("app.validator.engine.validate_syntax", return_value=_syntax()),
146
+ patch(
147
+ "app.validator.engine.check_dns",
148
+ new=AsyncMock(return_value=_dns()),
149
+ ),
150
+ patch(
151
+ "app.validator.engine.check_disposable",
152
+ return_value=_disposable(),
153
+ ),
154
+ patch(
155
+ "app.validator.mailbox_provider.smtp_verifier.verify",
156
+ new=AsyncMock(return_value=SMTPResult(verified=True, smtp_code=250)),
157
+ ),
158
+ patch(
159
+ "app.validator.mailbox_provider.smtp_verifier.check_catch_all",
160
+ new=AsyncMock(return_value=(True, 0.95)),
161
+ ),
162
+ ):
163
+ result = await engine.validate("person@example.test", deep=True)
164
+
165
+ self.assertEqual(result.reason_code, "catch_all_detected")
166
+ self.assertEqual(result.status, ValidationStatus.RISKY)
167
+
168
+ async def test_reason_code_smtp_timeout(self):
169
+ engine = EmailValidationEngine()
170
+ with (
171
+ patch("app.validator.engine.validate_syntax", return_value=_syntax()),
172
+ patch(
173
+ "app.validator.engine.check_dns",
174
+ new=AsyncMock(return_value=_dns()),
175
+ ),
176
+ patch(
177
+ "app.validator.engine.check_disposable",
178
+ return_value=_disposable(),
179
+ ),
180
+ patch(
181
+ "app.validator.mailbox_provider.smtp_verifier.verify",
182
+ new=AsyncMock(
183
+ return_value=SMTPResult(verified=None, error="SMTP verification timed out")
184
+ ),
185
+ ),
186
+ patch(
187
+ "app.validator.mailbox_provider.smtp_verifier.check_catch_all",
188
+ new=AsyncMock(return_value=(None, 0.0)),
189
+ ),
190
+ ):
191
+ result = await engine.validate("person@example.test", deep=True)
192
+
193
+ self.assertEqual(result.reason_code, "smtp_timeout")
194
+
195
+
196
+ class CatchAllUnknownTests(unittest.IsolatedAsyncioTestCase):
197
+ """An unreachable catch-all probe must read as UNKNOWN (None), never as
198
+ False ("domain rejects unknown recipients"). RC6."""
199
+
200
+ async def test_catch_all_probe_unavailable_is_unknown_not_false(self):
201
+ engine = EmailValidationEngine()
202
+ with (
203
+ patch("app.validator.engine.validate_syntax", return_value=_syntax()),
204
+ patch(
205
+ "app.validator.engine.check_dns",
206
+ new=AsyncMock(return_value=_dns()),
207
+ ),
208
+ patch(
209
+ "app.validator.engine.check_disposable",
210
+ return_value=_disposable(),
211
+ ),
212
+ patch(
213
+ "app.validator.mailbox_provider.smtp_verifier.verify",
214
+ new=AsyncMock(
215
+ return_value=SMTPResult(verified=None, error="SMTP verification timed out")
216
+ ),
217
+ ),
218
+ # Probe returned "unknown" (None, 0.0) — the blocked-host case.
219
+ patch(
220
+ "app.validator.mailbox_provider.smtp_verifier.check_catch_all",
221
+ new=AsyncMock(return_value=(None, 0.0)),
222
+ ),
223
+ ):
224
+ result = await engine.validate("person@example.test", deep=True)
225
+
226
+ self.assertIsNone(result.catch_all.is_catch_all)
227
+ self.assertEqual(result.catch_all.confidence, 0.0)
228
+
229
+ async def test_catch_all_exception_is_unknown_not_false(self):
230
+ engine = EmailValidationEngine()
231
+ with (
232
+ patch("app.validator.engine.validate_syntax", return_value=_syntax()),
233
+ patch(
234
+ "app.validator.engine.check_dns",
235
+ new=AsyncMock(return_value=_dns()),
236
+ ),
237
+ patch(
238
+ "app.validator.engine.check_disposable",
239
+ return_value=_disposable(),
240
+ ),
241
+ patch(
242
+ "app.validator.mailbox_provider.smtp_verifier.verify",
243
+ new=AsyncMock(return_value=SMTPResult(verified=True, smtp_code=250)),
244
+ ),
245
+ patch(
246
+ "app.validator.mailbox_provider.smtp_verifier.check_catch_all",
247
+ new=AsyncMock(side_effect=RuntimeError("port 25 unreachable")),
248
+ ),
249
+ ):
250
+ result = await engine.validate("person@example.test", deep=True)
251
+
252
+ self.assertIsNone(result.catch_all.is_catch_all)
253
+
254
+
255
+ class ScoreCoherenceTests(unittest.IsolatedAsyncioTestCase):
256
+ """A perfect score (100/low) must only appear when a mailbox verdict exists.
257
+ Unverified-but-plausible rows are capped and marked medium. RC4."""
258
+
259
+ async def test_smtp_verified_can_reach_high_score(self):
260
+ engine = EmailValidationEngine()
261
+ with (
262
+ patch("app.validator.engine.validate_syntax", return_value=_syntax()),
263
+ patch(
264
+ "app.validator.engine.check_dns",
265
+ new=AsyncMock(return_value=_dns()),
266
+ ),
267
+ patch(
268
+ "app.validator.engine.check_disposable",
269
+ return_value=_disposable(is_free_provider=False),
270
+ ),
271
+ patch(
272
+ "app.validator.mailbox_provider.smtp_verifier.verify",
273
+ new=AsyncMock(return_value=SMTPResult(verified=True, smtp_code=250)),
274
+ ),
275
+ patch(
276
+ "app.validator.mailbox_provider.smtp_verifier.check_catch_all",
277
+ new=AsyncMock(return_value=(False, 0.9)),
278
+ ),
279
+ ):
280
+ result = await engine.validate("person@example.test", deep=True)
281
+
282
+ # Definitive mailbox acceptance + clean domain → low risk, high score.
283
+ self.assertGreaterEqual(result.scoring.score, 75)
284
+ self.assertEqual(result.scoring.risk_level.value, "low")
285
+ self.assertEqual(result.status, ValidationStatus.VALID)
286
+
287
+ async def test_unverified_mailbox_never_scores_100(self):
288
+ engine = EmailValidationEngine()
289
+ with (
290
+ patch("app.validator.engine.validate_syntax", return_value=_syntax()),
291
+ patch(
292
+ "app.validator.engine.check_dns",
293
+ new=AsyncMock(return_value=_dns()),
294
+ ),
295
+ patch(
296
+ "app.validator.engine.check_disposable",
297
+ return_value=_disposable(),
298
+ ),
299
+ patch(
300
+ "app.validator.mailbox_provider.smtp_verifier.verify",
301
+ new=AsyncMock(
302
+ return_value=SMTPResult(verified=None, error="SMTP verification timed out")
303
+ ),
304
+ ),
305
+ patch(
306
+ "app.validator.mailbox_provider.smtp_verifier.check_catch_all",
307
+ new=AsyncMock(return_value=(None, 0.0)),
308
+ ),
309
+ ):
310
+ result = await engine.validate("person@example.test", deep=True)
311
+
312
+ # Inconclusive SMTP caps the score below "low risk" territory.
313
+ self.assertLess(result.scoring.score, 75)
314
+ self.assertNotEqual(result.scoring.risk_level.value, "low")
315
+
316
+
317
+ if __name__ == "__main__":
318
+ unittest.main()
tests/test_mailbox_provider.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ from unittest.mock import AsyncMock, patch
3
+
4
+ from app.config import settings
5
+ from app.models import SMTPResult
6
+ from app.validator.mailbox_provider import (
7
+ MailboxProvider,
8
+ MillionVerifierProvider,
9
+ LocalSmtpProvider,
10
+ resolve_provider,
11
+ map_mv_result,
12
+ )
13
+
14
+
15
+ class MapMVResultTests(unittest.TestCase):
16
+ """MillionVerifier live schema (verified 2026-10-11 against API_KEY_FOR_TEST):
17
+ {"result": "ok"|"catch_all"|"invalid"|"disposable"|"unknown"|"error",
18
+ "quality": "good"|"risky"|"bad", "resultcode": 1..4, "free": bool, "role": bool}
19
+ The mapping must translate that into our SMTPResult taxonomy."""
20
+
21
+ def test_ok_maps_to_verified(self):
22
+ r = map_mv_result({"result": "ok", "quality": "good", "resultcode": 1, "free": False, "role": False})
23
+ self.assertTrue(r.verified)
24
+
25
+ def test_invalid_maps_to_rejected_5xx(self):
26
+ r = map_mv_result({"result": "invalid", "quality": "bad", "resultcode": 4, "free": False, "role": False})
27
+ self.assertFalse(r.verified)
28
+ self.assertEqual(r.smtp_code, 550)
29
+
30
+ def test_catch_all_maps_to_inconclusive(self):
31
+ # A catch-all domain accepts the probe but proves nothing about the
32
+ # specific mailbox — it must NOT read as verified.
33
+ r = map_mv_result({"result": "catch_all", "quality": "risky", "resultcode": 2, "free": False, "role": False})
34
+ self.assertIsNone(r.verified)
35
+
36
+ def test_unknown_maps_to_inconclusive(self):
37
+ r = map_mv_result({"result": "unknown", "quality": "risky", "resultcode": 5, "free": False, "role": False})
38
+ self.assertIsNone(r.verified)
39
+
40
+ def test_error_maps_to_inconclusive_with_error(self):
41
+ r = map_mv_result({"result": "error", "error": "rate limited"})
42
+ self.assertIsNone(r.verified)
43
+ self.assertIn("rate limited", r.error)
44
+
45
+
46
+ class MillionVerifierProviderTests(unittest.IsolatedAsyncioTestCase):
47
+ async def test_verify_calls_api_with_email_and_key(self):
48
+ provider = MillionVerifierProvider(api_key="test-key", timeout=5)
49
+ fake = {"result": "ok", "quality": "good", "resultcode": 1, "free": False, "role": False}
50
+ with patch("app.validator.mailbox_provider.httpx.AsyncClient") as client_cls:
51
+ resp = AsyncMock()
52
+ resp.raise_for_status = lambda: None
53
+ resp.json = lambda: fake
54
+ client_cls.return_value.__aenter__ = AsyncMock(return_value=AsyncMock(get=AsyncMock(return_value=resp)))
55
+ client_cls.return_value.__aexit__ = AsyncMock(return_value=False)
56
+ result = await provider.verify("a@example.com", "mx.example.com")
57
+ self.assertTrue(result.verified)
58
+
59
+ async def test_catch_all_probe_gibberish_not_real_address(self):
60
+ # catch-all must be detected with a gibberish local part, never the
61
+ # real address (that would be a false negative).
62
+ provider = MillionVerifierProvider(api_key="test-key", timeout=5)
63
+ captured = {}
64
+
65
+ with patch("app.validator.mailbox_provider.httpx.AsyncClient") as client_cls:
66
+ async def fake_get(url, params=None, timeout=None):
67
+ captured["params"] = params
68
+ resp = AsyncMock()
69
+ resp.raise_for_status = lambda: None
70
+ resp.json = lambda: {"result": "catch_all", "quality": "risky", "resultcode": 2}
71
+ return resp
72
+ client_cls.return_value.__aenter__ = AsyncMock(return_value=AsyncMock(get=fake_get))
73
+ client_cls.return_value.__aexit__ = AsyncMock(return_value=False)
74
+ is_catch_all, confidence = await provider.catch_all("example.com", "mx.example.com")
75
+
76
+ self.assertNotIn("example.com", captured["params"]["email"].split("@")[0])
77
+ self.assertTrue(is_catch_all)
78
+ self.assertGreater(confidence, 0.5)
79
+
80
+
81
+ class ResolveProviderTests(unittest.TestCase):
82
+ def test_api_forced(self):
83
+ with patch.object(settings, "mailbox_provider", "api"), patch.object(
84
+ settings, "mv_api_key", "k"
85
+ ):
86
+ self.assertIsInstance(resolve_provider(), MillionVerifierProvider)
87
+
88
+ def test_local_forced(self):
89
+ with patch.object(settings, "mailbox_provider", "local"):
90
+ self.assertIsInstance(resolve_provider(), LocalSmtpProvider)
91
+
92
+ def test_auto_with_key_uses_api(self):
93
+ with patch.object(settings, "mailbox_provider", "auto"), patch.object(
94
+ settings, "mv_api_key", "k"
95
+ ):
96
+ self.assertIsInstance(resolve_provider(), MillionVerifierProvider)
97
+
98
+ def test_auto_without_key_uses_local(self):
99
+ with patch.object(settings, "mailbox_provider", "auto"), patch.object(
100
+ settings, "mv_api_key", ""
101
+ ):
102
+ self.assertIsInstance(resolve_provider(), LocalSmtpProvider)
103
+
104
+ def test_provider_satisfies_protocol(self):
105
+ # Structural check: both providers expose verify + catch_all.
106
+ self.assertTrue(hasattr(MillionVerifierProvider, "verify"))
107
+ self.assertTrue(hasattr(MillionVerifierProvider, "catch_all"))
108
+ self.assertTrue(hasattr(LocalSmtpProvider, "verify"))
109
+ self.assertTrue(hasattr(LocalSmtpProvider, "catch_all"))
110
+
111
+
112
+ class CircuitBreakerTests(unittest.TestCase):
113
+ """Blocked egress must fail fast instead of burning smtp_timeout per row."""
114
+
115
+ def test_local_provider_opens_circuit_after_threshold(self):
116
+ p = LocalSmtpProvider(fail_threshold=2, cooldown_seconds=60)
117
+ p.record_failure()
118
+ self.assertFalse(p.circuit_open)
119
+ p.record_failure()
120
+ self.assertTrue(p.circuit_open)
121
+
122
+ def test_open_circuit_returns_immediately_unavailable(self):
123
+ import asyncio
124
+
125
+ p = LocalSmtpProvider(fail_threshold=1, cooldown_seconds=60)
126
+ p.record_failure()
127
+ result = asyncio.run(p.verify("a@example.com", "mx.example.com"))
128
+ self.assertIsNone(result.verified)
129
+ self.assertIn("unavailable", (result.error or "").lower())
130
+
131
+ def test_circuit_closes_after_cooldown(self):
132
+ import time as _t
133
+
134
+ p = LocalSmtpProvider(fail_threshold=1, cooldown_seconds=60)
135
+ p.record_failure()
136
+ self.assertTrue(p.circuit_open)
137
+ # Simulate the cooldown elapsing: the open-window is now in the past.
138
+ p._open_until = _t.monotonic() - 1
139
+ self.assertFalse(p.circuit_open)
140
+ self.assertFalse(p.circuit_open_after_cooldown())
141
+
142
+ def test_zero_cooldown_never_stays_open(self):
143
+ # cooldown_seconds=0 opens and closes in the same instant — there is no
144
+ # window, so it must not read as open on the next call.
145
+ p = LocalSmtpProvider(fail_threshold=1, cooldown_seconds=0)
146
+ p.record_failure()
147
+ self.assertFalse(p.circuit_open)
148
+
149
+
150
+ if __name__ == "__main__":
151
+ unittest.main()
tests/test_production_config.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from pydantic import ValidationError
4
+
5
+ from app.config import Settings
6
+
7
+
8
+ class ProductionSettingsTests(unittest.TestCase):
9
+ def test_production_accepts_explicit_secure_configuration(self):
10
+ settings = Settings(
11
+ _env_file=None,
12
+ app_environment="production",
13
+ debug=False,
14
+ license_enforcement="true",
15
+ supabase_url="https://project.example",
16
+ supabase_service_role_key="server-only-key",
17
+ cors_origins=["https://app.example.com"],
18
+ )
19
+
20
+ self.assertEqual(settings.app_environment, "production")
21
+
22
+ def test_production_rejects_demo_or_insecure_configuration(self):
23
+ with self.assertRaisesRegex(
24
+ ValidationError,
25
+ "DEBUG must be false.*LICENSE_ENFORCEMENT must be true.*"
26
+ "SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY are required.*"
27
+ "CORS_ORIGINS must contain only HTTPS origins",
28
+ ):
29
+ Settings(
30
+ _env_file=None,
31
+ app_environment="production",
32
+ debug=True,
33
+ license_enforcement="false",
34
+ cors_origins=["http://localhost:5173"],
35
+ )
36
+
37
+ def test_development_keeps_demo_configuration_available(self):
38
+ settings = Settings(
39
+ _env_file=None,
40
+ app_environment="development",
41
+ license_enforcement="false",
42
+ cors_origins=["http://localhost:5173"],
43
+ )
44
+
45
+ self.assertEqual(settings.license_enforcement, "false")
46
+
47
+
48
+ if __name__ == "__main__":
49
+ unittest.main()
tests/test_scoring_claims.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ from app.models import (
4
+ CatchAllResult,
5
+ DNSResult,
6
+ DisposableResult,
7
+ SMTPResult,
8
+ SyntaxResult,
9
+ )
10
+ from app.validator.scoring import calculate_score
11
+
12
+
13
+ class ScoringClaimTests(unittest.TestCase):
14
+ def test_transient_dns_has_fixed_medium_risk_score_and_audit_code(self):
15
+ result = calculate_score(
16
+ SyntaxResult(passed=True),
17
+ DNSResult(
18
+ domain_exists=False,
19
+ has_mx_records=False,
20
+ error_code="timeout",
21
+ ),
22
+ None,
23
+ None,
24
+ None,
25
+ )
26
+
27
+ self.assertEqual(result.score, 50)
28
+ self.assertEqual(result.risk_level.value, "medium")
29
+ self.assertEqual(result.breakdown["DNS_TRANSIENT_FAILURE"], -50)
30
+
31
+ def test_missing_mail_routes_is_a_zero_score_hard_failure(self):
32
+ result = calculate_score(
33
+ SyntaxResult(passed=True),
34
+ DNSResult(
35
+ domain_exists=True,
36
+ has_mx_records=False,
37
+ error_code="no_mail_records",
38
+ ),
39
+ None,
40
+ None,
41
+ None,
42
+ )
43
+
44
+ self.assertEqual(result.score, 0)
45
+ self.assertEqual(result.risk_level.value, "high")
46
+ self.assertEqual(result.breakdown["DNS_MX_MISSING"], -100)
47
+
48
+ def test_explicit_mailbox_unknown_is_a_zero_score_hard_failure(self):
49
+ result = calculate_score(
50
+ SyntaxResult(passed=True),
51
+ DNSResult(domain_exists=True, has_mx_records=True),
52
+ None,
53
+ None,
54
+ SMTPResult(
55
+ verified=False,
56
+ smtp_code=550,
57
+ smtp_message="550 5.1.1 The recipient does not exist",
58
+ ),
59
+ )
60
+
61
+ self.assertEqual(result.score, 0)
62
+ self.assertEqual(result.risk_level.value, "high")
63
+ self.assertEqual(result.breakdown["SMTP_MAILBOX_NOT_FOUND"], -100)
64
+
65
+ def test_legacy_user_unknown_rejection_is_detected_without_enhanced_code(self):
66
+ result = calculate_score(
67
+ SyntaxResult(passed=True),
68
+ DNSResult(domain_exists=True, has_mx_records=True),
69
+ None,
70
+ None,
71
+ SMTPResult(
72
+ verified=False,
73
+ smtp_code=550,
74
+ smtp_message="550 User Unknown",
75
+ ),
76
+ )
77
+
78
+ self.assertEqual(result.score, 0)
79
+ self.assertIn("SMTP_MAILBOX_NOT_FOUND", result.breakdown)
80
+
81
+ def test_inconclusive_smtp_is_medium_risk_not_an_implicit_pass(self):
82
+ result = calculate_score(
83
+ SyntaxResult(passed=True),
84
+ DNSResult(domain_exists=True, has_mx_records=True),
85
+ None,
86
+ None,
87
+ SMTPResult(verified=None, error="SMTP connection refused"),
88
+ )
89
+
90
+ self.assertEqual(result.score, 70)
91
+ self.assertEqual(result.risk_level.value, "medium")
92
+ self.assertEqual(result.breakdown["SMTP_CHECK_INCONCLUSIVE"], -30)
93
+
94
+ def test_disposable_domain_is_invalid(self):
95
+ result = calculate_score(
96
+ SyntaxResult(passed=True),
97
+ DNSResult(domain_exists=True, has_mx_records=True),
98
+ DisposableResult(
99
+ is_disposable=True,
100
+ is_free_provider=False,
101
+ is_role_based=False,
102
+ ),
103
+ None,
104
+ None,
105
+ )
106
+
107
+ self.assertEqual(result.score, 0)
108
+ self.assertEqual(result.risk_level.value, "high")
109
+ self.assertEqual(result.breakdown["DISPOSABLE_DOMAIN"], -100)
110
+
111
+ def test_catch_all_never_receives_a_low_risk_score(self):
112
+ result = calculate_score(
113
+ SyntaxResult(passed=True),
114
+ DNSResult(domain_exists=True, has_mx_records=True),
115
+ None,
116
+ CatchAllResult(is_catch_all=True, confidence=0.95),
117
+ SMTPResult(verified=True, smtp_code=250),
118
+ )
119
+
120
+ self.assertEqual(result.score, 74)
121
+ self.assertEqual(result.risk_level.value, "medium")
122
+
123
+ def test_role_based_address_never_receives_a_low_risk_score(self):
124
+ result = calculate_score(
125
+ SyntaxResult(passed=True),
126
+ DNSResult(domain_exists=True, has_mx_records=True),
127
+ DisposableResult(
128
+ is_disposable=False,
129
+ is_free_provider=False,
130
+ is_role_based=True,
131
+ ),
132
+ None,
133
+ SMTPResult(verified=True, smtp_code=250),
134
+ )
135
+
136
+ self.assertEqual(result.score, 74)
137
+ self.assertEqual(result.risk_level.value, "medium")
138
+
139
+ def test_generic_smtp_550_does_not_claim_mailbox_is_nonexistent(self):
140
+ result = calculate_score(
141
+ SyntaxResult(passed=True),
142
+ DNSResult(domain_exists=True, has_mx_records=True),
143
+ None,
144
+ None,
145
+ SMTPResult(verified=False, smtp_code=550),
146
+ )
147
+
148
+ self.assertTrue(
149
+ any(
150
+ "provider policy may make the result inconclusive" in warning
151
+ for warning in result.warnings
152
+ )
153
+ )
154
+ self.assertFalse(
155
+ any("Mailbox does not exist" in warning for warning in result.warnings)
156
+ )
157
+ self.assertGreater(result.score, 0)
158
+ self.assertNotIn("SMTP_MAILBOX_NOT_FOUND", result.breakdown)
159
+
160
+
161
+ if __name__ == "__main__":
162
+ unittest.main()
venv/Lib/site-packages/_pytest/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+
4
+ __all__ = ["__version__", "version_tuple"]
5
+
6
+ try:
7
+ from ._version import version as __version__
8
+ from ._version import version_tuple
9
+ except ImportError: # pragma: no cover
10
+ # broken installation, we don't even try
11
+ # unknown only works because we do poor mans version compare
12
+ __version__ = "unknown"
13
+ version_tuple = (0, 0, "unknown")
venv/Lib/site-packages/_pytest/_argcomplete.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Allow bash-completion for argparse with argcomplete if installed.
2
+
3
+ Needs argcomplete>=0.5.6 for python 3.2/3.3 (older versions fail
4
+ to find the magic string, so _ARGCOMPLETE env. var is never set, and
5
+ this does not need special code).
6
+
7
+ Function try_argcomplete(parser) should be called directly before
8
+ the call to ArgumentParser.parse_args().
9
+
10
+ The filescompleter is what you normally would use on the positional
11
+ arguments specification, in order to get "dirname/" after "dirn<TAB>"
12
+ instead of the default "dirname ":
13
+
14
+ optparser.add_argument(Config._file_or_dir, nargs='*').completer=filescompleter
15
+
16
+ Other, application specific, completers should go in the file
17
+ doing the add_argument calls as they need to be specified as .completer
18
+ attributes as well. (If argcomplete is not installed, the function the
19
+ attribute points to will not be used).
20
+
21
+ SPEEDUP
22
+ =======
23
+
24
+ The generic argcomplete script for bash-completion
25
+ (/etc/bash_completion.d/python-argcomplete.sh)
26
+ uses a python program to determine startup script generated by pip.
27
+ You can speed up completion somewhat by changing this script to include
28
+ # PYTHON_ARGCOMPLETE_OK
29
+ so the python-argcomplete-check-easy-install-script does not
30
+ need to be called to find the entry point of the code and see if that is
31
+ marked with PYTHON_ARGCOMPLETE_OK.
32
+
33
+ INSTALL/DEBUGGING
34
+ =================
35
+
36
+ To include this support in another application that has setup.py generated
37
+ scripts:
38
+
39
+ - Add the line:
40
+ # PYTHON_ARGCOMPLETE_OK
41
+ near the top of the main python entry point.
42
+
43
+ - Include in the file calling parse_args():
44
+ from _argcomplete import try_argcomplete, filescompleter
45
+ Call try_argcomplete just before parse_args(), and optionally add
46
+ filescompleter to the positional arguments' add_argument().
47
+
48
+ If things do not work right away:
49
+
50
+ - Switch on argcomplete debugging with (also helpful when doing custom
51
+ completers):
52
+ export _ARC_DEBUG=1
53
+
54
+ - Run:
55
+ python-argcomplete-check-easy-install-script $(which appname)
56
+ echo $?
57
+ will echo 0 if the magic line has been found, 1 if not.
58
+
59
+ - Sometimes it helps to find early on errors using:
60
+ _ARGCOMPLETE=1 _ARC_DEBUG=1 appname
61
+ which should throw a KeyError: 'COMPLINE' (which is properly set by the
62
+ global argcomplete script).
63
+ """
64
+
65
+ from __future__ import annotations
66
+
67
+ import argparse
68
+ from glob import glob
69
+ import os
70
+ import sys
71
+ from typing import Any
72
+
73
+
74
+ class FastFilesCompleter:
75
+ """Fast file completer class."""
76
+
77
+ def __init__(self, directories: bool = True) -> None:
78
+ self.directories = directories
79
+
80
+ def __call__(self, prefix: str, **kwargs: Any) -> list[str]:
81
+ # Only called on non option completions.
82
+ if os.sep in prefix[1:]:
83
+ prefix_dir = len(os.path.dirname(prefix) + os.sep)
84
+ else:
85
+ prefix_dir = 0
86
+ completion = []
87
+ globbed = []
88
+ if "*" not in prefix and "?" not in prefix:
89
+ # We are on unix, otherwise no bash.
90
+ if not prefix or prefix[-1] == os.sep:
91
+ globbed.extend(glob(prefix + ".*"))
92
+ prefix += "*"
93
+ globbed.extend(glob(prefix))
94
+ for x in sorted(globbed):
95
+ if os.path.isdir(x):
96
+ x += "/"
97
+ # Append stripping the prefix (like bash, not like compgen).
98
+ completion.append(x[prefix_dir:])
99
+ return completion
100
+
101
+
102
+ if os.environ.get("_ARGCOMPLETE"):
103
+ try:
104
+ import argcomplete.completers
105
+ except ImportError:
106
+ sys.exit(-1)
107
+ filescompleter: FastFilesCompleter | None = FastFilesCompleter()
108
+
109
+ def try_argcomplete(parser: argparse.ArgumentParser) -> None:
110
+ argcomplete.autocomplete(parser, always_complete_options=False)
111
+
112
+ else:
113
+
114
+ def try_argcomplete(parser: argparse.ArgumentParser) -> None:
115
+ pass
116
+
117
+ filescompleter = None
venv/Lib/site-packages/_pytest/_code/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Python inspection/code generation API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from .code import Code
6
+ from .code import ExceptionInfo
7
+ from .code import filter_traceback
8
+ from .code import Frame
9
+ from .code import getfslineno
10
+ from .code import Traceback
11
+ from .code import TracebackEntry
12
+ from .source import getrawcode
13
+ from .source import Source
14
+
15
+
16
+ __all__ = [
17
+ "Code",
18
+ "ExceptionInfo",
19
+ "Frame",
20
+ "Source",
21
+ "Traceback",
22
+ "TracebackEntry",
23
+ "filter_traceback",
24
+ "getfslineno",
25
+ "getrawcode",
26
+ ]
venv/Lib/site-packages/_pytest/_code/code.py ADDED
@@ -0,0 +1,1632 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from collections.abc import Callable
6
+ from collections.abc import Iterable
7
+ from collections.abc import Mapping
8
+ from collections.abc import Sequence
9
+ import dataclasses
10
+ import inspect
11
+ from io import StringIO
12
+ import os
13
+ from pathlib import Path
14
+ import re
15
+ import sys
16
+ from traceback import extract_tb
17
+ from traceback import format_exception
18
+ from traceback import format_exception_only
19
+ from traceback import FrameSummary
20
+ from types import CodeType
21
+ from types import FrameType
22
+ from types import TracebackType
23
+ from typing import Any
24
+ from typing import ClassVar
25
+ from typing import Final
26
+ from typing import final
27
+ from typing import Generic
28
+ from typing import Literal
29
+ from typing import overload
30
+ from typing import SupportsIndex
31
+ from typing import TypeAlias
32
+ from typing import TypeVar
33
+
34
+ import pluggy
35
+
36
+ import _pytest
37
+ from _pytest._code.source import findsource
38
+ from _pytest._code.source import getrawcode
39
+ from _pytest._code.source import getstatementrange_ast
40
+ from _pytest._code.source import Source
41
+ from _pytest._io import TerminalWriter
42
+ from _pytest._io.saferepr import safeformat
43
+ from _pytest._io.saferepr import saferepr
44
+ from _pytest.compat import get_real_func
45
+ from _pytest.deprecated import check_ispytest
46
+ from _pytest.pathlib import absolutepath
47
+ from _pytest.pathlib import bestrelpath
48
+
49
+
50
+ if sys.version_info < (3, 11):
51
+ from exceptiongroup import BaseExceptionGroup
52
+
53
+ TracebackStyle = Literal["long", "short", "line", "no", "native", "value", "auto"]
54
+
55
+ EXCEPTION_OR_MORE = type[BaseException] | tuple[type[BaseException], ...]
56
+
57
+
58
+ class Code:
59
+ """Wrapper around Python code objects."""
60
+
61
+ __slots__ = ("raw",)
62
+
63
+ def __init__(self, obj: CodeType) -> None:
64
+ self.raw = obj
65
+
66
+ @classmethod
67
+ def from_function(cls, obj: object) -> Code:
68
+ return cls(getrawcode(obj))
69
+
70
+ def __eq__(self, other):
71
+ return self.raw == other.raw
72
+
73
+ # Ignore type because of https://github.com/python/mypy/issues/4266.
74
+ __hash__ = None # type: ignore
75
+
76
+ @property
77
+ def firstlineno(self) -> int:
78
+ return self.raw.co_firstlineno - 1
79
+
80
+ @property
81
+ def name(self) -> str:
82
+ return self.raw.co_name
83
+
84
+ @property
85
+ def path(self) -> Path | str:
86
+ """Return a path object pointing to source code, or an ``str`` in
87
+ case of ``OSError`` / non-existing file."""
88
+ filename = inspect.getfile(self.raw)
89
+ if not filename:
90
+ return ""
91
+ try:
92
+ p = absolutepath(filename)
93
+ # maybe don't try this checking
94
+ if not p.exists():
95
+ raise OSError("path check failed.")
96
+ return p
97
+ except OSError:
98
+ # XXX maybe try harder like the weird logic
99
+ # in the standard lib [linecache.updatecache] does?
100
+ return filename
101
+
102
+ @property
103
+ def fullsource(self) -> Source | None:
104
+ """Return a _pytest._code.Source object for the full source file of the code."""
105
+ full, _ = findsource(self.raw)
106
+ return full
107
+
108
+ def source(self) -> Source:
109
+ """Return a _pytest._code.Source object for the code object's source only."""
110
+ # return source only for that part of code
111
+ return Source(self.raw)
112
+
113
+ def getargs(self, var: bool = False) -> tuple[str, ...]:
114
+ """Return a tuple with the argument names for the code object.
115
+
116
+ If 'var' is set True also return the names of the variable and
117
+ keyword arguments when present.
118
+ """
119
+ # inspect.getargs merges positional and kwonly into a single list;
120
+ # co_argcount is needed to exclude kwonly when var=False.
121
+ args, varargs, varkw = inspect.getargs(self.raw)
122
+ if not var:
123
+ return tuple(args[: self.raw.co_argcount])
124
+ result = list(args)
125
+ if varargs is not None:
126
+ result.append(varargs)
127
+ if varkw is not None:
128
+ result.append(varkw)
129
+ return tuple(result)
130
+
131
+
132
+ class Frame:
133
+ """Wrapper around a Python frame holding f_locals and f_globals
134
+ in which expressions can be evaluated."""
135
+
136
+ __slots__ = ("raw",)
137
+
138
+ def __init__(self, frame: FrameType) -> None:
139
+ self.raw = frame
140
+
141
+ @property
142
+ def lineno(self) -> int:
143
+ return self.raw.f_lineno - 1
144
+
145
+ @property
146
+ def f_globals(self) -> dict[str, Any]:
147
+ return self.raw.f_globals
148
+
149
+ @property
150
+ def f_locals(self) -> dict[str, Any]:
151
+ return self.raw.f_locals
152
+
153
+ @property
154
+ def code(self) -> Code:
155
+ return Code(self.raw.f_code)
156
+
157
+ @property
158
+ def statement(self) -> Source:
159
+ """Statement this frame is at."""
160
+ if self.code.fullsource is None:
161
+ return Source("")
162
+ return self.code.fullsource.getstatement(self.lineno)
163
+
164
+ def eval(self, code, **vars):
165
+ """Evaluate 'code' in the frame.
166
+
167
+ 'vars' are optional additional local variables.
168
+
169
+ Returns the result of the evaluation.
170
+ """
171
+ f_locals = self.f_locals.copy()
172
+ f_locals.update(vars)
173
+ return eval(code, self.f_globals, f_locals)
174
+
175
+ def repr(self, object: object) -> str:
176
+ """Return a 'safe' (non-recursive, one-line) string repr for 'object'."""
177
+ return saferepr(object)
178
+
179
+ def getargs(self, var: bool = False):
180
+ """Return a list of tuples (name, value) for all arguments.
181
+
182
+ If 'var' is set True, also include the variable and keyword arguments
183
+ when present.
184
+ """
185
+ retval = []
186
+ for arg in self.code.getargs(var):
187
+ try:
188
+ retval.append((arg, self.f_locals[arg]))
189
+ except KeyError:
190
+ pass # this can occur when using Psyco
191
+ return retval
192
+
193
+
194
+ class TracebackEntry:
195
+ """A single entry in a Traceback."""
196
+
197
+ __slots__ = ("_rawentry", "_repr_style")
198
+
199
+ def __init__(
200
+ self,
201
+ rawentry: TracebackType,
202
+ repr_style: Literal["short", "long"] | None = None,
203
+ ) -> None:
204
+ self._rawentry: Final = rawentry
205
+ self._repr_style: Final = repr_style
206
+
207
+ def with_repr_style(
208
+ self, repr_style: Literal["short", "long"] | None
209
+ ) -> TracebackEntry:
210
+ return TracebackEntry(self._rawentry, repr_style)
211
+
212
+ @property
213
+ def lineno(self) -> int:
214
+ return self._rawentry.tb_lineno - 1
215
+
216
+ def get_python_framesummary(self) -> FrameSummary:
217
+ # Python's built-in traceback module implements all the nitty gritty
218
+ # details to get column numbers of out frames.
219
+ stack_summary = extract_tb(self._rawentry, limit=1)
220
+ return stack_summary[0]
221
+
222
+ # Column and end line numbers introduced in python 3.11
223
+ if sys.version_info < (3, 11):
224
+
225
+ @property
226
+ def end_lineno_relative(self) -> int | None:
227
+ return None
228
+
229
+ @property
230
+ def colno(self) -> int | None:
231
+ return None
232
+
233
+ @property
234
+ def end_colno(self) -> int | None:
235
+ return None
236
+ else:
237
+
238
+ @property
239
+ def end_lineno_relative(self) -> int | None:
240
+ frame_summary = self.get_python_framesummary()
241
+ if frame_summary.end_lineno is None: # pragma: no cover
242
+ return None
243
+ return frame_summary.end_lineno - 1 - self.frame.code.firstlineno
244
+
245
+ @property
246
+ def colno(self) -> int | None:
247
+ """Starting byte offset of the expression in the traceback entry."""
248
+ return self.get_python_framesummary().colno
249
+
250
+ @property
251
+ def end_colno(self) -> int | None:
252
+ """Ending byte offset of the expression in the traceback entry."""
253
+ return self.get_python_framesummary().end_colno
254
+
255
+ @property
256
+ def frame(self) -> Frame:
257
+ return Frame(self._rawentry.tb_frame)
258
+
259
+ @property
260
+ def relline(self) -> int:
261
+ return self.lineno - self.frame.code.firstlineno
262
+
263
+ def __repr__(self) -> str:
264
+ return f"<TracebackEntry {self.frame.code.path}:{self.lineno + 1}>"
265
+
266
+ @property
267
+ def statement(self) -> Source:
268
+ """_pytest._code.Source object for the current statement."""
269
+ source = self.frame.code.fullsource
270
+ assert source is not None
271
+ return source.getstatement(self.lineno)
272
+
273
+ @property
274
+ def path(self) -> Path | str:
275
+ """Path to the source code."""
276
+ return self.frame.code.path
277
+
278
+ @property
279
+ def locals(self) -> dict[str, Any]:
280
+ """Locals of underlying frame."""
281
+ return self.frame.f_locals
282
+
283
+ def getfirstlinesource(self) -> int:
284
+ return self.frame.code.firstlineno
285
+
286
+ def getsource(
287
+ self, astcache: dict[str | Path, ast.AST] | None = None
288
+ ) -> Source | None:
289
+ """Return failing source code."""
290
+ # we use the passed in astcache to not reparse asttrees
291
+ # within exception info printing
292
+ source = self.frame.code.fullsource
293
+ if source is None:
294
+ return None
295
+ key = astnode = None
296
+ if astcache is not None:
297
+ key = self.frame.code.path
298
+ if key is not None:
299
+ astnode = astcache.get(key, None)
300
+ start = self.getfirstlinesource()
301
+ try:
302
+ astnode, _, end = getstatementrange_ast(
303
+ self.lineno, source, astnode=astnode
304
+ )
305
+ except SyntaxError:
306
+ end = self.lineno + 1
307
+ else:
308
+ if key is not None and astcache is not None:
309
+ astcache[key] = astnode
310
+ return source[start:end]
311
+
312
+ source = property(getsource)
313
+
314
+ def ishidden(self, excinfo: ExceptionInfo[BaseException] | None) -> bool:
315
+ """Return True if the current frame has a var __tracebackhide__
316
+ resolving to True.
317
+
318
+ If __tracebackhide__ is a callable, it gets called with the
319
+ ExceptionInfo instance and can decide whether to hide the traceback.
320
+
321
+ Mostly for internal use.
322
+ """
323
+ tbh: bool | Callable[[ExceptionInfo[BaseException] | None], bool] = False
324
+ for maybe_ns_dct in (self.frame.f_locals, self.frame.f_globals):
325
+ # in normal cases, f_locals and f_globals are dictionaries
326
+ # however via `exec(...)` / `eval(...)` they can be other types
327
+ # (even incorrect types!).
328
+ # as such, we suppress all exceptions while accessing __tracebackhide__
329
+ try:
330
+ tbh = maybe_ns_dct["__tracebackhide__"]
331
+ except Exception:
332
+ pass
333
+ else:
334
+ break
335
+ if tbh and callable(tbh):
336
+ return tbh(excinfo)
337
+ return tbh
338
+
339
+ def __str__(self) -> str:
340
+ name = self.frame.code.name
341
+ try:
342
+ line = str(self.statement).lstrip()
343
+ except KeyboardInterrupt:
344
+ raise
345
+ except BaseException:
346
+ line = "???"
347
+ # This output does not quite match Python's repr for traceback entries,
348
+ # but changing it to do so would break certain plugins. See
349
+ # https://github.com/pytest-dev/pytest/pull/7535/ for details.
350
+ return f" File '{self.path}':{self.lineno + 1} in {name}\n {line}\n"
351
+
352
+ @property
353
+ def name(self) -> str:
354
+ """co_name of underlying code."""
355
+ return self.frame.code.raw.co_name
356
+
357
+
358
+ class Traceback(list[TracebackEntry]):
359
+ """Traceback objects encapsulate and offer higher level access to Traceback entries."""
360
+
361
+ def __init__(
362
+ self,
363
+ tb: TracebackType | Iterable[TracebackEntry],
364
+ ) -> None:
365
+ """Initialize from given python traceback object and ExceptionInfo."""
366
+ if isinstance(tb, TracebackType):
367
+
368
+ def f(cur: TracebackType) -> Iterable[TracebackEntry]:
369
+ cur_: TracebackType | None = cur
370
+ while cur_ is not None:
371
+ yield TracebackEntry(cur_)
372
+ cur_ = cur_.tb_next
373
+
374
+ super().__init__(f(tb))
375
+ else:
376
+ super().__init__(tb)
377
+
378
+ def cut(
379
+ self,
380
+ path: os.PathLike[str] | str | None = None,
381
+ lineno: int | None = None,
382
+ firstlineno: int | None = None,
383
+ excludepath: os.PathLike[str] | None = None,
384
+ ) -> Traceback:
385
+ """Return a Traceback instance wrapping part of this Traceback.
386
+
387
+ By providing any combination of path, lineno and firstlineno, the
388
+ first frame to start the to-be-returned traceback is determined.
389
+
390
+ This allows cutting the first part of a Traceback instance e.g.
391
+ for formatting reasons (removing some uninteresting bits that deal
392
+ with handling of the exception/traceback).
393
+ """
394
+ path_ = None if path is None else os.fspath(path)
395
+ excludepath_ = None if excludepath is None else os.fspath(excludepath)
396
+ for x in self:
397
+ code = x.frame.code
398
+ codepath = code.path
399
+ if path is not None and str(codepath) != path_:
400
+ continue
401
+ if (
402
+ excludepath is not None
403
+ and isinstance(codepath, Path)
404
+ and excludepath_ in (str(p) for p in codepath.parents) # type: ignore[operator]
405
+ ):
406
+ continue
407
+ if lineno is not None and x.lineno != lineno:
408
+ continue
409
+ if firstlineno is not None and x.frame.code.firstlineno != firstlineno:
410
+ continue
411
+ return Traceback(x._rawentry)
412
+ return self
413
+
414
+ @overload
415
+ def __getitem__(self, key: SupportsIndex) -> TracebackEntry: ...
416
+
417
+ @overload
418
+ def __getitem__(self, key: slice) -> Traceback: ...
419
+
420
+ def __getitem__(self, key: SupportsIndex | slice) -> TracebackEntry | Traceback:
421
+ if isinstance(key, slice):
422
+ return self.__class__(super().__getitem__(key))
423
+ else:
424
+ return super().__getitem__(key)
425
+
426
+ def filter(
427
+ self,
428
+ excinfo_or_fn: ExceptionInfo[BaseException] | Callable[[TracebackEntry], bool],
429
+ /,
430
+ ) -> Traceback:
431
+ """Return a Traceback instance with certain items removed.
432
+
433
+ If the filter is an `ExceptionInfo`, removes all the ``TracebackEntry``s
434
+ which are hidden (see ishidden() above).
435
+
436
+ Otherwise, the filter is a function that gets a single argument, a
437
+ ``TracebackEntry`` instance, and should return True when the item should
438
+ be added to the ``Traceback``, False when not.
439
+ """
440
+ if isinstance(excinfo_or_fn, ExceptionInfo):
441
+ fn = lambda x: not x.ishidden(excinfo_or_fn) # noqa: E731
442
+ else:
443
+ fn = excinfo_or_fn
444
+ return Traceback(filter(fn, self))
445
+
446
+ def recursionindex(self) -> int | None:
447
+ """Return the index of the frame/TracebackEntry where recursion originates if
448
+ appropriate, None if no recursion occurred."""
449
+ cache: dict[tuple[Any, int, int], list[dict[str, Any]]] = {}
450
+ for i, entry in enumerate(self):
451
+ # id for the code.raw is needed to work around
452
+ # the strange metaprogramming in the decorator lib from pypi
453
+ # which generates code objects that have hash/value equality
454
+ # XXX needs a test
455
+ key = entry.frame.code.path, id(entry.frame.code.raw), entry.lineno
456
+ values = cache.setdefault(key, [])
457
+ # Since Python 3.13 f_locals is a proxy, freeze it.
458
+ loc = dict(entry.frame.f_locals)
459
+ if values:
460
+ for otherloc in values:
461
+ if otherloc == loc:
462
+ return i
463
+ values.append(loc)
464
+ return None
465
+
466
+
467
+ def stringify_exception(
468
+ exc: BaseException, include_subexception_msg: bool = True
469
+ ) -> str:
470
+ try:
471
+ notes = getattr(exc, "__notes__", [])
472
+ except KeyError:
473
+ # Workaround for https://github.com/python/cpython/issues/98778 on
474
+ # some 3.10 and 3.11 patch versions.
475
+ HTTPError = getattr(sys.modules.get("urllib.error", None), "HTTPError", ())
476
+ if sys.version_info < (3, 12) and isinstance(exc, HTTPError):
477
+ notes = []
478
+ else: # pragma: no cover
479
+ # exception not related to above bug, reraise
480
+ raise
481
+ if not include_subexception_msg and isinstance(exc, BaseExceptionGroup):
482
+ message = exc.message
483
+ else:
484
+ message = str(exc)
485
+
486
+ return "\n".join(
487
+ [
488
+ message,
489
+ *notes,
490
+ ]
491
+ )
492
+
493
+
494
+ E = TypeVar("E", bound=BaseException, covariant=True)
495
+
496
+
497
+ @final
498
+ @dataclasses.dataclass
499
+ class ExceptionInfo(Generic[E]):
500
+ """Wraps sys.exc_info() objects and offers help for navigating the traceback."""
501
+
502
+ _assert_start_repr: ClassVar = "AssertionError('assert "
503
+
504
+ _excinfo: tuple[type[E], E, TracebackType] | None
505
+ _striptext: str
506
+ _traceback: Traceback | None
507
+
508
+ def __init__(
509
+ self,
510
+ excinfo: tuple[type[E], E, TracebackType] | None,
511
+ striptext: str = "",
512
+ traceback: Traceback | None = None,
513
+ *,
514
+ _ispytest: bool = False,
515
+ ) -> None:
516
+ check_ispytest(_ispytest)
517
+ self._excinfo = excinfo
518
+ self._striptext = striptext
519
+ self._traceback = traceback
520
+
521
+ @classmethod
522
+ def from_exception(
523
+ cls,
524
+ # Ignoring error: "Cannot use a covariant type variable as a parameter".
525
+ # This is OK to ignore because this class is (conceptually) readonly.
526
+ # See https://github.com/python/mypy/issues/7049.
527
+ exception: E, # type: ignore[misc]
528
+ exprinfo: str | None = None,
529
+ ) -> ExceptionInfo[E]:
530
+ """Return an ExceptionInfo for an existing exception.
531
+
532
+ The exception must have a non-``None`` ``__traceback__`` attribute,
533
+ otherwise this function fails with an assertion error. This means that
534
+ the exception must have been raised, or added a traceback with the
535
+ :py:meth:`~BaseException.with_traceback()` method.
536
+
537
+ :param exprinfo:
538
+ A text string helping to determine if we should strip
539
+ ``AssertionError`` from the output. Defaults to the exception
540
+ message/``__str__()``.
541
+
542
+ .. versionadded:: 7.4
543
+ """
544
+ assert exception.__traceback__, (
545
+ "Exceptions passed to ExcInfo.from_exception(...)"
546
+ " must have a non-None __traceback__."
547
+ )
548
+ exc_info = (type(exception), exception, exception.__traceback__)
549
+ return cls.from_exc_info(exc_info, exprinfo)
550
+
551
+ @classmethod
552
+ def from_exc_info(
553
+ cls,
554
+ exc_info: tuple[type[E], E, TracebackType],
555
+ exprinfo: str | None = None,
556
+ ) -> ExceptionInfo[E]:
557
+ """Like :func:`from_exception`, but using old-style exc_info tuple."""
558
+ _striptext = ""
559
+ if exprinfo is None and isinstance(exc_info[1], AssertionError):
560
+ exprinfo = getattr(exc_info[1], "msg", None)
561
+ if exprinfo is None:
562
+ exprinfo = saferepr(exc_info[1])
563
+ if exprinfo and exprinfo.startswith(cls._assert_start_repr):
564
+ _striptext = "AssertionError: "
565
+
566
+ return cls(exc_info, _striptext, _ispytest=True)
567
+
568
+ @classmethod
569
+ def from_current(cls, exprinfo: str | None = None) -> ExceptionInfo[BaseException]:
570
+ """Return an ExceptionInfo matching the current traceback.
571
+
572
+ .. warning::
573
+
574
+ Experimental API
575
+
576
+ :param exprinfo:
577
+ A text string helping to determine if we should strip
578
+ ``AssertionError`` from the output. Defaults to the exception
579
+ message/``__str__()``.
580
+ """
581
+ tup = sys.exc_info()
582
+ assert tup[0] is not None, "no current exception"
583
+ assert tup[1] is not None, "no current exception"
584
+ assert tup[2] is not None, "no current exception"
585
+ exc_info = (tup[0], tup[1], tup[2])
586
+ return ExceptionInfo.from_exc_info(exc_info, exprinfo)
587
+
588
+ @classmethod
589
+ def for_later(cls) -> ExceptionInfo[E]:
590
+ """Return an unfilled ExceptionInfo."""
591
+ return cls(None, _ispytest=True)
592
+
593
+ def fill_unfilled(self, exc_info: tuple[type[E], E, TracebackType]) -> None:
594
+ """Fill an unfilled ExceptionInfo created with ``for_later()``."""
595
+ assert self._excinfo is None, "ExceptionInfo was already filled"
596
+ self._excinfo = exc_info
597
+
598
+ @property
599
+ def type(self) -> type[E]:
600
+ """The exception class."""
601
+ assert self._excinfo is not None, (
602
+ ".type can only be used after the context manager exits"
603
+ )
604
+ return self._excinfo[0]
605
+
606
+ @property
607
+ def value(self) -> E:
608
+ """The exception value."""
609
+ assert self._excinfo is not None, (
610
+ ".value can only be used after the context manager exits"
611
+ )
612
+ return self._excinfo[1]
613
+
614
+ @property
615
+ def tb(self) -> TracebackType:
616
+ """The exception raw traceback."""
617
+ assert self._excinfo is not None, (
618
+ ".tb can only be used after the context manager exits"
619
+ )
620
+ return self._excinfo[2]
621
+
622
+ @property
623
+ def typename(self) -> str:
624
+ """The type name of the exception."""
625
+ assert self._excinfo is not None, (
626
+ ".typename can only be used after the context manager exits"
627
+ )
628
+ return self.type.__name__
629
+
630
+ @property
631
+ def traceback(self) -> Traceback:
632
+ """The traceback."""
633
+ if self._traceback is None:
634
+ self._traceback = Traceback(self.tb)
635
+ return self._traceback
636
+
637
+ @traceback.setter
638
+ def traceback(self, value: Traceback) -> None:
639
+ self._traceback = value
640
+
641
+ def __repr__(self) -> str:
642
+ if self._excinfo is None:
643
+ return "<ExceptionInfo for raises contextmanager>"
644
+ return f"<{self.__class__.__name__} {saferepr(self._excinfo[1])} tblen={len(self.traceback)}>"
645
+
646
+ def exconly(self, tryshort: bool = False) -> str:
647
+ """Return the exception as a string.
648
+
649
+ This is usually a single line "<exception type>: <exception str>", but
650
+ may also include additional lines for the exception notes, and detailed
651
+ information for SyntaxError's.
652
+
653
+ :param tryshort:
654
+ If true, and the exception is an AssertionError, strip
655
+ 'AssertionError: ' from the beginning.
656
+ """
657
+
658
+ def _get_single_subexc(
659
+ eg: BaseExceptionGroup[BaseException],
660
+ ) -> BaseException | None:
661
+ if len(eg.exceptions) != 1:
662
+ return None
663
+ if isinstance(e := eg.exceptions[0], BaseExceptionGroup):
664
+ return _get_single_subexc(e)
665
+ return e
666
+
667
+ if (
668
+ tryshort
669
+ and isinstance(self.value, BaseExceptionGroup)
670
+ and (subexc := _get_single_subexc(self.value)) is not None
671
+ ):
672
+ return f"{subexc!r} [single exception in {type(self.value).__name__}]"
673
+
674
+ lines = format_exception_only(self.value)
675
+ # The lines already include line separators.
676
+ text = "".join(lines)
677
+ text = text.rstrip()
678
+ if tryshort:
679
+ if text.startswith(self._striptext):
680
+ text = text[len(self._striptext) :]
681
+ return text
682
+
683
+ def errisinstance(self, exc: EXCEPTION_OR_MORE) -> bool:
684
+ """Return True if the exception is an instance of exc.
685
+
686
+ Consider using ``isinstance(excinfo.value, exc)`` instead.
687
+ """
688
+ return isinstance(self.value, exc)
689
+
690
+ def _getreprcrash(self) -> ReprFileLocation | None:
691
+ # Find last non-hidden traceback entry that led to the exception of the
692
+ # traceback, or None if all hidden.
693
+ for i in range(-1, -len(self.traceback) - 1, -1):
694
+ entry = self.traceback[i]
695
+ if not entry.ishidden(self):
696
+ path, lineno = entry.frame.code.raw.co_filename, entry.lineno
697
+ exconly = self.exconly(tryshort=True)
698
+ return ReprFileLocation(path, lineno + 1, exconly)
699
+ return None
700
+
701
+ def getrepr(
702
+ self,
703
+ showlocals: bool = False,
704
+ style: TracebackStyle = "long",
705
+ abspath: bool = False,
706
+ tbfilter: bool | Callable[[ExceptionInfo[BaseException]], Traceback] = True,
707
+ funcargs: bool = False,
708
+ truncate_locals: bool = True,
709
+ truncate_args: bool = True,
710
+ chain: bool = True,
711
+ ) -> ReprExceptionInfo | ExceptionChainRepr:
712
+ """Return str()able representation of this exception info.
713
+
714
+ The formatting parameters are ineffective if ``style="native"``,
715
+ since in this case the native formatting is used.
716
+
717
+ :param bool showlocals:
718
+ Show locals per traceback entry.
719
+
720
+ :param str style:
721
+ long|short|line|no|native|value traceback style.
722
+
723
+ :param bool abspath:
724
+ If paths should be changed to absolute or left unchanged.
725
+
726
+ :param tbfilter:
727
+ A filter for traceback entries.
728
+
729
+ * If false, don't hide any entries.
730
+ * If true, hide internal entries and entries that contain a local
731
+ variable ``__tracebackhide__ = True``.
732
+ * If a callable, delegates the filtering to the callable.
733
+
734
+ :param bool funcargs:
735
+ Show function arguments per traceback entry.
736
+
737
+ :param bool truncate_locals:
738
+ Whether to show a size-limited `repr()` of locals, or a full
739
+ pretty-printing.
740
+
741
+ :param bool truncate_args:
742
+ Whether to show a size-limited truncated `repr()` of function
743
+ arguments, or a full pretty-printing.
744
+
745
+ :param bool chain:
746
+ If chained exceptions should be shown.
747
+
748
+ .. versionchanged:: 3.9
749
+
750
+ Added the ``chain`` parameter.
751
+ """
752
+ if style == "native":
753
+ return ReprExceptionInfo(
754
+ reprtraceback=ReprTracebackNative(
755
+ format_exception(
756
+ self.type,
757
+ self.value,
758
+ self.traceback[0]._rawentry if self.traceback else None,
759
+ )
760
+ ),
761
+ reprcrash=self._getreprcrash(),
762
+ )
763
+
764
+ fmt = ExceptionInfoFormatter(
765
+ showlocals=showlocals,
766
+ style=style,
767
+ abspath=abspath,
768
+ tbfilter=tbfilter,
769
+ funcargs=funcargs,
770
+ truncate_locals=truncate_locals,
771
+ truncate_args=truncate_args,
772
+ chain=chain,
773
+ )
774
+ return fmt.repr_excinfo(self)
775
+
776
+ def match(self, regexp: str | re.Pattern[str]) -> Literal[True]:
777
+ """Check whether the regular expression `regexp` matches the string
778
+ representation of the exception using :func:`python:re.search`.
779
+
780
+ If it matches `True` is returned, otherwise an `AssertionError` is raised.
781
+ """
782
+ __tracebackhide__ = True
783
+ value = stringify_exception(self.value)
784
+ msg = (
785
+ f"Regex pattern did not match.\n"
786
+ f" Expected regex: {regexp!r}\n"
787
+ f" Actual message: {value!r}"
788
+ )
789
+ if regexp == value:
790
+ msg += "\n Did you mean to `re.escape()` the regex?"
791
+ assert re.search(regexp, value), msg
792
+ # Return True to allow for "assert excinfo.match()".
793
+ return True
794
+
795
+ def _group_contains(
796
+ self,
797
+ exc_group: BaseExceptionGroup[BaseException],
798
+ expected_exception: EXCEPTION_OR_MORE,
799
+ match: str | re.Pattern[str] | None,
800
+ target_depth: int | None = None,
801
+ current_depth: int = 1,
802
+ ) -> bool:
803
+ """Return `True` if a `BaseExceptionGroup` contains a matching exception."""
804
+ if (target_depth is not None) and (current_depth > target_depth):
805
+ # already descended past the target depth
806
+ return False
807
+ for exc in exc_group.exceptions:
808
+ if isinstance(exc, BaseExceptionGroup):
809
+ if self._group_contains(
810
+ exc, expected_exception, match, target_depth, current_depth + 1
811
+ ):
812
+ return True
813
+ if (target_depth is not None) and (current_depth != target_depth):
814
+ # not at the target depth, no match
815
+ continue
816
+ if not isinstance(exc, expected_exception):
817
+ continue
818
+ if match is not None:
819
+ value = stringify_exception(exc)
820
+ if not re.search(match, value):
821
+ continue
822
+ return True
823
+ return False
824
+
825
+ def group_contains(
826
+ self,
827
+ expected_exception: EXCEPTION_OR_MORE,
828
+ *,
829
+ match: str | re.Pattern[str] | None = None,
830
+ depth: int | None = None,
831
+ ) -> bool:
832
+ """Check whether a captured exception group contains a matching exception.
833
+
834
+ :param Type[BaseException] | Tuple[Type[BaseException]] expected_exception:
835
+ The expected exception type, or a tuple if one of multiple possible
836
+ exception types are expected.
837
+
838
+ :param str | re.Pattern[str] | None match:
839
+ If specified, a string containing a regular expression,
840
+ or a regular expression object, that is tested against the string
841
+ representation of the exception and its `PEP-678 <https://peps.python.org/pep-0678/>` `__notes__`
842
+ using :func:`re.search`.
843
+
844
+ To match a literal string that may contain :ref:`special characters
845
+ <re-syntax>`, the pattern can first be escaped with :func:`re.escape`.
846
+
847
+ :param Optional[int] depth:
848
+ If `None`, will search for a matching exception at any nesting depth.
849
+ If >= 1, will only match an exception if it's at the specified depth (depth = 1 being
850
+ the exceptions contained within the topmost exception group).
851
+
852
+ .. versionadded:: 8.0
853
+
854
+ .. warning::
855
+ This helper makes it easy to check for the presence of specific exceptions,
856
+ but it is very bad for checking that the group does *not* contain
857
+ *any other exceptions*.
858
+ You should instead consider using :class:`pytest.RaisesGroup`
859
+
860
+ """
861
+ msg = "Captured exception is not an instance of `BaseExceptionGroup`"
862
+ assert isinstance(self.value, BaseExceptionGroup), msg
863
+ msg = "`depth` must be >= 1 if specified"
864
+ assert (depth is None) or (depth >= 1), msg
865
+ return self._group_contains(self.value, expected_exception, match, depth)
866
+
867
+
868
+ # Type alias for the `tbfilter` setting:
869
+ # bool: If True, it should be filtered using Traceback.filter()
870
+ # callable: A callable that takes an ExceptionInfo and returns the filtered traceback.
871
+ TracebackFilter: TypeAlias = bool | Callable[[ExceptionInfo[BaseException]], Traceback]
872
+
873
+
874
+ @dataclasses.dataclass
875
+ class ExceptionInfoFormatter:
876
+ """Helper object to format ExceptionInfo's and individual exception parts
877
+ into TerminalRepr's.
878
+
879
+ See :func:`ExceptionInfo.getrepr` for parameters.
880
+ """
881
+
882
+ # for traceback entries
883
+ flow_marker: ClassVar = ">"
884
+ fail_marker: ClassVar = "E"
885
+
886
+ showlocals: bool = False
887
+ # Note: "native" is handled outside of ExceptionInfoFormatter.
888
+ style: TracebackStyle = "long"
889
+ abspath: bool = True
890
+ tbfilter: TracebackFilter = True
891
+ funcargs: bool = False
892
+ truncate_locals: bool = True
893
+ truncate_args: bool = True
894
+ chain: bool = True
895
+
896
+ astcache: dict[str | Path, ast.AST] = dataclasses.field(
897
+ default_factory=dict, init=False, repr=False
898
+ )
899
+
900
+ def _getindent(self, source: Source) -> int:
901
+ # Figure out indent for the given source.
902
+ try:
903
+ s = str(source.getstatement(len(source) - 1))
904
+ except KeyboardInterrupt:
905
+ raise
906
+ except BaseException:
907
+ try:
908
+ s = str(source[-1])
909
+ except KeyboardInterrupt:
910
+ raise
911
+ except BaseException:
912
+ return 0
913
+ return 4 + (len(s) - len(s.lstrip()))
914
+
915
+ def _getentrysource(self, entry: TracebackEntry) -> Source | None:
916
+ source = entry.getsource(self.astcache)
917
+ if source is not None:
918
+ source = source.deindent()
919
+ return source
920
+
921
+ def repr_args(self, entry: TracebackEntry) -> ReprFuncArgs | None:
922
+ if self.funcargs:
923
+ args = []
924
+ for argname, argvalue in entry.frame.getargs(var=True):
925
+ if self.truncate_args:
926
+ str_repr = saferepr(argvalue)
927
+ else:
928
+ str_repr = saferepr(argvalue, maxsize=None)
929
+ args.append((argname, str_repr))
930
+ return ReprFuncArgs(args)
931
+ return None
932
+
933
+ def get_source(
934
+ self,
935
+ source: Source | None,
936
+ line_index: int = -1,
937
+ excinfo: ExceptionInfo[BaseException] | None = None,
938
+ short: bool = False,
939
+ end_line_index: int | None = None,
940
+ colno: int | None = None,
941
+ end_colno: int | None = None,
942
+ ) -> list[str]:
943
+ """Return formatted and marked up source lines."""
944
+ lines = []
945
+ if source is not None and line_index < 0:
946
+ line_index += len(source)
947
+ if source is None or line_index >= len(source.lines) or line_index < 0:
948
+ # `line_index` could still be outside `range(len(source.lines))` if
949
+ # we're processing AST with pathological position attributes.
950
+ source = Source("???")
951
+ line_index = 0
952
+ space_prefix = " "
953
+ if short:
954
+ lines.append(space_prefix + source.lines[line_index].strip())
955
+ lines.extend(
956
+ self.get_highlight_arrows_for_line(
957
+ raw_line=source.raw_lines[line_index],
958
+ line=source.lines[line_index].strip(),
959
+ lineno=line_index,
960
+ end_lineno=end_line_index,
961
+ colno=colno,
962
+ end_colno=end_colno,
963
+ )
964
+ )
965
+ else:
966
+ for line in source.lines[:line_index]:
967
+ lines.append(space_prefix + line)
968
+ lines.append(self.flow_marker + " " + source.lines[line_index])
969
+ lines.extend(
970
+ self.get_highlight_arrows_for_line(
971
+ raw_line=source.raw_lines[line_index],
972
+ line=source.lines[line_index],
973
+ lineno=line_index,
974
+ end_lineno=end_line_index,
975
+ colno=colno,
976
+ end_colno=end_colno,
977
+ )
978
+ )
979
+ for line in source.lines[line_index + 1 :]:
980
+ lines.append(space_prefix + line)
981
+ if excinfo is not None:
982
+ indent = 4 if short else self._getindent(source)
983
+ lines.extend(self.get_exconly(excinfo, indent=indent, markall=True))
984
+ return lines
985
+
986
+ def get_highlight_arrows_for_line(
987
+ self,
988
+ line: str,
989
+ raw_line: str,
990
+ lineno: int | None,
991
+ end_lineno: int | None,
992
+ colno: int | None,
993
+ end_colno: int | None,
994
+ ) -> list[str]:
995
+ """Return characters highlighting a source line.
996
+
997
+ Example with colno and end_colno pointing to the bar expression:
998
+ "foo() + bar()"
999
+ returns " ^^^^^"
1000
+ """
1001
+ if lineno != end_lineno:
1002
+ # Don't handle expressions that span multiple lines.
1003
+ return []
1004
+ if colno is None or end_colno is None:
1005
+ # Can't do anything without column information.
1006
+ return []
1007
+
1008
+ num_stripped_chars = len(raw_line) - len(line)
1009
+
1010
+ start_char_offset = _byte_offset_to_character_offset(raw_line, colno)
1011
+ end_char_offset = _byte_offset_to_character_offset(raw_line, end_colno)
1012
+ num_carets = end_char_offset - start_char_offset
1013
+ # If the highlight would span the whole line, it is redundant, don't
1014
+ # show it.
1015
+ if num_carets >= len(line.strip()):
1016
+ return []
1017
+
1018
+ highlights = " "
1019
+ highlights += " " * (start_char_offset - num_stripped_chars + 1)
1020
+ highlights += "^" * num_carets
1021
+ return [highlights]
1022
+
1023
+ def get_exconly(
1024
+ self,
1025
+ excinfo: ExceptionInfo[BaseException],
1026
+ indent: int = 4,
1027
+ markall: bool = False,
1028
+ ) -> list[str]:
1029
+ lines = []
1030
+ indentstr = " " * indent
1031
+ # Get the real exception information out.
1032
+ exlines = excinfo.exconly(tryshort=True).split("\n")
1033
+ failindent = self.fail_marker + indentstr[1:]
1034
+ for line in exlines:
1035
+ lines.append(failindent + line)
1036
+ if not markall:
1037
+ failindent = indentstr
1038
+ return lines
1039
+
1040
+ def repr_locals(self, locals: Mapping[str, object]) -> ReprLocals | None:
1041
+ if self.showlocals:
1042
+ lines = []
1043
+ # Variables starting with `@` are helpers injected by assertion
1044
+ # rewriting, not user variables, so hide them.
1045
+ keys = [loc for loc in locals if loc[0] != "@"]
1046
+ keys.sort()
1047
+ for name in keys:
1048
+ value = locals[name]
1049
+ if name == "__builtins__":
1050
+ lines.append("__builtins__ = <builtins>")
1051
+ else:
1052
+ # This formatting could all be handled by the
1053
+ # _repr() function, which is only reprlib.Repr in
1054
+ # disguise, so is very configurable.
1055
+ if self.truncate_locals:
1056
+ str_repr = saferepr(value)
1057
+ else:
1058
+ str_repr = safeformat(value)
1059
+ # if len(str_repr) < 70 or not isinstance(value, (list, tuple, dict)):
1060
+ lines.append(f"{name:<10} = {str_repr}")
1061
+ # else:
1062
+ # self._line("%-10s =\\" % (name,))
1063
+ # # XXX
1064
+ # pprint.pprint(value, stream=self.excinfowriter)
1065
+ return ReprLocals(lines)
1066
+ return None
1067
+
1068
+ def repr_traceback_entry(
1069
+ self,
1070
+ entry: TracebackEntry | None,
1071
+ excinfo: ExceptionInfo[BaseException] | None = None,
1072
+ ) -> ReprEntry:
1073
+ lines: list[str] = []
1074
+ style = (
1075
+ entry._repr_style
1076
+ if entry is not None and entry._repr_style is not None
1077
+ else self.style
1078
+ )
1079
+ if style in ("short", "long") and entry is not None:
1080
+ source = self._getentrysource(entry)
1081
+ if source is None:
1082
+ source = Source("???")
1083
+ line_index = 0
1084
+ end_line_index, colno, end_colno = None, None, None
1085
+ else:
1086
+ line_index = entry.relline
1087
+ end_line_index = entry.end_lineno_relative
1088
+ colno = entry.colno
1089
+ end_colno = entry.end_colno
1090
+ short = style == "short"
1091
+ reprargs = self.repr_args(entry) if not short else None
1092
+ s = self.get_source(
1093
+ source=source,
1094
+ line_index=line_index,
1095
+ excinfo=excinfo,
1096
+ short=short,
1097
+ end_line_index=end_line_index,
1098
+ colno=colno,
1099
+ end_colno=end_colno,
1100
+ )
1101
+ lines.extend(s)
1102
+ if short:
1103
+ message = f"in {entry.name}"
1104
+ else:
1105
+ message = (excinfo and excinfo.typename) or ""
1106
+ entry_path = entry.path
1107
+ path = self._makepath(entry_path)
1108
+ reprfileloc = ReprFileLocation(path, entry.lineno + 1, message)
1109
+ localsrepr = self.repr_locals(entry.locals)
1110
+ return ReprEntry(lines, reprargs, localsrepr, reprfileloc, style)
1111
+ elif style == "value":
1112
+ if excinfo:
1113
+ lines.extend(str(excinfo.value).split("\n"))
1114
+ return ReprEntry(lines, None, None, None, style)
1115
+ else:
1116
+ if excinfo:
1117
+ lines.extend(self.get_exconly(excinfo, indent=4))
1118
+ return ReprEntry(lines, None, None, None, style)
1119
+
1120
+ def _makepath(self, path: Path | str) -> str:
1121
+ if not self.abspath and isinstance(path, Path):
1122
+ try:
1123
+ np = bestrelpath(Path.cwd(), path)
1124
+ except OSError:
1125
+ return str(path)
1126
+ if len(np) < len(str(path)):
1127
+ return np
1128
+ return str(path)
1129
+
1130
+ def repr_traceback(self, excinfo: ExceptionInfo[BaseException]) -> ReprTraceback:
1131
+ traceback = filter_excinfo_traceback(self.tbfilter, excinfo)
1132
+
1133
+ if isinstance(excinfo.value, RecursionError):
1134
+ traceback, extraline = self._truncate_recursive_traceback(traceback)
1135
+ else:
1136
+ extraline = None
1137
+
1138
+ if not traceback:
1139
+ if extraline is None:
1140
+ extraline = "All traceback entries are hidden. Pass `--full-trace` to see hidden and internal frames."
1141
+ entries = [self.repr_traceback_entry(None, excinfo)]
1142
+ return ReprTraceback(entries, extraline, style=self.style)
1143
+
1144
+ last = traceback[-1]
1145
+ if self.style == "value":
1146
+ entries = [self.repr_traceback_entry(last, excinfo)]
1147
+ return ReprTraceback(entries, None, style=self.style)
1148
+
1149
+ entries = [
1150
+ self.repr_traceback_entry(entry, excinfo if last == entry else None)
1151
+ for entry in traceback
1152
+ ]
1153
+ return ReprTraceback(entries, extraline, style=self.style)
1154
+
1155
+ def _truncate_recursive_traceback(
1156
+ self, traceback: Traceback
1157
+ ) -> tuple[Traceback, str | None]:
1158
+ """Truncate the given recursive traceback trying to find the starting
1159
+ point of the recursion.
1160
+
1161
+ The detection is done by going through each traceback entry and
1162
+ finding the point in which the locals of the frame are equal to the
1163
+ locals of a previous frame (see ``recursionindex()``).
1164
+
1165
+ Handle the situation where the recursion process might raise an
1166
+ exception (for example comparing numpy arrays using equality raises a
1167
+ TypeError), in which case we do our best to warn the user of the
1168
+ error and show a limited traceback.
1169
+ """
1170
+ try:
1171
+ recursionindex = traceback.recursionindex()
1172
+ except Exception as e:
1173
+ max_frames = 10
1174
+ extraline: str | None = (
1175
+ "!!! Recursion error detected, but an error occurred locating the origin of recursion.\n"
1176
+ " The following exception happened when comparing locals in the stack frame:\n"
1177
+ f" {type(e).__name__}: {e!s}\n"
1178
+ f" Displaying first and last {max_frames} stack frames out of {len(traceback)}."
1179
+ )
1180
+ # Type ignored because adding two instances of a List subtype
1181
+ # currently incorrectly has type List instead of the subtype.
1182
+ traceback = traceback[:max_frames] + traceback[-max_frames:] # type: ignore
1183
+ else:
1184
+ if recursionindex is not None:
1185
+ extraline = "!!! Recursion detected (same locals & position)"
1186
+ traceback = traceback[: recursionindex + 1]
1187
+ else:
1188
+ extraline = None
1189
+
1190
+ return traceback, extraline
1191
+
1192
+ def repr_excinfo(self, excinfo: ExceptionInfo[BaseException]) -> ExceptionChainRepr:
1193
+ repr_chain: list[tuple[ReprTraceback, ReprFileLocation | None, str | None]] = []
1194
+ e: BaseException | None = excinfo.value
1195
+ excinfo_: ExceptionInfo[BaseException] | None = excinfo
1196
+ description = None
1197
+ seen: set[int] = set()
1198
+ while e is not None and id(e) not in seen:
1199
+ seen.add(id(e))
1200
+
1201
+ if excinfo_:
1202
+ # Fall back to native traceback as a temporary workaround until
1203
+ # full support for exception groups added to ExceptionInfo.
1204
+ # See https://github.com/pytest-dev/pytest/issues/9159
1205
+ reprtraceback: ReprTraceback | ReprTracebackNative
1206
+ if isinstance(e, BaseExceptionGroup):
1207
+ # don't filter any sub-exceptions since they shouldn't have any internal frames
1208
+ traceback = filter_excinfo_traceback(self.tbfilter, excinfo)
1209
+ extraline = (
1210
+ "All traceback entries are hidden. Pass `--full-trace` to see hidden and internal frames."
1211
+ if not traceback
1212
+ else None
1213
+ )
1214
+ reprtraceback = ReprTracebackNative(
1215
+ format_exception(
1216
+ type(excinfo.value),
1217
+ excinfo.value,
1218
+ traceback[0]._rawentry if traceback else None,
1219
+ ),
1220
+ extraline=extraline,
1221
+ )
1222
+
1223
+ else:
1224
+ reprtraceback = self.repr_traceback(excinfo_)
1225
+ reprcrash = excinfo_._getreprcrash()
1226
+ else:
1227
+ # Fallback to native repr if the exception doesn't have a traceback:
1228
+ # ExceptionInfo objects require a full traceback to work.
1229
+ reprtraceback = ReprTracebackNative(format_exception(type(e), e, None))
1230
+ reprcrash = None
1231
+ repr_chain.append((reprtraceback, reprcrash, description))
1232
+
1233
+ if e.__cause__ is not None and self.chain:
1234
+ e = e.__cause__
1235
+ excinfo_ = ExceptionInfo.from_exception(e) if e.__traceback__ else None
1236
+ description = "The above exception was the direct cause of the following exception:"
1237
+ elif (
1238
+ e.__context__ is not None and not e.__suppress_context__ and self.chain
1239
+ ):
1240
+ e = e.__context__
1241
+ excinfo_ = ExceptionInfo.from_exception(e) if e.__traceback__ else None
1242
+ description = "During handling of the above exception, another exception occurred:"
1243
+ else:
1244
+ e = None
1245
+ repr_chain.reverse()
1246
+ return ExceptionChainRepr(repr_chain)
1247
+
1248
+
1249
+ @dataclasses.dataclass(eq=False)
1250
+ class TerminalRepr:
1251
+ """Base class for terminal representations -- pieces of data that display
1252
+ themselves to a terminal."""
1253
+
1254
+ def __str__(self) -> str:
1255
+ # FYI this is called from pytest-xdist's serialization of exception
1256
+ # information.
1257
+ io = StringIO()
1258
+ tw = TerminalWriter(file=io)
1259
+ self.toterminal(tw)
1260
+ return io.getvalue().strip()
1261
+
1262
+ def __repr__(self) -> str:
1263
+ return f"<{self.__class__} instance at {id(self):0x}>"
1264
+
1265
+ def toterminal(self, tw: TerminalWriter) -> None:
1266
+ raise NotImplementedError()
1267
+
1268
+
1269
+ @dataclasses.dataclass(eq=False)
1270
+ class ExceptionRepr(TerminalRepr):
1271
+ """Base class for exception terminal representations.
1272
+
1273
+ The representation generally contains:
1274
+ - The exception traceback (`reprtraceback`)
1275
+ - The exception message and location (`reprcrash`)
1276
+ - Separated, titled sections with additional data (pytest core doesn't use
1277
+ this currently).
1278
+ """
1279
+
1280
+ reprtraceback: ReprTraceback
1281
+ reprcrash: ReprFileLocation | None
1282
+ sections: list[tuple[str, str, str]] = dataclasses.field(
1283
+ init=False, default_factory=list
1284
+ )
1285
+
1286
+ def addsection(self, name: str, content: str, sep: str = "-") -> None:
1287
+ self.sections.append((name, content, sep))
1288
+
1289
+ def toterminal(self, tw: TerminalWriter) -> None:
1290
+ for name, content, sep in self.sections:
1291
+ tw.sep(sep, name)
1292
+ tw.line(content)
1293
+
1294
+
1295
+ @dataclasses.dataclass(eq=False)
1296
+ class ExceptionChainRepr(ExceptionRepr):
1297
+ """A chain of exceptions, separated by descriptions (e.g. "The above
1298
+ exception was the direct cause of the following exception")."""
1299
+
1300
+ chain: Sequence[tuple[ReprTraceback, ReprFileLocation | None, str | None]]
1301
+
1302
+ def __init__(
1303
+ self,
1304
+ chain: Sequence[tuple[ReprTraceback, ReprFileLocation | None, str | None]],
1305
+ ) -> None:
1306
+ # reprcrash and reprtraceback of the outermost (the newest) exception
1307
+ # in the chain.
1308
+ super().__init__(
1309
+ reprtraceback=chain[-1][0],
1310
+ reprcrash=chain[-1][1],
1311
+ )
1312
+ self.chain = chain
1313
+
1314
+ def toterminal(self, tw: TerminalWriter) -> None:
1315
+ for reprtraceback, reprcrash, description in self.chain:
1316
+ reprtraceback.toterminal(tw)
1317
+ if description is not None:
1318
+ tw.line("")
1319
+ tw.line(description, yellow=True)
1320
+ super().toterminal(tw)
1321
+
1322
+
1323
+ @dataclasses.dataclass(eq=False)
1324
+ class ReprExceptionInfo(ExceptionRepr):
1325
+ """A single exception with optional extra details (function arguments,
1326
+ function locals, file location) and possible extra line and sections emitted
1327
+ at the end."""
1328
+
1329
+ def toterminal(self, tw: TerminalWriter) -> None:
1330
+ self.reprtraceback.toterminal(tw)
1331
+ super().toterminal(tw)
1332
+
1333
+
1334
+ @dataclasses.dataclass(eq=False)
1335
+ class ReprTraceback(TerminalRepr):
1336
+ """A traceback with optional extra details (function arguments, function
1337
+ locals, file location) and possible extra line emitted at the end."""
1338
+
1339
+ reprentries: Sequence[ReprEntry | ReprEntryNative]
1340
+ extraline: str | None
1341
+ style: TracebackStyle
1342
+
1343
+ entrysep: ClassVar = "_ "
1344
+
1345
+ def toterminal(self, tw: TerminalWriter) -> None:
1346
+ # The entries might have different styles.
1347
+ for i, entry in enumerate(self.reprentries):
1348
+ if entry.style == "long":
1349
+ tw.line("")
1350
+ entry.toterminal(tw)
1351
+ if i < len(self.reprentries) - 1:
1352
+ next_entry = self.reprentries[i + 1]
1353
+ if entry.style == "long" or (
1354
+ entry.style == "short" and next_entry.style == "long"
1355
+ ):
1356
+ tw.sep(self.entrysep)
1357
+
1358
+ if self.extraline:
1359
+ tw.line(self.extraline)
1360
+
1361
+
1362
+ class ReprTracebackNative(ReprTraceback):
1363
+ """A traceback in native style.
1364
+
1365
+ The lines are emitted as is; uses a single entry for the entire native
1366
+ traceback.
1367
+ """
1368
+
1369
+ def __init__(self, tblines: Sequence[str], *, extraline: str | None = None) -> None:
1370
+ self.reprentries = [ReprEntryNative(tblines)]
1371
+ self.extraline = extraline
1372
+ self.style = "native"
1373
+
1374
+
1375
+ @dataclasses.dataclass(eq=False)
1376
+ class ReprEntryNative(TerminalRepr):
1377
+ """An entry in a traceback in native style.
1378
+
1379
+ Emits the lines as is. The lines are assumed to include the line separators.
1380
+
1381
+ [Note that we currently use a single "entry" for the entire native
1382
+ traceback, so this is a bit misleading, but there's no point trying to parse
1383
+ or split a native traceback.]
1384
+ """
1385
+
1386
+ lines: Sequence[str]
1387
+
1388
+ style: ClassVar[TracebackStyle] = "native"
1389
+
1390
+ def toterminal(self, tw: TerminalWriter) -> None:
1391
+ tw.write("".join(self.lines))
1392
+
1393
+
1394
+ @dataclasses.dataclass(eq=False)
1395
+ class ReprEntry(TerminalRepr):
1396
+ """An entry in a traceback with possible extra details (function arguments,
1397
+ function locals, source snippet, function's file and line)."""
1398
+
1399
+ lines: Sequence[str]
1400
+ reprfuncargs: ReprFuncArgs | None
1401
+ reprlocals: ReprLocals | None
1402
+ reprfileloc: ReprFileLocation | None
1403
+ style: TracebackStyle
1404
+
1405
+ def _write_entry_lines(self, tw: TerminalWriter) -> None:
1406
+ """Write the source code portions of a list of traceback entries with syntax highlighting.
1407
+
1408
+ Usually entries are lines like these:
1409
+
1410
+ " x = 1"
1411
+ "> assert x == 2"
1412
+ "E assert 1 == 2"
1413
+
1414
+ This function takes care of rendering the "source" portions of it (the lines without
1415
+ the "E" prefix) using syntax highlighting, taking care to not highlighting the ">"
1416
+ character, as doing so might break line continuations.
1417
+ """
1418
+ if not self.lines:
1419
+ return
1420
+
1421
+ if self.style == "value":
1422
+ # Using tw.write instead of tw.line for testing purposes due to TWMock implementation;
1423
+ # lines written with TWMock.line and TWMock._write_source cannot be distinguished
1424
+ # from each other, whereas lines written with TWMock.write are marked with TWMock.WRITE
1425
+ for line in self.lines:
1426
+ tw.write(line)
1427
+ tw.write("\n")
1428
+ return
1429
+
1430
+ # separate indents and source lines that are not failures: we want to
1431
+ # highlight the code but not the indentation, which may contain markers
1432
+ # such as "> assert 0"
1433
+ fail_marker = f"{ExceptionInfoFormatter.fail_marker} "
1434
+ indent_size = len(fail_marker)
1435
+ indents: list[str] = []
1436
+ source_lines: list[str] = []
1437
+ failure_lines: list[str] = []
1438
+ for index, line in enumerate(self.lines):
1439
+ is_failure_line = line.startswith(fail_marker)
1440
+ if is_failure_line:
1441
+ # from this point on all lines are considered part of the failure
1442
+ failure_lines.extend(self.lines[index:])
1443
+ break
1444
+ else:
1445
+ indents.append(line[:indent_size])
1446
+ source_lines.append(line[indent_size:])
1447
+
1448
+ tw._write_source(source_lines, indents)
1449
+
1450
+ # failure lines are always completely red and bold
1451
+ for line in failure_lines:
1452
+ tw.line(line, bold=True, red=True)
1453
+
1454
+ def toterminal(self, tw: TerminalWriter) -> None:
1455
+ if self.style == "short":
1456
+ if self.reprfileloc:
1457
+ self.reprfileloc.toterminal(tw)
1458
+ self._write_entry_lines(tw)
1459
+ if self.reprlocals:
1460
+ self.reprlocals.toterminal(tw, indent=" " * 8)
1461
+ return
1462
+
1463
+ if self.reprfuncargs:
1464
+ self.reprfuncargs.toterminal(tw)
1465
+
1466
+ self._write_entry_lines(tw)
1467
+
1468
+ if self.reprlocals:
1469
+ tw.line("")
1470
+ self.reprlocals.toterminal(tw)
1471
+ if self.reprfileloc:
1472
+ if self.lines:
1473
+ tw.line("")
1474
+ self.reprfileloc.toterminal(tw)
1475
+
1476
+ def __str__(self) -> str:
1477
+ return "{}\n{}\n{}".format(
1478
+ "\n".join(self.lines), self.reprlocals, self.reprfileloc
1479
+ )
1480
+
1481
+
1482
+ @dataclasses.dataclass(eq=False)
1483
+ class ReprFileLocation(TerminalRepr):
1484
+ """A message at a file location, using the `<path>:<lineno>: <message>`
1485
+ format that most editors understand.
1486
+
1487
+ Only the first line of the message is emitted.
1488
+ """
1489
+
1490
+ path: str
1491
+ lineno: int
1492
+ message: str
1493
+
1494
+ def __post_init__(self) -> None:
1495
+ self.path = str(self.path)
1496
+
1497
+ def toterminal(self, tw: TerminalWriter) -> None:
1498
+ msg = self.message
1499
+ i = msg.find("\n")
1500
+ if i != -1:
1501
+ msg = msg[:i]
1502
+ tw.write(self.path, bold=True, red=True)
1503
+ tw.line(f":{self.lineno}: {msg}")
1504
+
1505
+
1506
+ @dataclasses.dataclass(eq=False)
1507
+ class ReprLocals(TerminalRepr):
1508
+ """Function local variables (pre-formatted)."""
1509
+
1510
+ lines: Sequence[str]
1511
+
1512
+ def toterminal(self, tw: TerminalWriter, indent: str = "") -> None:
1513
+ for line in self.lines:
1514
+ tw.line(indent + line)
1515
+
1516
+
1517
+ @dataclasses.dataclass(eq=False)
1518
+ class ReprFuncArgs(TerminalRepr):
1519
+ """Function arguments - name = value, comma separated."""
1520
+
1521
+ args: Sequence[tuple[str, object]]
1522
+
1523
+ def toterminal(self, tw: TerminalWriter) -> None:
1524
+ if self.args:
1525
+ linesofar = ""
1526
+ for name, value in self.args:
1527
+ ns = f"{name} = {value}"
1528
+ if len(ns) + len(linesofar) + 2 > tw.fullwidth:
1529
+ if linesofar:
1530
+ tw.line(linesofar)
1531
+ linesofar = ns
1532
+ else:
1533
+ if linesofar:
1534
+ linesofar += ", " + ns
1535
+ else:
1536
+ linesofar = ns
1537
+ if linesofar:
1538
+ tw.line(linesofar)
1539
+ tw.line("")
1540
+
1541
+
1542
+ def getfslineno(obj: object) -> tuple[str | Path, int]:
1543
+ """Return source location (path, lineno) for the given object.
1544
+
1545
+ If the source cannot be determined return ("", -1).
1546
+
1547
+ The line number is 0-based.
1548
+ """
1549
+ # xxx let decorators etc specify a sane ordering
1550
+ # NOTE: this used to be done in _pytest.compat.getfslineno, initially added
1551
+ # in 6ec13a2b9. It ("place_as") appears to be something very custom.
1552
+ obj = get_real_func(obj)
1553
+ if hasattr(obj, "place_as"):
1554
+ obj = obj.place_as
1555
+
1556
+ try:
1557
+ code = Code.from_function(obj)
1558
+ except TypeError:
1559
+ try:
1560
+ fn = inspect.getsourcefile(obj) or inspect.getfile(obj) # type: ignore[arg-type]
1561
+ except TypeError:
1562
+ return "", -1
1563
+
1564
+ fspath = (fn and absolutepath(fn)) or ""
1565
+ lineno = -1
1566
+ if fspath:
1567
+ try:
1568
+ _, lineno = findsource(obj)
1569
+ except OSError:
1570
+ pass
1571
+ return fspath, lineno
1572
+
1573
+ return code.path, code.firstlineno
1574
+
1575
+
1576
+ def _byte_offset_to_character_offset(str, offset):
1577
+ """Converts a byte based offset in a string to a code-point."""
1578
+ as_utf8 = str.encode("utf-8")
1579
+ return len(as_utf8[:offset].decode("utf-8", errors="replace"))
1580
+
1581
+
1582
+ # Relative paths that we use to filter traceback entries from appearing to the user;
1583
+ # see filter_traceback.
1584
+ # note: if we need to add more paths than what we have now we should probably use a list
1585
+ # for better maintenance.
1586
+
1587
+ _PLUGGY_DIR = Path(pluggy.__file__.rstrip("oc"))
1588
+ # pluggy is either a package or a single module depending on the version
1589
+ if _PLUGGY_DIR.name == "__init__.py":
1590
+ _PLUGGY_DIR = _PLUGGY_DIR.parent
1591
+ _PYTEST_DIR = Path(_pytest.__file__).parent
1592
+
1593
+
1594
+ def filter_traceback(entry: TracebackEntry) -> bool:
1595
+ """Return True if a TracebackEntry instance should be included in tracebacks.
1596
+
1597
+ We hide traceback entries of:
1598
+
1599
+ * dynamically generated code (no code to show up for it);
1600
+ * internal traceback from pytest or its internal libraries, py and pluggy.
1601
+ """
1602
+ # entry.path might sometimes return a str object when the entry
1603
+ # points to dynamically generated code.
1604
+ # See https://bitbucket.org/pytest-dev/py/issues/71.
1605
+ raw_filename = entry.frame.code.raw.co_filename
1606
+ is_generated = "<" in raw_filename and ">" in raw_filename
1607
+ if is_generated:
1608
+ return False
1609
+
1610
+ # entry.path might point to a non-existing file, in which case it will
1611
+ # also return a str object. See #1133.
1612
+ p = Path(entry.path)
1613
+
1614
+ parents = p.parents
1615
+ if _PLUGGY_DIR in parents:
1616
+ return False
1617
+ if _PYTEST_DIR in parents:
1618
+ return False
1619
+
1620
+ return True
1621
+
1622
+
1623
+ def filter_excinfo_traceback(
1624
+ tbfilter: TracebackFilter, excinfo: ExceptionInfo[BaseException]
1625
+ ) -> Traceback:
1626
+ """Filter the exception traceback in ``excinfo`` according to ``tbfilter``."""
1627
+ if callable(tbfilter):
1628
+ return tbfilter(excinfo)
1629
+ elif tbfilter:
1630
+ return excinfo.traceback.filter(excinfo)
1631
+ else:
1632
+ return excinfo.traceback
venv/Lib/site-packages/_pytest/_code/source.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from bisect import bisect_right
6
+ from collections.abc import Iterable
7
+ from collections.abc import Iterator
8
+ import inspect
9
+ import textwrap
10
+ import tokenize
11
+ import types
12
+ from typing import overload
13
+ import warnings
14
+
15
+
16
+ class Source:
17
+ """An immutable object holding a source code fragment.
18
+
19
+ When using Source(...), the source lines are deindented.
20
+ """
21
+
22
+ def __init__(self, obj: object = None) -> None:
23
+ if not obj:
24
+ self.lines: list[str] = []
25
+ self.raw_lines: list[str] = []
26
+ elif isinstance(obj, Source):
27
+ self.lines = obj.lines
28
+ self.raw_lines = obj.raw_lines
29
+ elif isinstance(obj, tuple | list):
30
+ self.lines = deindent(x.rstrip("\n") for x in obj)
31
+ self.raw_lines = list(x.rstrip("\n") for x in obj)
32
+ elif isinstance(obj, str):
33
+ self.lines = deindent(obj.split("\n"))
34
+ self.raw_lines = obj.split("\n")
35
+ else:
36
+ try:
37
+ rawcode = getrawcode(obj)
38
+ src = inspect.getsource(rawcode)
39
+ except TypeError:
40
+ src = inspect.getsource(obj) # type: ignore[arg-type]
41
+ self.lines = deindent(src.split("\n"))
42
+ self.raw_lines = src.split("\n")
43
+
44
+ def __eq__(self, other: object) -> bool:
45
+ if not isinstance(other, Source):
46
+ return NotImplemented
47
+ return self.lines == other.lines
48
+
49
+ # Ignore type because of https://github.com/python/mypy/issues/4266.
50
+ __hash__ = None # type: ignore
51
+
52
+ @overload
53
+ def __getitem__(self, key: int) -> str: ...
54
+
55
+ @overload
56
+ def __getitem__(self, key: slice) -> Source: ...
57
+
58
+ def __getitem__(self, key: int | slice) -> str | Source:
59
+ if isinstance(key, int):
60
+ return self.lines[key]
61
+ else:
62
+ if key.step not in (None, 1):
63
+ raise IndexError("cannot slice a Source with a step")
64
+ newsource = Source()
65
+ newsource.lines = self.lines[key.start : key.stop]
66
+ newsource.raw_lines = self.raw_lines[key.start : key.stop]
67
+ return newsource
68
+
69
+ def __iter__(self) -> Iterator[str]:
70
+ return iter(self.lines)
71
+
72
+ def __len__(self) -> int:
73
+ return len(self.lines)
74
+
75
+ def strip(self) -> Source:
76
+ """Return new Source object with trailing and leading blank lines removed."""
77
+ start, end = 0, len(self)
78
+ while start < end and not self.lines[start].strip():
79
+ start += 1
80
+ while end > start and not self.lines[end - 1].strip():
81
+ end -= 1
82
+ source = Source()
83
+ source.raw_lines = self.raw_lines
84
+ source.lines[:] = self.lines[start:end]
85
+ return source
86
+
87
+ def indent(self, indent: str = " " * 4) -> Source:
88
+ """Return a copy of the source object with all lines indented by the
89
+ given indent-string."""
90
+ newsource = Source()
91
+ newsource.raw_lines = self.raw_lines
92
+ newsource.lines = [(indent + line) for line in self.lines]
93
+ return newsource
94
+
95
+ def getstatement(self, lineno: int) -> Source:
96
+ """Return Source statement which contains the given linenumber
97
+ (counted from 0)."""
98
+ start, end = self.getstatementrange(lineno)
99
+ return self[start:end]
100
+
101
+ def getstatementrange(self, lineno: int) -> tuple[int, int]:
102
+ """Return (start, end) tuple which spans the minimal statement region
103
+ which containing the given lineno."""
104
+ if not (0 <= lineno < len(self)):
105
+ raise IndexError("lineno out of range")
106
+ _ast, start, end = getstatementrange_ast(lineno, self)
107
+ return start, end
108
+
109
+ def deindent(self) -> Source:
110
+ """Return a new Source object deindented."""
111
+ newsource = Source()
112
+ newsource.lines[:] = deindent(self.lines)
113
+ newsource.raw_lines = self.raw_lines
114
+ return newsource
115
+
116
+ def __str__(self) -> str:
117
+ return "\n".join(self.lines)
118
+
119
+
120
+ #
121
+ # helper functions
122
+ #
123
+
124
+
125
+ def findsource(obj) -> tuple[Source | None, int]:
126
+ try:
127
+ sourcelines, lineno = inspect.findsource(obj)
128
+ except Exception:
129
+ return None, -1
130
+ source = Source()
131
+ source.lines = [line.rstrip() for line in sourcelines]
132
+ source.raw_lines = sourcelines
133
+ return source, lineno
134
+
135
+
136
+ def getrawcode(obj: object, trycall: bool = True) -> types.CodeType:
137
+ """Return code object for given function."""
138
+ try:
139
+ return obj.__code__ # type: ignore[attr-defined,no-any-return]
140
+ except AttributeError:
141
+ pass
142
+ if trycall:
143
+ call = getattr(obj, "__call__", None)
144
+ if call and not isinstance(obj, type):
145
+ return getrawcode(call, trycall=False)
146
+ raise TypeError(f"could not get code object for {obj!r}")
147
+
148
+
149
+ def deindent(lines: Iterable[str]) -> list[str]:
150
+ return textwrap.dedent("\n".join(lines)).splitlines()
151
+
152
+
153
+ def get_statement_startend2(lineno: int, node: ast.AST) -> tuple[int, int | None]:
154
+ # Flatten all statements and except handlers into one lineno-list.
155
+ # AST's line numbers start indexing at 1.
156
+ values: list[int] = []
157
+ for x in ast.walk(node):
158
+ if isinstance(x, ast.stmt | ast.ExceptHandler):
159
+ # The lineno points to the class/def, so need to include the decorators.
160
+ if isinstance(x, ast.ClassDef | ast.FunctionDef | ast.AsyncFunctionDef):
161
+ for d in x.decorator_list:
162
+ values.append(d.lineno - 1)
163
+ values.append(x.lineno - 1)
164
+ for name in ("finalbody", "orelse"):
165
+ val: list[ast.stmt] | None = getattr(x, name, None)
166
+ if val:
167
+ # Treat the finally/orelse part as its own statement.
168
+ values.append(val[0].lineno - 1 - 1)
169
+ values.sort()
170
+ insert_index = bisect_right(values, lineno)
171
+ if insert_index == 0:
172
+ return 0, None
173
+ start = values[insert_index - 1]
174
+ if insert_index >= len(values):
175
+ end = None
176
+ else:
177
+ end = values[insert_index]
178
+ return start, end
179
+
180
+
181
+ def getstatementrange_ast(
182
+ lineno: int,
183
+ source: Source,
184
+ assertion: bool = False,
185
+ astnode: ast.AST | None = None,
186
+ ) -> tuple[ast.AST, int, int]:
187
+ if astnode is None:
188
+ content = str(source)
189
+ # See #4260:
190
+ # Don't produce duplicate warnings when compiling source to find AST.
191
+ with warnings.catch_warnings():
192
+ warnings.simplefilter("ignore")
193
+ astnode = ast.parse(content, "source", "exec")
194
+
195
+ start, end = get_statement_startend2(lineno, astnode)
196
+ # We need to correct the end:
197
+ # - ast-parsing strips comments
198
+ # - there might be empty lines
199
+ # - we might have lesser indented code blocks at the end
200
+ if end is None:
201
+ end = len(source.lines)
202
+
203
+ if end > start + 1:
204
+ # Make sure we don't span differently indented code blocks
205
+ # by using the BlockFinder helper used which inspect.getsource() uses itself.
206
+ block_finder = inspect.BlockFinder()
207
+ # If we start with an indented line, put blockfinder to "started" mode.
208
+ block_finder.started = (
209
+ bool(source.lines[start]) and source.lines[start][0].isspace()
210
+ )
211
+ it = ((x + "\n") for x in source.lines[start:end])
212
+ try:
213
+ for tok in tokenize.generate_tokens(lambda: next(it)):
214
+ block_finder.tokeneater(*tok)
215
+ except (inspect.EndOfBlock, IndentationError):
216
+ end = block_finder.last + start
217
+ except Exception:
218
+ pass
219
+
220
+ # The end might still point to a comment or empty line, correct it.
221
+ end = min(end, len(source.lines))
222
+ while end:
223
+ line = source.lines[end - 1].lstrip()
224
+ if line.startswith("#") or not line:
225
+ end -= 1
226
+ else:
227
+ break
228
+ return astnode, start, end
venv/Lib/site-packages/_pytest/_io/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from .terminalwriter import get_terminal_width
4
+ from .terminalwriter import TerminalWriter
5
+
6
+
7
+ __all__ = [
8
+ "TerminalWriter",
9
+ "get_terminal_width",
10
+ ]
venv/Lib/site-packages/_pytest/_io/pprint.py ADDED
@@ -0,0 +1,673 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # This module was imported from the cpython standard library
3
+ # (https://github.com/python/cpython/) at commit
4
+ # c5140945c723ae6c4b7ee81ff720ac8ea4b52cfd (python3.12).
5
+ #
6
+ #
7
+ # Original Author: Fred L. Drake, Jr.
8
+ # fdrake@acm.org
9
+ #
10
+ # This is a simple little module I wrote to make life easier. I didn't
11
+ # see anything quite like it in the library, though I may have overlooked
12
+ # something. I wrote this when I was trying to read some heavily nested
13
+ # tuples with fairly non-descriptive content. This is modeled very much
14
+ # after Lisp/Scheme - style pretty-printing of lists. If you find it
15
+ # useful, thank small children who sleep at night.
16
+ from __future__ import annotations
17
+
18
+ import collections as _collections
19
+ from collections.abc import Callable
20
+ from collections.abc import Iterator
21
+ import dataclasses as _dataclasses
22
+ from io import StringIO as _StringIO
23
+ import re
24
+ import types as _types
25
+ from typing import Any
26
+ from typing import IO
27
+
28
+
29
+ class _safe_key:
30
+ """Helper function for key functions when sorting unorderable objects.
31
+
32
+ The wrapped-object will fallback to a Py2.x style comparison for
33
+ unorderable types (sorting first comparing the type name and then by
34
+ the obj ids). Does not work recursively, so dict.items() must have
35
+ _safe_key applied to both the key and the value.
36
+
37
+ """
38
+
39
+ __slots__ = ["obj"]
40
+
41
+ def __init__(self, obj):
42
+ self.obj = obj
43
+
44
+ def __lt__(self, other):
45
+ try:
46
+ return self.obj < other.obj
47
+ except TypeError:
48
+ return (str(type(self.obj)), id(self.obj)) < (
49
+ str(type(other.obj)),
50
+ id(other.obj),
51
+ )
52
+
53
+
54
+ def _safe_tuple(t):
55
+ """Helper function for comparing 2-tuples"""
56
+ return _safe_key(t[0]), _safe_key(t[1])
57
+
58
+
59
+ class PrettyPrinter:
60
+ def __init__(
61
+ self,
62
+ indent: int = 4,
63
+ width: int = 80,
64
+ depth: int | None = None,
65
+ ) -> None:
66
+ """Handle pretty printing operations onto a stream using a set of
67
+ configured parameters.
68
+
69
+ indent
70
+ Number of spaces to indent for each level of nesting.
71
+
72
+ width
73
+ Attempted maximum number of columns in the output.
74
+
75
+ depth
76
+ The maximum depth to print out nested structures.
77
+
78
+ """
79
+ if indent < 0:
80
+ raise ValueError("indent must be >= 0")
81
+ if depth is not None and depth <= 0:
82
+ raise ValueError("depth must be > 0")
83
+ if not width:
84
+ raise ValueError("width must be != 0")
85
+ self._depth = depth
86
+ self._indent_per_level = indent
87
+ self._width = width
88
+
89
+ def pformat(self, object: Any) -> str:
90
+ sio = _StringIO()
91
+ self._format(object, sio, 0, 0, set(), 0)
92
+ return sio.getvalue()
93
+
94
+ def _format(
95
+ self,
96
+ object: Any,
97
+ stream: IO[str],
98
+ indent: int,
99
+ allowance: int,
100
+ context: set[int],
101
+ level: int,
102
+ ) -> None:
103
+ objid = id(object)
104
+ if objid in context:
105
+ stream.write(_recursion(object))
106
+ return
107
+
108
+ p = self._dispatch.get(type(object).__repr__, None)
109
+ if p is not None:
110
+ context.add(objid)
111
+ p(self, object, stream, indent, allowance, context, level + 1)
112
+ context.remove(objid)
113
+ elif (
114
+ _dataclasses.is_dataclass(object)
115
+ and not isinstance(object, type)
116
+ and object.__dataclass_params__.repr # type:ignore[attr-defined]
117
+ and
118
+ # Check dataclass has generated repr method.
119
+ hasattr(object.__repr__, "__wrapped__")
120
+ and "__create_fn__" in object.__repr__.__wrapped__.__qualname__
121
+ ):
122
+ context.add(objid)
123
+ self._pprint_dataclass(
124
+ object, stream, indent, allowance, context, level + 1
125
+ )
126
+ context.remove(objid)
127
+ else:
128
+ stream.write(self._repr(object, context, level))
129
+
130
+ def _pprint_dataclass(
131
+ self,
132
+ object: Any,
133
+ stream: IO[str],
134
+ indent: int,
135
+ allowance: int,
136
+ context: set[int],
137
+ level: int,
138
+ ) -> None:
139
+ cls_name = object.__class__.__name__
140
+ items = [
141
+ (f.name, getattr(object, f.name))
142
+ for f in _dataclasses.fields(object)
143
+ if f.repr
144
+ ]
145
+ stream.write(cls_name + "(")
146
+ self._format_namespace_items(items, stream, indent, allowance, context, level)
147
+ stream.write(")")
148
+
149
+ _dispatch: dict[
150
+ Callable[..., str],
151
+ Callable[[PrettyPrinter, Any, IO[str], int, int, set[int], int], None],
152
+ ] = {}
153
+
154
+ def _pprint_dict(
155
+ self,
156
+ object: Any,
157
+ stream: IO[str],
158
+ indent: int,
159
+ allowance: int,
160
+ context: set[int],
161
+ level: int,
162
+ ) -> None:
163
+ write = stream.write
164
+ write("{")
165
+ items = object.items()
166
+ self._format_dict_items(items, stream, indent, allowance, context, level)
167
+ write("}")
168
+
169
+ _dispatch[dict.__repr__] = _pprint_dict
170
+
171
+ def _pprint_ordered_dict(
172
+ self,
173
+ object: Any,
174
+ stream: IO[str],
175
+ indent: int,
176
+ allowance: int,
177
+ context: set[int],
178
+ level: int,
179
+ ) -> None:
180
+ if not len(object):
181
+ stream.write(repr(object))
182
+ return
183
+ cls = object.__class__
184
+ stream.write(cls.__name__ + "(")
185
+ self._pprint_dict(object, stream, indent, allowance, context, level)
186
+ stream.write(")")
187
+
188
+ _dispatch[_collections.OrderedDict.__repr__] = _pprint_ordered_dict
189
+
190
+ def _pprint_list(
191
+ self,
192
+ object: Any,
193
+ stream: IO[str],
194
+ indent: int,
195
+ allowance: int,
196
+ context: set[int],
197
+ level: int,
198
+ ) -> None:
199
+ stream.write("[")
200
+ self._format_items(object, stream, indent, allowance, context, level)
201
+ stream.write("]")
202
+
203
+ _dispatch[list.__repr__] = _pprint_list
204
+
205
+ def _pprint_tuple(
206
+ self,
207
+ object: Any,
208
+ stream: IO[str],
209
+ indent: int,
210
+ allowance: int,
211
+ context: set[int],
212
+ level: int,
213
+ ) -> None:
214
+ stream.write("(")
215
+ self._format_items(object, stream, indent, allowance, context, level)
216
+ stream.write(")")
217
+
218
+ _dispatch[tuple.__repr__] = _pprint_tuple
219
+
220
+ def _pprint_set(
221
+ self,
222
+ object: Any,
223
+ stream: IO[str],
224
+ indent: int,
225
+ allowance: int,
226
+ context: set[int],
227
+ level: int,
228
+ ) -> None:
229
+ if not len(object):
230
+ stream.write(repr(object))
231
+ return
232
+ typ = object.__class__
233
+ if typ is set:
234
+ stream.write("{")
235
+ endchar = "}"
236
+ else:
237
+ stream.write(typ.__name__ + "({")
238
+ endchar = "})"
239
+ object = sorted(object, key=_safe_key)
240
+ self._format_items(object, stream, indent, allowance, context, level)
241
+ stream.write(endchar)
242
+
243
+ _dispatch[set.__repr__] = _pprint_set
244
+ _dispatch[frozenset.__repr__] = _pprint_set
245
+
246
+ def _pprint_str(
247
+ self,
248
+ object: Any,
249
+ stream: IO[str],
250
+ indent: int,
251
+ allowance: int,
252
+ context: set[int],
253
+ level: int,
254
+ ) -> None:
255
+ write = stream.write
256
+ if not len(object):
257
+ write(repr(object))
258
+ return
259
+ chunks = []
260
+ lines = object.splitlines(True)
261
+ if level == 1:
262
+ indent += 1
263
+ allowance += 1
264
+ max_width1 = max_width = self._width - indent
265
+ for i, line in enumerate(lines):
266
+ rep = repr(line)
267
+ if i == len(lines) - 1:
268
+ max_width1 -= allowance
269
+ if len(rep) <= max_width1:
270
+ chunks.append(rep)
271
+ else:
272
+ # A list of alternating (non-space, space) strings
273
+ parts = re.findall(r"\S*\s*", line)
274
+ assert parts
275
+ assert not parts[-1]
276
+ parts.pop() # drop empty last part
277
+ max_width2 = max_width
278
+ current = ""
279
+ for j, part in enumerate(parts):
280
+ candidate = current + part
281
+ if j == len(parts) - 1 and i == len(lines) - 1:
282
+ max_width2 -= allowance
283
+ if len(repr(candidate)) > max_width2:
284
+ if current:
285
+ chunks.append(repr(current))
286
+ current = part
287
+ else:
288
+ current = candidate
289
+ if current:
290
+ chunks.append(repr(current))
291
+ if len(chunks) == 1:
292
+ write(rep)
293
+ return
294
+ if level == 1:
295
+ write("(")
296
+ for i, rep in enumerate(chunks):
297
+ if i > 0:
298
+ write("\n" + " " * indent)
299
+ write(rep)
300
+ if level == 1:
301
+ write(")")
302
+
303
+ _dispatch[str.__repr__] = _pprint_str
304
+
305
+ def _pprint_bytes(
306
+ self,
307
+ object: Any,
308
+ stream: IO[str],
309
+ indent: int,
310
+ allowance: int,
311
+ context: set[int],
312
+ level: int,
313
+ ) -> None:
314
+ write = stream.write
315
+ if len(object) <= 4:
316
+ write(repr(object))
317
+ return
318
+ parens = level == 1
319
+ if parens:
320
+ indent += 1
321
+ allowance += 1
322
+ write("(")
323
+ delim = ""
324
+ for rep in _wrap_bytes_repr(object, self._width - indent, allowance):
325
+ write(delim)
326
+ write(rep)
327
+ if not delim:
328
+ delim = "\n" + " " * indent
329
+ if parens:
330
+ write(")")
331
+
332
+ _dispatch[bytes.__repr__] = _pprint_bytes
333
+
334
+ def _pprint_bytearray(
335
+ self,
336
+ object: Any,
337
+ stream: IO[str],
338
+ indent: int,
339
+ allowance: int,
340
+ context: set[int],
341
+ level: int,
342
+ ) -> None:
343
+ write = stream.write
344
+ write("bytearray(")
345
+ self._pprint_bytes(
346
+ bytes(object), stream, indent + 10, allowance + 1, context, level + 1
347
+ )
348
+ write(")")
349
+
350
+ _dispatch[bytearray.__repr__] = _pprint_bytearray
351
+
352
+ def _pprint_mappingproxy(
353
+ self,
354
+ object: Any,
355
+ stream: IO[str],
356
+ indent: int,
357
+ allowance: int,
358
+ context: set[int],
359
+ level: int,
360
+ ) -> None:
361
+ stream.write("mappingproxy(")
362
+ self._format(object.copy(), stream, indent, allowance, context, level)
363
+ stream.write(")")
364
+
365
+ _dispatch[_types.MappingProxyType.__repr__] = _pprint_mappingproxy
366
+
367
+ def _pprint_simplenamespace(
368
+ self,
369
+ object: Any,
370
+ stream: IO[str],
371
+ indent: int,
372
+ allowance: int,
373
+ context: set[int],
374
+ level: int,
375
+ ) -> None:
376
+ if type(object) is _types.SimpleNamespace:
377
+ # The SimpleNamespace repr is "namespace" instead of the class
378
+ # name, so we do the same here. For subclasses; use the class name.
379
+ cls_name = "namespace"
380
+ else:
381
+ cls_name = object.__class__.__name__
382
+ items = object.__dict__.items()
383
+ stream.write(cls_name + "(")
384
+ self._format_namespace_items(items, stream, indent, allowance, context, level)
385
+ stream.write(")")
386
+
387
+ _dispatch[_types.SimpleNamespace.__repr__] = _pprint_simplenamespace
388
+
389
+ def _format_dict_items(
390
+ self,
391
+ items: list[tuple[Any, Any]],
392
+ stream: IO[str],
393
+ indent: int,
394
+ allowance: int,
395
+ context: set[int],
396
+ level: int,
397
+ ) -> None:
398
+ if not items:
399
+ return
400
+
401
+ write = stream.write
402
+ item_indent = indent + self._indent_per_level
403
+ delimnl = "\n" + " " * item_indent
404
+ for key, ent in items:
405
+ write(delimnl)
406
+ write(self._repr(key, context, level))
407
+ write(": ")
408
+ self._format(ent, stream, item_indent, 1, context, level)
409
+ write(",")
410
+
411
+ write("\n" + " " * indent)
412
+
413
+ def _format_namespace_items(
414
+ self,
415
+ items: list[tuple[Any, Any]],
416
+ stream: IO[str],
417
+ indent: int,
418
+ allowance: int,
419
+ context: set[int],
420
+ level: int,
421
+ ) -> None:
422
+ if not items:
423
+ return
424
+
425
+ write = stream.write
426
+ item_indent = indent + self._indent_per_level
427
+ delimnl = "\n" + " " * item_indent
428
+ for key, ent in items:
429
+ write(delimnl)
430
+ write(key)
431
+ write("=")
432
+ if id(ent) in context:
433
+ # Special-case representation of recursion to match standard
434
+ # recursive dataclass repr.
435
+ write("...")
436
+ else:
437
+ self._format(
438
+ ent,
439
+ stream,
440
+ item_indent + len(key) + 1,
441
+ 1,
442
+ context,
443
+ level,
444
+ )
445
+
446
+ write(",")
447
+
448
+ write("\n" + " " * indent)
449
+
450
+ def _format_items(
451
+ self,
452
+ items: list[Any],
453
+ stream: IO[str],
454
+ indent: int,
455
+ allowance: int,
456
+ context: set[int],
457
+ level: int,
458
+ ) -> None:
459
+ if not items:
460
+ return
461
+
462
+ write = stream.write
463
+ item_indent = indent + self._indent_per_level
464
+ delimnl = "\n" + " " * item_indent
465
+
466
+ for item in items:
467
+ write(delimnl)
468
+ self._format(item, stream, item_indent, 1, context, level)
469
+ write(",")
470
+
471
+ write("\n" + " " * indent)
472
+
473
+ def _repr(self, object: Any, context: set[int], level: int) -> str:
474
+ return self._safe_repr(object, context.copy(), self._depth, level)
475
+
476
+ def _pprint_default_dict(
477
+ self,
478
+ object: Any,
479
+ stream: IO[str],
480
+ indent: int,
481
+ allowance: int,
482
+ context: set[int],
483
+ level: int,
484
+ ) -> None:
485
+ rdf = self._repr(object.default_factory, context, level)
486
+ stream.write(f"{object.__class__.__name__}({rdf}, ")
487
+ self._pprint_dict(object, stream, indent, allowance, context, level)
488
+ stream.write(")")
489
+
490
+ _dispatch[_collections.defaultdict.__repr__] = _pprint_default_dict
491
+
492
+ def _pprint_counter(
493
+ self,
494
+ object: Any,
495
+ stream: IO[str],
496
+ indent: int,
497
+ allowance: int,
498
+ context: set[int],
499
+ level: int,
500
+ ) -> None:
501
+ stream.write(object.__class__.__name__ + "(")
502
+
503
+ if object:
504
+ stream.write("{")
505
+ items = object.most_common()
506
+ self._format_dict_items(items, stream, indent, allowance, context, level)
507
+ stream.write("}")
508
+
509
+ stream.write(")")
510
+
511
+ _dispatch[_collections.Counter.__repr__] = _pprint_counter
512
+
513
+ def _pprint_chain_map(
514
+ self,
515
+ object: Any,
516
+ stream: IO[str],
517
+ indent: int,
518
+ allowance: int,
519
+ context: set[int],
520
+ level: int,
521
+ ) -> None:
522
+ if not len(object.maps) or (len(object.maps) == 1 and not len(object.maps[0])):
523
+ stream.write(repr(object))
524
+ return
525
+
526
+ stream.write(object.__class__.__name__ + "(")
527
+ self._format_items(object.maps, stream, indent, allowance, context, level)
528
+ stream.write(")")
529
+
530
+ _dispatch[_collections.ChainMap.__repr__] = _pprint_chain_map
531
+
532
+ def _pprint_deque(
533
+ self,
534
+ object: Any,
535
+ stream: IO[str],
536
+ indent: int,
537
+ allowance: int,
538
+ context: set[int],
539
+ level: int,
540
+ ) -> None:
541
+ stream.write(object.__class__.__name__ + "(")
542
+ if object.maxlen is not None:
543
+ stream.write(f"maxlen={object.maxlen}, ")
544
+ stream.write("[")
545
+
546
+ self._format_items(object, stream, indent, allowance + 1, context, level)
547
+ stream.write("])")
548
+
549
+ _dispatch[_collections.deque.__repr__] = _pprint_deque
550
+
551
+ def _pprint_user_dict(
552
+ self,
553
+ object: Any,
554
+ stream: IO[str],
555
+ indent: int,
556
+ allowance: int,
557
+ context: set[int],
558
+ level: int,
559
+ ) -> None:
560
+ self._format(object.data, stream, indent, allowance, context, level - 1)
561
+
562
+ _dispatch[_collections.UserDict.__repr__] = _pprint_user_dict
563
+
564
+ def _pprint_user_list(
565
+ self,
566
+ object: Any,
567
+ stream: IO[str],
568
+ indent: int,
569
+ allowance: int,
570
+ context: set[int],
571
+ level: int,
572
+ ) -> None:
573
+ self._format(object.data, stream, indent, allowance, context, level - 1)
574
+
575
+ _dispatch[_collections.UserList.__repr__] = _pprint_user_list
576
+
577
+ def _pprint_user_string(
578
+ self,
579
+ object: Any,
580
+ stream: IO[str],
581
+ indent: int,
582
+ allowance: int,
583
+ context: set[int],
584
+ level: int,
585
+ ) -> None:
586
+ self._format(object.data, stream, indent, allowance, context, level - 1)
587
+
588
+ _dispatch[_collections.UserString.__repr__] = _pprint_user_string
589
+
590
+ def _safe_repr(
591
+ self, object: Any, context: set[int], maxlevels: int | None, level: int
592
+ ) -> str:
593
+ typ = type(object)
594
+ if typ in _builtin_scalars:
595
+ return repr(object)
596
+
597
+ r = getattr(typ, "__repr__", None)
598
+
599
+ if issubclass(typ, dict) and r is dict.__repr__:
600
+ if not object:
601
+ return "{}"
602
+ objid = id(object)
603
+ if maxlevels and level >= maxlevels:
604
+ return "{...}"
605
+ if objid in context:
606
+ return _recursion(object)
607
+ context.add(objid)
608
+ components: list[str] = []
609
+ append = components.append
610
+ level += 1
611
+ for k, v in object.items():
612
+ krepr = self._safe_repr(k, context, maxlevels, level)
613
+ vrepr = self._safe_repr(v, context, maxlevels, level)
614
+ append(f"{krepr}: {vrepr}")
615
+ context.remove(objid)
616
+ return "{{{}}}".format(", ".join(components))
617
+
618
+ if (issubclass(typ, list) and r is list.__repr__) or (
619
+ issubclass(typ, tuple) and r is tuple.__repr__
620
+ ):
621
+ if issubclass(typ, list):
622
+ if not object:
623
+ return "[]"
624
+ format = "[%s]"
625
+ elif len(object) == 1:
626
+ format = "(%s,)"
627
+ else:
628
+ if not object:
629
+ return "()"
630
+ format = "(%s)"
631
+ objid = id(object)
632
+ if maxlevels and level >= maxlevels:
633
+ return format % "..."
634
+ if objid in context:
635
+ return _recursion(object)
636
+ context.add(objid)
637
+ components = []
638
+ append = components.append
639
+ level += 1
640
+ for o in object:
641
+ orepr = self._safe_repr(o, context, maxlevels, level)
642
+ append(orepr)
643
+ context.remove(objid)
644
+ return format % ", ".join(components)
645
+
646
+ return repr(object)
647
+
648
+
649
+ _builtin_scalars = frozenset(
650
+ {str, bytes, bytearray, float, complex, bool, type(None), int}
651
+ )
652
+
653
+
654
+ def _recursion(object: Any) -> str:
655
+ return f"<Recursion on {type(object).__name__} with id={id(object)}>"
656
+
657
+
658
+ def _wrap_bytes_repr(object: Any, width: int, allowance: int) -> Iterator[str]:
659
+ current = b""
660
+ last = len(object) // 4 * 4
661
+ for i in range(0, len(object), 4):
662
+ part = object[i : i + 4]
663
+ candidate = current + part
664
+ if i == last:
665
+ width -= allowance
666
+ if len(repr(candidate)) > width:
667
+ if current:
668
+ yield repr(current)
669
+ current = part
670
+ else:
671
+ current = candidate
672
+ if current:
673
+ yield repr(current)
venv/Lib/site-packages/_pytest/_io/saferepr.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from itertools import islice
4
+ import pprint
5
+ import reprlib
6
+
7
+
8
+ def _try_repr_or_str(obj: object) -> str:
9
+ try:
10
+ return repr(obj)
11
+ except (KeyboardInterrupt, SystemExit):
12
+ raise
13
+ except BaseException:
14
+ return f'{type(obj).__name__}("{obj}")'
15
+
16
+
17
+ def _format_repr_exception(exc: BaseException, obj: object) -> str:
18
+ try:
19
+ exc_info = _try_repr_or_str(exc)
20
+ except (KeyboardInterrupt, SystemExit):
21
+ raise
22
+ except BaseException as inner_exc:
23
+ exc_info = f"unpresentable exception ({_try_repr_or_str(inner_exc)})"
24
+ return (
25
+ f"<[{exc_info} raised in repr()] {type(obj).__name__} object at 0x{id(obj):x}>"
26
+ )
27
+
28
+
29
+ def _ellipsize(s: str, maxsize: int) -> str:
30
+ if len(s) > maxsize:
31
+ i = max(0, (maxsize - 3) // 2)
32
+ j = max(0, maxsize - 3 - i)
33
+ return s[:i] + "..." + s[len(s) - j :]
34
+ return s
35
+
36
+
37
+ class SafeRepr(reprlib.Repr):
38
+ """
39
+ repr.Repr that limits the resulting size of repr() and includes
40
+ information on exceptions raised during the call.
41
+ """
42
+
43
+ def __init__(self, maxsize: int | None, use_ascii: bool = False) -> None:
44
+ """
45
+ :param maxsize:
46
+ If not None, will truncate the resulting repr to that specific size, using ellipsis
47
+ somewhere in the middle to hide the extra text.
48
+ If None, will not impose any size limits on the returning repr.
49
+ """
50
+ super().__init__()
51
+ # ``maxstring`` is used by the superclass, and needs to be an int; using a
52
+ # very large number in case maxsize is None, meaning we want to disable
53
+ # truncation.
54
+ self.maxstring = maxsize if maxsize is not None else 1_000_000_000
55
+ self.maxsize = maxsize
56
+ self.use_ascii = use_ascii
57
+
58
+ def repr(self, x: object) -> str:
59
+ try:
60
+ if self.use_ascii:
61
+ s = ascii(x)
62
+ else:
63
+ s = super().repr(x)
64
+ except (KeyboardInterrupt, SystemExit):
65
+ raise
66
+ except BaseException as exc:
67
+ s = _format_repr_exception(exc, x)
68
+ if self.maxsize is not None:
69
+ s = _ellipsize(s, self.maxsize)
70
+ return s
71
+
72
+ def repr_instance(self, x: object, level: int) -> str:
73
+ try:
74
+ s = repr(x)
75
+ except (KeyboardInterrupt, SystemExit):
76
+ raise
77
+ except BaseException as exc:
78
+ s = _format_repr_exception(exc, x)
79
+ if self.maxsize is not None:
80
+ s = _ellipsize(s, self.maxsize)
81
+
82
+ return s
83
+
84
+ def repr_dict(self, x: dict[object, object], level: int) -> str:
85
+ """Represent a dict while preserving its insertion order.
86
+
87
+ Differs from ``reprlib.Repr.repr_dict`` by iterating directly over ``x``
88
+ rather than using the stdlib's sorting helper.
89
+ """
90
+ fillvalue = "..."
91
+ n = len(x)
92
+ if n == 0:
93
+ return "{}"
94
+ if level <= 0:
95
+ return "{" + fillvalue + "}"
96
+ newlevel = level - 1
97
+ repr1 = self.repr1
98
+ pieces = []
99
+ for key in islice(x, self.maxdict):
100
+ keyrepr = repr1(key, newlevel)
101
+ valrepr = repr1(x[key], newlevel)
102
+ pieces.append(f"{keyrepr}: {valrepr}")
103
+ if n > self.maxdict:
104
+ pieces.append(fillvalue)
105
+ return "{" + ", ".join(pieces) + "}"
106
+
107
+
108
+ def safeformat(obj: object) -> str:
109
+ """Return a pretty printed string for the given object.
110
+
111
+ Failing __repr__ functions of user instances will be represented
112
+ with a short exception info.
113
+ """
114
+ try:
115
+ return pprint.pformat(obj)
116
+ except Exception as exc:
117
+ return _format_repr_exception(exc, obj)
118
+
119
+
120
+ # Maximum size of overall repr of objects to display during assertion errors.
121
+ DEFAULT_REPR_MAX_SIZE = 240
122
+
123
+
124
+ def saferepr(
125
+ obj: object, maxsize: int | None = DEFAULT_REPR_MAX_SIZE, use_ascii: bool = False
126
+ ) -> str:
127
+ """Return a size-limited safe repr-string for the given object.
128
+
129
+ Failing __repr__ functions of user instances will be represented
130
+ with a short exception info and 'saferepr' generally takes
131
+ care to never raise exceptions itself.
132
+
133
+ This function is a wrapper around the Repr/reprlib functionality of the
134
+ stdlib.
135
+ """
136
+ return SafeRepr(maxsize, use_ascii).repr(obj)
137
+
138
+
139
+ def saferepr_unlimited(obj: object, use_ascii: bool = True) -> str:
140
+ """Return an unlimited-size safe repr-string for the given object.
141
+
142
+ As with saferepr, failing __repr__ functions of user instances
143
+ will be represented with a short exception info.
144
+
145
+ This function is a wrapper around simple repr.
146
+
147
+ Note: a cleaner solution would be to alter ``saferepr``this way
148
+ when maxsize=None, but that might affect some other code.
149
+ """
150
+ try:
151
+ if use_ascii:
152
+ return ascii(obj)
153
+ return repr(obj)
154
+ except Exception as exc:
155
+ return _format_repr_exception(exc, obj)