Skip to contentSkip to conversation

tuna: Argparse refactoring and testing improvements

PATCH New John Kacur 1 participant 6 messages Jun 11

lore
Share & tools
lore

John Kacur

author
#0 lore raw

cover tuna: Argparse refactoring and testing improvements

This series refactors the argparse implementation in tuna-cmd.py to eliminate side effects during argument parsing and remove global variables, making the code more maintainable and testable.

The main improvements are:

1. Replace bare except clauses with specific exception types for better error handling

2. Defer type conversions until after parsing completes, eliminating side effects during argument parsing (parse → convert → execute pattern)

3. Remove global variables (ps, irqs, match_requested) and pass them as function parameters instead

4. Add comprehensive unit tests (12 tests) for argument converter functions using mock objects to avoid requiring procfs access

5. Update test documentation with detailed examples and explanations

All tests pass (18 total) and run without requiring root privileges.

John Kacur (5):
tuna: Replace bare except clauses with specific exception types
tuna: Eliminate side effects from argparse by deferring type
conversions
tuna: Eliminate global ps and irqs variables
tuna: Add .local/ directory to .gitignore
tuna: Add tests for converter functions and update test README

 .gitignore               |   1 +
 tests/README.md          |  85 ++++++++++++++++++++-
 tests/test_converters.py | 160 +++++++++++++++++++++++++++++++++++++++
 tuna-cmd.py              | 114 ++++++++++++++--------------
 4 files changed, 300 insertions(+), 60 deletions(-)
 create mode 100644 tests/test_converters.py
Signature · 1 line
2.54.0
author
#1 lore raw

PATCH 1/5 tuna: Replace bare except clauses with specific exception types

Replace all bare except clauses in tuna-cmd.py with specific exception types for better error handling and debugging. This improves code quality by being explicit about what errors are being caught.

Changes:
- inet_diag import (line 75): Use ImportError
- ps_show_sockets (lines 298, 305): Use OSError for process death cases
- irq users lookup (line 357): Use KeyError, ValueError, LookupError
- IRQ parsing (line 418): Use ValueError, KeyError
- socket iteration (line 457): Use OSError, StopIteration
- driver lookup (line 500): Use ValueError
- thread regex (line 571): Use re.error

All existing unit tests pass after these changes.

Assisted-by Claude:claude-sonnet-4-5
---
 tuna-cmd.py | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)
tuna-cmd.py +8 -8
index 6208bd116cea..54f0666fa1bb 100755
@@ -72,7 +72,7 @@ def add_handler(loglevel, tofile=False):
 try:
     import inet_diag
     have_inet_diag = True
-except:
+except ImportError:
     have_inet_diag = False
 
 # FIXME: ETOOMANYGLOBALS, we need a class!
@@ -295,14 +295,14 @@ def ps_show_sockets(pid, ps, inodes, inode_re, indent=0):
     dirname = f"/proc/{pid}/fd"
     try:
         filenames = os.listdir(dirname)
-    except:  # Process died
+    except OSError:  # Process died
         return
     sindent = " " * indent
     for filename in filenames:
         pathname = os.path.join(dirname, filename)
         try:
             linkto = os.readlink(pathname)
-        except:  # Process died
+        except OSError:  # Process died
             continue
         inode_match = inode_re.match(linkto)
         if not inode_match:
@@ -354,7 +354,7 @@ def ps_show_thread(pid, affect_children, ps, has_ctxt_switch_info, sock_inodes,
                     users[users.index(u)] = "%s(%s)" % (
                         u, ethtool.get_module(u))
             users = ",".join(users)
-        except:
+        except (KeyError, ValueError, LookupError):
             users = "Not found in /proc/interrupts!"
 
     ctxt_switch_info = ""
@@ -415,7 +415,7 @@ def ps_show(ps, affect_children, thread_list, cpu_list,
                             continue
                     else:
                         in_irq_list = True
-                except:
+                except (ValueError, KeyError):
                     pass
             elif not thread_list:
                 continue
@@ -454,7 +454,7 @@ def load_socktype(socktype, inodes):
     while True:
         try:
             s = idiag.get()
-        except:
+        except (OSError, StopIteration):
             break
         inodes[s.inode()] = s
 
@@ -497,7 +497,7 @@ def find_drivers_by_users(users):
         try:
             idx = u.index('-')
             u = u[:idx]
-        except:
+        except ValueError:
             pass
         if u in nics:
             driver = ethtool.get_module(u)
@@ -568,7 +568,7 @@ def threadstring_to_list(threadstr):
             ps = procfs.pidstats()
             try:
                 thread_list += ps.find_by_regex(re.compile(fnmatch.translate(s)))
-            except:
+            except re.error:
                 thread_list += ps.find_by_name(s)
     return thread_list
 
Signature · 1 line
2.54.0
author
#2 lore raw

PATCH 2/5 tuna: Eliminate side effects from argparse by deferring type conversions

In reply to John Kacur

Refactor argument parsing to remove side effects during the argparse phase by deferring type conversions until after parsing completes. This creates a clearer separation between parsing, conversion, and execution.

Problems with the previous implementation:
- Converter functions (threadstring_to_list, irqstring_to_list) were called via type= parameter during argparse parsing
- These converters set global variables and created procfs objects before knowing what command would run
- Global state (match_requested) was used to coordinate between parsing time and execution time

Changes:
- Removed type= parameters for threadstring_to_list and irqstring_to_list from POS and MODS dictionaries, changed to type=str with default=''
- Changed sockets argument to store in 'sockets' dest instead of 'cpu_list'
- Updated threadstring_to_list() to accept ps parameter and return tuple (thread_list, match_requested_flag)
- Updated irqstring_to_list() to return tuple (irq_list, match_requested_flag)
- Added explicit conversion block in main() after argument parsing
- Eliminated match_requested global variable, now local in main()
- Updated ps_show(), show_irqs(), do_ps() to accept match_requested parameter
- Kept ps and irqs as module-level variables for now

Benefits:
- No side effects during argument parsing
- Clear control flow: parse → convert → execute
- match_requested is now local state instead of global
- Easier to understand and maintain
- Sets foundation for future refactoring of remaining globals

All 6 existing unit tests pass.

Assisted-by Claude:claude-sonnet-4-5
---
 tuna-cmd.py | 65 ++++++++++++++++++++++++++++++++---------------------
 1 file changed, 39 insertions(+), 26 deletions(-)
tuna-cmd.py +39 -26
index 54f0666fa1bb..4da6c6ea6ce5 100755
@@ -79,7 +79,6 @@ except ImportError:
 
 ps = None
 irqs = None
-match_requested = False
 
 class HelpMessageParser(argparse.ArgumentParser):
     def error(self, message):
@@ -92,7 +91,7 @@ def gen_parser():
 
     POS = {
             "cpu_list": dict(metavar='CPU-LIST', type=tuna.cpustring_to_list, help="CPU-LIST affected by commands"),
-            "thread_list": dict(metavar='THREAD-LIST', type=threadstring_to_list, help="THREAD-LIST affected by commands"),
+            "thread_list": dict(metavar='THREAD-LIST', type=str, help="THREAD-LIST affected by commands"),
             "filename": dict(metavar='FILENAME', type=str, help="Save kthreads sched tunables to this file"),
             "profilename": dict(type=str, help="Apply changes described in this file"),
             "run_command": dict(metavar='COMMAND', type=str, help="fork a new process and run the \"COMMAND\""),
@@ -103,10 +102,10 @@ def gen_parser():
             "logging": dict(dest='loglevel', metavar='LOG-LEVEL', type=get_loglevel, help="Log application details to file for given LOG-LEVEL"),
             "debug" : dict(action='store_true', dest='debug', help='Print DEBUG level logging details to console'),
             "version": dict(action='version', version='0.20', help="show version"),
-            "threads": dict(dest='thread_list', default=[], metavar='THREAD-LIST', type=threadstring_to_list, help="THREAD-LIST affected by commands"),
-            "irqs": dict(dest='irq_list', default=[], metavar='IRQ-LIST', type=irqstring_to_list, help="IRQ-LIST affect by commands"),
+            "threads": dict(dest='thread_list', default='', metavar='THREAD-LIST', type=str, help="THREAD-LIST affected by commands"),
+            "irqs": dict(dest='irq_list', default='', metavar='IRQ-LIST', type=str, help="IRQ-LIST affect by commands"),
             "cpus": dict(dest='cpu_list', default=[], metavar='CPU-LIST', type=tuna.cpustring_to_list, help='CPU-LIST affected by commands'),
-            "sockets": dict(dest='cpu_list', default=[], metavar='CPU-SOCKET-LIST', type=socketstring_to_list, help="CPU-SOCKET-LIST affected by commands"),
+            "sockets": dict(dest='sockets', default='', metavar='CPU-SOCKET-LIST', type=str, help="CPU-SOCKET-LIST affected by commands"),
             "show_sockets": dict(action='store_true', help='Show network sockets in use by threads'),
             "cgroups": dict(action='store_true', dest='cgroups', help='Display the processes with the type of cgroups they are in'),
             "spaced": dict(action='store_false', dest='compact', help='Display spaced view for cgroups'),
@@ -394,9 +393,7 @@ def ps_show_thread(pid, affect_children, ps, has_ctxt_switch_info, sock_inodes,
 
 def ps_show(ps, affect_children, thread_list, cpu_list,
             irq_list_numbers, show_uthreads, show_kthreads,
-            has_ctxt_switch_info, sock_inodes, sock_inode_re, cgroups, compact):
-
-    global match_requested
+            has_ctxt_switch_info, sock_inodes, sock_inode_re, cgroups, compact, match_requested):
 
     ps_list = []
     for pid in list(ps.keys()):
@@ -467,7 +464,7 @@ def load_sockets():
 
 
 def do_ps(thread_list, cpu_list, irq_list, show_uthreads, show_kthreads,
-          affect_children, show_sockets, cgroups, compact):
+          affect_children, show_sockets, cgroups, compact, match_requested):
     ps = procfs.pidstats()
     if affect_children:
         ps.reload_threads()
@@ -484,7 +481,7 @@ def do_ps(thread_list, cpu_list, irq_list, show_uthreads, show_kthreads,
             ps_show_header(has_ctxt_switch_info, cgroups)
         ps_show(ps, affect_children, thread_list,
                 cpu_list, irq_list, show_uthreads, show_kthreads,
-                has_ctxt_switch_info, sock_inodes, sock_inode_re, cgroups, compact)
+                has_ctxt_switch_info, sock_inodes, sock_inode_re, cgroups, compact, match_requested)
     except IOError:
         # 'tuna -P | head' for instance
         pass
@@ -507,9 +504,8 @@ def find_drivers_by_users(users):
     return drivers
 
 
-def show_irqs(irq_list, cpu_list):
+def show_irqs(irq_list, cpu_list, match_requested):
     global irqs
-    global match_requested
     if not irqs:
         irqs = procfs.interrupts()
 
@@ -554,30 +550,29 @@ def do_list_op(op, current_list, op_list):
         return list(set(current_list) - set(op_list))
     return list(set(op_list))
 
-def threadstring_to_list(threadstr):
-    global ps
-    global match_requested
-    if threadstr:
-        match_requested = True
+def threadstring_to_list(threadstr, ps=None):
+    match_requested = bool(threadstr)
     thread_list = []
+    if not threadstr:
+        return thread_list, match_requested
     thread_strings = list(set(threadstr.split(',')))
     for s in thread_strings:
         if s.isdigit():
             thread_list.append(int(s))
         else:
-            ps = procfs.pidstats()
+            if ps is None:
+                ps = procfs.pidstats()
             try:
                 thread_list += ps.find_by_regex(re.compile(fnmatch.translate(s)))
             except re.error:
                 thread_list += ps.find_by_name(s)
-    return thread_list
+    return thread_list, match_requested
 
 def irqstring_to_list(irqstr):
-
-    global match_requested
-    if irqstr:
-        match_requested = True
+    match_requested = bool(irqstr)
     irq_list = []
+    if not irqstr:
+        return irq_list, match_requested
     irq_strings = list(set(irqstr.split(',')))
     for s in irq_strings:
         if s.isdigit():
@@ -586,7 +581,7 @@ def irqstring_to_list(irqstr):
             # find_by_user_regex returns a list of strings corresponding to irq number
             irq_list_str = procfs.interrupts().find_by_user_regex(re.compile(fnmatch.translate(s)))
             irq_list += [int(i) for i in irq_list_str if i.isdigit()]
-    return irq_list
+    return irq_list, match_requested
 
 def socketstring_to_list(socketstr):
     cpu_list = []
@@ -684,6 +679,24 @@ def main():
             print("Valid log levels: NOTSET, DEBUG, INFO, WARNING, ERROR")
             print("Log levels may be specified numerically (0-4)\n")
 
+    # Convert string arguments to lists after parsing
+    match_requested = False
+
+    # Convert thread_list from string to list
+    if 'thread_list' in vars(args) and args.thread_list:
+        if isinstance(args.thread_list, str):
+            args.thread_list, match_requested = threadstring_to_list(args.thread_list, ps)
+
+    # Convert irq_list from string to list
+    if 'irq_list' in vars(args) and args.irq_list:
+        if isinstance(args.irq_list, str):
+            args.irq_list, irq_match_requested = irqstring_to_list(args.irq_list)
+            match_requested = match_requested or irq_match_requested
+
+    # Convert socket strings to cpu lists
+    if hasattr(args, 'sockets') and args.sockets:
+        args.cpu_list = socketstring_to_list(args.sockets)
+
     if args.command == 'cpu_power':
         if not cpw.have_cpupower:
             print(f"Error: libcpupower bindings are not detected; please install libcpupower bindings from at least kernel {cpw.cpupower_required_kernel}.", file=sys.stderr)
@@ -738,10 +751,10 @@ def main():
 
     elif args.command in ['show_threads']:
         do_ps(args.thread_list, args.cpu_list, args.irq_list, args.uthreads,
-                args.kthreads, args.affect_children, args.show_sockets if "show_sockets" in args else None, args.cgroups, args.compact)
+                args.kthreads, args.affect_children, args.show_sockets if "show_sockets" in args else None, args.cgroups, args.compact, match_requested)
 
     elif args.command in ['show_irqs']:
-        show_irqs(args.irq_list, args.cpu_list)
+        show_irqs(args.irq_list, args.cpu_list, match_requested)
 
     elif args.command in ['move', 'm', 'spread', 'x']:
         spread = args.command in ['spread', 'x']
Signature · 1 line
2.54.0
author
#3 lore raw

PATCH 3/5 tuna: Eliminate global ps and irqs variables

In reply to John Kacur

Remove the remaining global variables (ps and irqs) and pass them as function parameters instead. This completes the refactoring to eliminate side effects and global state from the codebase.

The ps and irqs globals were used as a cache/singleton pattern where they would be lazily initialized on first use and reused across function calls. However, most commands only call these functions once, so the caching benefit was minimal while the global state made the code harder to understand and test.

Changes:
- Removed global variable declarations for ps and irqs (lines 78-82)
- Removed "FIXME: ETOOMANYGLOBALS" comment - issue is now resolved
- Updated thread_help() to accept ps as parameter
- Removed global ps declaration from main(), made it local variable
- Added irqs parameter to ps_show_thread() signature
- Added irqs parameter to ps_show() signature
- Updated do_ps() to create irqs locally and pass to ps_show()
- Updated show_irqs() to create irqs locally instead of using global
- Updated what_is command to create ps if needed and pass to thread_help()
- Updated all call sites to pass parameters correctly

Benefits:
- No global variables - all state is now local or explicitly passed
- Functions are pure with clear dependencies visible in signatures
- Code is more testable and easier to understand
- Explicit control flow with no hidden state

All 6 existing unit tests pass.

Assisted-by Claude:claude-sonnet-4-5
---
 tuna-cmd.py | 37 +++++++++++++------------------------
 1 file changed, 13 insertions(+), 24 deletions(-)
tuna-cmd.py +13 -24
index 4da6c6ea6ce5..d83e57732360 100755
@@ -75,11 +75,6 @@ try:
 except ImportError:
     have_inet_diag = False
 
-# FIXME: ETOOMANYGLOBALS, we need a class!
-
-ps = None
-irqs = None
-
 class HelpMessageParser(argparse.ArgumentParser):
     def error(self, message):
         sys.stderr.write(f'error: {message}\n')
@@ -250,11 +245,7 @@ def gen_parser():
     return parser
 
 
-def thread_help(tid):
-    global ps
-    if not ps:
-        ps = procfs.pidstats()
-
+def thread_help(tid, ps):
     if tid not in ps:
         print(f"tuna: thread {tid} doesn't exist!")
         return
@@ -329,8 +320,7 @@ def format_affinity(affinity):
     return ",".join(str(hex(a)) for a in procfs.hexbitmask(affinity, utils.get_nr_cpus()))
 
 def ps_show_thread(pid, affect_children, ps, has_ctxt_switch_info, sock_inodes,
-                   sock_inode_re, cgroups, columns=None, compact=True):
-    global irqs
+                   sock_inode_re, cgroups, irqs, columns=None, compact=True):
     try:
         affinity = format_affinity(os.sched_getaffinity(pid))
     except OSError as e:
@@ -345,8 +335,6 @@ def ps_show_thread(pid, affect_children, ps, has_ctxt_switch_info, sock_inodes,
     users = ""
     if tuna.is_irq_thread(cmd):
         try:
-            if not irqs:
-                irqs = procfs.interrupts()
             users = irqs[tuna.irq_thread_number(cmd)]["users"]
             for u in users:
                 if u in utils.get_nics():
@@ -388,12 +376,12 @@ def ps_show_thread(pid, affect_children, ps, has_ctxt_switch_info, sock_inodes,
         for tid in list(ps[pid]["threads"].keys()):
             ps_show_thread(tid, False, ps[pid]["threads"],
                            has_ctxt_switch_info,
-                           sock_inodes, sock_inode_re, cgroups, columns, compact)
+                           sock_inodes, sock_inode_re, cgroups, irqs, columns, compact)
 
 
 def ps_show(ps, affect_children, thread_list, cpu_list,
             irq_list_numbers, show_uthreads, show_kthreads,
-            has_ctxt_switch_info, sock_inodes, sock_inode_re, cgroups, compact, match_requested):
+            has_ctxt_switch_info, sock_inodes, sock_inode_re, cgroups, compact, match_requested, irqs):
 
     ps_list = []
     for pid in list(ps.keys()):
@@ -443,7 +431,7 @@ def ps_show(ps, affect_children, thread_list, cpu_list,
 
     for pid in ps_list:
         ps_show_thread(pid, affect_children, ps, has_ctxt_switch_info,
-                       sock_inodes, sock_inode_re, cgroups, columns, compact)
+                       sock_inodes, sock_inode_re, cgroups, irqs, columns, compact)
 
 
 def load_socktype(socktype, inodes):
@@ -469,6 +457,8 @@ def do_ps(thread_list, cpu_list, irq_list, show_uthreads, show_kthreads,
     if affect_children:
         ps.reload_threads()
 
+    irqs = procfs.interrupts()
+
     sock_inodes = None
     sock_inode_re = None
     if show_sockets:
@@ -481,7 +471,7 @@ def do_ps(thread_list, cpu_list, irq_list, show_uthreads, show_kthreads,
             ps_show_header(has_ctxt_switch_info, cgroups)
         ps_show(ps, affect_children, thread_list,
                 cpu_list, irq_list, show_uthreads, show_kthreads,
-                has_ctxt_switch_info, sock_inodes, sock_inode_re, cgroups, compact, match_requested)
+                has_ctxt_switch_info, sock_inodes, sock_inode_re, cgroups, compact, match_requested, irqs)
     except IOError:
         # 'tuna -P | head' for instance
         pass
@@ -505,9 +495,7 @@ def find_drivers_by_users(users):
 
 
 def show_irqs(irq_list, cpu_list, match_requested):
-    global irqs
-    if not irqs:
-        irqs = procfs.interrupts()
+    irqs = procfs.interrupts()
 
     if sys.stdout.isatty():
         print("%4s %-16s %8s" % ("#", _("users"), _("affinity"),))
@@ -655,8 +643,6 @@ def nohz_full_to_cpu():
 
 
 def main():
-    global ps
-
     i18n_init()
     parser = gen_parser()
     # Set all necessary defaults for gui subparser if no arguments provided
@@ -681,6 +667,7 @@ def main():
 
     # Convert string arguments to lists after parsing
     match_requested = False
+    ps = None
 
     # Convert thread_list from string to list
     if 'thread_list' in vars(args) and args.thread_list:
@@ -772,8 +759,10 @@ def main():
         save(args.cpu_list, args.thread_list, args.filename)
 
     elif args.command in ['W', 'what_is']:
+        if not ps:
+            ps = procfs.pidstats()
         for tid in args.thread_list:
-            thread_help(tid)
+            thread_help(tid, ps)
 
     elif args.command in ['g', 'gui']:
         # Don't try to start the gui if no display is available
Signature · 1 line
2.54.0
author
#4 lore raw

PATCH 4/5 tuna: Add .local/ directory to .gitignore

In reply to John Kacur

Add .local/ to .gitignore to exclude local project notes and documentation from version control. This directory is used for storing development notes, enhancement ideas, and other local files that should not be committed to the repository.

Assisted-by Claude:claude-sonnet-4-5
---
 .gitignore | 1 +
 1 file changed, 1 insertion(+)
.gitignore +1 -0
index d8e20215de9b..273af4ad6006 100644
@@ -3,3 +3,4 @@
 *.swp
 tags
 CLAUDE.md
+.local/
Signature · 1 line
2.54.0
author
#5 lore raw

PATCH 5/5 tuna: Add tests for converter functions and update test README

In reply to John Kacur

Add comprehensive unit tests for argument converter functions:
- threadstring_to_list(): 7 tests covering empty strings, numeric PIDs, duplicates, pattern matching, exact names, and mixed inputs
- irqstring_to_list(): 4 tests covering empty strings, numeric IRQs, and duplicates
- socketstring_to_list(): 1 test verifying function exists

Tests use MockPidStats to avoid requiring real procfs access, allowing them to run without root privileges and in CI/CD environments.

Update tests/README.md with comprehensive documentation:
- How to run tests via make and unittest directly
- Examples for running specific test files, classes, and methods
- Explanation of why tests don't require root privileges
- Description of all current tests (18 total: 6 EPERM + 12 converter)
- Expected output showing successful test run
- Updated requirements and test organization

All 18 tests pass successfully without requiring root access.

Assisted-by Claude:claude-sonnet-4-5
---
 tests/README.md          |  85 ++++++++++++++++++++-
 tests/test_converters.py | 160 +++++++++++++++++++++++++++++++++++++++
 2 files changed, 241 insertions(+), 4 deletions(-)
 create mode 100644 tests/test_converters.py
tests/README.md +81 -4
index aceb38d6f8f5..9f85e6fe97c2 100644
@@ -33,12 +33,22 @@ make test-eperm
 python3 -m unittest tests.test_eperm_handling -v
 ```
 
+### Specific Test Class
+
+Run a specific test class:
+
+```bash
+python3 -m unittest tests.test_converters.TestThreadstringToList -v
+python3 -m unittest tests.test_converters.TestIrqstringToList -v
+```
+
 ### Specific Test Method
 
 Run a single test method:
 
 ```bash
-python3 -m unittest tests.test_eperm_handling.TestEPERMHandling.test_eperm_constant_exists -v
+python3 -m unittest tests.test_eperm_handling.TestEPERMHandling.test_set_affinity_eperm -v
+python3 -m unittest tests.test_converters.TestThreadstringToList.test_pattern_with_mock_ps -v
 ```
 
 ## Test Organization
@@ -50,9 +60,41 @@ Tests are organized using Python's `unittest` framework. Each test file contains
 
 ### Current Tests
 
-- **test_eperm_handling.py** - Tests for EPERM error handling in `isolate_cpus()`
+- **test_eperm_handling.py** (6 tests) - Tests for EPERM error handling
   - Verifies that Permission Denied errors are handled gracefully
-  - Ensures tuna continues processing when it can't set affinity on protected processes
+  - Tests reading and setting affinity, scheduler, and priority on PID 1
+  - Ensures tuna handles permission errors without crashing
+
+- **test_converters.py** (12 tests) - Tests for argument converter functions
+  - Tests `threadstring_to_list()`: Converting thread specifications to PID lists
+  - Tests `irqstring_to_list()`: Converting IRQ specifications to IRQ number lists
+  - Tests `socketstring_to_list()`: Socket string conversion
+  - Uses MockPidStats to test without requiring real process access
+
+### Why Tests Don't Require Root
+
+The tuna program requires root privileges for operations like:
+- Setting CPU affinity on other processes
+- Changing scheduler policies and priorities
+- Moving IRQs to different CPUs
+- Isolating CPUs (system-wide CPU management)
+
+However, the tests are designed to run without root privileges:
+
+1. **EPERM tests** verify that permission errors are handled gracefully when running as non-root
+   - They intentionally trigger permission errors by trying to modify PID 1
+   - Success means the error was caught and handled properly
+
+2. **Converter tests** use mock objects instead of real system access
+   - Test pure logic: string parsing and conversion
+   - MockPidStats provides test data without accessing /proc
+   - No actual process manipulation occurs
+
+**Benefits:**
+- Developers can run tests without `sudo`
+- Tests run in CI/CD environments without elevated privileges
+- Tests are fast and don't affect the running system
+- Tests verify both happy path (with mocks) and error path (with real EPERM)
 
 ## Writing New Tests
 
@@ -125,7 +167,42 @@ self.assertRaises(Exception, fn) # fn() raises Exception
 ## Requirements
 
 - Python 3.6 or later
-- No additional packages required (uses Python standard library)
+- python3-procfs package (for importing procfs module used by converters)
+- No other external packages required (uses Python standard library and mocks)
+
+## Expected Output
+
+A successful test run with all 18 tests should look like:
+
+```
+Running tuna unit tests...
+
+test_get_affinity_eperm (test_eperm_handling.TestEPERMHandling) ... ok
+test_get_priority_eperm (test_eperm_handling.TestEPERMHandling) ... ok
+test_get_scheduler_eperm (test_eperm_handling.TestEPERMHandling) ... ok
+test_set_affinity_eperm (test_eperm_handling.TestEPERMHandling) ... ok
+test_set_priority_eperm (test_eperm_handling.TestEPERMHandling) ... ok
+test_set_scheduler_eperm (test_eperm_handling.TestEPERMHandling) ... ok
+test_duplicate_irqs_deduplicated (test_converters.TestIrqstringToList) ... ok
+test_empty_string (test_converters.TestIrqstringToList) ... ok
+test_multiple_numeric_irqs (test_converters.TestIrqstringToList) ... ok
+test_single_numeric_irq (test_converters.TestIrqstringToList) ... ok
+test_socketstring_exists (test_converters.TestSocketstringToList) ... ok
+test_duplicate_pids_deduplicated (test_converters.TestThreadstringToList) ... ok
+test_empty_string (test_converters.TestThreadstringToList) ... ok
+test_exact_name_with_mock_ps (test_converters.TestThreadstringToList) ... ok
+test_mixed_numeric_and_pattern (test_converters.TestThreadstringToList) ... ok
+test_multiple_numeric_pids (test_converters.TestThreadstringToList) ... ok
+test_pattern_with_mock_ps (test_converters.TestThreadstringToList) ... ok
+test_single_numeric_pid (test_converters.TestThreadstringToList) ... ok
+
+----------------------------------------------------------------------
+Ran 18 tests in 0.XXXs
+
+OK
+
+All tests passed!
+```
 
 ## Test Types
 
tests/test_converters.py new file +160 -0

160 lines not on this page · raw message

Signature · 1 line
2.54.0