Skip to content

Commit 5cfdd1f

Browse files
committed
update code to have single try-catch
1 parent c7f516e commit 5cfdd1f

File tree

4 files changed

+97
-151
lines changed

4 files changed

+97
-151
lines changed

bzt/modules/_apiritif/generator.py

Lines changed: 92 additions & 109 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def _gen_class_actionid_tracking(self):
7272
]
7373

7474
def _gen_action_start_with_tracking(self, actionId):
75-
# Assign actionId to self._current_actionId before action_start
75+
# Assign actionId (or None) to self._current_actionId before each action
7676
return [
7777
ast.Assign(
7878
targets=[ast_attr("self._current_actionId")],
@@ -96,63 +96,6 @@ def _gen_teardown_with_actionid(self):
9696
body=[ast.Expr(ast_call(func=ast_attr("self.driver.quit")))],
9797
orelse=[]
9898
),
99-
ast.Assign(
100-
targets=[ast.Name(id="outcome", ctx=ast.Store())],
101-
value=ast.Call(
102-
func=ast.Name(id="getattr", ctx=ast.Load()),
103-
args=[ast.Name(id="self", ctx=ast.Load()), ast.Constant("_outcome", kind=""),
104-
ast.Constant(None, kind="")],
105-
keywords=[]
106-
)
107-
),
108-
ast.Assign(
109-
targets=[ast.Name(id="result", ctx=ast.Store())],
110-
value=ast.Call(
111-
func=ast.Name(id="getattr", ctx=ast.Load()),
112-
args=[ast.Name(id="outcome", ctx=ast.Load()), ast.Constant("result", kind=""),
113-
ast.Constant(None, kind="")],
114-
keywords=[]
115-
)
116-
),
117-
ast.If(
118-
test=ast.BoolOp(
119-
op=ast.And(),
120-
values=[
121-
ast.Name(id="result", ctx=ast.Load()),
122-
ast.BoolOp(
123-
op=ast.Or(),
124-
values=[
125-
ast.Attribute(
126-
value=ast.Name(id="result", ctx=ast.Load()),
127-
attr="errors",
128-
ctx=ast.Load()
129-
),
130-
ast.Attribute(
131-
value=ast.Name(id="result", ctx=ast.Load()),
132-
attr="failures",
133-
ctx=ast.Load()
134-
)
135-
]
136-
)
137-
]
138-
),
139-
body=[
140-
ast.Expr(ast_call(
141-
func=ast.Name(id="print", ctx=ast.Load()),
142-
args=[ast.BinOp(
143-
left=ast.Constant("[TAURUS][actionId] ", kind=""),
144-
op=ast.Add(),
145-
right=ast.Call(
146-
func=ast.Name(id="str", ctx=ast.Load()),
147-
args=[ast_attr("self._current_actionId")],
148-
keywords=[]
149-
)
150-
)],
151-
keywords=[]
152-
))
153-
],
154-
orelse=[]
155-
),
15699
],
157100
decorator_list=[]
158101
)
@@ -257,6 +200,7 @@ def __init__(self, scenario, label, wdlog=None, executor=None, ignore_unknown_ac
257200
self.replace_dialogs = True
258201
self.bzm_tdo_settings = bzm_tdo_settings
259202
self.do_testdata_orchestration = False
203+
self.has_action_ids = False
260204

261205
def _parse_action_params(self, expr, name):
262206
res = expr.match(name)
@@ -337,7 +281,11 @@ def _parse_dict_action(self, action_config):
337281
# actionId is an optional unique identifier for this action, used to track or reference
338282
# the action in the generated code and logs. It is passed through multiple layers of the
339283
# code generation process to maintain traceability of actions.
340-
actionId = action_config.get("actionId")
284+
if "actionId" in action_config and action_config.get("actionId") not in (None, "", {}):
285+
actionId = action_config.get("actionId")
286+
self.has_action_ids = True
287+
else:
288+
actionId = None
341289
selectors = []
342290
if action_config.get("locators"):
343291
selectors = action_config.get("locators")
@@ -791,7 +739,7 @@ def _gen_action(self, action_config, parent_request=None, index_label=""):
791739
wrapInTransaction = self._is_report_inside_actions(parent_request)
792740

793741
action_tracking = []
794-
if actionId:
742+
if self.has_action_ids:
795743
action_tracking.extend(self._gen_action_start_with_tracking(actionId))
796744

797745
action_elements = []
@@ -880,50 +828,6 @@ def _gen_action(self, action_config, parent_request=None, index_label=""):
880828
action_elements.append(ast_call(func=ast_attr("waiter"), args=[]))
881829

882830
action_body = [ast.Expr(element) for element in action_elements]
883-
if actionId:
884-
prefixed_error = ast.BinOp(
885-
left=ast.BinOp(
886-
left=ast.Constant("[TAURUS][actionId] ", kind=""),
887-
op=ast.Add(),
888-
right=ast.Call(
889-
func=ast.Name(id="str", ctx=ast.Load()),
890-
args=[ast_attr("self._current_actionId")],
891-
keywords=[]
892-
)
893-
),
894-
op=ast.Add(),
895-
right=ast.BinOp(
896-
left=ast.Constant(" | ", kind=""),
897-
op=ast.Add(),
898-
right=ast.Call(
899-
func=ast.Name(id="str", ctx=ast.Load()),
900-
args=[ast.Name(id="exc", ctx=ast.Load())],
901-
keywords=[]
902-
)
903-
)
904-
)
905-
906-
action_body = [ast.Try(
907-
body=action_body,
908-
handlers=[ast.ExceptHandler(
909-
type=ast.Name(id="Exception", ctx=ast.Load()),
910-
name="exc",
911-
body=[ast.Raise(
912-
exc=ast.Call(
913-
func=ast.Call(
914-
func=ast.Name(id="type", ctx=ast.Load()),
915-
args=[ast.Name(id="exc", ctx=ast.Load())],
916-
keywords=[]
917-
),
918-
args=[prefixed_error],
919-
keywords=[]
920-
),
921-
cause=ast.Name(id="exc", ctx=ast.Load())
922-
)]
923-
)],
924-
orelse=[],
925-
finalbody=[]
926-
)]
927831

928832
if wrapInTransaction:
929833
label = self._create_action_label(parent_request.label, index_label, action)
@@ -1851,7 +1755,8 @@ def _gen_classdef(self):
18511755

18521756
def _gen_class_setup(self):
18531757
data_sources = [self._gen_default_vars()]
1854-
data_sources.extend(self._gen_class_actionid_tracking())
1758+
if self.has_action_ids:
1759+
data_sources.extend(self._gen_class_actionid_tracking())
18551760
for idx in range(len(self.data_sources)):
18561761
data_sources.append(ast.Expr(ast_call(func=ast_attr("reader_%s.read_vars" % (idx + 1)))))
18571762

@@ -1929,7 +1834,17 @@ def _gen_class_setup(self):
19291834
return [setup, gen_empty_line_stmt()]
19301835

19311836
def _gen_class_teardown(self):
1932-
return self._gen_teardown_with_actionid()
1837+
if self.has_action_ids:
1838+
return self._gen_teardown_with_actionid()
1839+
1840+
body = [
1841+
ast.If(
1842+
test=ast_attr("self.driver"),
1843+
body=[ast.Expr(ast_call(func=ast_attr("self.driver.quit")))],
1844+
orelse=[]
1845+
)
1846+
]
1847+
return ast.FunctionDef(name="tearDown", args=[ast_attr("self")], body=body, decorator_list=[])
19331848

19341849
def _nfc_preprocess(self, requests):
19351850
setup = []
@@ -2021,9 +1936,9 @@ def _gen_master_test_method(self, try_block, finally_block):
20211936
if not try_block:
20221937
raise TaurusConfigError("Supported transactions not found, test is empty")
20231938

2024-
body = []
1939+
main_body = []
20251940
for slave_name in try_block:
2026-
body.append(ast.Expr(ast_call(func=ast_attr("self." + slave_name))))
1941+
main_body.append(ast.Expr(ast_call(func=ast_attr("self." + slave_name))))
20271942

20281943
finally_body = []
20291944
for slave_name in finally_block:
@@ -2032,7 +1947,75 @@ def _gen_master_test_method(self, try_block, finally_block):
20321947
if finally_body:
20331948
teardown_marker = ast.Expr(ast_call(func=ast_attr("apiritif.set_stage"), args=[self._gen_expr("teardown")]))
20341949
finally_body.insert(0, teardown_marker)
2035-
body = [gen_try_except(try_body=body, final_body=finally_body)]
1950+
1951+
if self.has_action_ids:
1952+
prefixed_error = ast.BinOp(
1953+
left=ast.BinOp(
1954+
left=ast.BinOp(
1955+
left=ast.Constant("actionId: ", kind=""),
1956+
op=ast.Add(),
1957+
right=ast.Call(
1958+
func=ast.Name(id="str", ctx=ast.Load()),
1959+
args=[ast_attr("self._current_actionId")],
1960+
keywords=[]
1961+
)
1962+
),
1963+
op=ast.Add(),
1964+
right=ast.Constant(" | ", kind="")
1965+
),
1966+
op=ast.Add(),
1967+
right=ast.Call(
1968+
func=ast.Name(id="str", ctx=ast.Load()),
1969+
args=[ast.Name(id="exc", ctx=ast.Load())],
1970+
keywords=[]
1971+
)
1972+
)
1973+
1974+
final_error = ast.IfExp(
1975+
test=ast.Compare(
1976+
left=ast_attr("self._current_actionId"),
1977+
ops=[ast.IsNot()],
1978+
comparators=[ast.Constant(value=None, kind="")]
1979+
),
1980+
body=prefixed_error,
1981+
orelse=ast.Call(
1982+
func=ast.Name(id="str", ctx=ast.Load()),
1983+
args=[ast.Name(id="exc", ctx=ast.Load())],
1984+
keywords=[]
1985+
)
1986+
)
1987+
1988+
body = [ast.Try(
1989+
body=main_body,
1990+
handlers=[ast.ExceptHandler(
1991+
type=ast.Name(id="Exception", ctx=ast.Load()),
1992+
name="exc",
1993+
body=[ast.Raise(
1994+
exc=ast.Call(
1995+
func=ast.Call(
1996+
func=ast.Name(id="type", ctx=ast.Load()),
1997+
args=[ast.Name(id="exc", ctx=ast.Load())],
1998+
keywords=[]
1999+
),
2000+
args=[final_error],
2001+
keywords=[]
2002+
),
2003+
cause=ast.Name(id="exc", ctx=ast.Load())
2004+
)]
2005+
)],
2006+
orelse=[],
2007+
finalbody=finally_body
2008+
)]
2009+
else:
2010+
if finally_body:
2011+
body = [ast.Try(
2012+
body=main_body,
2013+
handlers=[],
2014+
orelse=[],
2015+
finalbody=finally_body
2016+
)]
2017+
else:
2018+
body = main_body
20362019

20372020
name = 'test_' + create_method_name(self.label)
20382021
return self._gen_test_method(name=name, body=body)

bzt/modules/aggregator.py

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,6 @@ def __init__(self, perc_levels=(), hist_max_rt=1000.0, ext_aggregation=False):
232232
self[KPISet.RESP_CODES] = Counter()
233233
self[KPISet.PERCENTILES] = {}
234234
self.ext_aggregation = ext_aggregation
235-
self.log = logging.getLogger(self.__class__.__name__)
236235

237236
def __deepcopy__(self, memo):
238237
mycopy = KPISet(self.perc_levels, self[KPISet.RESP_TIMES].high)
@@ -251,9 +250,7 @@ def error_item_skel(
251250
error: str, ret_c: str, cnt: int, err_type: int,
252251
urls: Counter, tag: str, err_resp_data: Optional[ErrorResponseData] = None, action_id: str = None) -> dict:
253252
assert isinstance(urls, collections.Counter)
254-
logging.getLogger("DEV DEV").info("In error_item_skel, err_resp_data: {}".format(err_resp_data))
255253
response_bodies = KPISet._get_response_bodies(err_resp_data)
256-
logging.getLogger("DEV DEV").info("In error_item_skel, response_bodies: {}".format(response_bodies))
257254
item = {
258255
"cnt": cnt,
259256
"msg": error,
@@ -307,10 +304,6 @@ def add_sample(self, sample):
307304

308305
if error is not None:
309306
self[self.FAILURES] += 1
310-
self.log.info(f"DEV DEV: error: {error}")
311-
self.log.info(f"DEV DEV: r_code: {r_code}")
312-
self.log.info(f"DEV DEV: error: {error}")
313-
self.log.info(f"DEV DEV: action_id: {action_id}")
314307
item = self.error_item_skel(
315308
error,
316309
r_code,
@@ -319,7 +312,6 @@ def add_sample(self, sample):
319312
Counter(),
320313
None,
321314
action_id=action_id)
322-
self.log.info(f"DEV DEV: item: {item}")
323315
self.inc_list(self[self.ERRORS], ("msg", error), item)
324316
else:
325317
self[self.SUCCESSES] += 1
@@ -760,7 +752,7 @@ def __aggregate_current(self, datapoint, samples):
760752

761753
if self.generalize_labels:
762754
base_label = self._generalize_label(base_label)
763-
self.log.info(f"Sample: {sample}")
755+
764756
self.__add_sample(current, base_label, sample[1:])
765757

766758
overall = KPISet(self.track_percentiles, self.__get_rtimes_max(''), ext_aggregation=self._redundant_aggregation)
@@ -788,7 +780,7 @@ def __add_sample(self, current, label, kpis):
788780
perc_levels=self.track_percentiles,
789781
hist_max_rt=self.__get_rtimes_max(label),
790782
ext_aggregation=self._redundant_aggregation)
791-
self.log.info(f"kpis: {kpis}")
783+
792784
current[label].add_sample(kpis)
793785

794786
def __get_rtimes_max(self, label):

0 commit comments

Comments
 (0)