简体   繁体   English

从不同的python模块访问全局变量意外失败

[英]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). 出于某种原因,全局类在tests.py模块和经过测试的代码之间是不同的对象(尽管是同一过程)。

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... 疯狂的事情#1:当我独自运行测试(例如./manage.py test tests.TestClass.test_func )时,在tests.py和views.py中, id(MockSettings)相同,但是当在测试套件中运行(例如./manage.py test ),则pid匹配,但类ID不同-因此, fake_random也不同...

Crazy thing #2: when I tried to reproduce it in a new project, I couldn't. 疯狂的事情#2:当我尝试在一个新项目中重现它时,我做不到。 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 我仍然不明白为什么,但是我发现,如果我在两个模块中都更改为全路径导入,那么它将按预期工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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