Skip to content

Commit

Permalink
qemu.py: make VM() a context manager
Browse files Browse the repository at this point in the history
There are a number of ways to ensure that the QEMU process is shut down
when the test ends, including atexit.register(), try: finally:, or
unittest.teardown() methods.  All of these require extra code and the
programmer must remember to add vm.shutdown().

A nice solution is context managers:

  with VM(binary) as vm:
      ...
  # vm is guaranteed to be shut down here

Cc: Eduardo Habkost <ehabkost@redhat.com>
Signed-off-by: Stefan Hajnoczi <stefanha@redhat.com>
Reviewed-by: Eduardo Habkost <ehabkost@redhat.com>
Message-id: 20170824072202.26818-2-stefanha@redhat.com
Signed-off-by: Stefan Hajnoczi <stefanha@redhat.com>
  • Loading branch information
stefanhaRH committed Sep 5, 2017
1 parent 2b48373 commit d792bc3
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion scripts/qemu.py
Expand Up @@ -21,7 +21,14 @@


class QEMUMachine(object):
'''A QEMU VM'''
'''A QEMU VM
Use this object as a context manager to ensure the QEMU process terminates::
with VM(binary) as vm:
...
# vm is guaranteed to be shut down here
'''

def __init__(self, binary, args=[], wrapper=[], name=None, test_dir="/var/tmp",
monitor_address=None, socket_scm_helper=None, debug=False):
Expand All @@ -40,6 +47,13 @@ def __init__(self, binary, args=[], wrapper=[], name=None, test_dir="/var/tmp",
self._socket_scm_helper = socket_scm_helper
self._debug = debug

def __enter__(self):
return self

def __exit__(self, exc_type, exc_val, exc_tb):
self.shutdown()
return False

# This can be used to add an unused monitor instance.
def add_monitor_telnet(self, ip, port):
args = 'tcp:%s:%d,server,nowait,telnet' % (ip, port)
Expand Down

0 comments on commit d792bc3

Please sign in to comment.