【问题标题】:Catch SystemExit message with Pytest使用 Pytest 捕获 SystemExit 消息
【发布时间】:2021-06-13 13:45:03
【问题描述】:

我正在使用 pytest 编写测试。我有一种情况,如果输入错误,某些函数会在终端上抛出 SystemExit 并显示一些错误消息。

我想为抛出SystemExit的情况编写测试,并验证输出错误消息中是否存在特定字符串。

代码如下:


def test_validate_input():
  ...
  with pytest.raises(SystemExit) as error:
    _validate_function(test_wrong_input)
  assert error.value.code == 1

如果我运行验证某些输入的实际函数,我无法在命令行上获得error 中的输出错误消息。请让我知道我在这里缺少什么。

编辑:

我正在调用 subprocess.call_output 来运行引发错误的命令。我必须在call_output 调用中添加stderr=subprocess.STDOUT 作为参数来获取错误消息。然后我在测试中使用了@p3j4p5 的答案。

【问题讨论】:

  • 如果这确实是记录器生成的消息,您将需要查看this thread
  • 对不起,我把log换成了终端上的错误信息。

标签: python python-3.x pytest systemexit


【解决方案1】:

如果我理解正确,您的消息会打印在 stderr 之前 SystemExit 被提出,在这种情况下你需要capsys

def test_validate_input(capsys):
  ...
  with pytest.raises(SystemExit) as error:
      _validate_function(test_wrong_input)
  assert error.value.code == 1
  captured = capsys.readouterr()
  assert captured.err == "Expected error message\n"

【讨论】:

  • 我尝试使用capsys,但在captured.err.out 中没有得到任何东西
  • 那么,消息是否可能在 SystemExit 异常中,请参阅其他答案。
【解决方案2】:

Pytest 的 raises() 接受 match 参数。文档告诉我们:

如果指定,则为包含正则表达式的字符串,或正则表达式对象,针对异常的字符串表示进行测试

这仅在pytest.raises 用作上下文管理器时使用

所以应该适合你的情况:

def test_validate_input():
  ...
  with pytest.raises(SystemExit, match='exception message content'):
      _validate_function(test_wrong_input)

如果引发的 SystemExit 异常已引发并带有与提供的正则表达式匹配的消息,则此测试将通过,否则将失败。

或者,如果您想手动检查消息:

上下文管理器生成一个ExceptionInfo 对象,可用于检查捕获的异常的详细信息

在您的情况下,假设 SystemExit 使用整数(代码)和字符串(消息)调用:

def test_validate_input():
  ...
  with pytest.raises(SystemExit) as exc_info:
      _validate_function(test_wrong_input)

  assert exc_info.value.args[0] == 1
  assert exc_info.value.args[1] == 'exception message content'

【讨论】:

  • 我想去手动检查的方式,还是无法在exc_info.value.args[1]得到终端输出。
  • 到底是什么问题?
  • 我发现了问题所在。我必须添加 stderror=subprocess.STDOUT 才能收到错误消息。
  • 太棒了!您能否与我们分享您在哪里添加了该声明?
  • 是的,我在答案中添加了我添加的内容作为编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-24
  • 2013-12-10
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多