Reputation: 4386
I'm new to Python and I was trying out nose as a unit test framework. I came across a behavior I didn't expect, but maybe this is normal, hence my question.
I have two (very basic) files:
__init__.py:
#!/usr/bin/env python
glob = 0
def setup():
global glob
glob = 42
print "Package setup"
test_mymod.py:
#!/usr/bin/env python
from unittest import TestCase
from . import glob
print "test_mymod.py"
class testMyMod(TestCase):
def setUp(self):
print glob
def test_random(self):
pass
def tearDown(self):
pass
Running nosetest -s
gives me following output:
test_mymod.py
Package setup
0
Since the setup() function of the package is invoked before the setUp() function of the test, I expected to see print glob
to output 42
.
Am I doing something wrong, or is there no way of doing what I want? It seems to me that importing a variable copies its value instead of referencing it, but maybe there is way to do otherwise?
Thank you
Upvotes: 2
Views: 551
Reputation: 20520
When you do from . import glob
at the top of your test file, you get a reference to the value of glob
in your namespace. This happens before you call setup()
. When you call setup()
the value of glob
is updated in the __init__.py
namespace but not test_mymod.py
. Instead of importing glob
directly, reference it like package.glob
. Alternatively, set glob
to its correct value at package import time; having unitialized globals that people can import is considered bad practice for exactly this reason.
Upvotes: 2