TypeError:assertEqual()至少需要3个参数(给定2个)

时间:2016-08-31 19:42:05

标签: python-2.7 unit-testing

我正在使用python 2.7.6,并且我正在尝试创建一个继承自unittest.TestCase的测试用例类。我在使用assertEqual功能时遇到问题。

这是我的代码:

import assignment3 as a3
import unittest
import numpy as np


class a3Testcase(unittest.TestCase):
    """Test for a3 functions"""
    def func_const(self, x):
        return 1

    def func_linear(self, x):
        return x

    def func_quad(self, x):
        return x**2

    def test_gamma_calc(self):
        """determine the Gamma from gamma distribution
        a to b"""
        self.assertAlmostEqual(a3.gamma_calc(self.func_linear, 0, 2), 2)
        self.assertAlmostEqual(a3.gamma_calc(self.func_quad, 0, 1), 1.0/3)

    def test_cal_gamma_array(self):
        """Find the Gamma at mid point of panels a given gamma distribution"""
        panel_coordinates = np.linspace(0, 1, 1+1)
        self.assertEqual((
            a3.calc_gamma_array(panel_coordinates, self.func_const),
            np.array([1.0])))

if __name__ == '__main__':
    unittest.main()

这是我得到的错误:

Traceback (most recent call last):

File "test_assignment3.py", line 32, in test_cal_gamma_array
    np.array([1.0])))

TypeError: assertEqual() takes at least 3 arguments (2 given)

----------------------------------------------------------------------
Ran 2 tests in 0.000s

FAILED (errors=1)

1 个答案:

答案 0 :(得分:2)

通过这样做:

self.assertEqual((
        a3.calc_gamma_array(panel_coordinates, self.func_const),
        np.array([1.0])))

您实际上是将2个参数传递给assertEqual

  • self(因为它是一个实例方法,对象作为第一个arg传递)
  • (a3.calc_gamma_array(panel_coordinates,self.func_const),np.array([1.0]))

您需要删除括号以实际传递3个参数。写下这个:

self.assertEqual(
        a3.calc_gamma_array(panel_coordinates, self.func_const),
        np.array([1.0]))

对大多数人来说令人困惑的是,self参数与您所犯的错误之间存在一些参数编号错误补偿,使得错误消息难以理解:毕竟,您认为您传递了2个参数。谁需要3个参数? :)