将numpy.testing函数与unittest一起使用

问题描述 投票:1回答:1

[我在单元测试环境中使用numpy.testing.assert_almost_equal-但我不确定将numpy和unittest结合使用的正确方法是什么。

我的第一种方法是将unittest中的assertTrue与is None比较结合使用,如下所示:

from unittest import TestCase
import numpy as np

class TestPredict(TestCase):
    def test_succeeding(self):
        self.assertTrue(
            np.testing.assert_almost_equal(1, 0.9999999999999) is None
        )
    def test_failing(self):
        self.assertTrue(
            np.testing.assert_almost_equal(1, 0.9) is None
        )

这给出了正确的测试结果,但是它有点笨拙,并且使测试代码膨胀。

一种更简单的方法如下:

from unittest import TestCase
import numpy as np

class TestPredict(TestCase):
    def test_succeeding(self):
        np.testing.assert_almost_equal(1, 0.9999999999999)
    def test_failing(self):
        np.testing.assert_almost_equal(1, 0.9)

此代码也返回上述正确的测试统计信息,但是可读性更高。我看到的唯一缺点是pylint抱怨“ R0201方法可能是函数”消息。这会成为问题吗?

PS:我在此处检查了多个与SO相关的帖子,但没有回答有关unittest和numpy测试集成的具体问题。 (例如https://stackoverflow.com/a/4319870/6018688谈论在单元测试中捕获异常。这似乎是错误的,或者仅仅是一个过大的杀手。)

python numpy python-unittest
1个回答
1
投票

如果您处于unittest环境中,则第二次尝试完全可以。如果您不想使用pylint警告,可以通过以下方法创建静态函数:

from unittest import TestCase
import numpy as np

class TestPredict(TestCase):
    @staticmethod
    def test_succeeding():
        np.testing.assert_almost_equal(1, 0.9999999999999)

    @staticmethod
    def test_failing():
        np.testing.assert_almost_equal(1, 0.9)

请注意,pylint基本上只是警告未使用的self参数-除了警告本身之外,这不会引起任何问题。

如果可以使用pytest代替,则代码将变得更加简洁,因为您不必从测试用例类派生:

import numpy as np

def test_succeeding():
    np.testing.assert_almost_equal(1, 0.9999999999999)

def test_failing():
    np.testing.assert_almost_equal(1, 0.9)
© www.soinside.com 2019 - 2024. All rights reserved.