Mock systemctl Wrapper in Python for Service Testing

A Python class-based mock of systemctl that simulates start, stop, restart, and status operations for a service, useful for testing automation scripts.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 14 views 0 copies

Python code

47 lines
Python 3.9+
import subprocess
import sys

class ServiceManager:
    def __init__(self, service_name):
        self.service_name = service_name
        self.status = "inactive"
    
    def start(self):
        self.status = "active"
        print(f"Starting {self.service_name}... OK")
    
    def stop(self):
        self.status = "inactive"
        print(f"Stopping {self.service_name}... OK")
    
    def restart(self):
        print(f"Restarting {self.service_name}...")
        self.stop()
        self.start()
        print(f"{self.service_name} restarted successfully")
    
    def status_report(self):
        return f"{self.service_name} is {self.status}"

def mock_systemctl(action, service_name):
    manager = ServiceManager(service_name)
    
    if action == "restart":
        manager.restart()
    elif action == "start":
        manager.start()
    elif action == "stop":
        manager.stop()
    elif action == "status":
        print(manager.status_report())
    else:
        print(f"Unknown action: {action}", file=sys.stderr)
        return 1
    return 0

if __name__ == "__main__":
    service = "nginx"
    print(mock_systemctl("start", service))
    print(mock_systemctl("restart", service))
    print(mock_systemctl("status", service))
    print(mock_systemctl("stop", service))

Output

stdout
Starting nginx... OK
0
Restarting nginx...
Stopping nginx... OK
Starting nginx... OK
nginx restarted successfully
0
nginx is active
0
Stopping nginx... OK
0

How it works

This class encapsulates service state in a ServiceManager object, with start, stop, restart, and status_report methods that mutate and report the internal status attribute. The mock_systemctl function acts as a dispatcher, mapping action strings to the appropriate manager method and printing results. The __main__ block demonstrates a realistic CLI flow: start, restart, check status, and stop — mirroring how systemctl commands are chained in deployment scripts. Because it uses only the standard library, it runs anywhere Python does, making it ideal for unit tests, CI pipelines, or local dev environments where real systemd isn't available.

Common mistakes

  • Passing the service name as a positional arg instead of using it consistently across all method calls
  • Forgetting to return the exit code from mock_systemctl for non-zero failure paths
  • Using a mutable class-level status attribute shared across instances instead of per-instance state

Variations

  1. Use a dataclass or a dict-based state store instead of a class when state is trivial
  2. Add a delay or simulated retry logic to mimic systemd's restart backoff behavior

Real-world use cases

  • Testing deployment scripts in CI without needing root access or a real service manager.
  • Simulating service lifecycle in unit tests for automation code that calls systemctl.
  • Local development sandboxes where starting real services would be heavyweight or unsafe.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.