Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if code is being run from a nose-test?

Tags:

python

nose

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.

like image 731
Brian Postow Avatar asked Jan 04 '16 19:01

Brian Postow


People also ask

Which command is used to run nose tests?

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.

What is nose test in python?

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.

What is Nose tools?

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.


2 Answers

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>
like image 149
Brian Postow Avatar answered Nov 02 '22 14:11

Brian Postow


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.

like image 23
Łukasz Rogalski Avatar answered Nov 02 '22 14:11

Łukasz Rogalski