如何使用 mock 停止执行 python 程序?

我正在使用 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 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)

如果我不模拟call_other方法,它将调用 sys.exit(1) 并且会在 unittest 运行中导致一些问题,所以,我不想call_other在测试期间调用 sys.exit(1) 。但是,如果我像上面那样模拟call_other方法(in this_line),它将简单地打印一些东西并继续执行 method f。意思是,它将执行 print 语句(in this_print)这在实际程序中不应该是这种情况,当捕获到异常时,它将执行 sys.exit(1) 并停止程序。当捕获到异常时,如何使用 unittest 和 mock 实现相同的目标我想停止执行此测试用例并继续执行下一个测试用例。


如何做到这一点?请帮忙


慕斯709654
浏览 137回答 1
1回答

达令说

您可以使用unittest' 的功能来断言您是否期望不需要模拟的异常:import unittestimport sysclass ToTest:    def foo(self):        raise SystemExit(1)    def bar(self):        sys.exit(1)    def foo_bar(self):        print("This is okay")        return 0class Test(unittest.TestCase):    def test_1(self):        with self.assertRaises(SystemExit) as cm:            ToTest().foo()        self.assertEqual(cm.exception.code, 1)    def test_2(self):        with self.assertRaises(SystemExit) as cm:            ToTest().bar()        self.assertEqual(cm.exception.code, 1)    def test_3(self):        self.assertEqual(ToTest().foo_bar(), 0)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python