Skip to content

Commit

Permalink
Merge pull request #57 from timmyb824/refactor/improve-dist-version
Browse files Browse the repository at this point in the history
Merge pull request #56 from timmyb824/refactor/system-info
  • Loading branch information
timmyb824 authored Apr 29, 2024
2 parents 557412e + 36a289e commit 5abc0a3
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 160 deletions.
47 changes: 10 additions & 37 deletions src/core/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,11 @@
import subprocess
import time
import re

import distro

from src.utilities.utils import print_bold_kv, print_title


# def get_last_boot_time() -> float:
# """Returns the last boot time as a float for macOS."""
# if platform.system() == "Darwin":
# try:
# result = subprocess.run(
# ["sysctl", "-n", "kern.boottime"],
# capture_output=True,
# text=True,
# check=True,
# ).stdout.strip()
# if match := re.search(r"sec = (\d+)", result):
# return float(match[1])
# else:
# raise ValueError("Could not parse kern.boottime output")
# except (subprocess.CalledProcessError, ValueError) as e:
# print(f"An error occurred while getting last boot time: {e}")
# return 0.0
# else:
# try:
# result = subprocess.run(
# ["uptime", "-s"],
# capture_output=True,
# text=True,
# check=True,
# ).stdout.strip()
# return float(result)
# except subprocess.CalledProcessError as e:
# print(f"An error occurred while getting last boot time: {e}")
# return 0.0


def get_last_boot_time() -> str:
"""Returns the last boot time as a date and time string."""
if platform.system() == "Darwin":
Expand All @@ -60,7 +29,7 @@ def get_last_boot_time() -> str:
except (subprocess.CalledProcessError, ValueError) as e:
print(f"An error occurred while getting last boot time: {e}")
return "Error obtaining last boot time"
else: # Assuming this else branch is for Linux
elif platform.system() == "Linux":
try:
return subprocess.run(
["uptime", "-s"],
Expand All @@ -71,6 +40,8 @@ def get_last_boot_time() -> str:
except subprocess.CalledProcessError as e:
print(f"An error occurred while getting last boot time: {e}")
return "Error obtaining last boot time"
else:
return "Not supported on this OS"


def get_system_uptime() -> str:
Expand All @@ -85,7 +56,7 @@ def get_system_uptime() -> str:
except Exception as e:
print(f"An error occurred while getting system uptime on Linux: {e}")
return "Error in obtaining uptime"
else:
elif platform.system() == "Darwin":
try:
uptime_output = subprocess.run(
["uptime"],
Expand All @@ -97,6 +68,8 @@ def get_system_uptime() -> str:
except subprocess.CalledProcessError as e:
print(f"An error occurred while getting system uptime: {e}")
return "Error in obtaining uptime"
else:
return "Not supported on this OS"


def get_user_count_unix(path: str) -> int:
Expand Down Expand Up @@ -132,10 +105,10 @@ def get_system_info() -> dict:
system_info["uptime"] = get_system_uptime()
system_info["last_boot_date"] = get_last_boot_time()
if system_info["os_type"] == "Linux":
import distro # distro is a Linux-specific package

system_info["dist"] = distro.name()
system_info["dist_version"] = distro.version()
system_info["dist_version"] = (
platform.freedesktop_os_release().get("VERSION") or distro.version()
)
system_info["users_nb"] = get_user_count_unix("/home")

elif system_info["os_type"] == "Darwin":
Expand Down
124 changes: 1 addition & 123 deletions tests/test_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,72 +6,9 @@
get_last_boot_time,
get_system_uptime,
get_user_count_unix,
get_system_info,
)


# # Test get_last_boot_time_macos
# @pytest.mark.parametrize(
# "output,expected",
# [
# ("{ sec = 1625097600, usec = 0 }", 1625097600.0), # ID: valid-output
# ("", 0.0), # ID: empty-output
# ("invalid output", 0.0), # ID: invalid-output
# ],
# ids=["valid-output", "empty-output", "invalid-output"],
# )
# def test_get_last_boot_time_macos(output, expected):
# with patch("subprocess.run") as mocked_run:
# mocked_run.return_value = MagicMock(stdout=output)

# # Act
# result = get_last_boot_time_macos()

# # Assert
# assert result == expected


# # Test get_system_uptime
# @pytest.mark.parametrize("output,expected", [
# ("13:05 up 3 days, 18:53, 5 users", "13:05 up 3 days, 18:53"), # ID: normal-case
# ("", ""), # ID: empty-output
# ("uptime: unexpected output", "uptime: unexpected output"), # ID: unexpected-output
# ], ids=["normal-case", "empty-output", "unexpected-output"])
# def test_get_system_uptime(output, expected):
# with patch("subprocess.run") as mocked_run:
# mocked_run.return_value = MagicMock(stdout=output)

# # Act
# result = get_system_uptime()

# # Assert
# assert result == expected

# @pytest.mark.skipif(platform.system() != "Darwin", reason="Running on non-Darwin system")
# def test_get_last_boot_time_darwin():
# with patch("platform.system", return_value="Darwin"), patch(
# "subprocess.run", return_value=MagicMock(stdout="kern.boottime = { sec = 1625097600, usec = 0 } Mon Jun 1 00:00:00 2020")
# ):
# assert get_last_boot_time() == 1625097600.0

# with patch("platform.system", return_value="Darwin"), patch(
# "subprocess.run", side_effect=subprocess.CalledProcessError(1, "sysctl")
# ):
# assert get_last_boot_time() == 0.0

# @pytest.mark.skipif(platform.system() != "Linux", reason="Running on non-Linux system")
# def test_get_last_boot_time_linux():
# with patch("platform.system", return_value="Linux"), patch(
# "subprocess.run", return_value=MagicMock(stdout="2020-06-01 00:00:00")
# ):
# assert get_last_boot_time() == 1590969600.0

# with patch("platform.system", return_value="Linux"), patch(
# "subprocess.run", side_effect=subprocess.CalledProcessError(1, "uptime")
# ):
# assert get_last_boot_time() == 0.0


# Test for macOS
@pytest.mark.skipif(
platform.system() != "Darwin", reason="Test only applicable on macOS"
Expand Down Expand Up @@ -146,63 +83,4 @@ def test_get_user_count_unix(path, dirs, expected):
# Assert
assert result == expected


# TODO: test is currently missing uptime and last_boot_time
@pytest.mark.parametrize(
"os_type,expected_keys",
[
(
"Linux",
[
"os_type",
"hostname",
"kernel_info",
"architecture",
"dist",
"dist_version",
"users_nb",
"current_date",
],
), # ID: linux
(
"Darwin",
[
"os_type",
"hostname",
"kernel_info",
"architecture",
"dist",
"dist_version",
"users_nb",
"current_date",
],
), # ID: darwin
],
ids=["linux", "darwin"],
)
def test_get_system_info(os_type, expected_keys):

with patch("platform.system", return_value=os_type), patch(
"platform.node", return_value="test_hostname"
), patch("platform.uname", return_value=MagicMock(release="test_release")), patch(
"platform.machine", return_value="test_machine"
), patch(
"platform.mac_ver", return_value=("10.15.1", "", "")
), patch(
"os.listdir"
), patch(
"os.path.isdir", return_value=True
), patch(
"time.time", return_value=1625097600
), patch(
"distro.name", return_value="Ubuntu"
), patch(
"distro.version", return_value="20.04"
):

# Act
result = get_system_info()

# Assert
for key in expected_keys:
assert key in result
#TODO: Add test back for get_system_info

0 comments on commit 5abc0a3

Please sign in to comment.