unittest 类 init 模拟异常引发

问题描述 投票:0回答:1
#!/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 ,但我找不到正确的补丁。

python unit-testing patch
1个回答
0
投票

一种方法是使用抑制

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)

演示:https://ideone.com/TEpHsF

© www.soinside.com 2019 - 2024. All rights reserved.