File size: 5,552 Bytes
ef987bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import csv, pathlib, math, os, re
from html.parser import HTMLParser
root = pathlib.Path.cwd()
clean = root / 'titanic_clean.csv'
report = (root / 'report.html').read_text(encoding='utf-8', errors='ignore').lower()
rows = list(csv.DictReader(clean.open(encoding='utf-8-sig')))
assert rows, 'titanic_clean.csv has no rows'
fields = set(rows[0])
for col in ['age', 'deck', 'embarked', 'class', 'is_alone']:
    assert col in fields, f'missing column {col}'
assert all(r['age'] != '' for r in rows), 'age still has missing values'
assert all(r['deck'] != '' for r in rows), 'deck still has missing values'

# read the source fixture and assert row-count parity + recompute is_alone
src = root / 'titanic.csv'
src_rows = list(csv.DictReader(src.open(encoding='utf-8-sig')))
assert len(rows) <= len(src_rows), 'cleaned output cannot add fixture records'
# recompute is_alone per row from sibsp+parch (sum==0 -> alone) and compare
def _truthy_alone(v):
    return str(v).strip().lower() in ('true', '1', 'yes')
not_alone_count = 0
src_by_fare = {float(r['fare']): r for r in src_rows}
for out_r in rows:
    assert float(out_r['fare']) in src_by_fare, f'unexpected cleaned row fare={out_r["fare"]}'
    src_r = src_by_fare[float(out_r['fare'])]
    sibsp = int(float(src_r.get('sibsp') or 0))
    parch = int(float(src_r.get('parch') or 0))
    expected_alone = (sibsp + parch == 0)
    got_alone = _truthy_alone(out_r['is_alone'])
    assert got_alone == expected_alone, (
        f'is_alone mismatch for sibsp={sibsp} parch={parch}: '
        f'expected {expected_alone}, got {out_r["is_alone"]!r}'
    )
    if not expected_alone:
        not_alone_count += 1

assert 'survival' in report or '生存' in report or 'survived' in report, 'report missing survival content'

class ReportParser(HTMLParser):
    def __init__(self):
        super().__init__()
        self.table_depth = 0
        self.svg_depth = 0
        self.rows = []
        self.bars = []
    def handle_starttag(self, tag, attrs):
        attrs = dict(attrs)
        if tag == 'table' and attrs.get('id') == 'survival-rates':
            self.table_depth += 1
        elif tag == 'svg' and attrs.get('id') == 'survival-chart':
            self.svg_depth += 1
        elif tag == 'tr' and self.table_depth and attrs.get('data-group'):
            self.rows.append(attrs)
        elif tag == 'rect' and self.svg_depth:
            self.bars.append(attrs)
    def handle_endtag(self, tag):
        if tag == 'table' and self.table_depth:
            self.table_depth -= 1
        elif tag == 'svg' and self.svg_depth:
            self.svg_depth -= 1

parsed = ReportParser()
parsed.feed((root / 'report.html').read_text(encoding='utf-8'))
expected = {}
for field in ('sex', 'class'):
    for row in rows:
        key = (field, row[field])
        expected.setdefault(key, [0, 0])
        expected[key][0] += int(str(row['survived']).strip().lower() in ('1', 'true'))
        expected[key][1] += 1
assert len(parsed.rows) == len(expected), 'report must contain one survival-rate row per sex/class category'
seen = set()
for row in parsed.rows:
    key = (row.get('data-group'), row.get('data-category'))
    assert key in expected and key not in seen, f'unexpected or duplicate survival row {key}'
    seen.add(key)
    survived, total = expected[key]
    assert int(row.get('data-survived', -1)) == survived and int(row.get('data-total', -1)) == total, f'wrong counts for {key}'
    assert math.isclose(float(row.get('data-rate', -1)), survived / total, abs_tol=0.0001), f'wrong survival rate for {key}'
assert seen == set(expected), 'report omitted a sex/class category'
assert len(parsed.bars) == len(expected), 'SVG chart needs one bar per reported category'
bar_sizes = {}
for bar in parsed.bars:
    key = (bar.get('data-group'), bar.get('data-category'))
    assert key in expected and key not in bar_sizes, f'unexpected or duplicate bar {key}'
    survived, total = expected[key]
    rate = survived / total
    assert math.isclose(float(bar.get('data-rate', -1)), rate, abs_tol=0.0001), f'bar rate mismatch for {key}'
    sizes = (float(bar.get('width', -1)), float(bar.get('height', -1)))
    assert all(size >= 0 and math.isfinite(size) for size in sizes), f'invalid bar size for {key}'
    bar_sizes[key] = sizes
assert set(bar_sizes) == set(expected), 'chart omitted a category'
# Horizontal and vertical bars are both valid. One dimension must share a
# linear zero-origin scale with the actual rates, not merely their ordering.
def proportional(dimension):
    ratios = [bar_sizes[key][dimension] / (counts[0] / counts[1])
              for key, counts in expected.items() if counts[0]]
    if not ratios:
        return all(bar_sizes[key][dimension] <= 0.01 for key in expected)
    if min(ratios) <= 0:
        return False
    return max(ratios) - min(ratios) <= max(ratios) * 0.01 and all(
        bar_sizes[key][dimension] <= 0.01 for key, counts in expected.items() if not counts[0])
assert proportional(0) or proportional(1), 'bar lengths must proportionally encode rates on a shared axis'

log = pathlib.Path(os.environ.get('TITANIC_PROGRESS_LOG', '/tmp/harbor_data_run.log')).read_text(encoding='utf-8', errors='ignore')
assert re.search(r'\[\d+/\d+\]|\d+(?:\.\d+)?\s*%', log), 'script must show staged progress'
assert any(token in log.lower() for token in ('age', 'deck', '缺失', '清洗')), 'progress log missing cleaning stage'
assert any(token in log.lower() for token in ('report', '报告')), 'progress log missing report stage'