Docking imported modules in Python

I am trying to implement unit tests for a function using imported external objects.

For example helpers.py :

import os import pylons def some_func(arg): ... var1 = os.path.exist(...) var2 = os.path.getmtime(...) var3 = pylons.request.environ['HTTP_HOST'] ... 

So, when I create a unit test for this, I do some ridicule (minimax in my case) and replacing the links with pylons.request and os.path:

 import helpers def test_some_func(): helpers.pylons.request = minimock.Mock("pylons.request") helpers.pylons.request.environ = { 'HTTP_HOST': "localhost" } helpers.os.path = minimock.Mock(....) ... some_func(...) # assert ... 

This does not look good to me.

Is there any other better way or strategy to replace imported function / objects in Python?

+4
source share
2 answers

Well, in minimax there is a simpler paradigm for this than what you use above:

 >>> from minimock import mock >>> import os.path >>> mock('os.path.isfile', returns=True) 

See http://pypi.python.org/pypi/MiniMock#creating-mocks

Once you do this, any module that runs os.path.isfile("blah") will get True back. You do not need to go and explicitly reassign the module namespace under the test.

+1
source

Use the voidspace sound library and its ability to patch / pack.

http://www.voidspace.org.uk/python/mock/patch.html

+2
source

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


All Articles