fab*_*gli 5 python numpy python-unittest
我正在numpy.testing.assert_almost_equal单元测试环境中使用 - 但我不确定结合 numpy 和单元测试的正确方法是什么。
我的第一个方法是使用单元测试中的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
)
Run Code Online (Sandbox Code Playgroud)
这给出了正确的测试结果,但它有点 hacky 并且使测试代码变得臃肿。
更简单的方法如下:
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)
Run Code Online (Sandbox Code Playgroud)
此代码还返回正确的测试统计信息,如上面所示,但它更具可读性。我看到的唯一缺点是 pylint 抱怨“R0201 方法可能是一个函数”消息。这会成为一个问题吗?
PS:我在这里检查了多篇看起来相关的帖子,但没有回答我关于单元测试和 numpy 测试集成的具体问题。(例如/sf/answers/302390931/讨论了在单元测试中捕获异常。这似乎是错误的,或者只是一种矫枉过正。)
如果你在一个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)
Run Code Online (Sandbox Code Playgroud)
请注意,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)
Run Code Online (Sandbox Code Playgroud)