Python 3.3: 使用nose.tools.assert_equals时出现弃用警告

6 投票
1 回答
4453 浏览
提问于 2025-04-18 02:33

我正在使用nosetest工具来进行Python的unittest测试:

...
from nose.tools import assert_equals, assert_almost_equal

class TestPolycircles(unittest.TestCase):

    def setUp(self):
        self.latitude = 32.074322
        self.longitude = 34.792081
        self.radius_meters = 100
        self.number_of_vertices = 36
        self.vertices = polycircles.circle(latitude=self.latitude,
                                           longitude=self.longitude,
                                           radius=self.radius_meters,
                                           number_of_vertices=self.number_of_vertices)

    def test_number_of_vertices(self):
        """Asserts that the number of vertices in the approximation polygon
        matches the input."""
        assert_equals(len(self.vertices), self.number_of_vertices)

    ...

当我运行python setup.py test时,出现了一个弃用警告:

...
Asserts that the number of vertices in the approximation polygon ...
/Users/adamatan/personal/polycircles/polycircles/test/test_polycircles.py:22:    
DeprecationWarning: Please use assertEqual instead.
  assert_equals(len(self.vertices), self.number_of_vertices)
ok
...

我在nose工具中找不到任何assertEqual,这个警告是从哪里来的,我该如何解决呢?

1 个回答

11

nose.tools里的assert_*函数其实就是一些自动生成的PEP8 别名,它们和TestCase的方法是一样的。所以,assert_equalsTestCase.assertEquals()是同一个东西。

不过,后者其实只是TestCase.assertEqual()的一个别名(注意:没有结尾的s)。这个警告是想告诉你,应该用TestCase.assertEqual(),而不是TestCase.assertEquals(),因为这个alias已经被弃用了。

nose.tools中,这意味着你应该使用assert_equal(同样没有结尾的s):

from nose.tools import assert_equal, assert_almost_equal

def test_number_of_vertices(self):
    """Asserts that the number of vertices in the approximation polygon
    matches the input."""
    assert_equal(len(self.vertices), self.number_of_vertices)

如果你用了assert_almost_equals(带有结尾的s),你也会看到类似的警告,提示你使用assertAlmostEqual

撰写回答