python - 用 Nose 测试 python 多处理池代码

标签 python testing multiprocessing python-nose

我正在尝试使用 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 支撑固定装置装饰器。这是一种可能性(可能是最简单的更改,同时将 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

关于python - 用 Nose 测试 python 多处理池代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18640334/

相关文章:

testing - 使用 Selenium,xpath 找不到 'text' 元素

python - multiprocessing.Pool.map_async() 的结果是否以与输入相同的顺序返回?

用于并行进程的 Python 多处理

python - 程序与 map() 一起工作,但通过 pool.map() 引发 TypeError

python - 在python中展平列表

python - 处理数据帧列中大量不同值的总和

python - 从 numpy 数组中删除多次出现的元素

python - 尝试超出顶级包的相对导入?

java - 如何使用嵌套生成器编写 jqwik 生成器方法

testing - 在 testcafe 中捕获数据属性