nosetests framework: how to pass environment variables to my tests?

Mihai picture Mihai · Jan 15, 2015 · Viewed 7.4k times · Source

I have a test suite that gets executed as a part of a larger build framework, written in Python. Some of the tests require parameters, which I want to pass using environment variables.

Apparently the nosetests runner has an env parameter, which does what I want, according to the documentation. It seems, however, that it does not work as thought it should?

Here's a minimal test script that exemplifies the problem:

#!/usr/bin/env python
# pip install nose

import os, nose, unittest

class Test(unittest.TestCase):
    def test_env(self):
        self.assertEquals(os.environ.get('HELLO'), 'WORLD')

if __name__ == '__main__':
    nose.run(env={'HELLO': 'WORLD'})

The assertion fails, because the env parameter does not get passed to the test. Does anyone know why?

NB: I worked around the problem by launching the console nosetests tool:

#!/usr/bin/env python

import sys, os, nose, unittest, subprocess

class Test(unittest.TestCase):
    def test_env(self):
        self.assertEquals(os.environ.get('HELLO'), 'WORLD')

if __name__ == '__main__':
    subprocess.Popen(['nosetests', sys.argv[0]],
                     env={'HELLO': 'WORLD'}).wait()

However, this feels like a kludge, and I'd still be interested in learning to use nose.run() properly.

Answer

Alex Bliskovsky picture Alex Bliskovsky · Jan 15, 2015

I couldn't get env to behave itself either, but I have come up with a solution that I consider slighly less kludgy than opening a subprocess. You can modify the os.environ variable before you call nose.run(), and as long as the tests are running in the same process, the tests will all see the modified os.environ:

#!/usr/bin/env python
import os, nose, unittest

class Test(unittest.TestCase):
    def test_env(self):
        self.assertEquals(os.environ.get('HELLO'), 'WORLD')

if __name__ == '__main__':
    os.environ["HELLO"] = "WORLD"
    nose.run()