Currently I am writing unit-tests for legacy code in a Web2Py project. I am stuck at the following issue:
I want to patch tempfile.NamedTemporaryFile but I can't seem to find where to patch this. My module that contains the class to be tested needs to be loaded via Pythons execfile see here for details, so it is not imported all its members are globally available. Following are severely stripped versions of the files involved:
Module A.py which needs to be loaded in the Web2Py context looks something like this:
import os
import tempfile
class foo:
def worker(self):
#do work
square = 2*2
write2file(square)
def write2file(self, value)
with tempfile.NamedTemporaryFile(mode='w+t', suffix='.csv', delete=False, dir= '/dev/shm') as tf:
write(square)self
My test.py looks like this
import unittest
import mock
from mock import patch
from mock import mock_open
from gluon.globals import Request
execfile("applications/demoapp/controllers/A.py", globals())
class Testfoo(unittest.TestCase):
def setUp(self):
self.bar = foo()
def tearDown(self):
pass
@patch('__main__.foo.tempfile')
def test_patched_worker(self, tf):
self.bar.worker()
print(tf.mock_calls)
print
suite = unittest.TestSuite()
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(Testfoo))
unittest.TextTestRunner(verbosity=2).run(suite)
Finally the test is run with:
web2py.py -S demoapp -M -R applications/demoapp/tests/test.py
I try different locations to patch, but keep getting errors like the following:
ImportError: No module named foo
Any hints are much appreciated.
Edit: I have removed the Web2Py tag, as it seems to limit the number of interested readers significantly, and is not the core of the issue at hand.