Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I repeat each test multiple times in a py.test run?

Tags:

python

pytest

I want to run each selected py.test item an arbitrary number of times, sequentially.
I don't see any standard py.test mechanism for doing this.

I attempted to do this in the pytest_collection_modifyitems() hook. I modified the list of items passed in, to specify each item more than once. The first execution of a test item works as expected, but that seems to cause some problems for my code.

Further, I would prefer to have a unique test item object for each run, as I use id (item) as a key in various reporting code. Unfortunately, I can't find any py.test code to duplicate a test item, copy.copy() doesn't work, and copy.deepcopy() gets an exception.

Can anybody suggest a strategy for executing a test multiple times?

like image 597
Martin Del Vecchio Avatar asked Feb 13 '14 20:02

Martin Del Vecchio


People also ask

How do you run failed test cases in pytest?

The plugin provides two command line options to rerun failures from the last pytest invocation: --lf , --last-failed - to only re-run the failures. --ff , --failed-first - to run the failures first and then the rest of the tests.

What is pytest mark?

Pytest allows us to use markers on test functions. Markers are used to set various features/attributes to test functions. Pytest provides many inbuilt markers such as xfail, skip and parametrize. Apart from that, users can create their own marker names.

What are pytest plugins?

pytest comes with a plugin named pytester that helps you write tests for your plugin code. The plugin is disabled by default, so you will have to enable it before you can use it. Alternatively you can invoke pytest with the -p pytester command line option.


2 Answers

One possible strategy is parameterizing the test in question, but not explicitly using the parameter.

For example:

@pytest.mark.parametrize('execution_number', range(5)) def run_multiple_times(execution_number):     assert True 

The above test should run five times.

Check out the parametrization documentation: https://pytest.org/latest/parametrize.html

like image 163
Frank T Avatar answered Sep 19 '22 06:09

Frank T


The pytest module pytest-repeat exists for this purpose, and I recommend using modules where possible, rather than re-implementing their functionality yourself.

To use it simply add pytest-repeat to your requirements.txt or pip install pytest-repeat, then execute your tests with --count n.

like image 25
jsj Avatar answered Sep 19 '22 06:09

jsj