Run pyupgrade to clean up Python 2 syntaxes

Update all .py source files by
 $ pyupgrade --py3-only $(git ls-files | grep ".py$")
to modernize the code according to Python 3 syntaxes.

pep8 errors are fixed by
 $ autopep8 --select=E127,E128,E501 --max-line-length 79 -r \
    --in-place oslo_utils

Also add the pyupgrade hook to pre-commit to avoid merging additional
Python 2 syntaxes.

Change-Id: If34f08dc3156b75f38dfe1c5e4698952fea7abba
This commit is contained in:
Takashi Kajinami 2025-01-13 13:32:18 +09:00 committed by Jay Faulkner
parent a0c8385fdc
commit 41f5fb6e00
31 changed files with 95 additions and 107 deletions

View File

@ -1,6 +1,6 @@
repos: repos:
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0 rev: v5.0.0
hooks: hooks:
- id: trailing-whitespace - id: trailing-whitespace
# Replaces or checks mixed line ending # Replaces or checks mixed line ending
@ -19,12 +19,17 @@ repos:
- id: check-yaml - id: check-yaml
files: .*\.(yaml|yml)$ files: .*\.(yaml|yml)$
- repo: https://opendev.org/openstack/hacking - repo: https://opendev.org/openstack/hacking
rev: 6.1.0 rev: 7.0.0
hooks: hooks:
- id: hacking - id: hacking
additional_dependencies: [] additional_dependencies: []
- repo: https://github.com/PyCQA/bandit - repo: https://github.com/PyCQA/bandit
rev: 1.7.6 rev: 1.7.10
hooks: hooks:
- id: bandit - id: bandit
args: ['-x', 'tests'] args: ['-x', 'tests']
- repo: https://github.com/asottile/pyupgrade
rev: v3.18.0
hooks:
- id: pyupgrade
args: [--py3-only]

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2020 Red Hat, Inc. # Copyright (C) 2020 Red Hat, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");

View File

@ -24,6 +24,6 @@ def flatten_dict_to_keypairs(d, separator=':'):
if isinstance(value, dict): if isinstance(value, dict):
for subname, subvalue in flatten_dict_to_keypairs(value, for subname, subvalue in flatten_dict_to_keypairs(value,
separator): separator):
yield '%s%s%s' % (name, separator, subname), subvalue yield '{}{}{}'.format(name, separator, subname), subvalue
else: else:
yield name, value yield name, value

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2015 Yahoo! Inc. All Rights Reserved. # Copyright (C) 2015 Yahoo! Inc. All Rights Reserved.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may # Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -146,14 +144,14 @@ def is_monkey_patched(module):
return _patcher.is_monkey_patched(module) return _patcher.is_monkey_patched(module)
class EventletEvent(object): class EventletEvent:
"""A class that provides consistent eventlet/threading Event API. """A class that provides consistent eventlet/threading Event API.
This wraps the eventlet.event.Event class to have the same API as This wraps the eventlet.event.Event class to have the same API as
the standard threading.Event object. the standard threading.Event object.
""" """
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(EventletEvent, self).__init__() super().__init__()
self.clear() self.clear()
def clear(self): def clear(self):

View File

@ -49,7 +49,7 @@ class CausedByException(Exception):
.. versionadded:: 2.4 .. versionadded:: 2.4
""" """
def __init__(self, message, cause=None): def __init__(self, message, cause=None):
super(CausedByException, self).__init__(message) super().__init__(message)
self.cause = cause self.cause = cause
def __bytes__(self): def __bytes__(self):
@ -142,7 +142,7 @@ def raise_with_cause(exc_cls, message, *args, **kwargs):
raise exc_cls(message, *args, **kwargs) from kwargs.get('cause') raise exc_cls(message, *args, **kwargs) from kwargs.get('cause')
class save_and_reraise_exception(object): class save_and_reraise_exception:
"""Save current exception, run some code and then re-raise. """Save current exception, run some code and then re-raise.
In some cases the exception context can be cleared, resulting in None In some cases the exception context can be cleared, resulting in None
@ -287,7 +287,7 @@ def forever_retry_uncaught_exceptions(*args, **kwargs):
return decorator return decorator
class exception_filter(object): class exception_filter:
"""A context manager that prevents some exceptions from being raised. """A context manager that prevents some exceptions from being raised.
Use this class as a decorator for a function that returns whether a given Use this class as a decorator for a function that returns whether a given

View File

@ -150,7 +150,7 @@ def last_bytes(path, num):
with open(path, 'rb') as fp: with open(path, 'rb') as fp:
try: try:
fp.seek(-num, os.SEEK_END) fp.seek(-num, os.SEEK_END)
except IOError as e: except OSError as e:
# seek() fails with EINVAL when trying to go before the start of # seek() fails with EINVAL when trying to go before the start of
# the file. It means that num is larger than the file size, so # the file. It means that num is larger than the file size, so
# just go to the start. # just go to the start.
@ -173,7 +173,7 @@ def is_json(file_path):
:returns: bool :returns: bool
""" """
with open(file_path, 'r') as fh: with open(file_path) as fh:
data = fh.read() data = fh.read()
try: try:
json.loads(data) json.loads(data)
@ -195,7 +195,7 @@ def is_yaml(file_path):
:returns: bool :returns: bool
""" """
with open(file_path, 'r') as fh: with open(file_path) as fh:
data = fh.read() data = fh.read()
is_yaml = False is_yaml = False
try: try:

View File

@ -1,4 +1,3 @@
# Copyright 2015 OpenStack Foundation # Copyright 2015 OpenStack Foundation
# All Rights Reserved. # All Rights Reserved.
# #
@ -37,11 +36,11 @@ class TimeFixture(fixtures.Fixture):
""" """
def __init__(self, override_time=None): def __init__(self, override_time=None):
super(TimeFixture, self).__init__() super().__init__()
self._override_time = override_time self._override_time = override_time
def setUp(self): def setUp(self):
super(TimeFixture, self).setUp() super().setUp()
timeutils.set_time_override(self._override_time) timeutils.set_time_override(self._override_time)
self.addCleanup(timeutils.clear_time_override) self.addCleanup(timeutils.clear_time_override)
@ -54,7 +53,7 @@ class TimeFixture(fixtures.Fixture):
timeutils.advance_time_seconds(seconds) timeutils.advance_time_seconds(seconds)
class _UUIDSentinels(object): class _UUIDSentinels:
"""Registry of dynamically created, named, random UUID strings in regular """Registry of dynamically created, named, random UUID strings in regular
(with hyphens) and similar to some keystone IDs (without hyphens) formats. (with hyphens) and similar to some keystone IDs (without hyphens) formats.

View File

@ -77,7 +77,7 @@ def main():
safe = False safe = False
failure_reasons = [] failure_reasons = []
for exc in e.failures.items(): for exc in e.failures.items():
failure_reasons.append("%s: %s" % (exc[0], exc[1])) failure_reasons.append("{}: {}".format(exc[0], exc[1]))
virtual_size = inspector.virtual_size virtual_size = inspector.virtual_size
actual_size = inspector.actual_size actual_size = inspector.actual_size

View File

@ -39,7 +39,7 @@ def _chunked_reader(fileobj, chunk_size=512):
yield chunk yield chunk
class CaptureRegion(object): class CaptureRegion:
"""Represents a region of a file we want to capture. """Represents a region of a file we want to capture.
A region of a file we want to capture requires a byte offset into A region of a file we want to capture requires a byte offset into
@ -1416,7 +1416,7 @@ class InspectWrapper:
This will be None if a decision has not been reached. This will be None if a decision has not been reached.
""" """
non_raw = set([i for i in self._inspectors if i.NAME != 'raw']) non_raw = {i for i in self._inspectors if i.NAME != 'raw'}
complete = all([i.complete for i in non_raw]) complete = all([i.complete for i in non_raw])
matches = [i for i in non_raw if i.format_match] matches = [i for i in non_raw if i.format_match]
if not complete and not self._finished: if not complete and not self._finished:

View File

@ -34,7 +34,7 @@ from oslo_utils._i18n import _
from oslo_utils import strutils from oslo_utils import strutils
class QemuImgInfo(object): class QemuImgInfo:
"""Parse Qemu image information from command `qemu-img info`'s output. """Parse Qemu image information from command `qemu-img info`'s output.
The instance of :class:`QemuImgInfo` has properties: `image`, The instance of :class:`QemuImgInfo` has properties: `image`,
@ -130,7 +130,8 @@ class QemuImgInfo(object):
# Allow abbreviated unit such as K to mean KB for compatibility. # Allow abbreviated unit such as K to mean KB for compatibility.
if len(unit_of_measure) == 1 and unit_of_measure != 'B': if len(unit_of_measure) == 1 and unit_of_measure != 'B':
unit_of_measure += 'B' unit_of_measure += 'B'
return strutils.string_to_bytes('%s%s' % (magnitude, unit_of_measure), return strutils.string_to_bytes(
'{}{}'.format(magnitude, unit_of_measure),
return_int=True) return_int=True)
def _extract_details(self, root_cmd, root_details, lines_after): def _extract_details(self, root_cmd, root_details, lines_after):

View File

@ -57,7 +57,7 @@ def import_object_ns(name_space, import_str, *args, **kwargs):
Don't capture :exc:`ImportError` when instanciating the object, only Don't capture :exc:`ImportError` when instanciating the object, only
when importing the object class. when importing the object class.
""" """
import_value = "%s.%s" % (name_space, import_str) import_value = "{}.{}".format(name_space, import_str)
try: try:
cls = import_class(import_value) cls = import_class(import_value)
except ImportError: except ImportError:
@ -91,7 +91,7 @@ def import_versioned_module(module, version, submodule=None):
# NOTE(gcb) Disallow parameter version include character '.' # NOTE(gcb) Disallow parameter version include character '.'
if '.' in '%s' % version: if '.' in '%s' % version:
raise ValueError("Parameter version shouldn't include character '.'.") raise ValueError("Parameter version shouldn't include character '.'.")
module_str = '%s.v%s' % (module, version) module_str = '{}.v{}'.format(module, version)
if submodule: if submodule:
module_str = '.'.join((module_str, submodule)) module_str = '.'.join((module_str, submodule))
return import_module(module_str) return import_module(module_str)

View File

@ -270,7 +270,7 @@ def is_ipv6_enabled():
if _IS_IPV6_ENABLED is None: if _IS_IPV6_ENABLED is None:
disabled_ipv6_path = "/proc/sys/net/ipv6/conf/default/disable_ipv6" disabled_ipv6_path = "/proc/sys/net/ipv6/conf/default/disable_ipv6"
if os.path.exists(disabled_ipv6_path): if os.path.exists(disabled_ipv6_path):
with open(disabled_ipv6_path, 'r') as f: with open(disabled_ipv6_path) as f:
disabled = f.read().strip() disabled = f.read().strip()
_IS_IPV6_ENABLED = disabled == "0" _IS_IPV6_ENABLED = disabled == "0"
else: else:
@ -389,7 +389,7 @@ def get_my_ipv4():
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as csock: with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as csock:
csock.connect(('192.0.2.0', 80)) csock.connect(('192.0.2.0', 80))
return csock.getsockname()[0] return csock.getsockname()[0]
except socket.error: except OSError:
return _get_my_ipv4_address() return _get_my_ipv4_address()
@ -445,7 +445,7 @@ def get_my_ipv6():
with socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) as csock: with socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) as csock:
csock.connect(('2001:db8::1', 80)) csock.connect(('2001:db8::1', 80))
return csock.getsockname()[0] return csock.getsockname()[0]
except socket.error: except OSError:
return _get_my_ipv6_address() return _get_my_ipv6_address()

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2012-2013 Yahoo! Inc. All Rights Reserved. # Copyright (C) 2012-2013 Yahoo! Inc. All Rights Reserved.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may # Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -88,7 +86,7 @@ def get_class_name(obj, fully_qualified=True, truncate_builtins=True):
if built_in: if built_in:
return obj.__name__ return obj.__name__
if fully_qualified and hasattr(obj, '__module__'): if fully_qualified and hasattr(obj, '__module__'):
return '%s.%s' % (obj.__module__, obj.__name__) return '{}.{}'.format(obj.__module__, obj.__name__)
else: else:
return obj.__name__ return obj.__name__

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain # not use this file except in compliance with the License. You may obtain
# a copy of the License at # a copy of the License at

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2010-2011 OpenStack Foundation # Copyright 2010-2011 OpenStack Foundation
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P. # Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
# #
@ -32,7 +30,7 @@ class TestCase(testtools.TestCase):
def setUp(self): def setUp(self):
"""Run before each test method to initialize test environment.""" """Run before each test method to initialize test environment."""
super(TestCase, self).setUp() super().setUp()
test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0) test_timeout = os.environ.get('OS_TEST_TIMEOUT', 0)
try: try:
test_timeout = int(test_timeout) test_timeout = int(test_timeout)

View File

@ -13,16 +13,16 @@
# under the License. # under the License.
class V2FakeDriver(object): class V2FakeDriver:
def __init__(self, first_arg=True): def __init__(self, first_arg=True):
self.first_arg = first_arg self.first_arg = first_arg
class V2FakeDriver2(object): class V2FakeDriver2:
def __init__(self, first_arg): def __init__(self, first_arg):
self.first_arg = first_arg self.first_arg = first_arg
class V2FakeDriver3(object): class V2FakeDriver3:
def __init__(self): def __init__(self):
raise ImportError("ImportError occurs in __init__") raise ImportError("ImportError occurs in __init__")

View File

@ -42,11 +42,11 @@ def get_size_format_from_qemu_img(filename):
@ddt.ddt @ddt.ddt
class TestFormatInspectors(test_base.BaseTestCase): class TestFormatInspectors(test_base.BaseTestCase):
def setUp(self): def setUp(self):
super(TestFormatInspectors, self).setUp() super().setUp()
self._created_files = [] self._created_files = []
def tearDown(self): def tearDown(self):
super(TestFormatInspectors, self).tearDown() super().tearDown()
for fn in self._created_files: for fn in self._created_files:
try: try:
os.remove(fn) os.remove(fn)
@ -95,7 +95,7 @@ class TestFormatInspectors(test_base.BaseTestCase):
# are the same and can cause test failures # are the same and can cause test failures
out_fn = "%s.iso" % fn out_fn = "%s.iso" % fn
subprocess.check_output( subprocess.check_output(
'%s -V "TEST" -o %s %s' % (base_cmd, out_fn, fn), '{} -V "TEST" -o {} {}'.format(base_cmd, out_fn, fn),
shell=True) shell=True)
self._created_files.append(out_fn) self._created_files.append(out_fn)
return out_fn return out_fn
@ -120,7 +120,7 @@ class TestFormatInspectors(test_base.BaseTestCase):
0x01, # start LBA 0x01, # start LBA
0x00, # size LBA 0x00, # size LBA
) )
fn = tempfile.mktemp(prefix='%s-gpt-%s' % (TEST_IMAGE_PREFIX, fn = tempfile.mktemp(prefix='{}-gpt-{}'.format(TEST_IMAGE_PREFIX,
subformat)) subformat))
with open(fn, 'wb') as f: with open(fn, 'wb') as f:
f.write(data) f.write(data)
@ -180,7 +180,7 @@ class TestFormatInspectors(test_base.BaseTestCase):
prefix += subformat + '-' prefix += subformat + '-'
if options: if options:
opt += '-o ' + ','.join('%s=%s' % (k, v) opt += '-o ' + ','.join('{}={}'.format(k, v)
for k, v in options.items()) for k, v in options.items())
if backing_file is not None: if backing_file is not None:
@ -218,8 +218,8 @@ class TestFormatInspectors(test_base.BaseTestCase):
# Convert it to VMDK # Convert it to VMDK
subprocess.check_output( subprocess.check_output(
'qemu-img convert -f raw -O vmdk -o subformat=%s -S 0 %s %s' % ( 'qemu-img convert -f raw -O vmdk -o subformat={} -S 0 {} {}'
subformat, raw, fn), .format(subformat, raw, fn),
shell=True) shell=True)
return fn return fn
@ -334,10 +334,10 @@ class TestFormatInspectors(test_base.BaseTestCase):
fn = tempfile.mktemp(prefix=prefix, suffix='.iso') fn = tempfile.mktemp(prefix=prefix, suffix='.iso')
self._created_files.append(fn) self._created_files.append(fn)
subprocess.check_output( subprocess.check_output(
'dd if=%s of=%s bs=32K count=1' % (qcow, fn), 'dd if={} of={} bs=32K count=1'.format(qcow, fn),
shell=True) shell=True)
subprocess.check_output( subprocess.check_output(
'dd if=%s of=%s bs=32K skip=1 seek=1' % (iso, fn), 'dd if={} of={} bs=32K skip=1 seek=1'.format(iso, fn),
shell=True) shell=True)
return qcow, iso, fn return qcow, iso, fn

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (c) 2016 EasyStack Inc. # Copyright (c) 2016 EasyStack Inc.
# All Rights Reserved. # All Rights Reserved.
# #

View File

@ -25,12 +25,12 @@ from oslo_utils import eventletutils
class EventletUtilsTest(test_base.BaseTestCase): class EventletUtilsTest(test_base.BaseTestCase):
def setUp(self): def setUp(self):
super(EventletUtilsTest, self).setUp() super().setUp()
self._old_avail = eventletutils.EVENTLET_AVAILABLE self._old_avail = eventletutils.EVENTLET_AVAILABLE
eventletutils.EVENTLET_AVAILABLE = True eventletutils.EVENTLET_AVAILABLE = True
def tearDown(self): def tearDown(self):
super(EventletUtilsTest, self).tearDown() super().tearDown()
eventletutils.EVENTLET_AVAILABLE = self._old_avail eventletutils.EVENTLET_AVAILABLE = self._old_avail
@mock.patch("oslo_utils.eventletutils._patcher") @mock.patch("oslo_utils.eventletutils._patcher")

View File

@ -63,7 +63,7 @@ class SaveAndReraiseTest(test_base.BaseTestCase):
def _force_reraise(): def _force_reraise():
try: try:
raise IOError("I broke") raise OSError("I broke")
except Exception: except Exception:
with excutils.save_and_reraise_exception() as e: with excutils.save_and_reraise_exception() as e:
e.reraise = False e.reraise = False
@ -75,7 +75,7 @@ class SaveAndReraiseTest(test_base.BaseTestCase):
def _force_reraise(): def _force_reraise():
try: try:
raise IOError("I broke") raise OSError("I broke")
except Exception: except Exception:
excutils.save_and_reraise_exception().capture().force_reraise() excutils.save_and_reraise_exception().capture().force_reraise()
@ -163,7 +163,7 @@ class SaveAndReraiseTest(test_base.BaseTestCase):
class ForeverRetryUncaughtExceptionsTest(test_base.BaseTestCase): class ForeverRetryUncaughtExceptionsTest(test_base.BaseTestCase):
def setUp(self): def setUp(self):
super(ForeverRetryUncaughtExceptionsTest, self).setUp() super().setUp()
self._exceptions = [] self._exceptions = []
@ -437,7 +437,7 @@ class ExceptionFilterTest(test_base.BaseTestCase):
return ignore_exceptions return ignore_exceptions
def _make_filter_method(self, ignore_classes=AssertionError): def _make_filter_method(self, ignore_classes=AssertionError):
class ExceptionIgnorer(object): class ExceptionIgnorer:
def __init__(self, ignore): def __init__(self, ignore):
self.ignore = ignore self.ignore = ignore
@ -449,7 +449,7 @@ class ExceptionFilterTest(test_base.BaseTestCase):
return ExceptionIgnorer(ignore_classes).ignore_exceptions return ExceptionIgnorer(ignore_classes).ignore_exceptions
def _make_filter_classmethod(self, ignore_classes=AssertionError): def _make_filter_classmethod(self, ignore_classes=AssertionError):
class ExceptionIgnorer(object): class ExceptionIgnorer:
ignore = ignore_classes ignore = ignore_classes
@excutils.exception_filter @excutils.exception_filter
@ -461,7 +461,7 @@ class ExceptionFilterTest(test_base.BaseTestCase):
return ExceptionIgnorer.ignore_exceptions return ExceptionIgnorer.ignore_exceptions
def _make_filter_staticmethod(self, ignore_classes=AssertionError): def _make_filter_staticmethod(self, ignore_classes=AssertionError):
class ExceptionIgnorer(object): class ExceptionIgnorer:
@excutils.exception_filter @excutils.exception_filter
@staticmethod @staticmethod
def ignore_exceptions(ex): def ignore_exceptions(ex):

View File

@ -36,7 +36,7 @@ class EnsureTree(test_base.BaseTestCase):
def test_ensure_tree(self): def test_ensure_tree(self):
tmpdir = tempfile.mkdtemp() tmpdir = tempfile.mkdtemp()
try: try:
testdir = '%s/foo/bar/baz' % (tmpdir,) testdir = '{}/foo/bar/baz'.format(tmpdir)
fileutils.ensure_tree(testdir, TEST_PERMISSIONS) fileutils.ensure_tree(testdir, TEST_PERMISSIONS)
self.assertTrue(os.path.isdir(testdir)) self.assertTrue(os.path.isdir(testdir))
self.assertEqual(os.stat(testdir).st_mode, self.assertEqual(os.stat(testdir).st_mode,
@ -124,11 +124,11 @@ class RemovePathOnError(test_base.BaseTestCase):
class WriteToTempfileTestCase(test_base.BaseTestCase): class WriteToTempfileTestCase(test_base.BaseTestCase):
def setUp(self): def setUp(self):
super(WriteToTempfileTestCase, self).setUp() super().setUp()
self.content = 'testing123'.encode('ascii') self.content = b'testing123'
def check_file_content(self, path): def check_file_content(self, path):
with open(path, 'r') as fd: with open(path) as fd:
ans = fd.read() ans = fd.read()
self.assertEqual(self.content, ans.encode("latin-1")) self.assertEqual(self.content, ans.encode("latin-1"))
@ -197,11 +197,11 @@ class WriteToTempfileTestCase(test_base.BaseTestCase):
class TestComputeFileChecksum(test_base.BaseTestCase): class TestComputeFileChecksum(test_base.BaseTestCase):
def setUp(self): def setUp(self):
super(TestComputeFileChecksum, self).setUp() super().setUp()
self.content = 'fake_content'.encode('ascii') self.content = b'fake_content'
def check_file_content(self, content, path): def check_file_content(self, content, path):
with open(path, 'r') as fd: with open(path) as fd:
ans = fd.read() ans = fd.read()
self.assertEqual(content, ans.encode("latin-1")) self.assertEqual(content, ans.encode("latin-1"))
@ -269,7 +269,7 @@ class LastBytesTestCase(test_base.BaseTestCase):
"""Test the last_bytes() utility method.""" """Test the last_bytes() utility method."""
def setUp(self): def setUp(self):
super(LastBytesTestCase, self).setUp() super().setUp()
self.content = b'1234567890' self.content = b'1234567890'
def test_truncated(self): def test_truncated(self):
@ -295,7 +295,7 @@ class FileTypeTestCase(test_base.BaseTestCase):
"""Test the is_yaml() and is_json() utility methods.""" """Test the is_yaml() and is_json() utility methods."""
def setUp(self): def setUp(self):
super(FileTypeTestCase, self).setUp() super().setUp()
data = { data = {
'name': 'test', 'name': 'test',
'website': 'example.com' 'website': 'example.com'

View File

@ -1,4 +1,3 @@
# Copyright 2015 OpenStack Foundation # Copyright 2015 OpenStack Foundation
# All Rights Reserved. # All Rights Reserved.
# #

View File

@ -513,7 +513,7 @@ def mock_file_content(content):
class TestIsIPv6Enabled(test_base.BaseTestCase): class TestIsIPv6Enabled(test_base.BaseTestCase):
def setUp(self): def setUp(self):
super(TestIsIPv6Enabled, self).setUp() super().setUp()
def reset_detection_flag(): def reset_detection_flag():
netutils._IS_IPV6_ENABLED = None netutils._IS_IPV6_ENABLED = None

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2012 Yahoo! Inc. All Rights Reserved. # Copyright (C) 2012 Yahoo! Inc. All Rights Reserved.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); you may # Licensed under the Apache License, Version 2.0 (the "License"); you may
@ -47,7 +45,7 @@ def function_with_kwargs(a, b, **kwargs):
pass pass
class TestObject(object): class TestObject:
def _hello(self): def _hello(self):
pass pass
@ -55,7 +53,7 @@ class TestObject(object):
pass pass
class Class(object): class Class:
def method(self, c, d): def method(self, c, d):
pass pass
@ -69,7 +67,7 @@ class Class(object):
pass pass
class BadClass(object): class BadClass:
def do_something(self): def do_something(self):
pass pass
@ -77,12 +75,12 @@ class BadClass(object):
return False return False
class CallableClass(object): class CallableClass:
def __call__(self, i, j): def __call__(self, i, j):
pass pass
class ClassWithInit(object): class ClassWithInit:
def __init__(self, k, lll): def __init__(self, k, lll):
pass pass
@ -123,7 +121,7 @@ class CallbackEqualityTest(test_base.BaseTestCase):
def test_static_instance_callbacks(self): def test_static_instance_callbacks(self):
class A(object): class A:
@staticmethod @staticmethod
def b(a, b, c): def b(a, b, c):
@ -136,7 +134,7 @@ class CallbackEqualityTest(test_base.BaseTestCase):
def test_different_instance_callbacks(self): def test_different_instance_callbacks(self):
class A(object): class A:
def b(self): def b(self):
pass pass
@ -201,7 +199,7 @@ class GetCallableNameTest(test_base.BaseTestCase):
class GetCallableNameTestExtended(test_base.BaseTestCase): class GetCallableNameTestExtended(test_base.BaseTestCase):
# Tests items in http://legacy.python.org/dev/peps/pep-3155/ # Tests items in http://legacy.python.org/dev/peps/pep-3155/
class InnerCallableClass(object): class InnerCallableClass:
def __call__(self): def __call__(self):
pass pass
@ -298,7 +296,7 @@ class GetClassNameTest(test_base.BaseTestCase):
self.assertEqual('.'.join((__name__, 'Class')), name) self.assertEqual('.'.join((__name__, 'Class')), name)
def test_qualified_class(self): def test_qualified_class(self):
class QualifiedClass(object): class QualifiedClass:
pass pass
name = reflection.get_class_name(QualifiedClass) name = reflection.get_class_name(QualifiedClass)

View File

@ -31,7 +31,7 @@ class SecretUtilsTest(testscenarios.TestWithScenarios,
('unicode', {'converter': lambda text: text}), ('unicode', {'converter': lambda text: text}),
] ]
_test_data = "Openstack forever".encode('utf-8') _test_data = b"Openstack forever"
_md5_digest = hashlib.md5(_test_data).digest() _md5_digest = hashlib.md5(_test_data).digest()
def test_md5_with_data(self): def test_md5_with_data(self):

View File

@ -170,7 +170,7 @@ class StrUtilsTest(test_base.BaseTestCase):
self.assertEqual("ju5tnum8er", to_slug("ju5tnum8er")) self.assertEqual("ju5tnum8er", to_slug("ju5tnum8er"))
self.assertEqual("strip-", to_slug(" strip - ")) self.assertEqual("strip-", to_slug(" strip - "))
self.assertEqual("perche", self.assertEqual("perche",
to_slug("perch\xc3\xa9".encode("latin-1"))) to_slug(b"perch\xc3\xa9"))
self.assertEqual("strange", self.assertEqual("strange",
to_slug("\x80strange", errors="ignore")) to_slug("\x80strange", errors="ignore"))
@ -250,7 +250,7 @@ class StringToBytesTest(test_base.BaseTestCase):
def test_string_to_bytes(self): def test_string_to_bytes(self):
def _get_quantity(sign, magnitude, unit_suffix): def _get_quantity(sign, magnitude, unit_suffix):
res = float('%s%s' % (sign, magnitude)) res = float('{}{}'.format(sign, magnitude))
if unit_suffix in ['b', 'bit']: if unit_suffix in ['b', 'bit']:
res /= 8 res /= 8
return res return res
@ -689,7 +689,7 @@ class MaskPasswordTestCase(test_base.BaseTestCase):
class TestMapping(collections.abc.Mapping): class TestMapping(collections.abc.Mapping):
"""Test class for non-dict mappings""" """Test class for non-dict mappings"""
def __init__(self): def __init__(self):
super(TestMapping, self).__init__() super().__init__()
self.data = {'password': 'shhh', self.data = {'password': 'shhh',
'foo': 'bar', 'foo': 'bar',
} }
@ -707,7 +707,7 @@ class TestMapping(collections.abc.Mapping):
class NestedMapping(TestMapping): class NestedMapping(TestMapping):
"""Test class that contains an instance of TestMapping""" """Test class that contains an instance of TestMapping"""
def __init__(self): def __init__(self):
super(NestedMapping, self).__init__() super().__init__()
self.data = {'nested': TestMapping()} self.data = {'nested': TestMapping()}

View File

@ -34,7 +34,7 @@ def monotonic_iter(start=0, incr=0.05):
class TimeUtilsTest(test_base.BaseTestCase): class TimeUtilsTest(test_base.BaseTestCase):
def setUp(self): def setUp(self):
super(TimeUtilsTest, self).setUp() super().setUp()
self.skynet_self_aware_time_str = '1997-08-29T06:14:00Z' self.skynet_self_aware_time_str = '1997-08-29T06:14:00Z'
self.skynet_self_aware_time_ms_str = '1997-08-29T06:14:00.000123Z' self.skynet_self_aware_time_ms_str = '1997-08-29T06:14:00.000123Z'
self.skynet_self_aware_time = datetime.datetime(1997, 8, 29, 6, 14, 0) self.skynet_self_aware_time = datetime.datetime(1997, 8, 29, 6, 14, 0)
@ -361,7 +361,7 @@ class TimeItTest(test_base.BaseTestCase):
@timeutils.time_it(fake_logger) @timeutils.time_it(fake_logger)
def broken_function(): def broken_function():
raise IOError("Broken") raise OSError("Broken")
self.assertRaises(IOError, broken_function) self.assertRaises(IOError, broken_function)
self.assertFalse(fake_logger.log.called) self.assertFalse(fake_logger.log.called)

View File

@ -1,5 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright 2014 Red Hat, Inc. # Copyright 2014 Red Hat, Inc.
# All Rights Reserved. # All Rights Reserved.
# #
@ -29,19 +27,19 @@ class EncodeUtilsTest(test_base.BaseTestCase):
safe_decode = encodeutils.safe_decode safe_decode = encodeutils.safe_decode
self.assertRaises(TypeError, safe_decode, True) self.assertRaises(TypeError, safe_decode, True)
self.assertEqual('ni\xf1o', self.assertEqual('ni\xf1o',
safe_decode("ni\xc3\xb1o".encode("latin-1"), safe_decode(b"ni\xc3\xb1o",
incoming="utf-8")) incoming="utf-8"))
self.assertEqual("strange", self.assertEqual("strange",
safe_decode('\x80strange'.encode("latin-1"), safe_decode(b'\x80strange',
errors='ignore')) errors='ignore'))
self.assertEqual('\xc0', safe_decode('\xc0'.encode("latin-1"), self.assertEqual('\xc0', safe_decode(b'\xc0',
incoming='iso-8859-1')) incoming='iso-8859-1'))
# Forcing incoming to ascii so it falls back to utf-8 # Forcing incoming to ascii so it falls back to utf-8
self.assertEqual('ni\xf1o', self.assertEqual('ni\xf1o',
safe_decode('ni\xc3\xb1o'.encode("latin-1"), safe_decode(b'ni\xc3\xb1o',
incoming='ascii')) incoming='ascii'))
self.assertEqual('foo', safe_decode(b'foo')) self.assertEqual('foo', safe_decode(b'foo'))
@ -67,8 +65,8 @@ class EncodeUtilsTest(test_base.BaseTestCase):
def test_safe_encode_force_incoming_utf8_to_ascii(self): def test_safe_encode_force_incoming_utf8_to_ascii(self):
# Forcing incoming to ascii so it falls back to utf-8 # Forcing incoming to ascii so it falls back to utf-8
self.assertEqual( self.assertEqual(
'ni\xc3\xb1o'.encode("latin-1"), b'ni\xc3\xb1o',
encodeutils.safe_encode('ni\xc3\xb1o'.encode("latin-1"), encodeutils.safe_encode(b'ni\xc3\xb1o',
incoming='ascii'), incoming='ascii'),
) )
@ -91,7 +89,7 @@ class EncodeUtilsTest(test_base.BaseTestCase):
result = encodeutils.safe_encode( result = encodeutils.safe_encode(
text=text, incoming='utf-8', encoding='iso-8859-1') text=text, incoming='utf-8', encoding='iso-8859-1')
self.assertNotEqual(text, result) self.assertNotEqual(text, result)
self.assertNotEqual("foo\xf1bar".encode("latin-1"), result) self.assertNotEqual(b"foo\xf1bar", result)
def test_to_utf8(self): def test_to_utf8(self):
self.assertEqual(encodeutils.to_utf8(b'a\xe9\xff'), # bytes self.assertEqual(encodeutils.to_utf8(b'a\xe9\xff'), # bytes

View File

@ -254,7 +254,7 @@ def is_soon(dt, window):
return normalize_time(dt) <= soon return normalize_time(dt) <= soon
class Split(object): class Split:
"""A *immutable* stopwatch split. """A *immutable* stopwatch split.
See: http://en.wikipedia.org/wiki/Stopwatch for what this is/represents. See: http://en.wikipedia.org/wiki/Stopwatch for what this is/represents.
@ -280,7 +280,7 @@ class Split(object):
def __repr__(self): def __repr__(self):
r = reflection.get_class_name(self, fully_qualified=False) r = reflection.get_class_name(self, fully_qualified=False)
r += "(elapsed=%s, length=%s)" % (self._elapsed, self._length) r += "(elapsed={}, length={})".format(self._elapsed, self._length)
return r return r
@ -331,7 +331,7 @@ def time_it(logger, log_level=logging.DEBUG,
return decorator return decorator
class StopWatch(object): class StopWatch:
"""A simple timer/stopwatch helper class. """A simple timer/stopwatch helper class.
Inspired by: apache-commons-lang java stopwatch. Inspired by: apache-commons-lang java stopwatch.

View File

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Copyright (C) 2020 Red Hat, Inc. # Copyright (C) 2020 Red Hat, Inc.
# #
# Licensed under the Apache License, Version 2.0 (the "License"); # Licensed under the Apache License, Version 2.0 (the "License");

View File

@ -28,7 +28,7 @@ from oslo_utils import strutils
# http://dl.sileht.net/public/payload.json.gz # http://dl.sileht.net/public/payload.json.gz
infile = 'large_json_payload.txt' infile = 'large_json_payload.txt'
with open(infile, 'r') as f: with open(infile) as f:
input_str = f.read() input_str = f.read()
print('payload has %d bytes' % len(input_str)) print('payload has %d bytes' % len(input_str))
@ -38,9 +38,9 @@ for pattern in strutils._SANITIZE_PATTERNS_2['admin_pass']:
r"re.sub(pattern, r'\g<1>***\g<2>', payload)", r"re.sub(pattern, r'\g<1>***\g<2>', payload)",
""" """
import re import re
payload = '''%s''' payload = '''{}'''
pattern = re.compile(r'''%s''') pattern = re.compile(r'''{}''')
""" % (input_str, pattern.pattern)) """.format(input_str, pattern.pattern))
print(t.timeit(1)) print(t.timeit(1))
t = timeit.Timer( t = timeit.Timer(