Skip to content

Commit 1e10d21

Browse files
author
Sylvain MARIE
committed
New methods is_xdist_worker, is_xdist_master, get_xdist_worker_id. Fixes pytest-dev#504
1 parent 6fd5b56 commit 1e10d21

File tree

2 files changed

+41
-6
lines changed

2 files changed

+41
-6
lines changed

src/xdist/__init__.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
from xdist.plugin import is_xdist_worker, is_xdist_master, get_xdist_worker_id
12
from xdist._version import version as __version__
23

3-
__all__ = ["__version__"]
4+
__all__ = ['__version__',
5+
'is_xdist_worker', 'is_xdist_master', 'get_xdist_worker_id']

src/xdist/plugin.py

+38-5
Original file line numberDiff line numberDiff line change
@@ -201,16 +201,49 @@ def pytest_cmdline_main(config):
201201

202202

203203
# -------------------------------------------------------------------------
204-
# fixtures
204+
# fixtures and API to easily know the role of current node
205205
# -------------------------------------------------------------------------
206206

207+
def is_xdist_worker(request_or_session):
208+
"""Return `True` if this is an xdist worker, `False` otherwise
207209
208-
@pytest.fixture(scope="session")
209-
def worker_id(request):
210+
:param request_or_session: the `pytest` `request` or `session` object
211+
:return:
212+
"""
213+
return hasattr(request_or_session.config, "workerinput")
214+
215+
216+
def is_xdist_master(request_or_session):
217+
"""Return `True` if this is the xdist master, `False` otherwise
218+
219+
Note: this method also returns `False` when distribution has not been
220+
activated at all.
221+
222+
:param request_or_session: the `pytest` `request` or `session` object
223+
:return:
224+
"""
225+
return (not is_xdist_worker(request_or_session)
226+
and request_or_session.config.option.dist != "no")
227+
228+
229+
def get_xdist_worker_id(request_or_session):
210230
"""Return the id of the current worker ('gw0', 'gw1', etc) or 'master'
211231
if running on the master node.
232+
233+
:param request_or_session: the `pytest` `request` or `session` object
234+
:return:
212235
"""
213-
if hasattr(request.config, "workerinput"):
214-
return request.config.workerinput["workerid"]
236+
if hasattr(request_or_session.config, "workerinput"):
237+
return request_or_session.config.workerinput["workerid"]
215238
else:
239+
# TODO shall we raise an exception if dist is not enabled ?
240+
# i.e. `not is_xdist_master(request_or_session)` ?
216241
return "master"
242+
243+
244+
@pytest.fixture(scope="session")
245+
def worker_id(request):
246+
"""Return the id of the current worker ('gw0', 'gw1', etc) or 'master'
247+
if running on the master node.
248+
"""
249+
return get_xdist_worker_id(request)

0 commit comments

Comments
 (0)