Browse Source

pylint (test suite) - various cleanups

The MMGen Project 1 year ago
parent
commit
2076c0308b

+ 1 - 1
examples/coin-daemon-info.py

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

+ 3 - 1
scripts/compute-file-chksum.py

@@ -26,5 +26,7 @@ start = (1,0)[bool(cfg.include_first_line)]
 a = make_chksum_6(' '.join(lines[start:]).encode())
 a = make_chksum_6(' '.join(lines[start:]).encode())
 if start == 1:
 if start == 1:
 	b = lines[0]
 	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)
 Msg(a)

+ 2 - 2
scripts/tx-v2-to-v3.py

@@ -15,8 +15,8 @@ sys.path = [repo_root] + sys.path
 
 
 opts_data = {
 opts_data = {
 	'text': {
 	'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': """
 		'options': """
 -h, --help     Print this help message
 -h, --help     Print this help message
 -d, --outdir=d Output files to directory 'd' instead of working dir
 -d, --outdir=d Output files to directory 'd' instead of working dir

+ 4 - 4
test/gentest.py

@@ -198,9 +198,9 @@ class GenToolPycoin(GenTool):
 		super().__init__(*args,**kwargs)
 		super().__init__(*args,**kwargs)
 		try:
 		try:
 			from pycoin.networks.registry import network_for_netcode
 			from pycoin.networks.registry import network_for_netcode
-		except:
+		except Exception as e:
 			raise ImportError(
 			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
 		self.nfnc = network_for_netcode
 
 
 	def run(self,sec,vcoin):
 	def run(self,sec,vcoin):
@@ -232,9 +232,9 @@ class GenToolMonero_python(GenTool):
 		load_cryptodomex()
 		load_cryptodomex()
 		try:
 		try:
 			from monero.seed import Seed
 			from monero.seed import Seed
-		except:
+		except Exception as e:
 			raise ImportError(
 			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
 		self.Seed = Seed
 
 
 	def run(self,sec,vcoin):
 	def run(self,sec,vcoin):

+ 2 - 2
test/include/pexpect.py

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

+ 2 - 2
test/objattrtest.py

@@ -92,8 +92,8 @@ def test_attr_perm(obj,attrname,perm_name,perm_value,dobj,attrval_type):
 		elif perm_name == 'reassign_ok':
 		elif perm_name == 'reassign_ok':
 			try:
 			try:
 				so = sample_objs[attrval_type.__name__]
 				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
 			# ListItemAttr allows setting an attribute if its value is None
 			if type(dobj) is ListItemAttr and getattr(obj,attrname) is None:
 			if type(dobj) is ListItemAttr and getattr(obj,attrname) is None:
 				setattr(obj,attrname,so)
 				setattr(obj,attrname,so)

+ 1 - 1
test/objtest.py

@@ -114,7 +114,7 @@ def run_test(mod,test,arg,input_data,arg1,exc_name):
 		else:
 		else:
 			ret = cls(*args,**kwargs)
 			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):
 		if isinstance(ret_chk,str):
 			ret_chk = ret_chk.encode()
 			ret_chk = ret_chk.encode()

+ 0 - 2
test/test.py

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

+ 2 - 2
test/test_py_d/input.py

@@ -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)))
 		ret = t.expect((p_ok.format(wnum),p_err.format(wnum-1)))
 		if ret == 0:
 		if ret == 0:
 			wnum += 1
 			wnum += 1
-		for j in range(len(w)):
-			t.send(w[j])
+		for char in w:
+			t.send(char)
 			time.sleep(0.005)
 			time.sleep(0.005)
 
 
 def user_dieroll_entry(t,data):
 def user_dieroll_entry(t,data):

+ 1 - 1
test/test_py_d/ts_cfgfile.py

@@ -158,7 +158,7 @@ class TestSuiteCfgFile(TestSuiteBase):
 		write_to_file(self.path('usr'),'\n'.join(d) + '\n')
 		write_to_file(self.path('usr'),'\n'.join(d) + '\n')
 		return self.old_sample_common(
 		return self.old_sample_common(
 			old_set       = True,
 			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'):
 	def _autoset_opts(self,args=[],text='rpc_backend aiohttp\n'):
 		write_to_file( self.path('usr'), text )
 		write_to_file( self.path('usr'), text )

+ 1 - 1
test/test_py_d/ts_ethdev.py

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

+ 1 - 1
test/test_py_d/ts_input.py

@@ -240,7 +240,7 @@ class TestSuiteInput(TestSuiteBase):
 	def _input_func(self,func_name,arg_dfls,func_args,text,expect,term):
 	def _input_func(self,func_name,arg_dfls,func_args,text,expect,term):
 		if term and gc.platform == 'win':
 		if term and gc.platform == 'win':
 			return ('skip_warn','pexpect_spawn not supported on Windows platform')
 			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(
 		t = self.spawn(
 			'test/misc/input_func.py',
 			'test/misc/input_func.py',
 			[func_name,repr(func_args)],
 			[func_name,repr(func_args)],

+ 2 - 2
test/test_py_d/ts_main.py

@@ -991,5 +991,5 @@ class TestSuiteMain(TestSuiteBase,TestSuiteShared):
 			add_args                   = ['--vsize-adj=1.08'],
 			add_args                   = ['--vsize-adj=1.08'],
 			tweaks                     = ['confirm_non_mmgen'] )
 			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'])

+ 1 - 1
test/test_py_d/ts_ref_3seed.py

@@ -366,7 +366,7 @@ class TestSuiteRef3Addr(TestSuiteRef3Seed):
 		('ref_bip39_12_passwdgen',    ([],'new refwallet passwd file chksum (BIP39, 12 words)')),
 		('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_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_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)')),
 		('ref_hex2bip39_24_passwdgen',([],'new refwallet passwd file chksum (hex-to-BIP39, up to 24 words)')),
 	)
 	)
 
 

+ 7 - 7
test/test_py_d/ts_regtest.py

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

+ 1 - 1
test/test_py_d/ts_wallet.py

@@ -226,7 +226,7 @@ class TestSuiteWalletConv(TestSuiteBase,TestSuiteShared):
 			t.passphrase_new('new '+wcls.desc,self.wpasswd)
 			t.passphrase_new('new '+wcls.desc,self.wpasswd)
 			t.usr_rand(self.usr_rand_chars)
 			t.usr_rand(self.usr_rand_chars)
 		if wcls.type.startswith('incog'):
 		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')
 				t.expect('Encrypting random data from your operating system with ephemeral key')
 		if wcls.type == 'incog_hidden':
 		if wcls.type == 'incog_hidden':
 			t.hincog_create(hincog_bytes)
 			t.hincog_create(hincog_bytes)

+ 2 - 2
test/test_py_d/ts_xmr_autosign.py

@@ -168,13 +168,13 @@ class TestSuiteXMRAutosign(TestSuiteXMRWallet,TestSuiteAutosignBase):
 		return self._new_addr_alice(
 		return self._new_addr_alice(
 			'2:1',
 			'2:1',
 			'continue',
 			'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):
 	def new_address_alice_label(self):
 		return self._new_addr_alice(
 		return self._new_addr_alice(
 			'2:1,Alice’s new address',
 			'2:1,Alice’s new address',
 			'stop',
 			'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):
 	def dump_tmp_wallets(self):
 		return self._dump_wallets(autosign=False)
 		return self._dump_wallets(autosign=False)

+ 3 - 3
test/test_py_d/ts_xmrwallet.py

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

+ 2 - 3
test/tooltest.py

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

+ 4 - 3
test/tooltest2.py

@@ -779,9 +779,10 @@ def fork_cmd(cmd_name,args,opts,stdin_input):
 	return cmd_out.strip()
 	return cmd_out.strip()
 
 
 async def call_method(cls,method,cmd_name,args,mmtype,stdin_input):
 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)
 	aargs,kwargs = main_tool.process_args(cmd_name,args,cls)
 	oq_save = bool(cfg.quiet)
 	oq_save = bool(cfg.quiet)
 	if not cfg.verbose:
 	if not cfg.verbose:

+ 2 - 3
test/unit_tests_d/ut_rpc.py

@@ -133,9 +133,8 @@ def run_test(network_ids,test_cf_auth=False,daemon_ids=None):
 
 
 	for network_id in network_ids:
 	for network_id in network_ids:
 		proto = init_proto( cfg, network_id=network_id )
 		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:
 		for daemon_id in ids:
 			do_test( CoinDaemon(cfg, proto=proto,test_suite=True,daemon_id=daemon_id) )
 			do_test( CoinDaemon(cfg, proto=proto,test_suite=True,daemon_id=daemon_id) )
 
 

+ 2 - 2
test/unit_tests_d/ut_util.py

@@ -37,7 +37,7 @@ class unit_tests:
 
 
 		for name,sample in samples.items():
 		for name,sample in samples.items():
 			vmsg(cyan(f'Input: {sample}'))
 			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 ' '
 				spc = '\n' if fmt in ('col','list') else ' '
 				indent = '    + ' if fmt == 'col' else ''
 				indent = '    + ' if fmt == 'col' else ''
 				res = fmt_list(sample,fmt=fmt,indent=indent) if fmt else fmt_list(sample,indent=indent)
 				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():
 		for name,sample in samples.items():
 			vmsg(cyan(f'Input: {sample}'))
 			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)
 				res = fmt_dict(sample,fmt=fmt) if fmt else fmt_dict(sample)
 				vmsg(f'  {str(fmt)+":":{col1_w}} {res}')
 				vmsg(f'  {str(fmt)+":":{col1_w}} {res}')
 				if name in chks:
 				if name in chks: