为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕斯709654 2022-11-09 16:33:26
我正在使用 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 实现相同的目标我想停止执行此测试用例并继续执行下一个测试用例。如何做到这一点?请帮忙
查看完整描述

1 回答

?
达令说

TA贡献1821条经验 获得超6个赞

您可以使用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)


查看完整回答
反对 回复 2022-11-09
  • 1 回答
  • 0 关注
  • 136 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号