How to prohibit the correction of monkeys non-existent methods of bullying?

I would like to write a test that will help me determine if the API of the library that I use has changed, for example. after update.

If I created a “blind layout” object, then the layout will always use one method and the tests will pass, but my application will break with the actual library.

I know that there is a way to fix existing objects:

@patch.object(ZipFile, 'namelist')
def test_my_method(self, mocked_zipfile):

which will at least check if the method really namelistexists on the original object, but it still allows me to make a typo when it taunts the object inside:

@patch.object(ZipFile, 'namelist')
def test_my_method(self, mocked_zipfile):
    mocked_zipfile.namlist.return_value = [ 'one.txt', 'two.txt' ]

When I make a typo ( namlist) inside the test and inside the test code, the test will just silently pass.

- , , , ( , , )?

+4
2

zipfile.Zipfile autospec=True:

autospec=True, . , . , , TypeError, . , , ( 'Instance) , .

- AttributeError: Mock object has no attribute 'namlist':

from unittest import TestCase
from mock import patch

class MyTestCase(TestCase):
    @patch.object(ZipFile, 'namelist', autospec=True)
    def test_my_method(self, mocked_zipfile):
        mocked_zipfile.namlist.return_value = [ 'one.txt', 'two.txt' ]

, .

+3

wraps?

:

>>> from mock import Mock
>>> import zipfile
>>> mocked_zipfile = Mock(wraps=zipfile.ZipFile)
>>> mocked_zipfile.namlist.return_value = ['one.txt', 'two.txt']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/jbaiter/.envs/spreads/local/lib/python2.7/site-packages/mock.py", line 670, in __getattr__
    wraps = getattr(self._mock_wraps, name)
AttributeError: type object 'ZipFile' has no attribute 'namlist'
>>> mocked_zipfile.namelist.return_value = ['one.txt', 'two.txt']
>>> mocked_zipfile.namelist()
['one.txt', 'two.txt']

@patch , :

@patch('zipfile.ZipFile', Mock(wraps=zipfile.ZipFile))
def test_my_method(self, mocked_zipfile):
    # call code that depends on ZipFile
    pass
+2

Source: https://habr.com/ru/post/1538053/


All Articles