-
Notifications
You must be signed in to change notification settings - Fork 48
/
csvvalidator.py
1101 lines (887 loc) · 40.5 KB
/
csvvalidator.py
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
This module provides some simple utilities for validating data contained in CSV
files, or other similar data sources.
Note that the `csvvalidator` module is intended to be used in combination with
the standard Python `csv` module. The `csvvalidator` module **will not**
validate the *syntax* of a CSV file. Rather, the `csvvalidator` module can be
used to validate any source of row-oriented data, such as is provided by a
`csv.reader` object.
I.e., if you want to validate data from a CSV file, you have to first construct
a CSV reader using the standard Python `csv` module, specifying the appropriate
dialect, and then pass the CSV reader as the source of data to either the
`CSVValidator.validate` or the `CSVValidator.ivalidate` method.
The `CSVValidator` class is the foundation for all validator objects that are
capable of validating CSV data.
You can use the CSVValidator class to dynamically construct a validator, e.g.::
import sys
import csv
from csvvalidator import *
field_names = (
'study_id',
'patient_id',
'gender',
'age_years',
'age_months',
'date_inclusion'
)
validator = CSVValidator(field_names)
# basic header and record length checks
validator.add_header_check('EX1', 'bad header')
validator.add_record_length_check('EX2', 'unexpected record length')
# some simple value checks
validator.add_value_check('study_id', int,
'EX3', 'study id must be an integer')
validator.add_value_check('patient_id', int,
'EX4', 'patient id must be an integer')
validator.add_value_check('gender', enumeration('M', 'F'),
'EX5', 'invalid gender')
validator.add_value_check('age_years', number_range_inclusive(0, 120, int),
'EX6', 'invalid age in years')
validator.add_value_check('date_inclusion', datetime_string('%Y-%m-%d'),
'EX7', 'invalid date')
# a more complicated record check
def check_age_variables(r):
age_years = int(r['age_years'])
age_months = int(r['age_months'])
valid = (age_months >= age_years * 12 and
age_months % age_years < 12)
if not valid:
raise RecordError('EX8', 'invalid age variables')
validator.add_record_check(check_age_variables)
# validate the data and write problems to stdout
data = csv.reader('/path/to/data.csv', delimiter='\t')
problems = validator.validate(data)
write_problems(problems, sys.stdout)
For more complex use cases you can also sub-class `CSVValidator` to define
re-usable validator classes for specific data sources.
The source code for this module lives at:
https://github.com/alimanfoo/csvvalidator
For a complete account of all of the functionality available from this module,
see the example.py and tests.py modules in the source code repository.
"""
import re
from datetime import datetime
UNEXPECTED_EXCEPTION = 0
VALUE_CHECK_FAILED = 1
HEADER_CHECK_FAILED = 2
RECORD_LENGTH_CHECK_FAILED = 3
VALUE_PREDICATE_FALSE = 4
RECORD_CHECK_FAILED = 5
RECORD_PREDICATE_FALSE = 6
UNIQUE_CHECK_FAILED = 7
ASSERT_CHECK_FAILED = 8
FINALLY_ASSERT_CHECK_FAILED = 9
MESSAGES = {
UNEXPECTED_EXCEPTION: 'Unexpected exception [%s]: %s',
VALUE_CHECK_FAILED: 'Value check failed.',
HEADER_CHECK_FAILED: 'Header check failed.',
RECORD_LENGTH_CHECK_FAILED: 'Record length check failed.',
RECORD_CHECK_FAILED: 'Record check failed.',
VALUE_PREDICATE_FALSE: 'Value predicate returned false.',
RECORD_PREDICATE_FALSE: 'Record predicate returned false.',
UNIQUE_CHECK_FAILED: 'Unique check failed.',
ASSERT_CHECK_FAILED: 'Assertion check failed.',
FINALLY_ASSERT_CHECK_FAILED: 'Final assertion check failed.'
}
class RecordError(Exception):
"""Exception representing a validation problem in a record."""
def __init__(self, code=None, message=None, details=None):
self.code = code
self.message = message
self.details = details
def __str__(self):
return repr((self.code, self.message, self.details))
def __repr__(self):
return repr((self.code, self.message, self.details))
class CSVValidator(object):
"""
Instances of this class can be configured to run a variety of different
types of validation check on a CSV-like data source.
"""
def __init__(self, field_names):
"""
Instantiate a `CSVValidator`, supplying expected `field_names` as a
sequence of strings.
"""
self._field_names = tuple(field_names)
self._value_checks = []
self._header_checks = []
self._record_length_checks = []
self._value_predicates = []
self._record_checks = []
self._record_predicates = []
self._unique_checks = []
self._skips = []
def add_header_check(self,
code=HEADER_CHECK_FAILED,
message=MESSAGES[HEADER_CHECK_FAILED]):
"""
Add a header check, i.e., check whether the header record is consistent
with the expected field names.
Arguments
---------
`code` - problem code to report if the header record is not valid,
defaults to `HEADER_CHECK_FAILED`
`message` - problem message to report if a value is not valid
"""
t = code, message
self._header_checks.append(t)
def add_record_length_check(self,
code=RECORD_LENGTH_CHECK_FAILED,
message=MESSAGES[RECORD_LENGTH_CHECK_FAILED],
modulus=1):
"""
Add a record length check, i.e., check whether the length of a record is
consistent with the number of expected fields.
Arguments
---------
`code` - problem code to report if a record is not valid, defaults to
`RECORD_LENGTH_CHECK_FAILED`
`message` - problem message to report if a record is not valid
`modulus` - apply the check to every nth record, defaults to 1 (check
every record)
"""
t = code, message, modulus
self._record_length_checks.append(t)
def add_value_check(self, field_name, value_check,
code=VALUE_CHECK_FAILED,
message=MESSAGES[VALUE_CHECK_FAILED],
modulus=1):
"""
Add a value check function for the specified field.
Arguments
---------
`field_name` - the name of the field to attach the value check function
to
`value_check` - a function that accepts a single argument (a value) and
raises a `ValueError` if the value is not valid
`code` - problem code to report if a value is not valid, defaults to
`VALUE_CHECK_FAILED`
`message` - problem message to report if a value is not valid
`modulus` - apply the check to every nth record, defaults to 1 (check
every record)
"""
# guard conditions
assert field_name in self._field_names, 'unexpected field name: %s' % field_name
assert callable(value_check), 'value check must be a callable function'
t = field_name, value_check, code, message, modulus
self._value_checks.append(t)
def add_value_predicate(self, field_name, value_predicate,
code=VALUE_PREDICATE_FALSE,
message=MESSAGES[VALUE_PREDICATE_FALSE],
modulus=1):
"""
Add a value predicate function for the specified field.
N.B., everything you can do with value predicates can also be done with
value check functions, whether you use one or the other is a matter of
style.
Arguments
---------
`field_name` - the name of the field to attach the value predicate
function to
`value_predicate` - a function that accepts a single argument (a value)
and returns False if the value is not valid
`code` - problem code to report if a value is not valid, defaults to
`VALUE_PREDICATE_FALSE`
`message` - problem message to report if a value is not valid
`modulus` - apply the check to every nth record, defaults to 1 (check
every record)
"""
assert field_name in self._field_names, 'unexpected field name: %s' % field_name
assert callable(value_predicate), 'value predicate must be a callable function'
t = field_name, value_predicate, code, message, modulus
self._value_predicates.append(t)
def add_record_check(self, record_check, modulus=1):
"""
Add a record check function.
Arguments
---------
`record_check` - a function that accepts a single argument (a record as
a dictionary of values indexed by field name) and raises a
`RecordError` if the record is not valid
`modulus` - apply the check to every nth record, defaults to 1 (check
every record)
"""
assert callable(record_check), 'record check must be a callable function'
t = record_check, modulus
self._record_checks.append(t)
def add_record_predicate(self, record_predicate,
code=RECORD_PREDICATE_FALSE,
message=MESSAGES[RECORD_PREDICATE_FALSE],
modulus=1):
"""
Add a record predicate function.
N.B., everything you can do with record predicates can also be done with
record check functions, whether you use one or the other is a matter of
style.
Arguments
---------
`record_predicate` - a function that accepts a single argument (a record
as a dictionary of values indexed by field name) and returns False if
the value is not valid
`code` - problem code to report if a record is not valid, defaults to
`RECORD_PREDICATE_FALSE`
`message` - problem message to report if a record is not valid
`modulus` - apply the check to every nth record, defaults to 1 (check
every record)
"""
assert callable(record_predicate), 'record predicate must be a callable function'
t = record_predicate, code, message, modulus
self._record_predicates.append(t)
def add_unique_check(self, key,
code=UNIQUE_CHECK_FAILED,
message=MESSAGES[UNIQUE_CHECK_FAILED]):
"""
Add a unique check on a single column or combination of columns.
Arguments
---------
`key` - a single field name (string) specifying a field in which all
values are expected to be unique, or a sequence of field names (tuple
or list of strings) specifying a compound key
`code` - problem code to report if a record is not valid, defaults to
`UNIQUE_CHECK_FAILED`
`message` - problem message to report if a record is not valid
"""
if isinstance(key, basestring):
assert key in self._field_names, 'unexpected field name: %s' % key
else:
for f in key:
assert f in self._field_names, 'unexpected field name: %s' % key
t = key, code, message
self._unique_checks.append(t)
def add_skip(self, skip):
"""
Add a `skip` function which accepts a single argument (a record as a
sequence of values) and returns True if all checks on the record should
be skipped.
"""
assert callable(skip), 'skip must be a callable function'
self._skips.append(skip)
def validate(self, data,
expect_header_row=True,
ignore_lines=0,
summarize=False,
limit=0,
context=None,
report_unexpected_exceptions=True):
"""
Validate `data` and return a list of validation problems found.
Arguments
---------
`data` - any source of row-oriented data, e.g., as provided by a
`csv.reader`, or a list of lists of strings, or ...
`expect_header_row` - does the data contain a header row (i.e., the
first record is a list of field names)? Defaults to True.
`ignore_lines` - ignore n lines (rows) at the beginning of the data
`summarize` - only report problem codes, no other details
`limit` - report at most n problems
`context` - a dictionary of any additional information to be added to
any problems found - useful if problems are being aggregated from
multiple validators
`report_unexpected_exceptions` - value check function, value predicates,
record check functions, record predicates, and other user-supplied
validation functions may raise unexpected exceptions. If this argument
is true, any unexpected exceptions will be reported as validation
problems; if False, unexpected exceptions will be handled silently.
"""
problems = list()
problem_generator = self.ivalidate(data, expect_header_row,
ignore_lines, summarize, context,
report_unexpected_exceptions)
for i, p in enumerate(problem_generator):
if not limit or i < limit:
problems.append(p)
return problems
def ivalidate(self, data,
expect_header_row=True,
ignore_lines=0,
summarize=False,
context=None,
report_unexpected_exceptions=True):
"""
Validate `data` and return a iterator over problems found.
Use this function rather than validate() if you expect a large number
of problems.
Arguments
---------
`data` - any source of row-oriented data, e.g., as provided by a
`csv.reader`, or a list of lists of strings, or ...
`expect_header_row` - does the data contain a header row (i.e., the
first record is a list of field names)? Defaults to True.
`ignore_lines` - ignore n lines (rows) at the beginning of the data
`summarize` - only report problem codes, no other details
`context` - a dictionary of any additional information to be added to
any problems found - useful if problems are being aggregated from
multiple validators
`report_unexpected_exceptions` - value check function, value predicates,
record check functions, record predicates, and other user-supplied
validation functions may raise unexpected exceptions. If this argument
is true, any unexpected exceptions will be reported as validation
problems; if False, unexpected exceptions will be handled silently.
"""
unique_sets = self._init_unique_sets() # used for unique checks
for i, r in enumerate(data):
if expect_header_row and i == ignore_lines:
# r is the header row
for p in self._apply_header_checks(i, r, summarize, context):
yield p
elif i >= ignore_lines:
# r is a data row
skip = False
for p in self._apply_skips(i, r, summarize,
report_unexpected_exceptions,
context):
if p is True:
skip = True
else:
yield p
if not skip:
for p in self._apply_each_methods(i, r, summarize,
report_unexpected_exceptions,
context):
yield p # may yield a problem if an exception is raised
for p in self._apply_value_checks(i, r, summarize,
report_unexpected_exceptions,
context):
yield p
for p in self._apply_record_length_checks(i, r, summarize,
context):
yield p
for p in self._apply_value_predicates(i, r, summarize,
report_unexpected_exceptions,
context):
yield p
for p in self._apply_record_checks(i, r, summarize,
report_unexpected_exceptions,
context):
yield p
for p in self._apply_record_predicates(i, r, summarize,
report_unexpected_exceptions,
context):
yield p
for p in self._apply_unique_checks(i, r, unique_sets, summarize):
yield p
for p in self._apply_check_methods(i, r, summarize,
report_unexpected_exceptions,
context):
yield p
for p in self._apply_assert_methods(i, r, summarize,
report_unexpected_exceptions,
context):
yield p
for p in self._apply_finally_assert_methods(summarize,
report_unexpected_exceptions,
context):
yield p
def _init_unique_sets(self):
"""Initialise sets used for uniqueness checking."""
ks = dict()
for t in self._unique_checks:
key = t[0]
ks[key] = set() # empty set
return ks
def _apply_value_checks(self, i, r,
summarize=False,
report_unexpected_exceptions=True,
context=None):
"""Apply value check functions on the given record `r`."""
for field_name, check, code, message, modulus in self._value_checks:
if i % modulus == 0: # support sampling
fi = self._field_names.index(field_name)
if fi < len(r): # only apply checks if there is a value
value = r[fi]
try:
check(value)
except ValueError:
p = {'code': code}
if not summarize:
p['message'] = message
p['row'] = i + 1
p['column'] = fi + 1
p['field'] = field_name
p['value'] = value
p['record'] = r
if context is not None: p['context'] = context
yield p
except Exception as e:
if report_unexpected_exceptions:
p = {'code': UNEXPECTED_EXCEPTION}
if not summarize:
p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)
p['row'] = i + 1
p['column'] = fi + 1
p['field'] = field_name
p['value'] = value
p['record'] = r
p['exception'] = e
p['function'] = '%s: %s' % (check.__name__,
check.__doc__)
if context is not None: p['context'] = context
yield p
def _apply_header_checks(self, i, r, summarize=False, context=None):
"""Apply header checks on the given record `r`."""
for code, message in self._header_checks:
if tuple(r) != self._field_names:
p = {'code': code}
if not summarize:
p['message'] = message
p['row'] = i + 1
p['record'] = tuple(r)
p['missing'] = set(self._field_names) - set(r)
p['unexpected'] = set(r) - set(self._field_names)
if context is not None: p['context'] = context
yield p
def _apply_record_length_checks(self, i, r, summarize=False, context=None):
"""Apply record length checks on the given record `r`."""
for code, message, modulus in self._record_length_checks:
if i % modulus == 0: # support sampling
if len(r) != len(self._field_names):
p = {'code': code}
if not summarize:
p['message'] = message
p['row'] = i + 1
p['record'] = r
p['length'] = len(r)
if context is not None: p['context'] = context
yield p
def _apply_value_predicates(self, i, r,
summarize=False,
report_unexpected_exceptions=True,
context=None):
"""Apply value predicates on the given record `r`."""
for field_name, predicate, code, message, modulus in self._value_predicates:
if i % modulus == 0: # support sampling
fi = self._field_names.index(field_name)
if fi < len(r): # only apply predicate if there is a value
value = r[fi]
try:
valid = predicate(value)
if not valid:
p = {'code': code}
if not summarize:
p['message'] = message
p['row'] = i + 1
p['column'] = fi + 1
p['field'] = field_name
p['value'] = value
p['record'] = r
if context is not None: p['context'] = context
yield p
except Exception as e:
if report_unexpected_exceptions:
p = {'code': UNEXPECTED_EXCEPTION}
if not summarize:
p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)
p['row'] = i + 1
p['column'] = fi + 1
p['field'] = field_name
p['value'] = value
p['record'] = r
p['exception'] = e
p['function'] = '%s: %s' % (predicate.__name__,
predicate.__doc__)
if context is not None: p['context'] = context
yield p
def _apply_record_checks(self, i, r,
summarize=False,
report_unexpected_exceptions=True,
context=None):
"""Apply record checks on `r`."""
for check, modulus in self._record_checks:
if i % modulus == 0: # support sampling
rdict = self._as_dict(r)
try:
check(rdict)
except RecordError as e:
code = e.code if e.code is not None else RECORD_CHECK_FAILED
p = {'code': code}
if not summarize:
message = e.message if e.message is not None else MESSAGES[RECORD_CHECK_FAILED]
p['message'] = message
p['row'] = i + 1
p['record'] = r
if context is not None: p['context'] = context
if e.details is not None: p['details'] = e.details
yield p
except Exception as e:
if report_unexpected_exceptions:
p = {'code': UNEXPECTED_EXCEPTION}
if not summarize:
p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)
p['row'] = i + 1
p['record'] = r
p['exception'] = e
p['function'] = '%s: %s' % (check.__name__,
check.__doc__)
if context is not None: p['context'] = context
yield p
def _apply_record_predicates(self, i, r,
summarize=False,
report_unexpected_exceptions=True,
context=None):
"""Apply record predicates on `r`."""
for predicate, code, message, modulus in self._record_predicates:
if i % modulus == 0: # support sampling
rdict = self._as_dict(r)
try:
valid = predicate(rdict)
if not valid:
p = {'code': code}
if not summarize:
p['message'] = message
p['row'] = i + 1
p['record'] = r
if context is not None: p['context'] = context
yield p
except Exception as e:
if report_unexpected_exceptions:
p = {'code': UNEXPECTED_EXCEPTION}
if not summarize:
p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)
p['row'] = i + 1
p['record'] = r
p['exception'] = e
p['function'] = '%s: %s' % (predicate.__name__,
predicate.__doc__)
if context is not None: p['context'] = context
yield p
def _apply_unique_checks(self, i, r, unique_sets,
summarize=False,
context=None):
"""Apply unique checks on `r`."""
for key, code, message in self._unique_checks:
value = None
values = unique_sets[key]
if isinstance(key, basestring): # assume key is a field name
fi = self._field_names.index(key)
if fi >= len(r):
continue
value = r[fi]
else: # assume key is a list or tuple, i.e., compound key
value = []
for f in key:
fi = self._field_names.index(f)
if fi >= len(r):
break
value.append(r[fi])
value = tuple(value) # enable hashing
if value in values:
p = {'code': code}
if not summarize:
p['message'] = message
p['row'] = i + 1
p['record'] = r
p['key'] = key
p['value'] = value
if context is not None: p['context'] = context
yield p
values.add(value)
def _apply_each_methods(self, i, r,
summarize=False,
report_unexpected_exceptions=True,
context=None):
"""Invoke 'each' methods on `r`."""
for a in dir(self):
if a.startswith('each'):
rdict = self._as_dict(r)
f = getattr(self, a)
try:
f(rdict)
except Exception as e:
if report_unexpected_exceptions:
p = {'code': UNEXPECTED_EXCEPTION}
if not summarize:
p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)
p['row'] = i + 1
p['record'] = r
p['exception'] = e
p['function'] = '%s: %s' % (f.__name__,
f.__doc__)
if context is not None: p['context'] = context
yield p
def _apply_assert_methods(self, i, r,
summarize=False,
report_unexpected_exceptions=True,
context=None):
"""Apply 'assert' methods on `r`."""
for a in dir(self):
if a.startswith('assert'):
rdict = self._as_dict(r)
f = getattr(self, a)
try:
f(rdict)
except AssertionError as e:
code = ASSERT_CHECK_FAILED
message = MESSAGES[ASSERT_CHECK_FAILED]
if len(e.args) > 0:
custom = e.args[0]
if isinstance(custom, (list, tuple)):
if len(custom) > 0:
code = custom[0]
if len(custom) > 1:
message = custom[1]
else:
code = custom
p = {'code': code}
if not summarize:
p['message'] = message
p['row'] = i + 1
p['record'] = r
if context is not None: p['context'] = context
yield p
except Exception as e:
if report_unexpected_exceptions:
p = {'code': UNEXPECTED_EXCEPTION}
if not summarize:
p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)
p['row'] = i + 1
p['record'] = r
p['exception'] = e
p['function'] = '%s: %s' % (f.__name__,
f.__doc__)
if context is not None: p['context'] = context
yield p
def _apply_check_methods(self, i, r,
summarize=False,
report_unexpected_exceptions=True,
context=None):
"""Apply 'check' methods on `r`."""
for a in dir(self):
if a.startswith('check'):
rdict = self._as_dict(r)
f = getattr(self, a)
try:
f(rdict)
except RecordError as e:
code = e.code if e.code is not None else RECORD_CHECK_FAILED
p = {'code': code}
if not summarize:
message = e.message if e.message is not None else MESSAGES[RECORD_CHECK_FAILED]
p['message'] = message
p['row'] = i + 1
p['record'] = r
if context is not None: p['context'] = context
if e.details is not None: p['details'] = e.details
yield p
except Exception as e:
if report_unexpected_exceptions:
p = {'code': UNEXPECTED_EXCEPTION}
if not summarize:
p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)
p['row'] = i + 1
p['record'] = r
p['exception'] = e
p['function'] = '%s: %s' % (f.__name__,
f.__doc__)
if context is not None: p['context'] = context
yield p
def _apply_finally_assert_methods(self,
summarize=False,
report_unexpected_exceptions=True,
context=None):
"""Apply 'finally_assert' methods."""
for a in dir(self):
if a.startswith('finally_assert'):
f = getattr(self, a)
try:
f()
except AssertionError as e:
code = ASSERT_CHECK_FAILED
message = MESSAGES[ASSERT_CHECK_FAILED]
if len(e.args) > 0:
custom = e.args[0]
if isinstance(custom, (list, tuple)):
if len(custom) > 0:
code = custom[0]
if len(custom) > 1:
message = custom[1]
else:
code = custom
p = {'code': code}
if not summarize:
p['message'] = message
if context is not None: p['context'] = context
yield p
except Exception as e:
if report_unexpected_exceptions:
p = {'code': UNEXPECTED_EXCEPTION}
if not summarize:
p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)
p['exception'] = e
p['function'] = '%s: %s' % (f.__name__,
f.__doc__)
if context is not None: p['context'] = context
yield p
def _apply_skips(self, i, r,
summarize=False,
report_unexpected_exceptions=True,
context=None):
"""Apply skip functions on `r`."""
for skip in self._skips:
try:
result = skip(r)
if result is True:
yield True
except Exception as e:
if report_unexpected_exceptions:
p = {'code': UNEXPECTED_EXCEPTION}
if not summarize:
p['message'] = MESSAGES[UNEXPECTED_EXCEPTION] % (e.__class__.__name__, e)
p['row'] = i + 1
p['record'] = r
p['exception'] = e
p['function'] = '%s: %s' % (skip.__name__,
skip.__doc__)
if context is not None: p['context'] = context
yield p
def _as_dict(self, r):
"""Convert the record to a dictionary using field names as keys."""
d = dict()
for i, f in enumerate(self._field_names):
d[f] = r[i] if i < len(r) else None
return d
def enumeration(*args):
"""
Return a value check function which raises a value error if the value is not
in a pre-defined enumeration of values.
If you pass in a list, tuple or set as the single argument, it is assumed
that the list/tuple/set defines the membership of the enumeration.
If you pass in more than on argument, it is assumed the arguments themselves
define the enumeration.
"""
assert len(args) > 0, 'at least one argument is required'
if len(args) == 1:
# assume the first argument defines the membership
members = args[0]
else:
# assume the arguments are the members
members = args
def checker(value):
if value not in members:
raise ValueError(value)
return checker
def match_pattern(regex):
"""
Return a value check function which raises a ValueError if the value does
not match the supplied regular expression, see also `re.match`.
"""
prog = re.compile(regex)
def checker(v):
result = prog.match(v)
if result is None:
raise ValueError(v)
return checker
def search_pattern(regex):
"""
Return a value check function which raises a ValueError if the supplied
regular expression does not match anywhere in the value, see also
`re.search`.
"""
prog = re.compile(regex)
def checker(v):
result = prog.search(v)
if result is None:
raise ValueError(v)
return checker
def number_range_inclusive(min, max, type=float):
"""
Return a value check function which raises a ValueError if the supplied
value when cast as `type` is less than `min` or greater than `max`.
"""
def checker(v):
if type(v) < min or type(v) > max:
raise ValueError(v)
return checker
def number_range_exclusive(min, max, type=float):
"""
Return a value check function which raises a ValueError if the supplied
value when cast as `type` is less than or equal to `min` or greater than
or equal to `max`.
"""
def checker(v):
if type(v) <= min or type(v) >= max:
raise ValueError(v)
return checker