在这种使用情况下,我该如何模拟补丁?

时间:2020-03-05 12:09:19

标签: python python-3.x pytest

最初的场景是从库(lib.py)中编写针对功能的测试。

lib.py:

def fun_x(val):
  # does something with val
  return result

def fun(val):
  x = fun_x(val)
  # does seomthing with x
  return result

test__lib.py

import pytest
import lib

def lib_fun_x_mocked(val):
  return "qrs"

def test_fun():
  assert lib.fun("abc") == "xyz"

但是lib.fun_x()做的事情非常昂贵,或者需要的资源无法可靠地使用或无法确定。因此,我想用一个模拟函数代替它,以便在执行测试test_fun()lib.fun()使用lib_fun_x_mocked()而不是其本地范围的fun_x()

到目前为止,当我尝试应用模拟/补丁配方时,我遇到了隐秘的错误消息。

1 个答案:

答案 0 :(得分:1)

您可以使用pytest提供的内置夹具monkeypatch

import lib

def lib_fun_x_mocked(some_val):  # still takes an argument
    return "qrs"

def test_fun(monkeypatch):
    with monkeypatch.context() as mc:
        mc.setattr(lib, 'fun_x', lib_fun_x_mocked)
        result = lib.fun('abc')
    assert result == 'qrs'

此外,如果要测试函数fun,则不应在该测试中声明fun_x的输出。您应该断言fun的行为与您期望{em {1}}返回给定值的 一样。

相关问题