1# -*- coding: utf-8 -*-
2from flexmock import EXACTLY
3from flexmock import AT_LEAST
4from flexmock import AT_MOST
5from flexmock import UPDATED_ATTRS
6from flexmock import Mock
7from flexmock import MockBuiltinError
8from flexmock import FlexmockContainer
9from flexmock import FlexmockError
10from flexmock import MethodSignatureError
11from flexmock import ExceptionClassError
12from flexmock import ExceptionMessageError
13from flexmock import StateError
14from flexmock import MethodCallError
15from flexmock import CallOrderError
16from flexmock import ReturnValue
17from flexmock import flexmock_teardown
18from flexmock import _format_args
19from flexmock import _isproperty
20from flexmock import _is_class_method
21from flexmock import _is_static_method
22import flexmock
23import random
24import os
25import re
26import sys
27import unittest
28
29
30import some_module
31from proxy import Proxy
32
33
34def module_level_function(some, args):
35    return "%s, %s" % (some, args)
36
37
38module_level_attribute = 'test'
39
40class SomeClass:
41    CLASS_VALUE = "class_method"
42
43    def __init__(self):
44        self.instance_value = "instance_method"
45
46    @classmethod
47    def class_method(cls):
48        return cls.CLASS_VALUE
49
50    @classmethod
51    def class_method_with_args(cls, a):
52        return a
53
54    @staticmethod
55    def static_method():
56        return "static_method"
57
58    @staticmethod
59    def static_method_with_args(a):
60        return a
61
62    def instance_method(self):
63        return self.instance_value
64
65    def instance_method_with_args(self, a):
66        return a
67
68
69class DerivedClass(SomeClass):
70    pass
71
72class OldStyleClass:
73    pass
74
75
76class NewStyleClass(object):
77    pass
78
79
80def assertRaises(exception, method, *kargs, **kwargs):
81    try:
82        method(*kargs, **kwargs)
83    except exception:
84        return
85    except:
86        instance = sys.exc_info()[1]
87        print('%s' % instance)
88    raise Exception('%s not raised' % exception.__name__)
89
90
91def assertEqual(expected, received, msg=''):
92    if not msg:
93        msg = 'expected %s, received %s' % (expected, received)
94    if expected != received:
95        raise AssertionError('%s != %s : %s' % (expected, received, msg))
96
97
98class RegularClass(object):
99
100    def _tear_down(self):
101        return flexmock_teardown()
102
103    def test_flexmock_should_create_mock_object(self):
104        mock = flexmock()
105        assert isinstance(mock, Mock)
106
107    def test_flexmock_should_create_mock_object_from_dict(self):
108        mock = flexmock(foo='foo', bar='bar')
109        assertEqual('foo',  mock.foo)
110        assertEqual('bar', mock.bar)
111
112    def test_flexmock_should_add_expectations(self):
113        mock = flexmock(name='temp')
114        mock.should_receive('method_foo')
115        assert ('method_foo' in
116                [x.name for x in FlexmockContainer.flexmock_objects[mock]])
117
118    def test_flexmock_should_return_value(self):
119        mock = flexmock(name='temp')
120        mock.should_receive('method_foo').and_return('value_bar')
121        mock.should_receive('method_bar').and_return('value_baz')
122        assertEqual('value_bar', mock.method_foo())
123        assertEqual('value_baz', mock.method_bar())
124
125    def test_type_flexmock_with_unicode_string_in_should_receive(self):
126        class Foo(object):
127            def bar(self): return 'bar'
128
129        flexmock(Foo).should_receive(u'bar').and_return('mocked_bar')
130
131        foo = Foo()
132        assertEqual('mocked_bar', foo.bar())
133
134    def test_flexmock_should_accept_shortcuts_for_creating_mock_object(self):
135        mock = flexmock(attr1='value 1', attr2=lambda: 'returning 2')
136        assertEqual('value 1', mock.attr1)
137        assertEqual('returning 2',  mock.attr2())
138
139    def test_flexmock_should_accept_shortcuts_for_creating_expectations(self):
140        class Foo:
141            def method1(self):
142                pass
143
144            def method2(self):
145                pass
146
147        foo = Foo()
148        flexmock(foo, method1='returning 1', method2='returning 2')
149        assertEqual('returning 1', foo.method1())
150        assertEqual('returning 2', foo.method2())
151        assertEqual('returning 2', foo.method2())
152
153    def test_flexmock_expectations_returns_all(self):
154        mock = flexmock(name='temp')
155        assert mock not in FlexmockContainer.flexmock_objects
156        mock.should_receive('method_foo')
157        mock.should_receive('method_bar')
158        assertEqual(2, len(FlexmockContainer.flexmock_objects[mock]))
159
160    def test_flexmock_expectations_returns_named_expectation(self):
161        mock = flexmock(name='temp')
162        mock.should_receive('method_foo')
163        assertEqual('method_foo',
164                    FlexmockContainer.get_flexmock_expectation(mock, 'method_foo').name)
165
166    def test_flexmock_expectations_returns_none_if_not_found(self):
167        mock = flexmock(name='temp')
168        mock.should_receive('method_foo')
169        assert (FlexmockContainer.get_flexmock_expectation(mock, 'method_bar') is None)
170
171    def test_flexmock_should_check_parameters(self):
172        mock = flexmock(name='temp')
173        mock.should_receive('method_foo').with_args('bar').and_return(1)
174        mock.should_receive('method_foo').with_args('baz').and_return(2)
175        assertEqual(1, mock.method_foo('bar'))
176        assertEqual(2, mock.method_foo('baz'))
177
178    def test_flexmock_should_keep_track_of_calls(self):
179        mock = flexmock(name='temp')
180        mock.should_receive('method_foo').with_args('foo').and_return(0)
181        mock.should_receive('method_foo').with_args('bar').and_return(1)
182        mock.should_receive('method_foo').with_args('baz').and_return(2)
183        mock.method_foo('bar')
184        mock.method_foo('bar')
185        mock.method_foo('baz')
186        expectation = FlexmockContainer.get_flexmock_expectation(
187            mock, 'method_foo', ('foo',))
188        assertEqual(0, expectation.times_called)
189        expectation = FlexmockContainer.get_flexmock_expectation(
190            mock, 'method_foo', ('bar',))
191        assertEqual(2, expectation.times_called)
192        expectation = FlexmockContainer.get_flexmock_expectation(
193            mock, 'method_foo', ('baz',))
194        assertEqual(1, expectation.times_called)
195
196    def test_flexmock_should_set_expectation_call_numbers(self):
197        mock = flexmock(name='temp')
198        mock.should_receive('method_foo').times(1)
199        expectation = FlexmockContainer.get_flexmock_expectation(mock, 'method_foo')
200        assertRaises(MethodCallError, expectation.verify)
201        mock.method_foo()
202        expectation.verify()
203
204    def test_flexmock_should_check_raised_exceptions(self):
205        mock = flexmock(name='temp')
206
207        class FakeException(Exception):
208            pass
209
210        mock.should_receive('method_foo').and_raise(FakeException)
211        assertRaises(FakeException, mock.method_foo)
212        assertEqual(1,
213                    FlexmockContainer.get_flexmock_expectation(
214                        mock, 'method_foo').times_called)
215
216    def test_flexmock_should_check_raised_exceptions_instance_with_args(self):
217        mock = flexmock(name='temp')
218
219        class FakeException(Exception):
220            def __init__(self, arg, arg2):
221                pass
222
223        mock.should_receive('method_foo').and_raise(FakeException(1, arg2=2))
224        assertRaises(FakeException, mock.method_foo)
225        assertEqual(1,
226                    FlexmockContainer.get_flexmock_expectation(
227                        mock, 'method_foo').times_called)
228
229    def test_flexmock_should_check_raised_exceptions_class_with_args(self):
230        mock = flexmock(name='temp')
231
232        class FakeException(Exception):
233            def __init__(self, arg, arg2):
234                pass
235
236        mock.should_receive('method_foo').and_raise(FakeException, 1, arg2=2)
237        assertRaises(FakeException, mock.method_foo)
238        assertEqual(1,
239                    FlexmockContainer.get_flexmock_expectation(
240                        mock, 'method_foo').times_called)
241
242    def test_flexmock_should_match_any_args_by_default(self):
243        mock = flexmock(name='temp')
244        mock.should_receive('method_foo').and_return('bar')
245        mock.should_receive('method_foo').with_args('baz').and_return('baz')
246        assertEqual('bar', mock.method_foo())
247        assertEqual('bar', mock.method_foo(1))
248        assertEqual('bar', mock.method_foo('foo', 'bar'))
249        assertEqual('baz', mock.method_foo('baz'))
250
251    def test_flexmock_should_fail_to_match_exactly_no_args_when_calling_with_args(self):
252        mock = flexmock()
253        mock.should_receive('method_foo').with_args()
254        assertRaises(MethodSignatureError, mock.method_foo, 'baz')
255
256    def test_flexmock_should_match_exactly_no_args(self):
257        class Foo:
258            def bar(self): pass
259        foo = Foo()
260        flexmock(foo).should_receive('bar').with_args().and_return('baz')
261        assertEqual('baz', foo.bar())
262
263    def test_expectation_dot_mock_should_return_mock(self):
264        mock = flexmock(name='temp')
265        assertEqual(mock, mock.should_receive('method_foo').mock)
266
267    def test_flexmock_should_create_partial_new_style_object_mock(self):
268        class User(object):
269            def __init__(self, name=None):
270                self.name = name
271
272            def get_name(self):
273                return self.name
274
275            def set_name(self, name):
276                self.name = name
277
278        user = User()
279        flexmock(user)
280        user.should_receive('get_name').and_return('john')
281        user.set_name('mike')
282        assertEqual('john', user.get_name())
283
284    def test_flexmock_should_create_partial_old_style_object_mock(self):
285        class User:
286            def __init__(self, name=None):
287                self.name = name
288
289            def get_name(self):
290                return self.name
291
292            def set_name(self, name):
293                self.name = name
294
295        user = User()
296        flexmock(user)
297        user.should_receive('get_name').and_return('john')
298        user.set_name('mike')
299        assertEqual('john', user.get_name())
300
301    def test_flexmock_should_create_partial_new_style_class_mock(self):
302        class User(object):
303            def __init__(self):
304                pass
305
306            def get_name(self):
307                pass
308
309        flexmock(User)
310        User.should_receive('get_name').and_return('mike')
311        user = User()
312        assertEqual('mike', user.get_name())
313
314    def test_flexmock_should_create_partial_old_style_class_mock(self):
315        class User:
316            def __init__(self):
317                pass
318
319            def get_name(self):
320                pass
321
322        flexmock(User)
323        User.should_receive('get_name').and_return('mike')
324        user = User()
325        assertEqual('mike', user.get_name())
326
327    def test_flexmock_should_match_expectations_against_builtin_classes(self):
328        mock = flexmock(name='temp')
329        mock.should_receive('method_foo').with_args(str).and_return('got a string')
330        mock.should_receive('method_foo').with_args(int).and_return('got an int')
331        assertEqual('got a string', mock.method_foo('string!'))
332        assertEqual('got an int', mock.method_foo(23))
333        assertRaises(MethodSignatureError, mock.method_foo, 2.0)
334
335    def test_with_args_should_work_with_builtin_c_methods(self):
336        if sys.version_info > (3, 0):
337            flexmock(sys.stdout).should_call("write")  # set fall-through
338            flexmock(sys.stdout).should_receive("write").with_args("flexmock_builtin_test")
339            sys.stdout.write("flexmock_builtin_test")
340
341    def test_with_args_should_work_with_builtin_c_functions(self):
342        mocked = flexmock(sys)
343        mocked.should_receive("exit").with_args(1).once()
344        mocked.exit(1)
345        self._tear_down()
346        flexmock(os).should_receive("remove").with_args("path").once()
347        os.remove("path")
348
349    def test_with_args_should_work_with_builtin_python_methods(self):
350        flexmock(random).should_receive("randint").with_args(1, 10).once()
351        random.randint(1, 10)
352
353    def test_with_args_with_instance_method(self):
354        flexmock(SomeClass).should_receive("instance_method_with_args").with_args("red").once()
355        flexmock(SomeClass).should_receive("instance_method_with_args").with_args("blue").once()
356        instance = SomeClass()
357        instance.instance_method_with_args("red")
358        instance.instance_method_with_args("blue")
359
360    def test_with_args_with_class_method(self):
361        flexmock(SomeClass).should_receive("class_method_with_args").with_args("red").once()
362        flexmock(SomeClass).should_receive("class_method_with_args").with_args("blue").once()
363        SomeClass.class_method_with_args("red")
364        SomeClass.class_method_with_args("blue")
365
366    def test_with_args_with_static_method(self):
367        flexmock(SomeClass).should_receive("static_method_with_args").with_args("red").once()
368        flexmock(SomeClass).should_receive("static_method_with_args").with_args("blue").once()
369        SomeClass.static_method_with_args("red")
370        SomeClass.static_method_with_args("blue")
371
372    def test_mock_class_method_on_derived_class(self):
373        flexmock(DerivedClass).should_receive("class_method").and_return(2).twice()
374        assert DerivedClass().class_method() == 2
375        assert DerivedClass.class_method() == 2
376
377    def test_mock_class_method_on_derived_class_after_mocking_base_class(self):
378        flexmock(SomeClass).should_receive("class_method").and_return(1).once()
379        assert SomeClass.class_method() == 1
380        flexmock(DerivedClass).should_receive("class_method").and_return(2).twice()
381        assert DerivedClass().class_method() == 2
382        assert DerivedClass.class_method() == 2
383
384    def test_mock_static_method_on_derived_class(self):
385        flexmock(DerivedClass).should_receive("static_method").and_return(4).twice()
386        assert DerivedClass().static_method() == 4
387        assert DerivedClass.static_method() == 4
388
389    def test_mock_static_method_on_derived_class_after_mocking_base_class(self):
390        flexmock(SomeClass).should_receive("static_method").and_return(3).once()
391        assert SomeClass.static_method() == 3
392        flexmock(DerivedClass).should_receive("static_method").and_return(4).twice()
393        assert DerivedClass().static_method() == 4
394        assert DerivedClass.static_method() == 4
395
396    def test_mock_class_method_with_args_on_derived_class(self):
397        flexmock(DerivedClass).should_receive("class_method_with_args").with_args(2).and_return(
398            3
399        ).twice()
400        assert DerivedClass().class_method_with_args(2) == 3
401        assert DerivedClass.class_method_with_args(2) == 3
402
403    def test_mock_class_method_with_args_on_derived_class_after_mocking_base_class(self):
404        flexmock(SomeClass).should_receive("class_method_with_args").with_args(1).and_return(
405            2
406        ).once()
407        assert SomeClass.class_method_with_args(1) == 2
408        flexmock(DerivedClass).should_receive("class_method_with_args").with_args(2).and_return(
409            3
410        ).twice()
411        assert DerivedClass().class_method_with_args(2) == 3
412        assert DerivedClass.class_method_with_args(2) == 3
413
414    def test_mock_static_method_with_args_on_derived_class(self):
415        flexmock(DerivedClass).should_receive("static_method_with_args").with_args(4).and_return(
416            5
417        ).twice()
418        assert DerivedClass().static_method_with_args(4) == 5
419        assert DerivedClass.static_method_with_args(4) == 5
420
421    def test_mock_static_method_with_args_on_derived_class_after_mocking_base_class(self):
422        flexmock(SomeClass).should_receive("static_method_with_args").with_args(2).and_return(
423            3
424        ).once()
425        assert SomeClass.static_method_with_args(2) == 3
426        flexmock(DerivedClass).should_receive("static_method_with_args").with_args(4).and_return(
427            5
428        ).twice()
429        assert DerivedClass().static_method_with_args(4) == 5
430        assert DerivedClass.static_method_with_args(4) == 5
431
432    def test_spy_class_method_on_derived_class(self):
433        flexmock(DerivedClass).should_call("class_method").and_return("class_method").twice()
434        assert DerivedClass().class_method() == "class_method"
435        assert DerivedClass.class_method() == "class_method"
436
437    def test_spy_class_method_on_derived_class_after_spying_base_class(self):
438        flexmock(SomeClass).should_call("class_method").and_return("class_method").times(3)
439        assert SomeClass.class_method() == "class_method"
440        flexmock(DerivedClass).should_call("class_method").and_return("class_method").twice()
441        assert DerivedClass().class_method() == "class_method"
442        assert DerivedClass.class_method() == "class_method"
443
444    def test_spy_static_method_on_derived_class(self):
445        flexmock(DerivedClass).should_call("static_method").and_return("static_method").twice()
446        assert DerivedClass().static_method() == "static_method"
447        assert DerivedClass.static_method() == "static_method"
448
449    def test_spy_static_method_on_derived_class_after_spying_base_class(self):
450        flexmock(SomeClass).should_call("static_method").and_return("static_method").times(3)
451        assert SomeClass.static_method() == "static_method"
452        flexmock(DerivedClass).should_call("static_method").and_return("static_method").twice()
453        assert DerivedClass().static_method() == "static_method"
454        assert DerivedClass.static_method() == "static_method"
455
456    def test_spy_class_method_with_args_on_derived_class(self):
457        flexmock(DerivedClass).should_call("class_method_with_args").with_args(2).and_return(2)
458        assert DerivedClass().class_method_with_args(2) == 2
459        assert DerivedClass.class_method_with_args(2) == 2
460
461    def test_spy_static_method_with_args_on_derived_class(self):
462        flexmock(DerivedClass).should_call("static_method_with_args").with_args(4).and_return(
463            4
464        ).twice()
465        assert DerivedClass().static_method_with_args(4) == 4
466        assert DerivedClass.static_method_with_args(4) == 4
467
468    def test_flexmock_should_match_expectations_against_user_defined_classes(self):
469        mock = flexmock(name='temp')
470
471        class Foo:
472            pass
473
474        mock.should_receive('method_foo').with_args(Foo).and_return('got a Foo')
475        assertEqual('got a Foo', mock.method_foo(Foo()))
476        assertRaises(MethodSignatureError, mock.method_foo, 1)
477
478    def test_flexmock_configures_global_mocks_dict(self):
479        mock = flexmock(name='temp')
480        assert mock not in FlexmockContainer.flexmock_objects
481        mock.should_receive('method_foo')
482        assert mock in FlexmockContainer.flexmock_objects
483        assertEqual(len(FlexmockContainer.flexmock_objects[mock]), 1)
484
485    def test_flexmock_teardown_verifies_mocks(self):
486        mock = flexmock(name='temp')
487        mock.should_receive('verify_expectations').times(1)
488        assertRaises(MethodCallError, self._tear_down)
489
490    def test_flexmock_teardown_does_not_verify_stubs(self):
491        mock = flexmock(name='temp')
492        mock.should_receive('verify_expectations')
493        self._tear_down()
494
495    def test_flexmock_preserves_stubbed_object_methods_between_tests(self):
496        class User:
497            def get_name(self):
498                return 'mike'
499        user = User()
500        flexmock(user).should_receive('get_name').and_return('john')
501        assertEqual('john', user.get_name())
502        self._tear_down()
503        assertEqual('mike', user.get_name())
504
505    def test_flexmock_preserves_stubbed_class_methods_between_tests(self):
506        class User:
507            def get_name(self):
508                return 'mike'
509        user = User()
510        flexmock(User).should_receive('get_name').and_return('john')
511        assertEqual('john', user.get_name())
512        self._tear_down()
513        assertEqual('mike', user.get_name())
514
515    def test_flexmock_removes_new_stubs_from_objects_after_tests(self):
516        class User:
517            def get_name(self): pass
518        user = User()
519        saved = user.get_name
520        flexmock(user).should_receive('get_name').and_return('john')
521        assert saved != user.get_name
522        assertEqual('john', user.get_name())
523        self._tear_down()
524        assertEqual(saved, user.get_name)
525
526    def test_flexmock_removes_new_stubs_from_classes_after_tests(self):
527        class User:
528            def get_name(self): pass
529        user = User()
530        saved = user.get_name
531        flexmock(User).should_receive('get_name').and_return('john')
532        assert saved != user.get_name
533        assertEqual('john', user.get_name())
534        self._tear_down()
535        assertEqual(saved, user.get_name)
536
537    def test_flexmock_removes_stubs_from_multiple_objects_on_teardown(self):
538        class User:
539            def get_name(self): pass
540
541        class Group:
542            def get_name(self): pass
543
544        user = User()
545        group = User()
546        saved1 = user.get_name
547        saved2 = group.get_name
548        flexmock(user).should_receive('get_name').and_return('john').once()
549        flexmock(group).should_receive('get_name').and_return('john').once()
550        assert saved1 != user.get_name
551        assert saved2 != group.get_name
552        assertEqual('john', user.get_name())
553        assertEqual('john', group.get_name())
554        self._tear_down()
555        assertEqual(saved1, user.get_name)
556        assertEqual(saved2, group.get_name)
557
558    def test_flexmock_removes_stubs_from_multiple_classes_on_teardown(self):
559        class User:
560            def get_name(self): pass
561
562        class Group:
563            def get_name(self): pass
564
565        user = User()
566        group = User()
567        saved1 = user.get_name
568        saved2 = group.get_name
569        flexmock(User).should_receive('get_name').and_return('john')
570        flexmock(Group).should_receive('get_name').and_return('john')
571        assert saved1 != user.get_name
572        assert saved2 != group.get_name
573        assertEqual('john', user.get_name())
574        assertEqual('john', group.get_name())
575        self._tear_down()
576        assertEqual(saved1, user.get_name)
577        assertEqual(saved2, group.get_name)
578
579    def test_flexmock_respects_at_least_when_called_less_than_requested(self):
580        mock = flexmock(name='temp')
581        mock.should_receive('method_foo').and_return('bar').at_least().twice()
582        expectation = FlexmockContainer.get_flexmock_expectation(mock, 'method_foo')
583        assertEqual(AT_LEAST, expectation.modifier)
584        mock.method_foo()
585        assertRaises(MethodCallError, self._tear_down)
586
587    def test_flexmock_respects_at_least_when_called_requested_number(self):
588        mock = flexmock(name='temp')
589        mock.should_receive('method_foo').and_return('value_bar').at_least().once()
590        expectation = FlexmockContainer.get_flexmock_expectation(mock, 'method_foo')
591        assertEqual(AT_LEAST, expectation.modifier)
592        mock.method_foo()
593        self._tear_down()
594
595    def test_flexmock_respects_at_least_when_called_more_than_requested(self):
596        mock = flexmock(name='temp')
597        mock.should_receive('method_foo').and_return('value_bar').at_least().once()
598        expectation = FlexmockContainer.get_flexmock_expectation(mock, 'method_foo')
599        assertEqual(AT_LEAST, expectation.modifier)
600        mock.method_foo()
601        mock.method_foo()
602        self._tear_down()
603
604    def test_flexmock_respects_at_most_when_called_less_than_requested(self):
605        mock = flexmock(name='temp')
606        mock.should_receive('method_foo').and_return('bar').at_most().twice()
607        expectation = FlexmockContainer.get_flexmock_expectation(mock, 'method_foo')
608        assertEqual(AT_MOST, expectation.modifier)
609        mock.method_foo()
610        self._tear_down()
611
612    def test_flexmock_respects_at_most_when_called_requested_number(self):
613        mock = flexmock(name='temp')
614        mock.should_receive('method_foo').and_return('value_bar').at_most().once()
615        expectation = FlexmockContainer.get_flexmock_expectation(mock, 'method_foo')
616        assertEqual(AT_MOST, expectation.modifier)
617        mock.method_foo()
618        self._tear_down()
619
620    def test_flexmock_respects_at_most_when_called_more_than_requested(self):
621        mock = flexmock(name='temp')
622        mock.should_receive('method_foo').and_return('value_bar').at_most().once()
623        expectation = FlexmockContainer.get_flexmock_expectation(mock, 'method_foo')
624        assertEqual(AT_MOST, expectation.modifier)
625        mock.method_foo()
626        assertRaises(MethodCallError, mock.method_foo)
627
628    def test_flexmock_treats_once_as_times_one(self):
629        mock = flexmock(name='temp')
630        mock.should_receive('method_foo').and_return('value_bar').once()
631        expectation = FlexmockContainer.get_flexmock_expectation(mock, 'method_foo')
632        assertEqual(1, expectation.expected_calls[EXACTLY])
633        assertRaises(MethodCallError, self._tear_down)
634
635    def test_flexmock_treats_twice_as_times_two(self):
636        mock = flexmock(name='temp')
637        mock.should_receive('method_foo').twice().and_return('value_bar')
638        expectation = FlexmockContainer.get_flexmock_expectation(mock, 'method_foo')
639        assertEqual(2, expectation.expected_calls[EXACTLY])
640        assertRaises(MethodCallError, self._tear_down)
641
642    def test_flexmock_works_with_never_when_true(self):
643        mock = flexmock(name='temp')
644        mock.should_receive('method_foo').and_return('value_bar').never
645        expectation = FlexmockContainer.get_flexmock_expectation(mock, 'method_foo')
646        assertEqual(0, expectation.expected_calls[EXACTLY])
647        self._tear_down()
648
649    def test_flexmock_works_with_never_when_false(self):
650        mock = flexmock(name='temp')
651        mock.should_receive('method_foo').and_return('value_bar').never
652        assertRaises(MethodCallError, mock.method_foo)
653
654    def test_flexmock_get_flexmock_expectation_should_work_with_args(self):
655        mock = flexmock(name='temp')
656        mock.should_receive('method_foo').with_args('value_bar')
657        assert FlexmockContainer.get_flexmock_expectation(
658            mock, 'method_foo', 'value_bar')
659
660    def test_flexmock_function_should_return_previously_mocked_object(self):
661        class User(object):
662            pass
663
664        user = User()
665        foo = flexmock(user)
666        assert foo == user
667        assert foo == flexmock(user)
668
669    def test_flexmock_should_not_return_class_object_if_mocking_instance(self):
670        class User:
671            def method(self):
672                pass
673
674        user = User()
675        user2 = User()
676        class_mock = flexmock(User).should_receive(
677            'method').and_return('class').mock
678        user_mock = flexmock(user).should_receive(
679            'method').and_return('instance').mock
680        assert class_mock is not user_mock
681        assertEqual('instance', user.method())
682        assertEqual('class', user2.method())
683
684    def test_should_call_on_class_mock(self):
685        class User:
686            def __init__(self):
687                self.value = 'value'
688
689            def foo(self):
690                return 'class'
691
692            def bar(self):
693                return self.value
694
695        user1 = User()
696        user2 = User()
697
698        # Access class-level method
699        flexmock(User).should_call('foo').once()
700        assertRaises(MethodCallError, self._tear_down)
701        flexmock(User).should_call('foo').twice()
702        assertEqual('class', user1.foo())
703        assertEqual('class', user2.foo())
704
705        # Access instance attributes
706        flexmock(User).should_call('bar').once()
707        assertRaises(MethodCallError, self._tear_down)
708        flexmock(User).should_call('bar').twice()
709        assertEqual('value', user1.bar())
710        assertEqual('value', user2.bar())
711
712        # Try resetting the expectation
713        flexmock(User).should_call('bar').once()
714        assertEqual('value', user1.bar())
715
716    def test_with_args_on_class_mock(self):
717        # Instance method
718        flexmock(SomeClass).should_receive("instance_method_with_args").with_args("red").once()
719        flexmock(SomeClass).should_receive("instance_method_with_args").with_args("blue").once()
720        instance = SomeClass()
721        instance.instance_method_with_args("red")
722        instance.instance_method_with_args("blue")
723        self._tear_down()
724
725        # Class method
726        flexmock(SomeClass).should_receive("class_method_with_args").with_args("red").once()
727        flexmock(SomeClass).should_receive("class_method_with_args").with_args("blue").once()
728        SomeClass.class_method_with_args("red")
729        SomeClass.class_method_with_args("blue")
730        self._tear_down()
731
732        # Static method
733        flexmock(SomeClass).should_receive("static_method_with_args").with_args("red").once()
734        flexmock(SomeClass).should_receive("static_method_with_args").with_args("blue").once()
735        SomeClass.static_method_with_args("red")
736        SomeClass.static_method_with_args("blue")
737
738    def test_flexmock_should_not_blow_up_on_should_call_for_class_methods(self):
739        class User:
740            @classmethod
741            def foo(self):
742                return 'class'
743        flexmock(User).should_call('foo')
744        assertEqual('class', User.foo())
745
746    def test_flexmock_should_not_blow_up_on_should_call_for_static_methods(self):
747        class User:
748            @staticmethod
749            def foo():
750                return 'static'
751        flexmock(User).should_call('foo')
752        assertEqual('static', User.foo())
753
754    def test_flexmock_should_mock_new_instances_with_multiple_params(self):
755        class User(object):
756            pass
757
758        class Group(object):
759            def __init__(self, arg, arg2):
760                pass
761
762        user = User()
763        flexmock(Group).new_instances(user)
764        assert user is Group(1, 2)
765
766    def test_flexmock_should_revert_new_instances_on_teardown(self):
767        class User(object):
768            pass
769
770        class Group(object):
771            pass
772
773        user = User()
774        group = Group()
775        flexmock(Group).new_instances(user)
776        assert user is Group()
777        self._tear_down()
778        assertEqual(group.__class__, Group().__class__)
779
780    def test_flexmock_should_cleanup_added_methods_and_attributes(self):
781        class Group(object):
782            pass
783
784        group = Group()
785        flexmock(Group)
786        assert 'should_receive' in Group.__dict__
787        assert 'should_receive' not in group.__dict__
788        flexmock(group)
789        assert 'should_receive' in group.__dict__
790        self._tear_down()
791        for method in UPDATED_ATTRS:
792            assert method not in Group.__dict__
793            assert method not in group.__dict__
794
795    def test_class_attributes_are_unchanged_after_mocking(self):
796        class Base:
797            @classmethod
798            def class_method(cls):
799                pass
800
801            @staticmethod
802            def static_method():
803                pass
804
805            def instance_method(self):
806                pass
807
808        class Child(Base):
809            pass
810
811        instance = Base()
812        base_attrs = sorted(list(vars(Base).keys()))
813        instance_attrs = sorted(list(vars(instance).keys()))
814        child_attrs = sorted(list(vars(Child).keys()))
815        flexmock(Base).should_receive("class_method").once()
816        flexmock(Base).should_receive("static_method").once()
817        Base.class_method()
818        Base.static_method()
819
820        flexmock(instance).should_receive("class_method").once()
821        flexmock(instance).should_receive("static_method").once()
822        flexmock(instance).should_receive("instance_method").once()
823        instance.class_method()
824        instance.static_method()
825        instance.instance_method()
826
827        flexmock(Child).should_receive("class_method").once()
828        flexmock(Child).should_receive("static_method").once()
829        Child.class_method()
830        Child.static_method()
831
832        self._tear_down()
833        assert base_attrs == sorted(list(vars(Base).keys()))
834        assert instance_attrs == sorted(list(vars(instance).keys()))
835        assert child_attrs == sorted(list(vars(Child).keys()))
836
837    def test_class_attributes_are_unchanged_after_spying(self):
838        class Base:
839            @classmethod
840            def class_method(cls):
841                pass
842
843            @staticmethod
844            def static_method():
845                pass
846
847            def instance_method(self):
848                pass
849
850        class Child(Base):
851            pass
852
853        instance = Base()
854        base_attrs = sorted(list(vars(Base).keys()))
855        instance_attrs = sorted(list(vars(instance).keys()))
856        child_attrs = sorted(list(vars(Child).keys()))
857        flexmock(Base).should_call("class_method").times(3)
858        flexmock(Base).should_call("static_method").times(3)
859        Base.class_method()
860        Base.static_method()
861
862        flexmock(instance).should_call("class_method").once()
863        flexmock(instance).should_call("static_method").once()
864        flexmock(instance).should_call("instance_method").once()
865        instance.class_method()
866        instance.static_method()
867        instance.instance_method()
868
869        flexmock(Child).should_call("class_method").once()
870        flexmock(Child).should_call("static_method").once()
871        Child.class_method()
872        Child.static_method()
873
874        self._tear_down()
875        assert base_attrs == sorted(list(vars(Base).keys()))
876        assert instance_attrs == sorted(list(vars(instance).keys()))
877        assert child_attrs == sorted(list(vars(Child).keys()))
878
879    def test_flexmock_should_cleanup_after_exception(self):
880        class User:
881            def method2(self):
882                pass
883
884        class Group:
885            def method1(self):
886                pass
887
888        flexmock(Group)
889        flexmock(User)
890        Group.should_receive('method1').once()
891        User.should_receive('method2').once()
892        assertRaises(MethodCallError, self._tear_down)
893        for method in UPDATED_ATTRS:
894            assert method not in dir(Group)
895        for method in UPDATED_ATTRS:
896            assert method not in dir(User)
897
898    def test_flexmock_should_call_respects_matched_expectations(self):
899        class Group(object):
900            def method1(self, arg1, arg2='b'):
901                return '%s:%s' % (arg1, arg2)
902
903            def method2(self, arg):
904                return arg
905
906        group = Group()
907        flexmock(group).should_call('method1').twice()
908        assertEqual('a:c', group.method1('a', arg2='c'))
909        assertEqual('a:b', group.method1('a'))
910        group.should_call('method2').once().with_args('c')
911        assertEqual('c', group.method2('c'))
912        self._tear_down()
913
914    def test_flexmock_should_call_respects_unmatched_expectations(self):
915        class Group(object):
916            def method1(self, arg1, arg2='b'):
917                return '%s:%s' % (arg1, arg2)
918
919            def method2(self, a):
920                pass
921
922        group = Group()
923        flexmock(group).should_call('method1').at_least().once()
924        assertRaises(MethodCallError, self._tear_down)
925        flexmock(group)
926        group.should_call('method2').with_args('a').once()
927        group.should_receive('method2').with_args('not a')
928        group.method2('not a')
929        assertRaises(MethodCallError, self._tear_down)
930
931    def test_flexmock_doesnt_error_on_properly_ordered_expectations(self):
932        class Foo(object):
933            def foo(self):
934                pass
935
936            def method1(self, a):
937                pass
938
939            def bar(self):
940                pass
941
942            def baz(self):
943                pass
944
945        foo = Foo()
946        flexmock(foo).should_receive('foo')
947        flexmock(foo).should_receive('method1').with_args('a').ordered()
948        flexmock(foo).should_receive('bar')
949        flexmock(foo).should_receive('method1').with_args('b').ordered()
950        flexmock(foo).should_receive('baz')
951        foo.bar()
952        foo.method1('a')
953        foo.method1('b')
954        foo.baz()
955        foo.foo()
956
957    def test_flexmock_errors_on_improperly_ordered_expectations(self):
958        class Foo(object):
959            def method1(self, a): pass
960        foo = Foo()
961        flexmock(foo)
962        foo.should_receive('method1').with_args('a').ordered()
963        foo.should_receive('method1').with_args('b').ordered()
964        assertRaises(CallOrderError, foo.method1, 'b')
965
966    def test_flexmock_should_accept_multiple_return_values(self):
967        class Foo:
968            def method1(self): pass
969        foo = Foo()
970        flexmock(foo).should_receive('method1').and_return(1, 5).and_return(2)
971        assertEqual((1, 5), foo.method1())
972        assertEqual(2, foo.method1())
973        assertEqual((1, 5), foo.method1())
974        assertEqual(2, foo.method1())
975
976    def test_flexmock_should_accept_multiple_return_values_with_shortcut(self):
977        class Foo:
978            def method1(self): pass
979        foo = Foo()
980        flexmock(foo).should_receive('method1').and_return(1, 2).one_by_one()
981        assertEqual(1, foo.method1())
982        assertEqual(2, foo.method1())
983        assertEqual(1, foo.method1())
984        assertEqual(2, foo.method1())
985
986    def test_flexmock_should_mix_multiple_return_values_with_exceptions(self):
987        class Foo:
988            def method1(self): pass
989        foo = Foo()
990        flexmock(foo).should_receive('method1').and_return(1).and_raise(Exception)
991        assertEqual(1, foo.method1())
992        assertRaises(Exception, foo.method1)
993        assertEqual(1, foo.method1())
994        assertRaises(Exception, foo.method1)
995
996    def test_flexmock_should_match_types_on_multiple_arguments(self):
997        class Foo:
998            def method1(self, a, b): pass
999        foo = Foo()
1000        flexmock(foo).should_receive('method1').with_args(str, int).and_return('ok')
1001        assertEqual('ok', foo.method1('some string', 12))
1002        assertRaises(MethodSignatureError, foo.method1, 12, 32)
1003        flexmock(foo).should_receive('method1').with_args(str, int).and_return('ok')
1004        assertRaises(MethodSignatureError, foo.method1, 12, 'some string')
1005        flexmock(foo).should_receive('method1').with_args(str, int).and_return('ok')
1006        assertRaises(MethodSignatureError, foo.method1, 'string', 12, 14)
1007
1008    def test_flexmock_should_match_types_on_multiple_arguments_generic(self):
1009        class Foo:
1010            def method1(self, a, b, c): pass
1011        foo = Foo()
1012        flexmock(foo).should_receive('method1').with_args(
1013            object, object, object).and_return('ok')
1014        assertEqual('ok', foo.method1('some string', None, 12))
1015        assertEqual('ok', foo.method1((1,), None, 12))
1016        assertEqual('ok', foo.method1(12, 14, []))
1017        assertEqual('ok', foo.method1('some string', 'another one', False))
1018        assertRaises(MethodSignatureError, foo.method1, 'string', 12)
1019        flexmock(foo).should_receive('method1').with_args(
1020            object, object, object).and_return('ok')
1021        assertRaises(MethodSignatureError, foo.method1, 'string', 12, 13, 14)
1022
1023    def test_flexmock_should_match_types_on_multiple_arguments_classes(self):
1024        class Foo:
1025            def method1(self, a, b):
1026                pass
1027
1028        class Bar:
1029            pass
1030
1031        foo = Foo()
1032        bar = Bar()
1033        flexmock(foo).should_receive('method1').with_args(
1034            object, Bar).and_return('ok')
1035        assertEqual('ok', foo.method1('some string', bar))
1036        assertRaises(MethodSignatureError, foo.method1, bar, 'some string')
1037        flexmock(foo).should_receive('method1').with_args(
1038            object, Bar).and_return('ok')
1039        assertRaises(MethodSignatureError, foo.method1, 12, 'some string')
1040
1041    def test_flexmock_should_match_keyword_arguments(self):
1042        class Foo:
1043            def method1(self, a, **kwargs): pass
1044        foo = Foo()
1045        flexmock(foo).should_receive('method1').with_args(1, arg3=3, arg2=2).twice()
1046        foo.method1(1, arg2=2, arg3=3)
1047        foo.method1(1, arg3=3, arg2=2)
1048        self._tear_down()
1049        flexmock(foo).should_receive('method1').with_args(1, arg3=3, arg2=2)
1050        assertRaises(MethodSignatureError, foo.method1, arg2=2, arg3=3)
1051        flexmock(foo).should_receive('method1').with_args(1, arg3=3, arg2=2)
1052        assertRaises(MethodSignatureError, foo.method1, 1, arg2=2, arg3=4)
1053        flexmock(foo).should_receive('method1').with_args(1, arg3=3, arg2=2)
1054        assertRaises(MethodSignatureError, foo.method1, 1)
1055
1056    def test_flexmock_should_call_should_match_keyword_arguments(self):
1057        class Foo:
1058            def method1(self, arg1, arg2=None, arg3=None):
1059                return '%s%s%s' % (arg1, arg2, arg3)
1060        foo = Foo()
1061        flexmock(foo).should_call('method1').with_args(1, arg3=3, arg2=2).once()
1062        assertEqual('123', foo.method1(1, arg2=2, arg3=3))
1063
1064    def test_flexmock_should_mock_private_methods(self):
1065        class Foo:
1066            def __private_method(self):
1067                return 'foo'
1068
1069            def public_method(self):
1070                return self.__private_method()
1071
1072        foo = Foo()
1073        flexmock(foo).should_receive('__private_method').and_return('bar')
1074        assertEqual('bar', foo.public_method())
1075
1076    def test_flexmock_should_mock_special_methods(self):
1077        class Foo:
1078            def __special_method__(self):
1079                return 'foo'
1080
1081            def public_method(self):
1082                return self.__special_method__()
1083
1084        foo = Foo()
1085        flexmock(foo).should_receive('__special_method__').and_return('bar')
1086        assertEqual('bar', foo.public_method())
1087
1088    def test_flexmock_should_mock_double_underscore_method(self):
1089        class Foo:
1090            def __(self):
1091                return 'foo'
1092
1093            def public_method(self):
1094                return self.__()
1095
1096        foo = Foo()
1097        flexmock(foo).should_receive('__').and_return('bar')
1098        assertEqual('bar', foo.public_method())
1099
1100    def test_flexmock_should_mock_private_class_methods(self):
1101        class Foo:
1102            def __iter__(self): pass
1103        flexmock(Foo).should_receive('__iter__').and_yield(1, 2, 3)
1104        assertEqual([1, 2, 3], [x for x in Foo()])
1105
1106    def test_flexmock_should_mock_iter_on_new_style_instances(self):
1107        class Foo(object):
1108            def __iter__(self):
1109                yield None
1110        old = Foo.__iter__
1111        foo = Foo()
1112        foo2 = Foo()
1113        foo3 = Foo()
1114        flexmock(foo, __iter__=iter([1, 2, 3]))
1115        flexmock(foo2, __iter__=iter([3, 4, 5]))
1116        assertEqual([1, 2, 3], [x for x in foo])
1117        assertEqual([3, 4, 5], [x for x in foo2])
1118        assertEqual([None], [x for x in foo3])
1119        assertEqual(False, foo.__iter__ == old)
1120        assertEqual(False, foo2.__iter__ == old)
1121        assertEqual(False, foo3.__iter__ == old)
1122        self._tear_down()
1123        assertEqual([None], [x for x in foo])
1124        assertEqual([None], [x for x in foo2])
1125        assertEqual([None], [x for x in foo3])
1126        assertEqual(True, Foo.__iter__ == old, '%s != %s' % (Foo.__iter__, old))
1127
1128    def test_flexmock_should_mock_private_methods_with_leading_underscores(self):
1129        class _Foo:
1130            def __stuff(self):
1131                pass
1132
1133            def public_method(self):
1134                return self.__stuff()
1135
1136        foo = _Foo()
1137        flexmock(foo).should_receive('__stuff').and_return('bar')
1138        assertEqual('bar', foo.public_method())
1139
1140    def test_flexmock_should_mock_generators(self):
1141        class Gen:
1142            def foo(self):
1143                pass
1144
1145        gen = Gen()
1146        flexmock(gen).should_receive('foo').and_yield(*range(1, 10))
1147        output = [val for val in gen.foo()]
1148        assertEqual([val for val in range(1, 10)], output)
1149
1150    def test_flexmock_should_verify_correct_spy_return_values(self):
1151        class User:
1152            def get_stuff(self): return 'real', 'stuff'
1153        user = User()
1154        flexmock(user).should_call('get_stuff').and_return('real', 'stuff')
1155        assertEqual(('real', 'stuff'), user.get_stuff())
1156
1157    def test_flexmock_should_verify_correct_spy_regexp_return_values(self):
1158        class User:
1159            def get_stuff(self): return 'real', 'stuff'
1160        user = User()
1161        flexmock(user).should_call('get_stuff').and_return(
1162            re.compile('ea.*'), re.compile('^stuff$'))
1163        assertEqual(('real', 'stuff'), user.get_stuff())
1164
1165    def test_flexmock_should_verify_spy_raises_correct_exception_class(self):
1166        class FakeException(Exception):
1167            def __init__(self, param, param2):
1168                self.message = '%s, %s' % (param, param2)
1169                Exception.__init__(self)
1170
1171        class User:
1172            def get_stuff(self): raise FakeException(1, 2)
1173
1174        user = User()
1175        flexmock(user).should_call('get_stuff').and_raise(FakeException, 1, 2)
1176        user.get_stuff()
1177
1178    def test_flexmock_should_verify_spy_matches_exception_message(self):
1179        class FakeException(Exception):
1180            def __init__(self, param, param2):
1181                self.p1 = param
1182                self.p2 = param2
1183                Exception.__init__(self, param)
1184
1185            def __str__(self):
1186                return '%s, %s' % (self.p1, self.p2)
1187
1188        class User:
1189            def get_stuff(self): raise FakeException('1', '2')
1190
1191        user = User()
1192        flexmock(user).should_call('get_stuff').and_raise(FakeException, '2', '1')
1193        assertRaises(ExceptionMessageError, user.get_stuff)
1194
1195    def test_flexmock_should_verify_spy_matches_exception_regexp(self):
1196        class User:
1197            def get_stuff(self): raise Exception('123asdf345')
1198        user = User()
1199        flexmock(user).should_call(
1200            'get_stuff').and_raise(Exception, re.compile('asdf'))
1201        user.get_stuff()
1202        self._tear_down()
1203
1204    def test_flexmock_should_verify_spy_matches_exception_regexp_mismatch(self):
1205        class User:
1206            def get_stuff(self): raise Exception('123asdf345')
1207        user = User()
1208        flexmock(user).should_call(
1209            'get_stuff').and_raise(Exception, re.compile('^asdf'))
1210        assertRaises(ExceptionMessageError, user.get_stuff)
1211
1212    def test_flexmock_should_blow_up_on_wrong_spy_exception_type(self):
1213        class User:
1214            def get_stuff(self): raise CallOrderError('foo')
1215        user = User()
1216        flexmock(user).should_call('get_stuff').and_raise(MethodCallError)
1217        assertRaises(ExceptionClassError, user.get_stuff)
1218
1219    def test_flexmock_should_match_spy_exception_parent_type(self):
1220        class User:
1221            def get_stuff(self): raise CallOrderError('foo')
1222        user = User()
1223        flexmock(user).should_call('get_stuff').and_raise(FlexmockError)
1224        user.get_stuff()
1225
1226    def test_flexmock_should_blow_up_on_wrong_spy_return_values(self):
1227        class User:
1228            def get_stuff(self):
1229                return 'real', 'stuff'
1230
1231            def get_more_stuff(self):
1232                return 'other', 'stuff'
1233
1234        user = User()
1235        flexmock(user).should_call('get_stuff').and_return('other', 'stuff')
1236        assertRaises(MethodSignatureError, user.get_stuff)
1237        flexmock(user).should_call('get_more_stuff').and_return()
1238        assertRaises(MethodSignatureError, user.get_more_stuff)
1239
1240    def test_flexmock_should_mock_same_class_twice(self):
1241        class Foo:
1242            pass
1243
1244        flexmock(Foo)
1245        flexmock(Foo)
1246
1247    def test_flexmock_spy_should_not_clobber_original_method(self):
1248        class User:
1249            def get_stuff(self): return 'real', 'stuff'
1250        user = User()
1251        flexmock(user).should_call('get_stuff')
1252        flexmock(user).should_call('get_stuff')
1253        assertEqual(('real', 'stuff'), user.get_stuff())
1254
1255    def test_flexmock_should_properly_restore_static_methods(self):
1256        class User:
1257            @staticmethod
1258            def get_stuff(): return 'ok!'
1259        assert isinstance(User.__dict__["get_stuff"], staticmethod)
1260        assertEqual('ok!', User.get_stuff())
1261        flexmock(User).should_receive('get_stuff')
1262        assert User.get_stuff() is None
1263        self._tear_down()
1264        assertEqual('ok!', User.get_stuff())
1265        assert isinstance(User.__dict__["get_stuff"], staticmethod)
1266
1267    def test_flexmock_should_properly_restore_undecorated_static_methods(self):
1268        class User:
1269            def get_stuff(): return 'ok!'
1270            get_stuff = staticmethod(get_stuff)
1271        assertEqual('ok!', User.get_stuff())
1272        flexmock(User).should_receive('get_stuff')
1273        assert User.get_stuff() is None
1274        self._tear_down()
1275        assertEqual('ok!', User.get_stuff())
1276
1277    def test_flexmock_should_properly_restore_module_level_functions(self):
1278        if 'flexmock_test' in sys.modules:
1279            mod = sys.modules['flexmock_test']
1280        else:
1281            mod = sys.modules['__main__']
1282        flexmock(mod).should_receive('module_level_function').with_args(1, 2)
1283        assertEqual(None,  module_level_function(1, 2))
1284        self._tear_down()
1285        assertEqual('1, 2', module_level_function(1, 2))
1286
1287    def test_module_level_function_with_kwargs(self):
1288        if 'flexmock_test' in sys.modules:
1289            mod = sys.modules['flexmock_test']
1290        else:
1291            mod = sys.modules['__main__']
1292        flexmock(mod).should_receive('module_level_function').with_args(
1293            1, args="expected")
1294        assertRaises(FlexmockError, module_level_function, 1, args="not expected")
1295
1296    def test_flexmock_should_support_mocking_old_style_classes_as_functions(self):
1297        if 'flexmock_test' in sys.modules:
1298            mod = sys.modules['flexmock_test']
1299        else:
1300            mod = sys.modules['__main__']
1301        flexmock(mod).should_receive('OldStyleClass').and_return('yay')
1302        assertEqual('yay', OldStyleClass())
1303
1304    def test_flexmock_should_support_mocking_new_style_classes_as_functions(self):
1305        if 'flexmock_test' in sys.modules:
1306            mod = sys.modules['flexmock_test']
1307        else:
1308            mod = sys.modules['__main__']
1309        flexmock(mod).should_receive('NewStyleClass').and_return('yay')
1310        assertEqual('yay', NewStyleClass())
1311
1312    def test_flexmock_should_properly_restore_class_methods(self):
1313        class User:
1314            @classmethod
1315            def get_stuff(cls):
1316                return cls.__name__
1317        assert isinstance(User.__dict__["get_stuff"], classmethod)
1318        assertEqual('User', User.get_stuff())
1319        flexmock(User).should_receive('get_stuff').and_return('foo')
1320        assertEqual('foo', User.get_stuff())
1321        self._tear_down()
1322        assertEqual('User', User.get_stuff())
1323        assert isinstance(User.__dict__["get_stuff"], classmethod)
1324
1325    def test_spy_should_match_return_value_class(self):
1326        class User:
1327            pass
1328
1329        user = User()
1330        foo = flexmock(foo=lambda: ('bar', 'baz'),
1331                       bar=lambda: user,
1332                       baz=lambda: None,
1333                       bax=lambda: None)
1334        foo.should_call('foo').and_return(str, str)
1335        foo.should_call('bar').and_return(User)
1336        foo.should_call('baz').and_return(object)
1337        foo.should_call('bax').and_return(None)
1338        assertEqual(('bar', 'baz'), foo.foo())
1339        assertEqual(user, foo.bar())
1340        assertEqual(None, foo.baz())
1341        assertEqual(None, foo.bax())
1342
1343    def test_spy_should_not_match_falsy_stuff(self):
1344        class Foo:
1345            def foo(self):
1346                return None
1347
1348            def bar(self):
1349                return False
1350
1351            def baz(self):
1352                return []
1353
1354            def quux(self):
1355                return ''
1356
1357        foo = Foo()
1358        flexmock(foo).should_call('foo').and_return('bar').once
1359        flexmock(foo).should_call('bar').and_return('bar').once
1360        flexmock(foo).should_call('baz').and_return('bar').once
1361        flexmock(foo).should_call('quux').and_return('bar').once
1362        assertRaises(FlexmockError, foo.foo)
1363        assertRaises(FlexmockError, foo.bar)
1364        assertRaises(FlexmockError, foo.baz)
1365        assertRaises(FlexmockError, foo.quux)
1366
1367    def test_new_instances_should_blow_up_on_should_receive(self):
1368        class User(object):
1369            pass
1370
1371        mock = flexmock(User).new_instances(None).mock
1372        assertRaises(FlexmockError, mock.should_receive, 'foo')
1373
1374    def test_should_call_alias_should_create_a_spy(self):
1375        class Foo:
1376            def get_stuff(self):
1377                return 'yay'
1378
1379        foo = Foo()
1380        flexmock(foo).should_call('get_stuff').and_return('yay').once()
1381        assertRaises(MethodCallError, self._tear_down)
1382
1383    def test_flexmock_should_fail_mocking_nonexistent_methods(self):
1384        class User:
1385            pass
1386
1387        user = User()
1388        assertRaises(FlexmockError,
1389                     flexmock(user).should_receive, 'nonexistent')
1390
1391    def test_flexmock_should_not_explode_on_unicode_formatting(self):
1392        if sys.version_info >= (3, 0):
1393            formatted = _format_args('method', {'kargs': (chr(0x86C7),), 'kwargs': {}})
1394            assertEqual('method("蛇")', formatted)
1395        else:
1396            formatted = _format_args('method', {'kargs': (unichr(0x86C7),), 'kwargs': {}})
1397            assertEqual('method("%s")' % unichr(0x86C7), formatted)
1398
1399    def test_return_value_should_not_explode_on_unicode_values(self):
1400        class Foo:
1401            def method(self): pass
1402        if sys.version_info >= (3, 0):
1403            return_value = ReturnValue(chr(0x86C7))
1404            assertEqual('"蛇"', '%s' % return_value)
1405            return_value = ReturnValue((chr(0x86C7), chr(0x86C7)))
1406            assertEqual('("蛇", "蛇")', '%s' % return_value)
1407        else:
1408            return_value = ReturnValue(unichr(0x86C7))
1409            assertEqual('"%s"' % unichr(0x86C7), unicode(return_value))
1410
1411    def test_pass_thru_should_call_original_method_only_once(self):
1412        class Nyan(object):
1413            def __init__(self):
1414                self.n = 0
1415
1416            def method(self):
1417                self.n += 1
1418
1419        obj = Nyan()
1420        flexmock(obj)
1421        obj.should_call('method')
1422        obj.method()
1423        assertEqual(obj.n, 1)
1424
1425    def test_should_call_works_for_same_method_with_different_args(self):
1426        class Foo:
1427            def method(self, arg):
1428                pass
1429        foo = Foo()
1430        flexmock(foo).should_call('method').with_args('foo').once()
1431        flexmock(foo).should_call('method').with_args('bar').once()
1432        foo.method('foo')
1433        foo.method('bar')
1434        self._tear_down()
1435
1436    def test_should_call_fails_properly_for_same_method_with_different_args(self):
1437        class Foo:
1438            def method(self, arg):
1439                pass
1440        foo = Foo()
1441        flexmock(foo).should_call('method').with_args('foo').once()
1442        flexmock(foo).should_call('method').with_args('bar').once()
1443        foo.method('foo')
1444        assertRaises(MethodCallError, self._tear_down)
1445
1446    def test_should_give_reasonable_error_for_builtins(self):
1447        assertRaises(MockBuiltinError, flexmock, object)
1448
1449    def test_should_give_reasonable_error_for_instances_of_builtins(self):
1450        assertRaises(MockBuiltinError, flexmock, object())
1451
1452    def test_mock_chained_method_calls_works_with_one_level(self):
1453        class Foo:
1454            def method2(self):
1455                return 'foo'
1456
1457        class Bar:
1458            def method1(self):
1459                return Foo()
1460
1461        foo = Bar()
1462        assertEqual('foo', foo.method1().method2())
1463        flexmock(foo).should_receive('method1.method2').and_return('bar')
1464        assertEqual('bar', foo.method1().method2())
1465
1466    def test_mock_chained_method_supports_args_and_mocks(self):
1467        class Foo:
1468            def method2(self, arg):
1469                return arg
1470
1471        class Bar:
1472            def method1(self):
1473                return Foo()
1474
1475        foo = Bar()
1476        assertEqual('foo', foo.method1().method2('foo'))
1477        flexmock(foo).should_receive('method1.method2').with_args(
1478            'foo').and_return('bar').once()
1479        assertEqual('bar', foo.method1().method2('foo'))
1480        self._tear_down()
1481        flexmock(foo).should_receive('method1.method2').with_args(
1482            'foo').and_return('bar').once()
1483        assertRaises(MethodCallError, self._tear_down)
1484
1485    def test_mock_chained_method_calls_works_with_more_than_one_level(self):
1486        class Baz:
1487            def method3(self):
1488                return 'foo'
1489
1490        class Foo:
1491            def method2(self):
1492                return Baz()
1493
1494        class Bar:
1495            def method1(self):
1496                return Foo()
1497
1498        foo = Bar()
1499        assertEqual('foo', foo.method1().method2().method3())
1500        flexmock(foo).should_receive('method1.method2.method3').and_return('bar')
1501        assertEqual('bar', foo.method1().method2().method3())
1502
1503    def test_flexmock_should_replace_method(self):
1504        class Foo:
1505            def method(self, arg):
1506                return arg
1507        foo = Foo()
1508        flexmock(foo).should_receive('method').replace_with(lambda x: x == 5)
1509        assertEqual(foo.method(5), True)
1510        assertEqual(foo.method(4), False)
1511
1512    def test_flexmock_should_replace_cannot_be_specified_twice(self):
1513        class Foo:
1514            def method(self, arg):
1515                return arg
1516        foo = Foo()
1517        expectation = flexmock(foo).should_receive(
1518            'method').replace_with(lambda x: x == 5)
1519        assertRaises(FlexmockError,
1520                     expectation.replace_with, lambda x: x == 3)
1521
1522    def test_flexmock_should_mock_the_same_method_multiple_times(self):
1523        class Foo:
1524            def method(self): pass
1525        foo = Foo()
1526        flexmock(foo).should_receive('method').and_return(1)
1527        assertEqual(foo.method(), 1)
1528        flexmock(foo).should_receive('method').and_return(2)
1529        assertEqual(foo.method(), 2)
1530        flexmock(foo).should_receive('method').and_return(3)
1531        assertEqual(foo.method(), 3)
1532        flexmock(foo).should_receive('method').and_return(4)
1533        assertEqual(foo.method(), 4)
1534
1535    def test_new_instances_should_be_a_method(self):
1536        class Foo(object):
1537            pass
1538
1539        flexmock(Foo).new_instances('bar')
1540        assertEqual('bar', Foo())
1541        self._tear_down()
1542        assert 'bar' != Foo()
1543
1544    def test_new_instances_raises_error_when_not_a_class(self):
1545        class Foo(object):
1546            pass
1547
1548        foo = Foo()
1549        flexmock(foo)
1550        assertRaises(FlexmockError, foo.new_instances, 'bar')
1551
1552    def test_new_instances_works_with_multiple_return_values(self):
1553        class Foo(object):
1554            pass
1555
1556        flexmock(Foo).new_instances('foo', 'bar')
1557        assertEqual('foo', Foo())
1558        assertEqual('bar', Foo())
1559
1560    def test_should_receive_should_not_replace_flexmock_methods(self):
1561        class Foo:
1562            def bar(self):
1563                pass
1564
1565        foo = Foo()
1566        flexmock(foo)
1567        assertRaises(FlexmockError, foo.should_receive, 'should_receive')
1568
1569    def test_flexmock_should_not_add_methods_if_they_already_exist(self):
1570        class Foo:
1571            def should_receive(self):
1572                return 'real'
1573
1574            def bar(self):
1575                pass
1576
1577        foo = Foo()
1578        mock = flexmock(foo)
1579        assertEqual(foo.should_receive(), 'real')
1580        assert 'should_call' not in dir(foo)
1581        assert 'new_instances' not in dir(foo)
1582        mock.should_receive('bar').and_return('baz')
1583        assertEqual(foo.bar(), 'baz')
1584        self._tear_down()
1585        assertEqual(foo.should_receive(), 'real')
1586
1587    def test_flexmock_should_not_add_class_methods_if_they_already_exist(self):
1588        class Foo:
1589            def should_receive(self):
1590                return 'real'
1591
1592            def bar(self):
1593                pass
1594
1595        foo = Foo()
1596        mock = flexmock(Foo)
1597        assertEqual(foo.should_receive(), 'real')
1598        assert 'should_call' not in dir(Foo)
1599        assert 'new_instances' not in dir(Foo)
1600        mock.should_receive('bar').and_return('baz')
1601        assertEqual(foo.bar(), 'baz')
1602        self._tear_down()
1603        assertEqual(foo.should_receive(), 'real')
1604
1605    def test_expectation_properties_work_with_parens(self):
1606        foo = flexmock().should_receive(
1607            'bar').at_least().once().and_return('baz').mock()
1608        assertEqual('baz', foo.bar())
1609
1610    def test_mocking_down_the_inheritance_chain_class_to_class(self):
1611        class Parent(object):
1612            def foo(self):
1613                pass
1614
1615        class Child(Parent):
1616            def bar(self):
1617                pass
1618
1619        flexmock(Parent).should_receive('foo').and_return('outer')
1620        flexmock(Child).should_receive('bar').and_return('inner')
1621        assert 'outer', Parent().foo()
1622        assert 'inner', Child().bar()
1623
1624    def test_arg_matching_works_with_regexp(self):
1625        class Foo:
1626            def foo(self, arg1, arg2):
1627                pass
1628
1629        foo = Foo()
1630        flexmock(foo).should_receive('foo').with_args(
1631            re.compile('^arg1.*asdf$'), arg2=re.compile('f')).and_return('mocked')
1632        assertEqual('mocked', foo.foo('arg1somejunkasdf', arg2='aadsfdas'))
1633
1634    def test_arg_matching_with_regexp_fails_when_regexp_doesnt_match_karg(self):
1635        class Foo:
1636            def foo(self, arg1, arg2): pass
1637        foo = Foo()
1638        flexmock(foo).should_receive('foo').with_args(
1639            re.compile('^arg1.*asdf$'), arg2=re.compile('a')).and_return('mocked')
1640        assertRaises(MethodSignatureError, foo.foo, 'arg1somejunkasdfa', arg2='a')
1641
1642    def test_arg_matching_with_regexp_fails_when_regexp_doesnt_match_kwarg(self):
1643        class Foo:
1644            def foo(self, arg1, arg2): pass
1645        foo = Foo()
1646        flexmock(foo).should_receive('foo').with_args(
1647            re.compile('^arg1.*asdf$'), arg2=re.compile('a')).and_return('mocked')
1648        assertRaises(MethodSignatureError, foo.foo, 'arg1somejunkasdf', arg2='b')
1649
1650    def test_flexmock_class_returns_same_object_on_repeated_calls(self):
1651        class Foo:
1652            pass
1653
1654        a = flexmock(Foo)
1655        b = flexmock(Foo)
1656        assertEqual(a, b)
1657
1658    def test_flexmock_object_returns_same_object_on_repeated_calls(self):
1659        class Foo:
1660            pass
1661
1662        foo = Foo()
1663        a = flexmock(foo)
1664        b = flexmock(foo)
1665        assertEqual(a, b)
1666
1667    def test_flexmock_ordered_worked_after_default_stub(self):
1668        foo = flexmock()
1669        foo.should_receive('bar')
1670        foo.should_receive('bar').with_args('a').ordered()
1671        foo.should_receive('bar').with_args('b').ordered()
1672        assertRaises(CallOrderError, foo.bar, 'b')
1673
1674    def test_flexmock_ordered_works_with_same_args(self):
1675        foo = flexmock()
1676        foo.should_receive('bar').ordered().and_return(1)
1677        foo.should_receive('bar').ordered().and_return(2)
1678        a = foo.bar()
1679        assertEqual(a, 1)
1680        b = foo.bar()
1681        assertEqual(b, 2)
1682
1683    def test_flexmock_ordered_works_with_same_args_after_default_stub(self):
1684        foo = flexmock()
1685        foo.should_receive('bar').and_return(9)
1686        foo.should_receive('bar').ordered().and_return(1)
1687        foo.should_receive('bar').ordered().and_return(2)
1688        a = foo.bar()
1689        assertEqual(a, 1)
1690        b = foo.bar()
1691        assertEqual(b, 2)
1692        c = foo.bar()
1693        assertEqual(c, 9)
1694
1695    def test_state_machine(self):
1696        class Radio:
1697            def __init__(self):
1698                self.is_on = False
1699
1700            def switch_on(self):
1701                self.is_on = True
1702
1703            def switch_off(self):
1704                self.is_on = False
1705
1706            def select_channel(self):
1707                return None
1708
1709            def adjust_volume(self, num):
1710                self.volume = num
1711
1712        radio = Radio()
1713        flexmock(radio)
1714        radio.should_receive('select_channel').once().when(
1715            lambda: radio.is_on)
1716        radio.should_call('adjust_volume').once().with_args(5).when(
1717            lambda: radio.is_on)
1718
1719        assertRaises(StateError, radio.select_channel)
1720        assertRaises(StateError, radio.adjust_volume, 5)
1721        radio.is_on = True
1722        radio.select_channel()
1723        radio.adjust_volume(5)
1724
1725    def test_support_at_least_and_at_most_together(self):
1726        class Foo:
1727            def bar(self): pass
1728
1729        foo = Foo()
1730        flexmock(foo).should_call('bar').at_least().once().at_most().twice()
1731        assertRaises(MethodCallError, self._tear_down)
1732
1733        flexmock(foo).should_call('bar').at_least().once().at_most().twice()
1734        foo.bar()
1735        foo.bar()
1736        assertRaises(MethodCallError, foo.bar)
1737
1738        flexmock(foo).should_call('bar').at_least().once().at_most().twice()
1739        foo.bar()
1740        self._tear_down()
1741
1742        flexmock(foo).should_call('bar').at_least().once().at_most().twice()
1743        foo.bar()
1744        foo.bar()
1745        self._tear_down()
1746
1747    def test_at_least_cannot_be_used_twice(self):
1748        class Foo:
1749            def bar(self): pass
1750
1751        expectation = flexmock(Foo).should_receive('bar')
1752        try:
1753            expectation.at_least().at_least()
1754            raise Exception('should not be able to specify at_least twice')
1755        except FlexmockError:
1756            pass
1757        except Exception:
1758            raise
1759
1760    def test_at_most_cannot_be_used_twice(self):
1761        class Foo:
1762            def bar(self): pass
1763
1764        expectation = flexmock(Foo).should_receive('bar')
1765        try:
1766            expectation.at_most().at_most()
1767            raise Exception('should not be able to specify at_most twice')
1768        except FlexmockError:
1769            pass
1770        except Exception:
1771            raise
1772
1773    def test_at_least_cannot_be_specified_until_at_most_is_set(self):
1774        class Foo:
1775            def bar(self): pass
1776
1777        expectation = flexmock(Foo).should_receive('bar')
1778        try:
1779            expectation.at_least().at_most()
1780            raise Exception('should not be able to specify at_most if at_least unset')
1781        except FlexmockError:
1782            pass
1783        except Exception:
1784            raise
1785
1786    def test_at_most_cannot_be_specified_until_at_least_is_set(self):
1787        class Foo:
1788            def bar(self): pass
1789
1790        expectation = flexmock(Foo).should_receive('bar')
1791        try:
1792            expectation.at_most().at_least()
1793            raise Exception('should not be able to specify at_least if at_most unset')
1794        except FlexmockError:
1795            pass
1796        except Exception:
1797            raise
1798
1799    def test_proper_reset_of_subclass_methods(self):
1800        class A:
1801            def x(self):
1802                return 'a'
1803
1804        class B(A):
1805            def x(self):
1806                return 'b'
1807
1808        flexmock(B).should_receive('x').and_return('1')
1809        self._tear_down()
1810        assertEqual('b', B().x())
1811
1812    def test_format_args_supports_tuples(self):
1813        formatted = _format_args('method', {'kargs': ((1, 2),), 'kwargs': {}})
1814        assertEqual('method((1, 2))', formatted)
1815
1816    def test_mocking_subclass_of_str(self):
1817        class String(str):
1818            pass
1819
1820        s = String()
1821        flexmock(s, endswith='fake')
1822        assertEqual('fake', s.endswith('stuff'))
1823        self._tear_down()
1824        assertEqual(False, s.endswith('stuff'))
1825
1826    def test_ordered_on_different_methods(self):
1827        class String(str):
1828            pass
1829
1830        s = String('abc')
1831        flexmock(s)
1832        s.should_call('startswith').with_args('asdf', 0, 4).ordered()
1833        s.should_call('endswith').ordered()
1834        assertRaises(CallOrderError, s.endswith, 'c')
1835
1836    def test_fake_object_takes_properties(self):
1837        foo = flexmock(bar=property(lambda self: 'baz'))
1838        bar = flexmock(foo=property(lambda self: 'baz'))
1839        assertEqual('baz', foo.bar)
1840        assertEqual('baz', bar.foo)
1841
1842    def test_replace_non_callable_class_attributes(self):
1843        class Foo:
1844            bar = 1
1845        foo = Foo()
1846        bar = Foo()
1847        flexmock(foo, bar=2)
1848        assertEqual(2, foo.bar)
1849        assertEqual(1, bar.bar)
1850        self._tear_down()
1851        assertEqual(1, foo.bar)
1852
1853    def test_should_chain_attributes(self):
1854        class Baz:
1855            x = 1
1856
1857        class Bar:
1858            baz = Baz()
1859
1860        class Foo:
1861            bar = Bar()
1862
1863        foo = Foo()
1864        foo = flexmock(foo)
1865        foo.should_receive('bar.baz.x').and_return(2)
1866        assertEqual(2, foo.bar.baz.x)
1867        self._tear_down()
1868        assertEqual(1, foo.bar.baz.x)
1869
1870    def test_replace_non_callable_instance_attributes(self):
1871        class Foo:
1872            def __init__(self):
1873                self.bar = 1
1874        foo = Foo()
1875        bar = Foo()
1876        flexmock(foo, bar=2)
1877        flexmock(bar, bar=1)
1878        assertEqual(2, foo.bar)
1879        self._tear_down()
1880        assertEqual(1, foo.bar)
1881
1882    def test_replace_non_callable_module_attributes(self):
1883        if 'flexmock_test' in sys.modules:
1884            mod = sys.modules['flexmock_test']
1885        else:
1886            mod = sys.modules['__main__']
1887        flexmock(mod, module_level_attribute='yay')
1888        assertEqual('yay',  module_level_attribute)
1889        self._tear_down()
1890        assertEqual('test', module_level_attribute)
1891
1892    def test_non_callable_attributes_fail_to_set_expectations(self):
1893        class Foo:
1894            bar = 1
1895        foo = Foo()
1896        e = flexmock(foo).should_receive('bar').and_return(2)
1897        assertRaises(FlexmockError, e.times, 1)
1898        assertRaises(FlexmockError, e.with_args, ())
1899        assertRaises(FlexmockError, e.replace_with, lambda x: x)
1900        assertRaises(FlexmockError, e.and_raise, Exception)
1901        assertRaises(FlexmockError, e.when, lambda x: x)
1902        assertRaises(FlexmockError, e.and_yield, 1)
1903        assertRaises(FlexmockError, object.__getattribute__(e, 'ordered'))
1904        assertRaises(FlexmockError, object.__getattribute__(e, 'at_least'))
1905        assertRaises(FlexmockError, object.__getattribute__(e, 'at_most'))
1906        assertRaises(FlexmockError, object.__getattribute__(e, 'one_by_one'))
1907
1908    def test_and_return_defaults_to_none_with_no_arguments(self):
1909        foo = flexmock()
1910        foo.should_receive('bar').and_return()
1911        assertEqual(None, foo.bar())
1912
1913    def test_should_replace_attributes_that_are_instances_of_classes(self):
1914        class Foo(object):
1915            pass
1916
1917        class Bar(object):
1918            foo = Foo()
1919
1920        bar = Bar()
1921        flexmock(bar, foo='test')
1922        assertEqual('test', bar.foo)
1923
1924    def test_isproperty(self):
1925        class Foo:
1926            @property
1927            def bar(self):
1928                pass
1929
1930            def baz(self):
1931                pass
1932
1933        class Bar(Foo):
1934            pass
1935
1936        foo = Foo()
1937        bar = Bar()
1938        assertEqual(True, _isproperty(foo, 'bar'))
1939        assertEqual(False, _isproperty(foo, 'baz'))
1940        assertEqual(True, _isproperty(Foo, 'bar'))
1941        assertEqual(False, _isproperty(Foo, 'baz'))
1942        assertEqual(True, _isproperty(bar, 'bar'))
1943        assertEqual(False, _isproperty(bar, 'baz'))
1944        assertEqual(True, _isproperty(Bar, 'bar'))
1945        assertEqual(False, _isproperty(Bar, 'baz'))
1946        assertEqual(False, _isproperty(Mock(), 'baz'))
1947
1948    def test_fake_object_supporting_iteration(self):
1949        foo = flexmock()
1950        foo.should_receive('__iter__').and_yield(1, 2, 3)
1951        assertEqual([1, 2, 3], [i for i in foo])
1952
1953    def test_with_args_for_single_named_arg_with_optional_args(self):
1954        class Foo(object):
1955            def bar(self, one, two='optional'): pass
1956        e = flexmock(Foo).should_receive('bar')
1957        e.with_args(one=1)
1958
1959    def test_with_args_doesnt_set_max_when_using_varargs(self):
1960        class Foo(object):
1961            def bar(self, *kargs): pass
1962        flexmock(Foo).should_receive('bar').with_args(1, 2, 3)
1963
1964    def test_with_args_doesnt_set_max_when_using_kwargs(self):
1965        class Foo(object):
1966            def bar(self, **kwargs): pass
1967        flexmock(Foo).should_receive('bar').with_args(1, 2, 3)
1968
1969    def test_with_args_blows_up_on_too_few_args(self):
1970        class Foo(object):
1971            def bar(self, a, b, c=1): pass
1972        e = flexmock(Foo).should_receive('bar')
1973        assertRaises(MethodSignatureError, e.with_args, 1)
1974
1975    def test_with_args_blows_up_on_too_few_args_with_kwargs(self):
1976        class Foo(object):
1977            def bar(self, a, b, c=1): pass
1978        e = flexmock(Foo).should_receive('bar')
1979        assertRaises(MethodSignatureError, e.with_args, 1, c=2)
1980
1981    def test_with_args_blows_up_on_too_many_args(self):
1982        class Foo(object):
1983            def bar(self, a, b, c=1): pass
1984        e = flexmock(Foo).should_receive('bar')
1985        assertRaises(MethodSignatureError, e.with_args, 1, 2, 3, 4)
1986
1987    def test_with_args_blows_up_on_kwarg_overlapping_positional(self):
1988        class Foo(object):
1989            def bar(self, a, b, c=1, **kwargs): pass
1990        e = flexmock(Foo).should_receive('bar')
1991        assertRaises(MethodSignatureError, e.with_args, 1, 2, 3, c=2)
1992
1993    def test_with_args_blows_up_on_invalid_kwarg(self):
1994        class Foo(object):
1995            def bar(self, a, b, c=1): pass
1996        e = flexmock(Foo).should_receive('bar')
1997        assertRaises(MethodSignatureError, e.with_args, 1, 2, d=2)
1998
1999    def test_with_args_ignores_invalid_args_on_flexmock_instances(self):
2000        foo = flexmock(bar=lambda x: x)
2001        foo.should_receive('bar').with_args('stuff')
2002        foo.bar('stuff')
2003
2004    def test_with_args_does_not_compensate_for_self_on_static_instance_methods(self):
2005        class Foo(object):
2006            @staticmethod
2007            def bar(x): pass
2008        foo = Foo()
2009        flexmock(foo).should_receive('bar').with_args('stuff')
2010        foo.bar('stuff')
2011
2012    def test_with_args_does_not_compensate_for_self_on_static_class_methods(self):
2013        class Foo(object):
2014            @staticmethod
2015            def bar(x): pass
2016        flexmock(Foo).should_receive('bar').with_args('stuff')
2017        Foo.bar('stuff')
2018
2019    def test_with_args_does_compensate_for_cls_on_class_methods(self):
2020        class Foo(object):
2021            @classmethod
2022            def bar(cls, x): pass
2023        foo = Foo()
2024        flexmock(foo).should_receive('bar').with_args('stuff')
2025        foo.bar('stuff')
2026
2027    def test_calling_with_keyword_args_matches_mock_with_positional_args(self):
2028        class Foo(object):
2029            def bar(self, a, b, c):
2030                pass
2031
2032        foo = Foo()
2033        flexmock(foo).should_receive('bar').with_args(1, 2, 3).once()
2034        foo.bar(a=1, b=2, c=3)
2035
2036    def test_calling_with_positional_args_matches_mock_with_kwargs(self):
2037        class Foo(object):
2038            def bar(self, a, b, c):
2039                pass
2040
2041        foo = Foo()
2042        flexmock(foo).should_receive('bar').with_args(a=1, b=2, c=3).once()
2043        foo.bar(1, 2, c=3)
2044
2045    def test_use_replace_with_for_callable_shortcut_kwargs(self):
2046        class Foo(object):
2047            def bar(self): return 'bar'
2048        foo = Foo()
2049        flexmock(foo, bar=lambda: 'baz')
2050        assertEqual('baz', foo.bar())
2051
2052    def test_mock_property_with_attribute_on_instance(self):
2053        class Foo(object):
2054            @property
2055            def bar(self): return 'bar'
2056        foo = Foo()
2057        foo2 = Foo()
2058        foo3 = Foo()
2059        flexmock(foo, bar='baz')
2060        flexmock(foo2, bar='baz2')
2061        assertEqual('baz', foo.bar)
2062        assertEqual('baz2', foo2.bar)
2063        assertEqual('bar', foo3.bar)
2064        self._tear_down()
2065        assertEqual(False, hasattr(Foo, '_flexmock__bar'),
2066                    'Property bar not cleaned up')
2067        assertEqual('bar', foo.bar)
2068        assertEqual('bar', foo2.bar)
2069        assertEqual('bar', foo3.bar)
2070
2071    def test_mock_property_with_attribute_on_class(self):
2072        class Foo(object):
2073            @property
2074            def bar(self): return 'bar'
2075        foo = Foo()
2076        foo2 = Foo()
2077        flexmock(Foo, bar='baz')
2078        assertEqual('baz', foo.bar)
2079        assertEqual('baz', foo2.bar)
2080        self._tear_down()
2081        assertEqual(False, hasattr(Foo, '_flexmock__bar'),
2082                    'Property bar not cleaned up')
2083        assertEqual('bar', foo.bar)
2084        assertEqual('bar', foo2.bar)
2085
2086    def test_verifying_methods_when_mocking_module(self):
2087        # previously, we had problems with recognizing methods vs functions if the mocked
2088        #  object was an imported module
2089        flexmock(some_module).should_receive('SomeClass').with_args(1, 2)
2090        flexmock(some_module).should_receive('foo').with_args(1, 2)
2091
2092    def test_is_class_method(self):
2093        assert _is_class_method(SomeClass.class_method, "class_method") is True
2094        assert _is_class_method(SomeClass.static_method, "static_method") is False
2095        assert _is_class_method(SomeClass.instance_method, "instance_method") is False
2096
2097        some_class = SomeClass()
2098        assert _is_class_method(some_class.class_method, "class_method") is True
2099        assert _is_class_method(some_class.static_method, "static_method") is False
2100        assert _is_class_method(some_class.instance_method, "instance_method") is False
2101
2102        assert _is_class_method(DerivedClass.class_method, "class_method") is True
2103        assert _is_class_method(DerivedClass.static_method, "static_method") is False
2104        assert _is_class_method(DerivedClass.instance_method, "instance_method") is False
2105
2106        derived_class = DerivedClass()
2107        assert _is_class_method(derived_class.class_method, "class_method") is True
2108        assert _is_class_method(derived_class.static_method, "static_method") is False
2109        assert _is_class_method(derived_class.instance_method, "instance_method") is False
2110
2111    def test_is_static_method(self):
2112        assert _is_static_method(SomeClass, "class_method") is False
2113        assert _is_static_method(SomeClass, "static_method") is True
2114        assert _is_static_method(SomeClass, "instance_method") is False
2115
2116        some_class = SomeClass()
2117        assert _is_static_method(some_class, "class_method") is False
2118        assert _is_static_method(some_class, "static_method") is True
2119        assert _is_static_method(some_class, "instance_method") is False
2120
2121        assert _is_static_method(DerivedClass, "class_method") is False
2122        assert _is_static_method(DerivedClass, "static_method") is True
2123        assert _is_static_method(DerivedClass, "instance_method") is False
2124
2125        derived_class = DerivedClass()
2126        assert _is_static_method(derived_class, "class_method") is False
2127        assert _is_static_method(derived_class, "static_method") is True
2128        assert _is_static_method(derived_class, "instance_method") is False
2129
2130class TestFlexmockUnittest(RegularClass, unittest.TestCase):
2131    def tearDown(self):
2132        pass
2133
2134    def _tear_down(self):
2135        return flexmock_teardown()
2136
2137
2138if sys.version_info >= (2, 6):
2139    import flexmock_modern_test
2140
2141    class TestUnittestModern(flexmock_modern_test.TestFlexmockUnittestModern):
2142        pass
2143
2144
2145if sys.version_info >= (3, 0):
2146    import py3_only_features
2147
2148    class TestPy3Features(unittest.TestCase):
2149        def test_mock_kwargs_only_func_mock_all(self):
2150            flexmock(py3_only_features).should_receive(
2151                'kwargs_only_func').with_args(1, bar=2, baz=3).and_return(123)
2152            self.assertEqual(py3_only_features.kwargs_only_func(1, bar=2, baz=3),
2153                             123)
2154
2155        def test_mock_kwargs_only_func_mock_required(self):
2156            flexmock(py3_only_features).should_receive(
2157                'kwargs_only_func').with_args(1, bar=2).and_return(123)
2158            self.assertEqual(py3_only_features.kwargs_only_func(1, bar=2), 123)
2159
2160        def test_mock_kwargs_only_func_fails_if_required_not_provided(self):
2161            self.assertRaises(
2162                MethodSignatureError,
2163                flexmock(py3_only_features).should_receive(
2164                    'kwargs_only_func').with_args,
2165                1)
2166
2167        def test_mock_proxied_class(self):
2168            # pylint: disable=not-callable
2169            SomeClassProxy = Proxy(SomeClass)
2170            flexmock(SomeClassProxy).should_receive("class_method").and_return(2).twice()
2171            assert SomeClassProxy().class_method() == 2
2172            assert SomeClassProxy.class_method() == 2
2173            flexmock(SomeClassProxy).should_receive("static_method").and_return(3).twice()
2174            assert SomeClassProxy().static_method() == 3
2175            assert SomeClassProxy.static_method() == 3
2176            instance = SomeClassProxy()
2177            flexmock(instance).should_receive("instance_method").and_return(4).once()
2178            assert instance.instance_method() == 4
2179
2180        def test_mock_proxied_class_with_args(self):
2181            # pylint: disable=not-callable
2182            SomeClassProxy = Proxy(SomeClass)
2183            flexmock(SomeClassProxy).should_receive("class_method_with_args").with_args("a").and_return(
2184                2
2185            ).twice()
2186            assert SomeClassProxy().class_method_with_args("a") == 2
2187            assert SomeClassProxy.class_method_with_args("a") == 2
2188            flexmock(SomeClassProxy).should_receive("static_method_with_args").with_args(
2189                "b"
2190            ).and_return(3).twice()
2191            assert SomeClassProxy().static_method_with_args("b") == 3
2192            assert SomeClassProxy.static_method_with_args("b") == 3
2193            instance = SomeClassProxy()
2194            flexmock(instance).should_receive("instance_method_with_args").with_args("c").and_return(
2195                4
2196            ).once()
2197            assert instance.instance_method_with_args("c") == 4
2198
2199        def test_spy_proxied_class(self):
2200            # pylint: disable=not-callable
2201            SomeClassProxy = Proxy(SomeClass)
2202            flexmock(SomeClassProxy).should_call("class_method").and_return("class_method").twice()
2203            assert SomeClassProxy().class_method() == "class_method"
2204            assert SomeClassProxy.class_method() == "class_method"
2205            flexmock(SomeClassProxy).should_call("static_method").and_return("static_method").twice()
2206            assert SomeClassProxy().static_method() == "static_method"
2207            assert SomeClassProxy.static_method() == "static_method"
2208            instance = SomeClassProxy()
2209            flexmock(instance).should_call("instance_method").and_return("instance_method").once()
2210            assert instance.instance_method() == "instance_method"
2211
2212        def test_spy_proxied_class_with_args(self):
2213            # pylint: disable=not-callable
2214            SomeClassProxy = Proxy(SomeClass)
2215            flexmock(SomeClassProxy).should_call("class_method_with_args").with_args("a").and_return(
2216                "a"
2217            ).twice()
2218            assert SomeClassProxy().class_method_with_args("a") == "a"
2219            assert SomeClassProxy.class_method_with_args("a") == "a"
2220            flexmock(SomeClassProxy).should_call("static_method_with_args").with_args("b").and_return(
2221                "b"
2222            ).twice()
2223            assert SomeClassProxy().static_method_with_args("b") == "b"
2224            assert SomeClassProxy.static_method_with_args("b") == "b"
2225            instance = SomeClassProxy()
2226            flexmock(instance).should_call("instance_method_with_args").with_args("c").and_return(
2227                "c"
2228            ).once()
2229            assert instance.instance_method_with_args("c") == "c"
2230
2231        def test_mock_proxied_derived_class(self):
2232            # pylint: disable=not-callable
2233            DerivedClassProxy = Proxy(DerivedClass)
2234            flexmock(DerivedClassProxy).should_receive("class_method").and_return(2).twice()
2235            assert DerivedClassProxy().class_method() == 2
2236            assert DerivedClassProxy.class_method() == 2
2237            flexmock(DerivedClassProxy).should_receive("static_method").and_return(3).twice()
2238            assert DerivedClassProxy().static_method() == 3
2239            assert DerivedClassProxy.static_method() == 3
2240            instance = DerivedClassProxy()
2241            flexmock(instance).should_receive("instance_method").and_return(4).once()
2242            assert instance.instance_method() == 4
2243
2244        def test_mock_proxied_module_function(self):
2245            # pylint: disable=not-callable
2246            some_module_proxy = Proxy(some_module)
2247            flexmock(some_module_proxy).should_receive("foo").and_return(3).once()
2248            assert some_module_proxy.foo() == 3
2249
2250        def test_spy_proxied_module_function(self):
2251            # pylint: disable=not-callable
2252            some_module_proxy = Proxy(some_module)
2253            flexmock(some_module_proxy).should_receive("foo").and_return(0).once()
2254            assert some_module_proxy.foo(2, 2) == 0
2255
2256        def test_mock_proxied_derived_class_with_args(self):
2257            # pylint: disable=not-callable
2258            DerivedClassProxy = Proxy(DerivedClass)
2259            flexmock(DerivedClassProxy).should_receive("class_method_with_args").with_args(
2260                "a"
2261            ).and_return(2).twice()
2262            assert DerivedClassProxy().class_method_with_args("a") == 2
2263            assert DerivedClassProxy.class_method_with_args("a") == 2
2264            flexmock(DerivedClassProxy).should_receive("static_method_with_args").with_args(
2265                "b"
2266            ).and_return(3).twice()
2267            assert DerivedClassProxy().static_method_with_args("b") == 3
2268            assert DerivedClassProxy.static_method_with_args("b") == 3
2269            instance = DerivedClassProxy()
2270            flexmock(instance).should_receive("instance_method_with_args").with_args("c").and_return(
2271                4
2272            ).once()
2273            assert instance.instance_method_with_args("c") == 4
2274
2275        def test_spy_proxied_derived_class(self):
2276            # pylint: disable=not-callable
2277            DerivedClassProxy = Proxy(DerivedClass)
2278            flexmock(DerivedClassProxy).should_call("class_method").and_return("class_method").twice()
2279            assert DerivedClassProxy().class_method() == "class_method"
2280            assert DerivedClassProxy.class_method() == "class_method"
2281            flexmock(DerivedClassProxy).should_call("static_method").and_return("static_method").twice()
2282            assert DerivedClassProxy().static_method() == "static_method"
2283            assert DerivedClassProxy.static_method() == "static_method"
2284            instance = DerivedClassProxy()
2285            flexmock(instance).should_call("instance_method").and_return("instance_method").once()
2286            assert instance.instance_method() == "instance_method"
2287
2288        def test_spy_proxied_derived_class_with_args(self):
2289            # pylint: disable=not-callable
2290            DerivedClassProxy = Proxy(DerivedClass)
2291            flexmock(DerivedClassProxy).should_call("class_method_with_args").with_args("a").and_return(
2292                "a"
2293            ).twice()
2294            assert DerivedClassProxy().class_method_with_args("a") == "a"
2295            assert DerivedClassProxy.class_method_with_args("a") == "a"
2296            flexmock(DerivedClassProxy).should_call("static_method_with_args").with_args(
2297                "b"
2298            ).and_return("b").twice()
2299            assert DerivedClassProxy().static_method_with_args("b") == "b"
2300            assert DerivedClassProxy.static_method_with_args("b") == "b"
2301            instance = DerivedClassProxy()
2302            flexmock(instance).should_call("instance_method_with_args").with_args("c").and_return(
2303                "c"
2304            ).once()
2305            assert instance.instance_method_with_args("c") == "c"
2306
2307
2308if __name__ == '__main__':
2309    unittest.main()
2310