8000 Use f-strings by mjcaley · Pull Request #223 · mjcaley/aiospamc · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Use f-strings #223

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 19, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 4 additions & 12 deletions aiospamc/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,17 +63,9 @@ def __init__(self,
self.logger.debug('Created instance of %r', self)

def __repr__(self) -> str:
client_fmt = ('{}(socket_path={}, '
'host={}, '
'port={}, '
'user={}, '
'compress={})')
return client_fmt.format(self.__class__.__name__,
repr(self._socket_path),
repr(self._host),
repr(self._port),
repr(self.user),
repr(self.compress))
return f'{self.__class__.__name__}(socket_path={self._socker_path}, ' \
f'host={repr(self._host)}, port={repr(self._port)}, ' \
f'user={repr(self.user)}, compress={repr(self.compress)})'

@staticmethod
def new_ssl_context(value: Union[bool, str, Path]) -> ssl.SSLContext:
Expand All @@ -98,7 +90,7 @@ def new_ssl_context(value: Union[bool, str, Path]) -> ssl.SSLContext:
elif cert_path.is_file():
return ssl.create_default_context(cafile=str(cert_path))
else:
raise FileNotFoundError('Certificate path does not exist at {}'.format(value))
raise FileNotFoundError(f'Certificate path does not exist at {value}')

async def send(self, request: Request) -> Response:
'''Sends a request to the SPAMD service.
Expand Down
8 changes: 3 additions & 5 deletions aiospamc/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,9 @@ def __init__(self, *, headers: Mapping[str, Union[HeaderValue, str, Any]] = None
self[key] = value

def __str__(self):
return '<{} object at {}, keys: {}>'.format(
'.'.join([self.__class__.__module__, self.__class__.__qualname__]),
id(self),
', '.join(self._headers.keys())
)
return f'<{".".join([self.__class__.__module__, self.__class__.__qualname__])} ' \
f'object at {id(self)}, ' \
f'keys: {", ".join(self._headers.keys())}>'

def __bytes__(self) -> bytes:
return b''.join(
Expand Down
11 changes: 3 additions & 8 deletions aiospamc/connections/tcp_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,7 @@ def __init__(self, host: str, port: int, ssl: SSLContext = None) -> None:
super().__init__()

def __repr__(self) -> str:
return '{}(host={}, port={}, ssl={})'.format(self.__class__.__name__,
repr(self.host),
repr(self.port),
self.ssl)
return f'{self.__class__.__name__}(host={self.host}, port={self.port}, ssl={self.ssl})'

def new_connection(self) -> 'TcpConnection':
'''Creates a new TCP connection.
Expand Down Expand Up @@ -59,10 +56,8 @@ def __init__(self, host: str, port: int, ssl: SSLContext = None):
super().__init__()

def __repr__(self) -> str:
return '{}(host={}, port={}, ssl={})'.format(self.__class__.__name__,
repr(self.host),
repr(self.port),
self.ssl)
return f'{self.__class__.__name__}(' \
f'host={repr(self.host)}, port={repr(self.port)}, ssl={repr(self.ssl)})'

async def open(self) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]:
'''Opens a connection.
Expand Down
4 changes: 2 additions & 2 deletions aiospamc/connections/unix_connection.py
ED4F
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def __init__(self, path: str) -> None:
super().__init__()

def __repr__(self) -> str:
return 'UnixConnectionManager(path={})'.format(repr(self.path))
return f'UnixConnectionManager(path={repr(self.path)})'

def new_connection(self) -> 'UnixConnection':
'''Creates a new Unix domain socket connection.
Expand All @@ -47,7 +47,7 @@ def __init__(self, path: str) -> None:
super().__init__()

def __repr__(self) -> str:
return 'UnixConnection(path={})'.format(repr(self.path))
return f'UnixConnection(path={repr(self.path)})'

async def open(self) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]:
'''Opens a connection.
Expand Down
39 changes: 18 additions & 21 deletions aiospamc/header_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def __init__(self, value: str, encoding='utf8') -> None:
self.encoding = encoding

def __str__(self):
return 'value={}, encoding={}'.format(repr(self.value), repr(self.encoding))
return f'value={repr(self.value)}, encoding={repr(self.encoding)}'

def __bytes__(self) -> bytes:
return self.value.encode(self.encoding)
Expand All @@ -31,11 +31,9 @@ def __eq__(self, other):
return False

def __repr__(self):
return '{}(value={}, encoding={})'.format(
self.__class__.__qualname__,
repr(self.value),
repr(self.encoding)
)
return f'{self.__class__.__qualname__}(' \
f'value={repr(self.value)}, ' \
f'encoding={repr(self.encoding)})'


class CompressValue(HeaderValue):
Expand All @@ -52,7 +50,7 @@ def __init__(self, algorithm='zlib') -> None:
self.algorithm = algorithm

def __str__(self):
return 'algorithm={}'.format(repr(self.algorithm))
return f'algorithm={repr(self.algorithm)}'

def __eq__(self, other):
try:
Expand All @@ -61,7 +59,7 @@ def __eq__(self, other):
return False

def __repr__(self) -> str:
return '{}()'.format(self.__class__.__qualname__)
return f'{self.__class__.__qualname__}()'

def __bytes__(self) -> bytes:
return self.algorithm.encode('ascii')
Expand All @@ -78,7 +76,7 @@ def __init__(self, length: int = 0) -> None:
self.length = length

def __str__(self):
return 'length={}'.format(repr(self.length))
return f'length={repr(self.length)}'

def __eq__(self, other):
try:
Expand All @@ -90,7 +88,7 @@ def __bytes__(self) -> bytes:
return str(self.length).encode('ascii')

def __repr__(self) -> str:
return &# F438 39;{}(length={})'.format(self.__class__.__qualname__, self.length)
return f'{self.__class__.__qualname__}(length={repr(self.length)})'


class MessageClassValue(HeaderValue):
Expand Down Expand Up @@ -119,7 +117,7 @@ def __bytes__(self) -> bytes:
return self.value.name.encode('ascii')

def __repr__(self) -> str:
return '{}(value={})'.format(self.__class__.__qualname__, str(self.value))
return f'{self.__class__.__qualname__}(value={repr(self.value)})'


class SetOrRemoveValue(HeaderValue):
Expand All @@ -134,7 +132,7 @@ def __init__(self, action: ActionOption = None) -> None:
self.action = action or ActionOption(local=False, remote=False)

def __str__(self):
return 'local={}, remote={}'.format(str(self.action.local), str(self.action.remote))
return f'local={self.action.local}, remote={self.action.remote}'

def __eq__(self, other):
try:
Expand All @@ -157,8 +155,7 @@ def __bytes__(self) -> bytes:
return b', '.join(values)

def __repr__(self) -> str:
return '{}(action={})'.format(self.__class__.__qualname__,
repr(self.action))
return f'{self.__class__.__qualname__}(action={repr(self.action)})'


class SpamValue(HeaderValue):
Expand All @@ -178,7 +175,7 @@ def __init__(self, value: bool = False, score: float = 0.0, threshold: float = 0
self.threshold = threshold

def __str__(self):
return 'value={}, score={}, threshold={}'.format(str(self.value), str(self.score), str(self.threshold))
return f'value={str(self.value)}, score={self.score}, threshold={self.threshold}'

def __eq__(self, other):
try:
Expand All @@ -192,10 +189,10 @@ def __bytes__(self) -> bytes:
self.threshold)

def __repr__(self) -> str:
return '{}(value={}, score={}, threshold={})'.format(self.__class__.__qualname__,
self.value,
self.score,
self.threshold)
return f'{self.__class__.__qualname__}(' \
f'value={repr(self.value)}, ' \
f'score={repr(self.score)}, ' \
f'threshold={repr(self.threshold)})'


class UserValue(HeaderValue):
Expand All @@ -211,7 +208,7 @@ def __init__(self, name: str = None) -> None:
self.name = name or getpass.getuser()

def __str__(self):
return 'name={}'.format(self.name)
return f'name={self.name}'

def __eq__(self, other):
try:
Expand All @@ -223,4 +220,4 @@ def __bytes__(self) -> bytes:
return self.name.encode('ascii')

def __repr__(self) -> str:
return '{}(name={})'.format(self.__class__.__qualname__, repr(self.name))
return f'{self.__class__.__qualname__}(name={repr(self.name)})'
8 changes: 3 additions & 5 deletions aiospamc/requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,8 @@ def __bytes__(self) -> bytes:
b'body': body}

def __str__(self):
return '<{}: {} object at {}>'.format(
self.verb,
'.'.join([self.__class__.__module__, self.__class__.__qualname__]),
id(self)
)
return f'<{self.verb}: ' \
f'{".".join([self.__class__.__module__, self.__class__.__qualname__])} ' \
f'object at {id(self)}>'

body = SpamcBody() # type: Union[bytes, SupportsBytes]
10 changes: 4 additions & 6 deletions aiospamc/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,12 +110,10 @@ def __bytes__(self) -> bytes:
b'body': body}

def __str__(self):
return '<{} - {}: {} object at {}>'.format(
self.status_code.value,
self.status_code.name,
'.'.join([self.__class__.__module__, self.__class__.__qualname__]),
id(self)
)
return f'<{self.status_code.value} - ' \
f'{self.status_code.name}: ' \
f'{".".join([self.__class__.__module__, self.__class__.__qualname__])} ' \
f'object at {id(self)}>'

body = SpamcBody() # type: Union[bytes, SupportsBytes]

Expand Down
8 changes: 4 additions & 4 deletions docs/user_guide.rst
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,10 @@ spam as well as the score.

response = loop.run_until_complete(check_for_spam(example_message))
print(
'Is the message spam? {}'.format(response.headers['Spam'].value),
'The score and threshold is {} / {}'.format(
response.headers['Spam'].score,
response.headers['Spam'].threshold)
f'Is the message spam? {response.headers['Spam'].value}\n',
f'The score and threshold is {response.headers['Spam'].score} ',
f'/ {response.headers['Spam'].threshold}'),
sep=''
)

All the frontend functions instantiate the :class:`aiospamc.client.Client`
Expand Down
12 changes: 1 addition & 11 deletions tests/connections/test_tcp_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,6 @@ def test_instantiates_with_ssl(address, mocker):
assert conn.ssl is ssl_stub


def test_repr(address):
conn = TcpConnection(host=address[0], port=address[1])

assert repr(conn) == 'TcpConnection(host={}, port={}, ssl={})'.format(
repr(address[0]),
repr(address[1]),
repr(None)
)


@pytest.mark.asyncio
async def test_open(address, open_connection):
conn = TcpConnection(host=address[0], port=address[1])
Expand Down Expand Up @@ -62,4 +52,4 @@ async def test_open_error(address, os_error):
def test_connection_string(address):
conn = TcpConnection(host=address[0], port=address[1])

assert conn.connection_string == '{}:{}'.format(address[0], address[1])
assert conn.connection_string == f'{address[0]}:{address[1]}'
9 changes: 0 additions & 9 deletions tests/connections/test_tcp_connection_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,6 @@ def test_instantiates_with_ssl(address, mocker):
assert conn_man.ssl is ssl_stub


def test_repr(address):
conn_man = TcpConnectionManager(address[0], address[1])

assert repr(conn_man) == 'TcpConnectionManager(host={}, port={}, ssl=None)'.format(
repr(address[0]),
repr(address[1])
)


@pytest.mark.asyncio
async def test_new_connection(address, open_connection):
conn = TcpConnectionManager(address[0], address[1])
Expand Down
8 changes: 0 additions & 8 deletions tests/connections/test_unix_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,6 @@ def test_instantiates(unix_socket):
assert conn.path is unix_socket


def test_repr(unix_socket):
conn = UnixConnection(unix_socket)

assert repr(conn) == 'UnixConnection(path={})'.format(
repr(unix_socket)
)


@pytest.mark.asyncio
async def test_open(unix_socket, open_unix_connection):
conn = UnixConnection(unix_socket)
Expand Down
4 changes: 1 addition & 3 deletions tests/connections/test_unix_connection_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ def test_instantiates(unix_socket):
def test_repr(unix_socket):
conn_man = UnixConnectionManager(unix_socket)

assert repr(conn_man) == 'UnixConnectionManager(path={})'.format(
repr(unix_socket)
)
assert repr(conn_man) == f'UnixConnectionManager(path={repr(unix_socket)})'


@pytest.mark.asyncio
Expand Down
12 changes: 6 additions & 6 deletions tests/integration/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,18 +96,18 @@ def spamd(spamd_tcp_options, spamd_ssl_options, spamd_unix_options, tmp_path_fac
log_file = tmp_path_factory.mktemp('spamd') / 'spamd.log'

options = [
'--syslog={}'.format(str(log_file)),
f'--syslog={str(log_file)}',
'--local',
'--allow-tell',
'--listen={host}:{port}'.format(**spamd_tcp_options),
'--listen=ssl:{host}:{port}'.format(**spamd_ssl_options),
f'--listen={spamd_tcp_options["host"]}:{spamd_tcp_options["port"]}',
f'--listen=ssl:{spamd_ssl_options["host"]}:{spamd_ssl_options["port"]}',
'--server-key',
'{key}'.format(**spamd_ssl_options),
f'{spamd_ssl_options["key"]}',
'--server-cert',
'{cert}'.format(**spamd_ssl_options)
f'{spamd_ssl_options["cert"]}'
]
if spamd_unix_options:
options += ['--socketpath={socket}'.format(**spamd_unix_options)]
options += [f'--socketpath={spamd_unix_options["socket"]}']

process = Popen(
['spamd', *options],
Expand Down
9 changes: 0 additions & 9 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,6 @@
from aiospamc.responses import Response


def test_client_repr():
client = Client()
assert repr(client) == ('Client(socket_path=None, '
'host=\'localhost\', '
'port=783, '
'user=None, '
'compress=False)')


def test_ssl_context_from_true(mocker):
mocker.spy(ssl, 'create_default_context')
s = Client.new_ssl_context(True)
Expand Down
2 changes: 1 addition & 1 deletion tests/test_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ def test_headers_str_object():
h = SpamcHeaders()
result = str(h)

assert result.startswith('<aiospamc.common.SpamcHeaders object at {}'.format(id(h)))
assert result.startswith(f'<aiospamc.common.SpamcHeaders object at {id(h)}')
assert result.endswith('>')


Expand Down
Loading
0