Skip to main content
 首页 » 编程设计

python之在类之外模拟方法

2025年05月04日9cloudgamer

我需要为凭证检查模块编写单元测试,如下所示。很抱歉,我无法复制确切的代码。但我已尽力简化示例。 我想修补 methodA,以便它返回 False 作为返回值并测试 MyClass 以查看它是否抛出错误。 cred_check 是文件名,MyClass 是类名。 methodA 在 MyClass 之外,返回值 checkedcredential 为 True 或 False。

def methodA(username, password): 
    #credential check logic here... 
    #checkedcredential = True/False depending on the username+password combination 
    return checkedcredential 
 
class MyClass(wsgi.Middleware): 
    def methodB(self, req):  
        username = req.retrieve[constants.USER] 
        password = req.retrieve[constants.PW] 
         if methodA(username,password): 
            print(“passed”) 
        else: 
            print(“Not passed”) 
            return http_exception... 

我目前的单元测试看起来像...

import unittest 
import mock 
import cred_check import MyClass 
 
class TestMyClass(unittest.Testcase): 
    @mock.patch('cred_check') 
    def test_negative_cred(self, mock_A): 
        mock_A.return_value = False 
        #not sure what to do from this point.... 

我想在单元测试中写的部分是 return http_exception 部分。我正在考虑通过修补 methodA 来返回 False 来做到这一点。设置返回值后,编写单元测试以使其按预期工作的正确方法是什么?

请您参考如下方法:

你需要在你的单元测试中做些什么来测试 http_exception 返回情况是:

  1. 补丁 cred_check.methodA 返回False
  2. 实例化一个 MyClass() 对象(您也可以使用 Mock 代替)
  3. 调用 MyClass.methodB(),您可以在其中传递一个 MagicMock 作为请求,并检查返回值是否是 http_exception 的一个实例/li>

你的测试变成:

@mock.patch('cred_check.methodA', return_value=False, autospec=True) 
def test_negative_cred(self, mock_A): 
    obj = MyClass() 
    #if obj is a Mock object use MyClass.methodB(obj, MagicMock()) instead 
    response = obj.methodB(MagicMock())  
    self.assertIsInstance(response, http_exception) 
    #... and anything else you want to test on your response in that case