Skip to content

Commit

Permalink
Apply reformatting.
Browse files Browse the repository at this point in the history
  • Loading branch information
ionelmc committed Dec 14, 2023
1 parent dbfb956 commit fcb183c
Show file tree
Hide file tree
Showing 33 changed files with 2,378 additions and 2,212 deletions.
2 changes: 1 addition & 1 deletion docs/sample.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion src/pytest_benchmark/__main__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from pytest_benchmark.cli import main

if __name__ == "__main__":
if __name__ == '__main__':
main()
63 changes: 26 additions & 37 deletions src/pytest_benchmark/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
from .utils import load_storage
from .utils import report_noprogress

COMPARE_HELP = '''examples:
COMPARE_HELP = """examples:
pytest-benchmark {0} 'Linux-CPython-3.5-64bit/*'
Expand All @@ -31,7 +31,7 @@
pytest-benchmark {0} /foo/bar/0001_abc.json /lorem/ipsum/0001_sir_dolor.json
Loads runs from exactly those files.'''
Loads runs from exactly those files."""


class HelpAction(argparse.Action):
Expand All @@ -50,53 +50,41 @@ class CommandArgumentParser(argparse.ArgumentParser):
def __init__(self, *args, **kwargs):
kwargs['add_help'] = False

super(CommandArgumentParser, self).__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.'
)
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,
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
)
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.'
)
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="")
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:
epilog="""examples:
pytest-benchmark compare 'Linux-CPython-3.5-64bit/*'
Expand All @@ -109,16 +97,17 @@ def make_parser():
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="")
Loads runs from exactly those files.""",
)
add_display_options(compare_command.add_argument, prefix='')
add_histogram_options(compare_command.add_argument, prefix='')
add_glob_or_file(compare_command.add_argument)
add_csv_options(compare_command.add_argument, prefix="")
add_csv_options(compare_command.add_argument, prefix='')

return parser


class HookDispatch(object):
class HookDispatch:
def __init__(self, **kwargs):
conftest_file = pathlib.Path('conftest.py')
if conftest_file.exists():
Expand Down Expand Up @@ -152,7 +141,7 @@ def main():
histogram=first_or_value(args.histogram, False),
name_format=NAME_FORMATTERS[args.name],
logger=logger,
scale_unit=partial(hook.pytest_benchmark_scale_unit, config=None)
scale_unit=partial(hook.pytest_benchmark_scale_unit, config=None),
)
groups = hook.pytest_benchmark_group_stats(
benchmarks=storage.load_benchmarks(*args.glob_or_file),
Expand All @@ -162,16 +151,16 @@ def main():
results_table.display(TerminalReporter(), groups, progress_reporter=report_noprogress)
if args.csv:
results_csv = CSVResults(args.columns, args.sort, logger)
output_file, = args.csv
(output_file,) = args.csv

results_csv.render(output_file, groups)
elif args.command is None:
parser.error("missing command (available commands: %s)" % ', '.join(map(repr, parser.commands.choices)))
parser.error('missing command (available commands: %s)' % ', '.join(map(repr, parser.commands.choices)))
else:
parser.error("unexpected command %r" % args.command)
parser.error('unexpected command %r' % args.command)


class TerminalReporter(object):
class TerminalReporter:
def __init__(self):
self._tw = TerminalWriter()

Expand All @@ -183,17 +172,17 @@ def write(self, content, **markup):

def write_line(self, line, **markup):
if not isinstance(line, str):
line = line.decode(errors="replace")
line = line.decode(errors='replace')
self._tw.line(line, **markup)

def rewrite(self, line, **markup):
line = str(line)
self._tw.write("\r" + line, **markup)
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):
def section(self, title, sep='=', **kw):
self._tw.sep(sep, title, **kw)

def line(self, msg, **kw):
Expand Down
1 change: 0 additions & 1 deletion src/pytest_benchmark/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,3 @@

PY38 = sys.version_info[0] == 3 and sys.version_info[1] >= 8
PY311 = sys.version_info[0] == 3 and sys.version_info[1] >= 11

32 changes: 14 additions & 18 deletions src/pytest_benchmark/csv.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
from __future__ import absolute_import

import csv
import operator

import py


class CSVResults(object):
class CSVResults:
def __init__(self, columns, sort, logger):
self.columns = columns
self.sort = sort
Expand All @@ -18,25 +16,23 @@ def render(self, output_file, groups):
output_file = output_file.new(ext='csv')
with output_file.open('w', ensure=True) as stream:
writer = csv.writer(stream)
params = sorted(set(
param
for group, benchmarks in groups
for benchmark in benchmarks
for param in benchmark.get("params", {}) or ()
))
writer.writerow([
"name",
] + [
"param:{0}".format(p)
for p in params
] + self.columns)
params = sorted(
set(param for group, benchmarks in groups for benchmark in benchmarks for param in benchmark.get('params', {}) or ())
)
writer.writerow(
[
'name',
]
+ [f'param:{p}' for p in params]
+ self.columns
)

for group, benchmarks in groups:
benchmarks = sorted(benchmarks, key=operator.itemgetter(self.sort))

for bench in benchmarks:
row = [bench.get("fullfunc", bench["fullname"])]
row.extend(bench.get('params', {}).get(param, "") for param in params)
row = [bench.get('fullfunc', bench['fullname'])]
row.extend(bench.get('params', {}).get(param, '') for param in params)
row.extend(bench[prop] for prop in self.columns)
writer.writerow(row)
self.logger.info("Generated csv: {0}".format(output_file), bold=True)
self.logger.info(f'Generated csv: {output_file}', bold=True)
Loading

0 comments on commit fcb183c

Please sign in to comment.