-
Notifications
You must be signed in to change notification settings - Fork 11
/
mox_test.py
executable file
·2495 lines (1912 loc) · 79.3 KB
/
mox_test.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
#!/usr/bin/python2.4
#
# Unit tests for Mox.
#
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import cStringIO
import unittest
import re
import sys
import mox
import mox_test_helper
OS_LISTDIR = mox_test_helper.os.listdir
class ExpectedMethodCallsErrorTest(unittest.TestCase):
"""Test creation and string conversion of ExpectedMethodCallsError."""
def testAtLeastOneMethod(self):
self.assertRaises(ValueError, mox.ExpectedMethodCallsError, [])
def testOneError(self):
method = mox.MockMethod("testMethod", [], [], False)
method(1, 2).AndReturn('output')
e = mox.ExpectedMethodCallsError([method])
self.assertEqual(
"Verify: Expected methods never called:\n"
" 0. testMethod(1, 2) -> 'output'",
str(e))
def testManyErrors(self):
method1 = mox.MockMethod("testMethod", [], [], False)
method1(1, 2).AndReturn('output')
method2 = mox.MockMethod("testMethod", [], [], False)
method2(a=1, b=2, c="only named")
method3 = mox.MockMethod("testMethod2", [], [], False)
method3().AndReturn(44)
method4 = mox.MockMethod("testMethod", [], [], False)
method4(1, 2).AndReturn('output')
e = mox.ExpectedMethodCallsError([method1, method2, method3, method4])
self.assertEqual(
"Verify: Expected methods never called:\n"
" 0. testMethod(1, 2) -> 'output'\n"
" 1. testMethod(a=1, b=2, c='only named') -> None\n"
" 2. testMethod2() -> 44\n"
" 3. testMethod(1, 2) -> 'output'",
str(e))
class OrTest(unittest.TestCase):
"""Test Or correctly chains Comparators."""
def testValidOr(self):
"""Or should be True if either Comparator returns True."""
self.assert_(mox.Or(mox.IsA(dict), mox.IsA(str)) == {})
self.assert_(mox.Or(mox.IsA(dict), mox.IsA(str)) == 'test')
self.assert_(mox.Or(mox.IsA(str), mox.IsA(str)) == 'test')
def testInvalidOr(self):
"""Or should be False if both Comparators return False."""
self.failIf(mox.Or(mox.IsA(dict), mox.IsA(str)) == 0)
class AndTest(unittest.TestCase):
"""Test And correctly chains Comparators."""
def testValidAnd(self):
"""And should be True if both Comparators return True."""
self.assert_(mox.And(mox.IsA(str), mox.IsA(str)) == '1')
def testClauseOneFails(self):
"""And should be False if the first Comparator returns False."""
self.failIf(mox.And(mox.IsA(dict), mox.IsA(str)) == '1')
def testAdvancedUsage(self):
"""And should work with other Comparators.
Note: this test is reliant on In and ContainsKeyValue.
"""
test_dict = {"mock" : "obj", "testing" : "isCOOL"}
self.assert_(mox.And(mox.In("testing"),
mox.ContainsKeyValue("mock", "obj")) == test_dict)
def testAdvancedUsageFails(self):
"""Note: this test is reliant on In and ContainsKeyValue."""
test_dict = {"mock" : "obj", "testing" : "isCOOL"}
self.failIf(mox.And(mox.In("NOTFOUND"),
mox.ContainsKeyValue("mock", "obj")) == test_dict)
class FuncTest(unittest.TestCase):
"""Test Func correctly evaluates based upon true-false return."""
def testFuncTrueFalseEvaluation(self):
"""Should return True if the validating function returns True."""
equals_one = lambda x: x == 1
always_none = lambda x: None
self.assert_(mox.Func(equals_one) == 1)
self.failIf(mox.Func(equals_one) == 0)
self.failIf(mox.Func(always_none) == 1)
self.failIf(mox.Func(always_none) == 0)
self.failIf(mox.Func(always_none) == None)
def testFuncExceptionPropagation(self):
"""Exceptions within the validating function should propagate."""
class TestException(Exception):
pass
def raiseExceptionOnNotOne(value):
if value != 1:
raise TestException
else:
return True
self.assert_(mox.Func(raiseExceptionOnNotOne) == 1)
self.assertRaises(TestException, mox.Func(raiseExceptionOnNotOne).__eq__, 2)
class SameElementsAsTest(unittest.TestCase):
"""Test SameElementsAs correctly identifies sequences with same elements."""
def testSortedLists(self):
"""Should return True if two lists are exactly equal."""
self.assert_(mox.SameElementsAs([1, 2.0, 'c']) == [1, 2.0, 'c'])
def testUnsortedLists(self):
"""Should return True if two lists are unequal but have same elements."""
self.assert_(mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c', 1])
def testUnhashableLists(self):
"""Should return True if two lists have the same unhashable elements."""
self.assert_(mox.SameElementsAs([{'a': 1}, {2: 'b'}]) ==
[{2: 'b'}, {'a': 1}])
def testEmptyLists(self):
"""Should return True for two empty lists."""
self.assert_(mox.SameElementsAs([]) == [])
def testUnequalLists(self):
"""Should return False if the lists are not equal."""
self.failIf(mox.SameElementsAs([1, 2.0, 'c']) == [2.0, 'c'])
def testUnequalUnhashableLists(self):
"""Should return False if two lists with unhashable elements are unequal."""
self.failIf(mox.SameElementsAs([{'a': 1}, {2: 'b'}]) == [{2: 'b'}])
def testActualIsNotASequence(self):
"""Should return False if the actual object is not a sequence."""
self.failIf(mox.SameElementsAs([1]) == object())
def testOneUnhashableObjectInActual(self):
"""Store the entire iterator for a correct comparison.
In a previous version of SameElementsAs, iteration stopped when an
unhashable object was encountered and then was restarted, so the actual list
appeared smaller than it was.
"""
self.failIf(mox.SameElementsAs([1, 2]) == iter([{}, 1, 2]))
class ContainsKeyValueTest(unittest.TestCase):
"""Test ContainsKeyValue correctly identifies key/value pairs in a dict.
"""
def testValidPair(self):
"""Should return True if the key value is in the dict."""
self.assert_(mox.ContainsKeyValue("key", 1) == {"key": 1})
def testInvalidValue(self):
"""Should return False if the value is not correct."""
self.failIf(mox.ContainsKeyValue("key", 1) == {"key": 2})
def testInvalidKey(self):
"""Should return False if they key is not in the dict."""
self.failIf(mox.ContainsKeyValue("qux", 1) == {"key": 2})
class ContainsAttributeValueTest(unittest.TestCase):
"""Test ContainsAttributeValue correctly identifies properties in an object.
"""
def setUp(self):
"""Create an object to test with."""
class TestObject(object):
key = 1
self.test_object = TestObject()
def testValidPair(self):
"""Should return True if the object has the key attribute and it matches."""
self.assert_(mox.ContainsAttributeValue("key", 1) == self.test_object)
def testInvalidValue(self):
"""Should return False if the value is not correct."""
self.failIf(mox.ContainsKeyValue("key", 2) == self.test_object)
def testInvalidKey(self):
"""Should return False if they the object doesn't have the property."""
self.failIf(mox.ContainsKeyValue("qux", 1) == self.test_object)
class InTest(unittest.TestCase):
"""Test In correctly identifies a key in a list/dict"""
def testItemInList(self):
"""Should return True if the item is in the list."""
self.assert_(mox.In(1) == [1, 2, 3])
def testKeyInDict(self):
"""Should return True if the item is a key in a dict."""
self.assert_(mox.In("test") == {"test" : "module"})
def testItemInTuple(self):
"""Should return True if the item is in the list."""
self.assert_(mox.In(1) == (1, 2, 3))
def testTupleInTupleOfTuples(self):
self.assert_(mox.In((1, 2, 3)) == ((1, 2, 3), (1, 2)))
def testItemNotInList(self):
self.failIf(mox.In(1) == [2, 3])
def testTupleNotInTupleOfTuples(self):
self.failIf(mox.In((1, 2)) == ((1, 2, 3), (4, 5)))
class NotTest(unittest.TestCase):
"""Test Not correctly identifies False predicates."""
def testItemInList(self):
"""Should return True if the item is NOT in the list."""
self.assert_(mox.Not(mox.In(42)) == [1, 2, 3])
def testKeyInDict(self):
"""Should return True if the item is NOT a key in a dict."""
self.assert_(mox.Not(mox.In("foo")) == {"key" : 42})
def testInvalidKeyWithNot(self):
"""Should return False if they key is NOT in the dict."""
self.assert_(mox.Not(mox.ContainsKeyValue("qux", 1)) == {"key": 2})
class StrContainsTest(unittest.TestCase):
"""Test StrContains correctly checks for substring occurrence of a parameter.
"""
def testValidSubstringAtStart(self):
"""Should return True if the substring is at the start of the string."""
self.assert_(mox.StrContains("hello") == "hello world")
def testValidSubstringInMiddle(self):
"""Should return True if the substring is in the middle of the string."""
self.assert_(mox.StrContains("lo wo") == "hello world")
def testValidSubstringAtEnd(self):
"""Should return True if the substring is at the end of the string."""
self.assert_(mox.StrContains("ld") == "hello world")
def testInvaildSubstring(self):
"""Should return False if the substring is not in the string."""
self.failIf(mox.StrContains("AAA") == "hello world")
def testMultipleMatches(self):
"""Should return True if there are multiple occurances of substring."""
self.assert_(mox.StrContains("abc") == "ababcabcabcababc")
class RegexTest(unittest.TestCase):
"""Test Regex correctly matches regular expressions."""
def testIdentifyBadSyntaxDuringInit(self):
"""The user should know immediately if a regex has bad syntax."""
self.assertRaises(re.error, mox.Regex, '(a|b')
def testPatternInMiddle(self):
"""Should return True if the pattern matches at the middle of the string.
This ensures that re.search is used (instead of re.find).
"""
self.assert_(mox.Regex(r"a\s+b") == "x y z a b c")
def testNonMatchPattern(self):
"""Should return False if the pattern does not match the string."""
self.failIf(mox.Regex(r"a\s+b") == "x y z")
def testFlagsPassedCorrectly(self):
"""Should return True as we pass IGNORECASE flag."""
self.assert_(mox.Regex(r"A", re.IGNORECASE) == "a")
def testReprWithoutFlags(self):
"""repr should return the regular expression pattern."""
self.assert_(repr(mox.Regex(r"a\s+b")) == "<regular expression 'a\s+b'>")
def testReprWithFlags(self):
"""repr should return the regular expression pattern and flags."""
self.assert_(repr(mox.Regex(r"a\s+b", flags=4)) ==
"<regular expression 'a\s+b', flags=4>")
class IsTest(unittest.TestCase):
"""Verify Is correctly checks equality based upon identity, not value"""
class AlwaysComparesTrue(object):
def __eq__(self, other):
return True
def __cmp__(self, other):
return 0
def __ne__(self, other):
return False
def testEqualityValid(self):
o1 = self.AlwaysComparesTrue()
self.assertTrue(mox.Is(o1), o1)
def testEqualityInvalid(self):
o1 = self.AlwaysComparesTrue()
o2 = self.AlwaysComparesTrue()
self.assertTrue(o1 == o2)
# but...
self.assertFalse(mox.Is(o1) == o2)
def testInequalityValid(self):
o1 = self.AlwaysComparesTrue()
o2 = self.AlwaysComparesTrue()
self.assertTrue(mox.Is(o1) != o2)
def testInequalityInvalid(self):
o1 = self.AlwaysComparesTrue()
self.assertFalse(mox.Is(o1) != o1)
def testEqualityInListValid(self):
o1 = self.AlwaysComparesTrue()
o2 = self.AlwaysComparesTrue()
isa_list = [mox.Is(o1), mox.Is(o2)]
str_list = [o1, o2]
self.assertTrue(isa_list == str_list)
def testEquailtyInListInvalid(self):
o1 = self.AlwaysComparesTrue()
o2 = self.AlwaysComparesTrue()
isa_list = [mox.Is(o1), mox.Is(o2)]
mixed_list = [o2, o1]
self.assertFalse(isa_list == mixed_list)
class IsATest(unittest.TestCase):
"""Verify IsA correctly checks equality based upon class type, not value."""
def testEqualityValid(self):
"""Verify that == correctly identifies objects of the same type."""
self.assert_(mox.IsA(str) == 'test')
def testEqualityInvalid(self):
"""Verify that == correctly identifies objects of different types."""
self.failIf(mox.IsA(str) == 10)
def testInequalityValid(self):
"""Verify that != identifies objects of different type."""
self.assert_(mox.IsA(str) != 10)
def testInequalityInvalid(self):
"""Verify that != correctly identifies objects of the same type."""
self.failIf(mox.IsA(str) != "test")
def testEqualityInListValid(self):
"""Verify list contents are properly compared."""
isa_list = [mox.IsA(str), mox.IsA(str)]
str_list = ["abc", "def"]
self.assert_(isa_list == str_list)
def testEquailtyInListInvalid(self):
"""Verify list contents are properly compared."""
isa_list = [mox.IsA(str),mox.IsA(str)]
mixed_list = ["abc", 123]
self.failIf(isa_list == mixed_list)
def testSpecialTypes(self):
"""Verify that IsA can handle objects like cStringIO.StringIO."""
isA = mox.IsA(cStringIO.StringIO())
stringIO = cStringIO.StringIO()
self.assert_(isA == stringIO)
class IsAlmostTest(unittest.TestCase):
"""Verify IsAlmost correctly checks equality of floating point numbers."""
def testEqualityValid(self):
"""Verify that == correctly identifies nearly equivalent floats."""
self.assertEquals(mox.IsAlmost(1.8999999999), 1.9)
def testEqualityInvalid(self):
"""Verify that == correctly identifies non-equivalent floats."""
self.assertNotEquals(mox.IsAlmost(1.899), 1.9)
def testEqualityWithPlaces(self):
"""Verify that specifying places has the desired effect."""
self.assertNotEquals(mox.IsAlmost(1.899), 1.9)
self.assertEquals(mox.IsAlmost(1.899, places=2), 1.9)
def testNonNumericTypes(self):
"""Verify that IsAlmost handles non-numeric types properly."""
self.assertNotEquals(mox.IsAlmost(1.8999999999), '1.9')
self.assertNotEquals(mox.IsAlmost('1.8999999999'), 1.9)
self.assertNotEquals(mox.IsAlmost('1.8999999999'), '1.9')
class ValueRememberTest(unittest.TestCase):
"""Verify comparing argument against remembered value."""
def testValueEquals(self):
"""Verify that value will compare to stored value."""
value = mox.Value()
value.store_value('hello world')
self.assertEquals(value, 'hello world')
def testNoValue(self):
"""Verify that uninitialized value does not compare to "empty" values."""
value = mox.Value()
self.assertNotEquals(value, None)
self.assertNotEquals(value, False)
self.assertNotEquals(value, 0)
self.assertNotEquals(value, '')
self.assertNotEquals(value, ())
self.assertNotEquals(value, [])
self.assertNotEquals(value, {})
self.assertNotEquals(value, object())
self.assertNotEquals(value, set())
def testRememberValue(self):
"""Verify that comparing against remember will store argument."""
value = mox.Value()
remember = mox.Remember(value)
self.assertNotEquals(value, 'hello world') # value not yet stored.
self.assertEquals(remember, 'hello world') # store value here.
self.assertEquals(value, 'hello world') # compare against stored value.
class MockMethodTest(unittest.TestCase):
"""Test class to verify that the MockMethod class is working correctly."""
def setUp(self):
self.expected_method = mox.MockMethod("testMethod", [], [], False)(
['original'])
self.mock_method = mox.MockMethod("testMethod", [self.expected_method], [],
True)
def testNameAttribute(self):
"""Should provide a __name__ attribute."""
self.assertEquals('testMethod', self.mock_method.__name__)
def testAndReturnNoneByDefault(self):
"""Should return None by default."""
return_value = self.mock_method(['original'])
self.assert_(return_value == None)
def testAndReturnValue(self):
"""Should return a specificed return value."""
expected_return_value = "test"
self.expected_method.AndReturn(expected_return_value)
return_value = self.mock_method(['original'])
self.assert_(return_value == expected_return_value)
def testAndRaiseException(self):
"""Should raise a specified exception."""
expected_exception = Exception('test exception')
self.expected_method.AndRaise(expected_exception)
self.assertRaises(Exception, self.mock_method)
def testWithSideEffects(self):
"""Should call state modifier."""
local_list = ['original']
def modifier(mutable_list):
self.assertTrue(local_list is mutable_list)
mutable_list[0] = 'mutation'
self.expected_method.WithSideEffects(modifier).AndReturn(1)
self.mock_method(local_list)
self.assertEquals('mutation', local_list[0])
def testWithReturningSideEffects(self):
"""Should call state modifier and propagate its return value."""
local_list = ['original']
expected_return = 'expected_return'
def modifier_with_return(mutable_list):
self.assertTrue(local_list is mutable_list)
mutable_list[0] = 'mutation'
return expected_return
self.expected_method.WithSideEffects(modifier_with_return)
actual_return = self.mock_method(local_list)
self.assertEquals('mutation', local_list[0])
self.assertEquals(expected_return, actual_return)
def testWithReturningSideEffectsWithAndReturn(self):
"""Should call state modifier and ignore its return value."""
local_list = ['original']
expected_return = 'expected_return'
unexpected_return = 'unexpected_return'
def modifier_with_return(mutable_list):
self.assertTrue(local_list is mutable_list)
mutable_list[0] = 'mutation'
return unexpected_return
self.expected_method.WithSideEffects(modifier_with_return).AndReturn(
expected_return)
actual_return = self.mock_method(local_list)
self.assertEquals('mutation', local_list[0])
self.assertEquals(expected_return, actual_return)
def testEqualityNoParamsEqual(self):
"""Methods with the same name and without params should be equal."""
expected_method = mox.MockMethod("testMethod", [], [], False)
self.assertEqual(self.mock_method, expected_method)
def testEqualityNoParamsNotEqual(self):
"""Methods with different names and without params should not be equal."""
expected_method = mox.MockMethod("otherMethod", [], [], False)
self.failIfEqual(self.mock_method, expected_method)
def testEqualityParamsEqual(self):
"""Methods with the same name and parameters should be equal."""
params = [1, 2, 3]
expected_method = mox.MockMethod("testMethod", [], [], False)
expected_method._params = params
self.mock_method._params = params
self.assertEqual(self.mock_method, expected_method)
def testEqualityParamsNotEqual(self):
"""Methods with the same name and different params should not be equal."""
expected_method = mox.MockMethod("testMethod", [], [], False)
expected_method._params = [1, 2, 3]
self.mock_method._params = ['a', 'b', 'c']
self.failIfEqual(self.mock_method, expected_method)
def testEqualityNamedParamsEqual(self):
"""Methods with the same name and same named params should be equal."""
named_params = {"input1": "test", "input2": "params"}
expected_method = mox.MockMethod("testMethod", [], [], False)
expected_method._named_params = named_params
self.mock_method._named_params = named_params
self.assertEqual(self.mock_method, expected_method)
def testEqualityNamedParamsNotEqual(self):
"""Methods with the same name and diffnamed params should not be equal."""
expected_method = mox.MockMethod("testMethod", [], [], False)
expected_method._named_params = {"input1": "test", "input2": "params"}
self.mock_method._named_params = {"input1": "test2", "input2": "params2"}
self.failIfEqual(self.mock_method, expected_method)
def testEqualityWrongType(self):
"""Method should not be equal to an object of a different type."""
self.failIfEqual(self.mock_method, "string?")
def testObjectEquality(self):
"""Equality of objects should work without a Comparator"""
instA = TestClass();
instB = TestClass();
params = [instA, ]
expected_method = mox.MockMethod("testMethod", [], [], False)
expected_method._params = params
self.mock_method._params = [instB, ]
self.assertEqual(self.mock_method, expected_method)
def testStrConversion(self):
method = mox.MockMethod("f", [], [], False)
method(1, 2, "st", n1=8, n2="st2")
self.assertEqual(str(method), ("f(1, 2, 'st', n1=8, n2='st2') -> None"))
method = mox.MockMethod("testMethod", [], [], False)
method(1, 2, "only positional")
self.assertEqual(str(method), "testMethod(1, 2, 'only positional') -> None")
method = mox.MockMethod("testMethod", [], [], False)
method(a=1, b=2, c="only named")
self.assertEqual(str(method),
"testMethod(a=1, b=2, c='only named') -> None")
method = mox.MockMethod("testMethod", [], [], False)
method()
self.assertEqual(str(method), "testMethod() -> None")
method = mox.MockMethod("testMethod", [], [], False)
method(x="only 1 parameter")
self.assertEqual(str(method), "testMethod(x='only 1 parameter') -> None")
method = mox.MockMethod("testMethod", [], [], False)
method().AndReturn('return_value')
self.assertEqual(str(method), "testMethod() -> 'return_value'")
method = mox.MockMethod("testMethod", [], [], False)
method().AndReturn(('a', {1: 2}))
self.assertEqual(str(method), "testMethod() -> ('a', {1: 2})")
class MockAnythingTest(unittest.TestCase):
"""Verify that the MockAnything class works as expected."""
def setUp(self):
self.mock_object = mox.MockAnything()
def testRepr(self):
"""Calling repr on a MockAnything instance must work."""
self.assertEqual('<MockAnything instance>', repr(self.mock_object))
def testCanMockStr(self):
self.mock_object.__str__().AndReturn("foo");
self.mock_object._Replay()
actual = str(self.mock_object)
self.mock_object._Verify();
self.assertEquals("foo", actual)
def testSetupMode(self):
"""Verify the mock will accept any call."""
self.mock_object.NonsenseCall()
self.assert_(len(self.mock_object._expected_calls_queue) == 1)
def testReplayWithExpectedCall(self):
"""Verify the mock replays method calls as expected."""
self.mock_object.ValidCall() # setup method call
self.mock_object._Replay() # start replay mode
self.mock_object.ValidCall() # make method call
def testReplayWithUnexpectedCall(self):
"""Unexpected method calls should raise UnexpectedMethodCallError."""
self.mock_object.ValidCall() # setup method call
self.mock_object._Replay() # start replay mode
self.assertRaises(mox.UnexpectedMethodCallError,
self.mock_object.OtherValidCall)
def testVerifyWithCompleteReplay(self):
"""Verify should not raise an exception for a valid replay."""
self.mock_object.ValidCall() # setup method call
self.mock_object._Replay() # start replay mode
self.mock_object.ValidCall() # make method call
self.mock_object._Verify()
def testVerifyWithIncompleteReplay(self):
"""Verify should raise an exception if the replay was not complete."""
self.mock_object.ValidCall() # setup method call
self.mock_object._Replay() # start replay mode
# ValidCall() is never made
self.assertRaises(mox.ExpectedMethodCallsError, self.mock_object._Verify)
def testSpecialClassMethod(self):
"""Verify should not raise an exception when special methods are used."""
self.mock_object[1].AndReturn(True)
self.mock_object._Replay()
returned_val = self.mock_object[1]
self.assert_(returned_val)
self.mock_object._Verify()
def testNonzero(self):
"""You should be able to use the mock object in an if."""
self.mock_object._Replay()
if self.mock_object:
pass
def testNotNone(self):
"""Mock should be comparable to None."""
self.mock_object._Replay()
if self.mock_object is not None:
pass
if self.mock_object is None:
pass
def testEquals(self):
"""A mock should be able to compare itself to another object."""
self.mock_object._Replay()
self.assertEquals(self.mock_object, self.mock_object)
def testEqualsMockFailure(self):
"""Verify equals identifies unequal objects."""
self.mock_object.SillyCall()
self.mock_object._Replay()
self.assertNotEquals(self.mock_object, mox.MockAnything())
def testEqualsInstanceFailure(self):
"""Verify equals identifies that objects are different instances."""
self.mock_object._Replay()
self.assertNotEquals(self.mock_object, TestClass())
def testNotEquals(self):
"""Verify not equals works."""
self.mock_object._Replay()
self.assertFalse(self.mock_object != self.mock_object)
def testNestedMockCallsRecordedSerially(self):
"""Test that nested calls work when recorded serially."""
self.mock_object.CallInner().AndReturn(1)
self.mock_object.CallOuter(1)
self.mock_object._Replay()
self.mock_object.CallOuter(self.mock_object.CallInner())
self.mock_object._Verify()
def testNestedMockCallsRecordedNested(self):
"""Test that nested cals work when recorded in a nested fashion."""
self.mock_object.CallOuter(self.mock_object.CallInner().AndReturn(1))
self.mock_object._Replay()
self.mock_object.CallOuter(self.mock_object.CallInner())
self.mock_object._Verify()
def testIsCallable(self):
"""Test that MockAnything can even mock a simple callable.
This is handy for "stubbing out" a method in a module with a mock, and
verifying that it was called.
"""
self.mock_object().AndReturn('mox0rd')
self.mock_object._Replay()
self.assertEquals('mox0rd', self.mock_object())
self.mock_object._Verify()
def testIsReprable(self):
"""Test that MockAnythings can be repr'd without causing a failure."""
self.failUnless('MockAnything' in repr(self.mock_object))
class MethodCheckerTest(unittest.TestCase):
"""Tests MockMethod's use of MethodChecker method."""
def testNoParameters(self):
method = mox.MockMethod('NoParameters', [], [], False,
CheckCallTestClass.NoParameters)
method()
self.assertRaises(AttributeError, method, 1)
self.assertRaises(AttributeError, method, 1, 2)
self.assertRaises(AttributeError, method, a=1)
self.assertRaises(AttributeError, method, 1, b=2)
def testOneParameter(self):
method = mox.MockMethod('OneParameter', [], [], False,
CheckCallTestClass.OneParameter)
self.assertRaises(AttributeError, method)
method(1)
method(a=1)
self.assertRaises(AttributeError, method, b=1)
self.assertRaises(AttributeError, method, 1, 2)
self.assertRaises(AttributeError, method, 1, a=2)
self.assertRaises(AttributeError, method, 1, b=2)
def testTwoParameters(self):
method = mox.MockMethod('TwoParameters', [], [], False,
CheckCallTestClass.TwoParameters)
self.assertRaises(AttributeError, method)
self.assertRaises(AttributeError, method, 1)
self.assertRaises(AttributeError, method, a=1)
self.assertRaises(AttributeError, method, b=1)
method(1, 2)
method(1, b=2)
method(a=1, b=2)
method(b=2, a=1)
self.assertRaises(AttributeError, method, b=2, c=3)
self.assertRaises(AttributeError, method, a=1, b=2, c=3)
self.assertRaises(AttributeError, method, 1, 2, 3)
self.assertRaises(AttributeError, method, 1, 2, 3, 4)
self.assertRaises(AttributeError, method, 3, a=1, b=2)
def testOneDefaultValue(self):
method = mox.MockMethod('OneDefaultValue', [], [], False,
CheckCallTestClass.OneDefaultValue)
method()
method(1)
method(a=1)
self.assertRaises(AttributeError, method, b=1)
self.assertRaises(AttributeError, method, 1, 2)
self.assertRaises(AttributeError, method, 1, a=2)
self.assertRaises(AttributeError, method, 1, b=2)
def testTwoDefaultValues(self):
method = mox.MockMethod('TwoDefaultValues', [], [], False,
CheckCallTestClass.TwoDefaultValues)
self.assertRaises(AttributeError, method)
self.assertRaises(AttributeError, method, c=3)
self.assertRaises(AttributeError, method, 1)
self.assertRaises(AttributeError, method, 1, d=4)
self.assertRaises(AttributeError, method, 1, d=4, c=3)
method(1, 2)
method(a=1, b=2)
method(1, 2, 3)
method(1, 2, 3, 4)
method(1, 2, c=3)
method(1, 2, c=3, d=4)
method(1, 2, d=4, c=3)
method(d=4, c=3, a=1, b=2)
self.assertRaises(AttributeError, method, 1, 2, 3, 4, 5)
self.assertRaises(AttributeError, method, 1, 2, e=9)
self.assertRaises(AttributeError, method, a=1, b=2, e=9)
def testArgs(self):
method = mox.MockMethod('Args', [], [], False, CheckCallTestClass.Args)
self.assertRaises(AttributeError, method)
self.assertRaises(AttributeError, method, 1)
method(1, 2)
method(a=1, b=2)
method(1, 2, 3)
method(1, 2, 3, 4)
self.assertRaises(AttributeError, method, 1, 2, a=3)
self.assertRaises(AttributeError, method, 1, 2, c=3)
def testKwargs(self):
method = mox.MockMethod('Kwargs', [], [], False, CheckCallTestClass.Kwargs)
self.assertRaises(AttributeError, method)
method(1)
method(1, 2)
method(a=1, b=2)
method(b=2, a=1)
self.assertRaises(AttributeError, method, 1, 2, 3)
self.assertRaises(AttributeError, method, 1, 2, a=3)
method(1, 2, c=3)
method(a=1, b=2, c=3)
method(c=3, a=1, b=2)
method(a=1, b=2, c=3, d=4)
self.assertRaises(AttributeError, method, 1, 2, 3, 4)
def testArgsAndKwargs(self):
method = mox.MockMethod('ArgsAndKwargs', [], [], False,
CheckCallTestClass.ArgsAndKwargs)
self.assertRaises(AttributeError, method)
method(1)
method(1, 2)
method(1, 2, 3)
method(a=1)
method(1, b=2)
self.assertRaises(AttributeError, method, 1, a=2)
method(b=2, a=1)
method(c=3, b=2, a=1)
method(1, 2, c=3)
class CheckCallTestClass(object):
def NoParameters(self):
pass
def OneParameter(self, a):
pass
def TwoParameters(self, a, b):
pass
def OneDefaultValue(self, a=1):
pass
def TwoDefaultValues(self, a, b, c=1, d=2):
pass
def Args(self, a, b, *args):
pass
def Kwargs(self, a, b=2, **kwargs):
pass
def ArgsAndKwargs(self, a, *args, **kwargs):
pass
class MockObjectTest(unittest.TestCase):
"""Verify that the MockObject class works as exepcted."""
def setUp(self):
self.mock_object = mox.MockObject(TestClass)
def testSetupModeWithValidCall(self):
"""Verify the mock object properly mocks a basic method call."""
self.mock_object.ValidCall()
self.assert_(len(self.mock_object._expected_calls_queue) == 1)
def testSetupModeWithInvalidCall(self):
"""UnknownMethodCallError should be raised if a non-member method is called.
"""
# Note: assertRaises does not catch exceptions thrown by MockObject's
# __getattr__
try:
self.mock_object.InvalidCall()
self.fail("No exception thrown, expected UnknownMethodCallError")
except mox.UnknownMethodCallError:
pass
except Exception:
self.fail("Wrong exception type thrown, expected UnknownMethodCallError")
def testReplayWithInvalidCall(self):
"""UnknownMethodCallError should be raised if a non-member method is called.
"""
self.mock_object.ValidCall() # setup method call
self.mock_object._Replay() # start replay mode
# Note: assertRaises does not catch exceptions thrown by MockObject's
# __getattr__
try:
self.mock_object.InvalidCall()
self.fail("No exception thrown, expected UnknownMethodCallError")
except mox.UnknownMethodCallError:
pass
except Exception:
self.fail("Wrong exception type thrown, expected UnknownMethodCallError")
def testIsInstance(self):
"""Mock should be able to pass as an instance of the mocked class."""
self.assert_(isinstance(self.mock_object, TestClass))
def testFindValidMethods(self):
"""Mock should be able to mock all public methods."""
self.assert_('ValidCall' in self.mock_object._known_methods)
self.assert_('OtherValidCall' in self.mock_object._known_methods)
self.assert_('MyClassMethod' in self.mock_object._known_methods)
self.assert_('MyStaticMethod' in self.mock_object._known_methods)
self.assert_('_ProtectedCall' in self.mock_object._known_methods)
self.assert_('__PrivateCall' not in self.mock_object._known_methods)
self.assert_('_TestClass__PrivateCall' in self.mock_object._known_methods)
def testFindsSuperclassMethods(self):
"""Mock should be able to mock superclasses methods."""
self.mock_object = mox.MockObject(ChildClass)
self.assert_('ValidCall' in self.mock_object._known_methods)
self.assert_('OtherValidCall' in self.mock_object._known_methods)
self.assert_('MyClassMethod' in self.mock_object._known_methods)
self.assert_('ChildValidCall' in self.mock_object._known_methods)
def testAccessClassVariables(self):
"""Class variables should be accessible through the mock."""
self.assert_('SOME_CLASS_VAR' in self.mock_object._known_vars)
self.assert_('_PROTECTED_CLASS_VAR' in self.mock_object._known_vars)
self.assertEquals('test_value', self.mock_object.SOME_CLASS_VAR)
def testEquals(self):
"""A mock should be able to compare itself to another object."""
self.mock_object._Replay()
self.assertEquals(self.mock_object, self.mock_object)
def testEqualsMockFailure(self):
"""Verify equals identifies unequal objects."""
self.mock_object.ValidCall()
self.mock_object._Replay()
self.assertNotEquals(self.mock_object, mox.MockObject(TestClass))
def testEqualsInstanceFailure(self):
"""Verify equals identifies that objects are different instances."""
self.mock_object._Replay()
self.assertNotEquals(self.mock_object, TestClass())
def testNotEquals(self):
"""Verify not equals works."""
self.mock_object._Replay()
self.assertFalse(self.mock_object != self.mock_object)
def testMockSetItem_ExpectedSetItem_Success(self):
"""Test that __setitem__() gets mocked in Dummy.
In this test, _Verify() succeeds.
"""
dummy = mox.MockObject(TestClass)
dummy['X'] = 'Y'
dummy._Replay()
dummy['X'] = 'Y'
dummy._Verify()
def testMockSetItem_ExpectedSetItem_NoSuccess(self):
"""Test that __setitem__() gets mocked in Dummy.
In this test, _Verify() fails.
"""
dummy = mox.MockObject(TestClass)
dummy['X'] = 'Y'
dummy._Replay()
# NOT doing dummy['X'] = 'Y'
self.assertRaises(mox.ExpectedMethodCallsError, dummy._Verify)