jupyter notebook运行python单元测试报错及解决方案
在Jupyter Notebook中运行Python单元测试代码时,使用unittest.main()可能会导致程序意外退出,并出现AttributeError或SystemExit错误。本文将分析该问题,并提供有效的解决方案。
问题描述:
下图展示了在Jupyter Notebook中运行单元测试代码时遇到的错误。

立即学习“Python免费学习笔记(深入)”;
代码示例:
name_function.py:
<code class="python">def name_function_name(first, last):
"""生成格式规范的完整姓名"""
full_name = first + ' ' + last
return full_name.title()</code>test_name_function.py:
<code class="python">import unittest
from name_function import name_function_name
class NameTestCase(unittest.TestCase):
"""测试name_function"""
def test_first_last_name(self):
formatted_name = name_function_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
unittest.main()</code>错误信息通常类似于:
<code>AttributeError: module '__main__' has no attribute '...' SystemExit: True</code>
解决方案:
unittest.main()函数在执行完毕后会默认调用sys.exit(),这会导致Jupyter Notebook内核终止。为了避免这种情况,需要修改test_name_function.py文件,添加以下代码:
<code class="python">import unittest
from name_function import name_function_name
class NameTestCase(unittest.TestCase):
"""测试name_function"""
def test_first_last_name(self):
formatted_name = name_function_name('janis', 'joplin')
self.assertEqual(formatted_name, 'Janis Joplin')
if __name__ == '__main__':
unittest.main(argv=['first-arg-is-ignored'], exit=False)</code>关键修改:
if __name__ == '__main__': 这行代码确保unittest.main()只在脚本直接运行时执行,而不是在作为模块导入时执行。unittest.main(argv=['first-arg-is-ignored'], exit=False) argv参数是为了避免unittest.main()对命令行参数的处理,exit=False阻止了unittest.main()调用sys.exit()。通过以上修改,unittest.main()将不会终止Jupyter Notebook内核,测试结果将正常显示在Jupyter Notebook单元格中。 记住,assertEqual中的预期结果应为'Janis Joplin',而不是'janis joplin',因为title()方法会将首字母大写。
以上就是Jupyter Notebook中运行Python测试代码报错:如何解决unittest.main()导致程序退出问题?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号