Jam*_* C. 10 python unit-testing assert wsgi mocking
我需要为凭据检查模块编写一个单元测试,如下所示。很抱歉我无法复制确切的代码..但我尽力简化作为示例。\n我想修补 methodA,使其返回 False 作为返回值,并测试 MyClass 以查看它是否抛出错误。cred_check 是文件名,MyClass 是类名。methodA 位于 MyClass 之外,并且返回值 checkcredential 为 True 或 False。
\n\ndef methodA(username, password):\n #credential check logic here...\n #checkedcredential = True/False depending on the username+password combination\n return checkedcredential\n\nclass MyClass(wsgi.Middleware):\n def methodB(self, req): \n username = req.retrieve[constants.USER]\n password = req.retrieve[constants.PW]\n if methodA(username,password):\n print(\xe2\x80\x9cpassed\xe2\x80\x9d)\n else:\n print(\xe2\x80\x9cNot passed\xe2\x80\x9d)\n return http_exception...\nRun Code Online (Sandbox Code Playgroud)\n\n我目前的单元测试看起来像......
\n\nimport unittest\nimport mock\nimport cred_check import MyClass\n\nclass TestMyClass(unittest.Testcase):\n @mock.patch('cred_check')\n def test_negative_cred(self, mock_A):\n mock_A.return_value = False\n #not sure what to do from this point....\nRun Code Online (Sandbox Code Playgroud)\n\n我想在单元测试中编写的部分是return http_exception部分。我正在考虑通过修补 methodA 以返回 False 来做到这一点。设置返回值后,编写单元测试以使其按预期工作的正确方法是什么?
\n您需要在单元测试中执行以下操作来测试http_exception返回情况:
patch cred_check.methodA回来FalseMyClass()对象(也可以使用 aMock代替)MyClass.methodB()您可以传递MagicMockas 请求并检查返回值是否是实例的实例http_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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14118 次 |
| 最近记录: |