Skip to content

Commit

Permalink
Merge pull request #12 from jdugan1024/master
Browse files Browse the repository at this point in the history
Fix decorator so that fmt works when without logging.
  • Loading branch information
brouberol authored Sep 4, 2016
2 parents 077cb1f + 01dd0fd commit a580059
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 8 deletions.
15 changes: 7 additions & 8 deletions contexttimer/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,18 +121,17 @@ def wrapped_f(f):
def wrapped(*args, **kwargs):
with Timer(**timer_kwargs) as t:
out = f(*args, **kwargs)
context = {
'function_name': f.__name__,
'execution_time': t.elapsed,
}
if logger:
extra = {
'function_name': f.__name__,
'execution_time': t.elapsed,
}
logger.log(
level,
fmt % extra,
extra=extra)
fmt % context,
extra=context)
else:
print("function %s execution time: %.3f " %
(f.__name__, t.elapsed))
print(fmt % context)
return out
return wrapped
if (len(func_or_func_args) == 1
Expand Down
18 changes: 18 additions & 0 deletions tests/test_timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,21 @@ def print_reversed(string):

self.assertIsNotNone(output)
self.assertRegexpMatches(output.getvalue(), expected)

def test_decorator_print(self):
tests = [
({}, r"function foo execution time: [0-9.]+"),
({'fmt': '%(execution_time)s seconds later...'}, r"[0-9.]+ seconds later..."),
]


for kwargs, expected in tests:
output = StringIO()
with mock.patch('sys.stdout', new=output):
@contexttimer.timer(**kwargs)
def foo():
pass
foo()

self.assertIsNotNone(output)
self.assertRegexpMatches(output.getvalue(), expected)

0 comments on commit a580059

Please sign in to comment.