Upgrade Python syntax with pyupgrade --py36-plus

This commit is contained in:
Hugo 2018-10-18 13:42:45 +03:00 committed by Lex Berezhny
parent 18a0204105
commit 2e6c848c39
45 changed files with 109 additions and 109 deletions

View file

@ -182,7 +182,7 @@ class BlobFile:
if writer.len_so_far != self.length: if writer.len_so_far != self.length:
err_string = "blob length is %i vs expected %i" % (writer.len_so_far, self.length) err_string = "blob length is %i vs expected %i" % (writer.len_so_far, self.length)
else: else:
err_string = "blob hash is %s vs expected %s" % (writer.blob_hash, self.blob_hash) err_string = f"blob hash is {writer.blob_hash} vs expected {self.blob_hash}"
errback_finished_deferred(Failure(InvalidDataError(err_string))) errback_finished_deferred(Failure(InvalidDataError(err_string)))
d = defer.succeed(None) d = defer.succeed(None)
else: else:

View file

@ -147,15 +147,15 @@ def main(argv=None):
elif method not in Daemon.callable_methods: elif method not in Daemon.callable_methods:
if method not in Daemon.deprecated_methods: if method not in Daemon.deprecated_methods:
print('{} is not a valid command.'.format(method)) print(f'{method} is not a valid command.')
return 1 return 1
new_method = Daemon.deprecated_methods[method].new_command new_method = Daemon.deprecated_methods[method].new_command
if new_method is None: if new_method is None:
print("{} is permanently deprecated and does not have a replacement command.".format(method)) print(f"{method} is permanently deprecated and does not have a replacement command.")
return 0 return 0
print("{} is deprecated, using {}.".format(method, new_method)) print(f"{method} is deprecated, using {new_method}.")
method = new_method method = new_method
fn = Daemon.callable_methods[method] fn = Daemon.callable_methods[method]

View file

@ -154,7 +154,7 @@ def server_list(servers):
def server_list_reverse(servers): def server_list_reverse(servers):
return ["%s:%s" % (server, port) for server, port in servers] return [f"{server}:{port}" for server, port in servers]
class Env(envparse.Env): class Env(envparse.Env):
@ -367,7 +367,7 @@ class Config:
def _assert_valid_data_type(self, data_type): def _assert_valid_data_type(self, data_type):
if data_type not in self._data: if data_type not in self._data:
raise KeyError('{} in is not a valid data type'.format(data_type)) raise KeyError(f'{data_type} in is not a valid data type')
def get_valid_setting_names(self): def get_valid_setting_names(self):
return self._data[TYPE_DEFAULT].keys() return self._data[TYPE_DEFAULT].keys()
@ -377,7 +377,7 @@ class Config:
def _assert_valid_setting(self, name): def _assert_valid_setting(self, name):
if not self._is_valid_setting(name): if not self._is_valid_setting(name):
raise KeyError('{} is not a valid setting'.format(name)) raise KeyError(f'{name} is not a valid setting')
def _validate_settings(self, data): def _validate_settings(self, data):
invalid_settings = set(data.keys()) - set(self.get_valid_setting_names()) invalid_settings = set(data.keys()) - set(self.get_valid_setting_names())
@ -387,7 +387,7 @@ class Config:
def _assert_editable_setting(self, name): def _assert_editable_setting(self, name):
self._assert_valid_setting(name) self._assert_valid_setting(name)
if name in self._fixed_defaults: if name in self._fixed_defaults:
raise ValueError('{} is not an editable setting'.format(name)) raise ValueError(f'{name} is not an editable setting')
def _assert_valid_setting_value(self, name, value): def _assert_valid_setting_value(self, name, value):
if name == "max_key_fee": if name == "max_key_fee":
@ -442,7 +442,7 @@ class Config:
for possible_data_type in self._search_order: for possible_data_type in self._search_order:
if name in self._data[possible_data_type]: if name in self._data[possible_data_type]:
return self._data[possible_data_type][name] return self._data[possible_data_type][name]
raise KeyError('{} is not a valid setting'.format(name)) raise KeyError(f'{name} is not a valid setting')
def set(self, name, value, data_types=(TYPE_RUNTIME,)): def set(self, name, value, data_types=(TYPE_RUNTIME,)):
"""Set a config value """Set a config value
@ -582,7 +582,7 @@ class Config:
def get_api_connection_string(self, user: str = None, password: str = None) -> str: def get_api_connection_string(self, user: str = None, password: str = None) -> str:
return 'http%s://%s%s:%i/%s' % ( return 'http%s://%s%s:%i/%s' % (
"" if not self['use_https'] else "s", "" if not self['use_https'] else "s",
"" if not (user and password) else "%s:%s@" % (user, password), "" if not (user and password) else f"{user}:{password}@",
self['api_host'], self['api_host'],
self['api_port'], self['api_port'],
self['API_ADDRESS'] self['API_ADDRESS']

View file

@ -41,7 +41,7 @@ class DiskBlobManager:
blob that is already on the hard disk blob that is already on the hard disk
""" """
if length is not None and not isinstance(length, int): if length is not None and not isinstance(length, int):
raise Exception("invalid length type: %s (%s)" % (length, str(type(length)))) raise Exception("invalid length type: {} ({})".format(length, str(type(length))))
if blob_hash in self.blobs: if blob_hash in self.blobs:
return defer.succeed(self.blobs[blob_hash]) return defer.succeed(self.blobs[blob_hash])
return self._make_new_blob(blob_hash, length) return self._make_new_blob(blob_hash, length)

View file

@ -16,13 +16,13 @@ class DownloadCanceledError(Exception):
class DownloadSDTimeout(Exception): class DownloadSDTimeout(Exception):
def __init__(self, download): def __init__(self, download):
super().__init__('Failed to download sd blob {} within timeout'.format(download)) super().__init__(f'Failed to download sd blob {download} within timeout')
self.download = download self.download = download
class DownloadTimeoutError(Exception): class DownloadTimeoutError(Exception):
def __init__(self, download): def __init__(self, download):
super().__init__('Failed to download {} within timeout'.format(download)) super().__init__(f'Failed to download {download} within timeout')
self.download = download self.download = download
@ -73,32 +73,32 @@ class KeyFeeAboveMaxAllowed(Exception):
class InvalidExchangeRateResponse(Exception): class InvalidExchangeRateResponse(Exception):
def __init__(self, source, reason): def __init__(self, source, reason):
super().__init__('Failed to get exchange rate from {}:{}'.format(source, reason)) super().__init__(f'Failed to get exchange rate from {source}:{reason}')
self.source = source self.source = source
self.reason = reason self.reason = reason
class UnknownNameError(Exception): class UnknownNameError(Exception):
def __init__(self, name): def __init__(self, name):
super().__init__('Name {} is unknown'.format(name)) super().__init__(f'Name {name} is unknown')
self.name = name self.name = name
class UnknownClaimID(Exception): class UnknownClaimID(Exception):
def __init__(self, claim_id): def __init__(self, claim_id):
super().__init__('Claim {} is unknown'.format(claim_id)) super().__init__(f'Claim {claim_id} is unknown')
self.claim_id = claim_id self.claim_id = claim_id
class UnknownURI(Exception): class UnknownURI(Exception):
def __init__(self, uri): def __init__(self, uri):
super().__init__('URI {} cannot be resolved'.format(uri)) super().__init__(f'URI {uri} cannot be resolved')
self.name = uri self.name = uri
class UnknownOutpoint(Exception): class UnknownOutpoint(Exception):
def __init__(self, outpoint): def __init__(self, outpoint):
super().__init__('Outpoint {} cannot be resolved'.format(outpoint)) super().__init__(f'Outpoint {outpoint} cannot be resolved')
self.outpoint = outpoint self.outpoint = outpoint
@ -124,7 +124,7 @@ class InvalidStreamDescriptorError(Exception):
class InvalidStreamInfoError(Exception): class InvalidStreamInfoError(Exception):
def __init__(self, name, stream_info): def __init__(self, name, stream_info):
msg = '{} has claim with invalid stream info: {}'.format(name, stream_info) msg = f'{name} has claim with invalid stream info: {stream_info}'
super().__init__(msg) super().__init__(msg)
self.name = name self.name = name
self.stream_info = stream_info self.stream_info = stream_info
@ -180,13 +180,13 @@ class InvalidCurrencyError(Exception):
def __init__(self, currency): def __init__(self, currency):
self.currency = currency self.currency = currency
super().__init__( super().__init__(
'Invalid currency: {} is not a supported currency.'.format(currency)) f'Invalid currency: {currency} is not a supported currency.')
class NoSuchDirectoryError(Exception): class NoSuchDirectoryError(Exception):
def __init__(self, directory): def __init__(self, directory):
self.directory = directory self.directory = directory
super().__init__('No such directory {}'.format(directory)) super().__init__(f'No such directory {directory}')
class ComponentStartConditionNotMet(Exception): class ComponentStartConditionNotMet(Exception):

View file

@ -188,4 +188,4 @@ class HTTPBlobDownloader:
def url_for(server, blob_hash=''): def url_for(server, blob_hash=''):
return 'http://{}/{}'.format(server, blob_hash) return f'http://{server}/{blob_hash}'

View file

@ -40,7 +40,7 @@ class Peer:
self.stats[stat_type] += count self.stats[stat_type] += count
def __str__(self): def __str__(self):
return '{}:{}'.format(self.host, self.port) return f'{self.host}:{self.port}'
def __repr__(self): def __repr__(self):
return 'Peer({!r}, {!r})'.format(self.host, self.port) return f'Peer({self.host!r}, {self.port!r})'

View file

@ -27,7 +27,7 @@ def get_points(num_bytes, rate):
def cache(fn): def cache(fn):
"""Caches the function call for each instance""" """Caches the function call for each instance"""
attr = '__{}_value'.format(fn.__name__) attr = f'__{fn.__name__}_value'
def helper(self): def helper(self):
if not hasattr(self, attr): if not hasattr(self, attr):

View file

@ -3,7 +3,7 @@ class LoopingCallManager:
self.calls = calls or {} self.calls = calls or {}
def register_looping_call(self, name, call): def register_looping_call(self, name, call):
assert name not in self.calls, '{} is already registered'.format(name) assert name not in self.calls, f'{name} is already registered'
self.calls[name] = call self.calls[name] = call
def start(self, name, *args): def start(self, name, *args):

View file

@ -195,7 +195,7 @@ class DeferredProfiler:
caller: [(start, finished, finished - start, success) caller: [(start, finished, finished - start, success)
for (start, finished, _caller, success) in profile_results for (start, finished, _caller, success) in profile_results
if _caller == caller] if _caller == caller]
for caller in set(result[2] for result in profile_results) for caller in {result[2] for result in profile_results}
} }
log.info("called %s %i times from %i sources\n", fn.__name__, len(profile_results), len(call_counts)) log.info("called %s %i times from %i sources\n", fn.__name__, len(profile_results), len(call_counts))

View file

@ -13,7 +13,7 @@ TRACE = 5
# caller stack frame. # caller stack frame.
# #
if hasattr(sys, 'frozen'): # support for py2exe if hasattr(sys, 'frozen'): # support for py2exe
_srcfile = "logging%s__init__%s" % (os.sep, __file__[-4:]) _srcfile = "logging{}__init__{}".format(os.sep, __file__[-4:])
elif __file__[-4:].lower() in ['.pyc', '.pyo']: elif __file__[-4:].lower() in ['.pyc', '.pyo']:
_srcfile = __file__[:-4] + '.py' _srcfile = __file__[:-4] + '.py'
else: else:

View file

@ -60,7 +60,7 @@ def get_wallet_config():
if wallet_type == conf.LBRYCRD_WALLET: if wallet_type == conf.LBRYCRD_WALLET:
raise ValueError('LBRYcrd Wallet is no longer supported') raise ValueError('LBRYcrd Wallet is no longer supported')
elif wallet_type != conf.LBRYUM_WALLET: elif wallet_type != conf.LBRYUM_WALLET:
raise ValueError('Wallet Type {} is not valid'.format(wallet_type)) raise ValueError(f'Wallet Type {wallet_type} is not valid')
lbryum_servers = {address: {'t': str(port)} lbryum_servers = {address: {'t': str(port)}
for address, port in GCS('lbryum_servers')} for address, port in GCS('lbryum_servers')}
config = { config = {
@ -210,7 +210,7 @@ class HeadersComponent(Component):
self._headers_progress_percent = math.ceil(local_size / final_size * 100) self._headers_progress_percent = math.ceil(local_size / final_size * 100)
local_header_size = self.local_header_file_size() local_header_size = self.local_header_file_size()
resume_header = {"Range": "bytes={}-".format(local_header_size)} resume_header = {"Range": f"bytes={local_header_size}-"}
response = yield treq.get(HEADERS_URL, headers=resume_header) response = yield treq.get(HEADERS_URL, headers=resume_header)
got_406 = response.code == 406 # our file is bigger got_406 = response.code == 406 # our file is bigger
final_size_after_download = response.length + local_header_size final_size_after_download = response.length + local_header_size
@ -284,7 +284,7 @@ class HeadersComponent(Component):
hashsum.update(headers_file.read(checksum_length_in_bytes)) hashsum.update(headers_file.read(checksum_length_in_bytes))
current_checksum = hashsum.hexdigest() current_checksum = hashsum.hexdigest()
if current_checksum != checksum: if current_checksum != checksum:
msg = "Expected checksum {}, got {}".format(checksum, current_checksum) msg = f"Expected checksum {checksum}, got {current_checksum}"
log.warning("Wallet file corrupted, checksum mismatch. " + msg) log.warning("Wallet file corrupted, checksum mismatch. " + msg)
log.warning("Deleting header file so it can be downloaded again.") log.warning("Deleting header file so it can be downloaded again.")
os.unlink(self.headers_file) os.unlink(self.headers_file)
@ -664,7 +664,7 @@ class ReflectorComponent(Component):
log.info('Started reflector on port %s', self.reflector_server_port) log.info('Started reflector on port %s', self.reflector_server_port)
except error.CannotListenError as e: except error.CannotListenError as e:
log.exception("Couldn't bind reflector to port %d", self.reflector_server_port) log.exception("Couldn't bind reflector to port %d", self.reflector_server_port)
raise ValueError("{} lbrynet may already be running on your computer.".format(e)) raise ValueError(f"{e} lbrynet may already be running on your computer.")
@defer.inlineCallbacks @defer.inlineCallbacks
def stop(self): def stop(self):

View file

@ -278,7 +278,7 @@ class Daemon(AuthJSONRPCServer):
def setup(self): def setup(self):
log.info("Starting lbrynet-daemon") log.info("Starting lbrynet-daemon")
log.info("Platform: %s", json.dumps(system_info.get_platform())) log.info("Platform: %s", json.dumps(system_info.get_platform()))
yield super(Daemon, self).setup() yield super().setup()
log.info("Started lbrynet-daemon") log.info("Started lbrynet-daemon")
def _stop_streams(self): def _stop_streams(self):
@ -288,7 +288,7 @@ class Daemon(AuthJSONRPCServer):
def _shutdown(self): def _shutdown(self):
self._stop_streams() self._stop_streams()
return super(Daemon, self)._shutdown() return super()._shutdown()
def _download_blob(self, blob_hash, rate_manager=None, timeout=None): def _download_blob(self, blob_hash, rate_manager=None, timeout=None):
""" """
@ -597,7 +597,7 @@ class Daemon(AuthJSONRPCServer):
lbry_file = l_f lbry_file = l_f
break break
else: else:
raise NoValidSearch('{} is not a valid search operation'.format(search_by)) raise NoValidSearch(f'{search_by} is not a valid search operation')
if return_json and lbry_file: if return_json and lbry_file:
lbry_file = yield self._get_lbry_file_dict(lbry_file) lbry_file = yield self._get_lbry_file_dict(lbry_file)
defer.returnValue(lbry_file) defer.returnValue(lbry_file)
@ -984,7 +984,7 @@ class Daemon(AuthJSONRPCServer):
fn = self.callable_methods.get(command) fn = self.callable_methods.get(command)
if fn is None: if fn is None:
raise Exception( raise Exception(
"No help available for '{}'. It is not a valid command.".format(command) f"No help available for '{command}'. It is not a valid command."
) )
return self._render_response({ return self._render_response({
@ -1888,7 +1888,7 @@ class Daemon(AuthJSONRPCServer):
search_type, value = get_lbry_file_search_value(kwargs) search_type, value = get_lbry_file_search_value(kwargs)
lbry_file = yield self._get_lbry_file(search_type, value, return_json=False) lbry_file = yield self._get_lbry_file(search_type, value, return_json=False)
if not lbry_file: if not lbry_file:
raise Exception('Unable to find a file for {}:{}'.format(search_type, value)) raise Exception(f'Unable to find a file for {search_type}:{value}')
if status == 'start' and lbry_file.stopped or status == 'stop' and not lbry_file.stopped: if status == 'start' and lbry_file.stopped or status == 'stop' and not lbry_file.stopped:
yield self.file_manager.toggle_lbry_file_running(lbry_file) yield self.file_manager.toggle_lbry_file_running(lbry_file)
@ -3282,7 +3282,7 @@ class Daemon(AuthJSONRPCServer):
certificates = await self.wallet_manager.get_certificates( certificates = await self.wallet_manager.get_certificates(
private_key_accounts=accounts, claim_name=channel_name) private_key_accounts=accounts, claim_name=channel_name)
if not certificates: if not certificates:
raise ValueError("Couldn't find channel with name '{}'.".format(channel_name)) raise ValueError(f"Couldn't find channel with name '{channel_name}'.")
return certificates[0] return certificates[0]
raise ValueError("Couldn't find channel because a channel name or channel_id was not provided.") raise ValueError("Couldn't find channel because a channel name or channel_id was not provided.")
@ -3307,7 +3307,7 @@ class Daemon(AuthJSONRPCServer):
.format(account_id, account.ledger.symbol, argument_name) .format(account_id, account.ledger.symbol, argument_name)
) )
return account return account
raise ValueError("Couldn't find account: {}.".format(account_id)) raise ValueError(f"Couldn't find account: {account_id}.")
@staticmethod @staticmethod
def get_dewies_or_error(argument: str, lbc: str): def get_dewies_or_error(argument: str, lbc: str):
@ -3356,7 +3356,7 @@ def get_lbry_file_search_value(search_fields):
value = search_fields.get(searchtype, None) value = search_fields.get(searchtype, None)
if value is not None: if value is not None:
return searchtype, value return searchtype, value
raise NoValidSearch('{} is missing a valid search type'.format(search_fields)) raise NoValidSearch(f'{search_fields} is missing a valid search type')
def iter_lbry_file_search_values(search_fields): def iter_lbry_file_search_values(search_fields):

View file

@ -105,7 +105,7 @@ To exit:
""" """
welcome = "{:*^60}\n".format(" Welcome to the lbrynet interactive console! ") welcome = "{:*^60}\n".format(" Welcome to the lbrynet interactive console! ")
welcome += "\n".join(["{:<60}".format(w) for w in welcometext.splitlines()]) welcome += "\n".join([f"{w:<60}" for w in welcometext.splitlines()])
welcome += "\n%s" % ("*" * 60) welcome += "\n%s" % ("*" * 60)
welcome = color(welcome, "grey") welcome = color(welcome, "grey")
banner = color(logo, "green") + color(welcome, "grey") banner = color(logo, "green") + color(welcome, "grey")
@ -156,7 +156,7 @@ def run_terminal(callable_methods, started_daemon, quiet=False):
try: try:
reactor.callLater(0, reactor.stop) reactor.callLater(0, reactor.stop)
except Exception as err: except Exception as err:
print("error stopping reactor: {}".format(err)) print(f"error stopping reactor: {err}")
return sys.exit(status) return sys.exit(status)
locs.update({'exit': exit}) locs.update({'exit': exit})

View file

@ -107,8 +107,8 @@ class GetStream:
if converted_fee_amount > (yield f2d(self.wallet.default_account.get_balance())): if converted_fee_amount > (yield f2d(self.wallet.default_account.get_balance())):
raise InsufficientFundsError('Unable to pay the key fee of %s' % converted_fee_amount) raise InsufficientFundsError('Unable to pay the key fee of %s' % converted_fee_amount)
if converted_fee_amount > max_key_fee_amount and not self.disable_max_key_fee: if converted_fee_amount > max_key_fee_amount and not self.disable_max_key_fee:
raise KeyFeeAboveMaxAllowed('Key fee %s above max allowed %s' % (converted_fee_amount, raise KeyFeeAboveMaxAllowed('Key fee {} above max allowed {}'.format(converted_fee_amount,
max_key_fee_amount)) max_key_fee_amount))
converted_fee = { converted_fee = {
'currency': 'LBC', 'currency': 'LBC',
'amount': converted_fee_amount, 'amount': converted_fee_amount,
@ -120,7 +120,7 @@ class GetStream:
for factory in factories: for factory in factories:
if isinstance(factory, ManagedEncryptedFileDownloaderFactory): if isinstance(factory, ManagedEncryptedFileDownloaderFactory):
return factory return factory
raise Exception('No suitable factory was found in {}'.format(factories)) raise Exception(f'No suitable factory was found in {factories}')
@defer.inlineCallbacks @defer.inlineCallbacks
def get_downloader(self, factory, stream_metadata, file_name=None): def get_downloader(self, factory, stream_metadata, file_name=None):
@ -140,7 +140,7 @@ class GetStream:
reserved_points = self.wallet.reserve_points(address, fee_lbc) reserved_points = self.wallet.reserve_points(address, fee_lbc)
if reserved_points is None: if reserved_points is None:
raise InsufficientFundsError( raise InsufficientFundsError(
'Unable to pay the key fee of %s for %s' % (dewies_to_lbc(fee_lbc), name) 'Unable to pay the key fee of {} for {}'.format(dewies_to_lbc(fee_lbc), name)
) )
return f2d(self.wallet.send_points_to_address(reserved_points, fee_lbc)) return f2d(self.wallet.send_points_to_address(reserved_points, fee_lbc))

View file

@ -234,7 +234,7 @@ class ExchangeRateManager:
return self.convert_currency( return self.convert_currency(
market.rate.currency_pair[1], to_currency, amount * market.rate.spot) market.rate.currency_pair[1], to_currency, amount * market.rate.spot)
raise CurrencyConversionError( raise CurrencyConversionError(
'Unable to convert {} from {} to {}'.format(amount, from_currency, to_currency)) f'Unable to convert {amount} from {from_currency} to {to_currency}')
def fee_dict(self): def fee_dict(self):
return {market: market.rate.as_dict() for market in self.market_feeds} return {market: market.rate.as_dict() for market in self.market_feeds}

View file

@ -28,9 +28,9 @@ class Publisher:
"""Create lbry file and make claim""" """Create lbry file and make claim"""
log.info('Starting publish for %s', name) log.info('Starting publish for %s', name)
if not os.path.isfile(file_path): if not os.path.isfile(file_path):
raise Exception("File {} not found".format(file_path)) raise Exception(f"File {file_path} not found")
if os.path.getsize(file_path) == 0: if os.path.getsize(file_path) == 0:
raise Exception("Cannot publish empty file {}".format(file_path)) raise Exception(f"Cannot publish empty file {file_path}")
file_name = os.path.basename(file_path) file_name = os.path.basename(file_path)
with open(file_path, 'rb') as read_handle: with open(file_path, 'rb') as read_handle:

View file

@ -580,7 +580,7 @@ class SQLiteStorage:
return [ return [
_format_support(*support_info) _format_support(*support_info)
for support_info in transaction.execute( for support_info in transaction.execute(
"select * from support where claim_id {}".format(bind), f"select * from support where claim_id {bind}",
tuple(claim_ids) tuple(claim_ids)
).fetchall() ).fetchall()
] ]
@ -773,7 +773,7 @@ class SQLiteStorage:
results[stream_hash] = result results[stream_hash] = result
bind = "({})".format(','.join('?' for _ in range(len(channel_id_infos)))) bind = "({})".format(','.join('?' for _ in range(len(channel_id_infos))))
for claim_id, channel_name in transaction.execute( for claim_id, channel_name in transaction.execute(
"select claim_id, claim_name from claim where claim_id in {}".format(bind), f"select claim_id, claim_name from claim where claim_id in {bind}",
tuple(channel_id_infos.keys()) tuple(channel_id_infos.keys())
).fetchall(): ).fetchall():
for stream_hash in channel_id_infos[claim_id]: for stream_hash in channel_id_infos[claim_id]:

View file

@ -48,5 +48,5 @@ class ErrorMessage(ResponseMessage):
def __init__(self, rpcID, nodeID, exceptionType, errorMessage): def __init__(self, rpcID, nodeID, exceptionType, errorMessage):
super().__init__(rpcID, nodeID, errorMessage) super().__init__(rpcID, nodeID, errorMessage)
if isinstance(exceptionType, type): if isinstance(exceptionType, type):
exceptionType = ('%s.%s' % (exceptionType.__module__, exceptionType.__name__)).encode() exceptionType = (f'{exceptionType.__module__}.{exceptionType.__name__}').encode()
self.exceptionType = exceptionType self.exceptionType = exceptionType

View file

@ -499,7 +499,7 @@ class Node(MockKademliaHelper):
if 0 <= port <= 65536: if 0 <= port <= 65536:
compact_port = port.to_bytes(2, 'big') compact_port = port.to_bytes(2, 'big')
else: else:
raise TypeError('Invalid port: {}'.format(port)) raise TypeError(f'Invalid port: {port}')
compact_address = compact_ip + compact_port + rpc_contact.id compact_address = compact_ip + compact_port + rpc_contact.id
now = int(self.clock.seconds()) now = int(self.clock.seconds())
originallyPublished = now - age originallyPublished = now - age

View file

@ -55,7 +55,7 @@ class DHTPeerFinder(DummyPeerFinder):
finished_deferred.addTimeout(timeout, self.dht_node.clock) finished_deferred.addTimeout(timeout, self.dht_node.clock)
try: try:
peer_list = yield finished_deferred peer_list = yield finished_deferred
self.peers[blob_hash].update(set((host, port) for _, host, port in peer_list)) self.peers[blob_hash].update({(host, port) for _, host, port in peer_list})
except defer.TimeoutError: except defer.TimeoutError:
log.debug("DHT timed out while looking peers for blob %s after %s seconds", blob_hash, timeout) log.debug("DHT timed out while looking peers for blob %s after %s seconds", blob_hash, timeout)
finally: finally:
@ -63,4 +63,4 @@ class DHTPeerFinder(DummyPeerFinder):
def _filter_self(self, blob_hash): def _filter_self(self, blob_hash):
my_host, my_port = self.dht_node.externalIP, self.dht_node.peerPort my_host, my_port = self.dht_node.externalIP, self.dht_node.peerPort
return set((host, port) for host, port in self.peers[blob_hash] if (host, port) != (my_host, my_port)) return {(host, port) for host, port in self.peers[blob_hash] if (host, port) != (my_host, my_port)}

View file

@ -338,7 +338,7 @@ class KademliaProtocol(protocol.DatagramProtocol):
while seqNumber < totalPackets: while seqNumber < totalPackets:
packetData = data[startPos:startPos + self.msgSizeLimit] packetData = data[startPos:startPos + self.msgSizeLimit]
encSeqNumber = chr(seqNumber >> 8) + chr(seqNumber & 0xff) encSeqNumber = chr(seqNumber >> 8) + chr(seqNumber & 0xff)
txData = '\x00%s%s%s\x00%s' % (encTotalPackets, encSeqNumber, rpcID, packetData) txData = f'\x00{encTotalPackets}{encSeqNumber}{rpcID}\x00{packetData}'
self._scheduleSendNext(txData, address) self._scheduleSendNext(txData, address)
startPos += self.msgSizeLimit startPos += self.msgSizeLimit

View file

@ -93,7 +93,7 @@ class ManagedEncryptedFileDownloader(EncryptedFileSaver):
elif status == ManagedEncryptedFileDownloader.STATUS_FINISHED: elif status == ManagedEncryptedFileDownloader.STATUS_FINISHED:
self.completed = True self.completed = True
else: else:
raise Exception("Unknown status for stream %s: %s" % (self.stream_hash, status)) raise Exception(f"Unknown status for stream {self.stream_hash}: {status}")
@defer.inlineCallbacks @defer.inlineCallbacks
def stop(self, err=None, change_status=True): def stop(self, err=None, change_status=True):

View file

@ -111,7 +111,7 @@ class BlobReflectorClient(Protocol):
raise ValueError("Need protocol version number!") raise ValueError("Need protocol version number!")
server_version = int(response_dict['version']) server_version = int(response_dict['version'])
if self.protocol_version != server_version: if self.protocol_version != server_version:
raise ValueError("I can't handle protocol version {}!".format(self.protocol_version)) raise ValueError(f"I can't handle protocol version {self.protocol_version}!")
self.received_handshake_response = True self.received_handshake_response = True
return defer.succeed(True) return defer.succeed(True)
@ -141,7 +141,7 @@ class BlobReflectorClient(Protocol):
self.read_handle = read_handle self.read_handle = read_handle
return None return None
raise ValueError( raise ValueError(
"Couldn't open that blob for some reason. blob_hash: {}".format(blob.blob_hash)) f"Couldn't open that blob for some reason. blob_hash: {blob.blob_hash}")
def send_blob_info(self): def send_blob_info(self):
log.debug("Send blob info for %s", self.next_blob_to_send.blob_hash) log.debug("Send blob info for %s", self.next_blob_to_send.blob_hash)

View file

@ -195,7 +195,7 @@ class EncryptedFileReflectorClient(Protocol):
raise ValueError("Need protocol version number!") raise ValueError("Need protocol version number!")
self.server_version = int(response_dict['version']) self.server_version = int(response_dict['version'])
if self.server_version not in [REFLECTOR_V1, REFLECTOR_V2]: if self.server_version not in [REFLECTOR_V1, REFLECTOR_V2]:
raise ValueError("I can't handle protocol version {}!".format(self.server_version)) raise ValueError(f"I can't handle protocol version {self.server_version}!")
self.received_server_version = True self.received_server_version = True
return defer.succeed(True) return defer.succeed(True)
@ -258,7 +258,7 @@ class EncryptedFileReflectorClient(Protocol):
self.read_handle = read_handle self.read_handle = read_handle
return defer.succeed(None) return defer.succeed(None)
return defer.fail(ValueError( return defer.fail(ValueError(
"Couldn't open that blob for some reason. blob_hash: {}".format(blob.blob_hash))) f"Couldn't open that blob for some reason. blob_hash: {blob.blob_hash}"))
def send_blob_info(self): def send_blob_info(self):
assert self.next_blob_to_send is not None, "need to have a next blob to send at this point" assert self.next_blob_to_send is not None, "need to have a next blob to send at this point"

View file

@ -52,9 +52,9 @@ def verify_proof(proof, rootHash, name):
if i == 0 and 'txhash' in proof and 'nOut' in proof and 'last takeover height' in proof: if i == 0 and 'txhash' in proof and 'nOut' in proof and 'last takeover height' in proof:
if len(proof['txhash']) != 64: if len(proof['txhash']) != 64:
raise InvalidProofError("txhash was invalid: {}".format(proof['txhash'])) raise InvalidProofError("txhash was invalid: {}".format(proof['txhash']))
if not isinstance(proof['nOut'], six.integer_types): if not isinstance(proof['nOut'], (int,)):
raise InvalidProofError("nOut was invalid: {}".format(proof['nOut'])) raise InvalidProofError("nOut was invalid: {}".format(proof['nOut']))
if not isinstance(proof['last takeover height'], six.integer_types): if not isinstance(proof['last takeover height'], (int,)):
raise InvalidProofError( raise InvalidProofError(
'last takeover height was invalid: {}'.format(proof['last takeover height'])) 'last takeover height was invalid: {}'.format(proof['last takeover height']))
to_hash += get_hash_for_outpoint( to_hash += get_hash_for_outpoint(

View file

@ -148,7 +148,7 @@ class LbryWalletManager(BaseWalletManager):
while os.path.isfile(backup_path_template % i): while os.path.isfile(backup_path_template % i):
i += 1 i += 1
os.rename(path, backup_path_template % i) os.rename(path, backup_path_template % i)
temp_path = "%s.tmp.%s" % (path, os.getpid()) temp_path = "{}.tmp.{}".format(path, os.getpid())
with open(temp_path, "w") as f: with open(temp_path, "w") as f:
f.write(migrated_json) f.write(migrated_json)
f.flush() f.flush()
@ -241,7 +241,7 @@ class LbryWalletManager(BaseWalletManager):
account = account or self.default_account account = account or self.default_account
claims = await account.ledger.db.get_utxos(claim_id=claim_id) claims = await account.ledger.db.get_utxos(claim_id=claim_id)
if not claims: if not claims:
raise NameError("Claim not found: {}".format(claim_id)) raise NameError(f"Claim not found: {claim_id}")
tx = await Transaction.update( tx = await Transaction.update(
claims[0], ClaimDict.deserialize(claims[0].script.value['claim']), amount, claims[0], ClaimDict.deserialize(claims[0].script.value['claim']), amount,
destination_address.encode(), [account], account destination_address.encode(), [account], account
@ -359,7 +359,7 @@ class LbryWalletManager(BaseWalletManager):
existing_claims[0], claim, amount, claim_address, [account], account existing_claims[0], claim, amount, claim_address, [account], account
) )
else: else:
raise NameError("More than one other claim exists with the name '{}'.".format(name)) raise NameError(f"More than one other claim exists with the name '{name}'.")
await account.ledger.broadcast(tx) await account.ledger.broadcast(tx)
await self.old_db.save_claims([self._old_get_temp_claim_info( await self.old_db.save_claims([self._old_get_temp_claim_info(
tx, tx.outputs[0], claim_address, claim_dict, name, amount tx, tx.outputs[0], claim_address, claim_dict, name, amount
@ -480,7 +480,7 @@ class LBRYcrdAddressRequester:
def _handle_address_response(self, response_dict, peer, request, protocol): def _handle_address_response(self, response_dict, peer, request, protocol):
if request.response_identifier not in response_dict: if request.response_identifier not in response_dict:
raise ValueError( raise ValueError(
"Expected {} in response but did not get it".format(request.response_identifier)) f"Expected {request.response_identifier} in response but did not get it")
assert protocol in self._protocols, "Responding protocol is not in our list of protocols" assert protocol in self._protocols, "Responding protocol is not in our list of protocols"
address = response_dict[request.response_identifier] address = response_dict[request.response_identifier]
self.wallet.update_peer_address(peer, address) self.wallet.update_peer_address(peer, address)

View file

@ -304,13 +304,13 @@ def format_amount_value(obj):
def _get_permanent_url(claim_result): def _get_permanent_url(claim_result):
if claim_result.get('has_signature') and claim_result.get('channel_name'): if claim_result.get('has_signature') and claim_result.get('channel_name'):
return "{0}#{1}/{2}".format( return "{}#{}/{}".format(
claim_result['channel_name'], claim_result['channel_name'],
claim_result['value']['publisherSignature']['certificateId'], claim_result['value']['publisherSignature']['certificateId'],
claim_result['name'] claim_result['name']
) )
else: else:
return "{0}#{1}".format( return "{}#{}".format(
claim_result['name'], claim_result['name'],
claim_result['claim_id'] claim_result['claim_id']
) )
@ -461,7 +461,7 @@ def _handle_claim_result(results):
# case where there is no 'certificate', 'value', or 'claim' key # case where there is no 'certificate', 'value', or 'claim' key
elif 'certificate' not in results: elif 'certificate' not in results:
msg = 'result in unexpected format:{}'.format(results) msg = f'result in unexpected format:{results}'
assert False, msg assert False, msg
return results return results

View file

@ -72,12 +72,12 @@ class Output(BaseOutput):
def permanent_url(self) -> str: def permanent_url(self) -> str:
if self.script.is_claim_involved: if self.script.is_claim_involved:
if self.channel is not None: if self.channel is not None:
return "{0}#{1}/{2}".format( return "{}#{}/{}".format(
self.channel.claim_name, self.channel.claim_name,
self.channel.claim_id, self.channel.claim_id,
self.claim_name self.claim_name
) )
return "{}#{}".format(self.claim_name, self.claim_id) return f"{self.claim_name}#{self.claim_id}"
raise ValueError('No claim associated.') raise ValueError('No claim associated.')
@property @property

View file

@ -18,7 +18,7 @@ def get_api(obj):
try: try:
description, usage, options, returns = SECTIONS.search(docstr).groups() description, usage, options, returns = SECTIONS.search(docstr).groups()
except: except:
raise ValueError("Doc string format error for {}.".format(obj.__name__)) raise ValueError(f"Doc string format error for {obj.__name__}.")
required = re.findall(REQUIRED_OPTIONS, usage) required = re.findall(REQUIRED_OPTIONS, usage)

View file

@ -98,7 +98,7 @@ class ThePublisherOfThings:
for block in range(self.blocks): for block in range(self.blocks):
for txn in range(self.txns_per_block): for txn in range(self.txns_per_block):
name = 'block{}txn{}'.format(block, txn) name = f'block{block}txn{txn}'
self.profiler.start('total') self.profiler.start('total')
yield self.service.lbry.daemon.jsonrpc_publish( yield self.service.lbry.daemon.jsonrpc_publish(
name=name, bid=self.random.randrange(1, 5)/1000.0, name=name, bid=self.random.randrange(1, 5)/1000.0,
@ -124,9 +124,9 @@ def generate_publishes(_):
yield pub.start() yield pub.start()
yield pub.generate_publishes() yield pub.generate_publishes()
yield pub.stop() yield pub.stop()
print('lbrycrd: {}'.format(pub.service.lbrycrd.data_path)) print(f'lbrycrd: {pub.service.lbrycrd.data_path}')
print('lbrynet: {}'.format(pub.service.lbry.data_path)) print(f'lbrynet: {pub.service.lbry.data_path}')
print('lbryumserver: {}'.format(pub.service.lbryumserver.data_path)) print(f'lbryumserver: {pub.service.lbryumserver.data_path}')
if __name__ == "__main__": if __name__ == "__main__":

View file

@ -45,7 +45,7 @@ def resolve(name, timeout=(1, 3, 11, 45)):
return defer.succeed(MOCK_DHT_SEED_DNS[name]) return defer.succeed(MOCK_DHT_SEED_DNS[name])
class MockUDPTransport(object): class MockUDPTransport:
def __init__(self, address, port, max_packet_size, protocol): def __init__(self, address, port, max_packet_size, protocol):
self.address = address self.address = address
self.port = port self.port = port
@ -61,7 +61,7 @@ class MockUDPTransport(object):
pass pass
class MockUDPPort(object): class MockUDPPort:
def __init__(self, protocol, remover): def __init__(self, protocol, remover):
self.protocol = protocol self.protocol = protocol
self._remover = remover self._remover = remover
@ -75,7 +75,7 @@ class MockUDPPort(object):
return result return result
class MockNetwork(object): class MockNetwork:
peers = {} # (interface, port): (protocol, max_packet_size) peers = {} # (interface, port): (protocol, max_packet_size)
@classmethod @classmethod

View file

@ -11,7 +11,7 @@ class TestReJoin(TestKademliaBase):
@defer.inlineCallbacks @defer.inlineCallbacks
def setUp(self): def setUp(self):
yield super(TestReJoin, self).setUp() yield super().setUp()
self.removed_node = self.nodes[20] self.removed_node = self.nodes[20]
self.nodes.remove(self.removed_node) self.nodes.remove(self.removed_node)
yield self.run_reactor(1, [self.removed_node.stop()]) yield self.run_reactor(1, [self.removed_node.stop()])

View file

@ -42,7 +42,7 @@ def init_conf_windows(settings={}):
conf.settings.update(settings) conf.settings.update(settings)
class LbryUploader(object): class LbryUploader:
def __init__(self, file_size, ul_rate_limit=None): def __init__(self, file_size, ul_rate_limit=None):
self.file_size = file_size self.file_size = file_size
self.ul_rate_limit = ul_rate_limit self.ul_rate_limit = ul_rate_limit

View file

@ -25,7 +25,7 @@ def decode_rsa_key(pem_key):
return serialization.load_der_public_key(decoded, default_backend()) return serialization.load_der_public_key(decoded, default_backend())
class FakeLBRYFile(object): class FakeLBRYFile:
def __init__(self, blob_manager, stream_info_manager, stream_hash, uri="fake_uri"): def __init__(self, blob_manager, stream_info_manager, stream_hash, uri="fake_uri"):
self.blob_manager = blob_manager self.blob_manager = blob_manager
self.stream_info_manager = stream_info_manager self.stream_info_manager = stream_info_manager
@ -44,7 +44,7 @@ class Node(RealNode):
return self.joinNetwork(known_node_addresses) return self.joinNetwork(known_node_addresses)
class FakeNetwork(object): class FakeNetwork:
@staticmethod @staticmethod
def get_local_height(): def get_local_height():
return 1 return 1
@ -86,7 +86,7 @@ class ExchangeRateManager(ERM.ExchangeRateManager):
feed.market, rates[feed.market]['spot'], rates[feed.market]['ts']) feed.market, rates[feed.market]['spot'], rates[feed.market]['ts'])
class PointTraderKeyExchanger(object): class PointTraderKeyExchanger:
def __init__(self, wallet): def __init__(self, wallet):
self.wallet = wallet self.wallet = wallet
@ -117,7 +117,7 @@ class PointTraderKeyExchanger(object):
return err return err
class PointTraderKeyQueryHandlerFactory(object): class PointTraderKeyQueryHandlerFactory:
def __init__(self, wallet): def __init__(self, wallet):
self.wallet = wallet self.wallet = wallet
@ -134,7 +134,7 @@ class PointTraderKeyQueryHandlerFactory(object):
"point trader testing network") "point trader testing network")
class PointTraderKeyQueryHandler(object): class PointTraderKeyQueryHandler:
def __init__(self, wallet): def __init__(self, wallet):
self.wallet = wallet self.wallet = wallet
@ -152,7 +152,7 @@ class PointTraderKeyQueryHandler(object):
try: try:
decode_rsa_key(new_encoded_pub_key) decode_rsa_key(new_encoded_pub_key)
except (ValueError, TypeError, IndexError): except (ValueError, TypeError, IndexError):
value_error = ValueError("Client sent an invalid public key: {}".format(new_encoded_pub_key)) value_error = ValueError(f"Client sent an invalid public key: {new_encoded_pub_key}")
return defer.fail(Failure(value_error)) return defer.fail(Failure(value_error))
self.public_key = new_encoded_pub_key self.public_key = new_encoded_pub_key
self.wallet.set_public_key_for_peer(self.peer, self.public_key) self.wallet.set_public_key_for_peer(self.peer, self.public_key)
@ -164,7 +164,7 @@ class PointTraderKeyQueryHandler(object):
return defer.succeed({}) return defer.succeed({})
class Wallet(object): class Wallet:
def __init__(self): def __init__(self):
self.private_key = rsa.generate_private_key(public_exponent=PUBLIC_EXPONENT, self.private_key = rsa.generate_private_key(public_exponent=PUBLIC_EXPONENT,
key_size=1024, backend=default_backend()) key_size=1024, backend=default_backend())
@ -226,7 +226,7 @@ class Wallet(object):
return "aa04a949348f9f094d503e5816f0cfb57ee68a22f6d08d149217d071243e0378" return "aa04a949348f9f094d503e5816f0cfb57ee68a22f6d08d149217d071243e0378"
class PeerFinder(object): class PeerFinder:
def __init__(self, start_port, peer_manager, num_peers): def __init__(self, start_port, peer_manager, num_peers):
self.start_port = start_port self.start_port = start_port
self.peer_manager = peer_manager self.peer_manager = peer_manager
@ -247,7 +247,7 @@ class PeerFinder(object):
pass pass
class Announcer(object): class Announcer:
def __init__(self, *args): def __init__(self, *args):
pass pass
@ -366,7 +366,7 @@ class BlobAvailabilityTracker(BlobAvailability.BlobAvailabilityTracker):
# The components below viz. FakeWallet, FakeSession, FakeFileManager are just for testing Component Manager's # The components below viz. FakeWallet, FakeSession, FakeFileManager are just for testing Component Manager's
# startup and stop # startup and stop
class FakeComponent(object): class FakeComponent:
depends_on = [] depends_on = []
component_name = None component_name = None

View file

@ -70,7 +70,7 @@ class TestComponentManagerOverrides(unittest.TestCase):
mocks.mock_conf_settings(self) mocks.mock_conf_settings(self)
def test_init_with_overrides(self): def test_init_with_overrides(self):
class FakeWallet(object): class FakeWallet:
component_name = "wallet" component_name = "wallet"
depends_on = [] depends_on = []
@ -88,7 +88,7 @@ class TestComponentManagerOverrides(unittest.TestCase):
self.assertNotIsInstance(fake_wallet, Components.WalletComponent) self.assertNotIsInstance(fake_wallet, Components.WalletComponent)
def test_init_with_wrong_overrides(self): def test_init_with_wrong_overrides(self):
class FakeRandomComponent(object): class FakeRandomComponent:
component_name = "someComponent" component_name = "someComponent"
depends_on = [] depends_on = []

View file

@ -17,12 +17,12 @@ PEER_PORT = 5551
LOCAL_HOST = '127.0.0.1' LOCAL_HOST = '127.0.0.1'
class MocDownloader(object): class MocDownloader:
def insufficient_funds(self): def insufficient_funds(self):
pass pass
class MocRequestCreator(object): class MocRequestCreator:
def __init__(self, peers_to_return, peers_to_return_head_blob=None): def __init__(self, peers_to_return, peers_to_return_head_blob=None):
self.peers_to_return = peers_to_return self.peers_to_return = peers_to_return
@ -55,7 +55,7 @@ class MocRequestCreator(object):
return self.peers_to_return_head_blob return self.peers_to_return_head_blob
class MocFunctionalQueryHandler(object): class MocFunctionalQueryHandler:
def __init__(self, clock, is_good=True, is_delayed=False): def __init__(self, clock, is_good=True, is_delayed=False):
self.query_identifiers = ['moc_request'] self.query_identifiers = ['moc_request']
@ -81,7 +81,7 @@ class MocFunctionalQueryHandler(object):
return defer.succeed({}) return defer.succeed({})
class MocQueryHandlerFactory(object): class MocQueryHandlerFactory:
# is is_good, the query handler works as expectd, # is is_good, the query handler works as expectd,
# is is_delayed, the query handler will delay its resposne # is is_delayed, the query handler will delay its resposne
def __init__(self, clock, is_good=True, is_delayed=False): def __init__(self, clock, is_good=True, is_delayed=False):

View file

@ -13,7 +13,7 @@ import os
AES_BLOCK_SIZE_BYTES = int(AES.block_size / 8) AES_BLOCK_SIZE_BYTES = int(AES.block_size / 8)
class MocBlob(object): class MocBlob:
def __init__(self): def __init__(self):
self.data = b'' self.data = b''

View file

@ -65,7 +65,7 @@ fake_claim_info = {
} }
class FakeAnnouncer(object): class FakeAnnouncer:
def __init__(self): def __init__(self):
self._queue_size = 0 self._queue_size = 0
@ -73,7 +73,7 @@ class FakeAnnouncer(object):
return self._queue_size return self._queue_size
class MocSession(object): class MocSession:
def __init__(self, storage): def __init__(self, storage):
self.storage = storage self.storage = storage
@ -167,7 +167,7 @@ class SupportsStorageTests(StorageTest):
random_supports = [{ random_supports = [{
"txid": random_lbry_hash(), "txid": random_lbry_hash(),
"nout": i, "nout": i,
"address": "addr{}".format(i), "address": f"addr{i}",
"amount": i "amount": i
} for i in range(20)] } for i in range(20)]
expected_supports = {} expected_supports = {}

View file

@ -7,7 +7,7 @@ from tests.util import random_lbry_hash
from tests.mocks import mock_conf_settings from tests.mocks import mock_conf_settings
class MocDHTNode(object): class MocDHTNode:
def __init__(self): def __init__(self):
self.blobs_announced = 0 self.blobs_announced = 0
self.clock = task.Clock() self.clock = task.Clock()
@ -20,7 +20,7 @@ class MocDHTNode(object):
return d return d
class MocStorage(object): class MocStorage:
def __init__(self, blobs_to_announce): def __init__(self, blobs_to_announce):
self.blobs_to_announce = blobs_to_announce self.blobs_to_announce = blobs_to_announce
self.announced = False self.announced = False

View file

@ -21,7 +21,7 @@ class NodeIDTest(unittest.TestCase):
previous_ids = [] previous_ids = []
for i in range(100): for i in range(100):
new_id = self.node._generateID() new_id = self.node._generateID()
self.assertNotIn(new_id, previous_ids, 'id at index {} not unique'.format(i)) self.assertNotIn(new_id, previous_ids, f'id at index {i} not unique')
self.assertEqual(len(new_id), 48, 'id at index {} wrong length: {}'.format(i, len(new_id))) self.assertEqual(len(new_id), 48, 'id at index {} wrong length: {}'.format(i, len(new_id)))
previous_ids.append(new_id) previous_ids.append(new_id)

View file

@ -9,7 +9,7 @@ from lbrynet.dht.distance import Distance
from lbrynet.core.utils import generate_id from lbrynet.core.utils import generate_id
class FakeRPCProtocol(object): class FakeRPCProtocol:
""" Fake RPC protocol; allows lbrynet.dht.contact.Contact objects to "send" RPCs """ """ Fake RPC protocol; allows lbrynet.dht.contact.Contact objects to "send" RPCs """
def sendRPC(self, *args, **kwargs): def sendRPC(self, *args, **kwargs):
return defer.succeed(None) return defer.succeed(None)

View file

@ -108,6 +108,6 @@ class CreateEncryptedFileTest(unittest.TestCase):
def test_can_create_file_with_unicode_filename(self): def test_can_create_file_with_unicode_filename(self):
expected_stream_hash = ('d1da4258f3ce12edb91d7e8e160d091d3ab1432c2e55a6352dce0' expected_stream_hash = ('d1da4258f3ce12edb91d7e8e160d091d3ab1432c2e55a6352dce0'
'2fd5adb86fe144e93e110075b5865fff8617776c6c0') '2fd5adb86fe144e93e110075b5865fff8617776c6c0')
filename = u'☃.file' filename = '☃.file'
lbry_file = yield self.create_file(filename) lbry_file = yield self.create_file(filename)
self.assertEqual(expected_stream_hash, lbry_file.stream_hash) self.assertEqual(expected_stream_hash, lbry_file.stream_hash)

View file

@ -20,7 +20,7 @@ from lbrynet.wallet.manager import LbryWalletManager
from tests.mocks import mock_conf_settings from tests.mocks import mock_conf_settings
class MocDownloader(object): class MocDownloader:
def __init__(self): def __init__(self):
self.finish_deferred = defer.Deferred(None) self.finish_deferred = defer.Deferred(None)
self.stop_called = False self.stop_called = False

View file

@ -10,7 +10,7 @@ class DaemonDocsTests(unittest.TestCase):
try: try:
docopt.docopt(fn.__doc__, ()) docopt.docopt(fn.__doc__, ())
except docopt.DocoptLanguageError as err: except docopt.DocoptLanguageError as err:
failures.append("invalid docstring for %s, %s" % (name, err.message)) failures.append(f"invalid docstring for {name}, {err.message}")
except docopt.DocoptExit: except docopt.DocoptExit:
pass pass
if failures: if failures: