Python 未定义Unittest子测试中的局部变量

Python 未定义Unittest子测试中的局部变量,python,python-unittest,Python,Python Unittest,我有一个unittest的测试任务。我得到了NameError错误:没有在每个子测试中定义名称“x”。 在看了课程材料和文档之后,我不知道错误是什么。我该如何解决这个问题 import unittest def factorize(x): """ Factorize positive integer and return its factors. :type x: int,>=0 :rtype: tuple

我有一个unittest的测试任务。我得到了NameError
错误:没有在每个子测试中定义名称“x”。
在看了课程材料和文档之后,我不知道错误是什么。我该如何解决这个问题

    import unittest


    def factorize(x):
        """
        Factorize positive integer and return its factors.
        :type x: int,>=0
        :rtype: tuple[N],N>0
        """
        pass


    class TestFactorize(unittest.TestCase):
        def test_wrong_types_raise_exception(self):
            cases = ['string', 1]
            for case in cases:
                with self.subTest(x=case):
                    print(x)
                    self.assertRaises(TypeError, factorize, x)

        def test_negative(self):
            cases = [-1, -10, -100]
            for case in cases:
                with self.subTest(x=case):
                    self.assertRaises(ValueError, factorize, x)

        def test_zero_and_one_cases(self):
            cases = [0, 1]
            for case in cases:
                with self.subTest(x=case):
                    self.assertEqual(factorize(x), (x,))

        def test_simple_numbers(self):
            cases = [3, 13, 29]
            for case in cases:
                with self.subTest(x=case):
                    self.assertEqual(factorize(x), (x,))


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

子测试
未定义新的局部变量
x
x
只是测试失败时用作错误消息一部分的名称。例如,您需要在测试代码本身中继续使用
case

def test_wrong_types_raise_exception(self):
    cases = ['string', 1]
    for case in cases:
        with self.subTest(x=case):
            print(case)
            self.assertRaises(TypeError, factorize, case)
将调用更改为
子测试(foo=case)
将导致标记变为
foo='string'

======================================================================
FAIL: test_wrong_types_raise_exception (__main__.TestFactorize) (x='string')
----------------------------------------------------------------------
Traceback (most recent call last):
  File "tmp.py", line 19, in test_wrong_types_raise_exception
    self.assertRaises(TypeError, factorize, case)
AssertionError: TypeError not raised by factorize