Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Solve API GitHub integration issues #4502

Merged
merged 5 commits into from
Aug 19, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions api/features/feature_external_resources/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import json
import logging
import re

from django.db import models
from django.db.models import Q
Expand Down Expand Up @@ -79,9 +80,19 @@ def execute_after_save_actions(self):
.get(id=self.feature.project.organisation_id)
.github_config.first()
):
if self.type == "GITHUB_PR":
pattern = r"github.com/([^/]+)/([^/]+)/pull/\d+$"
elif self.type == "GITHUB_ISSUE":
pattern = r"github.com/([^/]+)/([^/]+)/issues/\d+$"
Comment on lines +83 to +86
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe to future proof this it could be helpful to add an else keyword and raise an exception.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it's necessary to implement this, because I am already validating it before creating the feature external resource here:


url_match = re.search(pattern, self.url)
owner, repo = url_match.groups()

github_repo = GithubRepository.objects.get(
github_configuration=github_configuration.id,
project=self.feature.project,
repository_owner=owner,
repository_name=repo,
)
if github_repo.tagging_enabled:
github_tag = Tag.objects.get(
Expand Down
20 changes: 17 additions & 3 deletions api/integrations/github/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,23 @@ def fetch_search_github_resource(
headers: dict[str, str] = build_request_headers(
github_configuration.installation_id
)
response = requests.get(url, headers=headers, timeout=GITHUB_API_CALLS_TIMEOUT)
response.raise_for_status()
json_response = response.json()
try:
response = requests.get(url, headers=headers, timeout=GITHUB_API_CALLS_TIMEOUT)
response.raise_for_status()
json_response = response.json()

except HTTPError:
response_content = response.content.decode("utf-8")
error_message = (
"The resources do not exist or you do not have permission to view them"
)
error_data = json.loads(response_content)
if error_data.get("message", "") == "Validation Failed" and any(
error.get("code", "") == "invalid" for error in error_data.get("errors", [])
):
logger.warning(error_message)
raise ValueError(error_message)

results = [
{
"html_url": i["html_url"],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ def test_update_feature_external_resource(
mock_generate_token.return_value = "mocked_token"
feature_external_resource_data = {
"type": "GITHUB_ISSUE",
"url": "https://github.com/userexample/example-project-repo/issues/12",
"url": f"https://github.com/{github_repository.repository_owner}/{github_repository.repository_name}/issues/12",
"feature": feature.id,
"metadata": '{"state": "open"}',
}
Expand Down
50 changes: 48 additions & 2 deletions api/tests/unit/integrations/github/test_unit_github_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,7 @@ def test_fetch_issues(
)


@responses.activate
def test_fetch_issues_returns_error_on_bad_response_from_github(
admin_client_new: APIClient,
organisation: Organisation,
Expand All @@ -556,17 +557,62 @@ def test_fetch_issues_returns_error_on_bad_response_from_github(
mocker: MockerFixture,
) -> None:
# Given
mocker.patch("requests.get", side_effect=mocked_requests_get_error)

mock_response = {
"message": "Validation Failed",
"errors": [{"message": "Error", "code": "not_found"}],
"documentation_url": "https://docs.github.com/v3/search/",
"status": "404",
}

responses.add(
method="GET",
url="https://api.github.com/search/issues?q=%20repo:repo/repo%20is:issue%20is:open%20in:title%20in:body&per_page=100&page=1", # noqa: E501
status=status.HTTP_404_NOT_FOUND,
json=mock_response,
)
url = reverse("api-v1:organisations:get-github-issues", args=[organisation.id])
data = {"repo_owner": "owner", "repo_name": "repo"}
# When
response = admin_client_new.get(url, data=data)

# Then
assert response.status_code == status.HTTP_502_BAD_GATEWAY
assert "Failed to retrieve GitHub issues." in response.json()["detail"]


@responses.activate
def test_search_issues_returns_error_on_bad_search_params(
admin_client_new: APIClient,
organisation: Organisation,
github_configuration: GithubConfiguration,
github_repository: GithubRepository,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit:

Suggested change
github_configuration: GithubConfiguration,
github_repository: GithubRepository,
github_configuration: GitHubConfiguration,
github_repository: GitHubRepository,

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can't change this because it is the model's name.

class GithubConfiguration(SoftDeleteExportableModel):

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok I guess it's too much work to change the name of the model?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I decided to rename the model, thanks for the suggestion. I will merge this PR afterward.

mock_github_client_generate_token: MagicMock,
mocker: MockerFixture,
) -> None:
# Given
mock_response = {
"message": "Validation Failed",
"errors": [{"message": "Error", "code": "invalid"}],
"documentation_url": "https://docs.github.com/v3/search/",
"status": "422",
}
responses.add(
method="GET",
url="https://api.github.com/search/issues?q=%20repo:owner/repo%20is:issue%20is:open%20in:title%20in:body&per_page=100&page=1", # noqa: E501
status=status.HTTP_422_UNPROCESSABLE_ENTITY,
json=mock_response,
)
url = reverse("api-v1:organisations:get-github-issues", args=[organisation.id])
data = {"repo_owner": "owner", "repo_name": "repo"}
# When
response = admin_client_new.get(url, data=data)

# Then
assert response.status_code == status.HTTP_400_BAD_REQUEST
response_json = response.json()
assert (
"Failed to retrieve GitHub issues. Error: HTTP Error 404"
"Failed to retrieve GitHub issues. Error: The resources do not exist or you do not have permission to view them"
in response_json["detail"]
)

Expand Down
Loading