如何使用mock停止python程序的执行?
我使用unittest和mock来测试一个脚本,它看起来像这样如何使用mock停止python程序的执行?,python,python-unittest,python-mock,Python,Python Unittest,Python Mock,我使用unittest和mock来测试一个脚本,它看起来像这样 class Hi: def call_other(self): perform some operation sys.exit(1) def f(self): try: res = self.do_something() a = self.something_else(res) except Exception a
class Hi:
def call_other(self):
perform some operation
sys.exit(1)
def f(self):
try:
res = self.do_something()
a = self.something_else(res)
except Exception as e:
print(e)
call_other()
print("hi after doing something") -----> (this_print)
def process(self)
self.f()
class Test_hi(unittest.TestCase)
def mock_call_other(self):
print("called during error")
def test_fail_scenario():
import Hi class here
h = Hi()
h.process()
h.do_something = mock.Mock(retrun_value="resource")
h.something_else = mock.Mock(side_effect=Exception('failing on purpose for testing'))
h.call_other(side_effect=self.mock_call_other) -----> (this_line)
我的测试脚本如下所示
class Hi:
def call_other(self):
perform some operation
sys.exit(1)
def f(self):
try:
res = self.do_something()
a = self.something_else(res)
except Exception as e:
print(e)
call_other()
print("hi after doing something") -----> (this_print)
def process(self)
self.f()
class Test_hi(unittest.TestCase)
def mock_call_other(self):
print("called during error")
def test_fail_scenario():
import Hi class here
h = Hi()
h.process()
h.do_something = mock.Mock(retrun_value="resource")
h.something_else = mock.Mock(side_effect=Exception('failing on purpose for testing'))
h.call_other(side_effect=self.mock_call_other) -----> (this_line)
如果我不mockcall\u other
方法,它将调用sys.exit(1),这将导致unittest运行中出现一些问题,因此,
在测试期间,我不想调用call\u other
中的sys.exit(1)。
但是,如果我像上面那样模拟调用_other
方法(在这一行中
),它将简单地打印一些内容并继续执行方法f
。也就是说,它将执行print语句(在这个\u print
中)
在实际程序中不应该是这种情况,当捕捉到异常时,它将执行sys.exit(1)并停止程序。
当异常被捕获时,我如何使用unittest和mock实现同样的效果?我想停止这个测试用例的执行并转到下一个测试用例
如何做到这一点?请帮助您可以使用
unittest
的功能来断言是否需要异常,而无需模拟:
导入单元测试
导入系统
类别测试:
def foo(self):
升起系统出口(1)
def bar(自):
系统出口(1)
def foo_bar(自):
打印(“这没关系”)
返回0
类测试(unittest.TestCase):
def测试_1(自身):
使用self.assertRaises(SystemExit)作为cm:
ToTest().foo()
self.assertEqual(cm.exception.code,1)
def测试_2(自身):
使用self.assertRaises(SystemExit)作为cm:
ToTest().bar()
self.assertEqual(cm.exception.code,1)
def测试_3(自身):
self.assertEqual(ToTest().foo_bar(),0)
您想在catch块内从f返回,但仅在测试期间返回?如果是,请将try/catch移到它自己的位置function@geckos将try/catch移动到其自身的功能,如中所示?