简体   繁体   中英

Unexpected failure to access global variable from different python module

I'm trying to add simple mocking to my tests, using a class with static fields to hold the settings (ie. singleton). This works fine when I'm running the test alone, but fails when it is ran as part of the full test suit.

For some reason the global class is a different object between the tests.py module and the tested code (despite being the same process).

ie. here is a simplified example:

   # in mock_settings.py
   class MockSettings(object):
       fake_random = False

   # in views.py
   def func(request)
       print(os.getpid(), id(MockSettings))
       if MockSettings.fake_random:
           return HttpResponse('123')
       else:
           return HttpResponse(str(random.randint(1000)))


   # in tests.py
   def test_func(self):
       print(os.getpid(), id(MockSettings))
       MockSettings.fake_random = True
       response = self.client.get('/func')
       self.assertEquals(response.content, '123')  # fails when ran as test suite, works when runs alone

Crazy thing #1: when I'm running the test alone (eg. ./manage.py test tests.TestClass.test_func ), the id(MockSettings) is the same in the tests.py and the views.py, but when ran in the test suite (eg. ./manage.py test ) then the pid matches but the class id is different - and thus fake_random is different...

Crazy thing #2: when I tried to reproduce it in a new project, I couldn't. When I commented out all the other tests in my project it still happened.

Any idea why?

Found the root cause a minute after posting the question...

in the test file I used:

from __future__ import absolute_import  #I'm using python 2.7
from .mock_settings import MockSettings

while in the app code I used

from full.path.to.module import MockSettings

Apparently the result is not the same object! I still don't understand why, but I found that if I change to full path import in both modules then it works as expected

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM