Reputation: 12187
I have some code which is used in a unit test. However, the library it loads requires some data which isn't actually required for the nose-test, because that data is mocked out by the unit test. I'd like to protect the file-reads in the library so that they don't get called in the case of a nose test.
Is there an easy way to do this?
I can probably do something with sys.modules, or the initial command line, but I'd prefer something more elegant, if it exists.
Upvotes: 9
Views: 2137
Reputation: 12187
As mentioned in comments, the structure of this code is a mess, and part of the point of the tests is to make sure that I don't break things when I refactor...
So, for now, (unless someone gives me a better answer), I'm using:
if 'nose' not in sys.modules.keys():
<read the data>
Upvotes: 12
Reputation: 23223
Correct approach would be to mock all code with side-effects (I'll assume that what you do not want) with empty mocks.
Given tested_module my_module:
def do_something_and_destroy_world():
destroy_world()
return None
Sample test file is:
import mock
import unittest
import my_module
class MyTest(unittest.TestCase):
def testSomethingUgly(self):
with mock.patch('my_module.destroy_world', return_value=None):
result = do_something_and_destroy_world()
self.assertIsNone(result)
When tests are run, assertion will be correct, and destroy_world
wouldn't be called - instead it'll get replaced with empty mock with fixed return value.
Upvotes: 2