From 620c5d3dfddcf5cecbf43204485c33c05882797c Mon Sep 17 00:00:00 2001 From: sgoral Date: Wed, 27 Nov 2024 12:59:16 +0100 Subject: [PATCH] fix: library version check is os independent --- .../install_python_libraries.py | 18 ++++++------------ tests/unit/test_install_python_libraries.py | 6 ++---- 2 files changed, 8 insertions(+), 16 deletions(-) diff --git a/splunk_add_on_ucc_framework/install_python_libraries.py b/splunk_add_on_ucc_framework/install_python_libraries.py index 4c20cb478..40ae0baea 100644 --- a/splunk_add_on_ucc_framework/install_python_libraries.py +++ b/splunk_add_on_ucc_framework/install_python_libraries.py @@ -95,11 +95,6 @@ def _pip_is_lib_installed( lib_installed_cmd = f"{installer} -m pip show --version {libname}" - if version: - cmd = f'{lib_installed_cmd} | grep "Version"' - else: - cmd = lib_installed_cmd - try: my_env = os.environ.copy() my_env["PYTHONPATH"] = target @@ -107,15 +102,14 @@ def _pip_is_lib_installed( # Disable writing of .pyc files (__pycache__) my_env["PYTHONDONTWRITEBYTECODE"] = "1" - result = _subprocess_run(command=cmd, env=my_env) - if result.returncode != 0: - cmd_windows = cmd.replace("grep", "findstr") - result = _subprocess_run(command=cmd_windows, env=my_env) - if result.returncode != 0: - return False + result = _subprocess_run(command=lib_installed_cmd, env=my_env) + if result.returncode != 0 or "Version:" not in result.stdout.decode("utf-8"): + return False if version: - result_version = result.stdout.decode("utf-8").split("Version:")[1].strip() + pip_show_result = result.stdout.decode("utf-8").splitlines() + result_row = next(el for el in pip_show_result if el.startswith("Version:")) + result_version = result_row.split("Version:")[1].strip() if allow_higher_version: return Version(result_version) >= Version(version) return Version(result_version) == Version(version) diff --git a/tests/unit/test_install_python_libraries.py b/tests/unit/test_install_python_libraries.py index a68edf9c2..d6740fbf0 100644 --- a/tests/unit/test_install_python_libraries.py +++ b/tests/unit/test_install_python_libraries.py @@ -386,9 +386,7 @@ def test_install_libraries_version_mismatch( tmp_lib_reqs_file = tmp_lib_path / "requirements.txt" tmp_lib_reqs_file.write_text("splunktaucclib\n") - version_mismatch_shell_cmd = ( - 'python3 -m pip show --version cryptography | grep "Version"' - ) + version_mismatch_shell_cmd = "python3 -m pip show --version cryptography" mock_subprocess_run.side_effect = ( lambda command, shell=True, env=None, capture_output=True: ( MockSubprocessResult(1) @@ -538,7 +536,7 @@ def run(command, env): assert command == "python3 -m pip show --version libname" assert env["PYTHONPATH"] == "target" assert env["PYTHONDONTWRITEBYTECODE"] == "1" - return Result(0, b"", b"") + return Result(0, b"Version: 1.0.0", b"") monkeypatch.setattr(install_python_libraries_module, "_subprocess_run", run) assert _pip_is_lib_installed("python3", "target", "libname")