[TIP] Identifying slowest py.test fixtures

Bruno Oliveira nicoddemus at gmail.com
Sat Jul 23 07:42:51 PDT 2016

On Sat, Jul 23, 2016 at 11:29 AM André Caron <andre.l.caron at gmail.com>

> These two new hooks look like what was looking for, so guess that yes,
> this will help a lot :-)  Do you have a ballpark-figure of how soon is
> "soon"?

We are aiming for a release right after EuroPython, probably on the week of
August 1st.

Unfortunately, printing is subject to log capture plug-ins, so it's very
> inconvenient.  I see your example plug-in uses printing as well.

Oh sorry, I meant to demonstrate only how to use the new hooks, certainly
printing is not the way to go.

How would I go about printing a report at the end like the `--durations`
> argument does?  I assume I also need to use the `pytest_terminal_summary()`
> hook, but I'm not sure how to pass info from your example
> `pytest_fixture_setup()` to the reporting function.  Any hints?

You are right, `pytest_terminal_summary` is the best way to approach this.
As to how to pass the information, aside from using global variables you
could implement a plugin class yourself and register it during

class MeasureSetupsPlugin:

    def __init__(self):
        self.elapsed_times = {}

    def pytest_fixture_setup(self, fixturedef, request):
        started = time.time()
        elapsed = time.time() - started
        self.elapsed_times.setdefault(fixturedef.name, []).append(elapsed)

    def pytest_terminal_summary(self, terminalreporter):
        terminalreporter.write_sep("=", "Fixture setup times (max)")
        for name, times in sorted(self.elapsed_times.items()):
            tr.write_line("%s %.3f" % (name, max(times))

def pytest_configure(config):
    config.pluginmanager.register(MeasureSetupsPlugin(), 'measure_setups')

You could decide to display all matter of different statistics during
pytest_terminal_summary, like number of setups, slowest setup, etc.

Hope this helps!

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.idyll.org/pipermail/testing-in-python/attachments/20160723/ed85ffd4/attachment.htm>

More information about the testing-in-python mailing list