【问题标题】:How can i test numba vectorized functions with pytest如何使用 pytest 测试 numba 矢量化函数
【发布时间】:2021-11-15 16:38:03
【问题描述】:

我目前正在编写几个函数,它们都使用numba 进行了优化(一个使用@guvectorize,一个使用@vectorize。 我还为这两个函数编写了一些测试,但是当我运行pytest --cov --cov-report term-missing 时,我发现缺少的行对应于优化的函数。

这是 pytest 如何在函数上运行测试的问题,还是由于其他(我的)问题?

这两个函数中最简单的是:

@vectorize(["float64(float64, float64)", "float32(float32, float32)"], nopython=True)
def binarize_mask(mask_data, threshold):
    """Binarize the mask array based on a threshold.

    :param mask_data: Mask array.
    :param threshold: Threshold to apply to the mask.
    """
    # Binarize the mask array
    return 1 if mask_data >= threshold else 0

我使用以下测试进行测试:

  1. 对于单个值:
def test_binarize_mask_return_value():
    threshold = np.float32(0.5)
    assert dl.binarize_mask(np.float32(0.3), threshold) == 0
    assert dl.binarize_mask(np.float32(0.7), threshold) == 1
  1. 对于数组:
def test_binarize_mask_float32():
    test_data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=np.float32)
    test_mask = np.array([0, 0, 1, 1, 1, 1, 1, 1, 1, 1], dtype=np.float32)
    binarized = dl.binarize_mask(test_data, 3.0)
    assert binarized.dtype == np.float64
    assert binarized.shape == test_mask.shape
    assert np.all(binarized == test_mask)

【问题讨论】:

    标签: python testing pytest numba test-coverage


    【解决方案1】:

    只要代码被编译,coverage.py 就无法再测量代码的覆盖率。你可以找到一些issuesabout这个。

    您可以简单地将未经测试的代码隐藏在 excluding code from coverage.py 之下。

    但我知道您对您的代码很认真,并且您确实想检查您的算法。然后你可以运行你的测试两次。通过设置环境变量NUMBA_DISABLE_JIT=1,一个用于检查您的代码,另一个仅用于覆盖范围,如here 所述。

    【讨论】:

    • 感谢您的回答,不幸的是,您链接NUMBA_DISABLE_JIT=1 的帖子不起作用,所以我按照您的建议将测试排除在覆盖范围之外。\
    猜你喜欢
    • 1970-01-01
    • 2021-04-27
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-13
    • 1970-01-01
    相关资源
    最近更新 更多