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

feat(codecov): Fetch code coverage for stacktrace #43116

Merged
merged 19 commits into from
Jan 18, 2023
Merged

Conversation

jangjodi
Copy link
Member

@jangjodi jangjodi commented Jan 11, 2023

Fixes WOR-2550

Comment on lines 192 to 194
CODECOV_URL.replace("service", config["provider"]["key"])
.replace("owner_username", repo_name[0])
.replace("repo_name", repo_name[1])
Copy link
Member

Choose a reason for hiding this comment

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

Try using variables and string interpolation here instead:

CODECOV_URL = "https://api.codecov.io/api/v2/{service}/{owner_username}/repos/{repo_name}/report"

Suggested change
CODECOV_URL.replace("service", config["provider"]["key"])
.replace("owner_username", repo_name[0])
.replace("repo_name", repo_name[1])
CODECOV_URL.format(service=config["provider"]["key"],owner_username=repo_name[0], repo_name=repo_name[1])

def get_codecov_line_coverage(
self, config: JSONData, source_url: str, access_token: str
) -> Any:
repo_name = config["repoName"].split("/")
Copy link
Member

Choose a reason for hiding this comment

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

You can assign both halves of the split to a variable, like so:

Suggested change
repo_name = config["repoName"].split("/")
owner_username, repo_name = config["repoName"].split("/")

codecov_path_index = 0

# Extract path from URL from "blob/<sha_or_branch>/" onwards
for i, path in enumerate(source_url_split):
Copy link
Member

Choose a reason for hiding this comment

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

Not entirely sure what this logic is trying to do, but it looks like we're trying to find a specific part of the path to split at.

Would using a regular expression work better here?

Copy link
Member Author

Choose a reason for hiding this comment

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

An example of the logic we are trying to achieve is:

source_url = "https://github.com/getsentry/sentry/blob/8a0bf7246d39cdeb56d457134ee32767673b7492/src/sentry/shared_integrations/client/base.py"
but we want the path to be
src/sentry/shared_integrations/client/base.py"

Thank you for your suggestion, I used find to clean this part up

@@ -225,6 +228,35 @@ def test_file_no_stack_root_match(self, mock_integration):
assert response.data["error"] == "stack_root_mismatch"
assert response.data["integrations"] == [serialized_integration(self.integration)]

@responses.activate
Copy link
Member

Choose a reason for hiding this comment

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

What does this do?

Copy link
Member Author

Choose a reason for hiding this comment

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

This was a mistake that I removed in a previous commit, I'm not sure why it was still visible. I think it's gone now haha


def get_codecov_line_coverage(
self, config: JSONData, source_url: str, access_token: str
) -> Iterable[Union[Any, Optional[int]]]:
Copy link
Member

Choose a reason for hiding this comment

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

We probably want to use Tuple instead of Union, and Sequence instead of Iterable.

For the lineCoverage, how about something like Sequence[Sequence[int, int]]. Or we can define a type called LineCoverage as Sequence[Sequence[int, int]] and return Optional[LineCoverage] to make the following more readable.

Suggested change
) -> Iterable[Union[Any, Optional[int]]]:
) -> Tuple[Sequence[Sequence[int, int]], Optional[int]]:

Copy link
Member Author

Choose a reason for hiding this comment

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

Thank you for the suggestion! I did Tuple[Optional[Sequence[Tuple[int, int]]], just because Sequence can only take one parameter

Co-authored-by: Snigdha Sharma <snigdha.sharma@sentry.io>
except Exception:
if status_code != 404:
logger.exception("Failed to get coverage from Codecov")
line_coverage = None
Copy link
Member

Choose a reason for hiding this comment

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

Does this need to be reset this here, given the assignment on L202?

Copy link
Member Author

Choose a reason for hiding this comment

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

Good catch, thank you!

@jangjodi jangjodi requested a review from armenzg January 17, 2023 22:49
CODECOV_TOKEN = options.get("codecov.client-secret")


class Codecov:
Copy link
Member

Choose a reason for hiding this comment

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

I would not make it a class but up to you. Specially since you're not taking advantage of self.

src/sentry/options/defaults.py Show resolved Hide resolved
@@ -0,0 +1,31 @@
from typing import Optional, Sequence, Tuple
Copy link
Member

Choose a reason for hiding this comment

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

When adding new files check to see if the file is listed under mypy.ini

Copy link
Member Author

Choose a reason for hiding this comment

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

Thank you, this is good to know!

src/sentry/integrations/utils/codecov.py Outdated Show resolved Hide resolved
branch=current_config["config"]["defaultBranch"],
path=current_config["outcome"]["sourcePath"],
)
except Exception:
Copy link
Member

Choose a reason for hiding this comment

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

If we use raise_status(), this code would look more like this:

                    except requests.exceptions.HTTPError as error:
                        if error.response.status_code == 404:
                            logger.exception("Failed to get expected coverage data from Codecov, pending investigation. Continuing execution.")
                    except Exception:
                        logger.exception("Something unexpected happen. Continuing execution")

For now, let's error on everything and later on determine if we need to silence certain cases:

                    except Exception:
                        logger.exception("Failed to get expected coverage data from Codecov, pending investigation. Continuing execution.")

You can remove the next few lines.

Co-authored-by: @armenzg <armenzg@sentry.io>
@jangjodi jangjodi requested a review from a team as a code owner January 18, 2023 17:18
from sentry.models import Integration, Project, RepositoryProjectPathConfig
from sentry.shared_integrations.exceptions import ApiError
from sentry.utils.event_frames import munged_filename_and_frames
from sentry.utils.json import JSONData

logger = logging.getLogger(__name__)
CODECOV_TOKEN = options.get("codecov.client-secret")
Copy link
Member

Choose a reason for hiding this comment

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

You can directly import CODECOV_TOKEN from sentry.integrations.utils.codecov and you will not need to do this here.

if result["lineCoverage"]:
result["codecovStatusCode"] = 200
except requests.exceptions.HTTPError as error:
result["codecovStatusCode"] = error.response.status_code
Copy link
Member

Choose a reason for hiding this comment

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

Smart :)

@getsentry-bot
Copy link
Contributor

PR reverted: 05056a3

getsentry-bot added a commit that referenced this pull request Jan 18, 2023
This reverts commit 3d2231d.

Co-authored-by: armenzg <44410+armenzg@users.noreply.github.com>
jangjodi added a commit that referenced this pull request Jan 18, 2023
Fixes WOR-2550

Co-authored-by: Snigdha Sharma <snigdha.sharma@sentry.io>
Co-authored-by: @armenzg <armenzg@sentry.io>
jangjodi added a commit that referenced this pull request Jan 19, 2023
Fixes WOR-2550

Co-authored-by: Snigdha Sharma <snigdha.sharma@sentry.io>
Co-authored-by: @armenzg <armenzg@sentry.io>
@github-actions github-actions bot locked and limited conversation to collaborators Feb 4, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Scope: Backend Automatically applied to PRs that change backend components Trigger: Revert add to a merged PR to revert it (skips CI)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants