From 05cfc442553669ff5e2f0e49828df2170bad8039 Mon Sep 17 00:00:00 2001 From: Martin Pilros <58504806+martin-pil@users.noreply.github.com> Date: Fri, 22 Nov 2024 19:51:26 +0100 Subject: [PATCH] Use rev-parse is-inside-work-tree to check if in git repo (#32) --- src/pytest_opentelemetry/resource.py | 8 ++++++- tests/test_resource.py | 35 +++++++++++++++++----------- 2 files changed, 29 insertions(+), 14 deletions(-) diff --git a/src/pytest_opentelemetry/resource.py b/src/pytest_opentelemetry/resource.py index fc8c4f8..4e52aa9 100644 --- a/src/pytest_opentelemetry/resource.py +++ b/src/pytest_opentelemetry/resource.py @@ -20,7 +20,13 @@ def get_codebase_name() -> str: @staticmethod def get_codebase_version() -> str: - if not os.path.exists('.git'): + try: + response = subprocess.check_output( + ['git', 'rev-parse', '--is-inside-work-tree'] + ) + if response.strip() != b'true': + return '[unknown: not a git repository]' + except Exception: # pylint: disable=broad-except return '[unknown: not a git repository]' try: diff --git a/tests/test_resource.py b/tests/test_resource.py index baf715d..f3d5222 100644 --- a/tests/test_resource.py +++ b/tests/test_resource.py @@ -1,7 +1,9 @@ import os import re +import subprocess import tempfile from typing import Generator +from unittest.mock import patch import pytest from opentelemetry.sdk.resources import Resource @@ -35,19 +37,26 @@ def test_service_version_unknown(bare_codebase: str, resource: Resource) -> None assert resource.attributes['service.version'] == '[unknown: not a git repository]' -@pytest.fixture -def broken_repo(bare_codebase: str) -> str: - # making an empty .git directory will get us past the first check, but then - # `git rev-parse HEAD` will fail - os.makedirs('.git') - return bare_codebase - - -def test_service_version_git_problems(broken_repo: str, resource: Resource) -> None: - assert resource.attributes['service.version'] == ( - "[unknown: Command '['git', 'rev-parse', 'HEAD']' " - "returned non-zero exit status 128.]" - ) +def test_service_version_git_problems() -> None: + with patch( + 'pytest_opentelemetry.resource.subprocess.check_output', + side_effect=[ + b'true', + subprocess.CalledProcessError(128, ['git', 'rev-parse', 'HEAD']), + ], + ): + resource = CodebaseResourceDetector().detect() + assert resource.attributes['service.version'] == ( + "[unknown: Command '['git', 'rev-parse', 'HEAD']' " + "returned non-zero exit status 128.]" + ) + with patch( + 'pytest_opentelemetry.resource.subprocess.check_output', side_effect=[b'false'] + ): + resource = CodebaseResourceDetector().detect() + assert resource.attributes['service.version'] == ( + "[unknown: not a git repository]" + ) @pytest.fixture