在python编码后覆盖更多的测试,以包括异常场景



try:
r = requests.get(url, params={'s': thing})
except requests.ConnectionError, e:
print(e)

如何使用pytest测试except中的行?那是在尝试获取/发布时出现错误的时候?

您需要捕获代码的标准输出(即print写入的文件)。您可以使用capsys夹具来执行此操作。

def test_code(capsys):
# Code in which the request will fail
try:
r = requests.get(url, params={'s': thing})
except requests.ConnectionError as e:
print(e)
assert capsys.readouterr().out == "Expected error message"