mirror of
https://github.com/Tautulli/Tautulli.git
synced 2025-07-06 05:01:14 -07:00
Add mock 4.0.2
This commit is contained in:
parent
c55c00a19e
commit
1dfbef89ff
14 changed files with 10635 additions and 0 deletions
15
lib/mock/__init__.py
Normal file
15
lib/mock/__init__.py
Normal file
|
@ -0,0 +1,15 @@
|
|||
from __future__ import absolute_import
|
||||
|
||||
import re, sys
|
||||
|
||||
IS_PYPY = 'PyPy' in sys.version
|
||||
|
||||
import mock.mock as _mock
|
||||
from mock.mock import *
|
||||
|
||||
__version__ = '4.0.2'
|
||||
version_info = tuple(int(p) for p in
|
||||
re.match(r'(\d+).(\d+).(\d+)', __version__).groups())
|
||||
|
||||
|
||||
__all__ = ('__version__', 'version_info') + _mock.__all__
|
89
lib/mock/backports.py
Normal file
89
lib/mock/backports.py
Normal file
|
@ -0,0 +1,89 @@
|
|||
import sys
|
||||
|
||||
|
||||
if sys.version_info[:2] < (3, 8):
|
||||
|
||||
import asyncio, functools
|
||||
from asyncio.coroutines import _is_coroutine
|
||||
from inspect import ismethod, isfunction, CO_COROUTINE
|
||||
from unittest import TestCase
|
||||
|
||||
def _unwrap_partial(func):
|
||||
while isinstance(func, functools.partial):
|
||||
func = func.func
|
||||
return func
|
||||
|
||||
def _has_code_flag(f, flag):
|
||||
"""Return true if ``f`` is a function (or a method or functools.partial
|
||||
wrapper wrapping a function) whose code object has the given ``flag``
|
||||
set in its flags."""
|
||||
while ismethod(f):
|
||||
f = f.__func__
|
||||
f = _unwrap_partial(f)
|
||||
if not isfunction(f):
|
||||
return False
|
||||
return bool(f.__code__.co_flags & flag)
|
||||
|
||||
def iscoroutinefunction(obj):
|
||||
"""Return true if the object is a coroutine function.
|
||||
|
||||
Coroutine functions are defined with "async def" syntax.
|
||||
"""
|
||||
return (
|
||||
_has_code_flag(obj, CO_COROUTINE) or
|
||||
getattr(obj, '_is_coroutine', None) is _is_coroutine
|
||||
)
|
||||
|
||||
|
||||
class IsolatedAsyncioTestCase(TestCase):
|
||||
|
||||
def __init__(self, methodName='runTest'):
|
||||
super().__init__(methodName)
|
||||
self._asyncioTestLoop = None
|
||||
self._asyncioCallsQueue = None
|
||||
|
||||
async def _asyncioLoopRunner(self, fut):
|
||||
self._asyncioCallsQueue = queue = asyncio.Queue()
|
||||
fut.set_result(None)
|
||||
while True:
|
||||
query = await queue.get()
|
||||
queue.task_done()
|
||||
assert query is None
|
||||
|
||||
def _setupAsyncioLoop(self):
|
||||
assert self._asyncioTestLoop is None
|
||||
loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(loop)
|
||||
loop.set_debug(True)
|
||||
self._asyncioTestLoop = loop
|
||||
fut = loop.create_future()
|
||||
self._asyncioCallsTask = loop.create_task(self._asyncioLoopRunner(fut))
|
||||
loop.run_until_complete(fut)
|
||||
|
||||
def _tearDownAsyncioLoop(self):
|
||||
assert self._asyncioTestLoop is not None
|
||||
loop = self._asyncioTestLoop
|
||||
self._asyncioTestLoop = None
|
||||
self._asyncioCallsQueue.put_nowait(None)
|
||||
loop.run_until_complete(self._asyncioCallsQueue.join())
|
||||
|
||||
try:
|
||||
# shutdown asyncgens
|
||||
loop.run_until_complete(loop.shutdown_asyncgens())
|
||||
finally:
|
||||
asyncio.set_event_loop(None)
|
||||
loop.close()
|
||||
|
||||
def run(self, result=None):
|
||||
self._setupAsyncioLoop()
|
||||
try:
|
||||
return super().run(result)
|
||||
finally:
|
||||
self._tearDownAsyncioLoop()
|
||||
|
||||
|
||||
else:
|
||||
|
||||
from asyncio import iscoroutinefunction
|
||||
from unittest import IsolatedAsyncioTestCase
|
||||
|
2941
lib/mock/mock.py
Normal file
2941
lib/mock/mock.py
Normal file
File diff suppressed because it is too large
Load diff
0
lib/mock/tests/__init__.py
Normal file
0
lib/mock/tests/__init__.py
Normal file
52
lib/mock/tests/support.py
Normal file
52
lib/mock/tests/support.py
Normal file
|
@ -0,0 +1,52 @@
|
|||
import contextlib
|
||||
import sys
|
||||
|
||||
target = {'foo': 'FOO'}
|
||||
|
||||
|
||||
def is_instance(obj, klass):
|
||||
"""Version of is_instance that doesn't access __class__"""
|
||||
return issubclass(type(obj), klass)
|
||||
|
||||
|
||||
class SomeClass(object):
|
||||
class_attribute = None
|
||||
|
||||
def wibble(self): pass
|
||||
|
||||
|
||||
class X(object):
|
||||
pass
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def uncache(*names):
|
||||
"""Uncache a module from sys.modules.
|
||||
|
||||
A basic sanity check is performed to prevent uncaching modules that either
|
||||
cannot/shouldn't be uncached.
|
||||
|
||||
"""
|
||||
for name in names:
|
||||
assert name not in ('sys', 'marshal', 'imp')
|
||||
try:
|
||||
del sys.modules[name]
|
||||
except KeyError:
|
||||
pass
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
for name in names:
|
||||
del sys.modules[name]
|
||||
|
||||
|
||||
class _ALWAYS_EQ:
|
||||
"""
|
||||
Object that is equal to anything.
|
||||
"""
|
||||
def __eq__(self, other):
|
||||
return True
|
||||
def __ne__(self, other):
|
||||
return False
|
||||
|
||||
ALWAYS_EQ = _ALWAYS_EQ()
|
1074
lib/mock/tests/testasync.py
Normal file
1074
lib/mock/tests/testasync.py
Normal file
File diff suppressed because it is too large
Load diff
149
lib/mock/tests/testcallable.py
Normal file
149
lib/mock/tests/testcallable.py
Normal file
|
@ -0,0 +1,149 @@
|
|||
# Copyright (C) 2007-2012 Michael Foord & the mock team
|
||||
# E-mail: fuzzyman AT voidspace DOT org DOT uk
|
||||
# http://www.voidspace.org.uk/python/mock/
|
||||
|
||||
import unittest
|
||||
from mock.tests.support import is_instance, X, SomeClass
|
||||
|
||||
from mock import (
|
||||
Mock, MagicMock, NonCallableMagicMock,
|
||||
NonCallableMock, patch, create_autospec,
|
||||
)
|
||||
from mock.mock import CallableMixin
|
||||
|
||||
|
||||
class TestCallable(unittest.TestCase):
|
||||
|
||||
def assertNotCallable(self, mock):
|
||||
self.assertTrue(is_instance(mock, NonCallableMagicMock))
|
||||
self.assertFalse(is_instance(mock, CallableMixin))
|
||||
|
||||
|
||||
def test_non_callable(self):
|
||||
for mock in NonCallableMagicMock(), NonCallableMock():
|
||||
self.assertRaises(TypeError, mock)
|
||||
self.assertFalse(hasattr(mock, '__call__'))
|
||||
self.assertIn(mock.__class__.__name__, repr(mock))
|
||||
|
||||
|
||||
def test_hierarchy(self):
|
||||
self.assertTrue(issubclass(MagicMock, Mock))
|
||||
self.assertTrue(issubclass(NonCallableMagicMock, NonCallableMock))
|
||||
|
||||
|
||||
def test_attributes(self):
|
||||
one = NonCallableMock()
|
||||
self.assertTrue(issubclass(type(one.one), Mock))
|
||||
|
||||
two = NonCallableMagicMock()
|
||||
self.assertTrue(issubclass(type(two.two), MagicMock))
|
||||
|
||||
|
||||
def test_subclasses(self):
|
||||
class MockSub(Mock):
|
||||
pass
|
||||
|
||||
one = MockSub()
|
||||
self.assertTrue(issubclass(type(one.one), MockSub))
|
||||
|
||||
class MagicSub(MagicMock):
|
||||
pass
|
||||
|
||||
two = MagicSub()
|
||||
self.assertTrue(issubclass(type(two.two), MagicSub))
|
||||
|
||||
|
||||
def test_patch_spec(self):
|
||||
patcher = patch('%s.X' % __name__, spec=True)
|
||||
mock = patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
instance = mock()
|
||||
mock.assert_called_once_with()
|
||||
|
||||
self.assertNotCallable(instance)
|
||||
self.assertRaises(TypeError, instance)
|
||||
|
||||
|
||||
def test_patch_spec_set(self):
|
||||
patcher = patch('%s.X' % __name__, spec_set=True)
|
||||
mock = patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
instance = mock()
|
||||
mock.assert_called_once_with()
|
||||
|
||||
self.assertNotCallable(instance)
|
||||
self.assertRaises(TypeError, instance)
|
||||
|
||||
|
||||
def test_patch_spec_instance(self):
|
||||
patcher = patch('%s.X' % __name__, spec=X())
|
||||
mock = patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
self.assertNotCallable(mock)
|
||||
self.assertRaises(TypeError, mock)
|
||||
|
||||
|
||||
def test_patch_spec_set_instance(self):
|
||||
patcher = patch('%s.X' % __name__, spec_set=X())
|
||||
mock = patcher.start()
|
||||
self.addCleanup(patcher.stop)
|
||||
|
||||
self.assertNotCallable(mock)
|
||||
self.assertRaises(TypeError, mock)
|
||||
|
||||
|
||||
def test_patch_spec_callable_class(self):
|
||||
class CallableX(X):
|
||||
def __call__(self): pass
|
||||
|
||||
class Sub(CallableX):
|
||||
pass
|
||||
|
||||
class Multi(SomeClass, Sub):
|
||||
pass
|
||||
|
||||
for arg in 'spec', 'spec_set':
|
||||
for Klass in CallableX, Sub, Multi:
|
||||
with patch('%s.X' % __name__, **{arg: Klass}) as mock:
|
||||
instance = mock()
|
||||
mock.assert_called_once_with()
|
||||
|
||||
self.assertTrue(is_instance(instance, MagicMock))
|
||||
# inherited spec
|
||||
self.assertRaises(AttributeError, getattr, instance,
|
||||
'foobarbaz')
|
||||
|
||||
result = instance()
|
||||
# instance is callable, result has no spec
|
||||
instance.assert_called_once_with()
|
||||
|
||||
result(3, 2, 1)
|
||||
result.assert_called_once_with(3, 2, 1)
|
||||
result.foo(3, 2, 1)
|
||||
result.foo.assert_called_once_with(3, 2, 1)
|
||||
|
||||
|
||||
def test_create_autospec(self):
|
||||
mock = create_autospec(X)
|
||||
instance = mock()
|
||||
self.assertRaises(TypeError, instance)
|
||||
|
||||
mock = create_autospec(X())
|
||||
self.assertRaises(TypeError, mock)
|
||||
|
||||
|
||||
def test_create_autospec_instance(self):
|
||||
mock = create_autospec(SomeClass, instance=True)
|
||||
|
||||
self.assertRaises(TypeError, mock)
|
||||
mock.wibble()
|
||||
mock.wibble.assert_called_once_with()
|
||||
|
||||
self.assertRaises(TypeError, mock.wibble, 'some', 'args')
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
1136
lib/mock/tests/testhelpers.py
Normal file
1136
lib/mock/tests/testhelpers.py
Normal file
File diff suppressed because it is too large
Load diff
509
lib/mock/tests/testmagicmethods.py
Normal file
509
lib/mock/tests/testmagicmethods.py
Normal file
|
@ -0,0 +1,509 @@
|
|||
import math
|
||||
import unittest
|
||||
import os
|
||||
from mock import AsyncMock, Mock, MagicMock
|
||||
from mock.backports import iscoroutinefunction
|
||||
from mock.mock import _magics
|
||||
|
||||
|
||||
class TestMockingMagicMethods(unittest.TestCase):
|
||||
|
||||
def test_deleting_magic_methods(self):
|
||||
mock = Mock()
|
||||
self.assertFalse(hasattr(mock, '__getitem__'))
|
||||
|
||||
mock.__getitem__ = Mock()
|
||||
self.assertTrue(hasattr(mock, '__getitem__'))
|
||||
|
||||
del mock.__getitem__
|
||||
self.assertFalse(hasattr(mock, '__getitem__'))
|
||||
|
||||
|
||||
def test_magicmock_del(self):
|
||||
mock = MagicMock()
|
||||
# before using getitem
|
||||
del mock.__getitem__
|
||||
self.assertRaises(TypeError, lambda: mock['foo'])
|
||||
|
||||
mock = MagicMock()
|
||||
# this time use it first
|
||||
mock['foo']
|
||||
del mock.__getitem__
|
||||
self.assertRaises(TypeError, lambda: mock['foo'])
|
||||
|
||||
|
||||
def test_magic_method_wrapping(self):
|
||||
mock = Mock()
|
||||
def f(self, name):
|
||||
return self, 'fish'
|
||||
|
||||
mock.__getitem__ = f
|
||||
self.assertIsNot(mock.__getitem__, f)
|
||||
self.assertEqual(mock['foo'], (mock, 'fish'))
|
||||
self.assertEqual(mock.__getitem__('foo'), (mock, 'fish'))
|
||||
|
||||
mock.__getitem__ = mock
|
||||
self.assertIs(mock.__getitem__, mock)
|
||||
|
||||
|
||||
def test_magic_methods_isolated_between_mocks(self):
|
||||
mock1 = Mock()
|
||||
mock2 = Mock()
|
||||
|
||||
mock1.__iter__ = Mock(return_value=iter([]))
|
||||
self.assertEqual(list(mock1), [])
|
||||
self.assertRaises(TypeError, lambda: list(mock2))
|
||||
|
||||
|
||||
def test_repr(self):
|
||||
mock = Mock()
|
||||
self.assertEqual(repr(mock), "<Mock id='%s'>" % id(mock))
|
||||
mock.__repr__ = lambda s: 'foo'
|
||||
self.assertEqual(repr(mock), 'foo')
|
||||
|
||||
|
||||
def test_str(self):
|
||||
mock = Mock()
|
||||
self.assertEqual(str(mock), object.__str__(mock))
|
||||
mock.__str__ = lambda s: 'foo'
|
||||
self.assertEqual(str(mock), 'foo')
|
||||
|
||||
|
||||
def test_dict_methods(self):
|
||||
mock = Mock()
|
||||
|
||||
self.assertRaises(TypeError, lambda: mock['foo'])
|
||||
def _del():
|
||||
del mock['foo']
|
||||
def _set():
|
||||
mock['foo'] = 3
|
||||
self.assertRaises(TypeError, _del)
|
||||
self.assertRaises(TypeError, _set)
|
||||
|
||||
_dict = {}
|
||||
def getitem(s, name):
|
||||
return _dict[name]
|
||||
def setitem(s, name, value):
|
||||
_dict[name] = value
|
||||
def delitem(s, name):
|
||||
del _dict[name]
|
||||
|
||||
mock.__setitem__ = setitem
|
||||
mock.__getitem__ = getitem
|
||||
mock.__delitem__ = delitem
|
||||
|
||||
self.assertRaises(KeyError, lambda: mock['foo'])
|
||||
mock['foo'] = 'bar'
|
||||
self.assertEqual(_dict, {'foo': 'bar'})
|
||||
self.assertEqual(mock['foo'], 'bar')
|
||||
del mock['foo']
|
||||
self.assertEqual(_dict, {})
|
||||
|
||||
|
||||
def test_numeric(self):
|
||||
original = mock = Mock()
|
||||
mock.value = 0
|
||||
|
||||
self.assertRaises(TypeError, lambda: mock + 3)
|
||||
|
||||
def add(self, other):
|
||||
mock.value += other
|
||||
return self
|
||||
mock.__add__ = add
|
||||
self.assertEqual(mock + 3, mock)
|
||||
self.assertEqual(mock.value, 3)
|
||||
|
||||
del mock.__add__
|
||||
def iadd(mock):
|
||||
mock += 3
|
||||
self.assertRaises(TypeError, iadd, mock)
|
||||
mock.__iadd__ = add
|
||||
mock += 6
|
||||
self.assertEqual(mock, original)
|
||||
self.assertEqual(mock.value, 9)
|
||||
|
||||
self.assertRaises(TypeError, lambda: 3 + mock)
|
||||
mock.__radd__ = add
|
||||
self.assertEqual(7 + mock, mock)
|
||||
self.assertEqual(mock.value, 16)
|
||||
|
||||
def test_division(self):
|
||||
original = mock = Mock()
|
||||
mock.value = 32
|
||||
self.assertRaises(TypeError, lambda: mock / 2)
|
||||
|
||||
def truediv(self, other):
|
||||
mock.value /= other
|
||||
return self
|
||||
mock.__truediv__ = truediv
|
||||
self.assertEqual(mock / 2, mock)
|
||||
self.assertEqual(mock.value, 16)
|
||||
|
||||
del mock.__truediv__
|
||||
def itruediv(mock):
|
||||
mock /= 4
|
||||
self.assertRaises(TypeError, itruediv, mock)
|
||||
mock.__itruediv__ = truediv
|
||||
mock /= 8
|
||||
self.assertEqual(mock, original)
|
||||
self.assertEqual(mock.value, 2)
|
||||
|
||||
self.assertRaises(TypeError, lambda: 8 / mock)
|
||||
mock.__rtruediv__ = truediv
|
||||
self.assertEqual(0.5 / mock, mock)
|
||||
self.assertEqual(mock.value, 4)
|
||||
|
||||
def test_hash(self):
|
||||
mock = Mock()
|
||||
# test delegation
|
||||
self.assertEqual(hash(mock), Mock.__hash__(mock))
|
||||
|
||||
def _hash(s):
|
||||
return 3
|
||||
mock.__hash__ = _hash
|
||||
self.assertEqual(hash(mock), 3)
|
||||
|
||||
|
||||
def test_nonzero(self):
|
||||
m = Mock()
|
||||
self.assertTrue(bool(m))
|
||||
|
||||
m.__bool__ = lambda s: False
|
||||
self.assertFalse(bool(m))
|
||||
|
||||
|
||||
def test_comparison(self):
|
||||
mock = Mock()
|
||||
def comp(s, o):
|
||||
return True
|
||||
mock.__lt__ = mock.__gt__ = mock.__le__ = mock.__ge__ = comp
|
||||
self. assertTrue(mock < 3)
|
||||
self. assertTrue(mock > 3)
|
||||
self. assertTrue(mock <= 3)
|
||||
self. assertTrue(mock >= 3)
|
||||
|
||||
self.assertRaises(TypeError, lambda: MagicMock() < object())
|
||||
self.assertRaises(TypeError, lambda: object() < MagicMock())
|
||||
self.assertRaises(TypeError, lambda: MagicMock() < MagicMock())
|
||||
self.assertRaises(TypeError, lambda: MagicMock() > object())
|
||||
self.assertRaises(TypeError, lambda: object() > MagicMock())
|
||||
self.assertRaises(TypeError, lambda: MagicMock() > MagicMock())
|
||||
self.assertRaises(TypeError, lambda: MagicMock() <= object())
|
||||
self.assertRaises(TypeError, lambda: object() <= MagicMock())
|
||||
self.assertRaises(TypeError, lambda: MagicMock() <= MagicMock())
|
||||
self.assertRaises(TypeError, lambda: MagicMock() >= object())
|
||||
self.assertRaises(TypeError, lambda: object() >= MagicMock())
|
||||
self.assertRaises(TypeError, lambda: MagicMock() >= MagicMock())
|
||||
|
||||
|
||||
def test_equality(self):
|
||||
for mock in Mock(), MagicMock():
|
||||
self.assertEqual(mock == mock, True)
|
||||
self.assertIsInstance(mock == mock, bool)
|
||||
self.assertEqual(mock != mock, False)
|
||||
self.assertIsInstance(mock != mock, bool)
|
||||
self.assertEqual(mock == object(), False)
|
||||
self.assertEqual(mock != object(), True)
|
||||
|
||||
def eq(self, other):
|
||||
return other == 3
|
||||
mock.__eq__ = eq
|
||||
self.assertTrue(mock == 3)
|
||||
self.assertFalse(mock == 4)
|
||||
|
||||
def ne(self, other):
|
||||
return other == 3
|
||||
mock.__ne__ = ne
|
||||
self.assertTrue(mock != 3)
|
||||
self.assertFalse(mock != 4)
|
||||
|
||||
mock = MagicMock()
|
||||
mock.__eq__.return_value = True
|
||||
self.assertIsInstance(mock == 3, bool)
|
||||
self.assertEqual(mock == 3, True)
|
||||
|
||||
mock.__ne__.return_value = False
|
||||
self.assertIsInstance(mock != 3, bool)
|
||||
self.assertEqual(mock != 3, False)
|
||||
|
||||
|
||||
def test_len_contains_iter(self):
|
||||
mock = Mock()
|
||||
|
||||
self.assertRaises(TypeError, len, mock)
|
||||
self.assertRaises(TypeError, iter, mock)
|
||||
self.assertRaises(TypeError, lambda: 'foo' in mock)
|
||||
|
||||
mock.__len__ = lambda s: 6
|
||||
self.assertEqual(len(mock), 6)
|
||||
|
||||
mock.__contains__ = lambda s, o: o == 3
|
||||
self.assertIn(3, mock)
|
||||
self.assertNotIn(6, mock)
|
||||
|
||||
mock.__iter__ = lambda s: iter('foobarbaz')
|
||||
self.assertEqual(list(mock), list('foobarbaz'))
|
||||
|
||||
|
||||
def test_magicmock(self):
|
||||
mock = MagicMock()
|
||||
|
||||
mock.__iter__.return_value = iter([1, 2, 3])
|
||||
self.assertEqual(list(mock), [1, 2, 3])
|
||||
|
||||
getattr(mock, '__bool__').return_value = False
|
||||
self.assertFalse(hasattr(mock, '__nonzero__'))
|
||||
self.assertFalse(bool(mock))
|
||||
|
||||
for entry in _magics:
|
||||
self.assertTrue(hasattr(mock, entry))
|
||||
self.assertFalse(hasattr(mock, '__imaginary__'))
|
||||
|
||||
|
||||
def test_magic_mock_equality(self):
|
||||
mock = MagicMock()
|
||||
self.assertIsInstance(mock == object(), bool)
|
||||
self.assertIsInstance(mock != object(), bool)
|
||||
|
||||
self.assertEqual(mock == object(), False)
|
||||
self.assertEqual(mock != object(), True)
|
||||
self.assertEqual(mock == mock, True)
|
||||
self.assertEqual(mock != mock, False)
|
||||
|
||||
def test_asyncmock_defaults(self):
|
||||
mock = AsyncMock()
|
||||
self.assertEqual(int(mock), 1)
|
||||
self.assertEqual(complex(mock), 1j)
|
||||
self.assertEqual(float(mock), 1.0)
|
||||
self.assertNotIn(object(), mock)
|
||||
self.assertEqual(len(mock), 0)
|
||||
self.assertEqual(list(mock), [])
|
||||
self.assertEqual(hash(mock), object.__hash__(mock))
|
||||
self.assertEqual(str(mock), object.__str__(mock))
|
||||
self.assertTrue(bool(mock))
|
||||
self.assertEqual(round(mock), mock.__round__())
|
||||
self.assertEqual(math.trunc(mock), mock.__trunc__())
|
||||
self.assertEqual(math.floor(mock), mock.__floor__())
|
||||
self.assertEqual(math.ceil(mock), mock.__ceil__())
|
||||
self.assertTrue(iscoroutinefunction(mock.__aexit__))
|
||||
self.assertTrue(iscoroutinefunction(mock.__aenter__))
|
||||
self.assertIsInstance(mock.__aenter__, AsyncMock)
|
||||
self.assertIsInstance(mock.__aexit__, AsyncMock)
|
||||
|
||||
# in Python 3 oct and hex use __index__
|
||||
# so these tests are for __index__ in py3k
|
||||
self.assertEqual(oct(mock), '0o1')
|
||||
self.assertEqual(hex(mock), '0x1')
|
||||
# how to test __sizeof__ ?
|
||||
|
||||
def test_magicmock_defaults(self):
|
||||
mock = MagicMock()
|
||||
self.assertEqual(int(mock), 1)
|
||||
self.assertEqual(complex(mock), 1j)
|
||||
self.assertEqual(float(mock), 1.0)
|
||||
self.assertNotIn(object(), mock)
|
||||
self.assertEqual(len(mock), 0)
|
||||
self.assertEqual(list(mock), [])
|
||||
self.assertEqual(hash(mock), object.__hash__(mock))
|
||||
self.assertEqual(str(mock), object.__str__(mock))
|
||||
self.assertTrue(bool(mock))
|
||||
self.assertEqual(round(mock), mock.__round__())
|
||||
self.assertEqual(math.trunc(mock), mock.__trunc__())
|
||||
self.assertEqual(math.floor(mock), mock.__floor__())
|
||||
self.assertEqual(math.ceil(mock), mock.__ceil__())
|
||||
self.assertTrue(iscoroutinefunction(mock.__aexit__))
|
||||
self.assertTrue(iscoroutinefunction(mock.__aenter__))
|
||||
self.assertIsInstance(mock.__aenter__, AsyncMock)
|
||||
self.assertIsInstance(mock.__aexit__, AsyncMock)
|
||||
|
||||
# in Python 3 oct and hex use __index__
|
||||
# so these tests are for __index__ in py3k
|
||||
self.assertEqual(oct(mock), '0o1')
|
||||
self.assertEqual(hex(mock), '0x1')
|
||||
# how to test __sizeof__ ?
|
||||
|
||||
|
||||
def test_magic_methods_fspath(self):
|
||||
mock = MagicMock()
|
||||
expected_path = mock.__fspath__()
|
||||
mock.reset_mock()
|
||||
|
||||
self.assertEqual(os.fspath(mock), expected_path)
|
||||
mock.__fspath__.assert_called_once()
|
||||
|
||||
|
||||
def test_magic_methods_and_spec(self):
|
||||
class Iterable(object):
|
||||
def __iter__(self): pass
|
||||
|
||||
mock = Mock(spec=Iterable)
|
||||
self.assertRaises(AttributeError, lambda: mock.__iter__)
|
||||
|
||||
mock.__iter__ = Mock(return_value=iter([]))
|
||||
self.assertEqual(list(mock), [])
|
||||
|
||||
class NonIterable(object):
|
||||
pass
|
||||
mock = Mock(spec=NonIterable)
|
||||
self.assertRaises(AttributeError, lambda: mock.__iter__)
|
||||
|
||||
def set_int():
|
||||
mock.__int__ = Mock(return_value=iter([]))
|
||||
self.assertRaises(AttributeError, set_int)
|
||||
|
||||
mock = MagicMock(spec=Iterable)
|
||||
self.assertEqual(list(mock), [])
|
||||
self.assertRaises(AttributeError, set_int)
|
||||
|
||||
|
||||
def test_magic_methods_and_spec_set(self):
|
||||
class Iterable(object):
|
||||
def __iter__(self): pass
|
||||
|
||||
mock = Mock(spec_set=Iterable)
|
||||
self.assertRaises(AttributeError, lambda: mock.__iter__)
|
||||
|
||||
mock.__iter__ = Mock(return_value=iter([]))
|
||||
self.assertEqual(list(mock), [])
|
||||
|
||||
class NonIterable(object):
|
||||
pass
|
||||
mock = Mock(spec_set=NonIterable)
|
||||
self.assertRaises(AttributeError, lambda: mock.__iter__)
|
||||
|
||||
def set_int():
|
||||
mock.__int__ = Mock(return_value=iter([]))
|
||||
self.assertRaises(AttributeError, set_int)
|
||||
|
||||
mock = MagicMock(spec_set=Iterable)
|
||||
self.assertEqual(list(mock), [])
|
||||
self.assertRaises(AttributeError, set_int)
|
||||
|
||||
|
||||
def test_setting_unsupported_magic_method(self):
|
||||
mock = MagicMock()
|
||||
def set_setattr():
|
||||
mock.__setattr__ = lambda self, name: None
|
||||
self.assertRaisesRegex(AttributeError,
|
||||
"Attempting to set unsupported magic method '__setattr__'.",
|
||||
set_setattr
|
||||
)
|
||||
|
||||
|
||||
def test_attributes_and_return_value(self):
|
||||
mock = MagicMock()
|
||||
attr = mock.foo
|
||||
def _get_type(obj):
|
||||
# the type of every mock (or magicmock) is a custom subclass
|
||||
# so the real type is the second in the mro
|
||||
return type(obj).__mro__[1]
|
||||
self.assertEqual(_get_type(attr), MagicMock)
|
||||
|
||||
returned = mock()
|
||||
self.assertEqual(_get_type(returned), MagicMock)
|
||||
|
||||
|
||||
def test_magic_methods_are_magic_mocks(self):
|
||||
mock = MagicMock()
|
||||
self.assertIsInstance(mock.__getitem__, MagicMock)
|
||||
|
||||
mock[1][2].__getitem__.return_value = 3
|
||||
self.assertEqual(mock[1][2][3], 3)
|
||||
|
||||
|
||||
def test_magic_method_reset_mock(self):
|
||||
mock = MagicMock()
|
||||
str(mock)
|
||||
self.assertTrue(mock.__str__.called)
|
||||
mock.reset_mock()
|
||||
self.assertFalse(mock.__str__.called)
|
||||
|
||||
|
||||
def test_dir(self):
|
||||
# overriding the default implementation
|
||||
for mock in Mock(), MagicMock():
|
||||
def _dir(self):
|
||||
return ['foo']
|
||||
mock.__dir__ = _dir
|
||||
self.assertEqual(dir(mock), ['foo'])
|
||||
|
||||
|
||||
def test_bound_methods(self):
|
||||
m = Mock()
|
||||
|
||||
# XXXX should this be an expected failure instead?
|
||||
|
||||
# this seems like it should work, but is hard to do without introducing
|
||||
# other api inconsistencies. Failure message could be better though.
|
||||
m.__iter__ = [3].__iter__
|
||||
self.assertRaises(TypeError, iter, m)
|
||||
|
||||
|
||||
def test_magic_method_type(self):
|
||||
class Foo(MagicMock):
|
||||
pass
|
||||
|
||||
foo = Foo()
|
||||
self.assertIsInstance(foo.__int__, Foo)
|
||||
|
||||
|
||||
def test_descriptor_from_class(self):
|
||||
m = MagicMock()
|
||||
type(m).__str__.return_value = 'foo'
|
||||
self.assertEqual(str(m), 'foo')
|
||||
|
||||
|
||||
def test_iterable_as_iter_return_value(self):
|
||||
m = MagicMock()
|
||||
m.__iter__.return_value = [1, 2, 3]
|
||||
self.assertEqual(list(m), [1, 2, 3])
|
||||
self.assertEqual(list(m), [1, 2, 3])
|
||||
|
||||
m.__iter__.return_value = iter([4, 5, 6])
|
||||
self.assertEqual(list(m), [4, 5, 6])
|
||||
self.assertEqual(list(m), [])
|
||||
|
||||
|
||||
def test_matmul(self):
|
||||
m = MagicMock()
|
||||
self.assertIsInstance(m @ 1, MagicMock)
|
||||
m.__matmul__.return_value = 42
|
||||
m.__rmatmul__.return_value = 666
|
||||
m.__imatmul__.return_value = 24
|
||||
self.assertEqual(m @ 1, 42)
|
||||
self.assertEqual(1 @ m, 666)
|
||||
m @= 24
|
||||
self.assertEqual(m, 24)
|
||||
|
||||
def test_divmod_and_rdivmod(self):
|
||||
m = MagicMock()
|
||||
self.assertIsInstance(divmod(5, m), MagicMock)
|
||||
m.__divmod__.return_value = (2, 1)
|
||||
self.assertEqual(divmod(m, 2), (2, 1))
|
||||
m = MagicMock()
|
||||
foo = divmod(2, m)
|
||||
self.assertIsInstance(foo, MagicMock)
|
||||
foo_direct = m.__divmod__(2)
|
||||
self.assertIsInstance(foo_direct, MagicMock)
|
||||
bar = divmod(m, 2)
|
||||
self.assertIsInstance(bar, MagicMock)
|
||||
bar_direct = m.__rdivmod__(2)
|
||||
self.assertIsInstance(bar_direct, MagicMock)
|
||||
|
||||
# http://bugs.python.org/issue23310
|
||||
# Check if you can change behaviour of magic methods in MagicMock init
|
||||
def test_magic_in_initialization(self):
|
||||
m = MagicMock(**{'__str__.return_value': "12"})
|
||||
self.assertEqual(str(m), "12")
|
||||
|
||||
def test_changing_magic_set_in_initialization(self):
|
||||
m = MagicMock(**{'__str__.return_value': "12"})
|
||||
m.__str__.return_value = "13"
|
||||
self.assertEqual(str(m), "13")
|
||||
m = MagicMock(**{'__str__.return_value': "12"})
|
||||
m.configure_mock(**{'__str__.return_value': "14"})
|
||||
self.assertEqual(str(m), "14")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
2159
lib/mock/tests/testmock.py
Normal file
2159
lib/mock/tests/testmock.py
Normal file
File diff suppressed because it is too large
Load diff
1947
lib/mock/tests/testpatch.py
Normal file
1947
lib/mock/tests/testpatch.py
Normal file
File diff suppressed because it is too large
Load diff
176
lib/mock/tests/testsealable.py
Normal file
176
lib/mock/tests/testsealable.py
Normal file
|
@ -0,0 +1,176 @@
|
|||
import unittest
|
||||
import mock
|
||||
|
||||
|
||||
class SampleObject:
|
||||
|
||||
def method_sample1(self): pass
|
||||
|
||||
def method_sample2(self): pass
|
||||
|
||||
|
||||
class TestSealable(unittest.TestCase):
|
||||
|
||||
def test_attributes_return_more_mocks_by_default(self):
|
||||
m = mock.Mock()
|
||||
|
||||
self.assertIsInstance(m.test, mock.Mock)
|
||||
self.assertIsInstance(m.test(), mock.Mock)
|
||||
self.assertIsInstance(m.test().test2(), mock.Mock)
|
||||
|
||||
def test_new_attributes_cannot_be_accessed_on_seal(self):
|
||||
m = mock.Mock()
|
||||
|
||||
mock.seal(m)
|
||||
with self.assertRaises(AttributeError):
|
||||
m.test
|
||||
with self.assertRaises(AttributeError):
|
||||
m()
|
||||
|
||||
def test_new_attributes_cannot_be_set_on_seal(self):
|
||||
m = mock.Mock()
|
||||
|
||||
mock.seal(m)
|
||||
with self.assertRaises(AttributeError):
|
||||
m.test = 1
|
||||
|
||||
def test_existing_attributes_can_be_set_on_seal(self):
|
||||
m = mock.Mock()
|
||||
m.test.test2 = 1
|
||||
|
||||
mock.seal(m)
|
||||
m.test.test2 = 2
|
||||
self.assertEqual(m.test.test2, 2)
|
||||
|
||||
def test_new_attributes_cannot_be_set_on_child_of_seal(self):
|
||||
m = mock.Mock()
|
||||
m.test.test2 = 1
|
||||
|
||||
mock.seal(m)
|
||||
with self.assertRaises(AttributeError):
|
||||
m.test.test3 = 1
|
||||
|
||||
def test_existing_attributes_allowed_after_seal(self):
|
||||
m = mock.Mock()
|
||||
|
||||
m.test.return_value = 3
|
||||
|
||||
mock.seal(m)
|
||||
self.assertEqual(m.test(), 3)
|
||||
|
||||
def test_initialized_attributes_allowed_after_seal(self):
|
||||
m = mock.Mock(test_value=1)
|
||||
|
||||
mock.seal(m)
|
||||
self.assertEqual(m.test_value, 1)
|
||||
|
||||
def test_call_on_sealed_mock_fails(self):
|
||||
m = mock.Mock()
|
||||
|
||||
mock.seal(m)
|
||||
with self.assertRaises(AttributeError):
|
||||
m()
|
||||
|
||||
def test_call_on_defined_sealed_mock_succeeds(self):
|
||||
m = mock.Mock(return_value=5)
|
||||
|
||||
mock.seal(m)
|
||||
self.assertEqual(m(), 5)
|
||||
|
||||
def test_seals_recurse_on_added_attributes(self):
|
||||
m = mock.Mock()
|
||||
|
||||
m.test1.test2().test3 = 4
|
||||
|
||||
mock.seal(m)
|
||||
self.assertEqual(m.test1.test2().test3, 4)
|
||||
with self.assertRaises(AttributeError):
|
||||
m.test1.test2().test4
|
||||
with self.assertRaises(AttributeError):
|
||||
m.test1.test3
|
||||
|
||||
def test_seals_recurse_on_magic_methods(self):
|
||||
m = mock.MagicMock()
|
||||
|
||||
m.test1.test2["a"].test3 = 4
|
||||
m.test1.test3[2:5].test3 = 4
|
||||
|
||||
mock.seal(m)
|
||||
self.assertEqual(m.test1.test2["a"].test3, 4)
|
||||
self.assertEqual(m.test1.test2[2:5].test3, 4)
|
||||
with self.assertRaises(AttributeError):
|
||||
m.test1.test2["a"].test4
|
||||
with self.assertRaises(AttributeError):
|
||||
m.test1.test3[2:5].test4
|
||||
|
||||
def test_seals_dont_recurse_on_manual_attributes(self):
|
||||
m = mock.Mock(name="root_mock")
|
||||
|
||||
m.test1.test2 = mock.Mock(name="not_sealed")
|
||||
m.test1.test2.test3 = 4
|
||||
|
||||
mock.seal(m)
|
||||
self.assertEqual(m.test1.test2.test3, 4)
|
||||
m.test1.test2.test4 # Does not raise
|
||||
m.test1.test2.test4 = 1 # Does not raise
|
||||
|
||||
def test_integration_with_spec_att_definition(self):
|
||||
"""You are not restricted when using mock with spec"""
|
||||
m = mock.Mock(SampleObject)
|
||||
|
||||
m.attr_sample1 = 1
|
||||
m.attr_sample3 = 3
|
||||
|
||||
mock.seal(m)
|
||||
self.assertEqual(m.attr_sample1, 1)
|
||||
self.assertEqual(m.attr_sample3, 3)
|
||||
with self.assertRaises(AttributeError):
|
||||
m.attr_sample2
|
||||
|
||||
def test_integration_with_spec_method_definition(self):
|
||||
"""You need to defin the methods, even if they are in the spec"""
|
||||
m = mock.Mock(SampleObject)
|
||||
|
||||
m.method_sample1.return_value = 1
|
||||
|
||||
mock.seal(m)
|
||||
self.assertEqual(m.method_sample1(), 1)
|
||||
with self.assertRaises(AttributeError):
|
||||
m.method_sample2()
|
||||
|
||||
def test_integration_with_spec_method_definition_respects_spec(self):
|
||||
"""You cannot define methods out of the spec"""
|
||||
m = mock.Mock(SampleObject)
|
||||
|
||||
with self.assertRaises(AttributeError):
|
||||
m.method_sample3.return_value = 3
|
||||
|
||||
def test_sealed_exception_has_attribute_name(self):
|
||||
m = mock.Mock()
|
||||
|
||||
mock.seal(m)
|
||||
with self.assertRaises(AttributeError) as cm:
|
||||
m.SECRETE_name
|
||||
self.assertIn("SECRETE_name", str(cm.exception))
|
||||
|
||||
def test_attribute_chain_is_maintained(self):
|
||||
m = mock.Mock(name="mock_name")
|
||||
m.test1.test2.test3.test4
|
||||
|
||||
mock.seal(m)
|
||||
with self.assertRaises(AttributeError) as cm:
|
||||
m.test1.test2.test3.test4.boom
|
||||
self.assertIn("mock_name.test1.test2.test3.test4.boom", str(cm.exception))
|
||||
|
||||
def test_call_chain_is_maintained(self):
|
||||
m = mock.Mock()
|
||||
m.test1().test2.test3().test4
|
||||
|
||||
mock.seal(m)
|
||||
with self.assertRaises(AttributeError) as cm:
|
||||
m.test1().test2.test3().test4()
|
||||
self.assertIn("mock.test1().test2.test3().test4", str(cm.exception))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
41
lib/mock/tests/testsentinel.py
Normal file
41
lib/mock/tests/testsentinel.py
Normal file
|
@ -0,0 +1,41 @@
|
|||
import unittest
|
||||
import copy
|
||||
import pickle
|
||||
from mock import sentinel, DEFAULT
|
||||
|
||||
|
||||
class SentinelTest(unittest.TestCase):
|
||||
|
||||
def testSentinels(self):
|
||||
self.assertEqual(sentinel.whatever, sentinel.whatever,
|
||||
'sentinel not stored')
|
||||
self.assertNotEqual(sentinel.whatever, sentinel.whateverelse,
|
||||
'sentinel should be unique')
|
||||
|
||||
|
||||
def testSentinelName(self):
|
||||
self.assertEqual(str(sentinel.whatever), 'sentinel.whatever',
|
||||
'sentinel name incorrect')
|
||||
|
||||
|
||||
def testDEFAULT(self):
|
||||
self.assertIs(DEFAULT, sentinel.DEFAULT)
|
||||
|
||||
def testBases(self):
|
||||
# If this doesn't raise an AttributeError then help(mock) is broken
|
||||
self.assertRaises(AttributeError, lambda: sentinel.__bases__)
|
||||
|
||||
def testPickle(self):
|
||||
for proto in range(pickle.HIGHEST_PROTOCOL+1):
|
||||
with self.subTest(protocol=proto):
|
||||
pickled = pickle.dumps(sentinel.whatever, proto)
|
||||
unpickled = pickle.loads(pickled)
|
||||
self.assertIs(unpickled, sentinel.whatever)
|
||||
|
||||
def testCopy(self):
|
||||
self.assertIs(copy.copy(sentinel.whatever), sentinel.whatever)
|
||||
self.assertIs(copy.deepcopy(sentinel.whatever), sentinel.whatever)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
347
lib/mock/tests/testwith.py
Normal file
347
lib/mock/tests/testwith.py
Normal file
|
@ -0,0 +1,347 @@
|
|||
import unittest
|
||||
from warnings import catch_warnings
|
||||
|
||||
from mock.tests.support import is_instance
|
||||
from mock import MagicMock, Mock, patch, sentinel, mock_open, call
|
||||
|
||||
|
||||
|
||||
something = sentinel.Something
|
||||
something_else = sentinel.SomethingElse
|
||||
|
||||
|
||||
class SampleException(Exception): pass
|
||||
|
||||
|
||||
class WithTest(unittest.TestCase):
|
||||
|
||||
def test_with_statement(self):
|
||||
with patch('%s.something' % __name__, sentinel.Something2):
|
||||
self.assertEqual(something, sentinel.Something2, "unpatched")
|
||||
self.assertEqual(something, sentinel.Something)
|
||||
|
||||
|
||||
def test_with_statement_exception(self):
|
||||
with self.assertRaises(SampleException):
|
||||
with patch('%s.something' % __name__, sentinel.Something2):
|
||||
self.assertEqual(something, sentinel.Something2, "unpatched")
|
||||
raise SampleException()
|
||||
self.assertEqual(something, sentinel.Something)
|
||||
|
||||
|
||||
def test_with_statement_as(self):
|
||||
with patch('%s.something' % __name__) as mock_something:
|
||||
self.assertEqual(something, mock_something, "unpatched")
|
||||
self.assertTrue(is_instance(mock_something, MagicMock),
|
||||
"patching wrong type")
|
||||
self.assertEqual(something, sentinel.Something)
|
||||
|
||||
|
||||
def test_patch_object_with_statement(self):
|
||||
class Foo(object):
|
||||
something = 'foo'
|
||||
original = Foo.something
|
||||
with patch.object(Foo, 'something'):
|
||||
self.assertNotEqual(Foo.something, original, "unpatched")
|
||||
self.assertEqual(Foo.something, original)
|
||||
|
||||
|
||||
def test_with_statement_nested(self):
|
||||
with catch_warnings(record=True):
|
||||
with patch('%s.something' % __name__) as mock_something, patch('%s.something_else' % __name__) as mock_something_else:
|
||||
self.assertEqual(something, mock_something, "unpatched")
|
||||
self.assertEqual(something_else, mock_something_else,
|
||||
"unpatched")
|
||||
|
||||
self.assertEqual(something, sentinel.Something)
|
||||
self.assertEqual(something_else, sentinel.SomethingElse)
|
||||
|
||||
|
||||
def test_with_statement_specified(self):
|
||||
with patch('%s.something' % __name__, sentinel.Patched) as mock_something:
|
||||
self.assertEqual(something, mock_something, "unpatched")
|
||||
self.assertEqual(mock_something, sentinel.Patched, "wrong patch")
|
||||
self.assertEqual(something, sentinel.Something)
|
||||
|
||||
|
||||
def testContextManagerMocking(self):
|
||||
mock = Mock()
|
||||
mock.__enter__ = Mock()
|
||||
mock.__exit__ = Mock()
|
||||
mock.__exit__.return_value = False
|
||||
|
||||
with mock as m:
|
||||
self.assertEqual(m, mock.__enter__.return_value)
|
||||
mock.__enter__.assert_called_with()
|
||||
mock.__exit__.assert_called_with(None, None, None)
|
||||
|
||||
|
||||
def test_context_manager_with_magic_mock(self):
|
||||
mock = MagicMock()
|
||||
|
||||
with self.assertRaises(TypeError):
|
||||
with mock:
|
||||
'foo' + 3
|
||||
mock.__enter__.assert_called_with()
|
||||
self.assertTrue(mock.__exit__.called)
|
||||
|
||||
|
||||
def test_with_statement_same_attribute(self):
|
||||
with patch('%s.something' % __name__, sentinel.Patched) as mock_something:
|
||||
self.assertEqual(something, mock_something, "unpatched")
|
||||
|
||||
with patch('%s.something' % __name__) as mock_again:
|
||||
self.assertEqual(something, mock_again, "unpatched")
|
||||
|
||||
self.assertEqual(something, mock_something,
|
||||
"restored with wrong instance")
|
||||
|
||||
self.assertEqual(something, sentinel.Something, "not restored")
|
||||
|
||||
|
||||
def test_with_statement_imbricated(self):
|
||||
with patch('%s.something' % __name__) as mock_something:
|
||||
self.assertEqual(something, mock_something, "unpatched")
|
||||
|
||||
with patch('%s.something_else' % __name__) as mock_something_else:
|
||||
self.assertEqual(something_else, mock_something_else,
|
||||
"unpatched")
|
||||
|
||||
self.assertEqual(something, sentinel.Something)
|
||||
self.assertEqual(something_else, sentinel.SomethingElse)
|
||||
|
||||
|
||||
def test_dict_context_manager(self):
|
||||
foo = {}
|
||||
with patch.dict(foo, {'a': 'b'}):
|
||||
self.assertEqual(foo, {'a': 'b'})
|
||||
self.assertEqual(foo, {})
|
||||
|
||||
with self.assertRaises(NameError):
|
||||
with patch.dict(foo, {'a': 'b'}):
|
||||
self.assertEqual(foo, {'a': 'b'})
|
||||
raise NameError('Konrad')
|
||||
|
||||
self.assertEqual(foo, {})
|
||||
|
||||
def test_double_patch_instance_method(self):
|
||||
class C:
|
||||
def f(self): pass
|
||||
|
||||
c = C()
|
||||
|
||||
with patch.object(c, 'f', autospec=True) as patch1:
|
||||
with patch.object(c, 'f', autospec=True) as patch2:
|
||||
c.f()
|
||||
self.assertEqual(patch2.call_count, 1)
|
||||
self.assertEqual(patch1.call_count, 0)
|
||||
c.f()
|
||||
self.assertEqual(patch1.call_count, 1)
|
||||
|
||||
|
||||
class TestMockOpen(unittest.TestCase):
|
||||
|
||||
def test_mock_open(self):
|
||||
mock = mock_open()
|
||||
with patch('%s.open' % __name__, mock, create=True) as patched:
|
||||
self.assertIs(patched, mock)
|
||||
open('foo')
|
||||
|
||||
mock.assert_called_once_with('foo')
|
||||
|
||||
|
||||
def test_mock_open_context_manager(self):
|
||||
mock = mock_open()
|
||||
handle = mock.return_value
|
||||
with patch('%s.open' % __name__, mock, create=True):
|
||||
with open('foo') as f:
|
||||
f.read()
|
||||
|
||||
expected_calls = [call('foo'), call().__enter__(), call().read(),
|
||||
call().__exit__(None, None, None)]
|
||||
self.assertEqual(mock.mock_calls, expected_calls)
|
||||
self.assertIs(f, handle)
|
||||
|
||||
def test_mock_open_context_manager_multiple_times(self):
|
||||
mock = mock_open()
|
||||
with patch('%s.open' % __name__, mock, create=True):
|
||||
with open('foo') as f:
|
||||
f.read()
|
||||
with open('bar') as f:
|
||||
f.read()
|
||||
|
||||
expected_calls = [
|
||||
call('foo'), call().__enter__(), call().read(),
|
||||
call().__exit__(None, None, None),
|
||||
call('bar'), call().__enter__(), call().read(),
|
||||
call().__exit__(None, None, None)]
|
||||
self.assertEqual(mock.mock_calls, expected_calls)
|
||||
|
||||
def test_explicit_mock(self):
|
||||
mock = MagicMock()
|
||||
mock_open(mock)
|
||||
|
||||
with patch('%s.open' % __name__, mock, create=True) as patched:
|
||||
self.assertIs(patched, mock)
|
||||
open('foo')
|
||||
|
||||
mock.assert_called_once_with('foo')
|
||||
|
||||
|
||||
def test_read_data(self):
|
||||
mock = mock_open(read_data='foo')
|
||||
with patch('%s.open' % __name__, mock, create=True):
|
||||
h = open('bar')
|
||||
result = h.read()
|
||||
|
||||
self.assertEqual(result, 'foo')
|
||||
|
||||
|
||||
def test_readline_data(self):
|
||||
# Check that readline will return all the lines from the fake file
|
||||
# And that once fully consumed, readline will return an empty string.
|
||||
mock = mock_open(read_data='foo\nbar\nbaz\n')
|
||||
with patch('%s.open' % __name__, mock, create=True):
|
||||
h = open('bar')
|
||||
line1 = h.readline()
|
||||
line2 = h.readline()
|
||||
line3 = h.readline()
|
||||
self.assertEqual(line1, 'foo\n')
|
||||
self.assertEqual(line2, 'bar\n')
|
||||
self.assertEqual(line3, 'baz\n')
|
||||
self.assertEqual(h.readline(), '')
|
||||
|
||||
# Check that we properly emulate a file that doesn't end in a newline
|
||||
mock = mock_open(read_data='foo')
|
||||
with patch('%s.open' % __name__, mock, create=True):
|
||||
h = open('bar')
|
||||
result = h.readline()
|
||||
self.assertEqual(result, 'foo')
|
||||
self.assertEqual(h.readline(), '')
|
||||
|
||||
|
||||
def test_dunder_iter_data(self):
|
||||
# Check that dunder_iter will return all the lines from the fake file.
|
||||
mock = mock_open(read_data='foo\nbar\nbaz\n')
|
||||
with patch('%s.open' % __name__, mock, create=True):
|
||||
h = open('bar')
|
||||
lines = [l for l in h]
|
||||
self.assertEqual(lines[0], 'foo\n')
|
||||
self.assertEqual(lines[1], 'bar\n')
|
||||
self.assertEqual(lines[2], 'baz\n')
|
||||
self.assertEqual(h.readline(), '')
|
||||
with self.assertRaises(StopIteration):
|
||||
next(h)
|
||||
|
||||
def test_next_data(self):
|
||||
# Check that next will correctly return the next available
|
||||
# line and plays well with the dunder_iter part.
|
||||
mock = mock_open(read_data='foo\nbar\nbaz\n')
|
||||
with patch('%s.open' % __name__, mock, create=True):
|
||||
h = open('bar')
|
||||
line1 = next(h)
|
||||
line2 = next(h)
|
||||
lines = [l for l in h]
|
||||
self.assertEqual(line1, 'foo\n')
|
||||
self.assertEqual(line2, 'bar\n')
|
||||
self.assertEqual(lines[0], 'baz\n')
|
||||
self.assertEqual(h.readline(), '')
|
||||
|
||||
def test_readlines_data(self):
|
||||
# Test that emulating a file that ends in a newline character works
|
||||
mock = mock_open(read_data='foo\nbar\nbaz\n')
|
||||
with patch('%s.open' % __name__, mock, create=True):
|
||||
h = open('bar')
|
||||
result = h.readlines()
|
||||
self.assertEqual(result, ['foo\n', 'bar\n', 'baz\n'])
|
||||
|
||||
# Test that files without a final newline will also be correctly
|
||||
# emulated
|
||||
mock = mock_open(read_data='foo\nbar\nbaz')
|
||||
with patch('%s.open' % __name__, mock, create=True):
|
||||
h = open('bar')
|
||||
result = h.readlines()
|
||||
|
||||
self.assertEqual(result, ['foo\n', 'bar\n', 'baz'])
|
||||
|
||||
|
||||
def test_read_bytes(self):
|
||||
mock = mock_open(read_data=b'\xc6')
|
||||
with patch('%s.open' % __name__, mock, create=True):
|
||||
with open('abc', 'rb') as f:
|
||||
result = f.read()
|
||||
self.assertEqual(result, b'\xc6')
|
||||
|
||||
|
||||
def test_readline_bytes(self):
|
||||
m = mock_open(read_data=b'abc\ndef\nghi\n')
|
||||
with patch('%s.open' % __name__, m, create=True):
|
||||
with open('abc', 'rb') as f:
|
||||
line1 = f.readline()
|
||||
line2 = f.readline()
|
||||
line3 = f.readline()
|
||||
self.assertEqual(line1, b'abc\n')
|
||||
self.assertEqual(line2, b'def\n')
|
||||
self.assertEqual(line3, b'ghi\n')
|
||||
|
||||
|
||||
def test_readlines_bytes(self):
|
||||
m = mock_open(read_data=b'abc\ndef\nghi\n')
|
||||
with patch('%s.open' % __name__, m, create=True):
|
||||
with open('abc', 'rb') as f:
|
||||
result = f.readlines()
|
||||
self.assertEqual(result, [b'abc\n', b'def\n', b'ghi\n'])
|
||||
|
||||
|
||||
def test_mock_open_read_with_argument(self):
|
||||
# At one point calling read with an argument was broken
|
||||
# for mocks returned by mock_open
|
||||
some_data = 'foo\nbar\nbaz'
|
||||
mock = mock_open(read_data=some_data)
|
||||
self.assertEqual(mock().read(10), some_data[:10])
|
||||
self.assertEqual(mock().read(10), some_data[:10])
|
||||
|
||||
f = mock()
|
||||
self.assertEqual(f.read(10), some_data[:10])
|
||||
self.assertEqual(f.read(10), some_data[10:])
|
||||
|
||||
|
||||
def test_interleaved_reads(self):
|
||||
# Test that calling read, readline, and readlines pulls data
|
||||
# sequentially from the data we preload with
|
||||
mock = mock_open(read_data='foo\nbar\nbaz\n')
|
||||
with patch('%s.open' % __name__, mock, create=True):
|
||||
h = open('bar')
|
||||
line1 = h.readline()
|
||||
rest = h.readlines()
|
||||
self.assertEqual(line1, 'foo\n')
|
||||
self.assertEqual(rest, ['bar\n', 'baz\n'])
|
||||
|
||||
mock = mock_open(read_data='foo\nbar\nbaz\n')
|
||||
with patch('%s.open' % __name__, mock, create=True):
|
||||
h = open('bar')
|
||||
line1 = h.readline()
|
||||
rest = h.read()
|
||||
self.assertEqual(line1, 'foo\n')
|
||||
self.assertEqual(rest, 'bar\nbaz\n')
|
||||
|
||||
|
||||
def test_overriding_return_values(self):
|
||||
mock = mock_open(read_data='foo')
|
||||
handle = mock()
|
||||
|
||||
handle.read.return_value = 'bar'
|
||||
handle.readline.return_value = 'bar'
|
||||
handle.readlines.return_value = ['bar']
|
||||
|
||||
self.assertEqual(handle.read(), 'bar')
|
||||
self.assertEqual(handle.readline(), 'bar')
|
||||
self.assertEqual(handle.readlines(), ['bar'])
|
||||
|
||||
# call repeatedly to check that a StopIteration is not propagated
|
||||
self.assertEqual(handle.readline(), 'bar')
|
||||
self.assertEqual(handle.readline(), 'bar')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
Loading…
Add table
Add a link
Reference in a new issue