forked from assertpy/assertpy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathassertpy.py
More file actions
1389 lines (1232 loc) · 60.6 KB
/
assertpy.py
File metadata and controls
1389 lines (1232 loc) · 60.6 KB
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
# Copyright (c) 2015-2018, Activision Publishing, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Assertion library for python unit testing with a fluent API"""
from __future__ import division, print_function
import re
import os
import sys
import datetime
import numbers
import collections
import inspect
import math
import contextlib
import json
__version__ = '0.14'
__tracebackhide__ = True # clean tracebacks via py.test integration
contextlib.__tracebackhide__ = True # monkey patch contextlib with clean py.test tracebacks
if sys.version_info[0] == 3:
str_types = (str,)
xrange = range
unicode = str
Iterable = collections.abc.Iterable
else:
str_types = (basestring,)
xrange = xrange
unicode = unicode
Iterable = collections.Iterable
### soft assertions ###
_soft_ctx = 0
_soft_err = []
@contextlib.contextmanager
def soft_assertions():
global _soft_ctx
global _soft_err
# init ctx
if _soft_ctx == 0:
_soft_err = []
_soft_ctx += 1
try:
yield
finally:
# reset ctx
_soft_ctx -= 1
if _soft_err and _soft_ctx == 0:
out = 'soft assertion failures:'
for i,msg in enumerate(_soft_err):
out += '\n%d. %s' % (i+1, msg)
# reset msg, then raise
_soft_err = []
raise AssertionError(out)
### factory methods ###
def assert_that(val, description=''):
"""Factory method for the assertion builder with value to be tested and optional description."""
global _soft_ctx
if _soft_ctx:
return AssertionBuilder(val, description, 'soft')
return AssertionBuilder(val, description)
def assert_warn(val, description=''):
"""Factory method for the assertion builder with value to be tested, optional description, and
just warn on assertion failures instead of raisings exceptions."""
return AssertionBuilder(val, description, 'warn')
def contents_of(f, encoding='utf-8'):
"""Helper to read the contents of the given file or path into a string with the given encoding.
Encoding defaults to 'utf-8', other useful encodings are 'ascii' and 'latin-1'."""
try:
contents = f.read()
except AttributeError:
try:
with open(f, 'r') as fp:
contents = fp.read()
except TypeError:
raise ValueError('val must be file or path, but was type <%s>' % type(f).__name__)
except OSError:
if not isinstance(f, str_types):
raise ValueError('val must be file or path, but was type <%s>' % type(f).__name__)
raise
if sys.version_info[0] == 3 and type(contents) is bytes:
# in PY3 force decoding of bytes to target encoding
return contents.decode(encoding, 'replace')
elif sys.version_info[0] == 2 and encoding == 'ascii':
# in PY2 force encoding back to ascii
return contents.encode('ascii', 'replace')
else:
# in all other cases, try to decode to target encoding
try:
return contents.decode(encoding, 'replace')
except AttributeError:
pass
# if all else fails, just return the contents "as is"
return contents
def fail(msg=''):
"""Force test failure with the given message."""
raise AssertionError('Fail: %s!' % msg if msg else 'Fail!')
def soft_fail(msg=''):
"""Adds error message to soft errors list if within soft assertions context.
Either just force test failure with the given message."""
global _soft_ctx
if _soft_ctx:
global _soft_err
_soft_err.append('Fail: %s!' % msg if msg else 'Fail!')
return
fail(msg)
class AssertionBuilder(object):
"""Assertion builder."""
def __init__(self, val, description='', kind=None, expected=None):
"""Construct the assertion builder."""
self.val = val
self.description = description
self.kind = kind
self.expected = expected
def described_as(self, description):
"""Describes the assertion. On failure, the description is included in the error message."""
self.description = str(description)
return self
def is_equal_to(self, other, **kwargs):
"""Asserts that val is equal to other."""
if self._check_dict_like(self.val, check_values=False, return_as_bool=True) and \
self._check_dict_like(other, check_values=False, return_as_bool=True):
if self._dict_not_equal(self.val, other, ignore=kwargs.get('ignore'), include=kwargs.get('include')):
self._dict_err(self.val, other, ignore=kwargs.get('ignore'), include=kwargs.get('include'))
else:
if self.val != other:
self._err('Expected <%s> to be equal to <%s>, but was not.' % (self.val, other))
return self
def is_not_equal_to(self, other):
"""Asserts that val is not equal to other."""
if self.val == other:
self._err('Expected <%s> to be not equal to <%s>, but was.' % (self.val, other))
return self
def is_same_as(self, other):
"""Asserts that the val is identical to other, via 'is' compare."""
if self.val is not other:
self._err('Expected <%s> to be identical to <%s>, but was not.' % (self.val, other))
return self
def is_not_same_as(self, other):
"""Asserts that the val is not identical to other, via 'is' compare."""
if self.val is other:
self._err('Expected <%s> to be not identical to <%s>, but was.' % (self.val, other))
return self
def is_true(self):
"""Asserts that val is true."""
if not self.val:
self._err('Expected <True>, but was not.')
return self
def is_false(self):
"""Asserts that val is false."""
if self.val:
self._err('Expected <False>, but was not.')
return self
def is_none(self):
"""Asserts that val is none."""
if self.val is not None:
self._err('Expected <%s> to be <None>, but was not.' % self.val)
return self
def is_not_none(self):
"""Asserts that val is not none."""
if self.val is None:
self._err('Expected not <None>, but was.')
return self
def is_type_of(self, some_type):
"""Asserts that val is of the given type."""
if type(some_type) is not type and\
not issubclass(type(some_type), type):
raise TypeError('given arg must be a type')
if type(self.val) is not some_type:
if hasattr(self.val, '__name__'):
t = self.val.__name__
elif hasattr(self.val, '__class__'):
t = self.val.__class__.__name__
else:
t = 'unknown'
self._err('Expected <%s:%s> to be of type <%s>, but was not.' % (self.val, t, some_type.__name__))
return self
def is_instance_of(self, some_class):
"""Asserts that val is an instance of the given class."""
try:
if not isinstance(self.val, some_class):
if hasattr(self.val, '__name__'):
t = self.val.__name__
elif hasattr(self.val, '__class__'):
t = self.val.__class__.__name__
else:
t = 'unknown'
self._err('Expected <%s:%s> to be instance of class <%s>, but was not.' % (self.val, t, some_class.__name__))
except TypeError:
raise TypeError('given arg must be a class')
return self
def is_length(self, length):
"""Asserts that val is the given length."""
if type(length) is not int:
raise TypeError('given arg must be an int')
if length < 0:
raise ValueError('given arg must be a positive int')
if len(self.val) != length:
self._err('Expected <%s> to be of length <%d>, but was <%d>.' % (self.val, length, len(self.val)))
return self
def contains(self, *items):
"""Asserts that val contains the given item or items."""
if len(items) == 0:
raise ValueError('one or more args must be given')
elif len(items) == 1:
if items[0] not in self.val:
if self._check_dict_like(self.val, return_as_bool=True):
self._err('Expected <%s> to contain key <%s>, but did not.' % (self.val, items[0]))
else:
self._err('Expected <%s> to contain item <%s>, but did not.' % (self.val, items[0]))
else:
missing = []
for i in items:
if i not in self.val:
missing.append(i)
if missing:
if self._check_dict_like(self.val, return_as_bool=True):
self._err('Expected <%s> to contain keys %s, but did not contain key%s %s.' % (self.val, self._fmt_items(items), '' if len(missing) == 0 else 's', self._fmt_items(missing)))
else:
self._err('Expected <%s> to contain items %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing)))
return self
def does_not_contain(self, *items):
"""Asserts that val does not contain the given item or items."""
if len(items) == 0:
raise ValueError('one or more args must be given')
elif len(items) == 1:
if items[0] in self.val:
self._err('Expected <%s> to not contain item <%s>, but did.' % (self.val, items[0]))
else:
found = []
for i in items:
if i in self.val:
found.append(i)
if found:
self._err('Expected <%s> to not contain items %s, but did contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(found)))
return self
def contains_only(self, *items):
"""Asserts that val contains only the given item or items."""
if len(items) == 0:
raise ValueError('one or more args must be given')
else:
extra = []
for i in self.val:
if i not in items:
extra.append(i)
if extra:
self._err('Expected <%s> to contain only %s, but did contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(extra)))
missing = []
for i in items:
if i not in self.val:
missing.append(i)
if missing:
self._err('Expected <%s> to contain only %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing)))
return self
def contains_sequence(self, *items):
"""Asserts that val contains the given sequence of items in order."""
if len(items) == 0:
raise ValueError('one or more args must be given')
else:
try:
for i in xrange(len(self.val) - len(items) + 1):
for j in xrange(len(items)):
if self.val[i+j] != items[j]:
break
else:
return self
except TypeError:
raise TypeError('val is not iterable')
self._err('Expected <%s> to contain sequence %s, but did not.' % (self.val, self._fmt_items(items)))
def contains_duplicates(self):
"""Asserts that val is iterable and contains duplicate items."""
try:
if len(self.val) != len(set(self.val)):
return self
except TypeError:
raise TypeError('val is not iterable')
self._err('Expected <%s> to contain duplicates, but did not.' % self.val)
def does_not_contain_duplicates(self):
"""Asserts that val is iterable and does not contain any duplicate items."""
try:
if len(self.val) == len(set(self.val)):
return self
except TypeError:
raise TypeError('val is not iterable')
self._err('Expected <%s> to not contain duplicates, but did.' % self.val)
def is_empty(self):
"""Asserts that val is empty."""
if len(self.val) != 0:
if isinstance(self.val, str_types):
self._err('Expected <%s> to be empty string, but was not.' % self.val)
else:
self._err('Expected <%s> to be empty, but was not.' % self.val)
return self
def is_not_empty(self):
"""Asserts that val is not empty."""
if len(self.val) == 0:
if isinstance(self.val, str_types):
self._err('Expected not empty string, but was empty.')
else:
self._err('Expected not empty, but was empty.')
return self
def is_in(self, *items):
"""Asserts that val is equal to one of the given items."""
if len(items) == 0:
raise ValueError('one or more args must be given')
else:
for i in items:
if self.val == i:
return self
self._err('Expected <%s> to be in %s, but was not.' % (self.val, self._fmt_items(items)))
def is_not_in(self, *items):
"""Asserts that val is not equal to one of the given items."""
if len(items) == 0:
raise ValueError('one or more args must be given')
else:
for i in items:
if self.val == i:
self._err('Expected <%s> to not be in %s, but was.' % (self.val, self._fmt_items(items)))
return self
### numeric assertions ###
COMPAREABLE_TYPES = set([datetime.datetime, datetime.timedelta, datetime.date, datetime.time])
NON_COMPAREABLE_TYPES = set([complex])
def _validate_compareable(self, other):
self_type = type(self.val)
other_type = type(other)
if self_type in self.NON_COMPAREABLE_TYPES:
raise TypeError('ordering is not defined for type <%s>' % self_type.__name__)
if self_type in self.COMPAREABLE_TYPES:
if other_type is not self_type:
raise TypeError('given arg must be <%s>, but was <%s>' % (self_type.__name__, other_type.__name__))
return
if isinstance(self.val, numbers.Number):
if not isinstance(other, numbers.Number):
raise TypeError('given arg must be a number, but was <%s>' % other_type.__name__)
return
raise TypeError('ordering is not defined for type <%s>' % self_type.__name__)
def _validate_number(self):
"""Raise TypeError if val is not numeric."""
if isinstance(self.val, numbers.Number) is False:
raise TypeError('val is not numeric')
def _validate_real(self):
"""Raise TypeError if val is not real number."""
if isinstance(self.val, numbers.Real) is False:
raise TypeError('val is not real number')
def is_zero(self):
"""Asserts that val is numeric and equal to zero."""
self._validate_number()
return self.is_equal_to(0)
def is_not_zero(self):
"""Asserts that val is numeric and not equal to zero."""
self._validate_number()
return self.is_not_equal_to(0)
def is_nan(self):
"""Asserts that val is real number and NaN (not a number)."""
self._validate_number()
self._validate_real()
if not math.isnan(self.val):
self._err('Expected <%s> to be <NaN>, but was not.' % self.val)
return self
def is_not_nan(self):
"""Asserts that val is real number and not NaN (not a number)."""
self._validate_number()
self._validate_real()
if math.isnan(self.val):
self._err('Expected not <NaN>, but was.')
return self
def is_inf(self):
"""Asserts that val is real number and Inf (infinity)."""
self._validate_number()
self._validate_real()
if not math.isinf(self.val):
self._err('Expected <%s> to be <Inf>, but was not.' % self.val)
return self
def is_not_inf(self):
"""Asserts that val is real number and not Inf (infinity)."""
self._validate_number()
self._validate_real()
if math.isinf(self.val):
self._err('Expected not <Inf>, but was.')
return self
def is_greater_than(self, other):
"""Asserts that val is numeric and is greater than other."""
self._validate_compareable(other)
if self.val <= other:
if type(self.val) is datetime.datetime:
self._err('Expected <%s> to be greater than <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S')))
else:
self._err('Expected <%s> to be greater than <%s>, but was not.' % (self.val, other))
return self
def is_greater_than_or_equal_to(self, other):
"""Asserts that val is numeric and is greater than or equal to other."""
self._validate_compareable(other)
if self.val < other:
if type(self.val) is datetime.datetime:
self._err('Expected <%s> to be greater than or equal to <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S')))
else:
self._err('Expected <%s> to be greater than or equal to <%s>, but was not.' % (self.val, other))
return self
def is_less_than(self, other):
"""Asserts that val is numeric and is less than other."""
self._validate_compareable(other)
if self.val >= other:
if type(self.val) is datetime.datetime:
self._err('Expected <%s> to be less than <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S')))
else:
self._err('Expected <%s> to be less than <%s>, but was not.' % (self.val, other))
return self
def is_less_than_or_equal_to(self, other):
"""Asserts that val is numeric and is less than or equal to other."""
self._validate_compareable(other)
if self.val > other:
if type(self.val) is datetime.datetime:
self._err('Expected <%s> to be less than or equal to <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S')))
else:
self._err('Expected <%s> to be less than or equal to <%s>, but was not.' % (self.val, other))
return self
def is_positive(self):
"""Asserts that val is numeric and greater than zero."""
return self.is_greater_than(0)
def is_negative(self):
"""Asserts that val is numeric and less than zero."""
return self.is_less_than(0)
def is_between(self, low, high):
"""Asserts that val is numeric and is between low and high."""
val_type = type(self.val)
self._validate_between_args(val_type, low, high)
if self.val < low or self.val > high:
if val_type is datetime.datetime:
self._err('Expected <%s> to be between <%s> and <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), low.strftime('%Y-%m-%d %H:%M:%S'), high.strftime('%Y-%m-%d %H:%M:%S')))
else:
self._err('Expected <%s> to be between <%s> and <%s>, but was not.' % (self.val, low, high))
return self
def is_not_between(self, low, high):
"""Asserts that val is numeric and is between low and high."""
val_type = type(self.val)
self._validate_between_args(val_type, low, high)
if self.val >= low and self.val <= high:
if val_type is datetime.datetime:
self._err('Expected <%s> to not be between <%s> and <%s>, but was.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), low.strftime('%Y-%m-%d %H:%M:%S'), high.strftime('%Y-%m-%d %H:%M:%S')))
else:
self._err('Expected <%s> to not be between <%s> and <%s>, but was.' % (self.val, low, high))
return self
def is_close_to(self, other, tolerance):
"""Asserts that val is numeric and is close to other within tolerance."""
self._validate_close_to_args(self.val, other, tolerance)
if self.val < (other-tolerance) or self.val > (other+tolerance):
if type(self.val) is datetime.datetime:
tolerance_seconds = tolerance.days * 86400 + tolerance.seconds + tolerance.microseconds / 1000000
h, rem = divmod(tolerance_seconds, 3600)
m, s = divmod(rem, 60)
self._err('Expected <%s> to be close to <%s> within tolerance <%d:%02d:%02d>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'), h, m, s))
else:
self._err('Expected <%s> to be close to <%s> within tolerance <%s>, but was not.' % (self.val, other, tolerance))
return self
def is_not_close_to(self, other, tolerance):
"""Asserts that val is numeric and is not close to other within tolerance."""
self._validate_close_to_args(self.val, other, tolerance)
if self.val >= (other-tolerance) and self.val <= (other+tolerance):
if type(self.val) is datetime.datetime:
tolerance_seconds = tolerance.days * 86400 + tolerance.seconds + tolerance.microseconds / 1000000
h, rem = divmod(tolerance_seconds, 3600)
m, s = divmod(rem, 60)
self._err('Expected <%s> to not be close to <%s> within tolerance <%d:%02d:%02d>, but was.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S'), h, m, s))
else:
self._err('Expected <%s> to not be close to <%s> within tolerance <%s>, but was.' % (self.val, other, tolerance))
return self
### string assertions ###
def is_equal_to_ignoring_case(self, other):
"""Asserts that val is case-insensitive equal to other."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a string')
if not isinstance(other, str_types):
raise TypeError('given arg must be a string')
if self.val.lower() != other.lower():
self._err('Expected <%s> to be case-insensitive equal to <%s>, but was not.' % (self.val, other))
return self
def contains_ignoring_case(self, *items):
"""Asserts that val is string and contains the given item or items."""
if len(items) == 0:
raise ValueError('one or more args must be given')
if isinstance(self.val, str_types):
if len(items) == 1:
if not isinstance(items[0], str_types):
raise TypeError('given arg must be a string')
if items[0].lower() not in self.val.lower():
self._err('Expected <%s> to case-insensitive contain item <%s>, but did not.' % (self.val, items[0]))
else:
missing = []
for i in items:
if not isinstance(i, str_types):
raise TypeError('given args must all be strings')
if i.lower() not in self.val.lower():
missing.append(i)
if missing:
self._err('Expected <%s> to case-insensitive contain items %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing)))
elif isinstance(self.val, Iterable):
missing = []
for i in items:
if not isinstance(i, str_types):
raise TypeError('given args must all be strings')
found = False
for v in self.val:
if not isinstance(v, str_types):
raise TypeError('val items must all be strings')
if i.lower() == v.lower():
found = True
break
if not found:
missing.append(i)
if missing:
self._err('Expected <%s> to case-insensitive contain items %s, but did not contain %s.' % (self.val, self._fmt_items(items), self._fmt_items(missing)))
else:
raise TypeError('val is not a string or iterable')
return self
def starts_with(self, prefix):
"""Asserts that val is string or iterable and starts with prefix."""
if prefix is None:
raise TypeError('given prefix arg must not be none')
if isinstance(self.val, str_types):
if not isinstance(prefix, str_types):
raise TypeError('given prefix arg must be a string')
if len(prefix) == 0:
raise ValueError('given prefix arg must not be empty')
if not self.val.startswith(prefix):
self._err('Expected <%s> to start with <%s>, but did not.' % (self.val, prefix))
elif isinstance(self.val, Iterable):
if len(self.val) == 0:
raise ValueError('val must not be empty')
first = next(iter(self.val))
if first != prefix:
self._err('Expected %s to start with <%s>, but did not.' % (self.val, prefix))
else:
raise TypeError('val is not a string or iterable')
return self
def ends_with(self, suffix):
"""Asserts that val is string or iterable and ends with suffix."""
if suffix is None:
raise TypeError('given suffix arg must not be none')
if isinstance(self.val, str_types):
if not isinstance(suffix, str_types):
raise TypeError('given suffix arg must be a string')
if len(suffix) == 0:
raise ValueError('given suffix arg must not be empty')
if not self.val.endswith(suffix):
self._err('Expected <%s> to end with <%s>, but did not.' % (self.val, suffix))
elif isinstance(self.val, Iterable):
if len(self.val) == 0:
raise ValueError('val must not be empty')
last = None
for last in self.val:
pass
if last != suffix:
self._err('Expected %s to end with <%s>, but did not.' % (self.val, suffix))
else:
raise TypeError('val is not a string or iterable')
return self
def matches(self, pattern):
"""Asserts that val is string and matches regex pattern."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a string')
if not isinstance(pattern, str_types):
raise TypeError('given pattern arg must be a string')
if len(pattern) == 0:
raise ValueError('given pattern arg must not be empty')
if re.search(pattern, self.val) is None:
self._err('Expected <%s> to match pattern <%s>, but did not.' % (self.val, pattern))
return self
def does_not_match(self, pattern):
"""Asserts that val is string and does not match regex pattern."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a string')
if not isinstance(pattern, str_types):
raise TypeError('given pattern arg must be a string')
if len(pattern) == 0:
raise ValueError('given pattern arg must not be empty')
if re.search(pattern, self.val) is not None:
self._err('Expected <%s> to not match pattern <%s>, but did.' % (self.val, pattern))
return self
def is_alpha(self):
"""Asserts that val is non-empty string and all characters are alphabetic."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a string')
if len(self.val) == 0:
raise ValueError('val is empty')
if not self.val.isalpha():
self._err('Expected <%s> to contain only alphabetic chars, but did not.' % self.val)
return self
def is_digit(self):
"""Asserts that val is non-empty string and all characters are digits."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a string')
if len(self.val) == 0:
raise ValueError('val is empty')
if not self.val.isdigit():
self._err('Expected <%s> to contain only digits, but did not.' % self.val)
return self
def is_lower(self):
"""Asserts that val is non-empty string and all characters are lowercase."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a string')
if len(self.val) == 0:
raise ValueError('val is empty')
if self.val != self.val.lower():
self._err('Expected <%s> to contain only lowercase chars, but did not.' % self.val)
return self
def is_upper(self):
"""Asserts that val is non-empty string and all characters are uppercase."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a string')
if len(self.val) == 0:
raise ValueError('val is empty')
if self.val != self.val.upper():
self._err('Expected <%s> to contain only uppercase chars, but did not.' % self.val)
return self
def is_unicode(self):
"""Asserts that val is a unicode string."""
if type(self.val) is not unicode:
self._err('Expected <%s> to be unicode, but was <%s>.' % (self.val, type(self.val).__name__))
return self
### collection assertions ###
def is_iterable(self):
"""Asserts that val is iterable collection."""
if not isinstance(self.val, Iterable):
self._err('Expected iterable, but was not.')
return self
def is_not_iterable(self):
"""Asserts that val is not iterable collection."""
if isinstance(self.val, Iterable):
self._err('Expected not iterable, but was.')
return self
def is_subset_of(self, *supersets):
"""Asserts that val is iterable and a subset of the given superset or flattened superset if multiple supersets are given."""
if not isinstance(self.val, Iterable):
raise TypeError('val is not iterable')
if len(supersets) == 0:
raise ValueError('one or more superset args must be given')
missing = []
if hasattr(self.val, 'keys') and callable(getattr(self.val, 'keys')) and hasattr(self.val, '__getitem__'):
# flatten superset dicts
superdict = {}
for l,j in enumerate(supersets):
self._check_dict_like(j, check_values=False, name='arg #%d' % (l+1))
for k in j.keys():
superdict.update({k: j[k]})
for i in self.val.keys():
if i not in superdict:
missing.append({i: self.val[i]}) # bad key
elif self.val[i] != superdict[i]:
missing.append({i: self.val[i]}) # bad val
if missing:
self._err('Expected <%s> to be subset of %s, but %s %s missing.' % (self.val, self._fmt_items(superdict), self._fmt_items(missing), 'was' if len(missing) == 1 else 'were'))
else:
# flatten supersets
superset = set()
for j in supersets:
try:
for k in j:
superset.add(k)
except Exception:
superset.add(j)
for i in self.val:
if i not in superset:
missing.append(i)
if missing:
self._err('Expected <%s> to be subset of %s, but %s %s missing.' % (self.val, self._fmt_items(superset), self._fmt_items(missing), 'was' if len(missing) == 1 else 'were'))
return self
### dict assertions ###
def contains_key(self, *keys):
"""Asserts the val is a dict and contains the given key or keys. Alias for contains()."""
self._check_dict_like(self.val, check_values=False, check_getitem=False)
return self.contains(*keys)
def does_not_contain_key(self, *keys):
"""Asserts the val is a dict and does not contain the given key or keys. Alias for does_not_contain()."""
self._check_dict_like(self.val, check_values=False, check_getitem=False)
return self.does_not_contain(*keys)
def contains_value(self, *values):
"""Asserts that val is a dict and contains the given value or values."""
self._check_dict_like(self.val, check_getitem=False)
if len(values) == 0:
raise ValueError('one or more value args must be given')
missing = []
for v in values:
if v not in self.val.values():
missing.append(v)
if missing:
self._err('Expected <%s> to contain values %s, but did not contain %s.' % (self.val, self._fmt_items(values), self._fmt_items(missing)))
return self
def does_not_contain_value(self, *values):
"""Asserts that val is a dict and does not contain the given value or values."""
self._check_dict_like(self.val, check_getitem=False)
if len(values) == 0:
raise ValueError('one or more value args must be given')
else:
found = []
for v in values:
if v in self.val.values():
found.append(v)
if found:
self._err('Expected <%s> to not contain values %s, but did contain %s.' % (self.val, self._fmt_items(values), self._fmt_items(found)))
return self
def contains_entry(self, *args, **kwargs):
"""Asserts that val is a dict and contains the given entry or entries."""
self._check_dict_like(self.val, check_values=False)
entries = list(args) + [{k:v} for k,v in kwargs.items()]
if len(entries) == 0:
raise ValueError('one or more entry args must be given')
missing = []
for e in entries:
if type(e) is not dict:
raise TypeError('given entry arg must be a dict')
if len(e) != 1:
raise ValueError('given entry args must contain exactly one key-value pair')
k = next(iter(e))
if k not in self.val:
missing.append(e) # bad key
elif self.val[k] != e[k]:
missing.append(e) # bad val
if missing:
self._err('Expected <%s> to contain entries %s, but did not contain %s.' % (self.val, self._fmt_items(entries), self._fmt_items(missing)))
return self
def does_not_contain_entry(self, *args, **kwargs):
"""Asserts that val is a dict and does not contain the given entry or entries."""
self._check_dict_like(self.val, check_values=False)
entries = list(args) + [{k:v} for k,v in kwargs.items()]
if len(entries) == 0:
raise ValueError('one or more entry args must be given')
found = []
for e in entries:
if type(e) is not dict:
raise TypeError('given entry arg must be a dict')
if len(e) != 1:
raise ValueError('given entry args must contain exactly one key-value pair')
k = next(iter(e))
if k in self.val and e[k] == self.val[k]:
found.append(e)
if found:
self._err('Expected <%s> to not contain entries %s, but did contain %s.' % (self.val, self._fmt_items(entries), self._fmt_items(found)))
return self
### datetime assertions ###
def is_before(self, other):
"""Asserts that val is a date and is before other date."""
if type(self.val) is not datetime.datetime:
raise TypeError('val must be datetime, but was type <%s>' % type(self.val).__name__)
if type(other) is not datetime.datetime:
raise TypeError('given arg must be datetime, but was type <%s>' % type(other).__name__)
if self.val >= other:
self._err('Expected <%s> to be before <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S')))
return self
def is_after(self, other):
"""Asserts that val is a date and is after other date."""
if type(self.val) is not datetime.datetime:
raise TypeError('val must be datetime, but was type <%s>' % type(self.val).__name__)
if type(other) is not datetime.datetime:
raise TypeError('given arg must be datetime, but was type <%s>' % type(other).__name__)
if self.val <= other:
self._err('Expected <%s> to be after <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S')))
return self
def is_equal_to_ignoring_milliseconds(self, other):
if type(self.val) is not datetime.datetime:
raise TypeError('val must be datetime, but was type <%s>' % type(self.val).__name__)
if type(other) is not datetime.datetime:
raise TypeError('given arg must be datetime, but was type <%s>' % type(other).__name__)
if self.val.date() != other.date() or self.val.hour != other.hour or self.val.minute != other.minute or self.val.second != other.second:
self._err('Expected <%s> to be equal to <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M:%S'), other.strftime('%Y-%m-%d %H:%M:%S')))
return self
def is_equal_to_ignoring_seconds(self, other):
if type(self.val) is not datetime.datetime:
raise TypeError('val must be datetime, but was type <%s>' % type(self.val).__name__)
if type(other) is not datetime.datetime:
raise TypeError('given arg must be datetime, but was type <%s>' % type(other).__name__)
if self.val.date() != other.date() or self.val.hour != other.hour or self.val.minute != other.minute:
self._err('Expected <%s> to be equal to <%s>, but was not.' % (self.val.strftime('%Y-%m-%d %H:%M'), other.strftime('%Y-%m-%d %H:%M')))
return self
def is_equal_to_ignoring_time(self, other):
if type(self.val) is not datetime.datetime:
raise TypeError('val must be datetime, but was type <%s>' % type(self.val).__name__)
if type(other) is not datetime.datetime:
raise TypeError('given arg must be datetime, but was type <%s>' % type(other).__name__)
if self.val.date() != other.date():
self._err('Expected <%s> to be equal to <%s>, but was not.' % (self.val.strftime('%Y-%m-%d'), other.strftime('%Y-%m-%d')))
return self
### file assertions ###
def exists(self):
"""Asserts that val is a path and that it exists."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a path')
if not os.path.exists(self.val):
self._err('Expected <%s> to exist, but was not found.' % self.val)
return self
def does_not_exist(self):
"""Asserts that val is a path and that it does not exist."""
if not isinstance(self.val, str_types):
raise TypeError('val is not a path')
if os.path.exists(self.val):
self._err('Expected <%s> to not exist, but was found.' % self.val)
return self
def is_file(self):
"""Asserts that val is an existing path to a file."""
self.exists()
if not os.path.isfile(self.val):
self._err('Expected <%s> to be a file, but was not.' % self.val)
return self
def is_directory(self):
"""Asserts that val is an existing path to a directory."""
self.exists()
if not os.path.isdir(self.val):
self._err('Expected <%s> to be a directory, but was not.' % self.val)
return self
def is_named(self, filename):
"""Asserts that val is an existing path to a file and that file is named filename."""
self.is_file()
if not isinstance(filename, str_types):
raise TypeError('given filename arg must be a path')
val_filename = os.path.basename(os.path.abspath(self.val))
if val_filename != filename:
self._err('Expected filename <%s> to be equal to <%s>, but was not.' % (val_filename, filename))
return self
def is_child_of(self, parent):
"""Asserts that val is an existing path to a file and that file is a child of parent."""
self.is_file()
if not isinstance(parent, str_types):
raise TypeError('given parent directory arg must be a path')
val_abspath = os.path.abspath(self.val)
parent_abspath = os.path.abspath(parent)
if not val_abspath.startswith(parent_abspath):
self._err('Expected file <%s> to be a child of <%s>, but was not.' % (val_abspath, parent_abspath))
return self
### collection of objects assertions ###
def extracting(self, *names, **kwargs):
"""Asserts that val is collection, then extracts the named properties or named zero-arg methods into a list (or list of tuples if multiple names are given)."""
if not isinstance(self.val, Iterable):
raise TypeError('val is not iterable')
if isinstance(self.val, str_types):
raise TypeError('val must not be string')
if len(names) == 0:
raise ValueError('one or more name args must be given')
def _extract(x, name):
if self._check_dict_like(x, check_values=False, return_as_bool=True):
if name in x:
return x[name]
else:
raise ValueError('item keys %s did not contain key <%s>' % (list(x.keys()), name))
elif isinstance(x, Iterable):
self._check_iterable(x, name='item')
return x[name]
elif hasattr(x, name):
attr = getattr(x, name)
if callable(attr):
try:
return attr()
except TypeError:
raise ValueError('val method <%s()> exists, but is not zero-arg method' % name)
else:
return attr
else:
raise ValueError('val does not have property or zero-arg method <%s>' % name)
def _filter(x):
if 'filter' in kwargs:
if isinstance(kwargs['filter'], str_types):
return bool(_extract(x, kwargs['filter']))
elif self._check_dict_like(kwargs['filter'], check_values=False, return_as_bool=True):
for k in kwargs['filter']:
if isinstance(k, str_types):
if _extract(x, k) != kwargs['filter'][k]:
return False
return True
elif callable(kwargs['filter']):
return kwargs['filter'](x)
return False
return True