-
Notifications
You must be signed in to change notification settings - Fork 128
Expand file tree
/
Copy pathcli.py
More file actions
219 lines (169 loc) · 7.03 KB
/
cli.py
File metadata and controls
219 lines (169 loc) · 7.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
"""
..
PYTEST_DONT_REWRITE
"""
import argparse
from functools import partial
from _pytest import pathlib
from _pytest._io import TerminalWriter
from _pytest.config import Config
from _pytest.config.findpaths import locate_config
from pytest_benchmark.csv import CSVResults
from . import plugin
from .logger import Logger
from .plugin import add_csv_options
from .plugin import add_display_options
from .plugin import add_global_options
from .plugin import add_histogram_options
from .table import CompareBetweenResults
from .table import TableResults
from .utils import NAME_FORMATTERS
from .utils import first_or_value
from .utils import load_storage
from .utils import report_noprogress
COMPARE_HELP = """examples:
pytest-benchmark {0} 'Linux-CPython-3.5-64bit/*'
Loads all benchmarks ran with that interpreter. Note the special quoting that disables your shell's glob
expansion.
pytest-benchmark {0} 0001
Loads first run from all the interpreters.
pytest-benchmark {0} /foo/bar/0001_abc.json /lorem/ipsum/0001_sir_dolor.json
Loads runs from exactly those files."""
class HelpAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
if values:
make_parser().parse_args([values, '--help'])
else:
parser.print_help()
parser.exit()
class CommandArgumentParser(argparse.ArgumentParser):
commands = None
commands_dispatch = None
def __init__(self, *args, **kwargs):
kwargs['add_help'] = False
super().__init__(*args, formatter_class=argparse.RawDescriptionHelpFormatter, **kwargs)
self.add_argument('-h', '--help', metavar='COMMAND', nargs='?', action=HelpAction, help='Display help and exit.')
help_command = self.add_command('help', description='Display help and exit.')
help_command.add_argument('command', nargs='?', action=HelpAction)
def add_command(self, name, **opts):
if self.commands is None:
self.commands = self.add_subparsers(
title='commands',
dest='command',
parser_class=argparse.ArgumentParser,
)
self.commands_dispatch = {}
if 'description' in opts and 'help' not in opts:
opts['help'] = opts['description']
command = self.commands.add_parser(name, formatter_class=argparse.RawDescriptionHelpFormatter, **opts)
self.commands_dispatch[name] = command
return command
def add_glob_or_file(addoption):
addoption('glob_or_file', nargs='*', help='Glob or exact path for json files. If not specified all runs are loaded.')
def make_parser():
parser = CommandArgumentParser('py.test-benchmark', description="pytest_benchmark's management commands.")
add_global_options(parser.add_argument, prefix='')
parser.add_command('list', description='List saved runs.')
compare_command = parser.add_command(
'compare',
description='Compare saved runs.',
epilog="""examples:
pytest-benchmark compare 'Linux-CPython-3.5-64bit/*'
Loads all benchmarks ran with that interpreter. Note the special quoting that disables your shell's glob
expansion.
pytest-benchmark compare 0001
Loads first run from all the interpreters.
pytest-benchmark compare /foo/bar/0001_abc.json /lorem/ipsum/0001_sir_dolor.json
Loads runs from exactly those files.""",
)
add_display_options(compare_command.add_argument, prefix='')
add_histogram_options(compare_command.add_argument, prefix='')
compare_command.add_argument(
'--compare-between',
action='store_true',
help='Compare same-named benchmarks across different source files.',
)
add_glob_or_file(compare_command.add_argument)
add_csv_options(compare_command.add_argument, prefix='')
return parser
class HookDispatch:
def __init__(self, *, root, **kwargs):
_, _, config, *_ = locate_config(invocation_dir=root, args=())
conftest_file = pathlib.Path('conftest.py')
if conftest_file.exists():
self.conftest = pathlib.import_path(
conftest_file,
**kwargs,
root=root,
consider_namespace_packages=bool(config.get('consider_namespace_packages')),
)
else:
self.conftest = None
def __getattr__(self, item):
default = getattr(plugin, item)
return getattr(self.conftest, item, default)
def main():
parser = make_parser()
args = parser.parse_args()
level = Logger.QUIET if args.quiet else Logger.NORMAL
if args.verbose:
level = Logger.VERBOSE
logger = Logger(level)
storage = load_storage(args.storage, logger=logger, netrc=args.netrc)
hook = HookDispatch(mode=args.importmode, root=pathlib.Path('.'))
if args.command == 'list':
for file in storage.query():
print(file)
elif args.command == 'compare':
histogram = first_or_value(args.histogram, False)
if args.compare_between:
if histogram:
parser.error('--compare-between is not compatible with --histogram')
results_table_cls = CompareBetweenResults
else:
results_table_cls = TableResults
results_table = results_table_cls(
columns=args.columns,
sort=args.sort,
histogram=histogram,
name_format=NAME_FORMATTERS[args.name],
logger=logger,
scale_unit=partial(
hook.pytest_benchmark_scale_unit,
config=Config.fromdictargs({'benchmark_time_unit': args.time_unit}, []),
),
)
groups = hook.pytest_benchmark_group_stats(
benchmarks=storage.load_benchmarks(*args.glob_or_file),
group_by=args.group_by,
config=None,
)
results_table.display(TerminalReporter(), groups, progress_reporter=report_noprogress)
if args.csv:
results_csv = CSVResults(args.columns, args.sort, logger)
(output_file,) = args.csv
results_csv.render(output_file, groups)
elif args.command is None:
parser.error('missing command (available commands: {})'.format(', '.join(map(repr, parser.commands.choices))))
else:
parser.error(f'unexpected command {args.command!r}')
class TerminalReporter:
def __init__(self):
self._tw = TerminalWriter()
def ensure_newline(self):
pass
def write(self, content, **markup):
self._tw.write(content, **markup)
def write_line(self, line, **markup):
if not isinstance(line, str):
line = line.decode(errors='replace')
self._tw.line(line, **markup)
def rewrite(self, line, **markup):
line = str(line)
self._tw.write('\r' + line, **markup)
def write_sep(self, sep, title=None, **markup):
self._tw.sep(sep, title, **markup)
def section(self, title, sep='=', **kw):
self._tw.sep(sep, title, **kw)
def line(self, msg, **kw):
self._tw.line(msg, **kw)