在iPy Notebook中运行unittest样本时的AttributeError

时间:2014-07-28 21:48:50

标签: python ipython-notebook

我是iPython的新手,并试图帮助其他开发人员开始,我们都遇到了同样的问题。

我们正试图从https://docs.python.org/2/library/unittest.html#basic-example在iPython中运行python unittest示例 代码在windows和ubuntu上的命令行运行良好,无需任何修改 来自iPy笔记本的完全相同的代码会产生以下异常:

AttributeError: 'module' object has no attribute '/home/myuser/'

文件名为:/home/myuser/example_unittest.ipynb

目前我已经对iPython文档进行了涂鸦并没有运气。任何调试技巧或解决此问题的线索都值得赞赏。

(全栈):

AttributeError                            Traceback (most recent call last)
<ipython-input-2-39bc0ec16f11> in <module>()
     28 
     29 if __name__ == '__main__':
---> 30     unittest.main()
     31 

/usr/lib/python2.7/unittest/main.pyc in __init__(self, module, defaultTest, argv, testRunner, testLoader, exit, verbosity, failfast, catchbreak, buffer)
     92         self.testLoader = testLoader
     93         self.progName = os.path.basename(argv[0])
---> 94         self.parseArgs(argv)
     95         self.runTests()
     96 

/usr/lib/python2.7/unittest/main.pyc in parseArgs(self, argv)
    147             else:
    148                 self.testNames = (self.defaultTest,)
--> 149             self.createTests()
    150         except getopt.error, msg:
    151             self.usageExit(msg)

/usr/lib/python2.7/unittest/main.pyc in createTests(self)
    156         else:
    157             self.test = self.testLoader.loadTestsFromNames(self.testNames,
--> 158                                                            self.module)
    159 
    160     def _do_discovery(self, argv, Loader=loader.TestLoader):

/usr/lib/python2.7/unittest/loader.pyc in loadTestsFromNames(self, names, module)
    126         of string specifiers. See 'loadTestsFromName()'.
    127         """
--> 128         suites = [self.loadTestsFromName(name, module) for name in names]
    129         return self.suiteClass(suites)
    130 

/usr/lib/python2.7/unittest/loader.pyc in loadTestsFromName(self, name, module)
     98         obj = module
     99         for part in parts:
--> 100             parent, obj = obj, getattr(obj, part)
    101 
    102         if isinstance(obj, types.ModuleType):

AttributeError: 'module' object has no attribute '/home/myuser/'

2 个答案:

答案 0 :(得分:9)

unittest.main()主要用于命令行执行。

要在ipython笔记本中运行unittest,请删除代码的if __name__ == '__main__'部分,然后在新单元格中创建一个测试套件,然后使用TextTestRunner运行它,

suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
unittest.TextTestRunner().run(suite)

答案 1 :(得分:4)

由于unittest.main检查参数(sys.argv)而导致该错误的原因。是什么启动了iPython或Jupyter。

将您的代码更改为:

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

在笔记本中,您还需要包含exit=False以防止unittest.main尝试关闭内核进程: