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, logger):
19 def before_api(self, api_name, api_args):
21 Function called before API call
22 Emit a debug message describing the API name and arguments
24 @param api_name: name of the API
25 @param api_args: tuple containing the API arguments
28 def _friendly_format(val):
29 if not isinstance(val, str):
32 return '{!s} ({!s})'.format(val, ':'.join(['{:02x}'.format(
33 ord(x)) for x in val]))
35 return '{!s} ({!s})'.format(val, str(
36 ipaddress.ip_address(val)))
37 except ipaddress.AddressValueError:
40 _args = ', '.join("{!s}={!r}".format(key, _friendly_format(val)) for
41 (key, val) in api_args.items())
42 self.logger.debug("API: %s (%s)" %
43 (api_name, _args), extra={'color': RED})
45 def after_api(self, api_name, api_args):
47 Function called after API call
49 @param api_name: name of the API
50 @param api_args: tuple containing the API arguments
54 def before_cli(self, cli):
56 Function called before CLI call
57 Emit a debug message describing the CLI
59 @param cli: CLI string
61 self.logger.debug("CLI: %s" % (cli), extra={'color': RED})
63 def after_cli(self, cli):
65 Function called after CLI call
70 class VppDiedError(Exception):
75 """ Hook which checks if the vpp subprocess is alive """
77 def __init__(self, testcase):
78 super(PollHook, self).__init__(testcase.logger)
79 self.testcase = testcase
81 def on_crash(self, core_path):
82 self.logger.error("Core file present, debug with: gdb %s %s" %
83 (self.testcase.vpp_bin, core_path))
84 check_core_path(self.logger, core_path)
85 self.logger.error("Running `file %s':" % core_path)
87 info = check_output(["file", core_path])
88 self.logger.error(info)
89 except CalledProcessError as e:
91 "Could not run `file' utility on core-file, "
92 "rc=%s" % e.returncode)
96 Poll the vpp status and throw an exception if it's not running
97 :raises VppDiedError: exception if VPP is not running anymore
99 if self.testcase.vpp_dead:
100 # already dead, nothing to do
103 self.testcase.vpp.poll()
104 if self.testcase.vpp.returncode is not None:
106 (k, v) for v, k in reversed(sorted(signal.__dict__.items()))
107 if v.startswith('SIG') and not v.startswith('SIG_'))
109 if self.testcase.vpp.returncode in signaldict:
110 s = signaldict[abs(self.testcase.vpp.returncode)]
113 msg = "VPP subprocess died unexpectedly with returncode %d [%s]." \
114 % (self.testcase.vpp.returncode, s)
115 self.logger.critical(msg)
116 core_path = get_core_path(self.testcase.tempdir)
117 if os.path.isfile(core_path):
118 self.on_crash(core_path)
119 self.testcase.vpp_dead = True
120 raise VppDiedError(msg)
122 def before_api(self, api_name, api_args):
124 Check if VPP died before executing an API
126 :param api_name: name of the API
127 :param api_args: tuple containing the API arguments
128 :raises VppDiedError: exception if VPP is not running anymore
131 super(PollHook, self).before_api(api_name, api_args)
134 def before_cli(self, cli):
136 Check if VPP died before executing a CLI
138 :param cli: CLI string
139 :raises Exception: exception if VPP is not running anymore
142 super(PollHook, self).before_cli(cli)
146 class StepHook(PollHook):
147 """ Hook which requires user to press ENTER before doing any API/CLI """
149 def __init__(self, testcase):
150 self.skip_stack = None
153 super(StepHook, self).__init__(testcase)
156 if self.skip_stack is None:
158 stack = traceback.extract_stack()
162 if counter > self.skip_num:
164 if e[0] != self.skip_stack[counter][0]:
166 if e[1] != self.skip_stack[counter][1]:
173 print("%d API/CLI calls skipped in specified stack "
174 "frame" % self.skip_count)
176 self.skip_stack = None
180 def user_input(self):
181 print('number\tfunction\tfile\tcode')
183 stack = traceback.extract_stack()
185 print('%02d.\t%s\t%s:%d\t[%s]' % (counter, e[2], e[0], e[1], e[3]))
187 print(single_line_delim)
188 print("You may enter a number of stack frame chosen from above")
189 print("Calls in/below that stack frame will be not be stepped anymore")
190 print(single_line_delim)
192 print("Enter your choice, if any, and press ENTER to continue "
193 "running the testcase...")
194 choice = sys.stdin.readline().rstrip('\r\n')
198 if choice is not None:
201 print("Invalid input")
203 if choice is not None and (num < 0 or num >= len(stack)):
204 print("Invalid choice")
207 if choice is not None:
208 self.skip_stack = stack
211 def before_cli(self, cli):
212 """ Wait for ENTER before executing CLI """
214 print("Skip pause before executing CLI: %s" % cli)
216 print(double_line_delim)
217 print("Test paused before executing CLI: %s" % cli)
218 print(single_line_delim)
220 super(StepHook, self).before_cli(cli)
222 def before_api(self, api_name, api_args):
223 """ Wait for ENTER before executing API """
225 print("Skip pause before executing API: %s (%s)"
226 % (api_name, api_args))
228 print(double_line_delim)
229 print("Test paused before executing API: %s (%s)"
230 % (api_name, api_args))
231 print(single_line_delim)
233 super(StepHook, self).before_api(api_name, api_args)