How to benchmark unit tests in Python without adding any code

2024/9/24 13:23:53

I have a Python project with a bunch of tests that have already been implemented, and I'd like to begin benchmarking them so I can compare performance of the code, servers, etc over time. Locating the files in a manner similar to Nose was no problem because I have "test" in the names of all my test files anyway. However, I'm running into some trouble in attempting to dynamically execute these tests.

As of right now, I'm able to run a script that takes a directory path as an argument and returns a list of filepaths like this:

def getTestFiles(directory):fileList = []print "Searching for 'test' in " + directoryif not os.path.isdir(os.path.dirname(directory)):# throw errorraise InputError(directory, "Not a valid directory")else:for root, dirs, files in os.walk(directory):#print filesfor f in files:if "test" in f and f.endswith(".py"):fileList.append(os.path.join(root, f))return fileList# returns a list like this:
# [  'C:/Users/myName/Desktop/example1_test.py',
#    'C:/Users/myName/Desktop/example2_test.py',
#    'C:/Users/myName/Desktop/folder1/example3_test.py',
#    'C:/Users/myName/Desktop/folder2/example4_test.py'...  ]

The issue is that these files can have different syntax, which I'm trying to figure out how to handle. For example:

TestExampleOne:

import dummy1
import dummy2
import dummy3class TestExampleOne(unittest.TestCase):@classmethoddef setUpClass(cls):# set updef test_one(self):# test stuffdef test_two(self):# test stuffdef test_three(self):# test stuff# etc...

TestExampleTwo:

import dummy1
import dummy2
import dummy3def setup(self):try:# config stuffexcept Exception as e:logger.exception(e)def test_one():# test stuff
def test_two():# test stuff
def test_three():# test stuff# etc...

TestExampleThree:

import dummy1
import dummy2
import dummy3def setup(self):try:# config stuffexcept Exception as e:logger.exception(e)class TestExampleTwo(unittest.TestCase):def test_one(self):# test stuffdef test_two(self):# test stuff# etc...class TestExampleThree(unittest.TestCase):def test_one(self):# test stuffdef test_two(self):# test stuff# etc...# etc...

I would really like to be able to write one module that searches a directory for every file containing "test" in its name, and then executes every unit test in each file, providing execution time for each test. I think something like NodeVisitor is on the right track, but I'm not sure. Even an idea of where to start would be greatly appreciated. Thanks

Answer

Using nose test runner would help to discover the tests, setup/teardown functions and methods.

nose-timer plugin would help with benchmarking:

A timer plugin for nosetests that answers the question: how much timedoes every test take?


Demo:

  • imagine you have a package named test_nose with the following scripts inside:

    • test1.py:

      import time
      import unittestclass TestExampleOne(unittest.TestCase):@classmethoddef setUpClass(cls):cls.value = 1def test_one(self):time.sleep(1)self.assertEqual(1, self.value)
      
    • test2.py:

      import timevalue = Nonedef setup():global valuevalue = 1def test_one():time.sleep(2)assert value == 1
      
    • test3.py:

      import time
      import unittestvalue = Nonedef setup():global valuevalue = 1class TestExampleTwo(unittest.TestCase):def test_one(self):time.sleep(3)self.assertEqual(1, value)class TestExampleThree(unittest.TestCase):def test_one(self):time.sleep(4)self.assertEqual(1, value)
      
  • install nose test runner:

    pip install nose
    
  • install nose-timer plugin:

    pip install nose-timer
    
  • run the tests:

    $ nosetests test_nose --with-timer
    ....
    test_nose.test3.TestExampleThree.test_one: 4.0003s
    test_nose.test3.TestExampleTwo.test_one: 3.0010s
    test_nose.test2.test_one: 2.0011s
    test_nose.test1.TestExampleOne.test_one: 1.0005s
    ----------------------------------------------------------------------
    Ran 4 tests in 10.006sOK
    

The result is actually conveniently highlighted: nosetests results

The coloring can be controlled by --timer-ok and --timer-warning arguments.

Note that time.sleep(n) calls were added for making the manual slowdowns to see the impact clearly. Also note that value variable is set to 1 in "setup" functions and methods, then in test function and methods the value is asserted to be 1 - this way you can see the work of setup functions.

UPD (running nose with nose-timer from script):

from pprint import pprint
import nose
from nosetimer import pluginplugin = plugin.TimerPlugin()
plugin.enabled = True
plugin.timer_ok = 1000
plugin.timer_warning = 2000
plugin.timer_no_color = Falsenose.run(plugins=[plugin])
result = plugin._timed_tests
pprint(result)

Save it into the test.py script and pass a target directory to it:

python test.py /home/example/dir/tests --with-timer

The result variable would contain:

{'test_nose.test1.TestExampleOne.test_one': 1.0009748935699463,'test_nose.test2.test_one': 2.0003929138183594,'test_nose.test3.TestExampleThree.test_one': 4.000233173370361,'test_nose.test3.TestExampleTwo.test_one': 3.001115083694458}
https://en.xdnf.cn/q/71695.html

Related Q&A

Digit recognition with Tesseract OCR and python

I use Tesseract and python to read digits (from a energy meter). Everything works well except for the number "1". Tesseract can not read the "1" Digit.This is the picture I send t…

Pycharm not recognizing packages even when __init__.py exits

This is my directory structure--> ProjectDirectory-->__init__.py--> BaseDirectory-->__init__.py--> AnotherBaseDirectory-->__init__.py-->program.pyinside program.pyWhen i give impor…

Scrapy is following and scraping non-allowed links

I have a CrawlSpider set up to following certain links and scrape a news magazine where the links to each issue follow the following URL scheme:http://example.com/YYYY/DDDD/index.htm where YYYY is the …

Overriding virtual methods in PyGObject

Im trying to implement the Heigh-for-width Geometry Management in GTK with Python for my custom Widget. My widget is a subclass from Gtk.DrawingArea and draws some parts of an Image.As I understood the…

How to find if two numbers are consecutive numbers in gray code sequence

I am trying to come up with a solution to the problem that given two numbers, find if they are the consecutive numbers in the gray code sequence i.e., if they are gray code neighbors assuming that the …

How do I get data from selected points in an offline plotly python jupyter notebook?

Example code:from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplotimport plotly.graph_objs as goimport numpy as npN = 30 random_x = np.random.randn(N) random_y = np.random.randn…

Set background colour for a custom QWidget

I am attempting to create a custom QWidget (from PyQt5) whose background colour can change. However, all the standard methods of setting the background colour do not seem to work for a custom QWidget c…

Plotly: How to set up a color palette for a figure created with multiple traces?

I using code below to generate chart with multiple traces. However the only way that i know to apply different colours for each trace is using a randon function that ger a numerico RGB for color. But r…

Which implementation of OrderedDict should be used in python2.6?

As some of you may know in python2.7/3.2 well get OrderedDict with PEP372 however one of the reason the PEP existed was because everyone did their own implementation and they were all sightly incompati…

Signal Handling in Windows

In Windows I am trying to create a python process that waits for SIGINT signal.And when it receives SIGINT I want it to just print a message and wait for another occurrence of SIGINT.So I used signal h…