5 from subprocess import check_output, CalledProcessError
9 from log import RED, single_line_delim, double_line_delim
10 from util import check_core_path, get_core_path
15 Generic hooks before/after API/CLI calls
18 def __init__(self, test):
20 self.logger = test.logger
22 def before_api(self, api_name, api_args):
24 Function called before API call
25 Emit a debug message describing the API name and arguments
27 @param api_name: name of the API
28 @param api_args: tuple containing the API arguments
31 def _friendly_format(val):
32 if not isinstance(val, str):
35 return '{!s} ({!s})'.format(val, ':'.join(['{:02x}'.format(
36 scapy.compat.orb(x)) for x in val]))
38 # we don't call test_type(val) because it is a packed value.
39 return '{!s} ({!s})'.format(val, str(
40 ipaddress.ip_address(val)))
44 _args = ', '.join("{!s}={!r}".format(key, _friendly_format(val)) for
45 (key, val) in api_args.items())
46 self.logger.debug("API: %s (%s)" %
47 (api_name, _args), extra={'color': RED})
49 def after_api(self, api_name, api_args):
51 Function called after API call
53 @param api_name: name of the API
54 @param api_args: tuple containing the API arguments
58 def before_cli(self, cli):
60 Function called before CLI call
61 Emit a debug message describing the CLI
63 @param cli: CLI string
65 self.logger.debug("CLI: %s" % (cli), extra={'color': RED})
67 def after_cli(self, cli):
69 Function called after CLI call
75 """ Hook which checks if the vpp subprocess is alive """
77 def __init__(self, test):
78 super(PollHook, self).__init__(test)
80 def on_crash(self, core_path):
81 self.logger.error("Core file present, debug with: gdb %s %s",
82 self.test.vpp_bin, core_path)
83 check_core_path(self.logger, core_path)
84 self.logger.error("Running `file %s':", core_path)
86 info = check_output(["file", core_path])
87 self.logger.error(info)
88 except CalledProcessError as e:
90 "Subprocess returned with error running `file' utility on "
92 "rc=%s", e.returncode)
95 "Subprocess returned OS error running `file' utility on "
97 "oserror=(%s) %s", e.errno, e.strerror)
98 except Exception as e:
100 "Subprocess returned unanticipated error running `file' "
101 "utility on core-file, "
106 Poll the vpp status and throw an exception if it's not running
107 :raises VppDiedError: exception if VPP is not running anymore
109 if self.test.vpp_dead:
110 # already dead, nothing to do
114 if self.test.vpp.returncode is not None:
115 self.test.vpp_dead = True
116 raise framework.VppDiedError(rv=self.test.vpp.returncode)
117 core_path = get_core_path(self.test.tempdir)
118 if os.path.isfile(core_path):
119 self.on_crash(core_path)
121 def before_api(self, api_name, api_args):
123 Check if VPP died before executing an API
125 :param api_name: name of the API
126 :param api_args: tuple containing the API arguments
127 :raises VppDiedError: exception if VPP is not running anymore
130 super(PollHook, self).before_api(api_name, api_args)
133 def before_cli(self, cli):
135 Check if VPP died before executing a CLI
137 :param cli: CLI string
138 :raises Exception: exception if VPP is not running anymore
141 super(PollHook, self).before_cli(cli)
145 class StepHook(PollHook):
146 """ Hook which requires user to press ENTER before doing any API/CLI """
148 def __init__(self, test):
149 self.skip_stack = None
152 self.break_func = None
153 super(StepHook, self).__init__(test)
156 if self.break_func is not None:
157 return self.should_skip_func_based()
158 if self.skip_stack is not None:
159 return self.should_skip_stack_based()
161 def should_skip_func_based(self):
162 stack = traceback.extract_stack()
164 if e[2] == self.break_func:
165 self.break_func = None
169 def should_skip_stack_based(self):
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("Alternatively, enter a test function name to stop at")
203 print(single_line_delim)
205 print("Enter your choice, if any, and press ENTER to continue "
206 "running the testcase...")
207 choice = sys.stdin.readline().rstrip('\r\n')
211 if choice is not None:
214 if choice.startswith("test_"):
216 print("Invalid input")
218 if choice is not None and (num < 0 or num >= len(stack)):
219 print("Invalid choice")
222 if choice is not None:
223 if choice.startswith("test_"):
224 self.break_func = choice
226 self.break_func = None
227 self.skip_stack = stack
230 def before_cli(self, cli):
231 """ Wait for ENTER before executing CLI """
233 print("Skip pause before executing CLI: %s" % cli)
235 print(double_line_delim)
236 print("Test paused before executing CLI: %s" % cli)
237 print(single_line_delim)
239 super(StepHook, self).before_cli(cli)
241 def before_api(self, api_name, api_args):
242 """ Wait for ENTER before executing API """
244 print("Skip pause before executing API: %s (%s)"
245 % (api_name, api_args))
247 print(double_line_delim)
248 print("Test paused before executing API: %s (%s)"
249 % (api_name, api_args))
250 print(single_line_delim)
252 super(StepHook, self).before_api(api_name, api_args)