diff --git a/CHANGELOG b/CHANGELOG index aa7a5a4..1e212b6 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,9 @@ -1.14.1.dev +1.15.0.dev ---------- +- new ``worker_id`` fixture, returns the id of the worker in a test or fixture. + Thanks Jared Hellman for the PR. + 1.14 ---- diff --git a/README.rst b/README.rst index 54c72e4..04452cb 100644 --- a/README.rst +++ b/README.rst @@ -185,6 +185,19 @@ at once. The specifications strings use the `xspec syntax`_. .. _`execnet`: http://codespeak.net/execnet +Identifying the worker process during a test ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ +If you need to determine the identity of a worker process in +a test or fixture, you may use the ``worker_id`` fixture to do so:: + + @pytest.fixture() + def user_account(worker_id): + """ use a different account in each xdist worker """ + return "account_%s" % worker_id + +When ``xdist`` is disabled (running with ``-n0`` for example), then +``worker_id`` will return ``"master"``. + Specifying test exec environments in an ini file +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ diff --git a/testing/acceptance_test.py b/testing/acceptance_test.py index c52a6da..9ba158b 100644 --- a/testing/acceptance_test.py +++ b/testing/acceptance_test.py @@ -620,3 +620,25 @@ class TestNodeFailure: "*Slave*crashed while running*", "*1 failed*2 passed*", ]) + + +@pytest.mark.parametrize('n', [0, 2]) +def test_worker_id_fixture(testdir, n): + import glob + f = testdir.makepyfile(""" + import pytest + @pytest.mark.parametrize("run_num", range(2)) + def test_worker_id1(worker_id, run_num): + with open("worker_id%s.txt" % run_num, "w") as f: + f.write(worker_id) + """) + result = testdir.runpytest(f, "-n%d" % n) + result.stdout.fnmatch_lines('* 2 passed in *') + worker_ids = set() + for fname in glob.glob(str(testdir.tmpdir.join("*.txt"))): + with open(fname) as f: + worker_ids.add(f.read().strip()) + if n == 0: + assert worker_ids == set(['master']) + else: + assert worker_ids == set(['gw0', 'gw1']) diff --git a/xdist/plugin.py b/xdist/plugin.py index 69c3a9b..c232a5e 100644 --- a/xdist/plugin.py +++ b/xdist/plugin.py @@ -99,3 +99,15 @@ def pytest_cmdline_main(config): if usepdb: raise pytest.UsageError( "--pdb incompatible with distributing tests.") + +# ------------------------------------------------------------------------- +# fixtures +# ------------------------------------------------------------------------- + + +@pytest.fixture(scope="session") +def worker_id(request): + if hasattr(request.config, 'slaveinput'): + return request.config.slaveinput['slaveid'] + else: + return 'master'