requests-mock - 模拟请求执行实际请求调用,而不是模拟
问题描述
我正在使用 requests-mock 在我的 unittest 代码中模拟一个 get 请求,但是当我在测试期间运行代码时,它仍然会尝试访问实际的 URL,而不是返回模拟的数据。
这是我的代码:
try:
response = requests.get(api_url, auth=requests.auth.HTTPBasicAuth(username, password))
response.raise_for_status()
except requests.ConnectionError as e:
raise dke.CLIError(f"Could not connect to Artifactory server to get NPM auth information: {str(e)}")
这是我的测试代码
class MyTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
m = requests_mock.Mocker()
m.get('https://artifactory.apps.openshift-sandbox.example.com/artifactory/api/npm/auth',
text=("_auth = base64string==\n"
"always-auth = true\n"
"email = shareduser@fake.com"))
我的api_url
代码中的 与我传递给的 URL 匹配m.get()
。但是,当我运行测试时,我没有得到“text”的值,而是得到了401 Client Error: Unauthorized
一个来自服务器的响应,指示“Bad credentials”,它告诉我它实际上试图联系服务器而不是返回文本我曾要求在模拟。
我迷路了。据我所知,我完全按照文档指示使用它。有任何想法吗?
解决方案
所以,看来你不能那样使用 request_mocker 。它必须是装饰器或上下文管理器。
推荐阅读
- python - Cmake 在 Windows 10 上找不到 python37.dll,但文件路径在缓存文件中。(pybind11)
- node.js - Socket.io + NodeJS IONIC CORS 问题
- node.js - 异步函数内部的异步错误
- electron - 未捕获的错误:无法在电子应用程序上调用远程函数“capturePage”
- python - 如何增加小应用程序的 Heroku Slug 大小?
- node.js - 在 NodeJS 中遍历 JSON 文件
- javascript - React.js onChange标签挂起
- mongodb - 如何在mongodb重复错误中检索错误对象
- c# - Blazor 中的 js 互操作的静态扩展如何工作?
- javascript - 如何使用 JavaScript for 循环将 ASCII 代码转换为单词