我想使用 pytest 测试以下函数:
def validate_account(number):
try:
number = int(number)
except:
raise ValueError("Please enter a valid account number")
if int(number) not in accounts_dict:
raise Exception("Pleaseeee enter a valid account number.")
return number
accounts_dict
稍后添加项目。对于使用 pytest 进行单元测试,我如何模仿这个字典来测试数字是否在字典中?
截至目前,
accounts_dict
为空。而且,当我尝试断言 validate_account("1") == 1 时,它会抛出“Pleaseeee”异常(不在accounts_dict字典中)。我用谷歌搜索并尝试了一些不同的选项,例如accounts_dict = Mock(return_value =n)
,accounts_dict.get('1') != None
等,但它们没有帮助。非常感谢您的帮助。
如果字典是一个参数(它应该),你可以这样做
def test_validate_account__valid():
assert validate_account("1", {1:True}) == 1
def test_validate_account__invalid():
with pytest.raises(Exception):
validate_account("1", {2:True})