Debian Codegraph @

bin/behave.step_durations.py

raw
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 """
4 Utility script to retrieve duration information from behave JSON output.
5
6 REQUIRES: Python >= 2.6 (json module is part of Python standard library)
7 LICENSE: BSD
8 """
9
10 from __future__ import absolute_import
11
12 __author__ = "Jens Engel"
13 __copyright__ = "(c) 2013 by Jens Engel"
14 __license__ = "BSD"
15 VERSION = "0.1.0"
16
17 # -- IMPORTS:
18 from behave import json_parser
19 from behave.model import ScenarioOutline
20 from optparse import OptionParser
21 from operator import attrgetter
22 import os.path
23 import sys
24
25
26 # ----------------------------------------------------------------------------
27 # FUNCTIONS:
28 # ----------------------------------------------------------------------------
29 class StepDurationData(object):
30 def __init__(self, step=None):
31 self.step_name = None
32 self.min_duration = sys.maxint
33 self.max_duration = 0
34 self.durations = []
35 self.step = step
36 if step:
37 self.process_step(step)
38
39 @staticmethod
40 def make_step_name(step):
41 step_name = "%s %s" % (step.step_type.capitalize(), step.name)
42 return step_name
43
44 def process_step(self, step):
45 step_name = self.make_step_name(step)
46 if not self.step_name:
47 self.step_name = step_name
48 if self.min_duration > step.duration:
49 self.min_duration = step.duration
50 if self.max_duration < step.duration:
51 self.max_duration = step.duration
52 self.durations.append(step.duration)
53
54
55 class BehaveDurationData(object):
56 def __init__(self):
57 self.step_registry = {}
58 self.all_steps = []
59 self.all_scenarios = []
60
61
62 def process_features(self, features):
63 for feature in features:
64 self.process_feature(feature)
65
66 def process_feature(self, feature):
67 if feature.background:
68 self.process_background(feature.background)
69 for scenario in feature.scenarios:
70 if isinstance(scenario, ScenarioOutline):
71 self.process_scenario_outline(scenario)
72 else:
73 self.process_scenario(scenario)
74
75 def process_step(self, step):
76 step_name = StepDurationData.make_step_name(step)
77 known_step = self.step_registry.get(step_name, None)
78 if known_step:
79 known_step.process_step(step)
80 else:
81 step_data = StepDurationData(step)
82 self.step_registry[step_name] = step_data
83 self.all_steps.append(step)
84
85 def process_background(self, scenario):
86 for step in scenario:
87 self.process_step(step)
88
89 def process_scenario(self, scenario):
90 for step in scenario:
91 self.process_step(step)
92
93 def process_scenario_outline(self, scenario_outline):
94 for scenario in scenario_outline:
95 self.process_scenario(scenario)
96
97 def report_step_durations(self, limit=None, min_duration=None, ostream=sys.stdout):
98 step_datas = list(self.step_registry.values())
99 steps_size = len(step_datas)
100 steps_by_longest_duration_first = sorted(step_datas,
101 key=attrgetter("max_duration"),
102 reverse=True)
103 ostream.write("STEP DURATIONS (longest first, size=%d):\n" % steps_size)
104 ostream.write("-" * 80)
105 ostream.write("\n")
106 for index, step in enumerate(steps_by_longest_duration_first):
107 ostream.write("% 4d. %9.6fs %s" % \
108 (index+1, step.max_duration, step.step_name))
109 calls = len(step.durations)
110 if calls > 1:
111 ostream.write(" (%d calls, min: %.6fs)\n" % (calls, step.min_duration))
112 else:
113 ostream.write("\n")
114 if ((limit and index+1 >= limit) or
115 (step.max_duration < min_duration)):
116 remaining = steps_size - (index+1)
117 ostream.write("...\nSkip remaining %d steps.\n" % remaining)
118 break
119
120
121 # ----------------------------------------------------------------------------
122 # MAIN FUNCTION:
123 # ----------------------------------------------------------------------------
124 def main(args=None):
125 if args is None:
126 args = sys.argv[1:]
127
128 usage_ = """%prog [OPTIONS] JsonFile
129 Read behave JSON data file and extract steps with longest duration."""
130 parser = OptionParser(usage=usage_, version=VERSION)
131 parser.add_option("-e", "--encoding", dest="encoding",
132 default="UTF-8",
133 help="Encoding to use (default: %default).")
134 parser.add_option("-l", "--limit", dest="limit", type="int",
135 help="Max. number of steps (default: %default).")
136 parser.add_option("-m", "--min", dest="min_duration", default="0",
137 help="Min. duration threshold (default: %default).")
138 options, filenames = parser.parse_args(args)
139 if not filenames:
140 parser.error("OOPS, no filenames provided.")
141 elif len(filenames) > 1:
142 parser.error("OOPS: Can only process one JSON file.")
143 min_duration = float(options.min_duration)
144 if min_duration < 0:
145 min_duration = None
146 json_filename = filenames[0]
147 if not os.path.exists(json_filename):
148 parser.error("JSON file '%s' not found" % json_filename)
149
150 # -- NORMAL PROCESSING: Read JSON, extract step durations and report them.
151 features = json_parser.parse(json_filename)
152 processor = BehaveDurationData()
153 processor.process_features(features)
154 processor.report_step_durations(options.limit, min_duration)
155 sys.stdout.write("Detected %d features.\n" % len(features))
156 return 0
157
158
159 # ----------------------------------------------------------------------------
160 # AUTO-MAIN:
161 # ----------------------------------------------------------------------------
162 if __name__ == "__main__":
163 sys.exit(main())