Python自调用单元测试功能不会引发错误

时间:2018-12-05 13:33:19

标签: python unit-testing recursion python-unittest

我有C和Fortran编程背景,但是我一直在尝试学习Python和面向对象。为了帮助我的某些项目,我一直在尝试定义一些其他的单元测试。

我已经使用了AssertAlmostEqual单元测试,但是我发现对于较大的数字,它不能很好地工作,因为它可以工作到7个小数位(我认为)。当测试大指数时,这变得毫无用处。因此,我尝试为有效数字而不是小数位定义一个assertEqualSigFig测试。该测试的灵感来自流程帖子上的堆栈,但是我找不到原始的帖子。

此测试适用于整数浮点数和布尔值,但是我想看看它是否也适用于复数。通过将数字分成实部和虚部,然后调用自身。发生这种情况时,不会引发断言错误,而且我不确定为什么。

这是我的代码:

import unittest
import math

class MyTestClass(unittest.TestCase):
    """
    MyTestClass
    Adds additional tests to the unit test module:
    defines:
    - AssertEqualSigFig
        description: 
        - Used in place of the assertAlmostEqualTest, this tests two values
          are the same to 7 significant figures (instead of decimal places)
        args:
        - any two integers, booleans, floats or complex number
        returns:
        - assertion error if not equal to defined significant figures
    """

    def AssertEqualSigFig(self, expected, actual, sig_fig = 7):

        if sig_fig < 1:
            msg = "sig fig must be more than 1"
            raise ValueError(msg)
        try:
            if isinstance(expected, bool):
                if expected != actual:
                    raise AssertionError
                else:
                    return

            elif isinstance(expected, (int,float)):
                pow_ex = int(math.floor(math.log(expected,10)))
                pow_ac = int(math.floor(math.log(actual,10)))

                tolerance = pow_ex - sig_fig + 1
                tolerance = (10** tolerance)/2.0

                if abs(expected - actual) > tolerance:
                    raise AssertionError
                else:
                    return

            elif isinstance(expected, complex):
                #this part doesnt raise an error when it should
                a_real = actual.real
                a_imag = actual.imag
                e_real = expected.real
                e_imag = expected.imag
                self.AssertEqualSigFig(self, a_imag, e_imag)
                self.AssertEqualSigFig(self, a_real, e_real)

        except AssertionError:
            msg = "{0} ! = {1} to {2} sig fig".format(expected, actual, sig_fig)
            raise AssertionError(msg)

当涉及复数时,该测试失败。这是失败的单元测试的单元测试:

import unittest

from MyTestClass import MyTestClass

class TestMyTestClass(MyTestClass):

    def test_comlex_imag_NE(self):
        a = complex(10,123455)
        b = complex(10,123333)
        self.assertRaises(AssertionError, self.AssertEqualSigFig, a, b)

    def test_complex_real_NE(self):
        a = complex(2222222,10)
        b = complex(1111111,10)
        self.assertRaises(AssertionError, self.AssertEqualSigFig, a, b)


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

我认为这是因为self.AssertEqualSigFig调用不会引发错误。我敢肯定我错过了一件愚蠢的事情,但是我仍在学习。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

我是个白痴,我找到了解决方法

我应该一直在使用

MyTestClass.assertEqualSigFig 

而不是

self.assertEqualSigFig