Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/amd_debug/sleep_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -502,8 +502,8 @@ def build_template(self, inc_prereq) -> str:
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
f.write(template.render(context))
if "SUDO_UID" in os.environ:
os.fchown(fd, int(os.environ["SUDO_UID"]), int(os.environ["SUDO_GID"]))
if "SUDO_UID" in os.environ:
os.fchown(fd, int(os.environ["SUDO_UID"]), int(os.environ["SUDO_GID"]))
except Exception:
try:
os.close(fd)
Expand Down
27 changes: 27 additions & 0 deletions src/test_sleep_report.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
"""

import math
import os
import tempfile
import unittest
from datetime import datetime
from unittest.mock import patch
Expand Down Expand Up @@ -153,6 +155,31 @@ def test_build_template(self, _mock_fsl, mock_env):
result = self.report.build_template(inc_prereq=False)
self.assertEqual(result, "Rendered Template")

@patch("amd_debug.sleep_report.Environment")
@patch("amd_debug.sleep_report.FileSystemLoader")
def test_build_template_fchown_called_while_fd_open(self, _mock_fsl, mock_env):
"""Test that fchown is called before the file descriptor is closed.

When SUDO_UID/SUDO_GID are set, os.fchown must be called inside the
'with os.fdopen(...)' block so that the file descriptor is still valid.
Calling it after the block exits causes OSError (Bad file descriptor).
"""
mock_template = mock_env.return_value.get_template.return_value
mock_template.render.return_value = "Rendered Template"

with tempfile.TemporaryDirectory() as tmpdir:
fname = os.path.join(tmpdir, "report.txt")
self.report.fname = fname

with patch.dict("os.environ", {"SUDO_UID": "1000", "SUDO_GID": "1000"}):
with patch("os.fchown") as mock_fchown:
self.report.build_template(inc_prereq=False)
# fchown must have been called exactly once with the real fd
mock_fchown.assert_called_once()
_fd, uid, gid = mock_fchown.call_args[0]
self.assertEqual(uid, 1000)
self.assertEqual(gid, 1000)

@patch("matplotlib.pyplot.savefig")
def test_build_battery_chart(self, mock_savefig):
"""Test the build_battery_chart method."""
Expand Down
Loading