如何在 Python 中的 class 中模拟 属性
How to mock a property inside a class in Python
这是我的第一个文件 user.py
from account import Account
class User:
def __init__(self, id):
self.id = id
self._account = None
@property
def account(self):
if not self._account:
self._account = Account(self.id)
return self._account
@property
def has_discount(self)
return self.account.discount_id > 0
我有第二个文件 account.py
class Account:
def __init__(self, user_id):
# some process to load DB data
self.account = load_account(user_id)
# do something after this to initialize account properties like discount, etc
@property
def discount_id(self):
return self.discount_id
我的目标是测试user.py。我想做的一件事是为 'has_discount' 属性 装饰器模拟 user.py 中的 Account 对象。我想测试 has_discount 将 return 0 或任何其他数字的不同场景。
我如何使用可以将用户 class 中的帐户对象模拟为 return 自定义值的补丁来执行此操作,以便我可以尝试不同的测试?
因为 user
模块将 Account
导入到它自己的命名空间中 patching 必须在那里完成,而不是 account
模块。换句话说,您必须暂时更改 user
模块中的名称 Account
所指的内容:
from user import User
from unittest.mock import patch
with patch('user.Account') as MockAccount:
MockAccount.return_value.discount_id = 1
u = User(1)
print(u.has_discount)
# True
with patch('user.Account') as MockAccount:
MockAccount.return_value.discount_id = 0
u = User(1)
print(u.has_discount)
# False
I want to test different scenarios where has_discount will return either 0 or any other number.
在其当前实施中,User.has_discount
将始终 return True
或 False
。您是说 Account.discount_id
吗?
这是我的第一个文件 user.py
from account import Account
class User:
def __init__(self, id):
self.id = id
self._account = None
@property
def account(self):
if not self._account:
self._account = Account(self.id)
return self._account
@property
def has_discount(self)
return self.account.discount_id > 0
我有第二个文件 account.py
class Account:
def __init__(self, user_id):
# some process to load DB data
self.account = load_account(user_id)
# do something after this to initialize account properties like discount, etc
@property
def discount_id(self):
return self.discount_id
我的目标是测试user.py。我想做的一件事是为 'has_discount' 属性 装饰器模拟 user.py 中的 Account 对象。我想测试 has_discount 将 return 0 或任何其他数字的不同场景。
我如何使用可以将用户 class 中的帐户对象模拟为 return 自定义值的补丁来执行此操作,以便我可以尝试不同的测试?
因为 user
模块将 Account
导入到它自己的命名空间中 patching 必须在那里完成,而不是 account
模块。换句话说,您必须暂时更改 user
模块中的名称 Account
所指的内容:
from user import User
from unittest.mock import patch
with patch('user.Account') as MockAccount:
MockAccount.return_value.discount_id = 1
u = User(1)
print(u.has_discount)
# True
with patch('user.Account') as MockAccount:
MockAccount.return_value.discount_id = 0
u = User(1)
print(u.has_discount)
# False
I want to test different scenarios where has_discount will return either 0 or any other number.
在其当前实施中,User.has_discount
将始终 return True
或 False
。您是说 Account.discount_id
吗?