You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python调用GitHub API获取分支时单元测试报TypeError问题

解决单元测试中json() missing 1 required positional argument: 'self'错误

错误根源

你在单元测试里把Response类直接作为requests.get的返回值,而不是创建一个Response实例。json()是Response类的实例方法,必须通过实例调用,直接用类调用就会报缺少self参数的错误。另外测试里的assert_called_with参数也不对,原代码里requests.get接收的是URL和headers,不是三个"test"。

还有实现代码里的两个小问题:

  • 列表推导式里用response作为循环变量,覆盖了外层的response对象,会导致后续代码逻辑混乱
  • git_base参数没被用到,硬编码了GitHub API地址,不符合参数设计的意图

修复步骤

1. 修正单元测试代码

需要创建模拟的Response实例,设置json()方法的返回值,同时修正assert_called_with的参数:

from unittest.mock import patch, Mock
import requests
from your_module import GithubService  # 替换成你的实际模块名

class TestGithubService:
    @patch.object(requests, "get")
    def test_get_branches(self, mock_get):
        # 创建模拟的Response实例,模拟分页返回数据
        mock_page1 = Mock()
        mock_page1.json.return_value = [{"name": "main"}, {"name": "develop"}]
        
        mock_page2 = Mock()
        mock_page2.json.return_value = []
        
        mock_get.side_effect = [mock_page1, mock_page2]

        # 调用待测试方法
        branches = GithubService.get_branches("https://api.github.com", "test", "test")

        # 验证调用逻辑
        assert mock_get.call_count == 2
        # 验证第一次请求的URL和headers
        mock_get.assert_any_call(
            "https://api.github.com/repos/test/test/branches/?per_page=100&page=1",
            headers=HEADERS  # 确保HEADERS在测试环境中可访问
        )
        # 验证返回结果正确性
        assert branches == ["main", "develop"]

2. 修正实现代码

解决变量名冲突和未使用参数的问题:

import requests

HEADERS = {"Authorization": "token your-auth-token"}  # 替换为你的实际请求头

class GithubService:
    @staticmethod
    def get_branches(git_base, org, repo):
        # 使用传入的git_base参数拼接API地址,支持不同GitHub实例
        github_repo_url = f"{git_base}/repos/{org}/{repo}"
        collected_all_branches = False
        page = 1
        github_branches = []
        
        while not collected_all_branches:
            response = requests.get(
                f"{github_repo_url}/branches/?per_page=100&page={page}",
                headers=HEADERS
            )
            # 先解析响应数据,避免变量名覆盖
            branch_data = response.json()
            if len(branch_data) == 0:
                collected_all_branches = True
            else:
                # 用branch作为循环变量,避免覆盖外层的response对象
                github_branches.extend([branch["name"] for branch in branch_data])
            page += 1
        
        return github_branches

关键说明

  • 模拟Response时,必须用Mock创建实例,并给json()方法绑定返回值,不能直接返回Response类
  • 循环变量要避开外层的response变量,防止变量名覆盖引发逻辑错误
  • 利用传入的git_base参数,让代码适配不同的GitHub环境(比如企业版GitHub)

内容的提问来源于stack exchange,提问作者user19251203

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 10:48:22