Converting compute-hyperv to py3

Initial conversion with 2to3 tool
Added support for Python3
Replaces / with // for Py3 compatibility
Adds Py2.7 compatibility
Fix IOUtils Py3 compatibility issue. The method retrieving
buffer data was raising a TypeError on Py3.

Co-Authored-By: Alessandro Pilotti <apilotti@cloudbasesolutions.com>
Co-Authored-By: Claudiu Belu <cbelu@cloudbasesolutions.com>
Co-Authored-By: Lucian Petrut <lpetrut@cloudbasesolutions.com>

Change-Id: I99212227105d5fd442a7bd88eb8832586a187e2f
This commit is contained in:
Adelina Tuvenie 2015-09-23 04:45:40 -07:00 committed by Lucian Petrut
parent 61b87f8094
commit cca46626a9
33 changed files with 138 additions and 120 deletions

View File

@ -37,8 +37,8 @@ source_suffix = '.rst'
master_doc = 'index'
# General information about the project.
project = u'compute-hyperv'
copyright = u'2013, OpenStack Foundation'
project = 'compute-hyperv'
copyright = '2013, OpenStack Foundation'
# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True
@ -67,8 +67,8 @@ htmlhelp_basename = '%sdoc' % project
latex_documents = [
('index',
'%s.tex' % project,
u'%s Documentation' % project,
u'OpenStack Foundation', 'manual'),
'%s Documentation' % project,
'OpenStack Foundation', 'manual'),
]
# Example configuration for intersphinx: refer to the Python standard library.

View File

@ -25,7 +25,7 @@ import re
import sys
if sys.platform == 'win32':
import _winreg
from six.moves import winreg
import wmi
from nova import block_device
@ -66,11 +66,11 @@ class BaseVolumeUtils(object):
keypath = ("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\"
"iSCSI\\Discovery")
try:
key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, keypath, 0,
_winreg.KEY_ALL_ACCESS)
temp = _winreg.QueryValueEx(key, 'DefaultInitiatorName')
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, keypath, 0,
winreg.KEY_ALL_ACCESS)
temp = winreg.QueryValueEx(key, 'DefaultInitiatorName')
initiator_name = str(temp[0])
_winreg.CloseKey(key)
winreg.CloseKey(key)
except Exception:
LOG.info(_LI("The ISCSI initiator name can't be found. "
"Choosing the default one"))

View File

@ -126,7 +126,7 @@ SERIAL_PORT_TYPES = {
DEFAULT_SERIAL_CONSOLE_PORT = 1
SERIAL_CONSOLE_BUFFER_SIZE = 4 * units.Ki
MAX_CONSOLE_LOG_FILE_SIZE = units.Mi / 2
MAX_CONSOLE_LOG_FILE_SIZE = units.Mi // 2
JOB_STATE_COMPLETED = 7
JOB_STATE_TERMINATED = 8

View File

@ -64,7 +64,7 @@ class InstanceEventHandler(object):
self._vmutils = utilsfactory.get_vmutils()
self._listener = self._vmutils.get_vm_power_state_change_listener(
timeframe=CONF.hyperv.power_state_check_timeframe,
filtered_states=self._TRANSITION_MAP.keys())
filtered_states=list(self._TRANSITION_MAP.keys()))
self._serial_console_ops = serialconsoleops.SerialConsoleOps()

View File

@ -19,6 +19,7 @@ Management class for host operations.
import datetime
import os
import platform
import six
import time
@ -81,12 +82,12 @@ class HostOps(object):
topology = dict()
topology['sockets'] = len(processors)
topology['cores'] = processors[0]['NumberOfCores']
topology['threads'] = (processors[0]['NumberOfLogicalProcessors'] /
topology['threads'] = (processors[0]['NumberOfLogicalProcessors'] //
processors[0]['NumberOfCores'])
cpu_info['topology'] = topology
features = list()
for fkey, fname in constants.PROCESSOR_FEATURE.items():
for fkey, fname in six.iteritems(constants.PROCESSOR_FEATURE):
if self._hostutils.is_cpu_feature_present(fkey):
features.append(fname)
cpu_info['features'] = features
@ -95,16 +96,16 @@ class HostOps(object):
def _get_memory_info(self):
(total_mem_kb, free_mem_kb) = self._hostutils.get_memory_info()
total_mem_mb = total_mem_kb / 1024
free_mem_mb = free_mem_kb / 1024
total_mem_mb = total_mem_kb // 1024
free_mem_mb = free_mem_kb // 1024
return (total_mem_mb, free_mem_mb, total_mem_mb - free_mem_mb)
def _get_local_hdd_info_gb(self):
drive = os.path.splitdrive(self._pathutils.get_instances_dir())[0]
(size, free_space) = self._hostutils.get_volume_info(drive)
total_gb = size / units.Gi
free_gb = free_space / units.Gi
total_gb = size // units.Gi
free_gb = free_space // units.Gi
used_gb = total_gb - free_gb
return (total_gb, free_gb, used_gb)
@ -222,7 +223,7 @@ class HostOps(object):
# value is same as in libvirt
return "%s up %s, 0 users, load average: 0, 0, 0" % (
str(time.strftime("%H:%M:%S")),
str(datetime.timedelta(milliseconds=long(tick_count64))))
str(datetime.timedelta(milliseconds=int(tick_count64))))
def host_maintenance_mode(self, host, mode):
"""Starts/Stops host maintenance. On start, it triggers

View File

@ -61,8 +61,8 @@ class HostUtils(object):
mem_info = self._conn_cimv2.query("SELECT TotalVisibleMemorySize, "
"FreePhysicalMemory "
"FROM win32_operatingsystem")[0]
return (long(mem_info.TotalVisibleMemorySize),
long(mem_info.FreePhysicalMemory))
return (int(mem_info.TotalVisibleMemorySize),
int(mem_info.FreePhysicalMemory))
def get_volume_info(self, drive):
"""Returns a tuple with total size and free space
@ -72,11 +72,11 @@ class HostUtils(object):
"FROM win32_logicaldisk "
"WHERE DeviceID='%s'"
% drive)[0]
return (long(logical_disk.Size), long(logical_disk.FreeSpace))
return (int(logical_disk.Size), int(logical_disk.FreeSpace))
def check_min_windows_version(self, major, minor, build=0):
version_str = self.get_windows_version()
return map(int, version_str.split('.')) >= [major, minor, build]
return list(map(int, version_str.split('.'))) >= [major, minor, build]
def get_windows_version(self):
if self._conn_cimv2:

View File

@ -14,6 +14,7 @@
# under the License.
import ctypes
import six
import struct
import sys
@ -27,7 +28,11 @@ from hyperv.nova import vmutils
LOG = logging.getLogger(__name__)
Queue = patcher.original('Queue')
# Avoid using six.moves.queue as we need a non monkey patched class
if sys.version_info > (3, 0):
Queue = patcher.original('queue')
else:
Queue = patcher.original('Queue')
if sys.platform == 'win32':
from ctypes import wintypes
@ -230,13 +235,11 @@ class IOUtils(object):
return (ctypes.c_ubyte * buff_size)()
def get_buffer_data(self, buff, num_bytes):
data = "".join([struct.pack('B', b)
for b in buff[:num_bytes]])
return data
return bytes(bytearray(buff[:num_bytes]))
def write_buffer_data(self, buff, data):
for i, c in enumerate(data):
buff[i] = struct.unpack('B', c)[0]
buff[i] = struct.unpack('B', six.b(c))[0]
class IOQueue(Queue.Queue):

View File

@ -20,6 +20,7 @@ if sys.platform == 'win32':
from nova import exception
from oslo_log import log as logging
import six
from hyperv.i18n import _, _LE
from hyperv.nova import vmutils
@ -119,13 +120,13 @@ class LiveMigrationUtils(object):
scsi_ctrl_path = self._vmutils.get_vm_scsi_controller(vm_name)
scsi_paths = self._vmutils.get_controller_volume_paths(scsi_ctrl_path)
return dict(ide_paths.items() + scsi_paths.items())
return dict(list(ide_paths.items()) + list(scsi_paths.items()))
def _get_remote_disk_data(self, vmutils_remote, disk_paths, dest_host):
volutils_remote = volumeutilsv2.VolumeUtilsV2(dest_host)
disk_paths_remote = {}
for (rasd_rel_path, disk_path) in disk_paths.items():
for rasd_rel_path, disk_path in six.iteritems(disk_paths):
target = self._volutils.get_target_from_disk_path(disk_path)
if target:
(target_iqn, target_lun) = target

View File

@ -72,8 +72,8 @@ class PathUtils(object):
def open(self, path, mode):
"""Wrapper on __builtin__.open used to simplify unit testing."""
import __builtin__
return __builtin__.open(path, mode)
from six.moves import builtins
return builtins.open(path, mode)
def exists(self, path):
return os.path.exists(path)

View File

@ -20,6 +20,7 @@ from nova import exception
from nova.i18n import _, _LI # noqa
from oslo_config import cfg
from oslo_log import log as logging
import six
from hyperv.nova import constants
from hyperv.nova import ioutils
@ -109,7 +110,7 @@ class SerialConsoleHandler(object):
log_rw_pipe_output = not serial_port_mapping.get(
constants.SERIAL_PORT_TYPE_RO)
for pipe_type, pipe_path in serial_port_mapping.iteritems():
for pipe_type, pipe_path in six.iteritems(serial_port_mapping):
enable_logging = (pipe_type == constants.SERIAL_PORT_TYPE_RO or
log_rw_pipe_output)
handler = self._get_named_pipe_handler(

View File

@ -93,7 +93,7 @@ class SerialConsoleOps(object):
instance_name)
try:
log = ''
log = b''
# Start with the oldest console log file.
for log_path in console_log_paths[::-1]:
if os.path.exists(log_path):

View File

@ -16,6 +16,7 @@
from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import importutils
import six
from hyperv.i18n import _
from hyperv.nova import hostutils
@ -33,7 +34,7 @@ class_utils = {
'hostutils': {'HostUtils': {'min_version': 6.0, 'max_version': 6.2},
'HostUtilsV2': {'min_version': 6.2, 'max_version': None}},
'livemigrationutils': {'LiveMigrationUtils': {'min_version': 6.0,
'max_version': 'None'}},
'max_version': None}},
'networkutils': {'NetworkUtils': {'min_version': 6.0,
'max_version': 6.2},
'NetworkUtilsV2': {'min_version': 6.2,
@ -61,11 +62,11 @@ def _get_class(utils_class_type):
% utils_class_type)
windows_version = utils.get_windows_version()
build = map(int, windows_version.split('.'))
build = list(map(int, windows_version.split('.')))
windows_version = float("%i.%i" % (build[0], build[1]))
existing_classes = class_utils.get(utils_class_type)
for class_variant in existing_classes.keys():
for class_variant in six.iterkeys(existing_classes):
version = existing_classes.get(class_variant)
if (version['min_version'] <= windows_version and
(version['max_version'] is None or

View File

@ -43,8 +43,8 @@ VHD_HEADER_SIZE_DYNAMIC = 512
VHD_FOOTER_SIZE_DYNAMIC = 512
VHD_BLK_SIZE_OFFSET = 544
VHD_SIGNATURE = 'conectix'
VHDX_SIGNATURE = 'vhdxfile'
VHD_SIGNATURE = b'conectix'
VHDX_SIGNATURE = b'vhdxfile'
class VHDUtils(object):
@ -145,7 +145,7 @@ class VHDUtils(object):
fs = VHD_FOOTER_SIZE_DYNAMIC
max_internal_size = (new_vhd_file_size -
(hs + ddhs + fs)) * bs / (bes + bs)
(hs + ddhs + fs)) * bs // (bes + bs)
return max_internal_size
else:
vhd_parent = self.get_vhd_parent_path(vhd_path)
@ -184,7 +184,7 @@ class VHDUtils(object):
if name == "ParentPath":
vhd_info_dict[name] = value_text
elif name in ["FileSize", "MaxInternalSize"]:
vhd_info_dict[name] = long(value_text)
vhd_info_dict[name] = int(value_text)
elif name in ["InSavedState", "InUse"]:
vhd_info_dict[name] = bool(value_text)
elif name == "Type":

View File

@ -160,11 +160,11 @@ class VHDUtilsV2(vhdutils.VHDUtils):
ls = self._get_vhdx_log_size(f)
ms = self._get_vhdx_metadata_size_and_offset(f)[0]
chunk_ratio = (1 << 23) * lss / bs
chunk_ratio = (1 << 23) * lss // bs
size = new_vhd_file_size
max_internal_size = (bs * chunk_ratio * (size - hs -
ls - ms - bes - bes / chunk_ratio) / (bs *
ls - ms - bes - bes // chunk_ratio) // (bs *
chunk_ratio + bes * chunk_ratio + bes))
return max_internal_size - (max_internal_size % bs)
@ -237,7 +237,7 @@ class VHDUtilsV2(vhdutils.VHDUtils):
vhd_info_dict[name] = value_text
elif name in ["BlockSize", "LogicalSectorSize",
"PhysicalSectorSize", "MaxInternalSize"]:
vhd_info_dict[name] = long(value_text)
vhd_info_dict[name] = int(value_text)
elif name in ["Type", "Format"]:
vhd_info_dict[name] = int(value_text)

View File

@ -36,6 +36,7 @@ from oslo_utils import excutils
from oslo_utils import fileutils
from oslo_utils import units
from oslo_utils import uuidutils
import six
from hyperv.i18n import _, _LI, _LE, _LW
from hyperv.nova import constants
@ -717,7 +718,7 @@ class VMOps(object):
self.power_on(instance, block_device_info, network_info)
def _create_vm_com_port_pipes(self, instance, serial_ports):
for port_number, port_type in serial_ports.iteritems():
for port_number, port_type in six.iteritems(serial_ports):
pipe_path = r'\\.\pipe\%s_%s' % (instance.uuid, port_type)
self._vmutils.set_vm_serial_port_connection(
instance.name, port_number, pipe_path)
@ -733,9 +734,9 @@ class VMOps(object):
image_props = image_meta['properties']
serial_ports = {}
for image_prop, port_type in constants.SERIAL_PORT_TYPES.iteritems():
for img_prop, port_type in six.iteritems(constants.SERIAL_PORT_TYPES):
port_number = int(image_props.get(
image_prop,
img_prop,
constants.DEFAULT_SERIAL_CONSOLE_PORT))
if port_number not in [1, 2]:
@ -892,7 +893,7 @@ class VMOps(object):
def _get_storage_qos_specs(self, instance):
extra_specs = instance.flavor.get('extra_specs') or {}
storage_qos_specs = {}
for spec, value in extra_specs.iteritems():
for spec, value in six.iteritems(extra_specs):
if ':' in spec:
scope, key = spec.split(':')
if scope == 'storage_qos':

View File

@ -171,10 +171,10 @@ class VMUtils(object):
si = summary_info[0]
memory_usage = None
if si.MemoryUsage is not None:
memory_usage = long(si.MemoryUsage)
memory_usage = int(si.MemoryUsage)
up_time = None
if si.UpTime is not None:
up_time = long(si.UpTime)
up_time = int(si.UpTime)
# Nova requires a valid state to be returned. Hyper-V has more
# states than Nova, typically intermediate ones and since there is
@ -224,14 +224,14 @@ class VMUtils(object):
mem_settings = vmsetting.associators(
wmi_result_class=self._MEMORY_SETTING_DATA_CLASS)[0]
max_mem = long(memory_mb)
max_mem = int(memory_mb)
mem_settings.Limit = max_mem
if dynamic_memory_ratio > 1:
mem_settings.DynamicMemoryEnabled = True
# Must be a multiple of 2
reserved_mem = min(
long(max_mem / dynamic_memory_ratio) >> 1 << 1,
int(max_mem // dynamic_memory_ratio) >> 1 << 1,
max_mem)
else:
mem_settings.DynamicMemoryEnabled = False
@ -246,7 +246,7 @@ class VMUtils(object):
def _set_vm_vcpus(self, vm, vmsetting, vcpus_num, limit_cpu_features):
procsetting = vmsetting.associators(
wmi_result_class=self._PROCESSOR_SETTING_DATA_CLASS)[0]
vcpus = long(vcpus_num)
vcpus = int(vcpus_num)
procsetting.VirtualQuantity = vcpus
procsetting.Reservation = vcpus
procsetting.Limit = 100000 # static assignment to 100%

View File

@ -29,6 +29,7 @@ from oslo_config import cfg
from oslo_log import log as logging
from oslo_utils import excutils
from oslo_utils import units
import six
from six.moves import range
from hyperv.i18n import _, _LE, _LW
@ -97,7 +98,7 @@ class VolumeOps(object):
mapping = driver.block_device_info_get_mapping(block_device_info)
block_devices = self._group_block_devices_by_type(
mapping)
for driver_type, block_device_mapping in block_devices.items():
for driver_type, block_device_mapping in six.iteritems(block_devices):
volume_driver = self._get_volume_driver(driver_type)
volume_driver.disconnect_volumes(block_device_mapping)
@ -195,7 +196,7 @@ class VolumeOps(object):
def _bytes_per_sec_to_iops(self, no_bytes):
# Hyper-v uses normalized IOPS (8 KB increments)
# as IOPS allocation units.
return (no_bytes + self._IOPS_BASE_SIZE - 1) / self._IOPS_BASE_SIZE
return (no_bytes + self._IOPS_BASE_SIZE - 1) // self._IOPS_BASE_SIZE
def _group_block_devices_by_type(self, block_device_mapping):
block_devices = collections.defaultdict(list)
@ -252,7 +253,7 @@ class ISCSIVolumeDriver(object):
target_iqn = vol['connection_info']['data']['target_iqn']
iscsi_targets[target_iqn] += 1
for target_iqn, disconnected_luns in iscsi_targets.items():
for target_iqn, disconnected_luns in six.iteritems(iscsi_targets):
self.logout_storage_target(target_iqn, disconnected_luns)
def logout_storage_target(self, target_iqn, disconnected_luns_count=1):

View File

@ -17,6 +17,7 @@ import uuid
from nova import objects
from nova.objects import fields
import six
def fake_db_instance(**updates):
@ -43,7 +44,7 @@ def fake_db_instance(**updates):
'tags': []
}
for name, field in objects.Instance.fields.items():
for name, field in six.iteritems(objects.Instance.fields):
if name in db_instance:
continue
if field.nullable:

View File

@ -28,6 +28,7 @@ eventlet.monkey_patch(os=False)
import inspect
import mock
import six
import fixtures
from nova.tests import fixtures as nova_fixtures
@ -111,13 +112,13 @@ class NoDBTestCase(testtools.TestCase):
# Delete attributes that don't start with _ so they don't pin
# memory around unnecessarily for the duration of the test
# suite
for key in [k for k in self.__dict__.keys() if k[0] != '_']:
for key in [k for k in six.iterkeys(self.__dict__) if k[0] != '_']:
del self.__dict__[key]
def flags(self, **kw):
"""Override flag variables for a test."""
group = kw.pop('group', None)
for k, v in kw.iteritems():
for k, v in six.iteritems(kw):
CONF.set_override(k, v, group)
def assertPublicAPISignatures(self, baseinst, inst):

View File

@ -15,6 +15,7 @@
# under the License.
import mock
from six.moves import builtins
from hyperv.nova import utilsfactory
from hyperv.tests import test
@ -25,8 +26,8 @@ class HyperVBaseTestCase(test.NoDBTestCase):
super(HyperVBaseTestCase, self).setUp()
self._mock_wmi = mock.MagicMock()
wmi_patcher = mock.patch('__builtin__.wmi', create=True,
new=self._mock_wmi)
wmi_patcher = mock.patch.object(builtins, 'wmi', create=True,
new=self._mock_wmi)
platform_patcher = mock.patch('sys.platform', 'win32')
hostutils_patcher = mock.patch.object(utilsfactory, 'utils')

View File

@ -64,7 +64,7 @@ class BaseVolumeUtilsTestCase(test.NoDBTestCase):
mock_computer]
with mock.patch.object(basevolumeutils,
'_winreg', create=True) as mock_winreg:
'winreg', create=True) as mock_winreg:
mock_winreg.OpenKey = winreg_method
mock_winreg.QueryValueEx = mock.MagicMock(return_value=[expected])

View File

@ -22,6 +22,7 @@ from nova import objects
from oslo_config import cfg
from oslo_serialization import jsonutils
from oslo_utils import units
import six
from hyperv.nova import constants
from hyperv.nova import hostops
@ -66,7 +67,7 @@ class HostOpsTestCase(test_base.HyperVBaseTestCase):
self._hostops._hostutils.get_cpus_info.assert_called_once_with()
expected = [mock.call(fkey)
for fkey in constants.PROCESSOR_FEATURE.keys()]
for fkey in six.iterkeys(constants.PROCESSOR_FEATURE)]
self._hostops._hostutils.is_cpu_feature_present.has_calls(expected)
expected_response = self._get_mock_cpu_info()
self.assertEqual(expected_response, response)
@ -76,7 +77,7 @@ class HostOpsTestCase(test_base.HyperVBaseTestCase):
'model': self.FAKE_NAME,
'arch': constants.WMI_WIN32_PROCESSOR_ARCHITECTURE[
self.FAKE_ARCHITECTURE],
'features': constants.PROCESSOR_FEATURE.values(),
'features': list(constants.PROCESSOR_FEATURE.values()),
'topology': {'cores': self.FAKE_NUM_CPUS,
'threads': self.FAKE_NUM_CPUS,
'sockets': self.FAKE_NUM_CPUS}}
@ -94,7 +95,7 @@ class HostOpsTestCase(test_base.HyperVBaseTestCase):
self.assertEqual((2, 1, 1), response)
def test_get_local_hdd_info_gb(self):
self._hostops._pathutils.get_instance_dir.return_value = ''
self._hostops._pathutils.get_instances_dir.return_value = ''
self._hostops._hostutils.get_volume_info.return_value = (2 * units.Gi,
1 * units.Gi)
response = self._hostops._get_local_hdd_info_gb()
@ -195,7 +196,7 @@ class HostOpsTestCase(test_base.HyperVBaseTestCase):
self.FAKE_TICK_COUNT)
response = self._hostops.get_host_uptime()
tdelta = datetime.timedelta(milliseconds=long(self.FAKE_TICK_COUNT))
tdelta = datetime.timedelta(milliseconds=int(self.FAKE_TICK_COUNT))
expected = "%s up %s, 0 users, load average: 0, 0, 0" % (
str(mock_time()), str(tdelta))

View File

@ -32,10 +32,10 @@ class FakeCPUSpec(object):
class HostUtilsTestCase(test.NoDBTestCase):
"""Unit tests for the Hyper-V hostutils class."""
_FAKE_MEMORY_TOTAL = 1024L
_FAKE_MEMORY_FREE = 512L
_FAKE_DISK_SIZE = 1024L
_FAKE_DISK_FREE = 512L
_FAKE_MEMORY_TOTAL = 1024
_FAKE_MEMORY_FREE = 512
_FAKE_DISK_SIZE = 1024
_FAKE_DISK_FREE = 512
_FAKE_VERSION_GOOD = '6.2.0'
_FAKE_VERSION_BAD = '6.1.9'

View File

@ -14,6 +14,8 @@
# under the License.
import ctypes
import six
import mock
from hyperv.nova import constants
@ -36,14 +38,14 @@ class IOUtilsTestCase(test_base.HyperVBaseTestCase):
@mock.patch.object(ioutils.IOUtils, 'handle_last_error')
def test_run_and_check_output(self, mock_handle_last_error):
mock_func = mock.Mock()
mock_func.__name__ = mock.sentinel.func_name
mock_func.__name__ = mock.sentinel.__name__
ret_val = self._ioutils._run_and_check_output(
mock_func, error_codes=[mock_func()],
ignored_error_codes=mock.sentinel.ignored_error_codes)
mock_handle_last_error.assert_called_once_with(
func_name=mock.sentinel.func_name,
func_name=mock.sentinel.__name__,
ignored_error_codes=mock.sentinel.ignored_error_codes)
self.assertEqual(mock_func(), ret_val)
@ -73,7 +75,7 @@ class IOUtilsTestCase(test_base.HyperVBaseTestCase):
self._ioutils.write_buffer_data(fake_buffer, fake_data)
buff_data = self._ioutils.get_buffer_data(fake_buffer, len(fake_data))
self.assertEqual(fake_data, buff_data)
self.assertEqual(six.b(fake_data), buff_data)
class IOQueueTestCase(test_base.HyperVBaseTestCase):

View File

@ -15,6 +15,7 @@
import errno
import mock
from six.moves import builtins
from hyperv.nova import constants
from hyperv.nova import namedpipe
@ -56,7 +57,7 @@ class NamedPipeTestCase(test_base.HyperVBaseTestCase):
self._handler._r_completion_routine = mock.Mock()
self._handler._w_completion_routine = mock.Mock()
@mock.patch('__builtin__.open')
@mock.patch.object(builtins, 'open')
@mock.patch.object(namedpipe.NamedPipeHandler, '_open_pipe')
def test_start_pipe_handler(self, mock_open_pipe, mock_open):
self._handler.start()
@ -190,7 +191,7 @@ class NamedPipeTestCase(test_base.HyperVBaseTestCase):
self._test_write_to_log(size_exceeded=True)
@mock.patch.object(namedpipe.NamedPipeHandler, '_retry_if_file_in_use')
@mock.patch('__builtin__.open')
@mock.patch.object(builtins, 'open')
@mock.patch.object(namedpipe, 'os')
def test_rotate_logs(self, mock_os, mock_open, mock_exec_retry):
fake_archived_log_path = self._FAKE_LOG_PATH + '.1'

View File

@ -15,6 +15,7 @@
import os
import mock
from six.moves import builtins
from hyperv.nova import constants
from hyperv.nova import pathutils
@ -178,8 +179,8 @@ class PathUtilsTestCase(test_base.HyperVBaseTestCase):
mock_rmtree.side_effect = [WindowsError(
pathutils.ERROR_DIR_IS_NOT_EMPTY), True]
fake_windows_error = WindowsError
with mock.patch('__builtin__.WindowsError',
fake_windows_error, create=True):
with mock.patch.object(builtins, 'WindowsError',
fake_windows_error, create=True):
self._pathutils.rmtree(mock.sentinel.FAKE_PATH)
mock_rmtree.assert_has_calls([mock.call(mock.sentinel.FAKE_PATH),
@ -196,8 +197,8 @@ class PathUtilsTestCase(test_base.HyperVBaseTestCase):
fake_windows_error = WindowsError
self._pathutils._check_create_dir = mock.MagicMock(
side_effect=WindowsError(pathutils.ERROR_INVALID_NAME))
with mock.patch('__builtin__.WindowsError',
fake_windows_error, create=True):
with mock.patch.object(builtins, 'WindowsError',
fake_windows_error, create=True):
self.assertRaises(vmutils.HyperVException,
self._pathutils._get_instances_sub_dir,
fake_dir_name)

View File

@ -160,7 +160,7 @@ class SerialConsoleHandlerTestCase(test_base.HyperVBaseTestCase):
mock.call(mock.sentinel.rw_pipe_path,
pipe_type=constants.SERIAL_PORT_TYPE_RW,
enable_logging=False)]
mock_get_handler.assert_has_calls(expected_calls)
mock_get_handler.assert_has_calls(expected_calls, any_order=True)
@mock.patch.object(namedpipe, 'NamedPipeHandler')
def _test_get_named_pipe_handler(self, mock_pipe_handler_class,

View File

@ -14,6 +14,7 @@
# under the License.
import mock
from six.moves import builtins
from nova import exception
@ -89,7 +90,7 @@ class SerialConsoleOpsTestCase(test_base.HyperVBaseTestCase):
self._serialops.get_serial_console,
mock.sentinel.instance_name)
@mock.patch("__builtin__.open")
@mock.patch.object(builtins, 'open')
@mock.patch("os.path.exists")
def test_get_console_output_exception(self, fake_path_exists, fake_open):
self._serialops._pathutils.get_vm_console_log_paths.return_value = [

View File

@ -29,7 +29,7 @@ class VHDUtilsBaseTestCase(test.NoDBTestCase):
_FAKE_FORMAT = 3
_FAKE_TYPE = 3
_FAKE_MAX_INTERNAL_SIZE = units.Gi
_FAKE_DYNAMIC_BLK_SIZE = 2097152L
_FAKE_DYNAMIC_BLK_SIZE = 2097152
_FAKE_BAD_TYPE = 5
_FAKE_JOB_PATH = 'fake_job_path'
@ -234,8 +234,10 @@ class VHDUtilsTestCase(VHDUtilsBaseTestCase):
def test_get_vhd_format_vhdx(self):
with mock.patch('hyperv.nova.vhdutils.open',
mock.mock_open(read_data=vhdutils.VHDX_SIGNATURE),
create=True):
mock.mock_open(),
create=True) as mock_open:
mock_file = mock_open.return_value
mock_file.read.return_value = vhdutils.VHDX_SIGNATURE
format = self._vhdutils.get_vhd_format(self._FAKE_VHD_PATH)

View File

@ -13,6 +13,7 @@
# under the License.
import mock
from six.moves import builtins
from hyperv.nova import constants
from hyperv.nova import vhdutilsv2
@ -23,11 +24,11 @@ from hyperv.tests.unit import test_vhdutils
class VHDUtilsV2TestCase(test_vhdutils.VHDUtilsBaseTestCase):
"""Unit tests for the Hyper-V VHDUtilsV2 class."""
_FAKE_BLOCK_SIZE = 33554432L
_FAKE_BLOCK_SIZE = 33554432
_FAKE_LOG_SIZE = 1048576
_FAKE_LOGICAL_SECTOR_SIZE = 4096
_FAKE_METADATA_SIZE = 1048576
_FAKE_PHYSICAL_SECTOR_SIZE = 4096L
_FAKE_PHYSICAL_SECTOR_SIZE = 4096
def setUp(self):
super(VHDUtilsV2TestCase, self).setUp()
@ -50,7 +51,8 @@ class VHDUtilsV2TestCase(test_vhdutils.VHDUtilsBaseTestCase):
def _mock_get_vhd_info(self):
mock_img_svc = self._vhdutils._conn.Msvm_ImageManagementService()[0]
mock_img_svc.GetVirtualHardDiskSettingData.return_value = (
self._FAKE_JOB_PATH, self._FAKE_RET_VAL, self._FAKE_VHD_INFO_XML)
self._FAKE_JOB_PATH, self._FAKE_RET_VAL,
self._FAKE_VHD_INFO_XML)
def test_get_vhd_info(self):
self._mock_get_vhd_info()
@ -124,7 +126,7 @@ class VHDUtilsV2TestCase(test_vhdutils.VHDUtilsBaseTestCase):
expected_virt_disk_data = self._FAKE_VHD_INFO_XML.replace(
self._FAKE_PARENT_PATH, fake_new_parent_path)
mock_img_svc.SetVirtualHardDiskSettingData.assert_called_once_with(
VirtualDiskSettingData=expected_virt_disk_data)
VirtualDiskSettingData=expected_virt_disk_data.encode())
def test_reconnect_parent_vhd_exception(self):
# Test that reconnect_parent_vhd raises an exception if the
@ -180,7 +182,7 @@ class VHDUtilsV2TestCase(test_vhdutils.VHDUtilsBaseTestCase):
return_value=self._FAKE_BLOCK_SIZE)
file_mock = mock.MagicMock()
with mock.patch('__builtin__.open', file_mock):
with mock.patch.object(builtins, 'open', file_mock):
internal_size = (
self._vhdutils.get_internal_vhd_size_by_file_size(
self._FAKE_VHD_PATH, self._FAKE_MAX_INTERNAL_SIZE))
@ -196,8 +198,9 @@ class VHDUtilsV2TestCase(test_vhdutils.VHDUtilsBaseTestCase):
def test_get_vhdx_current_header(self):
VHDX_HEADER_OFFSETS = [64 * 1024, 128 * 1024]
fake_sequence_numbers = ['\x01\x00\x00\x00\x00\x00\x00\x00',
'\x02\x00\x00\x00\x00\x00\x00\x00']
fake_sequence_numbers = [
bytearray(b'\x01\x00\x00\x00\x00\x00\x00\x00'),
bytearray(b'\x02\x00\x00\x00\x00\x00\x00\x00')]
self._fake_file_handle.read = mock.MagicMock(
side_effect=fake_sequence_numbers)
@ -206,8 +209,8 @@ class VHDUtilsV2TestCase(test_vhdutils.VHDUtilsBaseTestCase):
self.assertEqual(offset, VHDX_HEADER_OFFSETS[1])
def test_get_vhdx_metadata_size(self):
fake_metadata_offset = '\x01\x00\x00\x00\x00\x00\x00\x00'
fake_metadata_size = '\x01\x00\x00\x00'
fake_metadata_offset = bytearray(b'\x01\x00\x00\x00\x00\x00\x00\x00')
fake_metadata_size = bytearray(b'\x01\x00\x00\x00')
self._fake_file_handle.read = mock.MagicMock(
side_effect=[fake_metadata_offset, fake_metadata_size])
@ -220,7 +223,7 @@ class VHDUtilsV2TestCase(test_vhdutils.VHDUtilsBaseTestCase):
def test_get_block_size(self):
self._vhdutils._get_vhdx_metadata_size_and_offset = mock.MagicMock(
return_value=(self._FAKE_METADATA_SIZE, 1024))
fake_block_size = '\x01\x00\x00\x00'
fake_block_size = bytearray(b'\x01\x00\x00\x00')
self._fake_file_handle.read = mock.MagicMock(
return_value=fake_block_size)
@ -232,7 +235,7 @@ class VHDUtilsV2TestCase(test_vhdutils.VHDUtilsBaseTestCase):
fake_current_header_offset = 64 * 1024
self._vhdutils._get_vhdx_current_header_offset = mock.MagicMock(
return_value=fake_current_header_offset)
fake_log_size = '\x01\x00\x00\x00'
fake_log_size = bytearray(b'\x01\x00\x00\x00')
self._fake_file_handle.read = mock.MagicMock(
return_value=fake_log_size)

View File

@ -26,6 +26,7 @@ from oslo_concurrency import processutils
from oslo_config import cfg
from oslo_utils import fileutils
from oslo_utils import units
import six
from hyperv.nova import constants
from hyperv.nova import vmops
@ -1060,7 +1061,7 @@ class VMOpsTestCase(test_base.HyperVBaseTestCase):
self._vmops._create_vm_com_port_pipes(mock_instance,
mock_serial_ports)
expected_calls = []
for port_number, port_type in mock_serial_ports.iteritems():
for port_number, port_type in six.iteritems(mock_serial_ports):
expected_pipe = r'\\.\pipe\%s_%s' % (mock_instance.uuid,
port_type)
expected_calls.append(mock.call(mock_instance.name,

View File

@ -15,6 +15,7 @@
import mock
from nova import exception
import six
from hyperv.nova import constants
from hyperv.nova import vmutils
@ -91,7 +92,7 @@ class VMUtilsTestCase(test.NoDBTestCase):
mock_svc.GetSummaryInformation.return_value = (self._FAKE_RET_VAL,
[mock_summary])
for (key, val) in self._FAKE_SUMMARY_INFO.items():
for key, val in six.iteritems(self._FAKE_SUMMARY_INFO):
setattr(mock_summary, key, val)
summary = self._vmutils.get_vm_summary_info(self._FAKE_VM_NAME)
@ -270,8 +271,8 @@ class VMUtilsTestCase(test.NoDBTestCase):
def test_get_free_controller_slot_exception(self):
mock_get_address = mock.Mock()
mock_get_address.side_effect = range(
constants.SCSI_CONTROLLER_SLOTS_NUMBER)
mock_get_address.side_effect = list(range(
constants.SCSI_CONTROLLER_SLOTS_NUMBER))
mock_get_attached_disks = mock.Mock()
mock_get_attached_disks.return_value = (

View File

@ -16,7 +16,6 @@
import os
import contextlib
import mock
from oslo_config import cfg
@ -88,13 +87,11 @@ class VolumeOpsTestCase(test_base.HyperVBaseTestCase):
fake_vol_conn_info = (
block_device_info['block_device_mapping'][0]['connection_info'])
with contextlib.nested(
mock.patch.object(self._volumeops,
'_get_volume_driver'),
mock.patch.object(self._volumeops,
'ebs_root_in_block_devices')
) as (mock_get_volume_driver,
mock_ebs_in_block_devices):
mock_get_volume_driver = mock.MagicMock()
mock_ebs_in_block_devices = mock.MagicMock()
with mock.patch.multiple(self._volumeops,
_get_volume_driver=mock_get_volume_driver,
ebs_root_in_block_devices=mock_ebs_in_block_devices):
fake_vol_driver = mock_get_volume_driver.return_value
mock_ebs_in_block_devices.return_value = False
@ -368,22 +365,18 @@ class ISCSIVolumeDriverTestCase(test_base.HyperVBaseTestCase):
mock.sentinel.fake_iqn)
def test_get_mounted_disk_from_lun(self):
with contextlib.nested(
mock.patch.object(self._volume_driver._volutils,
'get_device_number_for_target'),
mock.patch.object(self._volume_driver._vmutils,
'get_mounted_disk_by_drive_number')
) as (mock_get_device_number_for_target,
mock_get_mounted_disk_by_drive_number):
mock_get_device_number_for_target = (
self._volume_driver._volutils.get_device_number_for_target)
mock_get_device_number_for_target.return_value = 0
mock_get_device_number_for_target.return_value = 0
mock_get_mounted_disk_by_drive_number.return_value = (
mock.sentinel.disk_path)
mock_get_mounted_disk = (
self._volume_driver._vmutils.get_mounted_disk_by_drive_number)
mock_get_mounted_disk.return_value = mock.sentinel.disk_path
disk = self._volume_driver._get_mounted_disk_from_lun(
mock.sentinel.target_iqn,
mock.sentinel.target_lun)
self.assertEqual(mock.sentinel.disk_path, disk)
disk = self._volume_driver._get_mounted_disk_from_lun(
mock.sentinel.target_iqn,
mock.sentinel.target_lun)
self.assertEqual(mock.sentinel.disk_path, disk)
def test_get_target_from_disk_path(self):
result = self._volume_driver.get_target_from_disk_path(