我在 Python 2.7.6 中运行的 Django 1.4 项目中有以下导入行:
from django.contrib.gis.utils import GeoIP
这条线在生产和开发中 100% 的时间都可以正常工作,但是这条线在测试中会出现 ImportError 失败——有时。给定以下虚拟测试:
from django.test import TestCase
from django.test.client import Client
class DummyTestCase(TestCase):
def test_GET_200_response_code(self):
c = Client()
response = c.get('/')
self.assertEqual(response.status_code, 200)
如果我只运行此模块中的测试,它将失败response = self.c.get('/')
:
...
File "...", line 19, in <module>
from django.contrib.gis.utils import GeoIP
ImportError: cannot import name GeoIP
但是,当我运行整个测试套件(包括同一个测试)时,它毫无问题地通过了。而且,导入在控制台中以及在开发和生产的服务器中都可以正常工作。
那么……为什么会这样?为什么我只会在运行这个单个测试模块时得到一个 ImportError ,而不是其他情况,即使我运行了包括这个模块在内的所有测试?
注意:我现在使用的是 Django 1.4。我知道导入路径会更改并且将会更改from django.contrib.gis.geoip import GeoIP
,但是 utils 的快捷方式在 1.4 中仍然存在,直到 1.6。无论哪种方式,切换导入路径都展示了与上述相同的行为。