pylint (test suite) - various cleanups

This commit is contained in:
The MMGen Project 2023-10-11 12:58:53 +00:00
commit 2076c0308b
Signed by: mmgen
GPG key ID: 3F8B1861E32B7DA2
22 changed files with 46 additions and 47 deletions

View file

@ -46,7 +46,7 @@ from mmgen.util import make_timestr
async def get_rpc(cfg):
try:
return await rpc_init( cfg, ignore_wallet=True )
except SocketError as e:
except SocketError:
return False
async def main(coins):

View file

@ -26,5 +26,7 @@ start = (1,0)[bool(cfg.include_first_line)]
a = make_chksum_6(' '.join(lines[start:]).encode())
if start == 1:
b = lines[0]
msg(("Checksum in file ({}) doesn't match computed value!".format(b),'Checksum in file OK')[a==b])
msg(
'Checksum in file OK' if a == b else
f"Checksum in file ({b}) doesn't match computed value!")
Msg(a)

View file

@ -15,8 +15,8 @@ sys.path = [repo_root] + sys.path
opts_data = {
'text': {
'desc': "Convert MMGen transaction file from v2 format to v3 format",
'usage': "<tx file>",
'desc': "Convert an MMGen transaction file from v2 format to v3 format",
'usage': "<TX file>",
'options': """
-h, --help Print this help message
-d, --outdir=d Output files to directory 'd' instead of working dir

View file

@ -198,9 +198,9 @@ class GenToolPycoin(GenTool):
super().__init__(*args,**kwargs)
try:
from pycoin.networks.registry import network_for_netcode
except:
except Exception as e:
raise ImportError(
'Unable to import pycoin.networks.registry. Is pycoin installed on your system?')
'Unable to import pycoin.networks.registry. Is pycoin installed on your system?') from e
self.nfnc = network_for_netcode
def run(self,sec,vcoin):
@ -232,9 +232,9 @@ class GenToolMonero_python(GenTool):
load_cryptodomex()
try:
from monero.seed import Seed
except:
except Exception as e:
raise ImportError(
'Unable to import monero-python. Is monero-python installed on your system?')
'Unable to import monero-python. Is monero-python installed on your system?') from e
self.Seed = Seed
def run(self,sec,vcoin):

View file

@ -206,13 +206,13 @@ class MMGenPexpect:
try:
ret = (self.p.expect_exact,self.p.expect)[bool(regex)](s) if s else 0
except pexpect.TIMEOUT:
except pexpect.TIMEOUT as e:
if cfg.debug_pexpect:
raise
m1 = f'\nERROR. Expect {s!r} timed out. Exiting\n'
m2 = f'before: [{self.p.before}]\n'
m3 = f'sent value: [{self.sent_value}]' if self.sent_value is not None else ''
raise pexpect.TIMEOUT(m1+m2+m3)
raise pexpect.TIMEOUT(m1+m2+m3) from e
if cfg.debug_pexpect:
debug_pexpect_msg(self.p)

View file

@ -92,8 +92,8 @@ def test_attr_perm(obj,attrname,perm_name,perm_value,dobj,attrval_type):
elif perm_name == 'reassign_ok':
try:
so = sample_objs[attrval_type.__name__]
except:
raise SampleObjError(f'unable to find sample object of type {attrval_type.__name__!r}')
except Exception as e:
raise SampleObjError(f'unable to find sample object of type {attrval_type.__name__!r}') from e
# ListItemAttr allows setting an attribute if its value is None
if type(dobj) is ListItemAttr and getattr(obj,attrname) is None:
setattr(obj,attrname,so)

View file

@ -114,7 +114,7 @@ def run_test(mod,test,arg,input_data,arg1,exc_name):
else:
ret = cls(*args,**kwargs)
bad_ret = list() if issubclass(cls,list) else None
bad_ret = [] if issubclass(cls,list) else None
if isinstance(ret_chk,str):
ret_chk = ret_chk.encode()

View file

@ -1051,5 +1051,3 @@ except Exception:
if os.getenv('MMGEN_EXEC_WRAPPER') or not os.getenv('MMGEN_IGNORE_TEST_PY_EXCEPTION'):
raise
die(1,red('Test script exited with error'))
except:
raise

View file

@ -68,8 +68,8 @@ def stealth_mnemonic_entry(t,mne,mn,entry_mode,pad_entry=False):
ret = t.expect((p_ok.format(wnum),p_err.format(wnum-1)))
if ret == 0:
wnum += 1
for j in range(len(w)):
t.send(w[j])
for char in w:
t.send(char)
time.sleep(0.005)
def user_dieroll_entry(t,data):

View file

@ -158,7 +158,7 @@ class TestSuiteCfgFile(TestSuiteBase):
write_to_file(self.path('usr'),'\n'.join(d) + '\n')
return self.old_sample_common(
old_set = True,
pexpect_spawn = False if gc.platform == 'win' else True )
pexpect_spawn = not gc.platform == 'win')
def _autoset_opts(self,args=[],text='rpc_backend aiohttp\n'):
write_to_file( self.path('usr'), text )

View file

@ -1373,7 +1373,7 @@ class TestSuiteEthdev(TestSuiteBase,TestSuiteShared):
def edit_comment1(self):
return self.edit_comment(out_num=del_addrs[0],comment_text=tw_comment_zh[:3])
def edit_comment2(self):
spawn = False if gc.platform == 'win' else True
spawn = not gc.platform == 'win'
return self.edit_comment(
out_num = del_addrs[0],
comment_text = tw_comment_zh[3:],

View file

@ -240,7 +240,7 @@ class TestSuiteInput(TestSuiteBase):
def _input_func(self,func_name,arg_dfls,func_args,text,expect,term):
if term and gc.platform == 'win':
return ('skip_warn','pexpect_spawn not supported on Windows platform')
func_args = {k:v for k,v in zip(arg_dfls.keys(),func_args)}
func_args = dict(zip(arg_dfls.keys(),func_args))
t = self.spawn(
'test/misc/input_func.py',
[func_name,repr(func_args)],

View file

@ -991,5 +991,5 @@ class TestSuiteMain(TestSuiteBase,TestSuiteShared):
add_args = ['--vsize-adj=1.08'],
tweaks = ['confirm_non_mmgen'] )
def txsign6(self,txf,wf):
return self.txsign5(txf,wf,bad_vsize=False,add_args=['--vsize-adj=1.08'])
def txsign6(self,wf,txf):
return self.txsign5(wf,txf,bad_vsize=False,add_args=['--vsize-adj=1.08'])

View file

@ -366,7 +366,7 @@ class TestSuiteRef3Addr(TestSuiteRef3Seed):
('ref_bip39_12_passwdgen', ([],'new refwallet passwd file chksum (BIP39, 12 words)')),
('ref_bip39_18_passwdgen', ([],'new refwallet passwd file chksum (BIP39, up to 18 words)')),
('ref_bip39_24_passwdgen', ([],'new refwallet passwd file chksum (BIP39, up to 24 words)')),
('ref_xmrseed_25_passwdgen', ([],'new refwallet passwd file chksum (Monero new-style mnemonic, 25 words)')),
('ref_xmrseed_25_passwdgen', ([],'new refwallet passwd file chksum (Monero 25-word mnemonic)')),
('ref_hex2bip39_24_passwdgen',([],'new refwallet passwd file chksum (hex-to-BIP39, up to 24 words)')),
)

View file

@ -850,7 +850,7 @@ class TestSuiteRegtest(TestSuiteBase,TestSuiteShared):
t.expect('draw:\b','q',regex=True)
else:
txnum,idx = (8,1) if self.proto.coin == 'BCH' else (9,3)
t.expect(f'\s{txnum}\).*Inputs:.*:L:{idx}.*Outputs \(3\):.*:C:2.*\s10\)','q',regex=True)
t.expect(rf'\s{txnum}\).*Inputs:.*:L:{idx}.*Outputs \(3\):.*:C:2.*\s10\)','q',regex=True)
return t
def bob_getbalance(self,bals,confs=1):
@ -1100,7 +1100,7 @@ class TestSuiteRegtest(TestSuiteBase,TestSuiteShared):
new_txid = self.read_from_tmpfile('rbf_txid2').strip()
return self.bob_rbf_status(rtFee[1],
'Replacement transaction has 1 confirmation',
f'Replacing transactions:\s+{new_txid}' )
rf'Replacing transactions:\s+{new_txid}' )
def bob_rbf_status5(self):
if not self.proto.cap('rbf'):
@ -1113,7 +1113,7 @@ class TestSuiteRegtest(TestSuiteBase,TestSuiteShared):
new_txid = self.read_from_tmpfile('rbf_txid2').strip()
return self.bob_rbf_status(rtFee[1],
'Replacement transaction has 2 confirmations',
f'Replacing transactions:\s+{new_txid}' )
rf'Replacing transactions:\s+{new_txid}' )
def _gen_pairs(self,n):
from mmgen.tool.api import tool_api
@ -1606,10 +1606,10 @@ class TestSuiteRegtest(TestSuiteBase,TestSuiteShared):
def alice_txcreate_info(self,pexpect_spawn=False):
t = self.spawn('mmgen-txcreate',['--alice','-Bi'],pexpect_spawn=pexpect_spawn)
pats = (
( '\d+', 'w'),
( '\d+', 'D'),
( '\d+', 'D'),
( '\d+', 'D'),
( r'\d+', 'w'),
( r'\d+', 'D'),
( r'\d+', 'D'),
( r'\d+', 'D'),
( pat_date, 'q'),
)
for d,s in pats:

View file

@ -226,7 +226,7 @@ class TestSuiteWalletConv(TestSuiteBase,TestSuiteShared):
t.passphrase_new('new '+wcls.desc,self.wpasswd)
t.usr_rand(self.usr_rand_chars)
if wcls.type.startswith('incog'):
for _ in (1,2,3):
for _ in range(3):
t.expect('Encrypting random data from your operating system with ephemeral key')
if wcls.type == 'incog_hidden':
t.hincog_create(hincog_bytes)

View file

@ -168,13 +168,13 @@ class TestSuiteXMRAutosign(TestSuiteXMRWallet,TestSuiteAutosignBase):
return self._new_addr_alice(
'2:1',
'continue',
fr'Account index:\s+1\s+Creating new address' )
r'Account index:\s+1\s+Creating new address' )
def new_address_alice_label(self):
return self._new_addr_alice(
'2:1,Alice’s new address',
'stop',
fr'Account index:\s+1\s+Creating new address.*Alice’s new address' )
r'Account index:\s+1\s+Creating new address.*Alice’s new address' )
def dump_tmp_wallets(self):
return self._dump_wallets(autosign=False)

View file

@ -423,13 +423,13 @@ class TestSuiteXMRWallet(TestSuiteBase):
return self.new_addr_alice(
'4:2',
'continue',
fr'Account index:\s+2\s+Creating new address' )
r'Account index:\s+2\s+Creating new address' )
def new_address_alice_label(self):
return self.new_addr_alice(
'4:2,Alice’s new address',
'stop',
fr'Account index:\s+2\s+Creating new address.*Alice’s new address' )
r'Account index:\s+2\s+Creating new address.*Alice’s new address' )
async def mine_initial_coins(self):
self.spawn('', msg_only=True, extra_desc='(opening wallet)')
@ -510,7 +510,7 @@ class TestSuiteXMRWallet(TestSuiteBase):
t.expect('Wallet height: ')
res = strip_ansi_escapes(t.expect_getend('Balance: '))
if bal_chk_func:
m = re.match( '(\S+) Unlocked balance: (\S+)', res, re.DOTALL )
m = re.match( r'(\S+) Unlocked balance: (\S+)', res, re.DOTALL )
amts = [XMRAmt(amt) for amt in m.groups()]
assert bal_chk_func(n,*amts), f'balance check for wallet {n} failed!'
return t

View file

@ -305,9 +305,8 @@ class MMGenToolTestUtils:
return
if Return:
return ret
else:
if not hush:
ok()
elif not hush:
ok()
else:
die(4,f'Error for command {name!r}')

View file

@ -779,9 +779,10 @@ def fork_cmd(cmd_name,args,opts,stdin_input):
return cmd_out.strip()
async def call_method(cls,method,cmd_name,args,mmtype,stdin_input):
vmsg('{}: {}{}'.format(purple('Running'),
' '.join([cmd_name]+[repr(e) for e in args]),
' '+mmtype if mmtype else '' ))
vmsg('{a}: {b}{c}'.format(
a = purple('Running'),
b = ' '.join([cmd_name]+[repr(e) for e in args]),
c = ' '+mmtype if mmtype else '' ))
aargs,kwargs = main_tool.process_args(cmd_name,args,cls)
oq_save = bool(cfg.quiet)
if not cfg.verbose:

View file

@ -133,9 +133,8 @@ def run_test(network_ids,test_cf_auth=False,daemon_ids=None):
for network_id in network_ids:
proto = init_proto( cfg, network_id=network_id )
ids = (lambda x:
set(daemon_ids) & set(x) if daemon_ids else x
)(CoinDaemon.get_daemon_ids(cfg,proto.coin))
all_ids = CoinDaemon.get_daemon_ids(cfg,proto.coin)
ids = set(daemon_ids) & set(all_ids) if daemon_ids else all_ids
for daemon_id in ids:
do_test( CoinDaemon(cfg, proto=proto,test_suite=True,daemon_id=daemon_id) )

View file

@ -37,7 +37,7 @@ class unit_tests:
for name,sample in samples.items():
vmsg(cyan(f'Input: {sample}'))
for fmt,chk in list(chks.values())[0].items():
for fmt in list(chks.values())[0]:
spc = '\n' if fmt in ('col','list') else ' '
indent = ' + ' if fmt == 'col' else ''
res = fmt_list(sample,fmt=fmt,indent=indent) if fmt else fmt_list(sample,indent=indent)
@ -86,7 +86,7 @@ class unit_tests:
for name,sample in samples.items():
vmsg(cyan(f'Input: {sample}'))
for fmt,chk in list(chks.values())[0].items():
for fmt in list(chks.values())[0]:
res = fmt_dict(sample,fmt=fmt) if fmt else fmt_dict(sample)
vmsg(f' {str(fmt)+":":{col1_w}} {res}')
if name in chks: