Add typing (3/3)

Fix test issues. There are lots of ignores since we are intentionally
testing things that don't work here.

Change-Id: I5e7b068c79340f18783e083f4d4d69f2f230a7b3
Signed-off-by: Stephen Finucane <sfinucan@redhat.com>
This commit is contained in:
Stephen Finucane
2025-08-01 18:30:56 +01:00
parent 3407f63a9c
commit 7665ec514f
7 changed files with 46 additions and 35 deletions

View File

@@ -396,9 +396,9 @@ class TestFormatInspectors(test_base.BaseTestCase):
) )
# Make sure the multiple detected formats are exposed # Make sure the multiple detected formats are exposed
self.assertEqual( formats = wrapper.formats
['iso', 'qcow2'], sorted(x.NAME for x in wrapper.formats) assert formats is not None
) self.assertEqual(['iso', 'qcow2'], sorted(x.NAME for x in formats))
def test_from_file_reads_minimum(self): def test_from_file_reads_minimum(self):
img = self._create_img('qcow2', 10 * units.Mi) img = self._create_img('qcow2', 10 * units.Mi)
@@ -411,7 +411,9 @@ class TestFormatInspectors(test_base.BaseTestCase):
def test_qed_always_unsafe(self): def test_qed_always_unsafe(self):
img = self._create_img('qed', 10 * units.Mi) img = self._create_img('qed', 10 * units.Mi)
fmt = format_inspector.get_inspector('qed').from_file(img) inspector = format_inspector.get_inspector('qed')
assert inspector is not None
fmt = inspector.from_file(img)
self.assertTrue(fmt.format_match) self.assertTrue(fmt.format_match)
self.assertRaises(format_inspector.SafetyCheckFailed, fmt.safety_check) self.assertRaises(format_inspector.SafetyCheckFailed, fmt.safety_check)
@@ -420,6 +422,7 @@ class TestFormatInspectors(test_base.BaseTestCase):
'vmdk', 10 * units.Mi, subformat='monolithicFlat' 'vmdk', 10 * units.Mi, subformat='monolithicFlat'
) )
fmt = format_inspector.detect_file_format(img) fmt = format_inspector.detect_file_format(img)
assert fmt is not None
self.assertEqual('vmdk', fmt.NAME) self.assertEqual('vmdk', fmt.NAME)
e = self.assertRaises( e = self.assertRaises(
format_inspector.SafetyCheckFailed, fmt.safety_check format_inspector.SafetyCheckFailed, fmt.safety_check
@@ -918,7 +921,7 @@ class TestFormatInspectors(test_base.BaseTestCase):
def test_vmdk_format_checks(self): def test_vmdk_format_checks(self):
# Invalid signature # Invalid signature
fmt = format_inspector.VMDKInspector() fmt = format_inspector.VMDKInspector()
chunk = b'\x00' * 512 chunk: bytes | bytearray = b'\x00' * 512
self.assertRaisesRegex( self.assertRaisesRegex(
format_inspector.ImageFormatError, format_inspector.ImageFormatError,
'Signature', 'Signature',
@@ -1057,7 +1060,7 @@ class TestFormatInspectorInfra(test_base.BaseTestCase):
for region in regions: for region in regions:
try: try:
region.finish() region.finish() # type: ignore
except AttributeError: except AttributeError:
pass pass
@@ -1134,7 +1137,8 @@ class TestFormatInspectorInfra(test_base.BaseTestCase):
self, mock_log, mock_eat, expected=None self, mock_log, mock_eat, expected=None
): ):
wrapper = format_inspector.InspectWrapper( wrapper = format_inspector.InspectWrapper(
iter([b'123', b'456']), expected_format=expected iter([b'123', b'456']), # type: ignore
expected_format=expected,
) )
mock_eat.side_effect = Exception('fail') mock_eat.side_effect = Exception('fail')
@@ -1157,7 +1161,7 @@ class TestFormatInspectorInfra(test_base.BaseTestCase):
# Test with an expected format, but not the one we're going to # Test with an expected format, but not the one we're going to
# intentionally fail to make sure that we do not log failures # intentionally fail to make sure that we do not log failures
# for non-expected formats. # for non-expected formats.
self.test_wrapper_iter_like_eats_error(expected='vhd') self.test_wrapper_iter_like_eats_error(expected='vhd') # type: ignore
def test_wrapper_aborts_early(self): def test_wrapper_aborts_early(self):
# Run the InspectWrapper with non-qcow2 data, expecting qcow2, first # Run the InspectWrapper with non-qcow2 data, expecting qcow2, first
@@ -1194,7 +1198,9 @@ class TestFormatInspectorInfra(test_base.BaseTestCase):
def test_safety_check_records_failure(self): def test_safety_check_records_failure(self):
# This check will fail with ValueError # This check will fail with ValueError
check = format_inspector.SafetyCheck( check = format_inspector.SafetyCheck(
'foo', lambda: int('a'), description='a fake check' 'foo',
lambda: int('a'), # type: ignore
description='a fake check',
) )
self.assertRaisesRegex( self.assertRaisesRegex(
format_inspector.SafetyViolation, 'Unexpected error', check format_inspector.SafetyViolation, 'Unexpected error', check
@@ -1203,7 +1209,7 @@ class TestFormatInspectorInfra(test_base.BaseTestCase):
def test_safety_check_constants(self): def test_safety_check_constants(self):
null_check = format_inspector.SafetyCheck.null() null_check = format_inspector.SafetyCheck.null()
self.assertIsInstance(null_check, format_inspector.SafetyCheck) self.assertIsInstance(null_check, format_inspector.SafetyCheck)
self.assertIsNone(null_check()) self.assertIsNone(null_check()) # type: ignore
banned_check = format_inspector.SafetyCheck.banned() banned_check = format_inspector.SafetyCheck.banned()
self.assertIsInstance(banned_check, format_inspector.SafetyCheck) self.assertIsInstance(banned_check, format_inspector.SafetyCheck)
@@ -1271,6 +1277,7 @@ class TestFormatInspectorsTargeted(test_base.BaseTestCase):
meta.data = self._make_vhd_meta(desired, 33 * 2048) meta.data = self._make_vhd_meta(desired, 33 * 2048)
ins.new_region('metadata', meta) ins.new_region('metadata', meta)
new_region = ins._find_meta_entry(ins._guid(desired)) new_region = ins._find_meta_entry(ins._guid(desired))
assert new_region is not None
# Make sure we clamp to our limit of 32 * 2048 # Make sure we clamp to our limit of 32 * 2048
self.assertEqual( self.assertEqual(
format_inspector.VHDXInspector.VHDX_METADATA_TABLE_MAX_SIZE, format_inspector.VHDXInspector.VHDX_METADATA_TABLE_MAX_SIZE,
@@ -1284,5 +1291,6 @@ class TestFormatInspectorsTargeted(test_base.BaseTestCase):
meta.data = self._make_vhd_meta(desired, 16 * 2048) meta.data = self._make_vhd_meta(desired, 16 * 2048)
ins.new_region('metadata', meta) ins.new_region('metadata', meta)
new_region = ins._find_meta_entry(ins._guid(desired)) new_region = ins._find_meta_entry(ins._guid(desired))
assert new_region is not None
# Table size was under the limit, make sure we get it back # Table size was under the limit, make sure we get it back
self.assertEqual(16 * 2048, new_region.length) self.assertEqual(16 * 2048, new_region.length)

View File

@@ -462,7 +462,7 @@ class ExceptionFilterTest(test_base.BaseTestCase):
def _make_filter_func(self, ignore_classes=AssertionError): def _make_filter_func(self, ignore_classes=AssertionError):
@excutils.exception_filter @excutils.exception_filter
def ignore_exceptions(ex): def ignore_exceptions(ex):
'''Ignore some exceptions F.''' """Ignore some exceptions F."""
return isinstance(ex, ignore_classes) return isinstance(ex, ignore_classes)
return ignore_exceptions return ignore_exceptions
@@ -472,9 +472,9 @@ class ExceptionFilterTest(test_base.BaseTestCase):
def __init__(self, ignore): def __init__(self, ignore):
self.ignore = ignore self.ignore = ignore
@excutils.exception_filter @excutils.exception_filter # type: ignore
def ignore_exceptions(self, ex): def ignore_exceptions(self, ex):
'''Ignore some exceptions M.''' """Ignore some exceptions M."""
return isinstance(ex, self.ignore) return isinstance(ex, self.ignore)
return ExceptionIgnorer(ignore_classes).ignore_exceptions return ExceptionIgnorer(ignore_classes).ignore_exceptions
@@ -483,10 +483,10 @@ class ExceptionFilterTest(test_base.BaseTestCase):
class ExceptionIgnorer: class ExceptionIgnorer:
ignore = ignore_classes ignore = ignore_classes
@excutils.exception_filter @excutils.exception_filter # type: ignore
@classmethod @classmethod
def ignore_exceptions(cls, ex): def ignore_exceptions(cls, ex):
'''Ignore some exceptions C.''' """Ignore some exceptions C."""
return isinstance(ex, cls.ignore) return isinstance(ex, cls.ignore)
return ExceptionIgnorer.ignore_exceptions return ExceptionIgnorer.ignore_exceptions
@@ -496,7 +496,7 @@ class ExceptionFilterTest(test_base.BaseTestCase):
@excutils.exception_filter @excutils.exception_filter
@staticmethod @staticmethod
def ignore_exceptions(ex): def ignore_exceptions(ex):
'''Ignore some exceptions S.''' """Ignore some exceptions S."""
return isinstance(ex, ignore_classes) return isinstance(ex, ignore_classes)
return ExceptionIgnorer.ignore_exceptions return ExceptionIgnorer.ignore_exceptions

View File

@@ -251,7 +251,7 @@ class NetworkUtilsTest(test_base.BaseTestCase):
self.assertFalse(netutils.is_valid_cidr('10.0.0.1')) self.assertFalse(netutils.is_valid_cidr('10.0.0.1'))
self.assertFalse(netutils.is_valid_cidr('10.0.0.1/33')) self.assertFalse(netutils.is_valid_cidr('10.0.0.1/33'))
self.assertFalse(netutils.is_valid_cidr(10)) self.assertFalse(netutils.is_valid_cidr(10)) # type: ignore
def test_is_valid_ipv6_cidr(self): def test_is_valid_ipv6_cidr(self):
self.assertTrue(netutils.is_valid_ipv6_cidr("2600::/64")) self.assertTrue(netutils.is_valid_ipv6_cidr("2600::/64"))
@@ -290,7 +290,7 @@ class NetworkUtilsTest(test_base.BaseTestCase):
'65535', '65535',
] ]
for input_str in valid_inputs: for input_str in valid_inputs:
self.assertTrue(netutils.is_valid_port(input_str)) self.assertTrue(netutils.is_valid_port(input_str)) # type: ignore
def test_valid_port_fail(self): def test_valid_port_fail(self):
invalid_inputs = [ invalid_inputs = [
@@ -303,7 +303,7 @@ class NetworkUtilsTest(test_base.BaseTestCase):
None, None,
] ]
for input_str in invalid_inputs: for input_str in invalid_inputs:
self.assertFalse(netutils.is_valid_port(input_str)) self.assertFalse(netutils.is_valid_port(input_str)) # type: ignore
def test_get_my_ipv4(self): def test_get_my_ipv4(self):
mock_sock = mock.Mock() mock_sock = mock.Mock()
@@ -347,7 +347,7 @@ class NetworkUtilsTest(test_base.BaseTestCase):
('-100', -100, 100), ('-100', -100, 100),
] ]
for input_value in valid_inputs: for input_value in valid_inputs:
self.assertTrue(netutils._is_int_in_range(*input_value)) self.assertTrue(netutils._is_int_in_range(*input_value)) # type: ignore
def test_is_int_not_in_range(self): def test_is_int_not_in_range(self):
invalid_inputs = [ invalid_inputs = [
@@ -357,27 +357,27 @@ class NetworkUtilsTest(test_base.BaseTestCase):
('None', 1, 100), ('None', 1, 100),
] ]
for input_value in invalid_inputs: for input_value in invalid_inputs:
self.assertFalse(netutils._is_int_in_range(*input_value)) self.assertFalse(netutils._is_int_in_range(*input_value)) # type: ignore
def test_valid_icmp_type(self): def test_valid_icmp_type(self):
valid_inputs = [1, '1', 0, '0', 255, '255'] valid_inputs = [1, '1', 0, '0', 255, '255']
for input_value in valid_inputs: for input_value in valid_inputs:
self.assertTrue(netutils.is_valid_icmp_type(input_value)) self.assertTrue(netutils.is_valid_icmp_type(input_value)) # type: ignore
def test_invalid_icmp_type(self): def test_invalid_icmp_type(self):
invalid_inputs = [-1, '-1', 256, '256', None, 'None', 'five'] invalid_inputs = [-1, '-1', 256, '256', None, 'None', 'five']
for input_value in invalid_inputs: for input_value in invalid_inputs:
self.assertFalse(netutils.is_valid_icmp_type(input_value)) self.assertFalse(netutils.is_valid_icmp_type(input_value)) # type: ignore
def test_valid_icmp_code(self): def test_valid_icmp_code(self):
valid_inputs = [1, '1', 0, '0', 255, '255', None] valid_inputs = [1, '1', 0, '0', 255, '255', None]
for input_value in valid_inputs: for input_value in valid_inputs:
self.assertTrue(netutils.is_valid_icmp_code(input_value)) self.assertTrue(netutils.is_valid_icmp_code(input_value)) # type: ignore
def test_invalid_icmp_code(self): def test_invalid_icmp_code(self):
invalid_inputs = [-1, '-1', 256, '256', 'None', 'zero'] invalid_inputs = [-1, '-1', 256, '256', 'None', 'zero']
for input_value in invalid_inputs: for input_value in invalid_inputs:
self.assertFalse(netutils.is_valid_icmp_code(input_value)) self.assertFalse(netutils.is_valid_icmp_code(input_value)) # type: ignore
@mock.patch('socket.socket') @mock.patch('socket.socket')
@mock.patch('oslo_utils.netutils._get_my_ipv4_address') @mock.patch('oslo_utils.netutils._get_my_ipv4_address')
@@ -513,7 +513,8 @@ class IPv6byEUI64TestCase(test_base.BaseTestCase):
mac = '00:16:3e:33:44:55' mac = '00:16:3e:33:44:55'
prefix = 123 prefix = 123
self.assertRaises( self.assertRaises(
TypeError, lambda: netutils.get_ipv6_addr_by_EUI64(prefix, mac) TypeError,
lambda: netutils.get_ipv6_addr_by_EUI64(prefix, mac), # type: ignore
) )
def test_generate_IPv6_with_empty_prefix(self): def test_generate_IPv6_with_empty_prefix(self):

View File

@@ -716,12 +716,12 @@ class MaskPasswordTestCase(test_base.BaseTestCase):
self.assertEqual(expected, strutils.mask_password(payload)) self.assertEqual(expected, strutils.mask_password(payload))
class TestMapping(collections.abc.Mapping): class TestMapping(collections.abc.Mapping[str, Any]):
"""Test class for non-dict mappings""" """Test class for non-dict mappings"""
def __init__(self): def __init__(self):
super().__init__() super().__init__()
self.data = { self.data: dict[str, Any] = {
'password': 'shhh', 'password': 'shhh',
'foo': 'bar', 'foo': 'bar',
} }
@@ -793,9 +793,7 @@ class MaskDictionaryPasswordTestCase(test_base.BaseTestCase):
self.assertEqual(expected, strutils.mask_dict_password(payload)) self.assertEqual(expected, strutils.mask_dict_password(payload))
def test_do_no_harm(self): def test_do_no_harm(self):
payload = {} self.assertEqual({}, strutils.mask_dict_password({}))
expected = {}
self.assertEqual(expected, strutils.mask_dict_password(payload))
payload = {'somekey': 'somevalue', 'anotherkey': 'anothervalue'} payload = {'somekey': 'somevalue', 'anotherkey': 'anothervalue'}
expected = {'somekey': 'somevalue', 'anotherkey': 'anothervalue'} expected = {'somekey': 'somevalue', 'anotherkey': 'anothervalue'}
@@ -901,7 +899,7 @@ class IsIntLikeTestCase(test_base.BaseTestCase):
class StringLengthTestCase(test_base.BaseTestCase): class StringLengthTestCase(test_base.BaseTestCase):
def test_check_string_length(self): def test_check_string_length(self):
self.assertIsNone( self.assertIsNone(
strutils.check_string_length('test', 'name', max_length=255) strutils.check_string_length('test', 'name', max_length=255) # type: ignore
) )
self.assertRaises( self.assertRaises(
ValueError, strutils.check_string_length, '', 'name', min_length=1 ValueError, strutils.check_string_length, '', 'name', min_length=1
@@ -925,7 +923,7 @@ class StringLengthTestCase(test_base.BaseTestCase):
) )
def test_check_string_length_noname(self): def test_check_string_length_noname(self):
self.assertIsNone(strutils.check_string_length('test', max_length=255)) self.assertIsNone(strutils.check_string_length('test', max_length=255)) # type: ignore
self.assertRaises( self.assertRaises(
ValueError, strutils.check_string_length, '', min_length=1 ValueError, strutils.check_string_length, '', min_length=1
) )

View File

@@ -235,7 +235,9 @@ class TestIso8601Time(test_base.BaseTestCase):
DAY_SECONDS = 24 * 60 * 60 DAY_SECONDS = 24 * 60 * 60
timestamp = timeutils.parse_isotime(time_str) timestamp = timeutils.parse_isotime(time_str)
self._instaneous(timestamp, yr, mon, day, hr, minute, sec, micro) self._instaneous(timestamp, yr, mon, day, hr, minute, sec, micro)
assert timestamp.tzinfo is not None
offset = timestamp.tzinfo.utcoffset(None) offset = timestamp.tzinfo.utcoffset(None)
assert offset is not None
self.assertEqual(offset.seconds + offset.days * DAY_SECONDS, shift) self.assertEqual(offset.seconds + offset.days * DAY_SECONDS, shift)
def test_zulu(self): def test_zulu(self):

View File

@@ -85,7 +85,7 @@ class EncodeUtilsTest(test_base.BaseTestCase):
encodeutils.safe_encode(utf8, 'UTF-8', 'utf-8'), encodeutils.safe_encode(utf8, 'UTF-8', 'utf-8'),
encodeutils.safe_encode(utf8, 'utf-8', 'utf-8'), encodeutils.safe_encode(utf8, 'utf-8', 'utf-8'),
) )
encodeutils.safe_decode.assert_has_calls([]) encodeutils.safe_decode.assert_has_calls([]) # type: ignore
def test_safe_encode_different_encodings(self): def test_safe_encode_different_encodings(self):
text = 'foo\xc3\xb1bar' text = 'foo\xc3\xb1bar'

View File

@@ -54,7 +54,9 @@ module = [
"oslo_utils.fixture", "oslo_utils.fixture",
"oslo_utils.tests.*", "oslo_utils.tests.*",
] ]
ignore_errors = true disallow_untyped_calls = false
disallow_untyped_defs = false
disallow_subclassing_any = false
[tool.ruff] [tool.ruff]
line-length = 79 line-length = 79