You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Unittest在Jupyter Notebook运行失败但Spyder正常的问题排查

问题

我是Python测试新手,编写了如下unittest测试用例:

def add(n,m):
    return n+m
def mul(a,b):
    return a*b

import unittest
class DemoTest(unittest.TestCase): #child of TestCase
    
    def testadd(self):
        self.assertEqual(add(5,5),10) #when we pass, 5 n 5 it should return 10
    def testmul(self):
        self.assertEqual(mul(5,7),35)
if __name__=='__main__':
    unittest.main()

在Jupyter Notebook中运行时出现如下错误:

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

----------------------------------------------------------------------
Ran 1 test in 0.003s

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

SystemExit: True

但相同代码在Spyder中运行正常,输出结果如下:

..
----------------------------------------------------------------------
Ran 2 tests in 0.003s

OK

请问需要对Jupyter Notebook进行哪些设置调整来解决该问题?

解决方法

无需调整Jupyter Notebook的设置,只需修改测试代码中unittest.main()的调用逻辑即可。问题根源是Jupyter环境下,unittest.main()会将当前文件路径误识别为测试用例名称,从而引发错误。

修改后的完整代码如下:

def add(n,m):
    return n+m
def mul(a,b):
    return a*b

import unittest
class DemoTest(unittest.TestCase): #child of TestCase
    
    def testadd(self):
        self.assertEqual(add(5,5),10) #when we pass, 5 n 5 it should return 10
    def testmul(self):
        self.assertEqual(mul(5,7),35)
if __name__=='__main__':
    unittest.main(argv=['ignored'], exit=False)

两处关键修改说明:

  • argv=['ignored']:让unittest忽略Jupyter传递的命令行参数(当前文件路径),避免将路径当作测试用例名解析。
  • exit=False:阻止unittest执行完成后触发SystemExit,避免Jupyter抛出异常。

修改后在Jupyter Notebook中运行,就能得到和Spyder一致的正常测试输出。

内容的提问来源于stack exchange,提问作者Anki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 10:12:04