unittest: AttributeError: module '__main__' has no attribute 'C:\...'

unittest: AttributeError: module '__main__' has no attribute 'C:\...'

我正在尝试 运行 在 Python 中进行测试。简化后看起来像这样:

#import librarys
import unittest

def methodToTest (df1, df2):
     #do something
     df3 = createDf3()
     return df3

#define test data
df4 = someDf
df5 = anotherDf

class TestMethodToTest(unittest.TestCase):
    def test_m (self):
        result = methodToTest(someDf, anotherDf)
        self.assertEqual(len(result), 2)

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

所以我有一个方法“methodToTest”,并且我创建了一些输入“df4”和“df5”。 我知道如果你把输入放在方法中,结果应该是一个有 2 行的数据框。 为了确保 运行ning 正确,我想编写一个单元测试。 但是,如果我尝试开始测试,则会显示以下错误信息:

E
======================================================================
ERROR: C:\...\runtime\kernel-... (unittest.loader._FailedTest)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute 'C:\...\jupyter\runtime\kernel-...'

----------------------------------------------------------------------
Ran 1 test in 0.002s

FAILED (errors=1)
An exception has occurred, use %tb to see the full traceback.

SystemExit: True
C:\...\interactiveshell.py:...: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D.
  warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)

我不知道为什么会出现这个错误以及如何避免它。

原因是 unittest.main 查看 sys.argv 并且第一个参数是启动 IPython 或 Jupyter,

因此有关内核连接文件不是有效属性的错误。

将显式列表传递给 unittest.main 将阻止 IPython 和 Jupyter 查看 sys.argv。

传递 exit=False 将阻止unittest.main关闭内核进程

https://medium.com/@vladbezden/using-python-unittest-in-ipython-or-jupyter-732448724e31

if __name__ == '__main__':
    unittest.main(argv=['first-arg-is-ignored'], exit=False)