我正在尝试使用 nose 编写测试设置一些东西 使用多处理计算。
我有这样的目录结构:
code/
tests/
tests.py
tests.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
通过。
nosetests tests/tests.py
未能 完成。它启动了,但从未完成对 pool.map
的调用,只是挂起。
这是为什么?最简单的解决方案是什么?
最佳答案
问题与 pool.map
在“全局级别”调用有关。通常您希望避免这种情况,因为即使您的文件只是简单地导入,这些语句也会被执行。
Nose 必须 import your module能够找到您的测试并稍后执行它们,因此我相信问题是在导入机制启动时发生的(我没有花时间试图找出这种行为的确切原因)
您应该将您的初始化代码移至测试夹具; Nose 用 with_setup
支撑固定装置装饰器。这是一种可能性(可能是最简单的更改,同时将 pool
和 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
关于python - 用 Nose 测试 python 多处理池代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18640334/