5 from log import RED, single_line_delim, double_line_delim
7 from subprocess import check_output, CalledProcessError
8 from util import check_core_path, get_core_path
13 Generic hooks before/after API/CLI calls
16 def __init__(self, test):
18 self.logger = test.logger
20 def before_api(self, api_name, api_args):
22 Function called before API call
23 Emit a debug message describing the API name and arguments
25 @param api_name: name of the API
26 @param api_args: tuple containing the API arguments
29 def _friendly_format(val):
30 if not isinstance(val, str):
33 return '{!s} ({!s})'.format(val, ':'.join(['{:02x}'.format(
34 ord(x)) for x in val]))
36 # we don't call test_type(val) because it is a packed value.
37 return '{!s} ({!s})'.format(val, str(
38 ipaddress.ip_address(val)))
39 except ipaddress.AddressValueError:
42 _args = ', '.join("{!s}={!r}".format(key, _friendly_format(val)) for
43 (key, val) in api_args.items())
44 self.logger.debug("API: %s (%s)" %
45 (api_name, _args), extra={'color': RED})
47 def after_api(self, api_name, api_args):
49 Function called after API call
51 @param api_name: name of the API
52 @param api_args: tuple containing the API arguments
56 def before_cli(self, cli):
58 Function called before CLI call
59 Emit a debug message describing the CLI
61 @param cli: CLI string
63 self.logger.debug("CLI: %s" % (cli), extra={'color': RED})
65 def after_cli(self, cli):
67 Function called after CLI call
72 class VppDiedError(Exception):
77 """ Hook which checks if the vpp subprocess is alive """
79 def __init__(self, test):
80 super(PollHook, self).__init__(test)
82 def on_crash(self, core_path):
83 self.logger.error("Core file present, debug with: gdb %s %s",
84 self.testcase.vpp_bin, core_path)
85 check_core_path(self.logger, core_path)
86 self.logger.error("Running `file %s':", core_path)
88 info = check_output(["file", core_path])
89 self.logger.error(info)
90 except CalledProcessError as e:
92 "Subprocess returned with error running `file' utility on "
94 "rc=%s", e.returncode)
97 "Subprocess returned OS error running `file' utility on "
99 "oserror=(%s) %s", e.errno, e.strerror)
100 except Exception as e:
102 "Subprocess returned unanticipated error running `file' "
103 "utility on core-file, "
108 Poll the vpp status and throw an exception if it's not running
109 :raises VppDiedError: exception if VPP is not running anymore
111 if self.test.vpp_dead:
112 # already dead, nothing to do
116 if self.test.vpp.returncode is not None:
118 (k, v) for v, k in reversed(sorted(signal.__dict__.items()))
119 if v.startswith('SIG') and not v.startswith('SIG_'))
121 if self.test.vpp.returncode in signaldict:
122 s = signaldict[abs(self.test.vpp.returncode)]
125 msg = "VPP subprocess died unexpectedly with returncode %d [%s]." \
126 % (self.test.vpp.returncode, s)
127 self.logger.critical(msg)
128 core_path = get_core_path(self.test.tempdir)
129 if os.path.isfile(core_path):
130 self.on_crash(core_path)
131 self.test.vpp_dead = True
132 raise VppDiedError(msg)
134 def before_api(self, api_name, api_args):
136 Check if VPP died before executing an API
138 :param api_name: name of the API
139 :param api_args: tuple containing the API arguments
140 :raises VppDiedError: exception if VPP is not running anymore
143 super(PollHook, self).before_api(api_name, api_args)
146 def before_cli(self, cli):
148 Check if VPP died before executing a CLI
150 :param cli: CLI string
151 :raises Exception: exception if VPP is not running anymore
154 super(PollHook, self).before_cli(cli)
158 class StepHook(PollHook):
159 """ Hook which requires user to press ENTER before doing any API/CLI """
161 def __init__(self, test):
162 self.skip_stack = None
165 super(StepHook, self).__init__(test)
168 if self.skip_stack is None:
170 stack = traceback.extract_stack()
174 if counter > self.skip_num:
176 if e[0] != self.skip_stack[counter][0]:
178 if e[1] != self.skip_stack[counter][1]:
185 print("%d API/CLI calls skipped in specified stack "
186 "frame" % self.skip_count)
188 self.skip_stack = None
192 def user_input(self):
193 print('number\tfunction\tfile\tcode')
195 stack = traceback.extract_stack()
197 print('%02d.\t%s\t%s:%d\t[%s]' % (counter, e[2], e[0], e[1], e[3]))
199 print(single_line_delim)
200 print("You may enter a number of stack frame chosen from above")
201 print("Calls in/below that stack frame will be not be stepped anymore")
202 print(single_line_delim)
204 print("Enter your choice, if any, and press ENTER to continue "
205 "running the testcase...")
206 choice = sys.stdin.readline().rstrip('\r\n')
210 if choice is not None:
213 print("Invalid input")
215 if choice is not None and (num < 0 or num >= len(stack)):
216 print("Invalid choice")
219 if choice is not None:
220 self.skip_stack = stack
223 def before_cli(self, cli):
224 """ Wait for ENTER before executing CLI """
226 print("Skip pause before executing CLI: %s" % cli)
228 print(double_line_delim)
229 print("Test paused before executing CLI: %s" % cli)
230 print(single_line_delim)
232 super(StepHook, self).before_cli(cli)
234 def before_api(self, api_name, api_args):
235 """ Wait for ENTER before executing API """
237 print("Skip pause before executing API: %s (%s)"
238 % (api_name, api_args))
240 print(double_line_delim)
241 print("Test paused before executing API: %s (%s)"
242 % (api_name, api_args))
243 print(single_line_delim)
245 super(StepHook, self).before_api(api_name, api_args)