Skip to content

Commit

Permalink
fix: library version check is os independent
Browse files Browse the repository at this point in the history
  • Loading branch information
sgoral-splunk committed Nov 27, 2024
1 parent 238e34b commit 620c5d3
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 16 deletions.
18 changes: 6 additions & 12 deletions splunk_add_on_ucc_framework/install_python_libraries.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,27 +95,21 @@ 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

# 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)
Expand Down
6 changes: 2 additions & 4 deletions tests/unit/test_install_python_libraries.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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")
Expand Down

0 comments on commit 620c5d3

Please sign in to comment.