| 1 |
# -*- coding: utf-8 -*- |
| 2 |
from __future__ import absolute_import, print_function, division |
| 3 |
|
| 4 |
|
| 5 |
import operator |
| 6 |
from petl.compat import text_type |
| 7 |
|
| 8 |
|
| 9 |
from petl.util.base import Table, asindices, Record |
| 10 |
|
| 11 |
|
| 12 |
def validate(table, constraints=None, header=None): |
| 13 |
""" |
| 14 |
Validate a `table` against a set of `constraints` and/or an expected |
| 15 |
`header`, e.g.:: |
| 16 |
|
| 17 |
>>> import petl as etl |
| 18 |
>>> # define some validation constraints |
| 19 |
... header = ('foo', 'bar', 'baz') |
| 20 |
>>> constraints = [ |
| 21 |
... dict(name='foo_int', field='foo', test=int), |
| 22 |
... dict(name='bar_date', field='bar', test=etl.dateparser('%Y-%m-%d')), |
| 23 |
... dict(name='baz_enum', field='baz', assertion=lambda v: v in ['Y', 'N']), |
| 24 |
... dict(name='not_none', assertion=lambda row: None not in row), |
| 25 |
... dict(name='qux_int', field='qux', test=int, optional=True), |
| 26 |
... ] |
| 27 |
>>> # now validate a table |
| 28 |
... table = (('foo', 'bar', 'bazzz'), |
| 29 |
... (1, '2000-01-01', 'Y'), |
| 30 |
... ('x', '2010-10-10', 'N'), |
| 31 |
... (2, '2000/01/01', 'Y'), |
| 32 |
... (3, '2015-12-12', 'x'), |
| 33 |
... (4, None, 'N'), |
| 34 |
... ('y', '1999-99-99', 'z'), |
| 35 |
... (6, '2000-01-01'), |
| 36 |
... (7, '2001-02-02', 'N', True)) |
| 37 |
>>> problems = etl.validate(table, constraints=constraints, header=header) |
| 38 |
>>> problems.lookall() |
| 39 |
+--------------+-----+-------+--------------+------------------+ |
| 40 |
| name | row | field | value | error | |
| 41 |
+==============+=====+=======+==============+==================+ |
| 42 |
| '__header__' | 0 | None | None | 'AssertionError' | |
| 43 |
+--------------+-----+-------+--------------+------------------+ |
| 44 |
| 'foo_int' | 2 | 'foo' | 'x' | 'ValueError' | |
| 45 |
+--------------+-----+-------+--------------+------------------+ |
| 46 |
| 'bar_date' | 3 | 'bar' | '2000/01/01' | 'ValueError' | |
| 47 |
+--------------+-----+-------+--------------+------------------+ |
| 48 |
| 'baz_enum' | 4 | 'baz' | 'x' | 'AssertionError' | |
| 49 |
+--------------+-----+-------+--------------+------------------+ |
| 50 |
| 'bar_date' | 5 | 'bar' | None | 'AttributeError' | |
| 51 |
+--------------+-----+-------+--------------+------------------+ |
| 52 |
| 'not_none' | 5 | None | None | 'AssertionError' | |
| 53 |
+--------------+-----+-------+--------------+------------------+ |
| 54 |
| 'foo_int' | 6 | 'foo' | 'y' | 'ValueError' | |
| 55 |
+--------------+-----+-------+--------------+------------------+ |
| 56 |
| 'bar_date' | 6 | 'bar' | '1999-99-99' | 'ValueError' | |
| 57 |
+--------------+-----+-------+--------------+------------------+ |
| 58 |
| 'baz_enum' | 6 | 'baz' | 'z' | 'AssertionError' | |
| 59 |
+--------------+-----+-------+--------------+------------------+ |
| 60 |
| '__len__' | 7 | None | 2 | 'AssertionError' | |
| 61 |
+--------------+-----+-------+--------------+------------------+ |
| 62 |
| 'baz_enum' | 7 | 'baz' | None | 'AssertionError' | |
| 63 |
+--------------+-----+-------+--------------+------------------+ |
| 64 |
| '__len__' | 8 | None | 4 | 'AssertionError' | |
| 65 |
+--------------+-----+-------+--------------+------------------+ |
| 66 |
|
| 67 |
Returns a table of validation problems. |
| 68 |
|
| 69 |
""" # noqa |
| 70 |
|
| 71 |
return ProblemsView(table, constraints=constraints, header=header) |
| 72 |
|
| 73 |
|
| 74 |
Table.validate = validate |
| 75 |
|
| 76 |
|
| 77 |
class ProblemsView(Table): |
| 78 |
|
| 79 |
def __init__(self, table, constraints, header): |
| 80 |
self.table = table |
| 81 |
self.constraints = constraints |
| 82 |
self.header = header |
| 83 |
|
| 84 |
def __iter__(self): |
| 85 |
return iterproblems(self.table, self.constraints, self.header) |
| 86 |
|
| 87 |
|
| 88 |
def normalize_constraints(constraints, flds): |
| 89 |
""" |
| 90 |
This method renders local constraints such that return value is: |
| 91 |
* a list, not None |
| 92 |
* a list of dicts |
| 93 |
* a list of non-optional constraints or optional with defined field |
| 94 |
|
| 95 |
.. note:: We use a new variable 'local_constraints' because the constraints |
| 96 |
parameter may be a mutable collection, and we do not wish to |
| 97 |
cause side-effects by modifying it locally |
| 98 |
""" |
| 99 |
local_constraints = constraints or [] |
| 100 |
local_constraints = [dict(**c) for c in local_constraints] |
| 101 |
local_constraints = [ |
| 102 |
c for c in local_constraints |
| 103 |
if c.get('field') in flds or |
| 104 |
not c.get('optional') |
| 105 |
] |
| 106 |
return local_constraints |
| 107 |
|
| 108 |
|
| 109 |
def iterproblems(table, constraints, expected_header): |
| 110 |
|
| 111 |
outhdr = ('name', 'row', 'field', 'value', 'error') |
| 112 |
yield outhdr |
| 113 |
|
| 114 |
it = iter(table) |
| 115 |
try: |
| 116 |
actual_header = next(it) |
| 117 |
except StopIteration: |
| 118 |
actual_header = [] |
| 119 |
|
| 120 |
if expected_header is None: |
| 121 |
flds = list(map(text_type, actual_header)) |
| 122 |
else: |
| 123 |
expected_flds = list(map(text_type, expected_header)) |
| 124 |
actual_flds = list(map(text_type, actual_header)) |
| 125 |
try: |
| 126 |
assert expected_flds == actual_flds |
| 127 |
except Exception as e: |
| 128 |
yield ('__header__', 0, None, None, type(e).__name__) |
| 129 |
flds = expected_flds |
| 130 |
|
| 131 |
local_constraints = normalize_constraints(constraints, flds) |
| 132 |
|
| 133 |
# setup getters |
| 134 |
for constraint in local_constraints: |
| 135 |
if 'getter' not in constraint: |
| 136 |
if 'field' in constraint: |
| 137 |
# should ensure FieldSelectionError if bad field in constraint |
| 138 |
indices = asindices(flds, constraint['field']) |
| 139 |
getter = operator.itemgetter(*indices) |
| 140 |
constraint['getter'] = getter |
| 141 |
|
| 142 |
# generate problems |
| 143 |
expected_len = len(flds) |
| 144 |
for i, row in enumerate(it): |
| 145 |
row = tuple(row) |
| 146 |
|
| 147 |
# row length constraint |
| 148 |
l = None |
| 149 |
try: |
| 150 |
l = len(row) |
| 151 |
assert l == expected_len |
| 152 |
except Exception as e: |
| 153 |
yield ('__len__', i+1, None, l, type(e).__name__) |
| 154 |
|
| 155 |
# user defined constraints |
| 156 |
row = Record(row, flds) |
| 157 |
for constraint in local_constraints: |
| 158 |
name = constraint.get('name', None) |
| 159 |
field = constraint.get('field', None) |
| 160 |
assertion = constraint.get('assertion', None) |
| 161 |
test = constraint.get('test', None) |
| 162 |
getter = constraint.get('getter', lambda x: x) |
| 163 |
try: |
| 164 |
target = getter(row) |
| 165 |
except Exception as e: |
| 166 |
# getting target value failed, report problem |
| 167 |
yield (name, i+1, field, None, type(e).__name__) |
| 168 |
else: |
| 169 |
value = target if field else None |
| 170 |
if test is not None: |
| 171 |
try: |
| 172 |
test(target) |
| 173 |
except Exception as e: |
| 174 |
# test raised exception, report problem |
| 175 |
yield (name, i+1, field, value, type(e).__name__) |
| 176 |
if assertion is not None: |
| 177 |
try: |
| 178 |
assert assertion(target) |
| 179 |
except Exception as e: |
| 180 |
# assertion raised exception, report problem |
| 181 |
yield (name, i+1, field, value, type(e).__name__) |