diff --git a/docs/usage.rst b/docs/usage.rst index a4054fdc..5160b09b 100644 --- a/docs/usage.rst +++ b/docs/usage.rst @@ -56,6 +56,11 @@ By default nox will run all sessions defined in the noxfile. However, you can ch nox -s lint tests nox -e lint +You can also use the ``NOXSESSION`` environment variable:: + + NOXSESSION=lint nox + NOXSESSION=lint,tests nox + Nox will run these sessions in the same order they are specified. You can also use `pytest-style keywords`_ to filter test sessions:: diff --git a/nox/__main__.py b/nox/__main__.py index 1362774d..37578b83 100644 --- a/nox/__main__.py +++ b/nox/__main__.py @@ -68,6 +68,7 @@ def main(): "-e", "--sessions", nargs="*", + default=_get_default_sessions(), help="Which sessions to run, by default, all sessions will run.", ) parser.add_argument( @@ -136,5 +137,11 @@ def main(): sys.exit(exit_code) +def _get_default_sessions(): + nox_env = os.environ.get("NOXSESSION") + env_sessions = nox_env.split(",") if nox_env else None + return env_sessions + + if __name__ == "__main__": # pragma: no cover main() diff --git a/tests/test_main.py b/tests/test_main.py index 598ee30f..97081d28 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -19,6 +19,7 @@ import contexter import pkg_resources +import pytest import nox import nox.__main__ @@ -59,7 +60,9 @@ def test_global_config_constructor(): assert config.posargs == ["a", "b", "c"] -def test_main_no_args(): +def test_main_no_args(monkeypatch): + # Prevents any interference from outside + monkeypatch.delenv("NOXSESSION", raising=False) sys.argv = [sys.executable] with mock.patch("nox.workflow.execute") as execute: execute.return_value = 0 @@ -146,6 +149,28 @@ def test_main_explicit_sessions(): assert config.sessions == ["1", "2"] +@pytest.mark.parametrize( + "env,sessions", [("foo", ["foo"]), ("foo,bar", ["foo", "bar"])] +) +def test_main_session_from_nox_env_var(monkeypatch, env, sessions): + monkeypatch.setenv("NOXSESSION", env) + sys.argv = [sys.executable] + with mock.patch("nox.workflow.execute") as execute: + execute.return_value = 0 + + # Call the main function. + with mock.patch.object(sys, "exit") as exit: + nox.__main__.main() + exit.assert_called_once_with(0) + assert execute.called + + # Verify that the sessions from the env var are listed in the config. + config = execute.call_args[1]["global_config"] + assert len(config.sessions) == len(sessions) + for session in sessions: + assert session in config.sessions + + def test_main_positional_args(): sys.argv = [sys.executable, "1", "2", "3"] with mock.patch("nox.workflow.execute") as execute: