首页 > 解决方案 > python自调用单元测试功能不会引发错误

问题描述

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

我使用了 AssertAlmostEqual 单元测试,但我发现对于大数字它效果不佳,因为它可以工作到小数点后 7 位(我认为)。当测试大指数时,这变得有点没用。所以我尝试为有效数字而不是小数位定义一个 assertEqualSigFig 测试。该测试的灵感来自于 stack over flow post,但是我恐怕找不到原始帖子。

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

这是我的代码:

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 调用不会引发错误。我确定我错过了一件愚蠢的事情,但我仍在学习。有人可以帮忙吗?

标签: pythonunit-testingrecursionpython-unittest

解决方案


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

我应该一直在使用

MyTestClass.assertEqualSigFig 

并不是

self.assertEqualSigFig

推荐阅读