#!/usr/bin/env python3
import unittest
from unittest.mock import patch
class User(object):
def __init__(self):
self.__name = None
self.__authorised_users = ["me", "you"]
local_input = input("please provide your windows 8 character lower case login: ")
if local_input not in self.__authorised_users:
raise ValueError("you have no permission to run this app")
else:
self.__name = local_input
class TestUser(unittest.TestCase):
def testUserClassFound(self):
self.assertNotIsInstance(ModuleNotFoundError, User)
@patch('builtins.input', lambda *args:"y")
def testUserClassInit(self): # just check if user class has __name set to none
local_object = User()
self.assertEqual(local_object._User__name, None)
if __name__ == "__main__":
unittest.main()
我想在第二个测试中,确保在创建类对象时,测试人员检查该类是否具有属性 __name 并设置为 None。 我需要从类 init 修补 raise ValueError ,但我找不到正确的补丁。
一种方法是使用抑制
User.__init__
的包装器来修补 ValueError
:
def ignore(func, exception):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except exception:
pass
return wrapper
class TestUser(unittest.TestCase):
@patch('builtins.input', lambda *args:"y")
@patch.object(User, '__init__', ignore(User.__init__, ValueError))
def testUserClassInit(self):
local_object = User()
self.assertEqual(local_object._User__name, None)