Python 在类外模拟方法

Python 在类外模拟方法,python,unit-testing,mocking,wsgi,assert,Python,Unit Testing,Mocking,Wsgi,Assert,我需要为凭证检查模块编写一个单元测试,如下所示。很抱歉,我无法复制准确的代码。。但我尽了最大努力简化了,作为一个例子。 我想修补methodA,使其返回False作为返回值,并测试MyClass以查看是否抛出错误。cred_check是文件名,MyClass是类名。methodA在MyClass之外,返回值checkedcredential为True或False def methodA(username, password): #credential check logic here..

我需要为凭证检查模块编写一个单元测试,如下所示。很抱歉,我无法复制准确的代码。。但我尽了最大努力简化了,作为一个例子。 我想修补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....
我想在unittest中编写的部分是返回http\U异常部分。我正在考虑通过修补methodA来返回False。设置返回值后,编写unittest以使其按预期工作的正确方法是什么

 import unittest
 import mock
 import cred_check import MyClass

class TestMyClass(unittest.Testcase):
    @mock.patch('cred_check.methodA',return_value=False)
    @mock.patch.dict(req.retrieve,{'constants.USER':'user','constants.PW':'pw'})
    def test_negative_cred(self, mock_A,):
        obj=MyClass(#you need to send some object here)
        obj.methodB()

它应该是这样工作的。

在unittest中要测试
http\u异常
返回案例,您需要做的是:

  • patch
    cred\u check.methodA
    返回
    False
  • 实例化
    MyClass()
    对象(也可以使用
    Mock
  • 调用
    MyClass.methodB()
    可以将
    MagicMock
    作为请求传递,并检查返回值是否是
    http\u异常的实例
  • 您的测试将成为:

    @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
    

    为什么要打补丁
    methodB
    。。正确的。谢谢,我去掉了methodB补丁。仍然不确定我应该怎么做。@killahjc你还对这个问题感兴趣吗?@Micheled'Amico对不起,我接受了你的回答。非常感谢,谢谢。我编辑了我的原始问题,以包含我真正想问的问题。。methodB中的用户名和密码是请求方法。我想这些也需要修补。。正确的方法是什么?@killahjc您也可以修补
    请求模块的retrieve
    @mock.patch.dict(req.retrieve,{'constants.USER':'USER','constants.PW':'PW})
    没有意义。也许你需要一个模拟,而不是修补一个不存在的对象。@Micheled'Amico他也想模拟
    请求
    ,所以我也包括了这一点…但他没有显示该对象是如何来的是的,但是
    请求
    在加载模块时不存在,所以在应用修补程序时。即使存在引用,也可能和测试运行时得到的对象不同。请求可以是一个模拟,您可以在测试中创建它:您不需要任何补丁来获得它,因为它是一个
    methodB
    参数。