python - python:如何模拟辅助方法?
问题描述
你能帮我弄清楚我做错了什么吗?我对 python lambdas 进行了以下单元测试
class Tests(unittest.TestCase):
def setUp(self):
//some setup
@mock.patch('functions.tested_class.requests.get')
@mock.patch('functions.helper_class.get_auth_token')
def test_tested_class(self, mock_auth, mock_get):
mock_get.side_effect = [self.mock_response]
mock_auth.return_value = "some id token"
response = get_xml(self.event, None)
self.assertEqual(response['statusCode'], 200)
问题是,当我运行此代码时,出现以下错误get_auth_token
:
Invalid URL '': No schema supplied. Perhaps you meant http://?
我调试了它,它看起来不像我正确修补它。授权帮助文件与测试类位于同一文件夹“functions”中。
编辑:在tested_class中我像这样导入get_auth_token:
from functions import helper_class
from functions.helper_class import get_auth_token
...
def get_xml(event, context):
...
response_token = get_auth_token()
改成这个后,它开始正常工作
import functions.helper_class
...
def get_xml(event, context):
...
response_token = functions.helper_class.get_auth_token()
我仍然不完全明白为什么
解决方案
- 在您的第一个场景中
在tested_class.py
,get_auth_token
被导入
from functions.helper_class import get_auth_token
补丁应该正好是get_auth_token
attested_class
@mock.patch('functions.tested_class.get_auth_token')
- 第二种情况
具有以下用法
response_token = functions.helper_class.get_auth_token()
修补的唯一方法是这个
@mock.patch('functions.helper_class.get_auth_token')
- 选择
像这样导入tested_class
from functions import helper_class
helper_class.get_auth_token()
补丁可能是这样的:
@mock.patch('functions.tested_class.helper_class.get_auth_token')
推荐阅读
- json - JSON PATCH / Remove:如何从对象中删除特定值?
- spring-boot - Openid-connect 或 SAML 2.0
- ios - 如何将图像导出到 Google 课堂?
- xamarin.forms - 是否可以将 RadioButton 保留为可扩展控件 Xamarin 表单 4.6 的标题
- sql - 如何更新 PostgreSQL 中的 JSON 字段?
- c - C - 获取字符串的所有排列并为每个重复的字符分配一个数字
- python - 您如何使用 object_ids 列表查询 pymongo db?
- azure-functions - 在 C# Azure 函数 (v2) 中使用来自 Azure Key Vault 的不可导出客户端证书
- arduino - ESP32 Arduino BLE DeepSleep
- cypress - cy.visit() 失败,因为在单个测试用例中尝试访问第二个唯一域/位置/url