问题描述
我需要为凭证检查模块编写一个单元测试,如下所示.抱歉,我无法复制确切的代码..但是,我尽力简化一下示例.我想修补methodA,以便它返回False作为返回值,并测试MyClass以查看是否抛出错误. cred_check是文件名,MyClass是类名. methodA在MyClass之外,返回值checkedcredential为True或False.
I need to write a unit test for credential checking module looks something like below. I apologize I cannot copy the exact code.. but I tried my best to simplify as an example.I want to patch methodA so it returns False as a return value and test MyClass to see if it is throwing error. cred_check is the file name and MyClass is the class name. methodA is outside of MyClass and the return value checkedcredential is either True or 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...
我目前拥有的单元测试看起来像...
The unit test I currently have looks like...
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....
我要在单元测试中编写的部分是返回http_exception 部分.我正在考虑通过修补methodA来返回False来做到这一点.设置返回值后,编写单元测试以使其按预期工作的正确方法是什么?
The part I want to write in my unittest is return http_exception part. I am thinking of doing it by patching methodA to return False. After setting the return value, what would be the proper way of writing the unittest so it works as intended?
推荐答案
在单元测试中,要测试http_exception
返回情况需要做的是:
What you need to do in your unittest to test http_exception
return case is:
-
patch
cred_check.methodA
返回False
- 实例化
MyClass()
对象(也可以使用Mock
代替) - 调用
MyClass.methodB()
,您可以在其中传递MagicMock
作为请求,并检查返回值是否为http_exception
的实例
patch
cred_check.methodA
to returnFalse
- Instantiate a
MyClass()
object (you can also use aMock
instead) - Call
MyClass.methodB()
where you can pass aMagicMock
as request and check if the return value is an instance ofhttp_exception
您的考试成为:
@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
这篇关于在类外模拟方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!