Python code modernization, 1/n (#1141)

* Remove unicode text prefixes.

* Replace str.format() uses with f-strings.

* Replace % with f-strings, and do some cleanup.

* Fix wrong variable.

* Avoid unnecessary string conversion.
This commit is contained in:
Felix Fontein
2025-10-06 18:30:54 +02:00
committed by GitHub
parent 1f2817fa20
commit f45232635c
93 changed files with 930 additions and 1122 deletions
@@ -107,8 +107,8 @@ class FakeClient(object):
'Image': host['Config']['Image'],
'ImageId': host['Image'],
})
self.get_results['/containers/{0}/json'.format(host['Name'])] = host
self.get_results['/containers/{0}/json'.format(host['Id'])] = host
self.get_results[f"/containers/{host['Name']}/json"] = host
self.get_results[f"/containers/{host['Id']}/json"] = host
self.get_results['/containers/json'] = list_reply
def get_json(self, url, *param, **kwargs):
@@ -74,7 +74,7 @@ def fake_resp(method, url, *args, **kwargs):
elif (url, method) in fake_api.fake_responses:
key = (url, method)
if not key:
raise Exception('{method} {url}'.format(method=method, url=url))
raise Exception(f'{method} {url}')
status_code, content = fake_api.fake_responses[key]()
return response(status_code=status_code, content=content)
@@ -102,10 +102,8 @@ def fake_read_from_socket(self, response, stream, tty=False, demux=False):
return b""
url_base = '{prefix}/'.format(prefix=fake_api.prefix)
url_prefix = '{0}v{1}/'.format(
url_base,
DEFAULT_DOCKER_API_VERSION)
url_base = f'{fake_api.prefix}/'
url_prefix = f'{url_base}v{DEFAULT_DOCKER_API_VERSION}/'
class BaseAPIClientTest(unittest.TestCase):
@@ -147,22 +145,18 @@ class DockerApiTest(BaseAPIClientTest):
def test_url_valid_resource(self):
url = self.client._url('/hello/{0}/world', 'somename')
assert url == '{0}{1}'.format(url_prefix, 'hello/somename/world')
assert url == f'{url_prefix}hello/somename/world'
url = self.client._url(
'/hello/{0}/world/{1}', 'somename', 'someothername'
)
assert url == '{0}{1}'.format(
url_prefix, 'hello/somename/world/someothername'
)
assert url == f'{url_prefix}hello/somename/world/someothername'
url = self.client._url('/hello/{0}/world', 'some?name')
assert url == '{0}{1}'.format(url_prefix, 'hello/some%3Fname/world')
assert url == f'{url_prefix}hello/some%3Fname/world'
url = self.client._url("/images/{0}/push", "localhost:5000/image")
assert url == '{0}{1}'.format(
url_prefix, 'images/localhost:5000/image/push'
)
assert url == f'{url_prefix}images/localhost:5000/image/push'
def test_url_invalid_resource(self):
with pytest.raises(ValueError):
@@ -170,13 +164,13 @@ class DockerApiTest(BaseAPIClientTest):
def test_url_no_resource(self):
url = self.client._url('/simple')
assert url == '{0}{1}'.format(url_prefix, 'simple')
assert url == f'{url_prefix}simple'
def test_url_unversioned_api(self):
url = self.client._url(
'/hello/{0}/world', 'somename', versioned_api=False
)
assert url == '{0}{1}'.format(url_base, 'hello/somename/world')
assert url == f'{url_base}hello/somename/world'
def test_version(self):
self.client.version()
@@ -401,7 +395,7 @@ class UnixSocketStreamTest(unittest.TestCase):
lines = []
for i in range(0, 50):
line = str(i).encode()
lines += [('%x' % len(line)).encode(), line]
lines += [f'{len(line):x}'.encode(), line]
lines.append(b'0')
lines.append(b'')
@@ -463,8 +457,7 @@ class TCPSocketStreamTest(unittest.TestCase):
cls.thread = threading.Thread(target=cls.server.serve_forever)
cls.thread.daemon = True
cls.thread.start()
cls.address = 'http://{0}:{1}'.format(
socket.gethostname(), cls.server.server_address[1])
cls.address = f'http://{socket.gethostname()}:{cls.server.server_address[1]}'
@classmethod
def teardown_class(cls):
@@ -503,7 +496,7 @@ class TCPSocketStreamTest(unittest.TestCase):
data += stderr_data
return data
else:
raise Exception('Unknown path {path}'.format(path=path))
raise Exception(f'Unknown path {path}')
@staticmethod
def frame_header(stream, data):
@@ -573,7 +566,7 @@ class UserAgentTest(unittest.TestCase):
self.patcher = mock.patch.object(
APIClient,
'send',
return_value=fake_resp("GET", "%s/version" % fake_api.prefix)
return_value=fake_resp("GET", f"{fake_api.prefix}/version")
)
self.mock_send = self.patcher.start()
@@ -15,7 +15,7 @@ from ansible_collections.community.docker.tests.unit.plugins.module_utils._api.c
from . import fake_stat
CURRENT_VERSION = 'v{api_version}'.format(api_version=DEFAULT_DOCKER_API_VERSION)
CURRENT_VERSION = f'v{DEFAULT_DOCKER_API_VERSION}'
FAKE_CONTAINER_ID = '3cc2351ab11b'
FAKE_IMAGE_ID = 'e9aa60c60128'
@@ -539,131 +539,117 @@ if constants.IS_WINDOWS_PLATFORM:
prefix = 'http+docker://localnpipe'
fake_responses = {
'{prefix}/version'.format(prefix=prefix):
f'{prefix}/version':
get_fake_version,
'{prefix}/{CURRENT_VERSION}/version'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/version':
get_fake_version,
'{prefix}/{CURRENT_VERSION}/info'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/info':
get_fake_info,
'{prefix}/{CURRENT_VERSION}/auth'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/auth':
post_fake_auth,
'{prefix}/{CURRENT_VERSION}/_ping'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/_ping':
get_fake_ping,
'{prefix}/{CURRENT_VERSION}/images/search'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/images/search':
get_fake_search,
'{prefix}/{CURRENT_VERSION}/images/json'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/images/json':
get_fake_images,
'{prefix}/{CURRENT_VERSION}/images/test_image/history'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/images/test_image/history':
get_fake_image_history,
'{prefix}/{CURRENT_VERSION}/images/create'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/images/create':
post_fake_import_image,
'{prefix}/{CURRENT_VERSION}/containers/json'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/json':
get_fake_containers,
'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/start'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/start':
post_fake_start_container,
'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/resize'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/resize':
post_fake_resize_container,
'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/json'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/json':
get_fake_inspect_container,
'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/rename'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/rename':
post_fake_rename_container,
'{prefix}/{CURRENT_VERSION}/images/e9aa60c60128/tag'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/images/e9aa60c60128/tag':
post_fake_tag_image,
'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/wait'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/wait':
get_fake_wait,
'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/logs'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/logs':
get_fake_logs,
'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/changes'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/changes':
get_fake_diff,
'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/export'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/export':
get_fake_export,
'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/update'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/update':
post_fake_update_container,
'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/exec'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/exec':
post_fake_exec_create,
'{prefix}/{CURRENT_VERSION}/exec/d5d177f121dc/start'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/exec/d5d177f121dc/start':
post_fake_exec_start,
'{prefix}/{CURRENT_VERSION}/exec/d5d177f121dc/json'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/exec/d5d177f121dc/json':
get_fake_exec_inspect,
'{prefix}/{CURRENT_VERSION}/exec/d5d177f121dc/resize'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/exec/d5d177f121dc/resize':
post_fake_exec_resize,
'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/stats'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/stats':
get_fake_stats,
'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/top'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/top':
get_fake_top,
'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/stop'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/stop':
post_fake_stop_container,
'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/kill'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/kill':
post_fake_kill_container,
'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/pause'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/pause':
post_fake_pause_container,
'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/unpause'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/unpause':
post_fake_unpause_container,
'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/restart'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b/restart':
post_fake_restart_container,
'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/3cc2351ab11b':
delete_fake_remove_container,
'{prefix}/{CURRENT_VERSION}/images/create'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/images/create':
post_fake_image_create,
'{prefix}/{CURRENT_VERSION}/images/e9aa60c60128'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/images/e9aa60c60128':
delete_fake_remove_image,
'{prefix}/{CURRENT_VERSION}/images/e9aa60c60128/get'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/images/e9aa60c60128/get':
get_fake_get_image,
'{prefix}/{CURRENT_VERSION}/images/load'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/images/load':
post_fake_load_image,
'{prefix}/{CURRENT_VERSION}/images/test_image/json'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/images/test_image/json':
get_fake_inspect_image,
'{prefix}/{CURRENT_VERSION}/images/test_image/insert'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/images/test_image/insert':
get_fake_insert_image,
'{prefix}/{CURRENT_VERSION}/images/test_image/push'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/images/test_image/push':
post_fake_push,
'{prefix}/{CURRENT_VERSION}/commit'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/commit':
post_fake_commit,
'{prefix}/{CURRENT_VERSION}/containers/create'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/containers/create':
post_fake_create_container,
'{prefix}/{CURRENT_VERSION}/build'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/build':
post_fake_build_container,
'{prefix}/{CURRENT_VERSION}/events'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/events':
get_fake_events,
('{prefix}/{CURRENT_VERSION}/volumes'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION), 'GET'):
(f'{prefix}/{CURRENT_VERSION}/volumes', 'GET'):
get_fake_volume_list,
('{prefix}/{CURRENT_VERSION}/volumes/create'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION), 'POST'):
(f'{prefix}/{CURRENT_VERSION}/volumes/create', 'POST'):
get_fake_volume,
('{1}/{0}/volumes/{2}'.format(
CURRENT_VERSION, prefix, FAKE_VOLUME_NAME
), 'GET'):
(f'{prefix}/{CURRENT_VERSION}/volumes/{FAKE_VOLUME_NAME}', 'GET'):
get_fake_volume,
('{1}/{0}/volumes/{2}'.format(
CURRENT_VERSION, prefix, FAKE_VOLUME_NAME
), 'DELETE'):
(f'{prefix}/{CURRENT_VERSION}/volumes/{FAKE_VOLUME_NAME}', 'DELETE'):
fake_remove_volume,
('{1}/{0}/nodes/{2}/update?version=1'.format(
CURRENT_VERSION, prefix, FAKE_NODE_ID
), 'POST'):
(f'{prefix}/{CURRENT_VERSION}/nodes/{FAKE_NODE_ID}/update?version=1', 'POST'):
post_fake_update_node,
('{prefix}/{CURRENT_VERSION}/swarm/join'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION), 'POST'):
(f'{prefix}/{CURRENT_VERSION}/swarm/join', 'POST'):
post_fake_join_swarm,
('{prefix}/{CURRENT_VERSION}/networks'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION), 'GET'):
(f'{prefix}/{CURRENT_VERSION}/networks', 'GET'):
get_fake_network_list,
('{prefix}/{CURRENT_VERSION}/networks/create'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION), 'POST'):
(f'{prefix}/{CURRENT_VERSION}/networks/create', 'POST'):
post_fake_network,
('{1}/{0}/networks/{2}'.format(
CURRENT_VERSION, prefix, FAKE_NETWORK_ID
), 'GET'):
(f'{prefix}/{CURRENT_VERSION}/networks/{FAKE_NETWORK_ID}', 'GET'):
get_fake_network,
('{1}/{0}/networks/{2}'.format(
CURRENT_VERSION, prefix, FAKE_NETWORK_ID
), 'DELETE'):
(f'{prefix}/{CURRENT_VERSION}/networks/{FAKE_NETWORK_ID}', 'DELETE'):
delete_fake_network,
('{1}/{0}/networks/{2}/connect'.format(
CURRENT_VERSION, prefix, FAKE_NETWORK_ID
), 'POST'):
(f'{prefix}/{CURRENT_VERSION}/networks/{FAKE_NETWORK_ID}/connect', 'POST'):
post_fake_network_connect,
('{1}/{0}/networks/{2}/disconnect'.format(
CURRENT_VERSION, prefix, FAKE_NETWORK_ID
), 'POST'):
(f'{prefix}/{CURRENT_VERSION}/networks/{FAKE_NETWORK_ID}/disconnect', 'POST'):
post_fake_network_disconnect,
'{prefix}/{CURRENT_VERSION}/secrets/create'.format(prefix=prefix, CURRENT_VERSION=CURRENT_VERSION):
f'{prefix}/{CURRENT_VERSION}/secrets/create':
post_fake_secret,
}
@@ -252,7 +252,7 @@ class LoadConfigTest(unittest.TestCase):
cfg_path = os.path.join(folder, '.dockercfg')
auth_ = base64.b64encode(b'sakuya:izayoi').decode('ascii')
with open(cfg_path, 'w') as f:
f.write('auth = {auth}\n'.format(auth=auth_))
f.write(f'auth = {auth_}\n')
f.write('email = sakuya@scarlet.net')
cfg = auth.load_config(cfg_path)
@@ -309,14 +309,12 @@ class LoadConfigTest(unittest.TestCase):
folder = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, folder)
dockercfg_path = os.path.join(folder,
'.{0}.dockercfg'.format(
random.randrange(100000)))
dockercfg_path = os.path.join(folder, f'.{random.randrange(100000)}.dockercfg')
registry = 'https://your.private.registry.io'
auth_ = base64.b64encode(b'sakuya:izayoi').decode('ascii')
config = {
registry: {
'auth': '{auth}'.format(auth=auth_),
'auth': f'{auth_}',
'email': 'sakuya@scarlet.net'
}
}
@@ -342,7 +340,7 @@ class LoadConfigTest(unittest.TestCase):
auth_ = base64.b64encode(b'sakuya:izayoi').decode('ascii')
config = {
registry: {
'auth': '{auth}'.format(auth=auth_),
'auth': f'{auth_}',
'email': 'sakuya@scarlet.net'
}
}
@@ -370,7 +368,7 @@ class LoadConfigTest(unittest.TestCase):
config = {
'auths': {
registry: {
'auth': '{auth}'.format(auth=auth_),
'auth': f'{auth_}',
'email': 'sakuya@scarlet.net'
}
}
@@ -399,7 +397,7 @@ class LoadConfigTest(unittest.TestCase):
config = {
'auths': {
registry: {
'auth': '{auth}'.format(auth=auth_),
'auth': f'{auth_}',
'email': 'sakuya@scarlet.net'
}
}
@@ -431,9 +431,7 @@ class TarTest(unittest.TestCase):
with pytest.raises(IOError) as ei:
tar(base)
assert 'Can not read file in context: {full_path}'.format(full_path=full_path) in (
ei.exconly()
)
assert f'Can not read file in context: {full_path}' in ei.exconly()
@pytest.mark.skipif(IS_WINDOWS_PLATFORM, reason='No symlinks on Windows')
def test_tar_with_file_symlinks(self):
@@ -33,12 +33,12 @@ class TestStreamAsText:
def test_stream_with_non_utf_unicode_character(self):
stream = [b'\xed\xf3\xf3']
output, = stream_as_text(stream)
assert output == u''
assert output == ''
def test_stream_with_utf_character(self):
stream = [u'ěĝ'.encode('utf-8')]
stream = ['ěĝ'.encode('utf-8')]
output, = stream_as_text(stream)
assert output == u'ěĝ'
assert output == 'ěĝ'
class TestJsonStream:
@@ -75,7 +75,7 @@ class ProxyConfigTest(unittest.TestCase):
# Proxy config is non null, env is None.
self.assertSetEqual(
set(CONFIG.inject_proxy_environment(None)),
set('{k}={v}'.format(k=k, v=v) for k, v in ENV.items()))
set(f'{k}={v}' for k, v in ENV.items()))
# Proxy config is null, env is None.
self.assertIsNone(ProxyConfig().inject_proxy_environment(None), None)
@@ -84,7 +84,7 @@ class ProxyConfigTest(unittest.TestCase):
# Proxy config is non null, env is non null
actual = CONFIG.inject_proxy_environment(env)
expected = ['{k}={v}'.format(k=k, v=v) for k, v in ENV.items()] + env
expected = [f'{k}={v}' for k, v in ENV.items()] + env
# It's important that the first 8 variables are the ones from the proxy
# config, and the last 2 are the ones from the input environment
self.assertSetEqual(set(actual[:8]), set(expected[:8]))
@@ -176,23 +176,23 @@ class ConverVolumeBindsTest(unittest.TestCase):
assert convert_volume_binds(data) == ['/mnt/vol1:/data:rw']
def test_convert_volume_binds_unicode_bytes_input(self):
expected = [u'/mnt/지연:/unicode/박:rw']
expected = ['/mnt/지연:/unicode/박:rw']
data = {
u'/mnt/지연'.encode('utf-8'): {
'bind': u'/unicode/박'.encode('utf-8'),
'mode': u'rw'
'/mnt/지연'.encode('utf-8'): {
'bind': '/unicode/박'.encode('utf-8'),
'mode': 'rw'
}
}
assert convert_volume_binds(data) == expected
def test_convert_volume_binds_unicode_unicode_input(self):
expected = [u'/mnt/지연:/unicode/박:rw']
expected = ['/mnt/지연:/unicode/박:rw']
data = {
u'/mnt/지연': {
'bind': u'/unicode/박',
'mode': u'rw'
'/mnt/지연': {
'bind': '/unicode/박',
'mode': 'rw'
}
}
assert convert_volume_binds(data) == expected
@@ -288,7 +288,7 @@ class ParseHostTest(unittest.TestCase):
}
for host in invalid_hosts:
msg = 'Should have failed to parse invalid host: {0}'.format(host)
msg = f'Should have failed to parse invalid host: {host}'
with self.assertRaises(DockerException, msg=msg):
parse_host(host, None)
@@ -296,7 +296,7 @@ class ParseHostTest(unittest.TestCase):
self.assertEqual(
parse_host(host, None),
expected,
msg='Failed to parse valid host: {0}'.format(host),
msg=f'Failed to parse valid host: {host}',
)
def test_parse_host_empty_value(self):
@@ -347,14 +347,14 @@ class ParseRepositoryTagTest(unittest.TestCase):
)
def test_index_image_sha(self):
assert parse_repository_tag("root@sha256:{sha}".format(sha=self.sha)) == (
"root", "sha256:{sha}".format(sha=self.sha)
assert parse_repository_tag(f"root@sha256:{self.sha}") == (
"root", f"sha256:{self.sha}"
)
def test_private_reg_image_sha(self):
assert parse_repository_tag(
"url:5000/repo@sha256:{sha}".format(sha=self.sha)
) == ("url:5000/repo", "sha256:{sha}".format(sha=self.sha))
f"url:5000/repo@sha256:{self.sha}"
) == ("url:5000/repo", f"sha256:{self.sha}")
class ParseDeviceTest(unittest.TestCase):
@@ -457,7 +457,7 @@ class UtilsTest(unittest.TestCase):
class SplitCommandTest(unittest.TestCase):
def test_split_command_with_unicode(self):
assert split_command(u'echo μμ') == ['echo', 'μμ']
assert split_command('echo μμ') == ['echo', 'μμ']
class FormatEnvironmentTest(unittest.TestCase):
@@ -465,7 +465,7 @@ class FormatEnvironmentTest(unittest.TestCase):
env_dict = {
'ARTIST_NAME': b'\xec\x86\xa1\xec\xa7\x80\xec\x9d\x80'
}
assert format_environment(env_dict) == [u'ARTIST_NAME=송지은']
assert format_environment(env_dict) == ['ARTIST_NAME=송지은']
def test_format_env_no_value(self):
env_dict = {
@@ -14,15 +14,15 @@ from ansible_collections.community.docker.plugins.module_utils._scramble import
@pytest.mark.parametrize('plaintext, key, scrambled', [
(u'', b'0', '=S='),
(u'hello', b'\x00', '=S=aGVsbG8='),
(u'hello', b'\x01', '=S=aWRtbW4='),
('', b'0', '=S='),
('hello', b'\x00', '=S=aGVsbG8='),
('hello', b'\x01', '=S=aWRtbW4='),
])
def test_scramble_unscramble(plaintext, key, scrambled):
scrambled_ = scramble(plaintext, key)
print('{0!r} == {1!r}'.format(scrambled_, scrambled))
print(f'{scrambled_!r} == {scrambled!r}')
assert scrambled_ == scrambled
plaintext_ = unscramble(scrambled, key)
print('{0!r} == {1!r}'.format(plaintext_, plaintext))
print(f'{plaintext_!r} == {plaintext!r}')
assert plaintext_ == plaintext
@@ -39,7 +39,7 @@ def test_parse_string(input, expected):
])
def test_parse_int(input):
assert parse_modern(input) == input
with pytest.raises(TypeError, match="^must be an octal string, got {value}L?$".format(value=input)):
with pytest.raises(TypeError, match=f"^must be an octal string, got {input}L?$"):
parse_octal_string_only(input)
@@ -18,7 +18,7 @@ from ..test_support.docker_image_archive_stubbing import (
def assert_no_logging(msg):
raise AssertionError('Should not have logged anything but logged %s' % msg)
raise AssertionError(f'Should not have logged anything but logged {msg}')
def capture_logging(messages):
@@ -41,7 +41,7 @@ def test_archived_image_action_when_missing(tar_file_name):
fake_name = 'a:latest'
fake_id = 'a1'
expected = 'Archived image %s to %s, since none present' % (fake_name, tar_file_name)
expected = f'Archived image {fake_name} to {tar_file_name}, since none present'
actual = ImageManager.archived_image_action(assert_no_logging, tar_file_name, fake_name, api_image_id(fake_id))
@@ -65,7 +65,7 @@ def test_archived_image_action_when_invalid(tar_file_name):
write_irrelevant_tar(tar_file_name)
expected = 'Archived image %s to %s, overwriting an unreadable archive file' % (fake_name, tar_file_name)
expected = f'Archived image {fake_name} to {tar_file_name}, overwriting an unreadable archive file'
actual_log = []
actual = ImageManager.archived_image_action(
@@ -88,9 +88,7 @@ def test_archived_image_action_when_obsolete_by_id(tar_file_name):
write_imitation_archive(tar_file_name, old_id, [fake_name])
expected = 'Archived image %s to %s, overwriting archive with image %s named %s' % (
fake_name, tar_file_name, old_id, fake_name
)
expected = f'Archived image {fake_name} to {tar_file_name}, overwriting archive with image {old_id} named {fake_name}'
actual = ImageManager.archived_image_action(assert_no_logging, tar_file_name, fake_name, api_image_id(new_id))
assert actual == expected
@@ -103,11 +101,9 @@ def test_archived_image_action_when_obsolete_by_name(tar_file_name):
write_imitation_archive(tar_file_name, fake_id, [old_name])
expected = 'Archived image %s to %s, overwriting archive with image %s named %s' % (
new_name, tar_file_name, fake_id, old_name
)
expected = f'Archived image {new_name} to {tar_file_name}, overwriting archive with image {fake_id} named {old_name}'
actual = ImageManager.archived_image_action(assert_no_logging, tar_file_name, new_name, api_image_id(fake_id))
print('actual : %s', actual)
print('expected : %s', expected)
print(f'actual : {actual}')
print(f'expected : {expected}')
assert actual == expected
@@ -32,4 +32,4 @@ def test_validate_cidr_positives(cidr, expected):
def test_validate_cidr_negatives(cidr):
with pytest.raises(ValueError) as e:
validate_cidr(cidr)
assert '"{0}" is not a valid CIDR'.format(cidr) == str(e.value)
assert f'"{cidr}" is not a valid CIDR' == str(e.value)
@@ -75,7 +75,7 @@ def test_get_docker_environment(mocker, docker_swarm_service):
mocker.patch.object(
docker_swarm_service,
'format_environment',
side_effect=lambda d: ['{0}={1}'.format(key, value) for key, value in d.items()],
side_effect=lambda d: [f'{key}={value}' for key, value in d.items()],
)
# Test with env dict and file
result = docker_swarm_service.get_docker_environment(
@@ -207,7 +207,7 @@ def test_has_list_changed(docker_swarm_service):
)
assert docker_swarm_service.has_list_changed(
['sleep', '3400'],
[u'sleep', u'3600'],
['sleep', '3600'],
sort_lists=False
)
@@ -22,14 +22,14 @@ from ansible_collections.community.docker.plugins.plugin_utils.unsafe import (
TEST_MAKE_UNSAFE = [
(
_make_trusted(u'text'),
_make_trusted('text'),
[],
[
(),
],
),
(
_make_trusted(u'{{text}}'),
_make_trusted('{{text}}'),
[
(),
],
@@ -117,7 +117,7 @@ def test_make_unsafe_idempotence():
def test_make_unsafe_dict_key():
value = {
_make_trusted(u'test'): 2,
_make_trusted('test'): 2,
}
if not SUPPORTS_DATA_TAGGING:
value[_make_trusted(b"test")] = 1
@@ -127,7 +127,7 @@ def test_make_unsafe_dict_key():
assert _is_trusted(obj)
value = {
_make_trusted(u'{{test}}'): 2,
_make_trusted('{{test}}'): 2,
}
if not SUPPORTS_DATA_TAGGING:
value[_make_trusted(b"{{test}}")] = 1
@@ -138,7 +138,7 @@ def test_make_unsafe_dict_key():
def test_make_unsafe_set():
value = set([_make_trusted(u'test')])
value = set([_make_trusted('test')])
if not SUPPORTS_DATA_TAGGING:
value.add(_make_trusted(b"test"))
unsafe_value = make_unsafe(value)
@@ -146,7 +146,7 @@ def test_make_unsafe_set():
for obj in unsafe_value:
assert _is_trusted(obj)
value = set([_make_trusted(u'{{test}}')])
value = set([_make_trusted('{{test}}')])
if not SUPPORTS_DATA_TAGGING:
value.add(_make_trusted(b"{{test}}"))
unsafe_value = make_unsafe(value)
@@ -28,7 +28,7 @@ def write_imitation_archive(file_name, image_id, repo_tags):
manifest = [
{
'Config': '%s.json' % image_id,
'Config': f'{image_id}.json',
'RepoTags': repo_tags
}
]