Python: Conditional variables based on whether nosetest is running
Asked Answered
W

2

8

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.

Watertight answered 7/9, 2011 at 21:57 Comment(0)
R
10

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

Rydder answered 7/9, 2011 at 23:41 Comment(1)
import sys; testing = sys.argv[0].endswith('nosetests')Marylynnmarylynne
Z
1

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)
Zosi answered 18/11, 2017 at 19:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.