diff --git a/cla-backend/cla/controllers/github_application.py b/cla-backend/cla/controllers/github_application.py index 7ced6eb23..4f3b9ec28 100644 --- a/cla-backend/cla/controllers/github_application.py +++ b/cla-backend/cla/controllers/github_application.py @@ -13,9 +13,10 @@ class GitHubInstallation(object): + @property def app_id(self): - return os.environ["GH_APP_ID"] + return os.environ['GH_APP_ID'] @property def private_key(self): @@ -29,10 +30,9 @@ def repos(self): def __init__(self, installation_id): self.installation_id = installation_id - cla.log.debug( - "Initializing github application - installation_id: {}, app id: {}, private key" - " (minus header): {}...".format(self.installation_id, self.app_id, self.private_key[32:38]) - ) + cla.log.debug('Initializing github application - installation_id: {}, app id: {}, private key' + ' (minus header): {}...'. + format(self.installation_id, self.app_id, self.private_key[32:38])) try: integration = GithubCLAIntegration(self.app_id, self.private_key) @@ -40,28 +40,20 @@ def __init__(self, installation_id): self.token = auth.token self.api_object = Github(self.token) except BadCredentialsException as e: - cla.log.warning( - "BadCredentialsException connecting to Github using app_id: {}, installation id: " - "{}, error: {}".format(self.app_id, self.installation_id, e) - ) + cla.log.warning('BadCredentialsException connecting to Github using app_id: {}, installation id: ' + '{}, error: {}'.format(self.app_id, self.installation_id, e)) raise e except UnknownObjectException as e: - cla.log.warning( - "UnknownObjectException connecting to Github using app_id: {}, installation id: " - "{}, error: {}".format(self.app_id, self.installation_id, e) - ) + cla.log.warning('UnknownObjectException connecting to Github using app_id: {}, installation id: ' + '{}, error: {}'.format(self.app_id, self.installation_id, e)) raise e except GithubException as e: - cla.log.warning( - "GithubException connecting to Github using app_id: {}, installation id: " - "{}, error: {}".format(self.app_id, self.installation_id, e) - ) + cla.log.warning('GithubException connecting to Github using app_id: {}, installation id: ' + '{}, error: {}'.format(self.app_id, self.installation_id, e)) raise e except Exception as e: - cla.log.warning( - "Error connecting to Github to fetch the access token using app_id: {}, installation id: " - "{}, error: {}".format(self.app_id, self.installation_id, e) - ) + cla.log.warning('Error connecting to Github to fetch the access token using app_id: {}, installation id: ' + '{}, error: {}'.format(self.app_id, self.installation_id, e)) raise e def create_check_run(self, repository_name, data): @@ -69,40 +61,15 @@ def create_check_run(self, repository_name, data): Function that creates a check run for unsigned users """ try: - url = "https://api.github.com/repos/{}/check-runs".format(repository_name) + url = 'https://api.github.com/repos/{}/check-runs'.format(repository_name) requests.post( url, data=data, headers={ - "Content-Type": "application/json", - "Authorization": "token %s" % self.token, - "Accept": "application/vnd.github.antiope-preview+json", - }, - ) - - except RequestException as err: - cla.log.debug(err) - - def add_labels_to_pr(self, repository_name, pr_number, labels): - """ - Function that adds labels to a PR - - :param repository_name: The name of the repository - :type repo: str - :param pr_number: The number of the PR - :type pr_number: int - :param labels: The labels to add to the PR - """ - try: - url = "https://api.github.com/repos/{}/issues/{}/labels".format(repository_name, pr_number) - requests.post( - url, - json=labels, - headers={ - "Content-Type": "application/json", - "Authorization": "token %s" % self.token, - "Accept": "application/vnd.github.v3+json", - }, + 'Content-Type': 'application/json', + 'Authorization': 'token %s' % self.token, + 'Accept': 'application/vnd.github.antiope-preview+json' + } ) except RequestException as err: @@ -120,7 +87,11 @@ def create_jwt(self): Couldn't get it working with pyjwt. """ now = int(time.time()) - payload = {"iat": now, "exp": now + 60, "iss": self.integration_id} - gh_jwt = jwt.encode(payload, self.private_key, "RS256") + payload = { + "iat": now, + "exp": now + 60, + "iss": self.integration_id + } + gh_jwt = jwt.encode(payload, self.private_key, 'RS256') # cla.log.debug('github jwt: {}'.format(gh_jwt)) return gh_jwt diff --git a/cla-backend/cla/models/github_models.py b/cla-backend/cla/models/github_models.py index 3725cdf64..73d0688f1 100644 --- a/cla-backend/cla/models/github_models.py +++ b/cla-backend/cla/models/github_models.py @@ -19,15 +19,13 @@ from cla.models import DoesNotExist, repository_service_interface from cla.models.dynamo_models import GitHubOrg, Repository from cla.user import UserCommitSummary -from cla.utils import append_project_version_to_url, get_project_instance, set_active_pr_metadata +from cla.utils import (append_project_version_to_url, get_project_instance, + set_active_pr_metadata) from github import PullRequest -from github.GithubException import ( - BadCredentialsException, - GithubException, - IncompletableObject, - RateLimitExceededException, - UnknownObjectException, -) +from github.GithubException import (BadCredentialsException, GithubException, + IncompletableObject, + RateLimitExceededException, + UnknownObjectException) from requests_oauthlib import OAuth2Session # some emails we want to exclude when we register the users @@ -1692,20 +1690,6 @@ def update_pull_request( ) create_commit_status(pull_request, last_commit.sha, state, sign_url, body, context) - # Add labels to the PR - labels = [] - cla.log.debug(f"{fn} - Adding labels to PR: {pull_request.number}...") - if missing: - labels.append("CLA: Error") - elif signed: - labels.append("CLA: Valid") - if labels: - client = GitHubInstallation(installation_id) - client.add_labels_to_pr(repository_name, pull_request.number, labels) - cla.log.debug(f"{fn} - Successfully added labels {labels} to PR: {pull_request.number}") - else: - cla.log.debug(f"{fn} - No labels to add to PR: {pull_request.number}") - def create_commit_status_for_merge_group(commit_obj, merge_commit_sha, state, sign_url, body, context): """ @@ -1807,28 +1791,6 @@ def create_commit_status(pull_request, commit_hash, state, sign_url, body, conte # return comment -def add_labels_to_pull_request(installation_id, github_repository_id, pull_request, labels): - """ - Helper function to add labels to a GitHub PR. - - :param: installation_id: The ID of the GitHub installation - :type: installation_id: int - :param: github_repository_id: The ID of the GitHub repository this PR belongs to. - :type: github_repository_id: int - :param: pull_request: The GitHub PullRequest object for this PR. - :type: pull_request: GitHub.PullRequest - :param: labels: The list of labels to add to the PR. - :type: labels: List[string] - """ - fn = "cla.models.github_models.add_labels_to_pull_request" - try: - client = GitHubInstallation(installation_id) - client.add_labels_to_pull_request(github_repository_id, pull_request.number, labels) - cla.log.debug(f"{fn} - Successfully added labels {labels} to PR: {pull_request.number}") - except Exception as e: - cla.log.warning(f"{fn} - Unable to add labels {labels} to PR: {pull_request.number}: {e}") - - def get_github_integration_client(installation_id): """ GitHub App integration client used for authenticated client actions through an installed app. diff --git a/cla-backend/cla/tests/unit/test_github_models.py b/cla-backend/cla/tests/unit/test_github_models.py index 6ac21920e..533744b62 100644 --- a/cla-backend/cla/tests/unit/test_github_models.py +++ b/cla-backend/cla/tests/unit/test_github_models.py @@ -5,13 +5,9 @@ from unittest import TestCase from unittest.mock import MagicMock, Mock, patch -from cla.models.github_models import ( - UserCommitSummary, - get_author_summary, - get_co_author_commits, - get_pull_request_commit_authors, - update_pull_request, -) +from cla.models.github_models import (UserCommitSummary, get_author_summary, + get_co_author_commits, + get_pull_request_commit_authors) class TestGetPullRequestCommitAuthors(TestCase): @@ -51,7 +47,7 @@ def test_get_pull_request_commit_with_co_author(self, mock_github_instance): self.assertIn(co_author_email_2, [author.author_email for author in result]) self.assertIn("fake_login", [author.author_login for author in result]) self.assertIn("co_author_login", [author.author_login for author in result]) - + @patch("cla.utils.get_repository_service") def test_get_co_author_commits_invalid_gh_email(self, mock_github_instance): # Mock data @@ -63,7 +59,7 @@ def test_get_co_author_commits_invalid_gh_email(self, mock_github_instance): installation_id = 123 # Call the function - result = get_co_author_commits(co_author, commit, pr, installation_id) + result = get_co_author_commits(co_author,commit, pr, installation_id) # Assertions self.assertEqual(result.commit_sha, "fake_sha") @@ -71,19 +67,21 @@ def test_get_co_author_commits_invalid_gh_email(self, mock_github_instance): self.assertEqual(result.author_login, None) self.assertEqual(result.author_email, "co_author_email.gmail.com") self.assertEqual(result.author_name, "co_author") - + @patch("cla.utils.get_repository_service") def test_get_co_author_commits_valid_gh_email(self, mock_github_instance): # Mock data co_author = ("co_author", "co_author_email.gmail.com") commit = MagicMock() commit.sha = "fake_sha" - mock_github_instance.return_value.get_github_user_by_email.return_value = Mock(id=123, login="co_author_login") + mock_github_instance.return_value.get_github_user_by_email.return_value = Mock( + id=123, login="co_author_login" + ) pr = 1 installation_id = 123 # Call the function - result = get_co_author_commits(co_author, commit, pr, installation_id) + result = get_co_author_commits(co_author,commit, pr, installation_id) # Assertions self.assertEqual(result.commit_sha, "fake_sha") @@ -92,57 +90,6 @@ def test_get_co_author_commits_valid_gh_email(self, mock_github_instance): self.assertEqual(result.author_email, "co_author_email.gmail.com") self.assertEqual(result.author_name, "co_author") - @patch("cla.models.github_models.cla.utils") - @patch("cla.models.github_models.GitHubInstallation") - def test_update_pull_request_valid_labels(self, mock_github_installation, mock_utils): - # Mock data - installation_id = 123 - github_repository_id = 456 - pull_request = MagicMock() - repository_name = "test_org/test_repo" - signed = [ - UserCommitSummary( - author_id="1", - author_login="fake_login", - author_name="Fake Author", - author_email="foo@gmail.com", - commit_sha="fake_sha", - authorized=True, - affiliated=True, - ) - ] - missing = [] - project_version = "2" - - last_commit = MagicMock() - last_commit.sha = "fake_sha" - pull_request.get_commits.return_value.reversed.__getitem__.return_value = last_commit - - mock_utils.get_full_sign_url.return_value = "https://example.com/sign" - mock_utils.assemble_cla_comment.return_value = "CLA comment" - mock_utils.assemble_cla_status.return_value = ("context", "CLA status") - - client_mock = MagicMock() - mock_github_installation.return_value = client_mock - - # Call the function - update_pull_request( - installation_id, - github_repository_id, - pull_request, - repository_name, - signed, - missing, - project_version, - ) - - # Assertions - client_mock.add_labels_to_pr.assert_called_once_with( - repository_name, - pull_request.number, - ["CLA: Valid"], - ) - if __name__ == "__main__": unittest.main()