使用Python的unittest测试class时,出现奇怪的错误

When using Python's unittest to test an class, an strange error occurs

我使用 unittest 制作了以下测试用例:

if __name__ == "__main__":
    class TestList(unittest.TestCase):
        def setUp(self):
            self.li = List(["ABC", 5.6, (3, 6)])
    
        def test_append(self):
            self.li.append(1)
            self.assertEqual(self.li, List(["ABC", 5.6, (3, 6), 1]))
    
        def test_insert(self):
            self.li.insert(1, "ABC")

这是我的 List class(为了简洁省略了一些方法):

class List(MutableSequence):
    def __init__(self, seq=None):
        self.seq = {} if seq is None else self._dict_from_seq(seq)

    def __getitem__(self, item):
        try:
            return self.seq[item]
        except KeyError:
            raise IndexError("list index out of range") from None

    def __setitem__(self, key, value, *, usage=None):
        if key > max(self.seq.keys()) and usage != "append":
            raise IndexError("list index out of range")
        self.seq[key] = value

    def __delitem__(self, key):
        try:
            del self.seq[key]
        except KeyError:
            raise IndexError("list index out of range") from None

    @classmethod
    def _dict_from_seq(cls, seq):
        return OrderedDict(enumerate(seq))

    def _next_available_slot(self):
        return max(self.seq) + 1

    def append(self, item):
        self.__setitem__(self._next_available_slot(), item, usage="append")

    def insert(self, index, value):
        if index > max(self.seq.keys()):
            raise IndexError("list index out of range")
        self[index] = value

当我 运行 unittest.main() 时,我得到以下错误:

File "C:\...\AppData\Local\Programs\Python\Python38\lib\unittest\loader.py", line 34, in testFailure
    raise self._exception
  File "C:\...\AppData\Local\Programs\Python\Python38\lib\unittest\loader.py", line 169, in loadTestsFromName
    parent, obj = obj, getattr(obj, part)
AttributeError: module 'fastseq' has no attribute 'TestList'

为什么会这样?

我解决了这个问题。显然,loader.py 无法获得 TestList class,因为 __name__ 不是 __main__。所以我只是将 if __name__ == "__main__": 行移动到我调用 unittest.main().

的位置