import json import requests from .fetch_github_info import AUTHENTICATED_USER_ENDPOINT, fetch_github_info def test_fetch_github_info(monkeypatch): # 定义一个模拟的 HTTP 响应类 class FakeResponse: def __init__(self, content) -> None: assert isinstance(content, (bytes, str)) self.content = content def json(self): return json.loads(self.content) # 定义模拟的响应函数,用于替换 requests.get 方法 def mock_response(*args, **kwargs): # 断言确保请求的 URL 正确 assert args[0] == AUTHENTICATED_USER_ENDPOINT # 断言确保请求头中包含 Authorization,并且以 "token " 开头 assert "Authorization" in kwargs["headers"] assert kwargs["headers"]["Authorization"].startswith("token ") # 断言确保请求头中包含 Accept assert "Accept" in kwargs["headers"] # 返回模拟的响应对象,其中的 content 是包含用户信息的 JSON 字符串 return FakeResponse(b'{"login":"test","id":1}') # 使用 monkeypatch 替换 requests.get 方法,使其返回模拟的响应 monkeypatch.setattr(requests, "get", mock_response) # 调用被测试的函数,传入模拟的 token,获取结果 result = fetch_github_info("token") # 断言确保返回的用户信息与预期相符 assert result["login"] == "test" assert result["id"] == 1
标签:info,content,Github,self,assert,获取,github,测试,kwargs From: https://www.cnblogs.com/mlhelloworld/p/18000890