/
mock_callable_testslide.py
1752 lines (1460 loc) · 69.2 KB
/
mock_callable_testslide.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
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import contextlib
import os
import testslide
from testslide.dsl import Skip, context, fcontext, xcontext # noqa: F401
from testslide.lib import CoroutineValueError, TypeCheckError
from testslide.mock_callable import (
UndefinedBehaviorForCall,
UnexpectedCallArguments,
UnexpectedCallReceived,
mock_callable,
)
from testslide.strict_mock import StrictMock
from . import sample_module
async def coro_fun(*args):
return 1
@context("mock_callable()")
def mock_callable_tests(context):
##
## Attributes
##
context.memoize("assertions", lambda self: [])
context.memoize("call_args", lambda self: ("first", "second"))
context.memoize("call_kwargs", lambda self: {"kwarg1": "first", "kwarg2": "second"})
context.memoize("type_validation", lambda self: True)
@context.memoize
def specific_call_args(self):
return tuple("specific {}".format(arg) for arg in self.call_args)
@context.memoize
def specific_call_kwargs(self):
return {k: "specific {}".format(v) for k, v in self.call_kwargs.items()}
##
## Functions
##
@context.function
def assert_all(self):
try:
for assertion in self.assertions:
assertion()
finally:
del self.assertions[:]
@context.function
@contextlib.contextmanager
def assertRaisesWithMessage(self, exception, msg):
with self.assertRaises(exception) as cm:
yield
ex_msg = str(cm.exception)
self.assertEqual(
ex_msg,
msg,
"Expected exception {}.{} message "
"to be\n{}\nbut got\n{}.".format(
exception.__module__, exception.__name__, repr(msg), repr(ex_msg)
),
)
##
## Hooks
##
@context.before
def register_assertions(self):
def register_assertion(assertion):
self.assertions.append(assertion)
testslide.mock_callable.register_assertion = register_assertion
@context.after
def cleanup_patches(self):
# Unpatch before assertions, to make sure it is done if assertion fails.
testslide.mock_callable.unpatch_all_callable_mocks()
for assertion in self.assertions:
assertion()
##
## Examples
##
@context.example
def patching_private_functions_raises_valueerror(self):
with self.assertRaises(ValueError):
self.mock_callable(sample_module.TargetStr, "_privatefun")
@context.example
def patching_private_functions_with_allow_private(self):
t = sample_module.TargetStr()
self.mock_callable(t, "_privatefun", allow_private=True).to_return_value(
"This fun is private"
).and_assert_called_once()
t._privatefun()
@context.example
def patching_functions_in_slotted_class(self):
t = sample_module.SomeClassWithSlots(attribute="value")
self.mock_callable(t, "method").to_return_value(42).and_assert_called_once()
self.assertEqual(t.method(), 42)
@context.example
def patching_functions_multiple_times_with_unhashable_class(self):
t1 = sample_module.SomeUnhashableClass()
t2 = sample_module.SomeUnhashableClass()
t3 = sample_module.SomeUnhashableClass()
self.mock_callable(t1, "method").to_return_value(0).and_assert_called_once()
self.assertEqual(t1.method(), 0)
self.mock_callable(t2, "method").to_return_value(1).and_assert_called_once()
self.assertEqual(t2.method(), 1)
self.mock_callable(t3, "method").to_return_value(2).and_assert_called_once()
self.assertEqual(t3.method(), 2)
##
## Shared Contexts
##
@context.shared_context
def mock_configuration_examples(
context, empty_args=False, has_original_callable=True, can_yield=True
):
@context.function
def no_behavior_msg(self):
if self.call_args:
args_msg = " {}\n".format(self.call_args)
else:
args_msg = ""
if self.call_kwargs:
kwargs_msg = (
" {\n"
+ "".join(
" {}={},\n".format(k, repr(self.call_kwargs[k]))
for k in sorted(self.call_kwargs.keys())
)
+ " }\n"
)
else:
kwargs_msg = ""
return str(
"{}, {}:\n".format(repr(self.target_arg), repr(self.callable_arg))
+ " Received call:\n"
+ args_msg
+ kwargs_msg
+ " But no behavior was defined for it."
)
@context.shared_context
def mock_call_arguments(context, has_return_value=True):
@context.sub_context
def mock_call(context):
@context.sub_context
def signature(context):
@context.example
def passes_with_valid_signature(self):
self.callable_target(*self.call_args, **self.call_kwargs)
@context.example
def raises_TypeError_for_mismatching_signature(self):
args = ("some", "invalid", "args", "list")
kwargs = {"invalid_kwarg": "invalid_value"}
with self.assertRaises(TypeError):
self.callable_target(*args, **kwargs)
if not empty_args:
@context.sub_context
def type_validation(context):
@context.sub_context
def arguments(context):
@context.example
def raises_TypeCheckError_for_invalid_types(self):
bad_signature_args = (1234 for arg in self.call_args)
bad_signature_kargs = {
k: 1234 for k, v in self.call_kwargs.items()
}
with self.assertRaises(TypeCheckError):
self.callable_target(
*bad_signature_args, **bad_signature_kargs
)
@context.sub_context("with type_validation=False")
def with_type_validation_False(context):
context.memoize("type_validation", lambda self: False)
@context.example
def passes_with_invalid_argument_type(self):
call_args = [1 for arg in self.call_args]
call_kwargs = {
key: 1 for key in self.call_kwargs.keys()
}
self.callable_target(*call_args, **call_kwargs)
if has_return_value:
@context.sub_context
def return_value(context):
@context.example
def passes_with_valid_type(self):
self.callable_target(
*self.call_args, **self.call_kwargs
)
@context.sub_context
def with_invalid_return_type(context):
context.memoize("value", lambda self: 1)
context.memoize("values_list", lambda self: [1])
@context.example
def raises_TypeCheckError(self):
with self.assertRaises(TypeCheckError):
self.callable_target(
*self.call_args, **self.call_kwargs
)
@context.sub_context(".for_call(*args, **kwargs)")
def for_call_args_kwargs(context):
@context.sub_context
def with_mismatching_signature(context):
@context.xexample
def it_fails_to_mock(self):
with self.assertRaisesWithMessage(
ValueError,
"Can not mock target for arguments that mismatch the "
"original callable signature.",
):
self.mock_callable_dsl.for_call(
"some",
"invalid",
"args",
and_some="invalid",
kwargs="values",
)
if not empty_args:
@context.sub_context
def with_matching_signature(context):
@context.before
def before(self):
self.mock_callable_dsl.for_call(
*self.specific_call_args, **self.specific_call_kwargs
)
@context.example
def it_accepts_known_arguments(self):
self.callable_target(
*self.specific_call_args, **self.specific_call_kwargs
)
@context.example
def it_rejects_unknown_arguments(self):
with self.assertRaisesWithMessage(
UnexpectedCallArguments,
self.no_behavior_msg()
+ "\n These are the registered calls:\n"
+ " {}\n".format(self.specific_call_args)
+ " {\n"
+ "".join(
" {}={},\n".format(
k, repr(self.specific_call_kwargs[k])
)
for k in sorted(self.specific_call_kwargs.keys())
)
+ " }\n",
):
self.callable_target(
*self.call_args, **self.call_kwargs
)
@context.shared_context
def assertions(context):
@context.shared_context
def assert_failure(context):
@context.after
def after(self):
with self.assertRaises(AssertionError):
self.assert_all()
@context.shared_context
def not_called(context):
@context.example
def not_called(self):
pass
@context.shared_context
def called_less_times(context):
@context.example
def called_less_times(self):
for _ in range(self.times - 1):
self.callable_target(*self.call_args, **self.call_kwargs)
@context.shared_context
def called_more_times(context):
@context.example
def called_more_times(self):
for _ in range(self.times + 1):
self.callable_target(*self.call_args, **self.call_kwargs)
@context.shared_context
def called_more_times_fail(context):
@context.example
def called_more_times(self):
for _ in range(self.times):
self.callable_target(*self.call_args, **self.call_kwargs)
with self.assertRaisesWithMessage(
UnexpectedCallReceived,
(
"Unexpected call received.\n"
"{}, {}:\n"
" expected to receive at most {} calls with any arguments "
" but received an extra call."
).format(
repr(self.target_arg), repr(self.callable_arg), self.times
),
):
self.callable_target(*self.call_args, **self.call_kwargs)
@context.shared_context
def called_exactly_times(context):
@context.example
def called_exactly_times(self):
for _ in range(self.times):
self.callable_target(*self.call_args, **self.call_kwargs)
@context.sub_context(".and_assert_called_exactly(times)")
def and_assert_called_exactly(context):
@context.sub_context
def with_valid_input(context):
@context.before
def setup_assertion(self):
self.mock_callable_dsl.and_assert_called_exactly(self.times)
@context.sub_context
def fails_when(context):
context.merge_context("assert failure")
context.merge_context("not called")
context.merge_context("called less times")
context.merge_context("called more times fail")
@context.sub_context
def passes_when(context):
context.merge_context("called exactly times")
@context.sub_context(".and_assert_called_at_least(times)")
def and_assert_called_at_least(context):
@context.sub_context
def with_invalid_input(context):
@context.example("fails to mock when times < 1")
def fails_to_mock_when_times_1(self):
with self.assertRaisesWithMessage(
ValueError, "times must be >= 1"
):
self.mock_callable_dsl.and_assert_called_at_least(0)
@context.sub_context
def with_valid_input(context):
@context.before
def setup_assertion(self):
self.mock_callable_dsl.and_assert_called_at_least(self.times)
@context.sub_context
def fails_when(context):
context.merge_context("assert failure")
context.merge_context("not called")
context.merge_context("called less times")
@context.sub_context
def passes_when(context):
context.merge_context("called exactly times")
context.merge_context("called more times")
@context.sub_context(".and_assert_called_at_most(times)")
def and_assert_called_at_most(context):
@context.sub_context
def with_invalid_input(context):
@context.example("fails to mock when times < 1")
def fails_to_mock_when_times_1(self):
with self.assertRaisesWithMessage(
ValueError, "times must be >= 1"
):
self.mock_callable_dsl.and_assert_called_at_most(0)
@context.sub_context
def with_valid_input(context):
@context.before
def setup_assertion(self):
self.mock_callable_dsl.and_assert_called_at_most(self.times)
@context.sub_context
def fails_when(context):
context.merge_context("assert failure")
context.merge_context("not called")
context.merge_context("called more times fail")
@context.sub_context
def passes_when(context):
context.merge_context("called less times")
context.merge_context("called exactly times")
@context.sub_context(".and_assert_called()")
def and_assert_called(context):
@context.before
def setup_assertion(self):
self.mock_callable_dsl.and_assert_called()
@context.sub_context
def fails_when(context):
context.merge_context("assert failure")
context.merge_context("not called")
@context.sub_context
def passes_when(context):
@context.example
def called_once(self):
self.callable_target(*self.call_args, **self.call_kwargs)
@context.example
def called_several_times(self):
for _ in range(self.times + 1):
self.callable_target(*self.call_args, **self.call_kwargs)
@context.sub_context(".and_assert_not_called()")
def and_assert_not_called(context):
@context.example
def can_use_with_previously_existing_behavior(self):
self.mock_callable_dsl.and_assert_not_called()
@context.sub_context
def default_behavior(context):
@context.example
def mock_call_fails_with_undefined_behavior(self):
with self.assertRaisesWithMessage(
UndefinedBehaviorForCall, self.no_behavior_msg()
):
self.callable_target(*self.call_args, **self.call_kwargs)
@context.example
def can_not_define_call_assertions(self):
with self.assertRaisesRegex(
ValueError, "^You must first define a behavior.+"
):
self.mock_callable_dsl.and_assert_called_exactly(1)
@context.example
def mock_callable_can_not_assert_if_already_received_call(self):
t = sample_module.SomeClass()
mock = self.mock_callable(t, "method").to_return_value("value")
t.method()
with self.assertRaisesRegex(
ValueError,
"^No extra configuration is allowed after mock_callable.+self.mock_callable",
):
mock.and_assert_called_once()
@context.sub_context(".and_assert_not_called()")
def and_assert_not_called(context):
@context.before
def setup_assertion(self):
self.mock_callable_dsl.and_assert_not_called()
@context.sub_context
def passes_when(context):
@context.example
def not_called(self):
pass
@context.sub_context
def fails_when(context):
@context.after
def after(self):
with self.assertRaises(AssertionError):
self.assert_all()
@context.example
def called(self):
with self.assertRaisesWithMessage(
UnexpectedCallReceived,
"{}, {}: Expected not to be called!".format(
repr(self.real_target), repr(self.callable_arg)
),
):
self.callable_target(*self.call_args, **self.call_kwargs)
@context.sub_context(".to_return(value)")
def to_return_value(context):
@context.memoize_before
def value(self):
# __str__ method is the only method returing `str`, while
# all the other tested methods returns `List[str]`
if self.callable_arg == "__str__":
return "mocked return"
else:
return ["mocked return"]
context.memoize("times", lambda self: 3)
@context.before
def setup_mock(self):
self.mock_callable_dsl.to_return_value(self.value)
if has_original_callable:
context.merge_context("mock call arguments")
context.nest_context("assertions")
@context.example
def mock_call_returns_given_value(self):
self.assertEqual(
self.callable_target(*self.call_args, **self.call_kwargs),
self.value,
)
other_args = ["other_arg" for arg in self.call_args]
other_kwargs = {k: "other_value" for k in self.call_kwargs}
self.assertEqual(
self.callable_target(*other_args, **other_kwargs), self.value
)
@context.example
def return_value_raises_with_coroutine(self):
with self.assertRaises(CoroutineValueError):
self.mock_callable(
sample_module, "test_function", type_validation=False
).to_return_value(coro_fun())
@context.sub_context(".to_return_values(values_list)")
def to_return_values_values_list(context):
@context.memoize_before
def values_list(self):
# __str__ method is the only method returing `str`, while
# all the other tested methods returns `List[str]`
if self.callable_arg == "__str__":
return ["first", "second", "thrift"]
else:
return [["first"], ["second"], ["thrift"]]
context.memoize("value", lambda self: self.values_list[0])
context.memoize("times", lambda self: len(self.values_list) - 1)
@context.before
def setup_mock(self):
self.mock_callable_dsl.to_return_values(self.values_list)
if has_original_callable:
context.merge_context("mock call arguments")
context.nest_context("assertions")
@context.example
def return_values_from_list_in_order(self):
for value in self.values_list:
self.assertEqual(
self.callable_target(*self.call_args, **self.call_kwargs), value
)
@context.example
def return_values_raises_with_coroutine(self):
with self.assertRaises(CoroutineValueError):
self.mock_callable(
sample_module, "test_function", type_validation=False
).to_return_values([1, 2, coro_fun()])
@context.sub_context
def when_list_is_exhausted(context):
@context.before
def before(self):
for _ in self.values_list:
self.callable_target(*self.call_args, **self.call_kwargs)
@context.example
def it_raises(self):
with self.assertRaisesWithMessage(
UndefinedBehaviorForCall, "No more values to return!"
):
self.callable_target(*self.call_args, **self.call_kwargs)
if can_yield:
@context.sub_context(".to_yield_values(values_list)")
def to_yield_values_values_list(context):
context.memoize(
"values_list", lambda self: [["first"], ["second"], ["third"]]
)
context.memoize("times", lambda self: len(self.values_list) - 1)
@context.before
def setup_mock(self):
self.mock_callable_dsl.to_yield_values(self.values_list)
if has_original_callable:
context.merge_context("mock call arguments", has_return_value=False)
context.nest_context("assertions")
@context.memoize
def iterable(self):
return iter(
self.callable_target(*self.call_args, **self.call_kwargs)
)
@context.example
def yield_values_from_list_in_order(self):
for value in self.values_list:
self.assertEqual(next(self.iterable), value)
@context.example
def yield_values_raises_with_coroutine(self):
with self.assertRaises(CoroutineValueError):
self.mock_callable(
sample_module, "test_function", type_validation=False
).to_yield_values([1, 2, coro_fun()])
@context.sub_context
def when_list_is_empty(context):
@context.before
def before(self):
for _ in self.values_list:
next(self.iterable)
@context.example
def it_raises_StopIteration(self):
with self.assertRaises(StopIteration):
next(self.iterable)
@context.sub_context(".to_raise(exception)")
def to_raise_exception(context):
context.memoize("exception_class", lambda self: RuntimeError)
context.memoize("times", lambda self: 3)
@context.shared_context
def integration(context):
@context.memoize_before
def _original_target(self):
return getattr(self.real_target, self.callable_arg)
@context.memoize_before
def callable_target(self):
original_callable_target = self._original_target
def _callable_target(*args, **kwargs):
with self.assertRaises(self.exception_class):
return original_callable_target(*args, **kwargs)
return _callable_target
if has_original_callable:
context.merge_context("mock call arguments", has_return_value=False)
context.nest_context("assertions")
@context.sub_context
def when_given_an_exception_class(context):
@context.before
def setup_mock(self):
self.mock_callable_dsl.to_raise(self.exception_class)
@context.example
def it_raises_an_instance_of_the_class(self):
with self.assertRaises(self.exception_class):
self.callable_target(*self.call_args, **self.call_kwargs)
context.nest_context("integration")
@context.sub_context
def when_given_an_exception_instance(context):
context.memoize("exception_message", lambda self: "test exception")
context.memoize(
"exception",
lambda self: self.exception_class(self.exception_message),
)
@context.before
def setup_mock(self):
self.mock_callable_dsl.to_raise(self.exception)
@context.example
def it_raises_the_exception_instance(self):
with self.assertRaises(self.exception_class) as cm:
self.callable_target(*self.call_args, **self.call_kwargs)
self.assertEqual(self.exception, cm.exception)
context.nest_context("integration")
@context.sub_context(".with_implementation(func)")
def with_implementation_func(context):
@context.memoize_before
def value(self):
# __str__ method is the only method returing `str`, while
# all the other tested methods returns `List[str]`
if self.callable_arg == "__str__":
return "mocked return"
else:
return ["mocked return"]
context.memoize("times", lambda self: 3)
context.memoize("func_return", lambda self: self.value)
@context.memoize
def func(self):
def _func(*args, **kwargs):
return self.func_return
return _func
@context.before
def setup_mock(self):
self.mock_callable_dsl.with_implementation(self.func)
if has_original_callable:
context.merge_context("mock call arguments")
context.nest_context("assertions")
@context.example
def it_calls_new_implementation(self):
self.assertEqual(
self.callable_target(*self.call_args, **self.call_kwargs),
self.func_return,
)
@context.example
def with_implementation_raises_with_coroutine(self):
self.mock_callable(
sample_module, "test_function", type_validation=False
).with_implementation(coro_fun)
with self.assertRaises(CoroutineValueError):
sample_module.test_function("a", "")
@context.sub_context(".with_wrapper(wrapper_func)")
def with_wrapper_wrappr_func(context):
@context.memoize_before
def value(self):
# __str__ method is the only method returing `str`, while
# all the other tested methods returns `List[str]`
if self.callable_arg == "__str__":
return "mocked return"
else:
return ["mocked return"]
context.memoize("func_return", lambda self: self.value)
@context.memoize
def wrapper_func(self):
def _wrapper_func(original_function, *args, **kwargs):
self.assertEqual(original_function, self.original_callable)
return self.func_return
return _wrapper_func
if has_original_callable:
context.memoize("times", lambda self: 3)
@context.before
def setup_mock(self):
self.mock_callable_dsl.with_wrapper(self.wrapper_func)
context.merge_context("mock call arguments")
context.nest_context("assertions")
@context.example
def it_calls_wrapper_function(self):
self.assertEqual(
self.callable_target(*self.call_args, **self.call_kwargs),
self.func_return,
)
@context.example
def with_wrapper_raises_with_coroutine(self):
async def _wrapper_coro_func(original_function, *args, **kwargs):
self.assertEqual(original_function, self.original_callable)
return self.func_return
self.mock_callable(
sample_module, "test_function", type_validation=False
).with_wrapper(_wrapper_coro_func)
with self.assertRaises(CoroutineValueError):
sample_module.test_function("a", "")
else:
@context.example
def it_fails_to_mock(self):
with self.assertRaisesWithMessage(
ValueError,
"Can not wrap original callable that does not exist.",
):
self.mock_callable_dsl.with_wrapper(self.wrapper_func)
@context.sub_context(".to_call_original()")
def to_call_original(context):
if has_original_callable:
context.memoize("times", lambda self: 3)
@context.before
def setup_mock(self):
self.mock_callable_dsl.to_call_original()
context.merge_context("mock call arguments", has_return_value=False)
context.nest_context("assertions")
@context.example
def it_calls_original_implementation(self):
self.assertEqual(
self.callable_target(*self.call_args, **self.call_kwargs),
self.original_callable(*self.call_args, **self.call_kwargs),
)
if not empty_args:
@context.sub_context("with type_validation=False")
def with_type_validation_False(context):
context.memoize("type_validation", lambda self: False)
@context.example
def it_doest_not_type_validate(self):
call_args = [1 for arg in self.call_args]
call_kwargs = {key: 1 for key in self.call_kwargs.keys()}
mock_callable(
self.target_arg,
self.callable_arg,
type_validation=self.type_validation,
).for_call(*call_args, **call_kwargs).to_return_value(None)
self.callable_target(*call_args, **call_kwargs)
else:
@context.example
def it_fails_to_mock(self):
with self.assertRaisesWithMessage(
ValueError,
"Can not call original callable that does not exist.",
):
self.mock_callable_dsl.to_call_original()
if not empty_args:
@context.sub_context
def composition(context):
"""
This context takes care of composition of multiple
call/behavior/assertion combination, to ensure they play along well.
"""
context.memoize(
"other_args", lambda self: ["other_arg" for arg in self.call_args]
)
context.memoize(
"other_kwargs",
lambda self: {
k: "other_value" for k, v in self.call_kwargs.items()
},
)
@context.example
def newest_mock_has_precedence_over_older_mocks(self):
"""
Mocks are designed to be composable, allowing us to declare
multiple behaviors for different calls. Those definitions stack up,
and when a call is made to the mock, they are searched from newest
to oldest, to find one that is able to be caled.
"""
# First, mock all calls
mock_callable(self.target_arg, self.callable_arg).to_return_value(
["any args"]
)
# Then we add some specific call behavior
mock_callable(self.target_arg, self.callable_arg).for_call(
*self.specific_call_args, **self.specific_call_kwargs
).to_return_value(["specific"])
# The first behavior should still be there
self.assertEqual(
self.callable_target(*self.call_args, **self.call_kwargs),
["any args"],
)
# as well as the specific case
self.assertEqual(
self.callable_target(
*self.specific_call_args, **self.specific_call_kwargs
),
["specific"],
)
# but if we add another "catch all" case
mock_callable(self.target_arg, self.callable_arg).to_return_value(
["new any args"]
)
# it should take over any previous mock
self.assertEqual(
self.callable_target(*self.call_args, **self.call_kwargs),
["new any args"],
)
self.assertEqual(
self.callable_target(
*self.specific_call_args, **self.specific_call_kwargs
),
["new any args"],
)
@context.sub_context
def multiple_assertions(context):
@context.before
def setup_mocks(self):
mock_callable(
self.target_arg, self.callable_arg
).to_return_value(["any args"]).and_assert_called_once()
mock_callable(self.target_arg, self.callable_arg).for_call(
*self.specific_call_args, **self.specific_call_kwargs
).to_return_value(["specific"]).and_assert_called_twice()
@context.example
def that_passes(self):
self.callable_target(*self.other_args, **self.other_kwargs)
self.callable_target(
*self.specific_call_args, **self.specific_call_kwargs
)
self.callable_target(
*self.specific_call_args, **self.specific_call_kwargs
)
@context.example
def that_fails(self):
# "Pass" this test when callable accepts no arguments
if (
self.specific_call_args == self.call_args
and self.specific_call_kwargs == self.call_kwargs
):
raise RuntimeError("FIXME")
return
self.callable_target(*self.other_args, **self.other_kwargs)
self.callable_target(
*self.specific_call_args, **self.specific_call_kwargs
)
with self.assertRaises(AssertionError):
self.assert_all()
@context.shared_context
def class_is_not_mocked(context):
@context.example
def class_is_not_mocked(self):
mock_callable(self.target_arg, self.callable_arg).to_return_value(
["mocked value"]
)
self.assertEqual(
self.callable_target(*self.call_args, **self.call_kwargs),
["mocked value"],
)
self.assertEqual(
getattr(sample_module.Target, self.callable_arg)(
*self.call_args, **self.call_kwargs
),
["original response"],
)
@context.shared_context
def can_not_mock_async_callable(context):
@context.example
def can_not_mock(self):
with self.assertRaisesRegex(
ValueError,
getattr(
self,
"exception_regex_message",
r"mock_callable\(\) can not be used with coroutine functions\.",
),
):
mock_callable(self.target_arg, self.callable_arg)
@context.shared_context
def async_methods_examples(context, not_in_class_instance_method=False):
@context.sub_context
def and_callable_is_an_async_instance_method(context):
context.memoize("callable_arg", lambda self: "async_instance_method")
if not_in_class_instance_method:
@context.memoize
def exception_regex_message(self):
return "Patching an instance method at the class is not supported"
context.merge_context("can not mock async callable")
@context.sub_context
def and_callable_is_an_async_class_method(context):
context.memoize("callable_arg", lambda self: "async_class_method")
context.merge_context("can not mock async callable")
@context.sub_context
def and_callable_is_an_async_static_method(context):
context.memoize("callable_arg", lambda self: "async_static_method")