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.
nose can be integrated with DocTest by using with-doctest option in athe bove command line. The result will be true if the test run is successful, or false if it fails or raises an uncaught exception. nose supports fixtures (setup and teardown methods) at the package, module, class, and test level.
Nose is a popular test automation framework in Python that extends unittest to make testing easier. The other advantages of using the Nose framework are the enablement of auto discovery of test cases and documentation collection.
The nose. tools module provides a number of testing aids that you may find useful, including decorators for restricting test execution time and testing for exceptions, and all of the same assertX methods found in unittest.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With