7

我正在尝试用鼻子编写测试,这些测试使用使用多处理计算的东西进行设置。

我有这个目录结构:

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而只是挂起。

为什么会这样,最简单的解决方案是什么?

4

1 回答 1

4

pool.map问题与在“全局级别”调用的事实有关。通常你想避免这种情况,因为即使你的文件只是被导入,这些语句也会被执行。

Nose 必须导入您的模块才能找到您的测试并稍后执行它们,因此我相信问题发生在导入机制启动时(我没有花时间试图找出这种行为的确切原因)

您应该将初始化代码移至测试夹具;鼻子用with_setup装饰器支撑固定装置。这是一种可能性(可能是保持poolout作为全局变量时最简单的更改):

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
于 2014-02-04T09:15:46.987 回答