Skip to content

Commit

Permalink
Upgrade code style to apply features from Python 3.7
Browse files Browse the repository at this point in the history
PiperOrigin-RevId: 650148392
  • Loading branch information
oprypin authored and copybara-github committed Jul 8, 2024
1 parent d0267ad commit dbd553a
Show file tree
Hide file tree
Showing 21 changed files with 99 additions and 90 deletions.
9 changes: 3 additions & 6 deletions absl/flags/_argument_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -329,12 +329,9 @@ def __init__(
ValueError: When enum_values is empty.
"""
if not enum_values:
raise ValueError(
'enum_values cannot be empty, found "{}"'.format(enum_values))
raise ValueError(f'enum_values cannot be empty, found "{enum_values}"')
if isinstance(enum_values, str):
raise ValueError(
'enum_values cannot be a str, found "{}"'.format(enum_values)
)
raise ValueError(f'enum_values cannot be a str, found "{enum_values}"')
super().__init__()
self.enum_values = list(enum_values)
self.case_sensitive = case_sensitive
Expand Down Expand Up @@ -388,7 +385,7 @@ def __init__(
ValueError: When enum_class is empty.
"""
if not issubclass(enum_class, enum.Enum):
raise TypeError('{} is not a subclass of Enum.'.format(enum_class))
raise TypeError(f'{enum_class} is not a subclass of Enum.')
if not enum_class.__members__:
raise ValueError('enum_class cannot be empty, but "{}" is empty.'
.format(enum_class))
Expand Down
3 changes: 2 additions & 1 deletion absl/flags/_flagvalues.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,7 +391,8 @@ def _set_unknown_flag(self, name: str, value: _T) -> _T:
return value
except (TypeError, ValueError): # Flag value is not valid.
raise _exceptions.IllegalFlagValueError(
'"{1}" is not valid for --{0}'.format(name, value))
f'"{value}" is not valid for --{name}'
)
except NameError: # Flag name is not valid.
pass
raise _exceptions.UnrecognizedFlagError(name, value)
Expand Down
5 changes: 3 additions & 2 deletions absl/flags/_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,8 +229,9 @@ def mark_flag_as_required(flag_name, flag_values=_flagvalues.FLAGS):
register_validator(
flag_name,
lambda value: value is not None,
message='Flag --{} must have a value other than None.'.format(flag_name),
flag_values=flag_values)
message=f'Flag --{flag_name} must have a value other than None.',
flag_values=flag_values,
)


def mark_flags_as_required(flag_names, flag_values=_flagvalues.FLAGS):
Expand Down
3 changes: 1 addition & 2 deletions absl/flags/tests/argparse_flags_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -448,8 +448,7 @@ def test_argparse_with_app_run(
helper = _bazelize_command.get_executable_path(
'absl/flags/tests/argparse_flags_test_helper')
try:
stdout = subprocess.check_output(
[helper] + args, env=env, universal_newlines=True)
stdout = subprocess.check_output([helper] + args, env=env, text=True)
except subprocess.CalledProcessError as e:
error_info = ('ERROR: argparse_helper failed\n'
'Command: {}\n'
Expand Down
5 changes: 2 additions & 3 deletions absl/logging/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,8 +257,7 @@ class _LoggerLevelsSerializer:
def serialize(self, value):
if isinstance(value, str):
return value
return ','.join(
'{}:{}'.format(name, level) for name, level in value.items())
return ','.join(f'{name}:{level}' for name, level in value.items())


class _StderrthresholdFlag(flags.Flag):
Expand Down Expand Up @@ -709,7 +708,7 @@ def get_log_file_name(level=INFO):
ValueError: Raised when `level` has an invalid value.
"""
if level not in converter.ABSL_LEVELS:
raise ValueError('Invalid absl.logging level {}'.format(level))
raise ValueError(f'Invalid absl.logging level {level}')
stream = get_absl_handler().python_handler.stream
if (stream == sys.stderr or stream == sys.stdout or
not hasattr(stream, 'name')):
Expand Down
6 changes: 3 additions & 3 deletions absl/logging/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def absl_to_cpp(level):
The corresponding integer level for use in Abseil C++.
"""
if not isinstance(level, int):
raise TypeError('Expect an int level, found {}'.format(type(level)))
raise TypeError(f'Expect an int level, found {type(level)}')
if level >= 0:
# C++ log levels must be >= 0
return 0
Expand All @@ -146,7 +146,7 @@ def absl_to_standard(level):
The corresponding integer level for use in standard logging.
"""
if not isinstance(level, int):
raise TypeError('Expect an int level, found {}'.format(type(level)))
raise TypeError(f'Expect an int level, found {type(level)}')
if level < ABSL_FATAL:
level = ABSL_FATAL
if level <= ABSL_DEBUG:
Expand Down Expand Up @@ -181,7 +181,7 @@ def standard_to_absl(level):
The corresponding integer level for use in absl logging.
"""
if not isinstance(level, int):
raise TypeError('Expect an int level, found {}'.format(type(level)))
raise TypeError(f'Expect an int level, found {type(level)}')
if level < 0:
level = 0
if level < STANDARD_DEBUG:
Expand Down
9 changes: 5 additions & 4 deletions absl/logging/tests/logging_functional_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -710,10 +710,11 @@ def test_unicode_py_logging(self):

def get_stderr_message(stderr, name):
match = re.search(
'-- begin {} --\n(.*)-- end {} --'.format(name, name),
stderr, re.MULTILINE | re.DOTALL)
self.assertTrue(
match, 'Cannot find stderr message for test {}'.format(name))
f'-- begin {name} --\n(.*)-- end {name} --',
stderr,
re.MULTILINE | re.DOTALL,
)
self.assertTrue(match, f'Cannot find stderr message for test {name}')
return match.group(1)

def assert_stderr(stderr):
Expand Down
4 changes: 2 additions & 2 deletions absl/logging/tests/logging_functional_test_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,9 +315,9 @@ def log(name, msg, *args):

# Add line separators so that tests can verify the output for each log
# message.
sys.stderr.write('-- begin {} --\n'.format(name))
sys.stderr.write(f'-- begin {name} --\n')
logging.info(msg, *args)
sys.stderr.write('-- end {} --\n'.format(name))
sys.stderr.write(f'-- end {name} --\n')

log('unicode', 'G\u00eete: Ch\u00e2tonnaye')
log('unicode % unicode', 'G\u00eete: %s', 'Ch\u00e2tonnaye')
Expand Down
13 changes: 7 additions & 6 deletions absl/logging/tests/logging_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def test_serialize_parse(self, levels_str):
fl.parse(levels_str)
expected = levels_str.replace(' ', '')
actual = fl.serialize()
self.assertEqual('--logger_levels={}'.format(expected), actual)
self.assertEqual(f'--logger_levels={expected}', actual)

def test_invalid_value(self):
with self.assertRaisesRegex(ValueError, 'Unknown level.*10'):
Expand Down Expand Up @@ -611,7 +611,7 @@ def setUp(self):
def test_default_prefixes(self, levelno, level_prefix):
self.record.levelno = levelno
self.record.created = 1494293880.378885
thread_id = '{: >5}'.format(logging._get_thread_id())
thread_id = f'{logging._get_thread_id(): >5}'
# Use UTC so the test passes regardless of the local time zone.
with mock.patch.object(time, 'localtime', side_effect=time.gmtime):
self.assertEqual(
Expand Down Expand Up @@ -647,18 +647,19 @@ def test_critical_absl(self):
self.record.levelno = std_logging.CRITICAL
self.record.created = 1494293880.378885
self.record._absl_log_fatal = True
thread_id = '{: >5}'.format(logging._get_thread_id())
thread_id = f'{logging._get_thread_id(): >5}'
# Use UTC so the test passes regardless of the local time zone.
with mock.patch.object(time, 'localtime', side_effect=time.gmtime):
self.assertEqual(
'F0509 01:38:00.378885 {} source.py:13] '.format(thread_id),
logging.get_absl_log_prefix(self.record))
f'F0509 01:38:00.378885 {thread_id} source.py:13] ',
logging.get_absl_log_prefix(self.record),
)
time.localtime.assert_called_once_with(self.record.created)

def test_critical_non_absl(self):
self.record.levelno = std_logging.CRITICAL
self.record.created = 1494293880.378885
thread_id = '{: >5}'.format(logging._get_thread_id())
thread_id = f'{logging._get_thread_id(): >5}'
# Use UTC so the test passes regardless of the local time zone.
with mock.patch.object(time, 'localtime', side_effect=time.gmtime):
self.assertEqual(
Expand Down
2 changes: 1 addition & 1 deletion absl/testing/_bazelize_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def get_executable_path(py_binary_name):
py_binary_name += '.exe'
manifest_file = os.path.join(FLAGS.test_srcdir, 'MANIFEST')
workspace_name = os.environ['TEST_WORKSPACE']
manifest_entry = '{}/{}'.format(workspace_name, py_binary_name)
manifest_entry = f'{workspace_name}/{py_binary_name}'
with open(manifest_file) as manifest_fd:
for line in manifest_fd:
tokens = line.strip().split(' ')
Expand Down
18 changes: 9 additions & 9 deletions absl/testing/absltest.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,8 +187,7 @@ def _get_default_randomize_ordering_seed() -> int:
return seed
except ValueError:
pass
raise ValueError(
'Unknown test randomization seed value: {}'.format(randomize))
raise ValueError(f'Unknown test randomization seed value: {randomize}')


TEST_SRCDIR = flags.DEFINE_string(
Expand Down Expand Up @@ -793,7 +792,7 @@ def _maybe_add_temp_path_cleanup(
elif cleanup == TempFileCleanup.SUCCESS:
self._internal_add_cleanup_on_success(_rmtree_ignore_errors, path)
else:
raise AssertionError('Unexpected cleanup value: {}'.format(cleanup))
raise AssertionError(f'Unexpected cleanup value: {cleanup}')

def _internal_add_cleanup_on_success(
self,
Expand Down Expand Up @@ -973,7 +972,7 @@ def assertEmpty(self, container, msg=None):
# explicitly check the length since some Sized objects (e.g. numpy.ndarray)
# have strange __nonzero__/__bool__ behavior.
if len(container): # pylint: disable=g-explicit-length-test
self.fail('{!r} has length of {}.'.format(container, len(container)), msg)
self.fail(f'{container!r} has length of {len(container)}.', msg)

def assertNotEmpty(self, container, msg=None):
"""Asserts that an object has non-zero length.
Expand All @@ -989,7 +988,7 @@ def assertNotEmpty(self, container, msg=None):
# explicitly check the length since some Sized objects (e.g. numpy.ndarray)
# have strange __nonzero__/__bool__ behavior.
if not len(container): # pylint: disable=g-explicit-length-test
self.fail('{!r} has length of 0.'.format(container), msg)
self.fail(f'{container!r} has length of 0.', msg)

def assertLen(self, container, expected_len, msg=None):
"""Asserts that an object has the expected length.
Expand Down Expand Up @@ -1044,7 +1043,7 @@ def assertSequenceAlmostEqual(self, expected_seq, actual_seq, places=None,
delta=delta)
# pytype: enable=wrong-keyword-args
except self.failureException as err:
err_list.append('At index {}: {}'.format(idx, err))
err_list.append(f'At index {idx}: {err}')

if err_list:
if len(err_list) > 30:
Expand Down Expand Up @@ -1146,7 +1145,7 @@ def assertMultiLineEqual(self, first, second, msg=None, **kwargs):
str), ('Second argument is not a string: %r' % (second,))
line_limit = kwargs.pop('line_limit', 0)
if kwargs:
raise TypeError('Unexpected keyword args {}'.format(tuple(kwargs)))
raise TypeError(f'Unexpected keyword args {tuple(kwargs)}')

if first == second:
return
Expand Down Expand Up @@ -2307,12 +2306,13 @@ def test_other_behavior(self):
Decorator function that will cause a class to be skipped.
"""
if isinstance(reason, type):
raise TypeError('Got {!r}, expected reason as string'.format(reason))
raise TypeError(f'Got {reason!r}, expected reason as string')

def _skip_class(test_case_class):
if not issubclass(test_case_class, unittest.TestCase):
raise TypeError(
'Decorating {!r}, expected TestCase subclass'.format(test_case_class))
f'Decorating {test_case_class!r}, expected TestCase subclass'
)

# Only shadow the setUpClass method if it is directly defined. If it is
# in the parent class we invoke it via a super() call instead of holding
Expand Down
2 changes: 1 addition & 1 deletion absl/testing/parameterized.py
Original file line number Diff line number Diff line change
Expand Up @@ -672,7 +672,7 @@ def id(self):
# test.xml file, the value is more informative than just "test_foo0".
# Use a space to separate them so that it's copy/paste friendly and
# easy to identify the actual test id.
return '{} {}'.format(base, params_repr)
return f'{base} {params_repr}'
else:
return base

Expand Down
2 changes: 1 addition & 1 deletion absl/testing/tests/absltest_sharding_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ def test_no_tests_ran(
self.assertEqual(
expected_exit_code,
exit_code,
'Unexpected exit code, output:\n{}'.format(out),
f'Unexpected exit code, output:\n{out}',
)


Expand Down
58 changes: 35 additions & 23 deletions absl/testing/tests/absltest_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def run_helper(
helper_name = 'absltest_test_helper'
command = [self._get_helper_exec_path(helper_name)]
if test_id is not None:
command.append('--test_id={}'.format(test_id))
command.append(f'--test_id={test_id}')
command.extend(args)
process = subprocess.Popen(
command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env,
Expand Down Expand Up @@ -145,15 +145,20 @@ def test_flags_no_env_var_flags(self):
srcdir = tempfile.mkdtemp(dir=absltest.TEST_TMPDIR.value)
self.run_helper(
3,
['--test_random_seed=123', '--test_srcdir={}'.format(srcdir),
'--test_tmpdir={}'.format(tmpdir)],
{'TEST_RANDOM_SEED': None,
'TEST_SRCDIR': None,
'TEST_TMPDIR': None,
'ABSLTEST_TEST_HELPER_EXPECTED_TEST_SRCDIR': srcdir,
'ABSLTEST_TEST_HELPER_EXPECTED_TEST_TMPDIR': tmpdir,
[
'--test_random_seed=123',
f'--test_srcdir={srcdir}',
f'--test_tmpdir={tmpdir}',
],
{
'TEST_RANDOM_SEED': None,
'TEST_SRCDIR': None,
'TEST_TMPDIR': None,
'ABSLTEST_TEST_HELPER_EXPECTED_TEST_SRCDIR': srcdir,
'ABSLTEST_TEST_HELPER_EXPECTED_TEST_TMPDIR': tmpdir,
},
expect_success=True)
expect_success=True,
)

def test_flags_env_var_flags(self):
tmpdir_from_flag = tempfile.mkdtemp(dir=absltest.TEST_TMPDIR.value)
Expand All @@ -162,15 +167,20 @@ def test_flags_env_var_flags(self):
srcdir_from_env_var = tempfile.mkdtemp(dir=absltest.TEST_TMPDIR.value)
self.run_helper(
4,
['--test_random_seed=221', '--test_srcdir={}'.format(srcdir_from_flag),
'--test_tmpdir={}'.format(tmpdir_from_flag)],
{'TEST_RANDOM_SEED': '123',
'TEST_SRCDIR': srcdir_from_env_var,
'TEST_TMPDIR': tmpdir_from_env_var,
'ABSLTEST_TEST_HELPER_EXPECTED_TEST_SRCDIR': srcdir_from_flag,
'ABSLTEST_TEST_HELPER_EXPECTED_TEST_TMPDIR': tmpdir_from_flag,
[
'--test_random_seed=221',
f'--test_srcdir={srcdir_from_flag}',
f'--test_tmpdir={tmpdir_from_flag}',
],
{
'TEST_RANDOM_SEED': '123',
'TEST_SRCDIR': srcdir_from_env_var,
'TEST_TMPDIR': tmpdir_from_env_var,
'ABSLTEST_TEST_HELPER_EXPECTED_TEST_SRCDIR': srcdir_from_flag,
'ABSLTEST_TEST_HELPER_EXPECTED_TEST_TMPDIR': tmpdir_from_flag,
},
expect_success=True)
expect_success=True,
)

def test_xml_output_file_from_xml_output_file_env(self):
xml_dir = tempfile.mkdtemp(dir=absltest.TEST_TMPDIR.value)
Expand Down Expand Up @@ -2223,15 +2233,17 @@ class TempFileTest(BaseTestCase):

def assert_dir_exists(self, temp_dir):
path = temp_dir.full_path
self.assertTrue(os.path.exists(path), 'Dir {} does not exist'.format(path))
self.assertTrue(os.path.isdir(path),
'Path {} exists, but is not a directory'.format(path))
self.assertTrue(os.path.exists(path), f'Dir {path} does not exist')
self.assertTrue(
os.path.isdir(path), f'Path {path} exists, but is not a directory'
)

def assert_file_exists(self, temp_file, expected_content=b''):
path = temp_file.full_path
self.assertTrue(os.path.exists(path), 'File {} does not exist'.format(path))
self.assertTrue(os.path.isfile(path),
'Path {} exists, but is not a file'.format(path))
self.assertTrue(os.path.exists(path), f'File {path} does not exist')
self.assertTrue(
os.path.isfile(path), f'Path {path} exists, but is not a file'
)

mode = 'rb' if isinstance(expected_content, bytes) else 'rt'
with open(path, mode) as fp:
Expand Down
9 changes: 3 additions & 6 deletions absl/testing/tests/absltest_test_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,7 @@ def test_flags(self):
absltest.TEST_TMPDIR.value,
os.environ['ABSLTEST_TEST_HELPER_EXPECTED_TEST_TMPDIR'])
else:
raise unittest.SkipTest(
'Not asked to run: --test_id={}'.format(_TEST_ID.value))
raise unittest.SkipTest(f'Not asked to run: --test_id={_TEST_ID.value}')

@unittest.expectedFailure
def test_expected_failure(self):
Expand All @@ -94,15 +93,13 @@ def test_xml_env_vars(self):
FLAGS.xml_output_file,
os.environ['ABSLTEST_TEST_HELPER_EXPECTED_XML_OUTPUT_FILE'])
else:
raise unittest.SkipTest(
'Not asked to run: --test_id={}'.format(_TEST_ID.value))
raise unittest.SkipTest(f'Not asked to run: --test_id={_TEST_ID.value}')

def test_name_flag(self):
if _TEST_ID.value == 7:
print('Names in test_name_flag() are:', ' '.join(_NAME.value))
else:
raise unittest.SkipTest(
'Not asked to run: --test_id={}'.format(_TEST_ID.value))
raise unittest.SkipTest(f'Not asked to run: --test_id={_TEST_ID.value}')


class TempFileHelperTest(absltest.TestCase):
Expand Down
Loading

0 comments on commit dbd553a

Please sign in to comment.