Skip to contentSkip to conversation

iotests: clean up resources using context managers

PATCH Applied Stefan Hajnoczi 5 participants 14 messages Aug 24, 2017 – Aug 31, 2017

lore
Share & tools
lore
#0 lore raw

cover iotests: clean up resources using context managers

This series introduces context managers for the two most commonly used
resources: files and VMs. Context managers eliminate the need to call a cleanup function explicitly.

Tests should declare resources upfront in a with statement. Resources are automatically cleaned up whether the test passes or fails:

with FilePath('test.img') as img_path,

       VM() as vm:
      ...test...
  # img_path is deleted and vm is shut down automatically

The final patch converts 194 to use context managers instead of atexit.register(). This makes the code shorter and easier to read.

Stefan Hajnoczi (3):
qemu.py: make VM() a context manager
iotests.py: add FilePath context manager
qemu-iotests: use context managers for resource cleanup in 194

 scripts/qemu.py               | 16 ++++++++-
 tests/qemu-iotests/194        | 83 +++++++++++++++++++++----------------------
 tests/qemu-iotests/iotests.py | 26 ++++++++++++++
 3 files changed, 82 insertions(+), 43 deletions(-)
Signature · 1 line
2.13.5
#1 lore raw

PATCH 1/3 qemu.py: make VM() a context manager

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
---
 scripts/qemu.py | 16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)
scripts/qemu.py +15 -1
index 880e3e8219..4d8ee10943 100644
@@ -21,7 +21,14 @@ import qmp.qmp
 
 
 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):
@@ -40,6 +47,13 @@ class QEMUMachine(object):
         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)
Signature · 1 line
2.13.5
#3 lore raw

PATCH 2/3 iotests.py: add FilePath context manager

In reply to Stefan Hajnoczi

The scratch/ (TEST_DIR) directory is not automatically cleaned up after test execution. It is the responsibility of tests to remove any files they create.

A nice way of doing this is to declare files at the beginning of the test and automatically remove them with a context manager:

with iotests.FilePath('test.img') as img_path:

      qemu_img(...)
      qemu_io(...)
  # img_path is guaranteed to be deleted here
---
 tests/qemu-iotests/iotests.py | 26 ++++++++++++++++++++++++++
 1 file changed, 26 insertions(+)
tests/qemu-iotests/iotests.py +26 -0
index 7233983f3c..07fa1626a0 100644
@@ -160,6 +160,32 @@ class Timeout:
     def timeout(self, signum, frame):
         raise Exception(self.errmsg)
 
+
+class FilePath(object):
+    '''An auto-generated filename that cleans itself up.
+
+    Use this context manager to generate filenames and ensure that the file
+    gets deleted::
+
+        with TestFilePath('test.img') as img_path:
+            qemu_img('create', img_path, '1G')
+        # migration_sock_path is automatically deleted
+    '''
+    def __init__(self, name):
+        filename = '{0}-{1}'.format(os.getpid(), name)
+        self.path = os.path.join(test_dir, filename)
+
+    def __enter__(self):
+        return self.path
+
+    def __exit__(self, exc_type, exc_val, exc_tb):
+        try:
+            os.remove(self.path)
+        except OSError:
+            pass
+        return False
+
+
 class VM(qtest.QEMUQtestMachine):
     '''A QEMU VM'''
 
Signature · 1 line
2.13.5
#4 lore raw

PATCH 3/3 qemu-iotests: use context managers for resource cleanup in 194

In reply to Stefan Hajnoczi

Switch from atexit.register() to a more elegant idiom of declaring resources in a with statement:

with FilePath('monitor.sock') as monitor_path,

       VM() as vm:
      ...

The files and VMs will be automatically cleaned up whether the test passes or fails.

---
 tests/qemu-iotests/194 | 83 +++++++++++++++++++++++++-------------------------
 1 file changed, 41 insertions(+), 42 deletions(-)
tests/qemu-iotests/194 +41 -42
index 8028111e21..06aea661d4 100755
@@ -19,55 +19,54 @@
 #
 # Non-shared storage migration test using NBD server and drive-mirror
 
-import os
-import atexit
 import iotests
 
 iotests.verify_platform(['linux'])
 
-img_size = '1G'
-source_img_path = os.path.join(iotests.test_dir, 'source.img')
-dest_img_path = os.path.join(iotests.test_dir, 'dest.img')
-iotests.qemu_img_pipe('create', '-f', iotests.imgfmt, source_img_path, img_size)
-iotests.qemu_img_pipe('create', '-f', iotests.imgfmt, dest_img_path, img_size)
+with iotests.FilePath('source.img') as source_img_path, \
+     iotests.FilePath('dest.img') as dest_img_path, \
+     iotests.FilePath('migration.sock') as migration_sock_path, \
+     iotests.FilePath('nbd.sock') as nbd_sock_path, \
+     iotests.VM('source') as source_vm, \
+     iotests.VM('dest') as dest_vm:
 
-iotests.log('Launching VMs...')
-migration_sock_path = os.path.join(iotests.test_dir, 'migration.sock')
-nbd_sock_path = os.path.join(iotests.test_dir, 'nbd.sock')
-source_vm = iotests.VM('source').add_drive(source_img_path)
-dest_vm = (iotests.VM('dest').add_drive(dest_img_path)
-                             .add_incoming('unix:{0}'.format(migration_sock_path)))
-source_vm.launch()
-atexit.register(source_vm.shutdown)
-dest_vm.launch()
-atexit.register(dest_vm.shutdown)
+    img_size = '1G'
+    iotests.qemu_img_pipe('create', '-f', iotests.imgfmt, source_img_path, img_size)
+    iotests.qemu_img_pipe('create', '-f', iotests.imgfmt, dest_img_path, img_size)
 
-iotests.log('Launching NBD server on destination...')
-iotests.log(dest_vm.qmp('nbd-server-start', addr={'type': 'unix', 'data': {'path': nbd_sock_path}}))
-iotests.log(dest_vm.qmp('nbd-server-add', device='drive0', writable=True))
+    iotests.log('Launching VMs...')
+    (source_vm.add_drive(source_img_path)
+              .launch())
+    (dest_vm.add_drive(dest_img_path)
+            .add_incoming('unix:{0}'.format(migration_sock_path))
+            .launch())
 
-iotests.log('Starting drive-mirror on source...')
-iotests.log(source_vm.qmp(
-              'drive-mirror',
-              device='drive0',
-              target='nbd+unix:///drive0?socket={0}'.format(nbd_sock_path),
-              sync='full',
-              format='raw', # always raw, the server handles the format
-              mode='existing'))
+    iotests.log('Launching NBD server on destination...')
+    iotests.log(dest_vm.qmp('nbd-server-start', addr={'type': 'unix', 'data': {'path': nbd_sock_path}}))
+    iotests.log(dest_vm.qmp('nbd-server-add', device='drive0', writable=True))
 
-iotests.log('Waiting for drive-mirror to complete...')
-iotests.log(source_vm.event_wait('BLOCK_JOB_READY'),
-            filters=[iotests.filter_qmp_event])
+    iotests.log('Starting drive-mirror on source...')
+    iotests.log(source_vm.qmp(
+                  'drive-mirror',
+                  device='drive0',
+                  target='nbd+unix:///drive0?socket={0}'.format(nbd_sock_path),
+                  sync='full',
+                  format='raw', # always raw, the server handles the format
+                  mode='existing'))
 
-iotests.log('Starting migration...')
-source_vm.qmp('migrate-set-capabilities',
-              capabilities=[{'capability': 'events', 'state': True}])
-dest_vm.qmp('migrate-set-capabilities',
-            capabilities=[{'capability': 'events', 'state': True}])
-iotests.log(source_vm.qmp('migrate', uri='unix:{0}'.format(migration_sock_path)))
+    iotests.log('Waiting for drive-mirror to complete...')
+    iotests.log(source_vm.event_wait('BLOCK_JOB_READY'),
+                filters=[iotests.filter_qmp_event])
 
-while True:
-    event = source_vm.event_wait('MIGRATION')
-    iotests.log(event, filters=[iotests.filter_qmp_event])
-    if event['data']['status'] in ('completed', 'failed'):
-        break
+    iotests.log('Starting migration...')
+    source_vm.qmp('migrate-set-capabilities',
+                  capabilities=[{'capability': 'events', 'state': True}])
+    dest_vm.qmp('migrate-set-capabilities',
+                capabilities=[{'capability': 'events', 'state': True}])
+    iotests.log(source_vm.qmp('migrate', uri='unix:{0}'.format(migration_sock_path)))
+
+    while True:
+        event = source_vm.event_wait('MIGRATION')
+        iotests.log(event, filters=[iotests.filter_qmp_event])
+        if event['data']['status'] in ('completed', 'failed'):
+            break
Signature · 1 line
2.13.5
#5 lore raw
In reply to Stefan Hajnoczi
Quoted 7 lines · Stefan Hajnoczi

Tests should declare resources upfront in a with statement. Resources are automatically cleaned up whether the test passes or fails:

with FilePath('test.img') as img_path,

       VM() as vm:
      ...test...
  # img_path is deleted and vm is shut down automatically

Looks good but still requires test writers to learn and remember to use FilePath and with. These are still boilerplates. Here goes my personal oppinion, so may not be plausible:

- For VM() maybe add an atexit in the launch() method also makes sure the VM is eventually terminated.

This means vm.shutdown() is still needed in tearDown() if there are multiple test methods and each of them expects a clean state, but that is probably still less typing (and also indenting) than the with approach, and also easy to remember (otherwise a test will fail).

- For scratch how about adding atexit in iotests.main to clean up everything in the scratch directory? The rationale is similar to above.

Fam

#6 lore raw
Quoted 11 lines · Fam Zheng
Quoted 7 lines · Stefan Hajnoczi

Tests should declare resources upfront in a with statement. Resources are automatically cleaned up whether the test passes or fails:

with FilePath('test.img') as img_path,

       VM() as vm:
      ...test...
  # img_path is deleted and vm is shut down automatically

Looks good but still requires test writers to learn and remember to use FilePath and with.

You cannot forget to use FilePath() unless you love typing at os.path.join(iotests.test_dir, 'test.img'). It's much better than open coding filename generation!

Quoted 10 lines

These are still boilerplates. Here goes my personal oppinion, so may not be plausible:

- For VM() maybe add an atexit in the launch() method also makes sure the VM is eventually terminated.

This means vm.shutdown() is still needed in tearDown() if there are multiple test methods and each of them expects a clean state, but that is probably still less typing (and also indenting) than the with approach, and also easy to remember (otherwise a test will fail).

I looked into atexit before going this route. atexit does not have an unregister() API in Python 2. This makes it ugly to use because some tests do not want the resource to remain for the duration of the process.

A related point is that the Python objects used by atexit handlers live until the end of the process. They cannot be garbage collected because the atexit handler still has a reference to them.

The with statement's identation is annoying for straightforward scripts. More complex tests use functions anyway, so the indentation doesn't matter there - it can be hidden by a parent function or even a decorator.

Quoted 2 lines

- For scratch how about adding atexit in iotests.main to clean up everything in the scratch directory? The rationale is similar to above.

If we decide to clear out TEST_DIR then it should be done in ./check, not by iotests.py, so that all tests get the same file cleanup behavior, regardless of the language they are written in.

Also, we can then chdir(iotests.test_dir) so filename generation isn't necessary at all. Tests can simply use 'test.img'. I guess there may be some cases where absolute paths are necessary, but for the most part this would be a win.

Kevin may have an opinion on whether TEST_DIR should be cleared out or not.

Stefan

#7 lore raw
Quoted 28 lines · Stefan Hajnoczi
Quoted 11 lines · Fam Zheng
Quoted 7 lines · Stefan Hajnoczi

Tests should declare resources upfront in a with statement. Resources are automatically cleaned up whether the test passes or fails:

with FilePath('test.img') as img_path,

       VM() as vm:
      ...test...
  # img_path is deleted and vm is shut down automatically

Looks good but still requires test writers to learn and remember to use FilePath and with.

You cannot forget to use FilePath() unless you love typing at os.path.join(iotests.test_dir, 'test.img'). It's much better than open coding filename generation!

Quoted 10 lines

These are still boilerplates. Here goes my personal oppinion, so may not be plausible:

- For VM() maybe add an atexit in the launch() method also makes sure the VM is eventually terminated.

This means vm.shutdown() is still needed in tearDown() if there are multiple test methods and each of them expects a clean state, but that is probably still less typing (and also indenting) than the with approach, and also easy to remember (otherwise a test will fail).

Quoted 8 lines

I looked into atexit before going this route. atexit does not have an unregister() API in Python 2. This makes it ugly to use because some tests do not want the resource to remain for the duration of the process.

A related point is that the Python objects used by atexit handlers live until the end of the process. They cannot be garbage collected because the atexit handler still has a reference to them.

I think this shortcoming can be solved with a clean up list ("all problems in computer science can be solved by another level of indirection"):

_clean_up_list = set()
def _clean_up_handler():
for i in _clean_up_list:
try:
i()
except:
pass

atexit.register(_clean_up_handler)

class VM(...):

    def launch():
        ...
        _clean_up_list.add(self.launch)

    def shutdown():
        _clean_up_list.remove(self.launch)
        ...
Quoted 9 lines

The with statement's identation is annoying for straightforward scripts. More complex tests use functions anyway, so the indentation doesn't matter there - it can be hidden by a parent function or even a decorator.

Quoted 2 lines

- For scratch how about adding atexit in iotests.main to clean up everything in the scratch directory? The rationale is similar to above.

Quoted 8 lines

If we decide to clear out TEST_DIR then it should be done in ./check, not by iotests.py, so that all tests get the same file cleanup behavior, regardless of the language they are written in.

Also, we can then chdir(iotests.test_dir) so filename generation isn't necessary at all. Tests can simply use 'test.img'. I guess there may be some cases where absolute paths are necessary, but for the most part this would be a win.

Good point, ./check can even invoke scripts with scratch as their working directory.

Fam

Quoted 6 lines

Kevin may have an opinion on whether TEST_DIR should be cleared out or not.

Stefan

#8 lore raw
Quoted 53 lines · Fam Zheng
Quoted 28 lines · Stefan Hajnoczi
Quoted 11 lines · Fam Zheng
Quoted 7 lines · Stefan Hajnoczi

Tests should declare resources upfront in a with statement. Resources are automatically cleaned up whether the test passes or fails:

with FilePath('test.img') as img_path,

       VM() as vm:
      ...test...
  # img_path is deleted and vm is shut down automatically

Looks good but still requires test writers to learn and remember to use FilePath and with.

You cannot forget to use FilePath() unless you love typing at os.path.join(iotests.test_dir, 'test.img'). It's much better than open coding filename generation!

Quoted 10 lines

These are still boilerplates. Here goes my personal oppinion, so may not be plausible:

- For VM() maybe add an atexit in the launch() method also makes sure the VM is eventually terminated.

This means vm.shutdown() is still needed in tearDown() if there are multiple test methods and each of them expects a clean state, but that is probably still less typing (and also indenting) than the with approach, and also easy to remember (otherwise a test will fail).

Quoted 8 lines

I looked into atexit before going this route. atexit does not have an unregister() API in Python 2. This makes it ugly to use because some tests do not want the resource to remain for the duration of the process.

A related point is that the Python objects used by atexit handlers live until the end of the process. They cannot be garbage collected because the atexit handler still has a reference to them.

I think this shortcoming can be solved with a clean up list ("all problems in computer science can be solved by another level of indirection"):

_clean_up_list = set()
def _clean_up_handler():
for i in _clean_up_list:
try:
i()
except:
pass

atexit.register(_clean_up_handler)

class VM(...):

Quoted 7 lines
    def launch():
        ...
        _clean_up_list.add(self.launch)

    def shutdown():
        _clean_up_list.remove(self.launch)
        ...

atexit is still less powerful than context managers because its scope is fixed. Handler functions are only called when the process terminates. Many test cases do not want resources (especially the VMs) around forever because they run several iterations or sub-tests.

The with statement can be used both for process-lifetime and for more fine-grained scoping. That's why I chose it.

If you stick to atexit then sub-tests or iterations require manual vm.shutdown() - something that is not necessary using the with statement.

Stefan

#9 lore raw
Quoted 67 lines · Stefan Hajnoczi
Quoted 53 lines · Fam Zheng
Quoted 28 lines · Stefan Hajnoczi
Quoted 11 lines · Fam Zheng
Quoted 7 lines · Stefan Hajnoczi

Tests should declare resources upfront in a with statement. Resources are automatically cleaned up whether the test passes or fails:

with FilePath('test.img') as img_path,

       VM() as vm:
      ...test...
  # img_path is deleted and vm is shut down automatically

Looks good but still requires test writers to learn and remember to use FilePath and with.

You cannot forget to use FilePath() unless you love typing at os.path.join(iotests.test_dir, 'test.img'). It's much better than open coding filename generation!

Quoted 10 lines

These are still boilerplates. Here goes my personal oppinion, so may not be plausible:

- For VM() maybe add an atexit in the launch() method also makes sure the VM is eventually terminated.

This means vm.shutdown() is still needed in tearDown() if there are multiple test methods and each of them expects a clean state, but that is probably still less typing (and also indenting) than the with approach, and also easy to remember (otherwise a test will fail).

Quoted 8 lines

I looked into atexit before going this route. atexit does not have an unregister() API in Python 2. This makes it ugly to use because some tests do not want the resource to remain for the duration of the process.

A related point is that the Python objects used by atexit handlers live until the end of the process. They cannot be garbage collected because the atexit handler still has a reference to them.

I think this shortcoming can be solved with a clean up list ("all problems in computer science can be solved by another level of indirection"):

_clean_up_list = set()
def _clean_up_handler():
for i in _clean_up_list:
try:
i()
except:
pass

atexit.register(_clean_up_handler)

class VM(...):

Quoted 7 lines
    def launch():
        ...
        _clean_up_list.add(self.launch)

    def shutdown():
        _clean_up_list.remove(self.launch)
        ...

atexit is still less powerful than context managers because its scope is fixed. Handler functions are only called when the process terminates. Many test cases do not want resources (especially the VMs) around forever because they run several iterations or sub-tests.

Quoted 6 lines

The with statement can be used both for process-lifetime and for more fine-grained scoping. That's why I chose it.

If you stick to atexit then sub-tests or iterations require manual vm.shutdown() - something that is not necessary using the with statement.

Sure!

I just think that if leftover VM instances are a concern and not all test code are converted to "with", having the atexit handler in addition may provide more robustness.

Fam

Reviewed-by on v1 1/3
#2 lore raw

Re: [Qemu-devel] [PATCH 1/3] qemu.py: make VM() a context manager

In reply to Stefan Hajnoczi
Quoted 5 lines · Stefan Hajnoczi

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().

Quoted 8 lines

A nice solution is context managers:

with VM(binary) as vm:

      ...
  # vm is guaranteed to be shut down here
Signature · 1 line
Eduardo
#12 lore raw
In reply to Stefan Hajnoczi
Quoted 62 lines · Stefan Hajnoczi
Quoted 53 lines · Fam Zheng
Quoted 28 lines · Stefan Hajnoczi
Quoted 11 lines · Fam Zheng
Quoted 7 lines · Stefan Hajnoczi

Tests should declare resources upfront in a with statement. Resources are automatically cleaned up whether the test passes or fails:

with FilePath('test.img') as img_path,

       VM() as vm:
      ...test...
  # img_path is deleted and vm is shut down automatically

Looks good but still requires test writers to learn and remember to use FilePath and with.

You cannot forget to use FilePath() unless you love typing at os.path.join(iotests.test_dir, 'test.img'). It's much better than open coding filename generation!

Quoted 10 lines

These are still boilerplates. Here goes my personal oppinion, so may not be plausible:

- For VM() maybe add an atexit in the launch() method also makes sure the VM is eventually terminated.

This means vm.shutdown() is still needed in tearDown() if there are multiple test methods and each of them expects a clean state, but that is probably still less typing (and also indenting) than the with approach, and also easy to remember (otherwise a test will fail).

Quoted 8 lines

I looked into atexit before going this route. atexit does not have an unregister() API in Python 2. This makes it ugly to use because some tests do not want the resource to remain for the duration of the process.

A related point is that the Python objects used by atexit handlers live until the end of the process. They cannot be garbage collected because the atexit handler still has a reference to them.

I think this shortcoming can be solved with a clean up list ("all problems in computer science can be solved by another level of indirection"):

_clean_up_list = set()
def _clean_up_handler():
for i in _clean_up_list:
try:
i()
except:
pass

atexit.register(_clean_up_handler)

class VM(...):

Quoted 7 lines
    def launch():
        ...
        _clean_up_list.add(self.launch)

    def shutdown():
        _clean_up_list.remove(self.launch)
        ...
Quoted 7 lines

atexit is still less powerful than context managers because its scope is fixed. Handler functions are only called when the process terminates. Many test cases do not want resources (especially the VMs) around forever because they run several iterations or sub-tests.

The with statement can be used both for process-lifetime and for more fine-grained scoping. That's why I chose it.

Moreover, context managers are Pythonic.

Quoted 5 lines

If you stick to atexit then sub-tests or iterations require manual vm.shutdown() - something that is not necessary using the with statement.

Stefan

#10 lore raw
In reply to Fam Zheng
Quoted 75 lines · Fam Zheng
Quoted 67 lines · Stefan Hajnoczi
Quoted 53 lines · Fam Zheng
Quoted 28 lines · Stefan Hajnoczi
Quoted 11 lines · Fam Zheng
Quoted 7 lines · Stefan Hajnoczi

Tests should declare resources upfront in a with statement. Resources are automatically cleaned up whether the test passes or fails:

with FilePath('test.img') as img_path,

       VM() as vm:
      ...test...
  # img_path is deleted and vm is shut down automatically

Looks good but still requires test writers to learn and remember to use FilePath and with.

You cannot forget to use FilePath() unless you love typing at os.path.join(iotests.test_dir, 'test.img'). It's much better than open coding filename generation!

Quoted 10 lines

These are still boilerplates. Here goes my personal oppinion, so may not be plausible:

- For VM() maybe add an atexit in the launch() method also makes sure the VM is eventually terminated.

This means vm.shutdown() is still needed in tearDown() if there are multiple test methods and each of them expects a clean state, but that is probably still less typing (and also indenting) than the with approach, and also easy to remember (otherwise a test will fail).

Quoted 8 lines

I looked into atexit before going this route. atexit does not have an unregister() API in Python 2. This makes it ugly to use because some tests do not want the resource to remain for the duration of the process.

A related point is that the Python objects used by atexit handlers live until the end of the process. They cannot be garbage collected because the atexit handler still has a reference to them.

I think this shortcoming can be solved with a clean up list ("all problems in computer science can be solved by another level of indirection"):

_clean_up_list = set()
def _clean_up_handler():
for i in _clean_up_list:
try:
i()
except:
pass

atexit.register(_clean_up_handler)

class VM(...):

Quoted 7 lines
    def launch():
        ...
        _clean_up_list.add(self.launch)

    def shutdown():
        _clean_up_list.remove(self.launch)
        ...

atexit is still less powerful than context managers because its scope is fixed. Handler functions are only called when the process terminates. Many test cases do not want resources (especially the VMs) around forever because they run several iterations or sub-tests.

Quoted 6 lines

The with statement can be used both for process-lifetime and for more fine-grained scoping. That's why I chose it.

If you stick to atexit then sub-tests or iterations require manual vm.shutdown() - something that is not necessary using the with statement.

Quoted 5 lines

Sure!

I just think that if leftover VM instances are a concern and not all test code are converted to "with", having the atexit handler in addition may provide more robustness.

Okay, I checked this. Existing code doesn't need to be changed (yet) because:

1. Most existing code uses unittest's setUp()/tearDown() and already correctly handles cleanup when the test fails.

2. The LUKS crypto test doesn't use unittest but also doesn't use VM(), so it doesn't need.

Are you happy for me to merge this series?

Stefan

#11 lore raw
Quoted 85 lines · Stefan Hajnoczi
Quoted 75 lines · Fam Zheng
Quoted 67 lines · Stefan Hajnoczi
Quoted 53 lines · Fam Zheng
Quoted 28 lines · Stefan Hajnoczi
Quoted 11 lines · Fam Zheng
Quoted 7 lines · Stefan Hajnoczi

Tests should declare resources upfront in a with statement. Resources are automatically cleaned up whether the test passes or fails:

with FilePath('test.img') as img_path,

       VM() as vm:
      ...test...
  # img_path is deleted and vm is shut down automatically

Looks good but still requires test writers to learn and remember to use FilePath and with.

You cannot forget to use FilePath() unless you love typing at os.path.join(iotests.test_dir, 'test.img'). It's much better than open coding filename generation!

Quoted 10 lines

These are still boilerplates. Here goes my personal oppinion, so may not be plausible:

- For VM() maybe add an atexit in the launch() method also makes sure the VM is eventually terminated.

This means vm.shutdown() is still needed in tearDown() if there are multiple test methods and each of them expects a clean state, but that is probably still less typing (and also indenting) than the with approach, and also easy to remember (otherwise a test will fail).

Quoted 8 lines

I looked into atexit before going this route. atexit does not have an unregister() API in Python 2. This makes it ugly to use because some tests do not want the resource to remain for the duration of the process.

A related point is that the Python objects used by atexit handlers live until the end of the process. They cannot be garbage collected because the atexit handler still has a reference to them.

I think this shortcoming can be solved with a clean up list ("all problems in computer science can be solved by another level of indirection"):

_clean_up_list = set()
def _clean_up_handler():
for i in _clean_up_list:
try:
i()
except:
pass

atexit.register(_clean_up_handler)

class VM(...):

Quoted 7 lines
    def launch():
        ...
        _clean_up_list.add(self.launch)

    def shutdown():
        _clean_up_list.remove(self.launch)
        ...

atexit is still less powerful than context managers because its scope is fixed. Handler functions are only called when the process terminates. Many test cases do not want resources (especially the VMs) around forever because they run several iterations or sub-tests.

Quoted 6 lines

The with statement can be used both for process-lifetime and for more fine-grained scoping. That's why I chose it.

If you stick to atexit then sub-tests or iterations require manual vm.shutdown() - something that is not necessary using the with statement.

Quoted 5 lines

Sure!

I just think that if leftover VM instances are a concern and not all test code are converted to "with", having the atexit handler in addition may provide more robustness.

Okay, I checked this. Existing code doesn't need to be changed (yet) because:

Quoted 7 lines

1. Most existing code uses unittest's setUp()/tearDown() and already correctly handles cleanup when the test fails.

2. The LUKS crypto test doesn't use unittest but also doesn't use VM(), so it doesn't need.

Are you happy for me to merge this series?

Yes. Sounds good! Thanks.

Fam

author Applied
#13 lore raw
In reply to Stefan Hajnoczi
Quoted 20 lines · Stefan Hajnoczi

This series introduces context managers for the two most commonly used
resources: files and VMs. Context managers eliminate the need to call a cleanup function explicitly.

Tests should declare resources upfront in a with statement. Resources are automatically cleaned up whether the test passes or fails:

with FilePath('test.img') as img_path,

       VM() as vm:
      ...test...
  # img_path is deleted and vm is shut down automatically

The final patch converts 194 to use context managers instead of atexit.register(). This makes the code shorter and easier to read.

Stefan Hajnoczi (3):
qemu.py: make VM() a context manager
iotests.py: add FilePath context manager
qemu-iotests: use context managers for resource cleanup in 194

Quoted 8 lines
 scripts/qemu.py               | 16 ++++++++-
 tests/qemu-iotests/194        | 83 +++++++++++++++++++++----------------------
 tests/qemu-iotests/iotests.py | 26 ++++++++++++++
 3 files changed, 82 insertions(+), 43 deletions(-)
Signature · 1 line
2.13.5

Thanks, applied to my block-next tree:
https://github.com/stefanha/qemu/commits/block-next

Stefan