Package: pytest-random-order
pytest-random-orderis apytestplugin that randomises the order of tests.
This can be useful to detect a test that passes just because it happens to run after an unrelated test that
leaves the system in afavourablestate.The plugin allows user to control the level of randomness they want to introduce and to disable
reordering on subsets of tests. Tests can be rerun in a specific order by passing a seed value reported
in a previous test run.Quick StartInstallation:$ pip install pytest-random-orderFrom v1.0.0 onwards,this plugin no longer randomises tests by default. To enable randomisation, you have to run
pytest in one of the following ways:pytest --random-order
pytest --random-order-bucket=<bucket_type>
pytest --random-order-seed=<seed>If you want to always randomise the order of tests, configure pytest. There are many ways to do it,
my favourite one is to addaddopts =--random-orderin your project-specific configuration file
under the pytest options (usually[pytest]or[tool:pytest]section).Alternatively, you can set environment variablePYTEST_ADDOPTS:export PYTEST_ADDOPTS="--random-order"To randomise the order of tests within modules and shuffle the order of
test modules (which is the default behaviour of the plugin), run pytest as follows:$ pytest --random-orderTo change the scope of re-ordering, run pytest with--random-order-bucket=<bucket-type>option
where<bucket-type>can beclass,module,package,global:$ pytest -v --random-order-bucket=packageTo disable reordering of tests in a module or class, use pytest marker notation:pytestmark = pytest.mark.random_order(disabled=True)To rerun tests in a particular order:$ pytest -v --random-order-seed=<seed>All runs in which the randomisation is enabled report seed so if you encounter a specific ordering of tests
that causes problems you can look up the value in the test report and repeat the run with the above command.platform darwin -- Python 3.5.6, pytest-3.9.1, py-1.7.0, pluggy-0.8.0
Using --random-order-bucket=module
Using --random-order-seed=383013DesignThe plugin groups tests in buckets, shuffles them within buckets and then shuffles the buckets.Given the test suite above, here are two of a few possible generated orders of tests:You can choose from a few types of buckets:classTests will be shuffled within a class and classes will be shuffled,
but tests from one class will never have tests from other classes or modules run in-between them.moduleSame as above at module level. This is the setting applied if you run pytest with just--random-orderflag
or--random-order-seed=<seed>.packageSame as above at package level. Note that modules (and hence tests inside those modules) that
belong to packagex.y.zdo not belong to packagex.y, so they will fall in different buckets
when randomising withpackagebucket type.parentIf you are using custom test items which don’t belong to any module, you can use this to
limit reordering of test items to within theparentto which they belong. For normal test
functions the parent is the module in which they are declared.grandparentSimilar toparentabove, but use the parent of the parent of the test item as the bucket key instead.globalAll tests fall in the same bucket, full randomness, tests probably take longer to run.none (deprecated)Disable shuffling.Deprecated since 1.0.4 because this plugin no longer shuffles tests by default
so there is nothing to disable.If you have three buckets of testsA,B, andCwith three tests1and2, and3in each of them,
then one of many potential orderings that non-global randomisation can produce could be:c2, c1, c3, a3, a1, a2, b3, b2, b1As you can see, all C tests are executed “next” to each other and so are tests in buckets A and B.
Tests from any bucket X are guaranteed to not be interspersed with tests from another bucket Y.
For example, if you choose bucket typemodulethen bucket X contains all tests that are in this module.By default, when randomisation is enabled, your tests will be randomised atmodulelevel which means that
tests within a single module X will be executed in no particular order, but tests from
other modules will not be mixed in between tests of module X.The randomised reordering can be disabled per module or per class irrespective of the chosen bucket type.Usage and TipsBucket Type ChoiceIt is best to start with smallest bucket type (classormoduledepending on whether you have class-based tests),
and switch to a larger bucket type when you are sure your tests handle that.If your tests rely on fixtures that are module or session-scoped, more randomised order of tests will mean slower tests.
You probably don’t want to randomise atglobalorpackagelevel while you are coding and need a quick confirmation
that nothing big is broken.Disable Shuffling in Module or ClassYou can disable shuffling of tests within a single module or class by marking the module or class
withrandom_ordermarker and passingdisabled=Trueto it:pytestmark = pytest.mark.random_order(disabled=True)

def test_number_one():
    assert True

def test_number_two():
    assert Trueclass MyTest(TestCase):
    pytestmark = pytest.mark.random_order(disabled=True)

    def test_number_one(self):
        self.assertTrue(True)No matter what will be the bucket type for the test run,test_number_onewill always run
beforetest_number_two.Rerun Tests in the Same Order (Same Seed)If you discover a failing test because you reordered tests, you will probably want to be able to rerun the tests
in the same failing order. To allow reproducing test order, the plugin reports the seed value it used with pseudo random number
generator:============================= test session starts ==============================
..
Using --random-order-bucket=module
Using --random-order-seed=24775
...You can now use the--random-order-seed=...bit as an argument to the next run to produce the same order:$ pytest -v --random-order-seed=24775Run Last Failed Tests FirstSince v0.8.0 pytest cache plugin’s--failed-firstflag is supported – tests that failed in the last run
will be run before tests that passed irrespective of shuffling bucket type.Disable the PluginIf the plugin misbehaves or you just want to assure yourself that it is not the plugin making your tests fail or
pass undeservedly, you can disable it:$ pytest -p no:random_orderNote that randomisation is disabled by default. By passing-pno:random_orderyou are stopping the plugin
from being registered so its hooks won’t be registered and its command line options won’t appear in--help.Changelogv1.1.1 (2024-01-20)Fixes #54 -AttributeErrorwhen cacheprovider plugin disabled. Thanks @jhanm12v1.1.0 (2022-12-03)Fixes xdist support (thanks @matejsp)v1.0.4 (2018-11-30)Fixes issues with doctests reported in #36 -class,packageandmoduledidn’t work
becauseDoctestItemdoesn’t haveclsormoduleattributes. Thanks @tobywf.Deprecatenonebucket type.With tox, run tests of pytest-random-order with both pytest 3 and 4.v1.0.3 (2018-11-16)Fixes compatibility issues with pytest 4.0.0, works with pytest 3.0+ as before.Tests included in the source distribution.v1.0.0 (2018-10-20)Plugin no longer alters the test order by default. You will have to either 1) pass--random-order,
or--random-order-bucket=<bucket>, or--random-order-seed=<seed>, or
2) edit your pytest configuration file and add one of these options
there underaddopts, or 3) specify these flags in environment variablePYTEST_ADDOPTS.Python 3.5+ is required. If you want to use this plugin with Python 2.7, use v0.8.0 which is stable and fine
if you are happy with it randomising the test order by default.The name under which the plugin registers itself is changed fromrandom-order(hyphen) torandom_order(underscore). This addresses the issue of consistency when disabling or enabling this plugin via the standard-pflag. Previously, the plugin could be disabled by passing-pno:random-orderyet re-enabled
only by passing-ppytest_random_order.plugin. Now they are-pno:random_orderto disable and-prandom_order.pluginto enable (The.pluginbit, I think, is required because
pytest probably thinks it’s an unrelated thing torandom_orderand import it, yet without it it’s the
same thing so doesn’t import it).v0.8.0pytest cache plugin’s--failed-firstworks now.CreditsThe shuffle icon in the diagram is by artistDaniele De Santisand it was found oniconarchive.The diagram is drawn withsketchboard.io