【问题标题】:In Python 3, using Pytest, how do we test for exit code : exit(1) and exit(0) for a python program?在 Python 3 中,使用 Pytest,我们如何测试退出代码:python 程序的 exit(1) 和 exit(0)?
【发布时间】:2020-06-17 10:47:32
【问题描述】:

我是 python 中 Pytest 的新手。

我面临一个棘手的场景,我需要使用 Pytest 模块测试退出代码 - exit(1) 和 exit(0) 。 下面是python程序:

 def sample_script():
     count_file  = 0
     if count_file == 0:
        print("The count of files is zero")
     exit(1)
     else:
         print("File are present")
     exit(0)

现在我想测试上述程序的退出代码 exit(1) 和 exit(0) 。使用 Pytest 我们如何构建测试代码以便我们可以测试或资产函数 sample_script 的退出代码?

请帮帮我。

【问题讨论】:

  • @Martin Prikryl,你能帮我解决这个问题吗?
  • 为什么不将exit() 替换为assert()raise()
  • @Martin Prikryl,你能帮我解决这个问题吗?
  • @Jens ,我们只需要测试退出代码。函数 sample_script () 有 exit code 、 exit(1) 和 exit(0) 。使用 Pytest ,我们需要一个测试程序来测试 sample_script () 的退出代码
  • 你的 Python 函数没有意义,它总是会以代码 1 退出,永远不会到达 else 分支。

标签: python python-3.x function pytest exit-code


【解决方案1】:

按照建议将exit(1) 放入 if 块后,您可以测试SystemExit 异常:

from some_package import sample_script


def test_exit():
    with pytest.raises(SystemExit) as pytest_wrapped_e:
        sample_script()
    assert pytest_wrapped_e.type == SystemExit
    assert pytest_wrapped_e.value.code == 42

示例取自这里:https://medium.com/python-pandemonium/testing-sys-exit-with-pytest-10c6e5f7726f

更新:

这是一个完整的工作示例,您可以复制/粘贴以进行测试:

import pytest

def sample_func():
    exit(1)

def test_exit():
    with pytest.raises(SystemExit) as e:
        sample_func()
    assert e.type == SystemExit
    assert e.value.code == 1

if __name__ == '__main__':
    test_exit()

【讨论】:

  • 在您共享的示例代码中,我可以在其中调用或放置我的python函数 sample_script() ,以便我可以测试退出代码1?
  • 我按照您的建议尝试了,但遇到以下错误:AttributeError : 'ExceptionInfo' object has no attribute 'type'
  • 给我一秒钟试试
  • 一切正常,请仔细检查您的运行方式。
  • 我正在尝试在 PyCharm 控制台中运行它。尝试在终端窗口中使用命令 py.test -v -s 执行 Pytest 程序。它因错误而失败: AttributeError : 'ExceptionInfo' 对象没有属性 'type' .. 如何尝试执行 Pytest 程序?
猜你喜欢
  • 2012-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-21
  • 1970-01-01
  • 2018-07-13
相关资源
最近更新 更多