jupyter notebook运行python单元测试报错及解决方案
在Jupyter Notebook中运行Python单元测试代码时,使用unittest.main()可能会导致程序意外退出,并出现AttributeError或SystemExit错误。本文将分析该问题,并提供有效的解决方案。
问题描述:
下图展示了在Jupyter Notebook中运行单元测试代码时遇到的错误。
立即学习“Python免费学习笔记(深入)”;
代码示例:
name_function.py:
def name_function_name(first, last): """生成格式规范的完整姓名""" full_name = first + ' ' + last return full_name.title()
test_name_function.py:
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()
错误信息通常类似于:
AttributeError: module '__main__' has no attribute '...' SystemExit: True
解决方案:
unittest.main()函数在执行完毕后会默认调用sys.exit(),这会导致Jupyter Notebook内核终止。为了避免这种情况,需要修改test_name_function.py文件,添加以下代码:
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)
关键修改:
通过以上修改,unittest.main()将不会终止Jupyter Notebook内核,测试结果将正常显示在Jupyter Notebook单元格中。 记住,assertEqual中的预期结果应为'Janis Joplin',而不是'janis joplin',因为title()方法会将首字母大写。
以上就是Jupyter Notebook中运行Python测试代码报错:如何解决unittest.main()导致程序退出问题?的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号