decorator: Extract zerver/lib/profile.py.

This lets us remove this debugging function from our core
authentication codebase.
This commit is contained in:
Tim Abbott
2017-08-14 16:14:32 -07:00
parent 077c05fc78
commit 319ea62cd9
2 changed files with 36 additions and 29 deletions

View File

@@ -26,7 +26,6 @@ from functools import wraps
import base64 import base64
import datetime import datetime
import logging import logging
import cProfile
import ujson import ujson
from io import BytesIO from io import BytesIO
from six.moves import zip, urllib from six.moves import zip, urllib
@@ -692,34 +691,6 @@ def rate_limit(domain='all'):
return wrapped_func return wrapped_func
return wrapper return wrapper
def profiled(func):
# type: (FuncT) -> FuncT
"""
This decorator should obviously be used only in a dev environment.
It works best when surrounding a function that you expect to be
called once. One strategy is to write a backend test and wrap the
test case with the profiled decorator.
You can run a single test case like this:
# edit zerver/tests/test_external.py and place @profiled above the test case below
./tools/test-backend zerver.tests.test_external.RateLimitTests.test_ratelimit_decrease
Then view the results like this:
./tools/show-profile-results.py test_ratelimit_decrease.profile
"""
@wraps(func)
def wrapped_func(*args, **kwargs):
# type: (*Any, **Any) -> Any
fn = func.__name__ + ".profile"
prof = cProfile.Profile()
retval = prof.runcall(func, *args, **kwargs) # type: Any
prof.dump_stats(fn)
return retval
return wrapped_func # type: ignore # https://github.com/python/mypy/issues/1927
def return_success_on_head_request(view_func): def return_success_on_head_request(view_func):
# type: (Callable) -> Callable # type: (Callable) -> Callable
@wraps(view_func) @wraps(view_func)

36
zerver/lib/profile.py Normal file
View File

@@ -0,0 +1,36 @@
from __future__ import absolute_import
import cProfile
from functools import wraps
from typing import Any
from zerver.decorator import FuncT
def profiled(func):
# type: (FuncT) -> FuncT
"""
This decorator should obviously be used only in a dev environment.
It works best when surrounding a function that you expect to be
called once. One strategy is to write a backend test and wrap the
test case with the profiled decorator.
You can run a single test case like this:
# edit zerver/tests/test_external.py and place @profiled above the test case below
./tools/test-backend zerver.tests.test_external.RateLimitTests.test_ratelimit_decrease
Then view the results like this:
./tools/show-profile-results.py test_ratelimit_decrease.profile
"""
@wraps(func)
def wrapped_func(*args, **kwargs):
# type: (*Any, **Any) -> Any
fn = func.__name__ + ".profile"
prof = cProfile.Profile()
retval = prof.runcall(func, *args, **kwargs) # type: Any
prof.dump_stats(fn)
return retval
return wrapped_func # type: ignore # https://github.com/python/mypy/issues/1927