Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,37 @@ and browse 20 findings per page. Details expose complete evidence on demand.
This view runs locally in the report and requires JavaScript, without Chart.js
or network access. JSON retains every finding as well.

All three HTML templates include **Crawl coverage & timing** and a **Pages &
response times** inventory. They distinguish the configured page limit from
recorded URLs and complete/partial/failed/skipped outcomes. Search by URL,
title, description, or error; filter outcomes; sort by fetch time, score, or
finding count; and paginate every record. Expand **Page details** for metadata,
word/link counts, headings, canonical/robots observations, category scores,
findings, recommendations, and individual timing measurements. The optimized
template's performance charts work offline without external scripts.

`summary.analysis_duration` uses a monotonic clock and covers discovery, pacing,
fetching, and analysis, excluding report assembly/export. `crawl_stats` records
HTTP requests by kind (including retries), applied robots crawl delays, and
analysis cache hits. Its page throughput counts analyzed HTML pages, excluding
failed/skipped URLs. Imported reports without run context keep these measurements
unavailable. Per-page `load_time` is network time; `timings.total_seconds` also
includes fetch waiting/pacing, while headers and download timings describe the
final response. Concurrent timings overlap and should not be added to estimate
total elapsed time.

A fast command exit is not evidence of a completed crawl. For example, this
command must include the URL; omitting it produces a usage error (exit code 2)
without creating a report:

```bash
tfq0seo crawl https://example.com --depth 5 --max-pages 500 --concurrent 5 --format json --output audit.json
```

`--max-pages 500` sets a ceiling; fewer discoverable pages can produce a smaller
report. Inspect the actual counts, discovery gaps, and completion reason. See
[the live-site verification](docs/report-validation.md) for a measured example.

JSON, HTML, CSV, and XLSX exports write a temporary file beside the destination,
close it successfully, and then atomically replace the destination. Rendering,
serialization, write, and replacement failures preserve an existing report and
Expand Down
107 changes: 107 additions & 0 deletions docs/report-validation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
# HTML reporting and crawl-speed verification

Measured on 25 September 2026 using the local source checkout, Python 3.14.6,
Windows, and the owner's authorized site `https://siwar.ksaa.gov.sa/`.
These observations describe this run and environment, not a capacity guarantee.

## Reproducing the reported fast exit

The supplied command omitted the required URL:

```sh
tfq0seo crawl --depth 5 --max-pages 500 --concurrent 5 --format json --output audit.json
```

Invoking it through `python -m tfq0seo.cli` exited with code **2** after **1.56
seconds**, with `Error: Missing argument 'URL'.` No crawl or report write occurs
in that case. This explains the command as supplied; it does not establish what
happened in a different invocation that included a URL.

## Live-site observations

Two real, unauthenticated crawls respected robots.txt and disabled analysis
caching. The first used a 110-page ceiling, concurrency 3, and a 120-second
crawl deadline. It completed 18 pages in 110.76 seconds; report assembly took
0.44 seconds and JSON/HTML exports 0.84 seconds (112.04 seconds overall).

The second used the supplied depth, page ceiling, and concurrency with the URL
added:

```sh
python -m tfq0seo.cli crawl https://siwar.ksaa.gov.sa/ --depth 5 --max-pages 500 --concurrent 5 --config reports/siwar-validation/live-config.yaml --format json --output reports/siwar-validation/audit.json
python -m tfq0seo.cli export --input reports/siwar-validation/audit.json --format html --output reports/siwar-validation/audit.html
```

The local verification configuration limited requests to 15 seconds (10 seconds
for connecting), one retry, and a 180-second crawl deadline, with caching off.
No robots or TLS safeguards were disabled.

To reproduce it, save this as `reports/siwar-validation/live-config.yaml`:

```yaml
crawler:
max_crawl_time: 180
timeout: 15
connect_timeout: 10
read_timeout: 15
max_retries: 1
cache_enabled: false
```

| Observation | Second run |
| --- | ---: |
| Configured page ceiling | 500 |
| Recorded URLs / analyzed HTML pages | 18 / 18 |
| Complete / partial / failed / skipped pages | 18 / 0 / 0 / 0 |
| HTTP requests | 23: 18 pages, 4 sitemap requests, 1 robots request |
| Analysis cache hits | 0 |
| Distinct recorded text hashes | 14 |
| Crawl + analysis elapsed | 110.67 s |
| Applied robots crawl delay | 5 s |
| Mean / median HTML network time | 0.100 / 0.064 s |
| Minimum / maximum HTML network time | 0.035 / 0.444 s |
| HTML export from saved JSON | 0.41 s |

The five-second delay came from the site's robots.txt. Fast HTTP responses do
not imply a two-second audit: pacing, discovery, and analysis are separate work.
The page ceiling is not an inventory of the website, and static crawling does
not render JavaScript or enumerate every dictionary/search result.

Both runs recorded discovery gaps: an excluded `/login` sitemap entry and
document-type parse errors at the three guessed sitemap locations
`/sitemap_index.xml`, `/sitemap-index.xml`, and `/sitemaps/sitemap.xml`. The report
therefore remains **partial**, despite all 18 fetched HTML pages completing
analysis. No claim of complete site coverage is made.

The second crawl saved its JSON successfully. The surrounding measurement
script then failed while decoding UTF-8 console output with Windows cp1252, so
its total CLI wall time was not retained. The HTML was subsequently exported
from that saved JSON without recrawling; elapsed crawl time above is the tool's
monotonic measurement. Local artifacts are in `reports/siwar-validation/`
(ignored by Git), including `audit.html`, `audit.json`, `measurements.json`,
`before-measurements.json`, and the observed `robots.txt`.

## Regression checks

- A 110-page loopback crawl compares every reported request with the HTTP
server log, verifies URL retention, and includes a failed response and a
skipped non-HTML response. Neither inflates analyzed-page throughput.
- Separate sitemap discovery and page-fetch sessions contribute to request
totals. Imported report records inherit neither stale timings nor budgets.
- HTML checks preserve all 506 records in a large report across all three
templates, retain missing measurements, and escape untrusted page content.
- Browser checks exercise 45-record pagination (20/20/5), search, outcome
filtering, numeric sorting, empty results, and expanded page details.
Injected HTML remains text and unsafe URL schemes are not clickable.

```sh
python -m pytest tests/test_app.py tests/test_exporters.py tests/test_cli.py
```

The complete suite passed **921 tests** in 239.04 seconds on Python 3.14.6.
Wheel and source builds passed Twine validation; the installed wheel passed
the isolated smoke test, including all report templates and shared partials.
Packaged Python/HTML files matched the working tree byte-for-byte. Modified
Python modules also passed Python 3.8 grammar parsing (not a Python 3.8 runtime
test). Interactive browser checks used a loopback HTTP preview; a direct
`file://` preview was blocked by the browser tool's URL policy.
60 changes: 60 additions & 0 deletions tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,66 @@ def test_http_statuses_and_even_median_are_preserved():
assert metrics['load_time_stats']['median'] == 2


def test_over_100_page_run_counts_real_requests_and_excludes_failures_from_speed(http_site):
import time
base, routes, requests = http_site
count = 110
routes['/robots.txt'] = (200, {'Content-Type': 'text/plain'}, 'User-agent: *\nAllow: /')
routes['/'] = (200, {'Content-Type': 'text/html'}, '<html><title>Start</title><h1>Start</h1>' +
''.join(f'<a href="/page/{i}">Page {i}</a>' for i in range(1, count)) + '</html>')
for i in range(1, count):
routes[f'/page/{i}'] = (200, {'Content-Type': 'text/html'}, f'<html><title>Page {i}</title><h1>Page {i}</h1></html>')
routes['/page/1'] = (404, {'Content-Type': 'text/html'}, 'Missing')
routes['/page/2'] = (200, {'Content-Type': 'application/json'}, '{}')
cfg = Config.from_dict({'crawler': {'max_pages': 150, 'max_concurrent': 5, 'use_sitemap': False,
'adaptive_delay': False, 'cache_enabled': False, 'max_retries': 0},
'analysis': {'enabled_analyzers': ['seo', 'technical']}})
async def run():
analyzer = SEOAnalyzer(cfg)
started = time.perf_counter()
pages = [item async for item in analyzer.crawl_site(base + '/')]
elapsed = time.perf_counter() - started
report = analyzer.generate_site_report(pages)
summary, stats = report['summary'], report['crawl_stats']
assert len(pages) == summary['total_pages'] == summary['unique_urls'] == count
assert summary['html_pages_analyzed'] == summary['successful_pages'] == count - 2
assert summary['failed_pages'] == summary['skipped_pages'] == 1
assert summary['page_limit'] == 150
assert 0 < summary['analysis_duration'] <= elapsed
assert stats['pages_per_second'] == pytest.approx((count - 2) / summary['analysis_duration'])
assert stats['requests_made'] == len(requests) == count + 1
assert stats['requests_by_kind'] == {'robots': 1, 'page': count}
assert len(set(requests)) == len(requests)
assert stats['cache_hits'] == 0
assert summary['completion_reason'] == 'queue_exhausted'
assert all(page['load_time'] is not None for page in pages)
assert all(page['timings']['total_seconds'] >= page['load_time'] for page in pages)
assert report['metadata']['start_url'] == base + '/'
assert report['metadata']['config']['max_depth'] == cfg.crawler.max_depth
assert report['metadata']['config']['respect_robots_txt'] is True
imported = SEOAnalyzer(cfg).generate_site_report(pages)
assert imported['summary']['analysis_duration'] is None
assert imported['summary']['page_limit'] is None
assert imported['crawl_stats']['requests_made'] is None
asyncio.run(run())


def test_request_counters_include_separate_sitemap_discovery_session(http_site):
base, routes, requests = http_site
routes['/robots.txt'] = (200, {}, 'User-agent: *\nAllow: /\nCrawl-delay: 0')
routes['/sitemap.xml'] = (200, {'Content-Type': 'application/xml'},
f'<urlset><url><loc>{base}/page</loc></url></urlset>')
routes['/page'] = (200, {'Content-Type': 'text/html'}, '<html><title>Page</title><h1>Page</h1></html>')
async def run():
analyzer = SEOAnalyzer(Config.from_dict({'crawler': {'adaptive_delay': False}}))
await analyzer.analyze_sitemap(base + '/sitemap.xml')
stats = analyzer.generate_site_report()['crawl_stats']
assert stats['requests_made'] == len(requests) == 4
assert stats['requests_by_kind'] == {'robots': 2, 'sitemap': 1, 'page': 1}
assert stats['robots_delays'] == {base: 0}
asyncio.run(run())


def test_rule_aggregation_retains_unique_page_evidence():
issues = [{'rule_id': 'seo.title', 'message': str(i), 'category': 'SEO', 'severity': 'warning',
'url': f'https://example.test/{i}'} for i in range(8)]
Expand Down
9 changes: 9 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,15 @@
from tfq0seo.cli import cli


def test_crawl_without_url_reports_usage_error_and_creates_no_report(tmp_path):
output = tmp_path / 'audit.json'
result = CliRunner().invoke(cli, ['crawl', '--depth', '5', '--max-pages', '500',
'--concurrent', '5', '--format', 'json', '--output', str(output)])
assert result.exit_code == 2
assert "Missing argument 'URL'" in result.output
assert not output.exists()


def write_config(tmp_path, **crawler):
path = tmp_path / 'config.json'
path.write_text(json.dumps({'profile': 'quick', 'crawler': {
Expand Down
67 changes: 61 additions & 6 deletions tests/test_exporters.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,62 @@ def test_complete_findings_data_survives_pagination_and_escapes_untrusted_text(t
assert not soup.find('img')


@pytest.mark.parametrize('template', ['report', 'enhanced', 'optimized'])
def test_html_inventory_exposes_timings_outcomes_and_complete_safe_details(tmp_path, template):
payload = '</script><img src=x onerror=alert(1)>'
complete = {'url': 'https://example.test/good', 'status': 'complete', 'status_code': 200,
'load_time': 0.123456, 'analysis_time': 0.25, 'content_length': 2048, 'overall_score': 75,
'timings': {'headers_seconds': 0.1, 'download_seconds': 0.023456, 'total_seconds': 5.5},
'seo': {'score': 75, 'data': {'title': {'text': payload}, 'description': {'text': 'Full description'}}},
'content': {'data': {'metrics': {'word_count': 321}}},
'context': {'depth': 2, 'parent_url': 'https://example.test/'},
'issues': [{'message': payload, 'severity': 'warning', 'category': 'SEO'}]}
records = [complete,
dict(complete, url='https://example.test/partial', status='partial'),
{'url': 'https://example.test/failed', 'status': 'error', 'error': 'Timed out', 'load_time': None},
{'url': 'https://example.test/skip', 'status': 'skipped', 'skipped': True, 'reason': 'Blocked by robots.txt'}]
data = {'pages': records, 'summary': {'page_limit': 500, 'analysis_duration': 12.5, 'completion_reason': 'queue_exhausted'},
'crawl_stats': {'requests_made': 5, 'cache_hits': 0, 'pages_per_second': 2 / 12.5,
'requests_by_kind': {'page': 4, 'robots': 1}, 'robots_delays': {'https://example.test': 5}}}
original = copy.deepcopy(data)
exporter = ExportManager({'output_directory': str(tmp_path), 'html_template': template})
soup = BeautifulSoup(Path(exporter.export(data, 'html')).read_text(encoding='utf-8'), 'html.parser')
inventory = json.loads(soup.select_one('#pages-data').string)
assert len(inventory) == 4
assert inventory[0]['load_time'] == 0.123456
assert inventory[0]['headers_seconds'] == 0.1
assert inventory[0]['fetch_elapsed_seconds'] == 5.5
assert inventory[0]['title'] == inventory[0]['findings'][0]['message'] == payload
assert inventory[0]['word_count'] == 321
assert inventory[0]['depth'] == 2
assert inventory[2]['load_time'] is None
assert inventory[3]['reason'] == 'Blocked by robots.txt'
assert soup.select_one('[data-metric="recorded"]').get_text() == '4'
assert soup.select_one('[data-metric="analyzed"]').get_text() == '2'
assert soup.select_one('[data-metric="page-limit"]').get_text() == '500'
assert soup.select_one('[data-metric="duration"]').get_text() == '12.50 s'
assert soup.select_one('#page-search') and soup.select_one('#page-sort') and soup.select_one('#page-outcome')
assert not soup.select('[onerror]')
assert not soup.find('img')
if template == 'optimized':
assert not soup.select('script[src]')
assert '0.123 s' in soup.select_one('#performance').get_text()
assert data == original


def test_imported_report_does_not_invent_fast_crawl_or_page_budget(exporter):
prepared = exporter._prepare_html_data({'pages': [{'url': 'https://example.test'}],
'summary': {'analysis_duration': 0}})
assert prepared['audit']['duration'] is None
assert prepared['audit']['throughput'] is None
assert prepared['audit']['page_limit'] is None
assert prepared['audit']['requests'] is None
assert prepared['audit']['unknown'] == 1
empty = exporter._prepare_html_data({'status': 'error', 'error': 'No pages to analyze'})
assert empty['audit']['recorded'] == 0
assert empty['pages_summary'] == []


@pytest.fixture
def page():
html = '''<html lang="en"><head><title>A useful title for the local export fixture</title>
Expand Down Expand Up @@ -239,12 +295,11 @@ def test_every_page_survives_large_report_export(tmp_path, page, template):
assert len(prepared['pages_summary']) == 506
assert prepared['pages_summary'][-1]['error'] == 'Timed out'
html = Path(exporter.export(report, 'html')).read_text(encoding='utf-8')
if template == 'optimized':
embedded = re.search(r'const pagesData = (.*);', html).group(1)
assert len(json.loads(embedded)) == 506
else:
soup = BeautifulSoup(html, 'html.parser')
assert len(soup.select('.pages-table tbody tr')) == 506
soup = BeautifulSoup(html, 'html.parser')
embedded = json.loads(soup.select_one('#pages-data').string)
assert len(embedded) == 506
assert embedded[-1]['error'] == 'Timed out'
assert len(soup.select('#pagesTable tbody tr')) == 20
with Path(exporter.export(report, 'csv')).open(encoding='utf-8', newline='') as stream:
rows = list(csv.DictReader(stream))
assert len(rows) == 506
Expand Down
12 changes: 5 additions & 7 deletions tests/test_rule_reports.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
import asyncio
import copy
import json
import re
from pathlib import Path

import pytest
Expand Down Expand Up @@ -119,10 +118,9 @@ def test_rule_metadata_does_not_drop_paginated_pages(tmp_path, analyzed_page, te
report = SEOAnalyzer().generate_site_report(pages)
soup, html, exporter = render(tmp_path, template, report)
assert len(exporter._prepare_html_data(report)['pages_summary']) == 25
if template == 'optimized':
embedded = re.search(r'const pagesData = (.*);', html).group(1)
assert len(json.loads(embedded)) == 25
assert 'Page 1 of 2' in soup.get_text()
else:
assert len(soup.select('.pages-table tbody tr')) == 25
embedded = json.loads(soup.select_one('#pages-data').string)
assert len(embedded) == 25
assert {page['url'] for page in embedded} == {page['url'] for page in pages}
assert 'Page 1 of 2' in soup.select_one('#pageInfo').get_text()
assert len(soup.select('#pagesTable tbody tr')) == 20
assert soup.select('.rule-metadata')
3 changes: 2 additions & 1 deletion tests/wheel_smoke.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,8 @@ async def main():
assert site['links']['node_count'] == 2 and site['links']['edge_count'] == 1
assert {'site.canonical_chain', 'site.canonical_target_redirect'} <= {
item['rule_id'] for item in site['findings']}
for filename in ('rule_metadata.html', 'site_analysis.html'):
for filename in ('rule_metadata.html', 'site_analysis.html', 'audit_summary.html',
'page_inventory.html', 'findings.html'):
assert (Path(tfq0seo.__file__).resolve().parent / 'templates' / filename).is_file()
exporter.jinja_env.get_template(filename)
templates = {'report': 'report.html', 'enhanced': 'enhanced_report.html', 'optimized': 'optimized_report.html'}
Expand Down
7 changes: 7 additions & 0 deletions tfq0seo/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ def create_summary_table(results: dict) -> Table:
for name in ('total_pages', 'successful_pages', 'partial_pages', 'failed_pages', 'skipped_pages'):
if name in results.get('summary', {}):
table.add_row(name.replace('_', ' ').title(), str(results['summary'][name]))
summary = results.get('summary', {})
if summary.get('page_limit') is not None:
table.add_row('Page Limit (Maximum)', str(summary['page_limit']))
if summary.get('analysis_duration') is not None:
table.add_row('Crawl + Analysis Elapsed', f"{summary['analysis_duration']:.2f}s")
if results.get('crawl_stats', {}).get('requests_made') is not None:
table.add_row('HTTP Requests (Including Discovery)', str(results['crawl_stats']['requests_made']))
table.add_row('Status', results.get('status', 'complete'))
return table

Expand Down
Loading
Loading