mmgen-wallet/test/include/pexpect.py

254 lines
7.8 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
#
2024-10-18 10:32:06 +00:00
# MMGen Wallet, a terminal-based cryptocurrency wallet
2025-02-16 14:42:27 +00:00
# Copyright (C)2013-2025 The MMGen Project <mmgen@tuta.io>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
2022-11-14 09:54:07 +00:00
test.include.pexpect: pexpect implementation for MMGen test suites
"""
2024-10-18 10:32:12 +00:00
import sys, time
from mmgen.color import red, yellow, green, cyan
from mmgen.util import msg, msg_r, rmsg, die
from .common import cfg, vmsg, vmsg_r, getrandstr, strip_ansi_escapes
try:
import pexpect
from pexpect.popen_spawn import PopenSpawn
except ImportError as e:
2024-10-18 10:32:12 +00:00
die(2, red(f'Pexpect module is missing. Cannnot run test suite ({e!r})'))
def debug_pexpect_msg(p):
2024-10-18 10:32:12 +00:00
msg('\n{}{}{}'.format(red('BEFORE ['), p.before, red(']')))
msg('{}{}{}'.format(red('MATCH ['), p.after, red(']')))
NL = '\n'
class MMGenPexpect:
2023-05-06 15:14:06 +00:00
def __init__(
self,
args,
no_output = False,
2023-05-23 12:12:32 +00:00
spawn_env = None,
2023-05-06 15:14:06 +00:00
pexpect_spawn = False,
send_delay = None,
2023-05-06 15:14:06 +00:00
timeout = None,
2025-03-29 09:30:15 +00:00
silent = False,
2024-10-18 10:32:12 +00:00
direct_exec = False):
self.pexpect_spawn = pexpect_spawn
self.send_delay = send_delay
self.skip_ok = False
self.sent_value = None
self.spawn_env = spawn_env
2024-03-10 14:43:33 +00:00
self.exit_val = None
2023-05-06 15:14:06 +00:00
if direct_exec or cfg.direct_exec:
2024-10-18 10:32:12 +00:00
from subprocess import Popen, DEVNULL
2023-05-06 15:14:06 +00:00
redir = DEVNULL if (no_output or not cfg.exact_output) else None
2024-10-18 10:32:12 +00:00
self.ep = Popen([args[0]] + args[1:], stderr=redir, env=spawn_env)
else:
2024-10-18 10:32:12 +00:00
timeout = int(timeout or cfg.pexpect_timeout or 0) or (60, 5)[bool(cfg.debug_pexpect)]
if pexpect_spawn:
2024-10-18 10:32:12 +00:00
self.p = pexpect.spawn(args[0], args[1:], encoding='utf8', timeout=timeout, env=spawn_env)
else:
2024-10-18 10:32:12 +00:00
self.p = PopenSpawn(args, encoding='utf8', timeout=timeout, env=spawn_env)
2025-03-29 09:30:15 +00:00
if cfg.exact_output and not silent:
2021-10-03 17:40:02 +00:00
self.p.logfile = sys.stdout
def do_decrypt_ka_data(
self,
pw,
desc = 'key-address data',
check = True,
have_yes_opt = False):
2024-10-18 10:32:12 +00:00
self.passphrase(desc, pw)
if not have_yes_opt:
2024-10-18 10:32:12 +00:00
self.expect('Check key-to-address validity? (y/N): ', ('n', 'y')[check])
2024-10-18 10:32:12 +00:00
def view_tx(self, view):
self.expect(r'View.* transaction.*\? .*: ', view, regex=True)
2025-02-06 10:12:50 +00:00
if view not in 'vn\n':
2024-10-18 10:32:12 +00:00
self.expect('to continue: ', '\n')
2024-10-18 10:32:12 +00:00
def do_comment(self, add_comment, has_label=False):
p = ('Add a comment to transaction', 'Edit transaction comment')[has_label]
self.expect(f'{p}? (y/N): ', ('n', 'y')[bool(add_comment)])
if add_comment:
2024-10-18 10:32:12 +00:00
self.expect('Comment: ', add_comment+'\n')
def ok(self, exit_val=None):
if not self.pexpect_spawn:
2022-01-15 14:00:10 +00:00
self.p.sendeof()
self.p.read()
ret = self.p.wait()
2024-03-10 14:43:33 +00:00
if ret != (self.exit_val or exit_val or 0) and not cfg.coverage:
2024-10-18 10:32:12 +00:00
die('TestSuiteSpawnedScriptException', f'Spawned script exited with value {ret}')
if cfg.profile:
return
if not self.skip_ok:
2022-08-04 13:44:31 +00:00
m = 'OK\n' if ret == 0 else f'OK[{ret}]\n'
2024-10-18 10:32:12 +00:00
sys.stderr.write(green(m) if cfg.exact_output or cfg.verbose else ' '+m)
return self
def license(self):
if self.spawn_env.get('MMGEN_NO_LICENSE'):
return
2024-10-18 10:32:12 +00:00
self.expect("'w' for conditions and warranty info, or 'c' to continue: ", 'c')
2024-10-18 10:32:12 +00:00
def label(self, label='Test Label (UTF-8) α'):
self.expect('Enter a wallet label, or hit ENTER for no label: ', label+'\n')
2024-10-18 10:32:12 +00:00
def usr_rand(self, num_chars):
if cfg.usr_random:
self.interactive()
self.send('\n')
else:
2024-10-18 10:32:12 +00:00
rand_chars = list(getrandstr(num_chars, no_space=True))
vmsg_r('SEND ')
while rand_chars:
ch = rand_chars.pop(0)
msg_r(yellow(ch)+' ' if cfg.verbose else '+')
2024-10-18 10:32:12 +00:00
self.expect('left: ', ch, delay=0.005)
self.expect('ENTER to continue: ', '\n')
2024-10-18 10:32:12 +00:00
def passphrase_new(self, desc, passphrase):
self.expect(f'Enter passphrase for {desc}: ', passphrase+'\n')
self.expect('Repeat passphrase: ', passphrase+'\n')
2024-10-18 10:32:12 +00:00
def passphrase(self, desc, passphrase, pwtype=''):
if pwtype:
pwtype += ' '
2024-10-18 10:32:12 +00:00
self.expect(f'Enter {pwtype}passphrase for {desc}.*?: ', passphrase+'\n', regex=True)
2024-10-18 10:32:12 +00:00
def hash_preset(self, desc, preset=''):
self.expect(f'Enter hash preset for {desc}')
2024-10-18 10:32:12 +00:00
self.expect('or hit ENTER .*?:', str(preset)+'\n', regex=True)
2024-10-18 10:32:12 +00:00
def written_to_file(self, desc, overwrite_unlikely=False, query='Overwrite? '):
s1 = f'{desc} written to file '
s2 = query + "Type uppercase 'YES' to confirm: "
2024-10-18 10:32:12 +00:00
ret = self.expect(([s1, s2], s1)[overwrite_unlikely])
if ret == 1:
self.send('YES\n')
return self.expect_getend("Overwriting file '").rstrip("'")
2024-10-18 10:32:12 +00:00
self.expect(NL, nonl=True)
outfile = self.p.before.strip().strip("'")
if cfg.debug_pexpect:
rmsg(f'Outfile [{outfile}]')
2024-10-18 10:32:12 +00:00
vmsg('{} file: {}'.format(desc, cyan(outfile.replace('"', ""))))
return outfile
2024-10-18 10:32:12 +00:00
def hincog_create(self, hincog_bytes):
ret = self.expect(['Create? (Y/n): ', "'YES' to confirm: "])
2019-10-10 19:53:42 +00:00
if ret == 0:
self.send('\n')
2024-10-18 10:32:12 +00:00
self.expect('Enter file size: ', str(hincog_bytes)+'\n')
2019-10-10 19:53:42 +00:00
else:
self.send('YES\n')
return ret
def no_overwrite(self):
2024-10-18 10:32:12 +00:00
self.expect("Overwrite? Type uppercase 'YES' to confirm: ", '\n')
self.expect('Exiting at user request')
2024-10-18 10:32:12 +00:00
def expect_getend(self, s, regex=False):
self.expect(s, regex=regex, nonl=True)
if cfg.debug_pexpect:
debug_pexpect_msg(self.p)
# readline() of partial lines doesn't work with PopenSpawn, so do this instead:
2024-10-18 10:32:12 +00:00
self.expect(NL, nonl=True, silent=True)
if cfg.debug_pexpect:
debug_pexpect_msg(self.p)
2019-03-26 13:02:09 +00:00
end = self.p.before.rstrip()
if not cfg.debug:
vmsg(f' ==> {cyan(end)}')
return end
def interactive(self):
return self.p.interact() # interact() not available with popen_spawn
2024-10-18 10:32:12 +00:00
def kill(self, signal):
return self.p.kill(signal)
2024-10-18 10:32:12 +00:00
def match_expect_list(self, expect_list, greedy=False):
2022-08-04 13:44:31 +00:00
allrep = '.*' if greedy else '.*?'
expect = (
r'(\b|\s)' +
2024-10-18 10:32:12 +00:00
fr'\s{allrep}\s'.join(s.replace(r'.', r'\.').replace(' ', r'\s+') for s in expect_list) +
r'(\b|\s)')
2023-03-28 18:14:37 +00:00
import re
2024-10-18 10:32:12 +00:00
m = re.search(expect, self.read(strip_color=True), re.DOTALL)
2022-08-04 13:44:31 +00:00
assert m, f'No match found for regular expression {expect!r}'
return m
2024-10-18 10:32:12 +00:00
def expect(self, s, t='', delay=None, regex=False, nonl=False, silent=False):
if not silent:
if cfg.verbose:
2019-03-23 14:30:47 +00:00
msg_r('EXPECT ' + yellow(str(s)))
elif not cfg.exact_output:
msg_r('+')
try:
2024-10-18 10:32:12 +00:00
ret = (self.p.expect_exact, self.p.expect)[bool(regex)](s) if s else 0
2023-10-11 12:58:53 +00:00
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 ''
2023-10-11 12:58:53 +00:00
raise pexpect.TIMEOUT(m1+m2+m3) from e
if cfg.debug_pexpect:
debug_pexpect_msg(self.p)
2024-10-18 10:32:12 +00:00
if cfg.verbose and not isinstance(s, str):
msg_r(f' ==> {ret} ')
if ret == -1:
2024-10-18 10:32:12 +00:00
die(4, f'Error. Expect returned {ret}')
else:
if t:
2024-10-18 10:32:12 +00:00
self.send(t, delay, s)
else:
if not nonl and not silent:
vmsg('')
return ret
2024-10-18 10:32:12 +00:00
def send(self, t, delay=None, s=False):
delay = delay or self.send_delay
if delay:
time.sleep(delay)
ret = self.p.send(t) # returns num bytes written
self.sent_value = t if ret else None
if cfg.demo and delay:
time.sleep(delay)
if cfg.verbose:
ls = '' if cfg.debug or not s else ' '
es = '' if s else ' '
2024-10-18 10:32:12 +00:00
yt = yellow('{!r}'.format(t.replace('\n', r'\n')))
msg(f'{ls}SEND {es}{yt}')
return ret
2024-10-18 10:32:12 +00:00
def read(self, n=-1, strip_color=False):
return strip_ansi_escapes(self.p.read(n)).replace('\r', '') if strip_color else self.p.read(n)
def close(self):
if self.pexpect_spawn:
self.p.close()