首页 > 解决方案 > unittest:AttributeError:模块'__main__'没有属性'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 行的数据框。为了确保它正确运行,我想编写一个单元测试。但是,如果我尝试开始测试,则会显示以下错误消息:

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)

我不知道为什么会发生此错误以及如何避免它。

标签: pythonpython-unittest

解决方案


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

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

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

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

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

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

推荐阅读