🐫 CAMEL: The first and the best multi-agent framework. Finding the Scaling Law of Agents. https://www.camel-ai.org
Python agentai-societiesartificial-intelligencecommunicative-aicooperative-aideep-learninglarge-language-modelsmulti-agent-systemsnatural-language-processing
feat: add github funcs with github toolkit (#1099)
Ray01e5803d27fe
diff --git a/camel/toolkits/github_toolkit.py b/camel/toolkits/github_toolkit.pyindex 09443a3a7..02481d8d0 100644--- a/camel/toolkits/github_toolkit.py+++ b/camel/toolkits/github_toolkit.py@@ -12,88 +12,15 @@# limitations under the License.# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========+import loggingimport os-from datetime import datetime, timedelta-from typing import List, Optional--from pydantic import BaseModel+from typing import Dict, List, Literal, Optional, Unionfrom camel.toolkits import FunctionToolfrom camel.toolkits.base import BaseToolkitfrom camel.utils import dependencies_required--class GithubIssue(BaseModel):- r"""Represents a GitHub issue.-- Attributes:- title (str): The title of the issue.- body (str): The body/content of the issue.- number (int): The issue number.- file_path (str): The path of the file associated with the issue.- file_content (str): The content of the file associated with the issue.- """-- title: str- body: str- number: int- file_path: str- file_content: str-- def __str__(self) -> str:- r"""Returns a string representation of the issue.-- Returns:- str: A string containing the title, body, number, file path, and- file content of the issue.- """- return (- f"Title: {self.title}\n"- f"Body: {self.body}\n"- f"Number: {self.number}\n"- f"File Path: {self.file_path}\n"- f"File Content: {self.file_content}"- )---class GithubPullRequestDiff(BaseModel):- r"""Represents a single diff of a pull request on Github.-- Attributes:- filename (str): The name of the file that was changed.- patch (str): The diff patch for the file.- """-- filename: str- patch: str-- def __str__(self) -> str:- r"""Returns a string representation of this diff."""- return f"Filename: {self.filename}\nPatch: {self.patch}"---class GithubPullRequest(BaseModel):- r"""Represents a pull request on Github.-- Attributes:- title (str): The title of the GitHub pull request.- body (str): The body/content of the GitHub pull request.- diffs (List[GithubPullRequestDiff]): A list of diffs for the pull- request.- """-- title: str- body: str- diffs: List[GithubPullRequestDiff]-- def __str__(self) -> str:- r"""Returns a string representation of the pull request."""- diff_summaries = '\n'.join(str(diff) for diff in self.diffs)- return (- f"Title: {self.title}\n"- f"Body: {self.body}\n"- f"Diffs: {diff_summaries}\n"- )+logger = logging.getLogger(__name__)class GithubToolkit(BaseToolkit):@@ -122,29 +49,14 @@ class GithubToolkit(BaseToolkit):with GitHub. If not provided, it will be obtained using the`get_github_access_token` method."""+ from github import Auth, Github+if access_token is None:access_token = self.get_github_access_token()- from github import Auth, Github-self.github = Github(auth=Auth.Token(access_token))self.repo = self.github.get_repo(repo_name)- def get_tools(self) -> List[FunctionTool]:- r"""Returns a list of FunctionTool objects representing the- functions in the toolkit.-- Returns:- List[FunctionTool]: A list of FunctionTool objects- representing the functions in the toolkit.- """- return [- FunctionTool(self.retrieve_issue_list),- FunctionTool(self.retrieve_issue),- FunctionTool(self.create_pull_request),- FunctionTool(self.retrieve_pull_requests),- ]-def get_github_access_token(self) -> str:r"""Retrieve the GitHub access token from environment variables.@@ -165,87 +77,6 @@ class GithubToolkit(BaseToolkit):)return GITHUB_ACCESS_TOKEN- def retrieve_issue_list(self) -> List[GithubIssue]:- r"""Retrieve a list of open issues from the repository.-- Returns:- A list of GithubIssue objects representing the open issues.- """- issues = self.repo.get_issues(state='open')- return [- GithubIssue(- title=issue.title,- body=issue.body,- number=issue.number,- file_path=issue.labels[- 0- ].name, # we require file path to be the first label in the PR- file_content=self.retrieve_file_content(issue.labels[0].name),- )- for issue in issues- if not issue.pull_request- ]-- def retrieve_issue(self, issue_number: int) -> Optional[str]:- r"""Retrieves an issue from a GitHub repository.-- This function retrieves an issue from a specified repository using the- issue number.-- Args:- issue_number (int): The number of the issue to retrieve.-- Returns:- str: A formatted report of the retrieved issue.- """- issues = self.retrieve_issue_list()- for issue in issues:- if issue.number == issue_number:- return str(issue)- return None-- def retrieve_pull_requests(- self, days: int, state: str, max_prs: int- ) -> List[str]:- r"""Retrieves a summary of merged pull requests from the repository.- The summary will be provided for the last specified number of days.-- Args:- days (int): The number of days to retrieve merged pull requests- for.- state (str): A specific state of PRs to retrieve. Can be open or- closed.- max_prs (int): The maximum number of PRs to retrieve.-- Returns:- List[str]: A list of merged pull request summaries.- """- pull_requests = self.repo.get_pulls(state=state)- merged_prs = []- earliest_date: datetime = datetime.utcnow() - timedelta(days=days)-- for pr in pull_requests[:max_prs]:- if (- pr.merged- and pr.merged_at is not None- and pr.merged_at.timestamp() > earliest_date.timestamp()- ):- pr_details = GithubPullRequest(- title=pr.title, body=pr.body, diffs=[]- )-- # Get files changed in the PR- files = pr.get_files()-- for file in files:- diff = GithubPullRequestDiff(- filename=file.filename, patch=file.patch- )- pr_details.diffs.append(diff)-- merged_prs.append(str(pr_details))- return merged_prs-def create_pull_request(self,file_path: str,@@ -280,6 +111,7 @@ class GithubToolkit(BaseToolkit):)file = self.repo.get_contents(file_path)+from github.ContentFile import ContentFileif isinstance(file, ContentFile):@@ -300,6 +132,155 @@ class GithubToolkit(BaseToolkit):else:raise ValueError("PRs with multiple files aren't supported yet.")+ def get_issue_list(+ self, state: Literal["open", "closed", "all"] = "all"+ ) -> List[Dict[str, object]]:+ r"""Retrieves all issues from the GitHub repository.++ Args:+ state (Literal["open", "closed", "all"]): The state of pull+ requests to retrieve. (default::obj: `all`)+ Options are:+ - "open": Retrieve only open pull requests.+ - "closed": Retrieve only closed pull requests.+ - "all": Retrieve all pull requests, regardless of state.++ Returns:+ List[Dict[str, object]]: A list of dictionaries where each+ dictionary contains the issue number and title.+ """+ issues_info = []+ issues = self.repo.get_issues(state=state)++ for issue in issues:+ issues_info.append({"number": issue.number, "title": issue.title})++ return issues_info++ def get_issue_content(self, issue_number: int) -> str:+ r"""Retrieves the content of a specific issue by its number.++ Args:+ issue_number (int): The number of the issue to retrieve.++ Returns:+ str: issues content details.+ """+ try:+ issue = self.repo.get_issue(number=issue_number)+ return issue.body+ except Exception as e:+ return f"can't get Issue number {issue_number}: {e!s}"++ def get_pull_request_list(+ self, state: Literal["open", "closed", "all"] = "all"+ ) -> List[Dict[str, object]]:+ r"""Retrieves all pull requests from the GitHub repository.++ Args:+ state (Literal["open", "closed", "all"]): The state of pull+ requests to retrieve. (default::obj: `all`)+ Options are:+ - "open": Retrieve only open pull requests.+ - "closed": Retrieve only closed pull requests.+ - "all": Retrieve all pull requests, regardless of state.++ Returns:+ list: A list of dictionaries where each dictionary contains the+ pull request number and title.+ """+ pull_requests_info = []+ pull_requests = self.repo.get_pulls(state=state)++ for pr in pull_requests:+ pull_requests_info.append({"number": pr.number, "title": pr.title})++ return pull_requests_info++ def get_pull_request_code(self, pr_number: int) -> List[Dict[str, str]]:+ r"""Retrieves the code changes of a specific pull request.++ Args:+ pr_number (int): The number of the pull request to retrieve.++ Returns:+ List[Dict[str, str]]: A list of dictionaries where each dictionary+ contains the file name and the corresponding code changes+ (patch).+ """+ # Retrieve the specific pull request+ pr = self.repo.get_pull(number=pr_number)++ # Collect the file changes from the pull request+ files_changed = []+ # Returns the files and their changes in the pull request+ files = pr.get_files()+ for file in files:+ files_changed.append(+ {+ "filename": file.filename,+ "patch": file.patch, # The code diff or changes+ }+ )++ return files_changed++ def get_pull_request_comments(+ self, pr_number: int+ ) -> List[Dict[str, str]]:+ r"""Retrieves the comments from a specific pull request.++ Args:+ pr_number (int): The number of the pull request to retrieve.++ Returns:+ List[Dict[str, str]]: A list of dictionaries where each dictionary+ contains the user ID and the comment body.+ """+ # Retrieve the specific pull request+ pr = self.repo.get_pull(number=pr_number)++ # Collect the comments from the pull request+ comments = []+ # Returns all the comments in the pull request+ for comment in pr.get_comments():+ comments.append({"user": comment.user.login, "body": comment.body})++ return comments++ def get_all_file_paths(self, path: str = "") -> List[str]:+ r"""Recursively retrieves all file paths in the GitHub repository.++ Args:+ path (str): The repository path to start the traversal from.+ empty string means starts from the root directory.+ (default::obj: `""`)++ Returns:+ List[str]: A list of file paths within the specified directory+ structure.+ """+ from github.ContentFile import ContentFile++ files: List[str] = []++ # Retrieves all contents of the current directory+ contents: Union[List[ContentFile], ContentFile] = (+ self.repo.get_contents(path)+ )++ if isinstance(contents, ContentFile):+ files.append(contents.path)+ else:+ for content in contents:+ if content.type == "dir":+ # If it's a directory, recursively retrieve its file paths+ files.extend(self.get_all_file_paths(content.path))+ else:+ # If it's a file, add its path to the list+ files.append(content.path)+ return files+def retrieve_file_content(self, file_path: str) -> str:r"""Retrieves the content of a file from the GitHub repository.@@ -309,11 +290,29 @@ class GithubToolkit(BaseToolkit):Returns:str: The decoded content of the file."""- file_content = self.repo.get_contents(file_path)-from github.ContentFile import ContentFile+ file_content = self.repo.get_contents(file_path)if isinstance(file_content, ContentFile):return file_content.decoded_content.decode()else:raise ValueError("PRs with multiple files aren't supported yet.")++ def get_tools(self) -> List[FunctionTool]:+ r"""Returns a list of FunctionTool objects representing the functions+ in the toolkit.++ Returns:+ List[FunctionTool]: A list of FunctionTool objects representing+ the functions in the toolkit.+ """+ return [+ FunctionTool(self.create_pull_request),+ FunctionTool(self.get_issue_list),+ FunctionTool(self.get_issue_content),+ FunctionTool(self.get_pull_request_list),+ FunctionTool(self.get_pull_request_code),+ FunctionTool(self.get_pull_request_comments),+ FunctionTool(self.get_all_file_paths),+ FunctionTool(self.retrieve_file_content),+ ]diff --git a/examples/toolkits/github_toolkit.py b/examples/toolkits/github_toolkit.pyindex 9c1d0965e..2c6c2132b 100644--- a/examples/toolkits/github_toolkit.py+++ b/examples/toolkits/github_toolkit.py@@ -11,140 +11,77 @@# See the License for the specific language governing permissions and# limitations under the License.# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========-import argparse-from colorama import Fore--from camel.agents import ChatAgent-from camel.configs import ChatGPTConfig-from camel.messages import BaseMessage-from camel.models import ModelFactory-from camel.toolkits import FunctionTool, GithubToolkit-from camel.types import ModelPlatformType, ModelType-from camel.utils import print_text_animated---def write_weekly_pr_summary(repo_name, model=None):- prompt = """- You need to write a summary of the pull requests that were merged in the- last week.- You can use the provided github function retrieve_pull_requests to- retrieve the list of pull requests that were merged in the last week.- The maximum amount of PRs to analyze is 3.- You have to pass the number of days as the first parameter to- retrieve_pull_requests and state='closed' as the second parameter.- The function will return a list of pull requests with the following- properties: title, body, and diffs.- Diffs is a list of dictionaries with the following properties: filename,- diff.- You will have to look closely at each diff to understand the changes that- were made in each pull request.- Output a twitter post that describes recent changes in the project and- thanks the contributors.-- Here is an example of a summary for one pull request:- 📢 We've improved function calling in the 🐪 CAMEL-AI framework!- This update enhances the handling of various docstring styles and supports- enum types, ensuring more accurate and reliable function calls.- Thanks to our contributor Jiahui Zhang for making this possible.- """- print(Fore.YELLOW + f"Final prompt:\n{prompt}\n")-- toolkit = GithubToolkit(repo_name=repo_name)- assistant_sys_msg = BaseMessage.make_assistant_message(- role_name="Marketing Manager",- content=f"""- You are an experienced marketing manager responsible for posting- weekly updates about the status- of an open source project {repo_name} on the project's blog.- """,- )- assistant_model_config_dict = ChatGPTConfig(temperature=0.0).as_dict()-- assistant_model = ModelFactory.create(- model_platform=ModelPlatformType.DEFAULT,- model_type=ModelType.DEFAULT,- model_config_dict=assistant_model_config_dict,- )-- agent = ChatAgent(- assistant_sys_msg,- model=assistant_model,- tools=[FunctionTool(toolkit.retrieve_pull_requests)],- )- agent.reset()-- user_msg = BaseMessage.make_user_message(role_name="User", content=prompt)- assistant_response = agent.step(user_msg)-- if len(assistant_response.msgs) > 0:- print_text_animated(- Fore.GREEN + f"Agent response:\n{assistant_response.msg.content}\n"- )---def solve_issue(- repo_name,- issue_number,- model=None,-) -> None:- prompt = f"""- You need to solve the issue with number: {issue_number}- For this you will have to use the provided github function to retrieve- that issue. You will get all the necessary parameters to later create a- pull request.-- When you have the issue, please follow the instruction and make the- necessary changes to the source code provided. Once you have made the- changes, you will need to use another provided github function to create a- pull request that updates the file on the provided file path in the- repository {repo_name}.- The new_content property of the function should be the corrected source- code.- Return response of this function as the output of this task.- """- print(Fore.YELLOW + f"Final prompt:\n{prompt}\n")-- toolkit = GithubToolkit(repo_name=repo_name)- assistant_sys_msg = BaseMessage.make_assistant_message(- role_name="Software Engineer",- content="""You are an experienced software engineer who- specializes on data structures and algorithms tasks.""",- )- assistant_model_config_dict = ChatGPTConfig(- temperature=0.0,- ).as_dict()-- model = ModelFactory.create(- model_platform=ModelPlatformType.DEFAULT,- model_type=ModelType.DEFAULT,- model_config_dict=assistant_model_config_dict,- )-- agent = ChatAgent(- assistant_sys_msg,- model=model,- tools=toolkit.get_tools(),- )- agent.reset()-- user_msg = BaseMessage.make_user_message(role_name="User", content=prompt)- assistant_response = agent.step(user_msg)-- if len(assistant_response.msgs) > 0:- print_text_animated(- Fore.GREEN + f"Agent response:\n{assistant_response.msg.content}\n"- )---def main(model=None) -> None:- parser = argparse.ArgumentParser(description='Enter repo name.')- parser.add_argument('repo_name', type=str, help='Name of the repository')- args = parser.parse_args()-- repo_name = args.repo_name- write_weekly_pr_summary(repo_name=repo_name, model=model)---if __name__ == "__main__":- main()+from camel.toolkits import GithubToolkit++gt = GithubToolkit(repo_name="camel-ai/camel")++# Retrieve a list of all file paths within the camel GitHub repository+paths = gt.get_all_file_paths()+print(paths)+'''+===============================================================================+['.container/.env.example', '.container/Dockerfile', '.container/README.md', '.+container/docker-compose.yaml', '.container/minimal_build/Dockerfile', '.+github/ISSUE_TEMPLATE/bug_report.yml', '.github/ISSUE_TEMPLATE/discussions.+yml', '.github/ISSUE_TEMPLATE/feature_request.yml', '.github/ISSUE_TEMPLATE/+questions.yml', '.github/PULL_REQUEST_TEMPLATE.md', '.github/actions/+camel_install/action.yml', '.github/workflows/build_package.yml', '.github/+workflows/documentation.yml', '.github/workflows/pre_commit.yml', '.github/+workflows/publish_release.yml', '.github/workflows/pytest_apps.yml', '.github/+workflows/pytest_package.yml', '.gitignore', '.pre-commit-config.yaml', '.+style.yapf', 'CONTRIBUTING.md', 'LICENSE', 'Makefile', 'README.md', 'apps/+agents/README.md', 'apps/agents/agents.py', 'apps/agents/test/test_agents.py',+'apps/agents/test/test_text_utils.py', 'apps/agents/text_utils.py', 'apps/+common/auto_zip.py', 'apps/common/test/test_archive_1.zip', 'apps/common/test/+test_auto_zip.py', 'apps/data_explorer/.gitignore', 'apps/data_explorer/README.+md', 'apps/data_explorer/data_explorer.py', 'apps/data_explorer/downloader.+py', 'apps/data_explorer/loader.py', 'apps/data_explorer/test/+test_data_explorer.py', 'apps/data_explorer/test/test_loader.py', 'apps/+dilemma/database_connection.py', 'apps/dilemma/dilemma.py', 'apps/dilemma/+requirements.txt', 'camel/__init__.py', 'camel/agents/__init__.py', 'camel/+agents/base.py', 'camel/agents/chat_agent.py', 'camel/agents/critic_agent.py',+'camel/agents/deductive_reasoner_agent.py',...+===============================================================================+'''++# Retrieve the content of a specific file in the repository+content = gt.retrieve_file_content("camel/agents/chat_agent.py")+print(content[:1000])+'''+===============================================================================+# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========+# Licensed under the Apache License, Version 2.0 (the “License”);+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an “AS IS” BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========+from __future__ import annotations++import json+import logging+import re+import uuid+from collections import defaultdict+from typing import (+ TYPE_CHECKING,+ Any,+ Dict,+ List,+ Optional,+ Tuple,+ Type,+ Union,+)++from openai.types.chat import ChatCompletionMessageToolCall+f+===============================================================================+'''diff --git a/test/toolkits/test_github_toolkit.py b/test/toolkits/test_github_toolkit.pyindex 714697aff..6bb6dcd7e 100644--- a/test/toolkits/test_github_toolkit.py+++ b/test/toolkits/test_github_toolkit.py@@ -12,18 +12,12 @@# limitations under the License.# =========== Copyright 2023 @ CAMEL-AI.org. All Rights Reserved. ===========-from datetime import datetimefrom unittest.mock import MagicMock, patchfrom github import Auth, Githubfrom github.ContentFile import ContentFile-from camel.toolkits.github_toolkit import (- GithubIssue,- GithubPullRequest,- GithubPullRequestDiff,- GithubToolkit,-)+from camel.toolkits.github_toolkit import GithubToolkit@patch.object(Github, '__init__', lambda self, *args, **kwargs: None)@@ -49,88 +43,6 @@ def test_get_tools(mock_get_repo):assert len(tools) > 0[email protected](Github, '__init__', lambda self, *args, **kwargs: None)[email protected](Github, 'get_repo', return_value=MagicMock())[email protected](Auth.Token, '__init__', lambda self, *args, **kwargs: None)-def test_retrieve_issue_list(monkeypatch):- # Call the constructor of the GithubToolkit class- github_toolkit = GithubToolkit("repo_name", "token")-- # Create a mock issue object- mock_issue = MagicMock()- mock_issue.number = 1- mock_issue.title = "Test Issue"- mock_issue.body = "This is a test issue"- mock_issue.pull_request = False-- mock_label = MagicMock()- mock_label.name = "path/to/file"- mock_issue.labels = [mock_label]-- # Mock the get_issues method of the mock_repo instance to return a list- # containing the mock issue object- github_toolkit.repo.get_issues.return_value = [mock_issue]- github_toolkit.retrieve_file_content = MagicMock(- return_value="This is the content of the file"- )-- # Call the retrieve_issue_list method- issue_list = github_toolkit.retrieve_issue_list()-- # Assert the returned issue list- expected_issue = GithubIssue(- title="Test Issue",- body="This is a test issue",- number=1,- file_path="path/to/file",- file_content="This is the content of the file",- )- assert issue_list == [- expected_issue- ], f"Expected {expected_issue}, but got {issue_list}"--[email protected](Github, '__init__', lambda self, *args, **kwargs: None)[email protected](Github, 'get_repo', return_value=MagicMock())[email protected](Auth.Token, '__init__', lambda self, *args, **kwargs: None)-def test_retrieve_issue(monkeypatch):- # Call the constructor of the GithubToolkit class- github_toolkit = GithubToolkit("repo_name", "token")-- # Create a mock issue object- mock_issue = MagicMock()- mock_issue.number = 1- mock_issue.title = "Test Issue"- mock_issue.body = "This is a test issue"- mock_issue.pull_request = False-- mock_label = MagicMock()- mock_label.name = "path/to/file"- mock_issue.labels = [mock_label]-- # Mock the get_issues method of the mock repo instance to return a list- # containing the mock issue object- github_toolkit.repo.get_issues.return_value = [mock_issue]- github_toolkit.retrieve_file_content = MagicMock(- return_value="This is the content of the file"- )-- # Call the retrieve_issue_list method- issue = github_toolkit.retrieve_issue(1)-- # Assert the returned issue list- expected_issue = GithubIssue(- title="Test Issue",- body="This is a test issue",- number=1,- file_path="path/to/file",- file_content="This is the content of the file",- )- assert issue == str(- expected_issue- ), f"Expected {expected_issue}, but got {issue}"--@patch.object(Github, 'get_repo', return_value=MagicMock())@patch.object(Auth.Token, '__init__', lambda self, *args, **kwargs: None)def test_create_pull_request(monkeypatch):@@ -173,78 +85,102 @@ def test_create_pull_request(monkeypatch):@patch.object(Github, 'get_repo', return_value=MagicMock())@patch.object(Auth.Token, '__init__', lambda self, *args, **kwargs: None)-def test_retrieve_pull_requests(monkeypatch):- # Call the constructor of the GithubToolkit class+def test_get_all_issues(monkeypatch):+ github_toolkit = GithubToolkit("repo_name", "token")+ mock_issue = MagicMock()+ mock_issue.number = 1+ mock_issue.title = "Test Issue"+ github_toolkit.repo.get_issues.return_value = [mock_issue]++ issues = github_toolkit.get_issue_list()++ expected_issues = [{"number": 1, "title": "Test Issue"}]+ assert (+ issues == expected_issues+ ), f"Expected {expected_issues}, but got {issues}"++[email protected](Github, 'get_repo', return_value=MagicMock())[email protected](Auth.Token, '__init__', lambda self, *args, **kwargs: None)+def test_get_issue_content(monkeypatch):github_toolkit = GithubToolkit("repo_name", "token")+ mock_issue = MagicMock()+ mock_issue.body = "Issue content"+ github_toolkit.repo.get_issue.return_value = mock_issue- # Create a mock file- mock_file = MagicMock()- mock_file.filename = "path/to/file"- mock_file.diff = "This is the diff of the file"+ content = github_toolkit.get_issue_content(1)+ expected_content = "Issue content"++ assert (+ content == expected_content+ ), f"Expected {expected_content}, but got {content}"++[email protected](Github, 'get_repo', return_value=MagicMock())[email protected](Auth.Token, '__init__', lambda self, *args, **kwargs: None)+def test_get_all_pull_requests(monkeypatch):+ github_toolkit = GithubToolkit("repo_name", "token")+ mock_pr = MagicMock()+ mock_pr.number = 1+ mock_pr.title = "Test PR"+ github_toolkit.repo.get_pulls.return_value = [mock_pr]++ prs = github_toolkit.get_pull_request_list()+ expected_prs = [{"number": 1, "title": "Test PR"}]++ assert prs == expected_prs, f"Expected {expected_prs}, but got {prs}"- # Create a mock pull request- mock_pull_request = MagicMock()- mock_pull_request.title = "Test PR"- mock_pull_request.body = "This is a test issue"- mock_pull_request.merged_at = datetime.utcnow()- # Create a mock file[email protected](Github, 'get_repo', return_value=MagicMock())[email protected](Auth.Token, '__init__', lambda self, *args, **kwargs: None)+def test_get_pull_request_code(monkeypatch):+ github_toolkit = GithubToolkit("repo_name", "token")mock_file = MagicMock()- mock_file.filename = "path/to/file"- mock_file.patch = "This is the diff of the file"+ mock_file.filename = "file1.py"+ mock_file.patch = "code changes"+ github_toolkit.repo.get_pull.return_value.get_files.return_value = [+ mock_file+ ]- # Mock the get_files method of the mock_pull_request instance to return a- # list containing the mock file object- mock_pull_request.get_files.return_value = [mock_file]+ files_changed = github_toolkit.get_pull_request_code(1)+ expected_files = [{"filename": "file1.py", "patch": "code changes"}]- # Mock the get_issues method of the mock repo instance to return a list- # containing the mock issue object- github_toolkit.repo.get_pulls.return_value = [mock_pull_request]+ assert (+ files_changed == expected_files+ ), f"Expected {expected_files}, but got {files_changed}"- pull_requests = github_toolkit.retrieve_pull_requests(- days=7, state='closed', max_prs=3- )- # Assert the returned issue list- expected_pull_request = GithubPullRequest(- title="Test PR",- body="This is a test issue",- diffs=[- GithubPullRequestDiff(- filename="path/to/file", patch="This is the diff of the file"- )- ],- )- assert pull_requests == [- str(expected_pull_request)- ], f"Expected {expected_pull_request}, but got {pull_requests}"[email protected](Github, 'get_repo', return_value=MagicMock())[email protected](Auth.Token, '__init__', lambda self, *args, **kwargs: None)+def test_get_pull_request_comments(monkeypatch):+ github_toolkit = GithubToolkit("repo_name", "token")+ mock_comment = MagicMock()+ mock_comment.user.login = "user1"+ mock_comment.body = "Test comment"+ github_toolkit.repo.get_pull.return_value.get_comments.return_value = [+ mock_comment+ ]-def test_github_issue():- # Create a GithubIssue object- issue = GithubIssue(- title="Test Issue",- body="This is a test issue",- number=1,- file_path="path/to/file",- file_content="This is the content of the file",- )+ comments = github_toolkit.get_pull_request_comments(1)+ expected_comments = [{"user": "user1", "body": "Test comment"}]++ assert (+ comments == expected_comments+ ), f"Expected {expected_comments}, but got {comments}"++[email protected](Github, 'get_repo', return_value=MagicMock())[email protected](Auth.Token, '__init__', lambda self, *args, **kwargs: None)+def test_get_all_file_paths(monkeypatch):+ github_toolkit = GithubToolkit("repo_name", "token")+ mock_content = MagicMock()+ mock_content.type = "file"+ mock_content.path = "path/to/file.py"+ github_toolkit.repo.get_contents.return_value = [mock_content]++ files = github_toolkit.get_all_file_paths()+ expected_files = ["path/to/file.py"]- # Assert the attributes of the GithubIssue object- assert issue.title == "Test Issue"- assert issue.body == "This is a test issue"- assert issue.number == 1- assert issue.file_path == "path/to/file"- assert issue.file_content == "This is the content of the file"-- # Test the summary method- summary = str(issue)- expected_summary = (- f"Title: {issue.title}\n"- f"Body: {issue.body}\n"- f"Number: {issue.number}\n"- f"File Path: {issue.file_path}\n"- f"File Content: {issue.file_content}"- )assert (- summary == expected_summary- ), f"Expected {expected_summary}, but got {summary}"+ files == expected_files+ ), f"Expected {expected_files}, but got {files}"