forked from pytest-dev/pytest-mock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_pytest_mock.py
470 lines (347 loc) · 12.2 KB
/
test_pytest_mock.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
import os
import platform
import sys
from contextlib import contextmanager
import py.code
import pytest
pytest_plugins = 'pytester'
# could not make some of the tests work on PyPy, patches are welcome!
skip_pypy = pytest.mark.skipif(platform.python_implementation() == 'PyPy',
reason='could not make work on pypy')
class UnixFS(object):
"""
Wrapper to os functions to simulate a Unix file system, used for testing
the mock fixture.
"""
@classmethod
def rm(cls, filename):
os.remove(filename)
@classmethod
def ls(cls, path):
return os.listdir(path)
@pytest.fixture
def check_unix_fs_mocked(tmpdir, mocker):
"""
performs a standard test in a UnixFS, assuming that both `os.remove` and
`os.listdir` have been mocked previously.
"""
def check(mocked_rm, mocked_ls):
assert mocked_rm is os.remove
assert mocked_ls is os.listdir
file_name = tmpdir / 'foo.txt'
file_name.ensure()
UnixFS.rm(str(file_name))
mocked_rm.assert_called_once_with(str(file_name))
assert os.path.isfile(str(file_name))
mocked_ls.return_value = ['bar.txt']
assert UnixFS.ls(str(tmpdir)) == ['bar.txt']
mocked_ls.assert_called_once_with(str(tmpdir))
mocker.stopall()
assert UnixFS.ls(str(tmpdir)) == ['foo.txt']
UnixFS.rm(str(file_name))
assert not os.path.isfile(str(file_name))
return check
def mock_using_patch_object(mocker):
return mocker.patch.object(os, 'remove'), mocker.patch.object(os, 'listdir')
def mock_using_patch(mocker):
return mocker.patch('os.remove'), mocker.patch('os.listdir')
def mock_using_patch_multiple(mocker):
from pytest_mock import mock_module
r = mocker.patch.multiple('os', remove=mock_module.DEFAULT,
listdir=mock_module.DEFAULT)
return r['remove'], r['listdir']
@pytest.mark.parametrize('mock_fs', [mock_using_patch_object, mock_using_patch,
mock_using_patch_multiple],
)
def test_mock_patches(mock_fs, mocker, check_unix_fs_mocked):
"""
Installs mocks into `os` functions and performs a standard testing of
mock functionality. We parametrize different mock methods to ensure
all (intended, at least) mock API is covered.
"""
# mock it twice on purpose to ensure we unmock it correctly later
mock_fs(mocker)
mocked_rm, mocked_ls = mock_fs(mocker)
check_unix_fs_mocked(mocked_rm, mocked_ls)
def test_mock_patch_dict(mocker):
"""
Testing
:param mock:
"""
x = {'original': 1}
mocker.patch.dict(x, values=[('new', 10)], clear=True)
assert x == {'new': 10}
mocker.stopall()
assert x == {'original': 1}
def test_mock_fixture_is_deprecated(testdir):
"""
Test that a warning emitted when using deprecated "mock" fixture.
"""
testdir.makepyfile('''
import warnings
import os
warnings.simplefilter('always')
def test_foo(mock, tmpdir):
mock.patch('os.listdir', return_value=['mocked'])
assert os.listdir(str(tmpdir)) == ['mocked']
mock.stopall()
assert os.listdir(str(tmpdir)) == []
''')
result = testdir.runpytest('-s')
result.stderr.fnmatch_lines(['*"mock" fixture has been deprecated*'])
def test_deprecated_mock(mock, tmpdir):
"""
Use backward-compatibility-only mock fixture to ensure complete coverage.
"""
mock.patch('os.listdir', return_value=['mocked'])
assert os.listdir(str(tmpdir)) == ['mocked']
mock.stopall()
assert os.listdir(str(tmpdir)) == []
def test_mocker_has_magic_mock_class_as_attribute_for_instantiation():
from pytest_mock import mock_module, MockFixture
mocker = MockFixture()
assert isinstance(mocker.MagicMock(), mock_module.MagicMock)
def test_mocker_has_property_mock_class_as_attribute_for_instantiation():
from pytest_mock import mock_module, MockFixture
mocker = MockFixture()
assert isinstance(mocker.PropertyMock(), mock_module.PropertyMock)
def test_mocker_has_mock_class_as_attribute_for_instantiation():
from pytest_mock import mock_module, MockFixture
mocker = MockFixture()
assert isinstance(mocker.Mock(), mock_module.Mock)
def test_mocker_resetall(mocker):
listdir = mocker.patch('os.listdir')
open = mocker.patch('os.open')
listdir("/tmp")
open("/tmp/foo.txt")
listdir.assert_called_once_with("/tmp")
open.assert_called_once_with("/tmp/foo.txt")
mocker.resetall()
assert not listdir.called
assert not open.called
def test_mocker_stub(mocker):
def foo(on_something):
on_something('foo', 'bar')
stub = mocker.stub()
foo(stub)
stub.assert_called_once_with('foo', 'bar')
def test_instance_method_spy(mocker):
class Foo(object):
def bar(self, arg):
return arg * 2
foo = Foo()
other = Foo()
spy = mocker.spy(foo, 'bar')
assert foo.bar(arg=10) == 20
assert other.bar(arg=10) == 20
foo.bar.assert_called_once_with(arg=10)
spy.assert_called_once_with(arg=10)
@skip_pypy
def test_instance_method_by_class_spy(mocker):
from pytest_mock import mock_module
class Foo(object):
def bar(self, arg):
return arg * 2
spy = mocker.spy(Foo, 'bar')
foo = Foo()
other = Foo()
assert foo.bar(arg=10) == 20
assert other.bar(arg=10) == 20
calls = [mock_module.call(foo, arg=10), mock_module.call(other, arg=10)]
assert spy.call_args_list == calls
@skip_pypy
def test_instance_method_by_subclass_spy(mocker):
from pytest_mock import mock_module
class Base(object):
def bar(self, arg):
return arg * 2
class Foo(Base):
pass
spy = mocker.spy(Foo, 'bar')
foo = Foo()
other = Foo()
assert foo.bar(arg=10) == 20
assert other.bar(arg=10) == 20
calls = [mock_module.call(foo, arg=10), mock_module.call(other, arg=10)]
assert spy.call_args_list == calls
@skip_pypy
def test_class_method_spy(mocker):
class Foo(object):
@classmethod
def bar(cls, arg):
return arg * 2
spy = mocker.spy(Foo, 'bar')
assert Foo.bar(arg=10) == 20
Foo.bar.assert_called_once_with(arg=10)
spy.assert_called_once_with(arg=10)
@skip_pypy
@pytest.mark.xfail(sys.version_info[0] == 2, reason='does not work on Python 2')
def test_class_method_subclass_spy(mocker):
class Base(object):
@classmethod
def bar(self, arg):
return arg * 2
class Foo(Base):
pass
spy = mocker.spy(Foo, 'bar')
assert Foo.bar(arg=10) == 20
Foo.bar.assert_called_once_with(arg=10)
spy.assert_called_once_with(arg=10)
@skip_pypy
def test_class_method_with_metaclass_spy(mocker):
class MetaFoo(type):
pass
class Foo(object):
__metaclass__ = MetaFoo
@classmethod
def bar(cls, arg):
return arg * 2
spy = mocker.spy(Foo, 'bar')
assert Foo.bar(arg=10) == 20
Foo.bar.assert_called_once_with(arg=10)
spy.assert_called_once_with(arg=10)
@skip_pypy
def test_static_method_spy(mocker):
class Foo(object):
@staticmethod
def bar(arg):
return arg * 2
spy = mocker.spy(Foo, 'bar')
assert Foo.bar(arg=10) == 20
Foo.bar.assert_called_once_with(arg=10)
spy.assert_called_once_with(arg=10)
@skip_pypy
@pytest.mark.xfail(sys.version_info[0] == 2, reason='does not work on Python 2')
def test_static_method_subclass_spy(mocker):
class Base(object):
@staticmethod
def bar(arg):
return arg * 2
class Foo(Base):
pass
spy = mocker.spy(Foo, 'bar')
assert Foo.bar(arg=10) == 20
Foo.bar.assert_called_once_with(arg=10)
spy.assert_called_once_with(arg=10)
@contextmanager
def assert_traceback():
"""
Assert that this file is at the top of the filtered traceback
"""
try:
yield
except AssertionError:
traceback = py.code.ExceptionInfo().traceback
crashentry = traceback.getcrashentry()
assert crashentry.path == __file__
else:
raise AssertionError("DID NOT RAISE")
@contextmanager
def assert_argument_introspection(left, right):
"""
Assert detailed argument introspection is used
"""
try:
yield
except AssertionError as e:
# this may be a bit too assuming, but seems nicer then hard-coding
import _pytest.assertion.util as util
# NOTE: we assert with either verbose or not, depending on how our own
# test was run by examining sys.argv
verbose = any(a.startswith('-v') for a in sys.argv)
expected = '\n '.join(util._compare_eq_iterable(left, right, verbose))
assert expected in e.msg
else:
raise AssertionError("DID NOT RAISE")
@pytest.mark.skipif(sys.version_info[0] == 3 and sys.version_info[1] in (3, 4),
reason="assert_not_called not available in python 3.3 and 3.4")
def test_assert_not_called_wrapper(mocker):
stub = mocker.stub()
stub.assert_not_called()
stub()
with assert_traceback():
stub.assert_not_called()
def test_assert_called_with_wrapper(mocker):
stub = mocker.stub()
stub("foo")
stub.assert_called_with("foo")
with assert_traceback():
stub.assert_called_with("bar")
def test_assert_called_once_with_wrapper(mocker):
stub = mocker.stub()
stub("foo")
stub.assert_called_once_with("foo")
stub("foo")
with assert_traceback():
stub.assert_called_once_with("foo")
def test_assert_called_args_with_introspection(mocker):
stub = mocker.stub()
complex_args = ('a', 1, set(['test']))
wrong_args = ('b', 2, set(['jest']))
stub(*complex_args)
stub.assert_called_with(*complex_args)
stub.assert_called_once_with(*complex_args)
with assert_argument_introspection(complex_args, wrong_args):
stub.assert_called_with(*wrong_args)
stub.assert_called_once_with(*wrong_args)
def test_assert_called_kwargs_with_introspection(mocker):
stub = mocker.stub()
complex_kwargs = dict(foo={'bar': 1, 'baz': 'spam'})
wrong_kwargs = dict(foo={'goo': 1, 'baz': 'bran'})
stub(**complex_kwargs)
stub.assert_called_with(**complex_kwargs)
stub.assert_called_once_with(**complex_kwargs)
with assert_argument_introspection(complex_kwargs, wrong_kwargs):
stub.assert_called_with(**wrong_kwargs)
stub.assert_called_once_with(**wrong_kwargs)
def test_assert_any_call_wrapper(mocker):
stub = mocker.stub()
stub("foo")
stub("foo")
stub.assert_any_call("foo")
with assert_traceback():
stub.assert_any_call("bar")
def test_assert_has_calls(mocker):
from pytest_mock import mock_module
stub = mocker.stub()
stub("foo")
stub.assert_has_calls([mock_module.call("foo")])
with assert_traceback():
stub.assert_has_calls([mock_module.call("bar")])
def test_monkeypatch_ini(mocker, testdir):
# Make sure the following function actually tests something
stub = mocker.stub()
assert stub.assert_called_with.__module__ != stub.__module__
testdir.makepyfile("""
import py.code
def test_foo(mocker):
stub = mocker.stub()
assert stub.assert_called_with.__module__ == stub.__module__
""")
testdir.makeini("""
[pytest]
mock_traceback_monkeypatch = false
""")
if hasattr(testdir, 'runpytest_subprocess'):
result = testdir.runpytest_subprocess()
else:
# pytest 2.7.X
result = testdir.runpytest()
assert result.ret == 0
def test_parse_ini_boolean(testdir):
import pytest_mock
assert pytest_mock.parse_ini_boolean('True') is True
assert pytest_mock.parse_ini_boolean('false') is False
with pytest.raises(ValueError):
pytest_mock.parse_ini_boolean('foo')
def test_patched_method_parameter_name(mocker):
"""Test that our internal code uses uncommon names when wrapping other
"mock" methods to avoid conflicts with user code (#31).
"""
class Request:
@classmethod
def request(cls, method, args):
pass
m = mocker.patch.object(Request, 'request')
Request.request(method='get', args={'type': 'application/json'})
m.assert_called_once_with(method='get', args={'type': 'application/json'})