如何在python测试中跳过嵌套函数

时间:2019-07-19 07:23:30

标签: python pytest python-unittest

def calculator(a, b):
      sum = a + b
      minus = a - b
      calculate(a, b)
      return sum, minus

def test_cal():
      sum, minus = calculator(5, 4)
      assert sum == 9
      assert minus == 1

我的要求是当上述测试称为计算器方法时,如何跳过计算(计算器中的嵌套方法)?

我听说我们可以通过模拟和修补来实现它,您能在这里帮助我吗?

1 个答案:

答案 0 :(得分:0)

您可以创建简单的“ mokey-patch”函数patch_calculate(),该函数临时对calculate方法进行补丁以使其无效:

from contextlib import contextmanager

def calculate(a, b):
    print("I don't want to call this")

def calculator(a, b):
      sum = a + b
      minus = a - b
      calculate(a, b)
      return sum, minus

@contextmanager
def patch_calculate():
    global calculate
    try:
        original_calculate = calculate
        calculate = lambda *args: None  # do nothing inside calculate
        yield
    finally:
        calculate = original_calculate

def test_cal():
    with patch_calculate():
        sum, minus = calculator(5, 4)
    assert sum == 9
    assert minus == 1

test_cal()