File size: 3,109 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
"""Validate semantic numeric rows without fixing a report's number formatting."""
from collections import Counter
from decimal import Decimal, InvalidOperation
from html.parser import HTMLParser
import re


class Tables(HTMLParser):
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.tables = []
        self.table = None
        self.row = None
        self.cell = None

    def handle_starttag(self, tag, attrs):
        if tag == 'table':
            self.table = []
        elif tag == 'tr' and self.table is not None:
            self.row = []
        elif tag in ('td', 'th') and self.row is not None:
            self.cell = []

    def handle_data(self, data):
        if self.cell is not None:
            self.cell.append(data)

    def handle_endtag(self, tag):
        if tag in ('td', 'th') and self.cell is not None:
            self.row.append(''.join(self.cell).strip())
            self.cell = None
        elif tag == 'tr' and self.row is not None:
            self.table.append(self.row)
            self.row = None
        elif tag == 'table' and self.table is not None:
            self.tables.append(self.table)
            self.table = None


def number(text):
    text = text.strip().replace('\u00a0', ' ').replace('\u202f', ' ')
    text = re.sub(r'^[¥¥$]\s*', '', text)
    if re.fullmatch(r'[+-]?\d{1,3}(?:[, ]\d{3})+(?:\.\d+)?', text):
        text = text.replace(',', '').replace(' ', '')
    try:
        value = Decimal(text)
    except InvalidOperation as exc:
        raise AssertionError(f'Invalid numeric table cell: {text!r}') from exc
    assert value.is_finite(), f'Non-finite table cell: {text!r}'
    return value


def assert_top_rows(report, expected):
    parser = Tables()
    parser.feed(report)
    assert_top_tables(parser.tables,expected)


def assert_top_tables(tables, expected):
    aliases = [('price', '价格'), ('carat', '克拉'), ('z', '深度')]
    candidates = []
    for table in tables:
        for index, row in enumerate(table):
            headers = [cell.lower().strip() for cell in row]
            columns = [next((i for i, cell in enumerate(headers)
                             if any(re.search(r'(?<!\w)' + re.escape(a) + r'(?!\w)', cell)
                                    for a in names)), None) for names in aliases]
            if None not in columns and len(set(columns)) == 3:
                candidates.append((table[index + 1:], columns))
                break
    assert candidates, 'report needs a top-ten table with price/carat/z column labels'
    target = Counter(tuple(number(row[key]) for key in ('price', 'carat', 'z')) for row in expected)
    for rows, columns in candidates:
        try:
            actual = [tuple(number(row[i]) for i in columns) for row in rows if row]
        except (AssertionError, IndexError):
            continue
        if Counter(actual) == target and [v[0] for v in actual] == sorted((v[0] for v in actual), reverse=True):
            return
    raise AssertionError('report top-ten rows have missing, incorrect or misassociated price/carat/z values')