我正在尝试编写测试nose http://nose.readthedocs.org/en/latest/建立一些东西
使用多处理计算。
我有这个目录结构:
code/
tests/
tests.py
test.py 看起来像这样:
import multiprocessing as mp
def f(i):
return i ** 2
pool = mp.Pool()
out = pool.map(f, range(10))
def test_pool():
"""Really simple test that relies on the output of pool.map.
The actual tests are much more complicated, but this is all
that is needed to produce the problem."""
ref_out = map(f, range(10))
assert out == ref_out
if __name__ == '__main__':
test_pool()
运行从code
目录,python tests/tests.py
passes.
nosetests tests/tests.py
fails去完成。它启动了,但从未接通对pool.map
并且只是挂起。
这是为什么?最简单的解决方案是什么?
这个问题与以下事实有关:pool.map
被称为“全球级别”。通常您希望避免这种情况,因为即使您的文件只是导入,这些语句也会被执行。
鼻子必须导入你的模块 https://github.com/nose-devs/nose/blob/bee2720b041e7a030124273dac6d39da562e4738/nose/loader.py#L412-L413能够找到您的测试并稍后执行它们,因此我相信问题是在导入机制启动时发生的(我没有花时间尝试找出此行为的确切原因)
您应该将初始化代码移至测试装置;鼻子支撑固定装置with_setup https://nose.readthedocs.org/en/latest/testing_tools.html#nose.tools.with_setup装饰师。这是一种可能性(可能是最简单的改变,同时保持pool
and out
作为全局变量):
import multiprocessing as mp
from nose import with_setup
pool = None
out = None
def f(i):
return i ** 2
def setup_func():
global pool
global out
pool = mp.Pool()
out = pool.map(f, range(10))
@with_setup(setup_func)
def test_pool():
"""Really simple test that relies on the output of pool.map.
The actual tests are much more complicated, but this is all
that is needed to produce the problem."""
global out
ref_out = map(f, range(10))
assert out == ref_out
if __name__ == '__main__':
test_pool()
执行:
$ nosetests tests/tests.py
.
----------------------------------------------------------------------
Ran 1 test in 0.011s
OK
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)