Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Conditional variables based on whether nosetest is running

I'm running nosetests which have a setup function that needs to load a different database than the production database. The ORM I'm using is peewee which requires that the database for a model is set in the definition.

So I need to set a conditional variable but I don't know what condition to use in order to check if nosetest is running the file.

I read on Stack Overflow that you can check for nose in sys.modules but I was wondering if there is a more exact way to check if nose is running.

like image 636
Emsu Avatar asked Sep 07 '11 21:09

Emsu


2 Answers

Perhaps examining sys.argv[0] to see what command is running?

like image 95
Ned Batchelder Avatar answered Oct 22 '22 00:10

Ned Batchelder


Examining sys.argv might work, but you can execute nose either with nosetests or python -m nose, which obviously will give you a different result.

I think the more robust way is to inspect the stack and see if the code is being called through a package called nose.

Example code:

import inspect
import unittest


def is_called_by_nose():
    stack = inspect.stack()
    return any(x[0].f_globals['__name__'].startswith('nose.') for x in stack)


class TestFoo(unittest.TestCase):
    def test_foo(self):
        self.assertTrue(is_called_by_nose())

Example usage:

$ python -m nose test_caller
.
----------------------------------------------------------------------
Ran 1 test in 0.009s

OK
$ nosetests test_caller
.
----------------------------------------------------------------------
Ran 1 test in 0.009s

OK
$ python -m unittest test_caller
F
======================================================================
FAIL: test_foo (test_caller.TestFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_caller.py", line 14, in test_foo
    self.assertTrue(is_called_by_nose())
AssertionError: False is not true

----------------------------------------------------------------------
Ran 1 test in 0.004s

FAILED (failures=1)
like image 29
Stefan Avatar answered Oct 22 '22 01:10

Stefan