如何在pytest中模拟模拟对象的输出



我有这个函数:

def get_sf_connection(usr, acc, key_path, vwh, db):
with open(f"{key_path}", "rb") as key:
p_key = serialization.load_pem_private_key(
key.read(), password=None, backend=default_backend()
)
pkb = p_key.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
return pkb

如何测试p_key.private_bytes已调用一次?

这是我迄今为止写的单元测试:

@patch("builtins.open", new_callable=mock_open)
def test_get_private_key(mock_open, mocker, key_path="my/path"):
mocker.patch.object(subject, "serialization")
subject._get_private_key(key_path)
mock_open.assert_called_with(key_path, "rb")
subject.serialization.load_pem_private_key.assert_called_once()

不确定它是否对您有帮助,这是一种使用装饰器的基本方法:


# decorator for counting f calls
def fcounter(f):
def helper(*args,**kwargs):
helper.calls+=1
return f(*args,**kwargs)
helper.calls=0
helper.__name__=f.__name__
return helper
# afterwards you can wrap p_key.private_bytes
pkb = fcounter(p_key.private_bytes)
# and then call it and count the number of calls using calls attribute
pkb()
# get no of calls
pkb.calls

你也可以看看这里,也许你可以找到一些有用的东西:使用python mock计算方法调用的次数

最新更新