Skip to content
Permalink
Browse files

implements #129 in unittest class (profiling)

  • Loading branch information...
sdpython committed Apr 17, 2018
1 parent 76149b9 commit 72d0a4495a28f79335831d472ead67c0ab1a3df9
Showing with 49 additions and 2 deletions.
  1. +17 −2 _unittests/ut_pycode/test_extunittest.py
  2. +32 −0 src/pyquickhelper/pycode/unittestclass.py
@@ -1,12 +1,11 @@
"""
@brief test tree node (time=5s)
"""


import sys
import os
import unittest
import warnings
import pandas

try:
import src
@@ -22,6 +21,8 @@
import src

from src.pyquickhelper.pycode import ExtTestCase
from src.pyquickhelper.pandashelper import df2rst
from src.pyquickhelper import __file__ as rootfile

if sys.version_info[0] == 2:
FileNotFoundError = Exception
@@ -186,6 +187,20 @@ def test_assertEqualNumber(self):
self.assertRaise(lambda: self.assertEqualNumber(1.1, "1.2"),
TypeError)

def test_profile(self):

def simple():
df = pandas.DataFrame([{"A": "x", "AA": "xx", "AAA": "xxx"},
{"AA": "xxxxxxx", "AAA": "xxx"}])
return df2rst(df)

rootrem = os.path.normpath(os.path.abspath(
os.path.join(os.path.dirname(rootfile), '..')))
ps, res = self.profile(simple, rootrem=rootrem)
res = res.replace('\\', '/')
self.assertIn('pyquickhelper/pandashelper/tblformat.py', res)
self.assertNotEmpty(ps)


if __name__ == "__main__":
unittest.main()
@@ -9,9 +9,17 @@
import unittest
import warnings
import decimal
import cProfile
import pstats
import site
from .ci_helper import is_travis_or_appveyor
from ..loghelper import fLOG

try:
from io import StringIO
except ImportError:
from StringIO import StringIO


class ExtTestCase(unittest.TestCase):
"""
@@ -313,6 +321,30 @@ def fLOG(self, *args, **kwargs):
"""
fLOG(*args, **kwargs)

def profile(self, fct, sort='cumulative', rootrem=None):
"""
Profiles the execution of a function.
@param fct function to profile
@param sort see `sort_stats <https://docs.python.org/3/library/profile.html#pstats.Stats.sort_stats>`_
@param rootrem root to remove in filenames
@return statistics text dump
"""
pr = cProfile.Profile()
pr.enable()
fct()
pr.disable()
s = StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats(sort)
ps.print_stats()
res = s.getvalue()
pack = site.getsitepackages()
res = res.replace(pack[-1], "site-packages")
if rootrem is not None:
res = res.replace(rootrem, '')

return ps, res


def skipif_appveyor(msg):
"""

0 comments on commit 72d0a44

Please sign in to comment.
You can’t perform that action at this time.