【发布时间】:2014-02-04 16:53:19
【问题描述】:
所以,我有一个小的 Python 导入谜团。我相信出于某种原因应该是这样的,因为 Guido 很少出错。但是,为什么会这样呢?
$ cat myModule.py
#!/usr/bin/python
class SomeModule(object):
def __init__(self):
print "in SomeModule.__init__ ! "
def doSomething(self):
print 'doing something.'
$ cat myTest.py
import unittest
from myModule import SomeModule
class TestMyModule(unittest.TestCase):
def test_001(self):
print "should see init below"
sm = SomeModule()
sm.doSomething()
print "should see init above\n"
def test_002(self):
print "should not see init below."
from myModule import SomeModule as SM2
SM2.__init__ = lambda x: None
sm2 = SM2()
sm2.doSomething()
print "should not have seen init above.\n"
def test_bbb(self):
print "Should see init below"
sm = SomeModule()
sm.doSomething()
print "should see init above\n"
$ nosetests myTest.py -s
should see init below
in SomeModule.__init__ !
doing something.
should see init above
.should not see init below.
doing something.
should not have seen init above.
.Should see init below
doing something.
should see init above
.
----------------------------------------------------------------------
Ran 3 tests in 0.001s
OK
最终测试应该不受中间测试导入的影响,对吧?我的直觉说我不必担心初始导入,因为第二次导入使用“as”。 因此,在最后一次测试中,我希望看到 init 但我没有。
显然,第二次导入,“从 myModule 导入 SomeModule 作为 SM2”,破坏了 Some Module 的初始导入,尽管它看起来应该是一个完全独立的实体,如 SM2,而不是 SomeModule。
这对某人有意义吗?
【问题讨论】:
标签: python nosetests python-unittest