blog.dbrgn.ch

Profiling Pytest Tests

written on Monday, September 08, 2014 by

If you want to run a profiler over your pytest cases (including underlying code), the easiest way is to run pytest directly using cPython:

python -m cProfile -o profile $(which py.test)

You can even pass in optional arguments:

python -m cProfile -o profile $(which py.test) \
    tests/worker/test_tasks.py -s campaigns

This will create a binary file called profile in your current directory. The file can then be analyzed with pstats:

import pstats
p = pstats.Stats('profile')
p.strip_dirs()
p.sort_stats('tottime')
p.print_stats(50)

This will print the 50 lines with the longest total duration. You can also sort by other columns, e.g. 'cumtime'.

This entry was tagged profiling, pytest, python and testing