单元测试:属性错误:模块“\uu main\uuuu”没有属性“C:\…”

2024-09-27 23:28:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用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)

我不知道,为什么会发生这种错误以及如何避免它


Tags: testimportselfusemaindefexitunittest
1条回答
网友
1楼 · 发布于 2024-09-27 23:28:38

原因是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)

相关问题 更多 >

    热门问题