Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use time elapsed as assertion in unit tests

I am facing a situation in which I want to ensure that if a method is modified it does not takes more than X ms to run (essentially if that function is slower, it will slow down the search results on our web page, and that has a bad impact on sales).

We have unit tests (in particular the code is done under python and we use py.test), the first idea is to assert that if the function did not execute in less than X ms, then mark the test as failed (or raise a warning).

However, this feels dangerous (not all computers are the same speed, for example), and also I am not quite sure that's the job of a unit test.

Has someone faced a similar situation? For me speed is a feature, and I want to ensure that such feature is not lost in the future as the code evolves.

If unit testing is not the answer, which other alternatives would you recommend?

Thanks

like image 676
Juan Antonio Gomez Moriano Avatar asked Aug 30 '12 05:08

Juan Antonio Gomez Moriano


People also ask

What is assertion in unit test?

Assertions replace us humans in checking that the software does what it should. They express requirements that the unit under test is expected to meet. Now, often one can write slightly different assertions to capture a given requirement.

What does the timely rule of unit testing mean?

Timely: Unit tests should be written just before the production code that makes the test pass. This is something that you would follow if you were doing TDD (Test Driven Development), but otherwise it might not apply.

How do you add assertions to a test case?

1. Getting started. So let's begin creating an Assertion TestStep: Right click TestCase then choose Add Step -> Assertion TestStep to open the Assertion TestStep window as shown below.


1 Answers

You could look into using the pytest-timeout plugin for a start. It currently only allows specifying seconds (as floats). But it could be extended to work with more adaptable timings such as pystone numbers so there would be a measurement of how fast your computer performs the pystone benchmark which could be cached and then you'd specify how many "pystones" your test(s) is allowed to take.

like image 147
hpk42 Avatar answered Oct 25 '22 09:10

hpk42