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

问题描述 投票:0回答:1

我正在使用unittest和嘲笑来测试如下所示的脚本

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),这会在单元测试运行中引起一些问题,因此,在测试期间,我不想在call_other中调用sys.exit(1)。但是,如果我模拟了上面的call_other方法(在this_line中),它将只打印一些内容并继续执行方法f。意思是,它将执行打印语句(在this_print中)在实际程序中情况并非如此,当捕获到异常时,它将执行sys.exit(1)并停止程序。捕获异常后,如何使用unittest和嘲笑实现相同的目的,我想停止执行该测试用例并继续进行下一个测试用例。

如何实现?请帮助

python python-unittest python-mock
1个回答
0
投票

如果您期望异常而无需模拟,则可以使用unittest的功能进行断言:

import unittest
import sys


class ToTest:
    def foo(self):
        raise SystemExit(1)

    def bar(self):
        sys.exit(1)

    def foo_bar(self):
        print("This is okay")
        return 0

class 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)
© www.soinside.com 2019 - 2024. All rights reserved.