python - 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)
我不知道为什么会发生此错误以及如何避免它。
解决方案
原因是 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)
推荐阅读
- codeigniter - 如何在codeigniter中正确连接表
- raw-input - 当另一个线程正在运行时,Python (2.7) raw_input 不响应用户输入
- c++ - 在同名的 C++ 顶级函数之间进行选择
- javascript - 使用 Ember 无需单击即可检测文本框中的更改
- maven - 在 Maven 中:如何显示详细的 SureFire 测试结果(从 xml 转换为 html)?
- c# - 当 Html.React() 上的 clientOnly = true 时,ReactJS.Net 给出错误 hydrate is not a function
- javascript - 是什么阻止我提交表格?
- azure - 如果安装 ID 未知,如何更新安装?
- javascript - 如何阻止 SignalR 排队警报
- composer-php - CakeDC 用户插件 Composer 安装