Hi, this series cleans up the Python sources, either static or generated, including also tests, to make them PEP 8 compliant; see https://www.python.org/dev/peps/pep-0008/ and tools like pep8. Almost all the issues reported by pep8 are fixed, reducing the issues from 3818 to 7. The changes should have no effect on the actual code, while it will help Python users with consistency with other Python code. Thanks, Pino Toscano (8): python: PEP 8: adapt whitespaces in lines python: PEP 8: adapt empty lines python: PEP 8: remove trailing semicolons python: PEP 8: break compound statements python: PEP 8: avoid too long lines python: PEP 8: miscellaneous indentation fixes python: PEP 8: avoid whitespace-only lines in docstrings python: PEP 8: miscellaneous coding fixes generator/bindtests.ml | 12 ++-- generator/python.ml | 146 ++++++++++++++++++++++++++------------- generator/python.mli | 8 +++ python/examples/create_disk.py | 36 +++++----- python/examples/inspect_vm.py | 42 +++++------ python/setup.py.in | 69 +++++++++--------- python/t/test010Load.py | 5 +- python/t/test070OptArgs.py | 23 +++--- python/t/test080Version.py | 25 +++---- python/t/test090RetValues.py | 142 ++++++++++++++++++------------------- python/t/test100Launch.py | 25 +++---- python/t/test410CloseEvent.py | 18 ++--- python/t/test420LogMessages.py | 30 ++++---- python/t/test800ExplicitClose.py | 30 ++++---- python/t/test810RHBZ811650.py | 17 ++--- python/t/test820RHBZ912499.py | 58 ++++++++-------- python/t/test910Libvirt.py | 17 ++--- python/t/tests_helper.py | 30 ++++---- tests/http/test-http.py | 143 +++++++++++++++++++------------------- 19 files changed, 473 insertions(+), 403 deletions(-) -- 2.5.5
Pino Toscano
2016-May-04 14:23 UTC
[Libguestfs] [PATCH 1/8] python: PEP 8: adapt whitespaces in lines
Add (after comma) or remove (before opening round bracket, and around '=' in arguments) whitespaces according to the PEP 8 specification. This is just code reformatting, with no behaviour changes; no content changed beside whitespaces, so "git diff -w" gives an empty diff. --- generator/bindtests.ml | 10 +-- generator/python.ml | 70 ++++++++++---------- python/examples/create_disk.py | 36 +++++----- python/examples/inspect_vm.py | 38 +++++------ python/setup.py.in | 70 ++++++++++---------- python/t/test010Load.py | 4 +- python/t/test070OptArgs.py | 22 +++---- python/t/test080Version.py | 24 +++---- python/t/test090RetValues.py | 128 ++++++++++++++++++------------------ python/t/test100Launch.py | 24 +++---- python/t/test410CloseEvent.py | 16 ++--- python/t/test420LogMessages.py | 26 ++++---- python/t/test800ExplicitClose.py | 28 ++++---- python/t/test810RHBZ811650.py | 16 ++--- python/t/test820RHBZ912499.py | 56 ++++++++-------- python/t/test910Libvirt.py | 16 ++--- python/t/tests_helper.py | 26 ++++---- tests/http/test-http.py | 138 +++++++++++++++++++-------------------- 18 files changed, 374 insertions(+), 374 deletions(-) diff --git a/generator/bindtests.ml b/generator/bindtests.ml index bd2600d..c6a4c6b 100644 --- a/generator/bindtests.ml +++ b/generator/bindtests.ml @@ -430,7 +430,7 @@ and generate_python_bindtests () pr "\ import guestfs -g = guestfs.GuestFS () +g = guestfs.GuestFS() "; let mkargs args optargs @@ -446,7 +446,7 @@ g = guestfs.GuestFS () | CallOptString None -> "None" | CallOptString (Some s) -> sprintf "\"%s\"" s | CallStringList xs -> - "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]" + "[" ^ String.concat ", " (List.map (sprintf "\"%s\"") xs) ^ "]" | CallInt i -> string_of_int i | CallInt64 i -> Int64.to_string i | CallBool b -> if b then "1" else "0" @@ -461,16 +461,16 @@ g = guestfs.GuestFS () | CallOString (n, v) -> n ^ "=\"" ^ v ^ "\"" | CallOStringList (n, xs) -> n ^ "=" ^ - "[" ^ String.concat "," (List.map (sprintf "\"%s\"") xs) ^ "]" + "[" ^ String.concat ", " (List.map (sprintf "\"%s\"") xs) ^ "]" ) optargs ) in generate_lang_bindtests ( - fun f args optargs -> pr "g.%s (%s)\n" f (mkargs args optargs) + fun f args optargs -> pr "g.%s(%s)\n" f (mkargs args optargs) ); - pr "print (\"EOF\")\n" + pr "print(\"EOF\")\n" and generate_ruby_bindtests () generate_header HashStyle GPLv2plus; diff --git a/generator/python.ml b/generator/python.ml index 9d9dc4a..a7fa2c5 100644 --- a/generator/python.ml +++ b/generator/python.ml @@ -632,10 +632,10 @@ and generate_python_py () \"\"\"Python bindings for libguestfs import guestfs -g = guestfs.GuestFS (python_return_dict=True) -g.add_drive_opts (\"guest.img\", format=\"raw\") -g.launch () -parts = g.list_partitions () +g = guestfs.GuestFS(python_return_dict=True) +g.add_drive_opts(\"guest.img\", format=\"raw\") +g.launch() +parts = g.list_partitions() The guestfs module provides a Python binding to the libguestfs API for examining and modifying virtual machine disk images. @@ -665,14 +665,14 @@ sequence of calls: # Create the handle, call add_drive* at least once, and possibly # several times if the guest has multiple block devices: -g = guestfs.GuestFS () -g.add_drive_opts (\"guest.img\", format=\"raw\") +g = guestfs.GuestFS() +g.add_drive_opts(\"guest.img\", format=\"raw\") # Launch the qemu subprocess and wait for it to become ready: -g.launch () +g.launch() # Now you can issue commands, for example: -logvols = g.lvs () +logvols = g.lvs() \"\"\" @@ -690,9 +690,9 @@ import libguestfsmod pr "\n"; pr "\ -def event_to_string (events): +def event_to_string(events): \"\"\"Return a printable string from an event or event bitmask\"\"\" - return libguestfsmod.event_to_string (events) + return libguestfsmod.event_to_string(events) class ClosedHandle(ValueError): pass @@ -700,8 +700,8 @@ class ClosedHandle(ValueError): class GuestFS(object): \"\"\"Instances of this class are libguestfs API handles.\"\"\" - def __init__ (self, python_return_dict=False, - environment=True, close_on_exit=True): + def __init__(self, python_return_dict=False, + environment=True, close_on_exit=True): \"\"\"Create a new libguestfs handle. Note about \"python_return_dict\" flag: @@ -718,27 +718,27 @@ class GuestFS(object): flags = 0 if not environment: flags |= 1 if not close_on_exit: flags |= 2 - self._o = libguestfsmod.create (flags) + self._o = libguestfsmod.create(flags) self._python_return_dict = python_return_dict # If we don't do this, the program name is always set to 'python'. - program = os.path.basename (sys.argv[0]) - libguestfsmod.set_program (self._o, program) + program = os.path.basename(sys.argv[0]) + libguestfsmod.set_program(self._o, program) - def __del__ (self): + def __del__(self): if self._o: - libguestfsmod.close (self._o) + libguestfsmod.close(self._o) - def _check_not_closed (self): + def _check_not_closed(self): if not self._o: - raise ClosedHandle (\"GuestFS: method called on closed handle\") + raise ClosedHandle(\"GuestFS: method called on closed handle\") - def _maybe_convert_to_dict (self, r): + def _maybe_convert_to_dict(self, r): if self._python_return_dict == True: - r = dict (r) + r = dict(r) return r - def close (self): + def close(self): \"\"\"Explicitly close the guestfs handle. The handle is closed implicitly when its reference count goes @@ -749,11 +749,11 @@ class GuestFS(object): any method on the handle (except the implicit call to __del__ which happens when the final reference is cleaned up). \"\"\" - self._check_not_closed () - libguestfsmod.close (self._o) + self._check_not_closed() + libguestfsmod.close(self._o) self._o = None - def set_event_callback (self, cb, event_bitmask): + def set_event_callback(self, cb, event_bitmask): \"\"\"Register an event callback. Register \"cb\" as a callback function for all of the @@ -775,20 +775,20 @@ class GuestFS(object): \"guestfs_set_event_callback\" in guestfs(3) before using this function. \"\"\" - self._check_not_closed () - return libguestfsmod.set_event_callback (self._o, cb, event_bitmask) + self._check_not_closed() + return libguestfsmod.set_event_callback(self._o, cb, event_bitmask) - def delete_event_callback (self, event_handle): + def delete_event_callback(self, event_handle): \"\"\"Delete an event callback.\"\"\" - self._check_not_closed () - libguestfsmod.delete_event_callback (self._o, event_handle) + self._check_not_closed() + libguestfsmod.delete_event_callback(self._o, event_handle) "; List.iter ( fun f -> let ret, args, optargs = f.style in - pr " def %s (self" f.name; + pr " def %s(self" f.name; List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args; List.iter ( fun optarg -> @@ -840,12 +840,12 @@ class GuestFS(object): | FileIn _ | FileOut _ | OptString _ | Bool _ | Int _ | Int64 _ | BufferIn _ | GUID _ -> () | StringList n | DeviceList n | FilenameList n -> - pr " %s = list (%s)\n" n n + pr " %s = list(%s)\n" n n | Pointer (_, n) -> pr " %s = %s.c_pointer()\n" n n ) args; - pr " self._check_not_closed ()\n"; - pr " r = libguestfsmod.%s (self._o" f.name; + pr " self._check_not_closed()\n"; + pr " r = libguestfsmod.%s(self._o" f.name; List.iter (fun arg -> pr ", %s" (name_of_argt arg)) (args @ args_of_optargs optargs); pr ")\n"; @@ -855,7 +855,7 @@ class GuestFS(object): *) (match ret with | RHashtable _ -> - pr " r = self._maybe_convert_to_dict (r)\n"; + pr " r = self._maybe_convert_to_dict(r)\n"; | _ -> () ); diff --git a/python/examples/create_disk.py b/python/examples/create_disk.py index ed42e70..f8f6ebc 100644 --- a/python/examples/create_disk.py +++ b/python/examples/create_disk.py @@ -8,56 +8,56 @@ output = "disk.img" # to the constructor. It indicates that your program wants # to receive Python dicts for methods in the API that return # hashtables. -g = guestfs.GuestFS (python_return_dict=True) +g = guestfs.GuestFS(python_return_dict=True) # Create a raw-format sparse disk image, 512 MB in size. -g.disk_create (output, "raw", 512 * 1024 * 1024); +g.disk_create(output, "raw", 512 * 1024 * 1024); # Set the trace flag so that we can see each libguestfs call. -g.set_trace (1) +g.set_trace(1) # Attach the disk image to libguestfs. -g.add_drive_opts (output, format = "raw", readonly = 0) +g.add_drive_opts(output, format="raw", readonly=0) # Run the libguestfs back-end. -g.launch () +g.launch() # Get the list of devices. Because we only added one drive # above, we expect that this list should contain a single # element. -devices = g.list_devices () -assert (len (devices) == 1) +devices = g.list_devices() +assert(len(devices) == 1) # Partition the disk as one single MBR partition. -g.part_disk (devices[0], "mbr") +g.part_disk(devices[0], "mbr") # Get the list of partitions. We expect a single element, which # is the partition we have just created. -partitions = g.list_partitions () -assert (len (partitions) == 1) +partitions = g.list_partitions() +assert(len(partitions) == 1) # Create a filesystem on the partition. -g.mkfs ("ext4", partitions[0]) +g.mkfs("ext4", partitions[0]) # Now mount the filesystem so that we can add files. -g.mount (partitions[0], "/") +g.mount(partitions[0], "/") # Create some files and directories. -g.touch ("/empty") +g.touch("/empty") message = "Hello, world\n" -g.write ("/hello", message) -g.mkdir ("/foo") +g.write("/hello", message) +g.mkdir("/foo") # This one uploads the local file /etc/resolv.conf into # the disk image. -g.upload ("/etc/resolv.conf", "/foo/resolv.conf") +g.upload("/etc/resolv.conf", "/foo/resolv.conf") # Because we wrote to the disk and we want to detect write # errors, call g.shutdown. You don't need to do this: # g.close will do it implicitly. -g.shutdown () +g.shutdown() # Note also that handles are automatically closed if they are # reaped by reference counting. You only need to call close # if you want to close the handle right away. -g.close () +g.close() diff --git a/python/examples/inspect_vm.py b/python/examples/inspect_vm.py index 0bbae78..8bfbbbc 100644 --- a/python/examples/inspect_vm.py +++ b/python/examples/inspect_vm.py @@ -3,55 +3,55 @@ import sys import guestfs -assert (len (sys.argv) == 2) +assert(len(sys.argv) == 2) disk = sys.argv[1] # All new Python code should pass python_return_dict=True # to the constructor. It indicates that your program wants # to receive Python dicts for methods in the API that return # hashtables. -g = guestfs.GuestFS (python_return_dict=True) +g = guestfs.GuestFS(python_return_dict=True) # Attach the disk image read-only to libguestfs. -g.add_drive_opts (disk, readonly=1) +g.add_drive_opts(disk, readonly=1) # Run the libguestfs back-end. -g.launch () +g.launch() # Ask libguestfs to inspect for operating systems. -roots = g.inspect_os () -if len (roots) == 0: - raise (Error ("inspect_vm: no operating systems found")) +roots = g.inspect_os() +if len(roots) == 0: + raise(Error("inspect_vm: no operating systems found")) for root in roots: print "Root device: %s" % root # Print basic information about the operating system. - print " Product name: %s" % (g.inspect_get_product_name (root)) + print " Product name: %s" % (g.inspect_get_product_name(root)) print " Version: %d.%d" % \ - (g.inspect_get_major_version (root), - g.inspect_get_minor_version (root)) - print " Type: %s" % (g.inspect_get_type (root)) - print " Distro: %s" % (g.inspect_get_distro (root)) + (g.inspect_get_major_version(root), + g.inspect_get_minor_version(root)) + print " Type: %s" % (g.inspect_get_type(root)) + print " Distro: %s" % (g.inspect_get_distro(root)) # Mount up the disks, like guestfish -i. # # Sort keys by length, shortest first, so that we end up # mounting the filesystems in the correct order. - mps = g.inspect_get_mountpoints (root) - def compare (a, b): return len(a) - len(b) - for device in sorted (mps.keys(), compare): + mps = g.inspect_get_mountpoints(root) + def compare(a, b): return len(a) - len(b) + for device in sorted(mps.keys(), compare): try: - g.mount_ro (mps[device], device) + g.mount_ro(mps[device], device) except RuntimeError as msg: print "%s (ignored)" % msg # If /etc/issue.net file exists, print up to 3 lines. filename = "/etc/issue.net" - if g.is_file (filename): + if g.is_file(filename): print "--- %s ---" % filename - lines = g.head_n (3, filename) + lines = g.head_n(3, filename) for line in lines: print line # Unmount everything. - g.umount_all () + g.umount_all() diff --git a/python/setup.py.in b/python/setup.py.in index 4d9b949..403c4b5 100644 --- a/python/setup.py.in +++ b/python/setup.py.in @@ -18,45 +18,45 @@ from distutils.core import setup, Extension -setup (name='guestfs', - version='@PACKAGE_VERSION@', +setup(name='guestfs', + version='@PACKAGE_VERSION@', - description='access and modify virtual machine disk images', - long_description=""" + description='access and modify virtual machine disk images', + long_description=""" libguestfs is a library and set of tools for accessing and modifying virtual machine (VM) disk images. This package contains the Python bindings for libguestfs. """, - author='The @PACKAGE_NAME@ team', - author_email='libguestfs@redhat.com', - url='http://libguestfs.org', - - license='LGPLv2+', - - classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Environment :: Console', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+)', - 'Operating System :: POSIX :: Linux', - 'Programming Language :: C', - 'Programming Language :: Python :: 2', - 'Programming Language :: Python :: 3', - 'Programming Language :: Python :: Implementation :: CPython', - 'Topic :: Utilities', - ], - - py_modules=['guestfs'], - ext_modules=[ - Extension ( - 'libguestfsmod', - ['guestfs-py-byhand.c', 'guestfs-py.c', 'utils.c'], - - include_dirs=['.', '../src'], - libraries=['guestfs'], - define_macros=[('GUESTFS_PRIVATE', '1')], - ) - ] - ) + author='The @PACKAGE_NAME@ team', + author_email='libguestfs@redhat.com', + url='http://libguestfs.org', + + license='LGPLv2+', + + classifiers=[ + 'Development Status :: 5 - Production/Stable', + 'Environment :: Console', + 'Intended Audience :: Developers', + 'License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+)', + 'Operating System :: POSIX :: Linux', + 'Programming Language :: C', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: Implementation :: CPython', + 'Topic :: Utilities', + ], + + py_modules=['guestfs'], + ext_modules=[ + Extension( + 'libguestfsmod', + ['guestfs-py-byhand.c', 'guestfs-py.c', 'utils.c'], + + include_dirs=['.', '../src'], + libraries=['guestfs'], + define_macros=[('GUESTFS_PRIVATE', '1')], + ) + ] +) diff --git a/python/t/test010Load.py b/python/t/test010Load.py index 1e6ea4d..cbc799b 100644 --- a/python/t/test010Load.py +++ b/python/t/test010Load.py @@ -17,6 +17,6 @@ import unittest -class Test010Load (unittest.TestCase): - def test_import (self): +class Test010Load(unittest.TestCase): + def test_import(self): import guestfs diff --git a/python/t/test070OptArgs.py b/python/t/test070OptArgs.py index 2cf1ea9..ba3a9e9 100644 --- a/python/t/test070OptArgs.py +++ b/python/t/test070OptArgs.py @@ -19,18 +19,18 @@ import unittest import os import guestfs -class Test070OptArgs (unittest.TestCase): - def setUp (self): - self.g = guestfs.GuestFS (python_return_dict=True) +class Test070OptArgs(unittest.TestCase): + def setUp(self): + self.g = guestfs.GuestFS(python_return_dict=True) - def test_no_optargs (self): - self.g.add_drive ("/dev/null") + def test_no_optargs(self): + self.g.add_drive("/dev/null") - def test_one_optarg (self): - self.g.add_drive ("/dev/null", readonly = True) + def test_one_optarg(self): + self.g.add_drive("/dev/null", readonly=True) - def test_two_optargs (self): - self.g.add_drive ("/dev/null", iface = "virtio", format = "raw") + def test_two_optargs(self): + self.g.add_drive("/dev/null", iface="virtio", format="raw") - def tearDown (self): - self.g.close () + def tearDown(self): + self.g.close() diff --git a/python/t/test080Version.py b/python/t/test080Version.py index 42ef56e..080c24b 100644 --- a/python/t/test080Version.py +++ b/python/t/test080Version.py @@ -21,19 +21,19 @@ import os import guestfs from .tests_helper import * -class Test080Version (unittest.TestCase): - def setUp (self): - self.g = guestfs.GuestFS (python_return_dict=True) - self.version = self.g.version () +class Test080Version(unittest.TestCase): + def setUp(self): + self.g = guestfs.GuestFS(python_return_dict=True) + self.version = self.g.version() - def test_major (self): - self.assertEqual (self.version['major'], 1) + def test_major(self): + self.assertEqual(self.version['major'], 1) - def test_minor (self): - self.assertIsInstance (self.version['minor'], int_type) + def test_minor(self): + self.assertIsInstance(self.version['minor'], int_type) - def test_release (self): - self.assertIsInstance (self.version['release'], int_type) + def test_release(self): + self.assertIsInstance(self.version['release'], int_type) - def test_extra (self): - self.assertIsInstance (self.version['extra'], str) + def test_extra(self): + self.assertIsInstance(self.version['extra'], str) diff --git a/python/t/test090RetValues.py b/python/t/test090RetValues.py index 24d97b4..bb10ce3 100644 --- a/python/t/test090RetValues.py +++ b/python/t/test090RetValues.py @@ -22,114 +22,114 @@ import guestfs from .tests_helper import * -class Test090PythonRetValues (unittest.TestCase): - def test_rint (self): - g = guestfs.GuestFS () +class Test090PythonRetValues(unittest.TestCase): + def test_rint(self): + g = guestfs.GuestFS() - self.assertAlmostEqual (g.internal_test_rint ("10"), 10, places=1) + self.assertAlmostEqual(g.internal_test_rint("10"), 10, places=1) - self.assertRaises (RuntimeError, g.internal_test_rinterr) + self.assertRaises(RuntimeError, g.internal_test_rinterr) - def test_rint64 (self): - g = guestfs.GuestFS () + def test_rint64(self): + g = guestfs.GuestFS() - self.assertAlmostEqual (g.internal_test_rint64 ("10"), int_type (10), places=1) + self.assertAlmostEqual(g.internal_test_rint64("10"), int_type(10), places=1) - self.assertRaises (RuntimeError, g.internal_test_rint64err) + self.assertRaises(RuntimeError, g.internal_test_rint64err) - def test_rbool (self): - g = guestfs.GuestFS () + def test_rbool(self): + g = guestfs.GuestFS() - self.assertTrue (g.internal_test_rbool ("true")) - self.assertFalse (g.internal_test_rbool ("false")) + self.assertTrue(g.internal_test_rbool("true")) + self.assertFalse(g.internal_test_rbool("false")) - self.assertRaises (RuntimeError, g.internal_test_rboolerr) + self.assertRaises(RuntimeError, g.internal_test_rboolerr) - def test_rconststring (self): - g = guestfs.GuestFS () + def test_rconststring(self): + g = guestfs.GuestFS() - self.assertEqual (g.internal_test_rconststring ("test"), "static string") + self.assertEqual(g.internal_test_rconststring("test"), "static string") - self.assertRaises (RuntimeError, g.internal_test_rconststringerr) + self.assertRaises(RuntimeError, g.internal_test_rconststringerr) - def test_rconstoptstring (self): - g = guestfs.GuestFS () + def test_rconstoptstring(self): + g = guestfs.GuestFS() - self.assertEqual (g.internal_test_rconstoptstring ("test"), "static string") + self.assertEqual(g.internal_test_rconstoptstring("test"), "static string") # this never fails - self.assertIsNone (g.internal_test_rconstoptstringerr ()) + self.assertIsNone(g.internal_test_rconstoptstringerr()) - def test_rstring (self): - g = guestfs.GuestFS () + def test_rstring(self): + g = guestfs.GuestFS() - self.assertEqual (g.internal_test_rstring ("test"), "test") + self.assertEqual(g.internal_test_rstring("test"), "test") - self.assertRaises (RuntimeError, g.internal_test_rstringerr) + self.assertRaises(RuntimeError, g.internal_test_rstringerr) - def test_rstringlist (self): - g = guestfs.GuestFS () + def test_rstringlist(self): + g = guestfs.GuestFS() - self.assertEqual (g.internal_test_rstringlist ("0"), []) - self.assertEqual (g.internal_test_rstringlist ("5"), ["0", "1", "2", "3", "4"]) + self.assertEqual(g.internal_test_rstringlist("0"), []) + self.assertEqual(g.internal_test_rstringlist("5"), ["0", "1", "2", "3", "4"]) - self.assertRaises (RuntimeError, g.internal_test_rstringlisterr) + self.assertRaises(RuntimeError, g.internal_test_rstringlisterr) - def test_rstruct (self): - g = guestfs.GuestFS () + def test_rstruct(self): + g = guestfs.GuestFS() - s = g.internal_test_rstruct ("unused") - self.assertIsInstance (s, dict) - self.assertEqual (s["pv_name"], "pv0") + s = g.internal_test_rstruct("unused") + self.assertIsInstance(s, dict) + self.assertEqual(s["pv_name"], "pv0") - self.assertRaises (RuntimeError, g.internal_test_rstructerr) + self.assertRaises(RuntimeError, g.internal_test_rstructerr) - def test_rstructlist (self): - g = guestfs.GuestFS () + def test_rstructlist(self): + g = guestfs.GuestFS() - self.assertEqual (g.internal_test_rstructlist ("0"), []) - l = g.internal_test_rstructlist ("5") - self.assertIsInstance (l, list) - self.assertEqual (len (l), 5) - for i in range (0, 5): - self.assertIsInstance (l[i], dict) - self.assertEqual (l[i]["pv_name"], "pv%d" % i) + self.assertEqual(g.internal_test_rstructlist("0"), []) + l = g.internal_test_rstructlist("5") + self.assertIsInstance(l, list) + self.assertEqual(len(l), 5) + for i in range(0, 5): + self.assertIsInstance(l[i], dict) + self.assertEqual(l[i]["pv_name"], "pv%d" % i) - self.assertRaises (RuntimeError, g.internal_test_rstructlisterr) + self.assertRaises(RuntimeError, g.internal_test_rstructlisterr) - def test_rhashtable_list (self): - g = guestfs.GuestFS (python_return_dict=False) + def test_rhashtable_list(self): + g = guestfs.GuestFS(python_return_dict=False) - self.assertEqual (g.internal_test_rhashtable ("0"), []) - r = g.internal_test_rhashtable ("5") - self.assertEqual (r, [ ("0","0"), ("1","1"), ("2","2"), - ("3","3"), ("4","4") ]) + self.assertEqual(g.internal_test_rhashtable("0"), []) + r = g.internal_test_rhashtable("5") + self.assertEqual(r, [("0", "0"), ("1", "1"), ("2", "2"), + ("3", "3"), ("4", "4")]) - self.assertRaises (RuntimeError, g.internal_test_rhashtableerr) + self.assertRaises(RuntimeError, g.internal_test_rhashtableerr) - def test_rhashtable_dict (self): - g = guestfs.GuestFS (python_return_dict=True) + def test_rhashtable_dict(self): + g = guestfs.GuestFS(python_return_dict=True) - self.assertEqual (g.internal_test_rhashtable ("0"), {}) - r = g.internal_test_rhashtable ("5") - self.assertEqual (r, {"0": "0", "1": "1", "2": "2", "3": "3", "4": "4"}) + self.assertEqual(g.internal_test_rhashtable("0"), {}) + r = g.internal_test_rhashtable("5") + self.assertEqual(r, {"0": "0", "1": "1", "2": "2", "3": "3", "4": "4"}) - self.assertRaises (RuntimeError, g.internal_test_rhashtableerr) + self.assertRaises(RuntimeError, g.internal_test_rhashtableerr) - def test_rbufferout (self): - g = guestfs.GuestFS () + def test_rbufferout(self): + g = guestfs.GuestFS() - self.assertEqual (g.internal_test_rbufferout ("test"), b'test') + self.assertEqual(g.internal_test_rbufferout("test"), b'test') - self.assertRaises (RuntimeError, g.internal_test_rbufferouterr) + self.assertRaises(RuntimeError, g.internal_test_rbufferouterr) diff --git a/python/t/test100Launch.py b/python/t/test100Launch.py index 8cd2a54..5d78ccc 100644 --- a/python/t/test100Launch.py +++ b/python/t/test100Launch.py @@ -19,16 +19,16 @@ import unittest import os import guestfs -class Test100Launch (unittest.TestCase): - def test_launch (self): - g = guestfs.GuestFS (python_return_dict=True) - g.add_drive_scratch (500 * 1024 * 1024) - g.launch () +class Test100Launch(unittest.TestCase): + def test_launch(self): + g = guestfs.GuestFS(python_return_dict=True) + g.add_drive_scratch(500 * 1024 * 1024) + g.launch() - g.pvcreate ("/dev/sda") - g.vgcreate ("VG", ["/dev/sda"]) - g.lvcreate ("LV1", "VG", 200) - g.lvcreate ("LV2", "VG", 200) - self.assertEqual (g.lvs (), ["/dev/VG/LV1", "/dev/VG/LV2"]) - g.shutdown () - g.close () + g.pvcreate("/dev/sda") + g.vgcreate("VG", ["/dev/sda"]) + g.lvcreate("LV1", "VG", 200) + g.lvcreate("LV2", "VG", 200) + self.assertEqual(g.lvs(), ["/dev/VG/LV1", "/dev/VG/LV2"]) + g.shutdown() + g.close() diff --git a/python/t/test410CloseEvent.py b/python/t/test410CloseEvent.py index f541f01..bc007e1 100644 --- a/python/t/test410CloseEvent.py +++ b/python/t/test410CloseEvent.py @@ -21,18 +21,18 @@ import guestfs close_invoked = 0 -def close_callback (ev, eh, buf, array): +def close_callback(ev, eh, buf, array): global close_invoked close_invoked += 1 -class Test410CloseEvent (unittest.TestCase): - def test_close_event (self): - g = guestfs.GuestFS (python_return_dict=True) +class Test410CloseEvent(unittest.TestCase): + def test_close_event(self): + g = guestfs.GuestFS(python_return_dict=True) # Register a callback for the close event. - g.set_event_callback (close_callback, guestfs.EVENT_CLOSE) + g.set_event_callback(close_callback, guestfs.EVENT_CLOSE) # Close the handle. The close callback should be invoked. - self.assertEqual (close_invoked, 0) - g.close () - self.assertEqual (close_invoked, 1) + self.assertEqual(close_invoked, 0) + g.close() + self.assertEqual(close_invoked, 1) diff --git a/python/t/test420LogMessages.py b/python/t/test420LogMessages.py index 69312ed..56c9500 100644 --- a/python/t/test420LogMessages.py +++ b/python/t/test420LogMessages.py @@ -21,7 +21,7 @@ import guestfs log_invoked = 0 -def log_callback (ev,eh,buf,array): +def log_callback(ev, eh, buf, array): global log_invoked log_invoked += 1 @@ -29,26 +29,26 @@ def log_callback (ev,eh,buf,array): buf = buf.rstrip() # Log what happened. - print ("python event logged: event=%s eh=%d buf='%s' array=%s" % - (guestfs.event_to_string (ev), eh, buf, array)) + print("python event logged: event=%s eh=%d buf='%s' array=%s" % + (guestfs.event_to_string(ev), eh, buf, array)) -class Test420LogMessages (unittest.TestCase): - def test_log_messages (self): - g = guestfs.GuestFS (python_return_dict=True) +class Test420LogMessages(unittest.TestCase): + def test_log_messages(self): + g = guestfs.GuestFS(python_return_dict=True) # Register an event callback for all log messages. events = guestfs.EVENT_APPLIANCE | guestfs.EVENT_LIBRARY \ | guestfs.EVENT_WARNING | guestfs.EVENT_TRACE - g.set_event_callback (log_callback, events) + g.set_event_callback(log_callback, events) # Now make sure we see some messages. - g.set_trace (1) - g.set_verbose (1) + g.set_trace(1) + g.set_verbose(1) # Do some stuff. - g.add_drive_ro ("/dev/null") - g.set_autosync (1) + g.add_drive_ro("/dev/null") + g.set_autosync(1) - g.close () + g.close() - self.assertNotEqual (log_invoked, 0) + self.assertNotEqual(log_invoked, 0) diff --git a/python/t/test800ExplicitClose.py b/python/t/test800ExplicitClose.py index 15b15fb..a8ec8bd 100644 --- a/python/t/test800ExplicitClose.py +++ b/python/t/test800ExplicitClose.py @@ -23,32 +23,32 @@ import guestfs close_invoked = 0 -def close_callback (ev, eh, buf, array): +def close_callback(ev, eh, buf, array): global close_invoked close_invoked += 1 -class Test800ExplicitClose (unittest.TestCase): - def test_explicit_close (self): - g = guestfs.GuestFS (python_return_dict=True) +class Test800ExplicitClose(unittest.TestCase): + def test_explicit_close(self): + g = guestfs.GuestFS(python_return_dict=True) - g.close () # explicit close + g.close() # explicit close del g # implicit close - should be no error/warning # Expect an exception if we call a method on a closed handle. - g = guestfs.GuestFS (python_return_dict=True) - g.close () - self.assertRaises (guestfs.ClosedHandle, g.set_memsize, 512) + g = guestfs.GuestFS(python_return_dict=True) + g.close() + self.assertRaises(guestfs.ClosedHandle, g.set_memsize, 512) del g # Verify that the handle is really being closed by g.close, by # setting up a close event and testing that it happened. - g = guestfs.GuestFS (python_return_dict=True) + g = guestfs.GuestFS(python_return_dict=True) - g.set_event_callback (close_callback, guestfs.EVENT_CLOSE) + g.set_event_callback(close_callback, guestfs.EVENT_CLOSE) - self.assertEqual (close_invoked, 0) - g.close () - self.assertEqual (close_invoked, 1) + self.assertEqual(close_invoked, 0) + g.close() + self.assertEqual(close_invoked, 1) del g - self.assertEqual (close_invoked, 1) + self.assertEqual(close_invoked, 1) diff --git a/python/t/test810RHBZ811650.py b/python/t/test810RHBZ811650.py index 6dc2da1..4a1192c 100644 --- a/python/t/test810RHBZ811650.py +++ b/python/t/test810RHBZ811650.py @@ -19,19 +19,19 @@ import unittest import os import guestfs -class Test810RHBZ811650 (unittest.TestCase): - def test_rhbz811650 (self): - g = guestfs.GuestFS (python_return_dict=True) +class Test810RHBZ811650(unittest.TestCase): + def test_rhbz811650(self): + g = guestfs.GuestFS(python_return_dict=True) - g.disk_create ("rhbz811650.img", "raw", 500 * 1024 * 1024) + g.disk_create("rhbz811650.img", "raw", 500 * 1024 * 1024) # Deliberate error: the disk format is supposed to be raw. - g.add_drive ("rhbz811650.img", format="qcow2"); + g.add_drive("rhbz811650.img", format="qcow2"); # Because error() wasn't being called, guestfs_last_error # would return NULL, causing a segfault in the Python bindings # (RHBZ#811650). - self.assertRaises (RuntimeError, g.launch) + self.assertRaises(RuntimeError, g.launch) - def tearDown (self): - os.unlink ("rhbz811650.img") + def tearDown(self): + os.unlink("rhbz811650.img") diff --git a/python/t/test820RHBZ912499.py b/python/t/test820RHBZ912499.py index ac381d0..c315c66 100644 --- a/python/t/test820RHBZ912499.py +++ b/python/t/test820RHBZ912499.py @@ -28,19 +28,19 @@ import sys import guestfs from .tests_helper import * -@skipUnlessArchMatches ("(i.86|x86_64)") # If the architecture doesn't support IDE, skip the test. -@skipUnlessGuestfsBackendIs ('libvirt') -@skipUnlessLibvirtHasCPointer () -class Test820RHBZ912499 (unittest.TestCase): - def setUp (self): +@skipUnlessArchMatches("(i.86|x86_64)") # If the architecture doesn't support IDE, skip the test. +@skipUnlessGuestfsBackendIs('libvirt') +@skipUnlessLibvirtHasCPointer() +class Test820RHBZ912499(unittest.TestCase): + def setUp(self): # Create a test disk. - self.filename = os.getcwd () + "/820-rhbz912499.img" - guestfs.GuestFS().disk_create (self.filename, "raw", 1024*1024*1024) + self.filename = os.getcwd() + "/820-rhbz912499.img" + guestfs.GuestFS().disk_create(self.filename, "raw", 1024*1024*1024) # Create a new domain. This won't work, it will just hang when # booted. But that's sufficient for the test. - self.domname = ''.join (random.choice (string.ascii_uppercase) - for _ in range (8)) + self.domname = ''.join(random.choice(string.ascii_uppercase) + for _ in range(8)) self.domname = "tmp-" + self.domname self.xml = """ @@ -62,33 +62,33 @@ class Test820RHBZ912499 (unittest.TestCase): </domain> """ % (self.domname, self.filename) - def test_rhbz912499 (self): + def test_rhbz912499(self): import libvirt - conn = libvirt.open (None) - dom = conn.createXML (self.xml, - libvirt.VIR_DOMAIN_START_AUTODESTROY) - self.assertIsNotNone (dom) + conn = libvirt.open(None) + dom = conn.createXML(self.xml, + libvirt.VIR_DOMAIN_START_AUTODESTROY) + self.assertIsNotNone(dom) - print ("temporary domain %s is running" % self.domname) + print("temporary domain %s is running" % self.domname) # Libvirt should have labelled the disk. - print ("before starting libguestfs") - before = check_output (["ls", "-Z", self.filename]) - print ("disk label = %s" % before) + print("before starting libguestfs") + before = check_output(["ls", "-Z", self.filename]) + print("disk label = %s" % before) # Now see if we can open the domain with libguestfs without # disturbing the label. - g = guestfs.GuestFS () - r = g.add_libvirt_dom (dom, readonly = 1) - self.assertEqual (r, 1) - g.launch () + g = guestfs.GuestFS() + r = g.add_libvirt_dom(dom, readonly=1) + self.assertEqual(r, 1) + g.launch() - print ("after starting libguestfs") - after = check_output (["ls", "-Z", self.filename]) - print ("disk label = %s" % after) + print("after starting libguestfs") + after = check_output(["ls", "-Z", self.filename]) + print("disk label = %s" % after) - self.assertEqual (before, after) + self.assertEqual(before, after) - def tearDown (self): - os.unlink (self.filename) + def tearDown(self): + os.unlink(self.filename) diff --git a/python/t/test910Libvirt.py b/python/t/test910Libvirt.py index 7a52454..a84963f 100644 --- a/python/t/test910Libvirt.py +++ b/python/t/test910Libvirt.py @@ -28,15 +28,15 @@ from .tests_helper import * guestsdir = os.environ['guestsdir'] -@skipUnlessLibvirtHasCPointer () -class Test910Libvirt (unittest.TestCase): - def test_libvirt (self): +@skipUnlessLibvirtHasCPointer() +class Test910Libvirt(unittest.TestCase): + def test_libvirt(self): import libvirt - conn = libvirt.open ("test:///%s/guests.xml" % guestsdir) - dom = conn.lookupByName ("blank-disk") + conn = libvirt.open("test:///%s/guests.xml" % guestsdir) + dom = conn.lookupByName("blank-disk") - g = guestfs.GuestFS () + g = guestfs.GuestFS() - r = g.add_libvirt_dom (dom, readonly=1) - self.assertEqual (r, 1) + r = g.add_libvirt_dom(dom, readonly=1) + self.assertEqual(r, 1) diff --git a/python/t/tests_helper.py b/python/t/tests_helper.py index c32e231..f47b157 100644 --- a/python/t/tests_helper.py +++ b/python/t/tests_helper.py @@ -27,7 +27,7 @@ else: int_type = long -def skipUnlessLibvirtHasCPointer (): +def skipUnlessLibvirtHasCPointer(): """ Skip the current class/method if: (a) libvirt cannot be imported (e.g. not installed) @@ -36,35 +36,35 @@ def skipUnlessLibvirtHasCPointer (): try: import libvirt except: - return unittest.skip ("could not import libvirt") + return unittest.skip("could not import libvirt") # Check we're using the version of libvirt-python that has c_pointer() methods. - if not "c_pointer" in dir (libvirt.open (None)): - return unittest.skip ("libvirt-python doesn't support c_pointer()") + if not "c_pointer" in dir(libvirt.open(None)): + return unittest.skip("libvirt-python doesn't support c_pointer()") return lambda func: func -def skipUnlessGuestfsBackendIs (wanted): +def skipUnlessGuestfsBackendIs(wanted): """ Skip the current class/method if the default backend of libguestfs is not 'wanted'. """ import guestfs - backend = guestfs.GuestFS ().get_backend () + backend = guestfs.GuestFS().get_backend() # Match both "backend" and "backend:etc" - if not (backend == wanted or backend.startswith (wanted + ":")): - return unittest.skip ("the current backend is not %s" % wanted) + if not (backend == wanted or backend.startswith(wanted + ":")): + return unittest.skip("the current backend is not %s" % wanted) return lambda func: func -def skipUnlessArchMatches (arch_re): +def skipUnlessArchMatches(arch_re): """ Skip the current class/method if the current architecture does not match the regexp specified. """ import platform import re - machine = platform.machine () - rex = re.compile (arch_re) - if not rex.match (machine): - return unittest.skip ("the current architecture (%s) does not match '%s'" % (machine, arch_re)) + machine = platform.machine() + rex = re.compile(arch_re) + if not rex.match(machine): + return unittest.skip("the current architecture (%s) does not match '%s'" % (machine, arch_re)) return lambda func: func diff --git a/tests/http/test-http.py b/tests/http/test-http.py index 8606c22..fa263a0 100755 --- a/tests/http/test-http.py +++ b/tests/http/test-http.py @@ -31,82 +31,82 @@ listen_addr = "localhost" connect_addr = "localhost" #connect_addr = "127.0.0.1" -if os.getenv ('SKIP_TEST_HTTP_PY'): +if os.getenv('SKIP_TEST_HTTP_PY'): print >>sys.stderr, \ ("%s: test skipped because environment variable is set" % progname) - exit (77) + exit(77) # Proxy settings can break this test. del os.environ['http_proxy'] # Remove the stamp file. stampfile = "%s/stamp-test-http" % os.getcwd() -def unlink_stampfile (): +def unlink_stampfile(): try: - os.unlink (stampfile) + os.unlink(stampfile) except: pass -unlink_stampfile () +unlink_stampfile() # Choose a random port number. # XXX Should check it is not in use. -port = randint (60000, 65000) +port = randint(60000, 65000) -pid = os.fork () +pid = os.fork() if pid > 0: # Parent (client). import guestfs # Make sure that the child (HTTP server) is killed on exit even if # we exit abnormally. - def cleanup (): - unlink_stampfile () + def cleanup(): + unlink_stampfile() if pid > 0: - os.kill (pid, 15) + os.kill(pid, 15) sys.exitfunc = cleanup # Wait for the child to touch the stamp file to indicate it has # started listening for requests. - for i in range (1, 10): - if os.access (stampfile, os.F_OK): + for i in range(1, 10): + if os.access(stampfile, os.F_OK): break - sleep (1) + sleep(1) if i == 3: - print ("%s: waiting for the web server to start up ..." % progname) - if not os.access (stampfile, os.F_OK): + print("%s: waiting for the web server to start up ..." % progname) + if not os.access(stampfile, os.F_OK): print >>sys.stderr, \ ("%s: error: web server process did not start up" % progname) - exit (1) + exit(1) # Create libguestfs handle and connect to the web server. - g = guestfs.GuestFS (python_return_dict=True) + g = guestfs.GuestFS(python_return_dict=True) server = "%s:%d" % (connect_addr, port) - g.add_drive_opts ("/fedora.img", readonly=True, format="raw", - protocol="http", server=[server]) - g.launch () + g.add_drive_opts("/fedora.img", readonly=True, format="raw", + protocol="http", server=[server]) + g.launch() # Inspection is quite a thorough test. - roots = g.inspect_os () - if len (roots) == 0: + roots = g.inspect_os() + if len(roots) == 0: print >>sys.stderr, \ ("%s: error: inspection failed to find any OSes in guest image" % progname) - exit (1) - if len (roots) > 1: + exit(1) + if len(roots) > 1: print >>sys.stderr, \ ("%s: error: inspection found a multi-boot OS which is not expected" % progname) - exit (1) + exit(1) - type_ = g.inspect_get_type (roots[0]) - distro = g.inspect_get_distro (roots[0]) + type_ = g.inspect_get_type(roots[0]) + distro = g.inspect_get_distro(roots[0]) if type_ != "linux" or distro != "fedora": print >>sys.stderr, \ ("%s: error: inspection found wrong OS type (%s, %s)" % (progname, type_, distro)) - exit (1) + exit(1) - g.close () + g.close() else: # Child (HTTP server). @@ -114,77 +114,77 @@ else: from SimpleHTTPServer import SimpleHTTPRequestHandler from SocketServer import ThreadingMixIn - os.chdir (guestsdir) + os.chdir(guestsdir) - class ThreadingServer (ThreadingMixIn, HTTPServer): + class ThreadingServer(ThreadingMixIn, HTTPServer): pass # This is an extended version of SimpleHTTPRequestHandler that can # handle byte ranges. See also: # https://naclports.googlecode.com/svn/trunk/src/httpd.py - class ByteRangeRequestHandler (SimpleHTTPRequestHandler): - def do_GET (self): + class ByteRangeRequestHandler(SimpleHTTPRequestHandler): + def do_GET(self): if 'Range' in self.headers: - m = re.match ('\s*bytes\s*=\s*(\d+)\s*-\s*(\d+)\s*', - self.headers['Range']) + m = re.match('\s*bytes\s*=\s*(\d+)\s*-\s*(\d+)\s*', + self.headers['Range']) if m: - start = int (m.group (1)) - end = int (m.group (2)) + start = int(m.group(1)) + end = int(m.group(2)) length = end - start + 1 - f = self.send_head_partial (start, length) + f = self.send_head_partial(start, length) if f: - f.seek (start, os.SEEK_CUR) - shutil.copyfileobj (f, self.wfile, length) - f.close () + f.seek(start, os.SEEK_CUR) + shutil.copyfileobj(f, self.wfile, length) + f.close() return - return SimpleHTTPRequestHandler.do_GET (self) + return SimpleHTTPRequestHandler.do_GET(self) - def send_head_partial (self, offset, length): + def send_head_partial(self, offset, length): path = self.translate_path(self.path) f = None - if os.path.isdir (path): - if not self.path.endswith ('/'): + if os.path.isdir(path): + if not self.path.endswith('/'): # redirect browser - doing basically what apache does - self.send_response (301) - self.send_header ("Location", self.path + "/") - self.end_headers () + self.send_response(301) + self.send_header("Location", self.path + "/") + self.end_headers() return None for index in "index.html", "index.htm": - index = os.path.join (path, index) - if os.path.exists (index): + index = os.path.join(path, index) + if os.path.exists(index): path = index break else: - return self.list_directory (path) - ctype = self.guess_type (path) + return self.list_directory(path) + ctype = self.guess_type(path) try: - f = open (path, 'rb') + f = open(path, 'rb') except IOError: - self.send_error (404, "File not found") + self.send_error(404, "File not found") return None - self.send_response (206, 'Partial content') - self.send_header ("Content-Range", str(offset) + '-' + - str(length+offset-1)) - self.send_header ("Content-Length", str(length)) - self.send_header ("Content-type", ctype) - fs = os.fstat (f.fileno()) - self.send_header ("Last-Modified", - self.date_time_string(fs.st_mtime)) + self.send_response(206, 'Partial content') + self.send_header("Content-Range", str(offset) + '-' + + str(length+offset-1)) + self.send_header("Content-Length", str(length)) + self.send_header("Content-type", ctype) + fs = os.fstat(f.fileno()) + self.send_header("Last-Modified", + self.date_time_string(fs.st_mtime)) self.end_headers() return f server_address = (listen_addr, port) - httpd = ThreadingServer (server_address, ByteRangeRequestHandler) + httpd = ThreadingServer(server_address, ByteRangeRequestHandler) - sa = httpd.socket.getsockname () - print ("%s: serving %s on %s port %d ..." % (progname, - os.getcwd(), sa[0], sa[1])) + sa = httpd.socket.getsockname() + print("%s: serving %s on %s port %d ..." % (progname, + os.getcwd(), sa[0], sa[1])) # Touch the stamp file, which starts the client. - open (stampfile, 'a') + open(stampfile, 'a') # Start serving until killed. - httpd.serve_forever () + httpd.serve_forever() - os._exit (0) + os._exit(0) -- 2.5.5
Pino Toscano
2016-May-04 14:23 UTC
[Libguestfs] [PATCH 2/8] python: PEP 8: adapt empty lines
Add or remove empty lines to match the needed ones around blocks/functions/etc. This is just formatting, no behaviour changes. --- generator/python.ml | 2 ++ python/t/test010Load.py | 1 + python/t/test070OptArgs.py | 1 + python/t/test080Version.py | 1 + python/t/test090RetValues.py | 11 ----------- python/t/test100Launch.py | 1 + python/t/test410CloseEvent.py | 2 ++ python/t/test420LogMessages.py | 2 ++ python/t/test800ExplicitClose.py | 2 ++ python/t/test810RHBZ811650.py | 1 + python/t/test820RHBZ912499.py | 1 + python/t/test910Libvirt.py | 1 + tests/http/test-http.py | 1 + 13 files changed, 16 insertions(+), 11 deletions(-) diff --git a/generator/python.ml b/generator/python.ml index a7fa2c5..8da36bc 100644 --- a/generator/python.ml +++ b/generator/python.ml @@ -694,9 +694,11 @@ def event_to_string(events): \"\"\"Return a printable string from an event or event bitmask\"\"\" return libguestfsmod.event_to_string(events) + class ClosedHandle(ValueError): pass + class GuestFS(object): \"\"\"Instances of this class are libguestfs API handles.\"\"\" diff --git a/python/t/test010Load.py b/python/t/test010Load.py index cbc799b..97a34da 100644 --- a/python/t/test010Load.py +++ b/python/t/test010Load.py @@ -17,6 +17,7 @@ import unittest + class Test010Load(unittest.TestCase): def test_import(self): import guestfs diff --git a/python/t/test070OptArgs.py b/python/t/test070OptArgs.py index ba3a9e9..2f07ab0 100644 --- a/python/t/test070OptArgs.py +++ b/python/t/test070OptArgs.py @@ -19,6 +19,7 @@ import unittest import os import guestfs + class Test070OptArgs(unittest.TestCase): def setUp(self): self.g = guestfs.GuestFS(python_return_dict=True) diff --git a/python/t/test080Version.py b/python/t/test080Version.py index 080c24b..4fc791a 100644 --- a/python/t/test080Version.py +++ b/python/t/test080Version.py @@ -21,6 +21,7 @@ import os import guestfs from .tests_helper import * + class Test080Version(unittest.TestCase): def setUp(self): self.g = guestfs.GuestFS(python_return_dict=True) diff --git a/python/t/test090RetValues.py b/python/t/test090RetValues.py index bb10ce3..c310cf1 100644 --- a/python/t/test090RetValues.py +++ b/python/t/test090RetValues.py @@ -30,7 +30,6 @@ class Test090PythonRetValues(unittest.TestCase): self.assertRaises(RuntimeError, g.internal_test_rinterr) - def test_rint64(self): g = guestfs.GuestFS() @@ -38,7 +37,6 @@ class Test090PythonRetValues(unittest.TestCase): self.assertRaises(RuntimeError, g.internal_test_rint64err) - def test_rbool(self): g = guestfs.GuestFS() @@ -47,7 +45,6 @@ class Test090PythonRetValues(unittest.TestCase): self.assertRaises(RuntimeError, g.internal_test_rboolerr) - def test_rconststring(self): g = guestfs.GuestFS() @@ -55,7 +52,6 @@ class Test090PythonRetValues(unittest.TestCase): self.assertRaises(RuntimeError, g.internal_test_rconststringerr) - def test_rconstoptstring(self): g = guestfs.GuestFS() @@ -64,7 +60,6 @@ class Test090PythonRetValues(unittest.TestCase): # this never fails self.assertIsNone(g.internal_test_rconstoptstringerr()) - def test_rstring(self): g = guestfs.GuestFS() @@ -72,7 +67,6 @@ class Test090PythonRetValues(unittest.TestCase): self.assertRaises(RuntimeError, g.internal_test_rstringerr) - def test_rstringlist(self): g = guestfs.GuestFS() @@ -81,7 +75,6 @@ class Test090PythonRetValues(unittest.TestCase): self.assertRaises(RuntimeError, g.internal_test_rstringlisterr) - def test_rstruct(self): g = guestfs.GuestFS() @@ -91,7 +84,6 @@ class Test090PythonRetValues(unittest.TestCase): self.assertRaises(RuntimeError, g.internal_test_rstructerr) - def test_rstructlist(self): g = guestfs.GuestFS() @@ -105,7 +97,6 @@ class Test090PythonRetValues(unittest.TestCase): self.assertRaises(RuntimeError, g.internal_test_rstructlisterr) - def test_rhashtable_list(self): g = guestfs.GuestFS(python_return_dict=False) @@ -116,7 +107,6 @@ class Test090PythonRetValues(unittest.TestCase): self.assertRaises(RuntimeError, g.internal_test_rhashtableerr) - def test_rhashtable_dict(self): g = guestfs.GuestFS(python_return_dict=True) @@ -126,7 +116,6 @@ class Test090PythonRetValues(unittest.TestCase): self.assertRaises(RuntimeError, g.internal_test_rhashtableerr) - def test_rbufferout(self): g = guestfs.GuestFS() diff --git a/python/t/test100Launch.py b/python/t/test100Launch.py index 5d78ccc..4b2c155 100644 --- a/python/t/test100Launch.py +++ b/python/t/test100Launch.py @@ -19,6 +19,7 @@ import unittest import os import guestfs + class Test100Launch(unittest.TestCase): def test_launch(self): g = guestfs.GuestFS(python_return_dict=True) diff --git a/python/t/test410CloseEvent.py b/python/t/test410CloseEvent.py index bc007e1..e0b38c7 100644 --- a/python/t/test410CloseEvent.py +++ b/python/t/test410CloseEvent.py @@ -21,10 +21,12 @@ import guestfs close_invoked = 0 + def close_callback(ev, eh, buf, array): global close_invoked close_invoked += 1 + class Test410CloseEvent(unittest.TestCase): def test_close_event(self): g = guestfs.GuestFS(python_return_dict=True) diff --git a/python/t/test420LogMessages.py b/python/t/test420LogMessages.py index 56c9500..ad98ea0 100644 --- a/python/t/test420LogMessages.py +++ b/python/t/test420LogMessages.py @@ -21,6 +21,7 @@ import guestfs log_invoked = 0 + def log_callback(ev, eh, buf, array): global log_invoked log_invoked += 1 @@ -32,6 +33,7 @@ def log_callback(ev, eh, buf, array): print("python event logged: event=%s eh=%d buf='%s' array=%s" % (guestfs.event_to_string(ev), eh, buf, array)) + class Test420LogMessages(unittest.TestCase): def test_log_messages(self): g = guestfs.GuestFS(python_return_dict=True) diff --git a/python/t/test800ExplicitClose.py b/python/t/test800ExplicitClose.py index a8ec8bd..c380e99 100644 --- a/python/t/test800ExplicitClose.py +++ b/python/t/test800ExplicitClose.py @@ -23,10 +23,12 @@ import guestfs close_invoked = 0 + def close_callback(ev, eh, buf, array): global close_invoked close_invoked += 1 + class Test800ExplicitClose(unittest.TestCase): def test_explicit_close(self): g = guestfs.GuestFS(python_return_dict=True) diff --git a/python/t/test810RHBZ811650.py b/python/t/test810RHBZ811650.py index 4a1192c..71386bb 100644 --- a/python/t/test810RHBZ811650.py +++ b/python/t/test810RHBZ811650.py @@ -19,6 +19,7 @@ import unittest import os import guestfs + class Test810RHBZ811650(unittest.TestCase): def test_rhbz811650(self): g = guestfs.GuestFS(python_return_dict=True) diff --git a/python/t/test820RHBZ912499.py b/python/t/test820RHBZ912499.py index c315c66..800b7dd 100644 --- a/python/t/test820RHBZ912499.py +++ b/python/t/test820RHBZ912499.py @@ -28,6 +28,7 @@ import sys import guestfs from .tests_helper import * + @skipUnlessArchMatches("(i.86|x86_64)") # If the architecture doesn't support IDE, skip the test. @skipUnlessGuestfsBackendIs('libvirt') @skipUnlessLibvirtHasCPointer() diff --git a/python/t/test910Libvirt.py b/python/t/test910Libvirt.py index a84963f..3f8f317 100644 --- a/python/t/test910Libvirt.py +++ b/python/t/test910Libvirt.py @@ -28,6 +28,7 @@ from .tests_helper import * guestsdir = os.environ['guestsdir'] + @skipUnlessLibvirtHasCPointer() class Test910Libvirt(unittest.TestCase): def test_libvirt(self): diff --git a/tests/http/test-http.py b/tests/http/test-http.py index fa263a0..2876ea5 100755 --- a/tests/http/test-http.py +++ b/tests/http/test-http.py @@ -41,6 +41,7 @@ del os.environ['http_proxy'] # Remove the stamp file. stampfile = "%s/stamp-test-http" % os.getcwd() + def unlink_stampfile(): try: os.unlink(stampfile) -- 2.5.5
Pino Toscano
2016-May-04 14:23 UTC
[Libguestfs] [PATCH 3/8] python: PEP 8: remove trailing semicolons
Remove extra semicolons at the end of single-statement lines. No behaviour changes. --- python/examples/create_disk.py | 2 +- python/t/test810RHBZ811650.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/python/examples/create_disk.py b/python/examples/create_disk.py index f8f6ebc..9fe43bc 100644 --- a/python/examples/create_disk.py +++ b/python/examples/create_disk.py @@ -11,7 +11,7 @@ output = "disk.img" g = guestfs.GuestFS(python_return_dict=True) # Create a raw-format sparse disk image, 512 MB in size. -g.disk_create(output, "raw", 512 * 1024 * 1024); +g.disk_create(output, "raw", 512 * 1024 * 1024) # Set the trace flag so that we can see each libguestfs call. g.set_trace(1) diff --git a/python/t/test810RHBZ811650.py b/python/t/test810RHBZ811650.py index 71386bb..3ca7a37 100644 --- a/python/t/test810RHBZ811650.py +++ b/python/t/test810RHBZ811650.py @@ -27,7 +27,7 @@ class Test810RHBZ811650(unittest.TestCase): g.disk_create("rhbz811650.img", "raw", 500 * 1024 * 1024) # Deliberate error: the disk format is supposed to be raw. - g.add_drive("rhbz811650.img", format="qcow2"); + g.add_drive("rhbz811650.img", format="qcow2") # Because error() wasn't being called, guestfs_last_error # would return NULL, causing a segfault in the Python bindings -- 2.5.5
Pino Toscano
2016-May-04 14:23 UTC
[Libguestfs] [PATCH 4/8] python: PEP 8: break compound statements
Avoid compound statements, simply indenting their blocks. No functional changes. --- generator/python.ml | 6 ++++-- python/examples/inspect_vm.py | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/generator/python.ml b/generator/python.ml index 8da36bc..b5ab168 100644 --- a/generator/python.ml +++ b/generator/python.ml @@ -718,8 +718,10 @@ class GuestFS(object): in libguestfs <= 1.20. \"\"\" flags = 0 - if not environment: flags |= 1 - if not close_on_exit: flags |= 2 + if not environment: + flags |= 1 + if not close_on_exit: + flags |= 2 self._o = libguestfsmod.create(flags) self._python_return_dict = python_return_dict diff --git a/python/examples/inspect_vm.py b/python/examples/inspect_vm.py index 8bfbbbc..077157c 100644 --- a/python/examples/inspect_vm.py +++ b/python/examples/inspect_vm.py @@ -39,7 +39,8 @@ for root in roots: # Sort keys by length, shortest first, so that we end up # mounting the filesystems in the correct order. mps = g.inspect_get_mountpoints(root) - def compare(a, b): return len(a) - len(b) + def compare(a, b): + return len(a) - len(b) for device in sorted(mps.keys(), compare): try: g.mount_ro(mps[device], device) @@ -51,7 +52,8 @@ for root in roots: if g.is_file(filename): print "--- %s ---" % filename lines = g.head_n(3, filename) - for line in lines: print line + for line in lines: + print line # Unmount everything. g.umount_all() -- 2.5.5
Pino Toscano
2016-May-04 14:23 UTC
[Libguestfs] [PATCH 5/8] python: PEP 8: avoid too long lines
Reindent Python scripts to make sure lines are not longer than 80 columns. Regarding autogenerated code (guestfs.py and bindtests.py): add an helper function to make sure comma-separated lists are wrapped at the wanted length. This produces only differences in the indentation of long Python lines, with no behaviour changes. --- generator/bindtests.ml | 4 +++- generator/python.ml | 50 ++++++++++++++++++++++++++++++++++---------- generator/python.mli | 8 +++++++ python/t/test090RetValues.py | 9 +++++--- python/t/tests_helper.py | 6 ++++-- tests/http/test-http.py | 4 ++-- 6 files changed, 62 insertions(+), 19 deletions(-) diff --git a/generator/bindtests.ml b/generator/bindtests.ml index c6a4c6b..742cb1b 100644 --- a/generator/bindtests.ml +++ b/generator/bindtests.ml @@ -467,7 +467,9 @@ g = guestfs.GuestFS() in generate_lang_bindtests ( - fun f args optargs -> pr "g.%s(%s)\n" f (mkargs args optargs) + fun f args optargs -> + pr "g.%s(%s)\n" f + (Python.indent_python (mkargs args optargs) (3 + String.length f) 78) ); pr "print(\"EOF\")\n" diff --git a/generator/python.ml b/generator/python.ml index b5ab168..d577ef1 100644 --- a/generator/python.ml +++ b/generator/python.ml @@ -789,16 +789,22 @@ class GuestFS(object): "; + let map_join f l + String.concat "" (List.map f l) + in + List.iter ( fun f -> let ret, args, optargs = f.style in - pr " def %s(self" f.name; - List.iter (fun arg -> pr ", %s" (name_of_argt arg)) args; - List.iter ( - fun optarg -> - pr ", %s=None" (name_of_optargt optarg) - ) optargs; - pr "):\n"; + let len_name = String.length f.name in + let decl_string + "self" ^ + map_join (fun arg ->sprintf ", %s" (name_of_argt arg)) + args ^ + map_join (fun optarg -> sprintf ", %s=None" (name_of_optargt optarg)) + optargs in + pr " def %s(%s):\n" + f.name (indent_python decl_string (9 + len_name) 78); if is_documented f then ( let doc = replace_str f.longdesc "C<guestfs_" "C<g." in @@ -849,10 +855,12 @@ class GuestFS(object): pr " %s = %s.c_pointer()\n" n n ) args; pr " self._check_not_closed()\n"; - pr " r = libguestfsmod.%s(self._o" f.name; - List.iter (fun arg -> pr ", %s" (name_of_argt arg)) - (args @ args_of_optargs optargs); - pr ")\n"; + let function_string + "self._o" ^ + map_join (fun arg -> sprintf ", %s" (name_of_argt arg)) + (args @ args_of_optargs optargs) in + pr " r = libguestfsmod.%s(%s)\n" + f.name (indent_python function_string (27 + len_name) 78); (* For RHashtable, if self._python_return_dict=True then we * have to convert the result to a dict. @@ -872,3 +880,23 @@ class GuestFS(object): pr " %s = %s\n\n" alias f.name ) f.non_c_aliases ) external_functions_sorted + +and indent_python str indent columns + let rec loop str endpos + let len = String.length str in + if len + indent > columns then + try + let pos = String.rindex_from str endpos ',' in + if pos + indent > columns then + loop str (pos - 1) + else ( + let rest = String.sub str (pos + 2) (len - pos - 2) in + String.sub str 0 pos :: loop rest (String.length rest - 1) + ) + with Not_found -> + [str] + else + [str] + in + let lines = loop str (String.length str - 1) in + String.concat (",\n" ^ String.make indent ' ') lines diff --git a/generator/python.mli b/generator/python.mli index 919dab3..d1d0247 100644 --- a/generator/python.mli +++ b/generator/python.mli @@ -18,3 +18,11 @@ val generate_python_c : unit -> unit val generate_python_py : unit -> unit + +val indent_python : string -> int -> int -> string +(** [indent_python str indent columns] indents a Python comma-based string + like "foo, bar, etc" (with space after the comma), splitting at commas + so each line does not take more than [columns] characters, including + [indent]. + + Lines after the first are indented with [indent] spaces. *) diff --git a/python/t/test090RetValues.py b/python/t/test090RetValues.py index c310cf1..d9a68d1 100644 --- a/python/t/test090RetValues.py +++ b/python/t/test090RetValues.py @@ -33,7 +33,8 @@ class Test090PythonRetValues(unittest.TestCase): def test_rint64(self): g = guestfs.GuestFS() - self.assertAlmostEqual(g.internal_test_rint64("10"), int_type(10), places=1) + self.assertAlmostEqual(g.internal_test_rint64("10"), + int_type(10), places=1) self.assertRaises(RuntimeError, g.internal_test_rint64err) @@ -55,7 +56,8 @@ class Test090PythonRetValues(unittest.TestCase): def test_rconstoptstring(self): g = guestfs.GuestFS() - self.assertEqual(g.internal_test_rconstoptstring("test"), "static string") + self.assertEqual(g.internal_test_rconstoptstring("test"), + "static string") # this never fails self.assertIsNone(g.internal_test_rconstoptstringerr()) @@ -71,7 +73,8 @@ class Test090PythonRetValues(unittest.TestCase): g = guestfs.GuestFS() self.assertEqual(g.internal_test_rstringlist("0"), []) - self.assertEqual(g.internal_test_rstringlist("5"), ["0", "1", "2", "3", "4"]) + self.assertEqual(g.internal_test_rstringlist("5"), + ["0", "1", "2", "3", "4"]) self.assertRaises(RuntimeError, g.internal_test_rstringlisterr) diff --git a/python/t/tests_helper.py b/python/t/tests_helper.py index f47b157..8493c40 100644 --- a/python/t/tests_helper.py +++ b/python/t/tests_helper.py @@ -37,7 +37,8 @@ def skipUnlessLibvirtHasCPointer(): import libvirt except: return unittest.skip("could not import libvirt") - # Check we're using the version of libvirt-python that has c_pointer() methods. + # Check we're using the version of libvirt-python that has + # c_pointer() methods. if not "c_pointer" in dir(libvirt.open(None)): return unittest.skip("libvirt-python doesn't support c_pointer()") return lambda func: func @@ -66,5 +67,6 @@ def skipUnlessArchMatches(arch_re): machine = platform.machine() rex = re.compile(arch_re) if not rex.match(machine): - return unittest.skip("the current architecture (%s) does not match '%s'" % (machine, arch_re)) + return unittest.skip("the current architecture (%s) does not match " + "'%s'" % (machine, arch_re)) return lambda func: func diff --git a/tests/http/test-http.py b/tests/http/test-http.py index 2876ea5..a353925 100755 --- a/tests/http/test-http.py +++ b/tests/http/test-http.py @@ -95,8 +95,8 @@ if pid > 0: exit(1) if len(roots) > 1: print >>sys.stderr, \ - ("%s: error: inspection found a multi-boot OS which is not expected" % - progname) + ("%s: error: inspection found a multi-boot OS which is not " + "expected" % progname) exit(1) type_ = g.inspect_get_type(roots[0]) -- 2.5.5
Pino Toscano
2016-May-04 14:23 UTC
[Libguestfs] [PATCH 6/8] python: PEP 8: miscellaneous indentation fixes
Small fixes for few remaining indentation issues. No behaviour changes. --- python/setup.py.in | 3 +-- python/t/test420LogMessages.py | 2 +- python/t/test820RHBZ912499.py | 3 ++- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/python/setup.py.in b/python/setup.py.in index 403c4b5..65939b0 100644 --- a/python/setup.py.in +++ b/python/setup.py.in @@ -58,5 +58,4 @@ This package contains the Python bindings for libguestfs. libraries=['guestfs'], define_macros=[('GUESTFS_PRIVATE', '1')], ) - ] -) + ]) diff --git a/python/t/test420LogMessages.py b/python/t/test420LogMessages.py index ad98ea0..bec3b9f 100644 --- a/python/t/test420LogMessages.py +++ b/python/t/test420LogMessages.py @@ -40,7 +40,7 @@ class Test420LogMessages(unittest.TestCase): # Register an event callback for all log messages. events = guestfs.EVENT_APPLIANCE | guestfs.EVENT_LIBRARY \ - | guestfs.EVENT_WARNING | guestfs.EVENT_TRACE + | guestfs.EVENT_WARNING | guestfs.EVENT_TRACE g.set_event_callback(log_callback, events) # Now make sure we see some messages. diff --git a/python/t/test820RHBZ912499.py b/python/t/test820RHBZ912499.py index 800b7dd..60509dc 100644 --- a/python/t/test820RHBZ912499.py +++ b/python/t/test820RHBZ912499.py @@ -29,7 +29,8 @@ import guestfs from .tests_helper import * -@skipUnlessArchMatches("(i.86|x86_64)") # If the architecture doesn't support IDE, skip the test. +# If the architecture doesn't support IDE, skip the test. +@skipUnlessArchMatches("(i.86|x86_64)") @skipUnlessGuestfsBackendIs('libvirt') @skipUnlessLibvirtHasCPointer() class Test820RHBZ912499(unittest.TestCase): -- 2.5.5
Pino Toscano
2016-May-04 14:23 UTC
[Libguestfs] [PATCH 7/8] python: PEP 8: avoid whitespace-only lines in docstrings
Tweak the docstring generation to avoid lines with only indentation spaces. No functional changes, only whitespaces removals. --- generator/python.ml | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/generator/python.ml b/generator/python.ml index d577ef1..70dc076 100644 --- a/generator/python.ml +++ b/generator/python.ml @@ -836,7 +836,25 @@ class GuestFS(object): doc ^ sprintf "\n\nThis function depends on the feature C<%s>. See also C<g.feature-available>." opt in let doc = pod2text ~width:60 f.name doc in let doc = List.map (fun line -> replace_str line "\\" "\\\\") doc in - let doc = String.concat "\n " doc in + let doc + match doc with + | [] -> "" + | [line] -> line + | hd :: tl -> + let endpos = List.length tl - 1 in + (* Add indentation spaces, but only if the line is not empty or + * it is not the last one (since there will be the 3 dobule-quotes + * at the end. + *) + let lines + mapi ( + fun lineno line -> + if line = "" && lineno <> endpos then + "" + else + " " ^ line + ) tl in + hd ^ "\n" ^ (String.concat "\n" lines) in pr " \"\"\"%s\"\"\"\n" doc; ); (* Callers might pass in iterables instead of plain lists; -- 2.5.5
Pino Toscano
2016-May-04 14:23 UTC
[Libguestfs] [PATCH 8/8] python: PEP 8: miscellaneous coding fixes
python/guestfs.py:136:37: E712 comparison to True should be 'if cond is True:' or 'if cond:' python/t/tests_helper.py:42:8: E713 test for membership should be 'not in' No functional changes, as the new versions follow the suggested Python coding style to do the same things. --- generator/python.ml | 2 +- python/t/tests_helper.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/generator/python.ml b/generator/python.ml index 70dc076..9744b8f 100644 --- a/generator/python.ml +++ b/generator/python.ml @@ -738,7 +738,7 @@ class GuestFS(object): raise ClosedHandle(\"GuestFS: method called on closed handle\") def _maybe_convert_to_dict(self, r): - if self._python_return_dict == True: + if self._python_return_dict: r = dict(r) return r diff --git a/python/t/tests_helper.py b/python/t/tests_helper.py index 8493c40..4ae1375 100644 --- a/python/t/tests_helper.py +++ b/python/t/tests_helper.py @@ -39,7 +39,7 @@ def skipUnlessLibvirtHasCPointer(): return unittest.skip("could not import libvirt") # Check we're using the version of libvirt-python that has # c_pointer() methods. - if not "c_pointer" in dir(libvirt.open(None)): + if "c_pointer" not in dir(libvirt.open(None)): return unittest.skip("libvirt-python doesn't support c_pointer()") return lambda func: func -- 2.5.5
On Wed, May 04, 2016 at 04:23:10PM +0200, Pino Toscano wrote:> Hi, > > this series cleans up the Python sources, either static or generated, > including also tests, to make them PEP 8 compliant; see > https://www.python.org/dev/peps/pep-0008/ and tools like pep8. > Almost all the issues reported by pep8 are fixed, reducing the issues > from 3818 to 7. > > The changes should have no effect on the actual code, while it will > help Python users with consistency with other Python code.ACK series, thanks. Rich. -- Richard Jones, Virtualization Group, Red Hat http://people.redhat.com/~rjones Read my programming and virtualization blog: http://rwmj.wordpress.com virt-top is 'top' for virtual machines. Tiny program with many powerful monitoring features, net stats, disk stats, logging, etc. http://people.redhat.com/~rjones/virt-top
Seemingly Similar Threads
- [PATCH 0/7] Various Python pycodestyle fixes
- [PATCH v2 0/8] Various Python pycodestyle fixes
- [PATCH 1/3] python: tests: refactor to use unittest's discovery
- [PATCH] python: tests: use more targeted assert*() functions/checks
- Malformed XML if LIBGUESTFS_HV is defined.