问题描述
我正在使用subprocess
执行任务,并且有一个try/except
块可以捕获TimeoutExpired
。我尝试使用side_effect
模拟对象,以便可以使用pytest.raises
捕获假异常。无论我做什么,我都会得到DID NOT RAISE <class 'subprocess.TimeoutExpired'>
。
我已经尝试了很多事情,尽管我对模拟还没有足够的经验,但我相信类似的事情原则上应该可以工作:
# my_check.py
from subprocess import TimeoutExpired,PIPE,check_output
class Check:
def __init__(self,name):
self.name = name
self.status = self.get_status()
def get_status(self):
try:
out = check_output(["ls"],universal_newlines=True,stderr=PIPE,timeout=2)
except TimeoutExpired as e:
print(f"Command timed out: {e}")
raise
if self.name in out:
return True
return False
# test_my_check.py
import pytest
from unittest import mock
from subprocess import TimeoutExpired
@mock.patch("src.my_check.Check",autospec=True)
def test_is_installed_exception(check_fake):
check_fake.get_status.side_effect = TimeoutExpired
obj_fake = check_fake("random_file.txt")
with pytest.raises(TimeoutExpired):
obj_fake.get_status()
由于某种原因它无法正常工作,而且我无法弄清问题所在。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)