-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_asserts.py
1540 lines (1250 loc) · 56.2 KB
/
test_asserts.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
# -*- coding: utf-8 -*-
import re
import sys
from collections import OrderedDict
from datetime import datetime, timedelta, timezone
from json import JSONDecodeError
from unittest import TestCase
from warnings import catch_warnings, simplefilter, warn
from asserts import (
Absent,
Exists,
Present,
assert_almost_equal,
assert_between,
assert_boolean_false,
assert_boolean_true,
assert_count_equal,
assert_datetime_about_now,
assert_datetime_about_now_utc,
assert_dict_equal,
assert_dict_superset,
assert_equal,
assert_false,
assert_greater,
assert_greater_equal,
assert_has_attr,
assert_in,
assert_is,
assert_is_instance,
assert_is_none,
assert_is_not,
assert_is_not_none,
assert_json_subset,
assert_less,
assert_less_equal,
assert_not_almost_equal,
assert_not_equal,
assert_not_in,
assert_not_is_instance,
assert_not_regex,
assert_raises,
assert_raises_errno,
assert_raises_regex,
assert_regex,
assert_succeeds,
assert_true,
assert_warns,
assert_warns_regex,
fail,
)
class Box:
def __init__(self, initial_value):
self.value = initial_value
class _DummyObject(object):
def __init__(self, value="x"):
self.value = value
def __repr__(self):
return "<Dummy>"
def _assert_raises_assertion(expected_message):
"""Fail if the context does not raise an AssertionError or the exception
message does not match.
This is used to test assertions, without using those assertions.
"""
class Context(object):
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
raise AssertionError("no AssertionError raised")
if not issubclass(exc_type, AssertionError):
return False
if str(exc_val) != expected_message:
raise AssertionError(
"expected exception message {!r}, got {!r}".format(
expected_message, str(exc_val)
)
)
return True
return Context()
class AssertTest(TestCase):
_type_string = "type" if sys.version_info[0] < 3 else "class"
# fail()
def test_fail__default_message(self):
with _assert_raises_assertion("assertion failure"):
fail()
def test_fail__with_message(self):
with _assert_raises_assertion("test message"):
fail("test message")
# assert_true()
def test_assert_true__truthy_value(self):
assert_true("Hello World!")
def test_assert_true__falsy_value__default_message(self):
with _assert_raises_assertion("'' is not truthy"):
assert_true("")
def test_assert_true__falsy_value__custom_message(self):
with _assert_raises_assertion("0 is not truthy;0"):
assert_true(0, "{msg};{expr}")
# assert_false()
def test_assert_false__falsy_value(self):
assert_false("")
def test_assert_false__truthy_value__default_message(self):
with _assert_raises_assertion("25 is not falsy"):
assert_false(25)
def test_assert_false__truthy_value__custom_message(self):
with _assert_raises_assertion("'foo' is not falsy;foo"):
assert_false("foo", "{msg};{expr}")
# assert_boolean_true()
def test_assert_boolean_true__true(self):
assert_boolean_true(True)
def test_assert_boolean_true__false__custom_message(self):
with _assert_raises_assertion("'Foo' is not True;Foo"):
assert_boolean_true("Foo", "{msg};{expr}")
def test_assert_boolean_true__truthy__default_message(self):
with _assert_raises_assertion("1 is not True"):
assert_boolean_true(1)
# assert_boolean_false()
def test_assert_boolean_false__false(self):
assert_boolean_false(False)
def test_assert_boolean_false__true__default_message(self):
with _assert_raises_assertion("'foo' is not False"):
assert_boolean_false("foo")
def test_assert_boolean_false__falsy__custom_message(self):
with _assert_raises_assertion("0 is not False;0"):
assert_boolean_false(0, "{msg};{expr}")
# assert_is_none()
def test_assert_is_none__none(self):
assert_is_none(None)
def test_assert_is_none__string__default_message(self):
with _assert_raises_assertion("'' is not None"):
assert_is_none("")
def test_assert_is_none__int__custom_message(self):
with _assert_raises_assertion("55 is not None;55"):
assert_is_none(55, "{msg};{expr}")
# assert_is_not_none()
def test_assert_is_not_none__string(self):
assert_is_not_none("")
def test_assert_is_not_none__none__default_message(self):
with _assert_raises_assertion("expression is None"):
assert_is_not_none(None)
def test_assert_is_not_none__none__custom_message(self):
with _assert_raises_assertion("expression is None;None"):
assert_is_not_none(None, "{msg};{expr!r}")
# assert_equal()
def test_assert_equal__equal_strings(self):
assert_equal("foo", "foo")
def test_assert_equal__equal_objects(self):
class MyClass(object):
def __eq__(self, other):
return True
assert_equal(MyClass(), MyClass())
def test_assert_equal__not_equal__default_message(self):
with _assert_raises_assertion("'string' != 55"):
assert_equal("string", 55)
def test_assert_equal__not_equal__custom_message(self):
with _assert_raises_assertion("'string' != 55;'string';55"):
assert_equal("string", 55, "{msg};{first!r};{second!r}")
def test_assert_equal__dict(self):
with _assert_raises_assertion("key 'foo' missing from right dict"):
assert_equal({"foo": 5}, {})
# assert_not_equal()
def test_assert_not_equal__not_equal(self):
assert_not_equal("abc", "def")
def test_assert_not_equal__equal__default_message(self):
with _assert_raises_assertion("'abc' == 'abc'"):
assert_not_equal("abc", "abc")
def test_assert_not_equal__equal__custom_message(self):
with _assert_raises_assertion("1.0 == 1;1.0;1"):
assert_not_equal(1.0, 1, "{msg};{first};{second}")
# assert_almost_equal()
def test_assert_almost_equal__same(self):
assert_almost_equal(5, 5)
def test_assert_almost_equal__similar__defaults(self):
assert_almost_equal(5, 5.00000001)
def test_assert_almost_equal__similar__places(self):
assert_almost_equal(5, 5.0001, places=3)
def test_assert_almost_equal__similar__delta(self):
assert_almost_equal(5, 5.001, delta=0.1)
def test_assert_almost_equal__similar__delta_reverse(self):
assert_almost_equal(5, 5.001, delta=0.1)
def test_assert_almost_equal__not_similar__default_message(self):
with _assert_raises_assertion("5 != 5.0001 within 7 places"):
assert_almost_equal(5, 5.0001)
def test_assert_almost_equal__not_similar__places__default_message(self):
with _assert_raises_assertion("5 != 6 within 3 places"):
assert_almost_equal(5, 6, places=3)
def test_assert_almost_equal__not_similar__delta__default_message(self):
with _assert_raises_assertion("5 != 6 with delta=0.1"):
assert_almost_equal(5, 6, delta=0.1)
def test_assert_almost_equal__not_similar__delta_reverse(self):
with _assert_raises_assertion("6 != 5 with delta=0.3"):
assert_almost_equal(6, 5, delta=0.3)
def test_assert_almost_equal__not_similar__custom_message(self):
with _assert_raises_assertion("5 != -5 within 7 places;5;-5;7;None"):
assert_almost_equal(
5, -5, msg_fmt="{msg};{first};{second};{places};{delta!r}"
)
def test_assert_almost_equal__not_similar__places__custom_message(self):
with _assert_raises_assertion("5 != -5 within 3 places;5;-5;3;None"):
assert_almost_equal(
5,
-5,
places=3,
msg_fmt="{msg};{first};{second};{places};{delta!r}",
)
def test_assert_almost_equal__not_similar__delta__custom_message(self):
with _assert_raises_assertion("5 != 6 with delta=0.1;5;6;None;0.1"):
assert_almost_equal(
5,
6,
delta=0.1,
msg_fmt="{msg};{first};{second};{places!r};{delta}",
)
def test_assert_almost_equal__wrong_types(self):
try:
assert_almost_equal("5", "5") # type: ignore[arg-type]
except TypeError:
pass
else:
raise AssertionError("TypeError not raised")
def test_assert_almost_equal__places_and_delta(self):
try:
assert_almost_equal(5, 5, places=3, delta=0.0003)
except TypeError:
pass
else:
raise AssertionError("TypeError not raised")
def test_assert_almost_equal__delta_eq_0(self):
try:
assert_almost_equal(5, 5, delta=0)
except ValueError:
pass
else:
raise AssertionError("ValueError not raised")
def test_assert_almost_equal__delta_lt_0(self):
try:
assert_almost_equal(5, 5, delta=-1)
except ValueError:
pass
else:
raise AssertionError("ValueError not raised")
# assert_not_almost_equal()
def test_assert_not_almost_equal__same(self):
with _assert_raises_assertion("5 == 5 within 7 places"):
assert_not_almost_equal(5, 5)
def test_assert_not_almost_equal__similar__defaults(self):
with _assert_raises_assertion("5 == 5.00000001 within 7 places"):
assert_not_almost_equal(5, 5.00000001)
def test_assert_not_almost_equal__similar__places(self):
with _assert_raises_assertion("5 == 5.0001 within 3 places"):
assert_not_almost_equal(5, 5.0001, places=3)
def test_assert_not_almost_equal__similar__delta(self):
with _assert_raises_assertion("5 == 5.1 with delta=0.1"):
assert_not_almost_equal(5, 5.1, delta=0.1)
def test_assert_not_almost_equal__similar__delta_reverse(self):
with _assert_raises_assertion("5 != 6 with delta=0.3"):
assert_almost_equal(5, 6, delta=0.3)
def test_assert_not_almost_equal__not_similar(self):
assert_not_almost_equal(5, 5.0001)
def test_assert_not_almost_equal__not_similar__delta(self):
assert_not_almost_equal(5, 5.1, delta=0.05)
def test_assert_not_almost_equal__not_similar__delta_reverse(self):
assert_not_almost_equal(5.1, 5, delta=0.05)
def test_assert_not_almost_equal__similar__custom_message(self):
with _assert_raises_assertion(
"5 == 5.00000001 within 7 places;5;5.00000001;7;None"
):
assert_not_almost_equal(
5,
5.00000001,
msg_fmt="{msg};{first};{second};{places};{delta!r}",
)
def test_assert_not_almost_equal__similar__places__custom_message(self):
with _assert_raises_assertion(
"5 == 5.0001 within 3 places;5;5.0001;3;None"
):
assert_not_almost_equal(
5,
5.0001,
places=3,
msg_fmt="{msg};{first};{second};{places};{delta!r}",
)
def test_assert_not_almost_equal__similar__delta__custom_message(self):
with _assert_raises_assertion("5 == 6 with delta=1.1;5;6;None;1.1"):
assert_not_almost_equal(
5,
6,
delta=1.1,
msg_fmt="{msg};{first};{second};{places!r};{delta}",
)
def test_assert_not_almost_equal__wrong_types(self):
try:
assert_not_almost_equal("5", "5") # type: ignore[arg-type]
except TypeError:
pass
else:
raise AssertionError("TypeError not raised")
def test_assert_not_almost_equal__places_and_delta(self):
try:
assert_not_almost_equal(5, 5, places=3, delta=0.0003)
except TypeError:
pass
else:
raise AssertionError("TypeError not raised")
def test_not_assert_almost_equal__delta_eq_0(self):
try:
assert_not_almost_equal(5, 5, delta=0)
except ValueError:
pass
else:
raise AssertionError("ValueError not raised")
def test_not_assert_almost_equal__delta_lt_0(self):
try:
assert_not_almost_equal(5, 5, delta=-1)
except ValueError:
pass
else:
raise AssertionError("ValueError not raised")
# assert_dict_equal()
def test_assert_dict_equal__empty_dicts(self):
assert_dict_equal({}, {})
def test_assert_dict_equal__dicts_are_equal(self):
assert_dict_equal({"foo": 5}, {"foo": 5})
def test_assert_dict_equal__one_key_missing_from_right(self):
with _assert_raises_assertion("key 'foo' missing from right dict"):
assert_dict_equal({"bar": 10, "foo": 5}, {"bar": 10})
def test_assert_dict_equal__multiple_keys_missing_from_right(self):
with _assert_raises_assertion(
"keys 'bar', 'foo' missing from right dict"
):
assert_dict_equal({"foo": 5, "bar": 10, "baz": 15}, {"baz": 15})
def test_assert_dict_equal__one_key_missing_from_left(self):
with _assert_raises_assertion("extra key 'foo' in right dict"):
assert_dict_equal({"bar": 10}, {"bar": 10, "foo": 5})
def test_assert_dict_equal__multiple_keys_missing_from_left(self):
with _assert_raises_assertion("extra keys 'bar', 'foo' in right dict"):
assert_dict_equal({"baz": 15}, {"foo": 5, "bar": 10, "baz": 15})
def test_assert_dict_equal__values_do_not_match(self):
with _assert_raises_assertion("key 'foo' differs: 15 != 10"):
assert_dict_equal({"foo": 15}, {"foo": 10})
def test_assert_dict_equal__not_string_keys(self):
with _assert_raises_assertion("key 10 missing from right dict"):
assert_dict_equal({10: "foo"}, {})
with _assert_raises_assertion("keys 'foo', 5 missing from right dict"):
assert_dict_equal({5: "", "foo": ""}, {})
with _assert_raises_assertion("extra key 10 in right dict"):
assert_dict_equal({}, {10: "foo"})
with _assert_raises_assertion("extra keys 'foo', 5 in right dict"):
assert_dict_equal({}, {5: "", "foo": ""})
def test_assert_dict_equal__message_precedence(self):
with _assert_raises_assertion("key 'foo' missing from right dict"):
assert_dict_equal(
{"foo": "", "bar": "", "baz": 5},
{"bar": "", "baz": 10, "extra": ""},
)
with _assert_raises_assertion("extra key 'extra' in right dict"):
assert_dict_equal(
{"bar": "", "baz": 5}, {"bar": "", "baz": 10, "extra": ""}
)
def test_assert_dict_equal__custom_key_message(self):
with _assert_raises_assertion(
"key 'foo' missing from right dict;"
"{'foo': ''};{'bar': ''};['foo'];['bar']"
):
assert_dict_equal(
{"foo": ""},
{"bar": ""},
key_msg_fmt="{msg};{first!r};{second!r};"
"{missing_keys!r};{extra_keys!r}",
)
def test_assert_dict_equal__custom_value_message(self):
with _assert_raises_assertion(
"key 'foo' differs: 5 != 10;{'foo': 5};{'foo': 10};" "'foo';5;10"
):
assert_dict_equal(
{"foo": 5},
{"foo": 10},
value_msg_fmt="{msg};{first!r};{second!r};"
"{key!r};{first_value};{second_value}",
)
# assert_dict_superset()
def test_assert_dict_superset__empty_dicts(self):
assert_dict_superset({}, {})
def test_assert_dict_superset__dicts_are_equal(self):
assert_dict_superset({"foo": 5}, {"foo": 5})
def test_assert_dict_superset__dicts_is_superset(self):
assert_dict_superset({"foo": 5}, {"foo": 5, "bar": 10})
def test_assert_dict_superset__one_key_missing_from_right(self):
with _assert_raises_assertion("key 'foo' missing from right dict"):
assert_dict_superset({"bar": 10, "foo": 5}, {"bar": 10})
def test_assert_dict_superset__multiple_keys_missing_from_right(self):
with _assert_raises_assertion(
"keys 'bar', 'foo' missing from right dict"
):
assert_dict_superset({"foo": 5, "bar": 10, "baz": 15}, {"baz": 15})
def test_assert_dict_superset__values_do_not_match(self):
with _assert_raises_assertion("key 'foo' differs: 15 != 10"):
assert_dict_superset({"foo": 15}, {"foo": 10, "bar": 15})
def test_assert_dict_superset__not_string_keys(self):
with _assert_raises_assertion("key 10 missing from right dict"):
assert_dict_superset({10: "foo"}, {})
with _assert_raises_assertion("keys 'foo', 5 missing from right dict"):
assert_dict_superset({5: "", "foo": ""}, {})
def test_assert_dict_superset__message_precedence(self):
with _assert_raises_assertion("key 'foo' missing from right dict"):
assert_dict_superset({"foo": "", "bar": 5}, {"bar": 1})
def test_assert_dict_superset__custom_key_message(self):
with _assert_raises_assertion(
"key 'foo' missing from right dict;"
"{'foo': ''};{'bar': ''};['foo']"
):
assert_dict_superset(
{"foo": ""},
{"bar": ""},
key_msg_fmt="{msg};{first!r};{second!r};" "{missing_keys!r}",
)
def test_assert_dict_superset__custom_value_message(self):
with _assert_raises_assertion(
"key 'foo' differs: 5 != 10;{'foo': 5};{'foo': 10};" "'foo';5;10"
):
assert_dict_superset(
{"foo": 5},
{"foo": 10},
value_msg_fmt="{msg};{first!r};{second!r};"
"{key!r};{first_value};{second_value}",
)
# assert_less()
def test_assert_less(self):
assert_less(4, 5)
with _assert_raises_assertion("5 is not less than 5"):
assert_less(5, 5)
with _assert_raises_assertion("'foo' is not less than 'bar'"):
assert_less("foo", "bar")
with _assert_raises_assertion("6 is not less than 5;6;5"):
assert_less(6, 5, "{msg};{first};{second}")
# assert_less_equal()
def test_assert_less_equal(self):
assert_less_equal(4, 5)
assert_less_equal(5, 5)
with _assert_raises_assertion(
"'foo' is not less than or equal to 'bar'"
):
assert_less_equal("foo", "bar")
with _assert_raises_assertion("6 is not less than or equal to 5;6;5"):
assert_less_equal(6, 5, "{msg};{first};{second}")
# assert_greater()
def test_assert_greater(self):
assert_greater(5, 4)
with _assert_raises_assertion("5 is not greater than 5"):
assert_greater(5, 5)
with _assert_raises_assertion("'bar' is not greater than 'foo'"):
assert_greater("bar", "foo")
with _assert_raises_assertion("5 is not greater than 6;5;6"):
assert_greater(5, 6, "{msg};{first};{second}")
# assert_greater_equal()
def test_assert_greater_equal(self):
assert_greater_equal(5, 4)
assert_greater_equal(5, 5)
with _assert_raises_assertion(
"'bar' is not greater than or equal to 'foo'"
):
assert_greater_equal("bar", "foo")
with _assert_raises_assertion(
"5 is not greater than or equal to 6;5;6"
):
assert_greater_equal(5, 6, "{msg};{first};{second}")
# assert_regex()
def test_assert_regex__matches_string(self):
assert_regex("This is a test text", "is.*test")
def test_assert_regex__matches_regex(self):
regex = re.compile("is.*test")
assert_regex("This is a test text", regex)
def test_assert_regex__does_not_match_string__default_message(self):
with _assert_raises_assertion(
"'This is a test text' does not match 'not found'"
):
assert_regex("This is a test text", "not found")
def test_assert_regex__does_not_match_regex__default_message(self):
regex = re.compile(r"not found")
with _assert_raises_assertion(
"'This is a test text' does not match 'not found'"
):
assert_regex("This is a test text", regex)
def test_assert_regex__does_not_match_string__custom_message(self):
with _assert_raises_assertion(
"'Wrong text' does not match 'not found';"
"'Wrong text';'not found'"
):
assert_regex(
"Wrong text", r"not found", "{msg};{text!r};{pattern!r}"
)
def test_assert_regex__does_not_match_regex__custom_message(self):
regex = re.compile(r"not found")
with _assert_raises_assertion(
"'Wrong text' does not match 'not found';'Wrong text';"
"'not found'"
):
assert_regex("Wrong text", regex, "{msg};{text!r};{pattern!r}")
# assert_not_regex()
def test_assert_not_regex__does_not_match_string(self):
assert_not_regex("This is a test text", "no match")
def test_assert_not_regex__does_not_match_regex(self):
regex = re.compile("no match")
assert_not_regex("This is a test text", regex)
def test_assert_not_regex__matches_string__default_message(self):
with _assert_raises_assertion(
"'This is a test text' matches 'is.*test'"
):
assert_not_regex("This is a test text", "is.*test")
def test_assert_not_regex__matches_regex__default_message(self):
regex = re.compile("is.*test")
with _assert_raises_assertion(
"'This is a test text' matches 'is.*test'"
):
assert_not_regex("This is a test text", regex)
def test_assert_not_regex__matches_string__custom_message(self):
with _assert_raises_assertion(
"'This is a test text' matches 'is.*test';"
"'This is a test text';'is.*test'"
):
assert_not_regex(
"This is a test text",
"is.*test",
"{msg};{text!r};{pattern!r}",
)
def test_assert_not_regex__matches_regex__custom_message(self):
regex = re.compile("is.*test")
with _assert_raises_assertion(
"'This is a test text' matches 'is.*test';'This is a test text';"
"'is.*test'"
):
assert_not_regex(
"This is a test text", regex, "{msg};{text!r};{pattern!r}"
)
# assert_is()
def test_assert_is__same(self):
x = _DummyObject()
assert_is(x, x)
def test_assert_is__not_same__default_message(self):
with _assert_raises_assertion("'x' is not 'y'"):
assert_is("x", "y")
def test_assert_is__equal_but_not_same__custom_message(self):
x = "x"
y = _DummyObject("y")
with _assert_raises_assertion("'x' is not <Dummy>;'x';y"):
assert_is(x, y, "{msg};{first!r};{second.value}")
# assert_is_not()
def test_assert_is_not__not_same(self):
x = _DummyObject()
y = _DummyObject()
assert_is_not(x, y)
def test_assert_is_not__same__default_message(self):
x = _DummyObject("x")
with _assert_raises_assertion("both arguments refer to <Dummy>"):
assert_is_not(x, x)
def test_assert_is_not__same__custom_message(self):
x = _DummyObject("x")
with _assert_raises_assertion("both arguments refer to <Dummy>;x;x"):
assert_is_not(x, x, "{msg};{first.value};{second.value}")
# assert_in()
def test_assert_in__contains(self):
assert_in("foo", ["foo", "bar", "baz"])
def test_assert_in__does_not_contain__default_message(self):
with _assert_raises_assertion("'foo' not in []"):
assert_in("foo", [])
def test_assert_in__does_not_contain__custom_message(self):
with _assert_raises_assertion("'foo' not in [];'foo';[]"):
assert_in("foo", [], "{msg};{first!r};{second!r}")
# assert_not_in()
def test_assert_not_in__does_not_contain(self):
assert_not_in("foo", [])
def test_assert_not_in__does_contain__default_message(self):
with _assert_raises_assertion("'foo' is in ['foo', 'bar', 'baz']"):
assert_not_in("foo", ["foo", "bar", "baz"])
def test_assert_not_in__does_contain__custom_message(self):
with _assert_raises_assertion("'foo' is in ['foo', 'bar'];'foo';bar"):
assert_not_in("foo", ["foo", "bar"], "{msg};{first!r};{second[1]}")
# assert_count_equal()
def test_assert_count_equal__equal(self):
with assert_succeeds(AssertionError):
assert_count_equal(["a"], ["a"])
def test_assert_count_equal__equal_differing_types(self):
with assert_succeeds(AssertionError):
assert_count_equal(["a"], {"a"})
def test_assert_count_equal__ignore_order(self):
with assert_succeeds(AssertionError):
assert_count_equal(["a", "b"], ["b", "a"])
def test_assert_count_equal__missing_from_sequence1(self):
with _assert_raises_assertion("missing from sequence 1: 'a'"):
assert_count_equal([], {"a"})
def test_assert_count_equal__multiple_missing_from_sequence1(self):
with _assert_raises_assertion("missing from sequence 1: 'b', 'c'"):
assert_count_equal(["a"], ["a", "b", "c"])
def test_assert_count_equal__respect_duplicates(self):
with _assert_raises_assertion("missing from sequence 1: 'a'"):
assert_count_equal({"a"}, ["a", "a"])
def test_assert_count_equal__missing_from_sequence2(self):
with _assert_raises_assertion("missing from sequence 2: 'a', 'c'"):
assert_count_equal(["a", "b", "c"], ["b"])
def test_assert_count_equal__missing_from_both(self):
msg = "missing from sequence 1: 'd'; missing from sequence 2: 'b', 'c'"
with _assert_raises_assertion(msg):
assert_count_equal(["a", "b", "c"], ["a", "d"])
def test_assert_count_equal__custom_message(self):
with _assert_raises_assertion("missing from sequence 1: 'a';[];['a']"):
assert_count_equal([], ["a"], "{msg};{first};{second}")
# assert_between()
def test_assert_between__within_range(self):
assert_between(0, 10, 0)
assert_between(0, 10, 10)
assert_between(0, 10, 5)
def test_assert_between__too_low__default_message(self):
with _assert_raises_assertion("-1 is not between 0 and 10"):
assert_between(0, 10, -1)
def test_assert_between__too_high__custom_message(self):
with _assert_raises_assertion("11 is not between 0 and 10;0;10;11"):
assert_between(0, 10, 11, "{msg};{lower};{upper};{expr}")
# assert_is_instance()
def _is_instance_message(self, expr, expected_type, real_type):
expected_message = (
"{!r} is an instance of <class {}>, expected {}".format(
expr, real_type, expected_type
)
)
if sys.version_info[0] < 3:
return expected_message.replace("class", "type")
else:
return expected_message
def test_assert_is_instance__single_type(self):
assert_is_instance(4, int)
assert_is_instance(OSError(), Exception)
def test_assert_is_instance__multiple_types(self):
assert_is_instance(4, (str, int))
def test_assert_is_instance__default_message(self):
expected_message = self._is_instance_message(
"my string", "<class 'int'>", "'str'"
)
with _assert_raises_assertion(expected_message):
assert_is_instance("my string", int)
def test_assert_is_instance__custom_message_single_type(self):
expected_message = self._is_instance_message(
"my string", "<class 'int'>", "'str'"
)
expected = "{};my string;(<class 'int'>,)".format(expected_message)
expected = expected.replace("class", self._type_string)
with _assert_raises_assertion(expected):
assert_is_instance("my string", int, "{msg};{obj};{types}")
def test_assert_is_instance__custom_message_multiple_types(self):
expected_message = self._is_instance_message(
"my string", "(<class 'int'>, <class 'float'>)", "'str'"
)
expected = "{};my string;(<class 'int'>, <class 'float'>)".format(
expected_message
)
expected = expected.replace("class", self._type_string)
with _assert_raises_assertion(expected):
assert_is_instance(
"my string", (int, float), "{msg};{obj};{types}"
)
# assert_not_is_instance()
def _not_is_instance_message(self, obj):
expected_message = "{!r} is an instance of {}".format(
obj, obj.__class__
)
if sys.version_info[0] < 3:
expected_message = expected_message.replace("class", "type")
expected_message = expected_message.replace(
"type 'OSError'", "type 'exceptions.OSError'"
)
return expected_message
def test_assert_not_is_instance__single_type(self):
assert_not_is_instance(4, str)
def test_assert_not_is_instance__multiple_types(self):
assert_not_is_instance(4, (str, bytes))
def test_assert_not_is_instance__default_message(self):
obj = OSError()
expected_message = self._not_is_instance_message(obj)
with _assert_raises_assertion(expected_message):
assert_not_is_instance(obj, Exception)
def test_assert_not_is_instance__custom_message__single_type(self):
msg = self._not_is_instance_message("Foo")
expected = "{};Foo;(<class 'str'>,)".format(msg)
expected = expected.replace("class", self._type_string)
with _assert_raises_assertion(expected):
assert_not_is_instance("Foo", str, "{msg};{obj};{types!r}")
def test_assert_not_is_instance__custom_message__multiple_types(self):
msg = self._not_is_instance_message("Foo")
expected = "{};Foo;(<class 'str'>, <class 'int'>)".format(msg)
expected = expected.replace("class", self._type_string)
with _assert_raises_assertion(expected):
assert_not_is_instance("Foo", (str, int), "{msg};{obj};{types!r}")
# assert_has_attr()
def test_assert_has_attr__has_attribute(self):
d = _DummyObject()
assert_has_attr(d, "value")
def test_assert_has_attr__does_not_have_attribute__default_message(self):
d = _DummyObject()
with _assert_raises_assertion("<Dummy> does not have attribute 'foo'"):
assert_has_attr(d, "foo")
def test_assert_has_attr__does_not_have_attribute__custom_message(self):
d = _DummyObject()
expected = "<Dummy> does not have attribute 'foo';<Dummy>;foo"
with _assert_raises_assertion(expected):
assert_has_attr(d, "foo", msg_fmt="{msg};{obj!r};{attribute}")
# assert_datetime_about_now()
def test_assert_datetime_about_now__close(self):
assert_datetime_about_now(datetime.now())
def test_assert_datetime_about_now__none__default_message(self):
expected_message = r"^None is not a valid date/time$"
with assert_raises_regex(AssertionError, expected_message):
assert_datetime_about_now(None)
def test_assert_datetime_about_now__none__custom_message(self):
dt = datetime.now().date().isoformat()
expected = "None is not a valid date/time;None;{}".format(dt)
with _assert_raises_assertion(expected):
assert_datetime_about_now(
None, msg_fmt="{msg};{actual!r};{now:%Y-%m-%d}"
)
def test_assert_datetime_about_now__too_low(self):
then = datetime.now() - timedelta(minutes=1)
with assert_raises(AssertionError):
assert_datetime_about_now(then)
def test_assert_datetime_about_now__too_high(self):
then = datetime.now() + timedelta(minutes=1)
with assert_raises(AssertionError):
assert_datetime_about_now(then)
def test_assert_datetime_about_now__default_message(self):
then = datetime(1990, 4, 13, 12, 30, 15)
expected_message = (
r"^datetime.datetime\(1990, 4, 13, 12, 30, 15\) "
"is not close to current date/time$"
)
with assert_raises_regex(AssertionError, expected_message):
assert_datetime_about_now(then)
def test_assert_datetime_about_now__custom_message(self):
then = datetime(1990, 4, 13, 12, 30, 15)
now = datetime.now().date().isoformat()
expected = (
"datetime.datetime(1990, 4, 13, 12, 30, 15) "
"is not close to current date/time;12:30;{}".format(now)
)
with _assert_raises_assertion(expected):
assert_datetime_about_now(
then, msg_fmt="{msg};{actual:%H:%M};{now:%Y-%m-%d}"
)
# assert_datetime_about_now_utc()
def test_assert_datetime_about_now_utc__close(self):
assert_datetime_about_now_utc(
datetime.now(timezone.utc).replace(tzinfo=None)
)
def test_assert_datetime_about_now_utc__none__default_message(self):
expected_message = r"^None is not a valid date/time$"
with assert_raises_regex(AssertionError, expected_message):
assert_datetime_about_now_utc(None)
def test_assert_datetime_about_now_utc__none__custom_message(self):
dt = datetime.now(timezone.utc).date().isoformat()
expected = "None is not a valid date/time;None;{}".format(dt)
with _assert_raises_assertion(expected):
assert_datetime_about_now_utc(
None, msg_fmt="{msg};{actual!r};{now:%Y-%m-%d}"
)
def test_assert_datetime_about_now_utc__too_low(self):
then = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(
minutes=1
)
with assert_raises(AssertionError):
assert_datetime_about_now_utc(then)
def test_assert_datetime_about_now_utc__too_high(self):
then = datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(
minutes=1
)
with assert_raises(AssertionError):
assert_datetime_about_now_utc(then)
def test_assert_datetime_about_now_utc__default_message(self):
then = datetime(1990, 4, 13, 12, 30, 15)
expected_message = (
r"datetime.datetime\(1990, 4, 13, 12, 30, 15\) "
r"is not close to current UTC date/time$"
)
with assert_raises_regex(AssertionError, expected_message):
assert_datetime_about_now_utc(then)
def test_assert_datetime_about_now_utc__custom_message(self):
then = datetime(1990, 4, 13, 12, 30, 15)
now = datetime.now(timezone.utc).date().isoformat()
expected = (
"datetime.datetime(1990, 4, 13, 12, 30, 15) "
"is not close to current UTC date/time;12:30;{}".format(now)
)
with _assert_raises_assertion(expected):
assert_datetime_about_now_utc(
then, msg_fmt="{msg};{actual:%H:%M};{now:%Y-%m-%d}"
)
# assert_raises()
def test_assert_raises__raises_right_exception(self):
with assert_raises(KeyError):
raise KeyError()
def test_assert_raises__exc_val(self):
exc = KeyError()
with assert_raises(KeyError) as context:
raise exc
assert_is(exc, context.exc_val)