diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index ccc8eab83..c98b8b4ec 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Reads deployment settings from `[tool.posit.connect]` in `pyproject.toml` and generates it in quickstart projects. The legacy `[tool.rsconnect]` name remains supported with a deprecation warning. + ### Fixed - Follows symlinks when bundling content: linked files are archived with their target contents and linked directories are included, instead of archiving broken links or omitting the directories. [#955](https://github.com/posit-dev/rsconnect-python/pull/955) diff --git a/docs/deploying.md b/docs/deploying.md index 9f2d62ac2..bbc7113aa 100644 --- a/docs/deploying.md +++ b/docs/deploying.md @@ -354,13 +354,14 @@ type and dependencies. The options are the same as for `deploy manifest`; see ### Deploying from a pyproject.toml -`rsconnect deploy pyproject` reads a `[tool.rsconnect]` table from a project's +`rsconnect deploy pyproject` reads a `[tool.posit.connect]` table from a project's `pyproject.toml` instead of taking the app mode and entrypoint as CLI arguments. It is designed as the deploy partner for projects scaffolded by `rsconnect quickstart`, but works with any project whose `pyproject.toml` -contains the required keys. +contains the required keys. The deprecated `[tool.rsconnect]` table is also accepted; +rename it to `[tool.posit.connect]`. Use only one of the two tables. -The `[tool.rsconnect]` table has two required keys: +The `[tool.posit.connect]` table has two required keys: - `app_mode` — the Connect app mode the deployment uses. Supported values are `python-streamlit`, `python-shiny`, `python-fastapi`, `python-api`, @@ -380,7 +381,7 @@ version = "0.1.0" requires-python = ">=3.9" dependencies = ["streamlit"] -[tool.rsconnect] +[tool.posit.connect] app_mode = "python-streamlit" entrypoint = "app.py" ``` diff --git a/rsconnect/main.py b/rsconnect/main.py index 85c87292f..78f11cd1c 100644 --- a/rsconnect/main.py +++ b/rsconnect/main.py @@ -2029,7 +2029,7 @@ def info(file: str): "Create a new Posit Connect project of the given TYPE in .//. " "Supported TYPE values: streamlit, shiny, fastapi, api, flask, " "notebook, voila, quarto. Writes a pyproject.toml " - "with a [tool.rsconnect] section, creates a uv-managed virtualenv, " + "with a [tool.posit.connect] section, creates a uv-managed virtualenv, " "and prints the local-run and deploy commands." ), no_args_is_help=True, @@ -2727,7 +2727,7 @@ def deploy_bundle( short_help="Deploy content to Posit Connect, Posit Connect Cloud, or shinyapps.io by pyproject.", help=( "Deploy content described by a project's pyproject.toml. The given directory must contain " - "a pyproject.toml with a [tool.rsconnect] table specifying app_mode and entrypoint. " + "a pyproject.toml with a [tool.posit.connect] table specifying app_mode and entrypoint. " "Designed as the deploy partner for projects scaffolded by 'rsconnect quickstart'." ), no_args_is_help=True, @@ -2744,7 +2744,7 @@ def deploy_bundle( default=None, help=( "Path to the requirements source, relative to the project directory. " - "Overrides ``[tool.rsconnect].requirements_file`` in pyproject.toml; " + "Overrides ``[tool.posit.connect].requirements_file`` in pyproject.toml; " "defaults to ``pyproject.toml`` (the project's declared dependencies). " "Pass ``uv.lock`` for a fully resolved deploy, or any ``requirements.txt``-compatible file." ), @@ -2903,7 +2903,7 @@ def quickstart_hint() -> str: "r_environment": r_environment, } else: - raise RSConnectException(f"Unsupported app_mode '{target.configured_app_mode}' in [tool.rsconnect]") + raise RSConnectException(f"Unsupported app_mode '{target.configured_app_mode}' in {target.table}") ce = RSConnectExecutor( ctx=ctx, @@ -4364,7 +4364,7 @@ def write_manifest_quarto( short_help="Create a manifest.json file from a project's pyproject.toml.", help=( "Create a manifest.json file for later deployment, for content described by a project's " - "pyproject.toml. The given directory must contain a pyproject.toml with a [tool.rsconnect] " + "pyproject.toml. The given directory must contain a pyproject.toml with a [tool.posit.connect] " "table specifying app_mode and entrypoint. This will also write the environment file the " 'manifest references (e.g. "requirements.txt"), regenerating it on each run unless it is ' "itself the requirements source. Designed as the write-manifest partner for projects " @@ -4380,7 +4380,7 @@ def write_manifest_quarto( default=None, help=( "Path to the requirements source, relative to the project directory. " - "Overrides ``[tool.rsconnect].requirements_file`` in pyproject.toml; " + "Overrides ``[tool.posit.connect].requirements_file`` in pyproject.toml; " "defaults to ``pyproject.toml`` (the project's declared dependencies). " "Pass ``uv.lock`` for a fully resolved manifest, or any ``requirements.txt``-compatible file." ), @@ -4440,7 +4440,7 @@ def quickstart_hint() -> str: AppModes.SHINY_QUARTO, ) if app_mode not in api_modes and app_mode not in entrypoint_manifest_modes: - raise RSConnectException(f"Unsupported app_mode '{target.configured_app_mode}' in [tool.rsconnect]") + raise RSConnectException(f"Unsupported app_mode '{target.configured_app_mode}' in {target.table}") with cli_feedback("Checking arguments"): # The bundle.py writers put manifest.json in different places: API modes diff --git a/rsconnect/pyproject.py b/rsconnect/pyproject.py index 5c03d41a1..10c881797 100644 --- a/rsconnect/pyproject.py +++ b/rsconnect/pyproject.py @@ -187,71 +187,87 @@ class InvalidVersionConstraintError(ValueError): class InvalidPyprojectConfigError(ValueError): - """Raised when ``[tool.rsconnect]`` is missing or incomplete.""" + """Raised when the deployment table is missing or incomplete.""" class UnsupportedAppModeError(ValueError): - """Raised when ``[tool.rsconnect].app_mode`` names an app mode rsconnect does not know. + """Raised when the configured app mode is unknown. Kept distinct from :class:`InvalidPyprojectConfigError` because the CLI does not append the quickstart hint for this failure. """ -_MINIMUM_VALID_TOOL_RSCONNECT_SNIPPET = """[tool.rsconnect] +_MINIMUM_VALID_TOOL_SNIPPET = """[tool.posit.connect] # e.g. python-streamlit, python-shiny, python-fastapi, jupyter-static, quarto-shiny app_mode = "" entrypoint = "" # e.g. app.py""" +_PYPROJECT_APP_MODES = ( + AppModes.STREAMLIT_APP, + AppModes.PYTHON_SHINY, + AppModes.PYTHON_FASTAPI, + AppModes.PYTHON_API, + AppModes.JUPYTER_NOTEBOOK, + AppModes.JUPYTER_VOILA, + AppModes.STATIC_QUARTO, + AppModes.SHINY_QUARTO, +) + def read_tool_rsconnect(pyproject_file: pathlib.Path) -> typing.Mapping[str, typing.Any]: - """Read the ``[tool.rsconnect]`` deployment config from pyproject.toml. + """Read the deployment config from the supported pyproject.toml tables.""" + return _read_deployment_config(pyproject_file)[1] - Returns the section mapping unchanged so forward-compatible fields pass - through. Raises ``InvalidPyprojectConfigError`` when the section is - missing or when required ``app_mode`` / ``entrypoint`` fields are absent or - not non-empty strings. - """ + +def _read_deployment_config(pyproject_file: pathlib.Path) -> typing.Tuple[str, typing.Mapping[str, typing.Any]]: content = pyproject_file.read_text(encoding="utf-8-sig") pyproject = tomllib.loads(content) - tool = pyproject.get("tool") - if tool is None: + if tool is not None and not isinstance(tool, Mapping): + raise InvalidPyprojectConfigError(f"[tool] is not a TOML table. Add at least:\n\n{_MINIMUM_VALID_TOOL_SNIPPET}") + tool = typing.cast(typing.Mapping[str, typing.Any], tool or {}) + posit = tool.get("posit", {}) + if not isinstance(posit, Mapping): raise InvalidPyprojectConfigError( - f"The [tool.rsconnect] section is missing. Add at least:\n\n{_MINIMUM_VALID_TOOL_RSCONNECT_SNIPPET}" + f"[tool.posit] is not a TOML table. Add at least:\n\n{_MINIMUM_VALID_TOOL_SNIPPET}" ) - if not isinstance(tool, Mapping): + posit = typing.cast(typing.Mapping[str, typing.Any], posit) + if "connect" in posit and "rsconnect" in tool: raise InvalidPyprojectConfigError( - f"[tool.rsconnect] is not a TOML table. Add at least:\n\n{_MINIMUM_VALID_TOOL_RSCONNECT_SNIPPET}" + "Both [tool.posit.connect] and [tool.rsconnect] are present. Keep only one table." ) - tool = typing.cast(typing.Mapping[str, typing.Any], tool) - - tool_rsconnect = tool.get("rsconnect") - if tool_rsconnect is None: + if "connect" in posit: + table = "[tool.posit.connect]" + config = posit["connect"] + elif "rsconnect" in tool: + table = "[tool.rsconnect]" + config = tool["rsconnect"] + else: raise InvalidPyprojectConfigError( - f"The [tool.rsconnect] section is missing. Add at least:\n\n{_MINIMUM_VALID_TOOL_RSCONNECT_SNIPPET}" + f"The [tool.posit.connect] section is missing; [tool.rsconnect] is also accepted. " + f"Add at least:\n\n{_MINIMUM_VALID_TOOL_SNIPPET}" ) - if not isinstance(tool_rsconnect, Mapping): + + if not isinstance(config, Mapping): raise InvalidPyprojectConfigError( - f"[tool.rsconnect] is not a TOML table. Add at least:\n\n{_MINIMUM_VALID_TOOL_RSCONNECT_SNIPPET}" + f"{table} is not a TOML table. Add at least:\n\n{_MINIMUM_VALID_TOOL_SNIPPET}" ) - tool_rsconnect = typing.cast(typing.Mapping[str, typing.Any], tool_rsconnect) - + config = typing.cast(typing.Mapping[str, typing.Any], config) for field in ("app_mode", "entrypoint"): - value = tool_rsconnect.get(field) + value = config.get(field) if not isinstance(value, str) or not value: raise InvalidPyprojectConfigError( - f"The [tool.rsconnect] field {field} must be a non-empty string. Add at least:\n\n" - f"{_MINIMUM_VALID_TOOL_RSCONNECT_SNIPPET}" + f"The {table} field {field} must be a non-empty string. Add at least:\n\n{_MINIMUM_VALID_TOOL_SNIPPET}" ) - - return tool_rsconnect + return table, config @dataclasses.dataclass(frozen=True) class PyprojectDeployTarget: - """Deployment configuration resolved from ``[tool.rsconnect]`` in pyproject.toml.""" + """Deployment configuration resolved from pyproject.toml.""" + table: str app_mode: AppMode # The app_mode string as written in pyproject.toml; may be an alias of # app_mode.name() and is what error messages should quote back to the user. @@ -266,7 +282,7 @@ def resolve_pyproject_deploy_target( requirements_file: typing.Optional[str] = None, title_override: typing.Optional[str] = None, ) -> PyprojectDeployTarget: - """Resolve the deployment target described by ``[tool.rsconnect]`` in pyproject.toml. + """Resolve the deployment target described in pyproject.toml. Raises ``InvalidPyprojectConfigError`` when the config is missing or incomplete, and ``UnsupportedAppModeError`` when ``app_mode`` does not name @@ -274,24 +290,28 @@ def resolve_pyproject_deploy_target( :param pathlib.Path pyproject_file: path to the project's pyproject.toml. :param typing.Optional[str] requirements_file: caller override for the - requirements source; wins over ``[tool.rsconnect].requirements_file``. + requirements source; wins over the configured ``requirements_file``. :param typing.Optional[str] title_override: fallback title used when the config declares none. """ - config = read_tool_rsconnect(pyproject_file) + table, config = _read_deployment_config(pyproject_file) configured_app_mode = typing.cast(str, config["app_mode"]) app_mode = AppModes.get_by_name(configured_app_mode, return_unknown=True) - if app_mode == AppModes.UNKNOWN: - raise UnsupportedAppModeError(f"Unsupported app_mode '{configured_app_mode}' in [tool.rsconnect]") + if app_mode not in _PYPROJECT_APP_MODES: + raise UnsupportedAppModeError(f"Unsupported app_mode '{configured_app_mode}' in {table}") + + if table == "[tool.rsconnect]": + logger.warning("[tool.rsconnect] is deprecated. Rename it to [tool.posit.connect].") # Requirements source precedence: caller override (the ``-r`` flag) > - # ``[tool.rsconnect].requirements_file`` > built-in default ``pyproject.toml`` + # configured ``requirements_file`` > built-in default ``pyproject.toml`` # (top-level deps; Connect resolves transitive). An explicit default keeps the # inspector from falling back to a ``pip freeze`` of the caller's interpreter. # Malformed TOML values (wrong type, missing file) are surfaced by the # inspector / file existence check. return PyprojectDeployTarget( + table=table, app_mode=app_mode, configured_app_mode=configured_app_mode, entrypoint=typing.cast(str, config["entrypoint"]), diff --git a/rsconnect/quickstart/quickstart.py b/rsconnect/quickstart/quickstart.py index 4f9ee9dcf..b902ea345 100644 --- a/rsconnect/quickstart/quickstart.py +++ b/rsconnect/quickstart/quickstart.py @@ -168,7 +168,7 @@ def _require_cwd_writable(cwd: pathlib.Path) -> None: # # The registry is the single source of truth that ties together what each # supported mode produces: the canonical Connect ``app_mode`` written to -# ``[tool.rsconnect]``, the entrypoint form, the local-run command +# ``[tool.posit.connect]``, the entrypoint form, the local-run command # documented in the post-scaffold stdout and the README, the minimum # dependencies for the hello-world, and the source files the per-mode # template materializes. diff --git a/rsconnect/quickstart/templates/api/pyproject.toml.tmpl b/rsconnect/quickstart/templates/api/pyproject.toml.tmpl index 8932dda39..ff09e98cb 100644 --- a/rsconnect/quickstart/templates/api/pyproject.toml.tmpl +++ b/rsconnect/quickstart/templates/api/pyproject.toml.tmpl @@ -6,7 +6,7 @@ dependencies = [ "flask", ] -[tool.rsconnect] +[tool.posit.connect] app_mode = "python-api" entrypoint = "$name.__connect__:app" title = "$name" diff --git a/rsconnect/quickstart/templates/fastapi/pyproject.toml.tmpl b/rsconnect/quickstart/templates/fastapi/pyproject.toml.tmpl index 7a5b2899f..8ae1aa2df 100644 --- a/rsconnect/quickstart/templates/fastapi/pyproject.toml.tmpl +++ b/rsconnect/quickstart/templates/fastapi/pyproject.toml.tmpl @@ -7,7 +7,7 @@ dependencies = [ "uvicorn", ] -[tool.rsconnect] +[tool.posit.connect] app_mode = "python-fastapi" entrypoint = "$name.__connect__:app" title = "$name" diff --git a/rsconnect/quickstart/templates/notebook/pyproject.toml.tmpl b/rsconnect/quickstart/templates/notebook/pyproject.toml.tmpl index 75d493758..ce88a5d25 100644 --- a/rsconnect/quickstart/templates/notebook/pyproject.toml.tmpl +++ b/rsconnect/quickstart/templates/notebook/pyproject.toml.tmpl @@ -6,7 +6,7 @@ dependencies = [ "jupyter", ] -[tool.rsconnect] +[tool.posit.connect] app_mode = "jupyter-static" entrypoint = "notebook.ipynb" title = "$name" diff --git a/rsconnect/quickstart/templates/quarto/pyproject.toml.tmpl b/rsconnect/quickstart/templates/quarto/pyproject.toml.tmpl index d5965c1b5..36fdae15b 100644 --- a/rsconnect/quickstart/templates/quarto/pyproject.toml.tmpl +++ b/rsconnect/quickstart/templates/quarto/pyproject.toml.tmpl @@ -4,7 +4,7 @@ version = "0.0.1" requires-python = "$requires_python" dependencies = [] -[tool.rsconnect] +[tool.posit.connect] app_mode = "quarto-static" entrypoint = "report.qmd" title = "$name" diff --git a/rsconnect/quickstart/templates/shiny/pyproject.toml.tmpl b/rsconnect/quickstart/templates/shiny/pyproject.toml.tmpl index 91cc70f78..fc20b8f90 100644 --- a/rsconnect/quickstart/templates/shiny/pyproject.toml.tmpl +++ b/rsconnect/quickstart/templates/shiny/pyproject.toml.tmpl @@ -6,7 +6,7 @@ dependencies = [ "shiny", ] -[tool.rsconnect] +[tool.posit.connect] app_mode = "python-shiny" entrypoint = "app.py" title = "$name" diff --git a/rsconnect/quickstart/templates/streamlit/pyproject.toml.tmpl b/rsconnect/quickstart/templates/streamlit/pyproject.toml.tmpl index bd3dbb41b..5c2771d6f 100644 --- a/rsconnect/quickstart/templates/streamlit/pyproject.toml.tmpl +++ b/rsconnect/quickstart/templates/streamlit/pyproject.toml.tmpl @@ -6,7 +6,7 @@ dependencies = [ "streamlit", ] -[tool.rsconnect] +[tool.posit.connect] app_mode = "python-streamlit" entrypoint = "app.py" title = "$name" diff --git a/rsconnect/quickstart/templates/voila/pyproject.toml.tmpl b/rsconnect/quickstart/templates/voila/pyproject.toml.tmpl index 775e21d56..2a6496ff9 100644 --- a/rsconnect/quickstart/templates/voila/pyproject.toml.tmpl +++ b/rsconnect/quickstart/templates/voila/pyproject.toml.tmpl @@ -7,7 +7,7 @@ dependencies = [ "jupyter", ] -[tool.rsconnect] +[tool.posit.connect] app_mode = "jupyter-voila" entrypoint = "notebook.ipynb" title = "$name" diff --git a/tests/test_deploy_pyproject.py b/tests/test_deploy_pyproject.py index 4a53b6392..abdd41b9d 100644 --- a/tests/test_deploy_pyproject.py +++ b/tests/test_deploy_pyproject.py @@ -13,6 +13,7 @@ from __future__ import annotations import pathlib +import re import textwrap import types import typing @@ -119,7 +120,7 @@ def test_read_tool_rsconnect_missing_section_raises(project_dir: pathlib.Path): # incidentally produce that shape. message = str(excinfo.value) assert "tool.rsconnect" in message.lower() or "rsconnect" in message.lower() - assert "[tool.rsconnect]" in message + assert "[tool.posit.connect]" in message assert 'app_mode = "' in message assert 'entrypoint = "' in message @@ -143,7 +144,7 @@ def test_read_tool_rsconnect_non_table_raises(project_dir: pathlib.Path, body: s read_tool_rsconnect(project_dir / "pyproject.toml") message = str(excinfo.value) assert "not a TOML table" in message - assert "[tool.rsconnect]" in message + assert "[tool.posit.connect]" in message assert 'app_mode = "' in message assert 'entrypoint = "' in message @@ -323,6 +324,7 @@ def spy_make_bundle( @pytest.mark.parametrize("app_mode,entrypoint,expected_builder_name", DISPATCH_MATRIX) +@pytest.mark.parametrize("table", ["posit.connect", "rsconnect"]) def test_deploy_pyproject_dispatches_by_app_mode( runner: CliRunner, project_dir: pathlib.Path, @@ -330,8 +332,11 @@ def test_deploy_pyproject_dispatches_by_app_mode( entrypoint: str, expected_builder_name: str, monkeypatch: pytest.MonkeyPatch, + table: str, ): - """Each ``[tool.rsconnect].app_mode`` routes to its matching bundle builder.""" + """Each configured app mode routes to its matching bundle builder.""" + warnings = [] + monkeypatch.setattr("rsconnect.main.logger.warning", warnings.append) captured = _spy_make_bundle(monkeypatch) _write_pyproject( @@ -341,7 +346,7 @@ def test_deploy_pyproject_dispatches_by_app_mode( name = "hello_app" version = "0.0.1" - [tool.rsconnect] + [tool.{table}] app_mode = "{app_mode}" entrypoint = "{entrypoint}" title = "Dispatch Test" @@ -356,6 +361,12 @@ def test_deploy_pyproject_dispatches_by_app_mode( ) assert captured.get("builder") == expected_builder_name, result.output + if table == "rsconnect": + assert len(warnings) == 1 + assert "[tool.rsconnect]" in warnings[0] + assert "[tool.posit.connect]" in warnings[0] + else: + assert not warnings if app_mode == "jupyter-static": # Legacy app mode - no need to override the bundle builder default pass @@ -366,8 +377,9 @@ def test_deploy_pyproject_dispatches_by_app_mode( ["no-such-mode", "python-dash", "nodejs-api"], ids=["unknown", "valid-but-unhandled", "aliased"], ) +@pytest.mark.parametrize("table", ["posit.connect", "rsconnect"]) def test_deploy_pyproject_errors_on_unsupported_app_mode( - runner: CliRunner, project_dir: pathlib.Path, app_mode: str, monkeypatch: pytest.MonkeyPatch + runner: CliRunner, project_dir: pathlib.Path, app_mode: str, monkeypatch: pytest.MonkeyPatch, table: str ): """Unsupported app modes fail quoting the configured string (not its canonical alias target) and without the quickstart hint.""" @@ -379,7 +391,7 @@ def test_deploy_pyproject_errors_on_unsupported_app_mode( name = "hello_app" version = "0.0.1" - [tool.rsconnect] + [tool.{table}] app_mode = "{app_mode}" entrypoint = "app.py" """, @@ -393,7 +405,7 @@ def test_deploy_pyproject_errors_on_unsupported_app_mode( assert result.exit_code != 0 combined = result.output + (result.stderr if result.stderr_bytes else "") - assert f"Unsupported app_mode '{app_mode}' in [tool.rsconnect]" in combined + assert f"Unsupported app_mode '{app_mode}' in [tool.{table}]" in combined assert "quickstart" not in combined.lower() @@ -614,10 +626,11 @@ def test_deploy_pyproject_requirements_file_flag_overrides_default( assert captured["requirements_file"] == "uv.lock" +@pytest.mark.parametrize("table", ["posit.connect", "rsconnect"]) def test_deploy_pyproject_honors_requirements_file_from_tool_rsconnect( - runner: CliRunner, project_dir: pathlib.Path, monkeypatch: pytest.MonkeyPatch + runner: CliRunner, project_dir: pathlib.Path, monkeypatch: pytest.MonkeyPatch, table: str ): - """``[tool.rsconnect].requirements_file`` becomes the default for this project. + """The configured requirements file becomes the default for this project. Lets users who maintain a ``uv.lock`` (or any other requirements source) bake that choice into the project once, instead of remembering ``-r`` on @@ -626,13 +639,13 @@ def test_deploy_pyproject_honors_requirements_file_from_tool_rsconnect( captured = _capture_environment(monkeypatch) _write_pyproject( project_dir, - """ + f""" [project] name = "hello_app" version = "0.0.1" dependencies = ["flask"] - [tool.rsconnect] + [tool.{table}] app_mode = "python-api" entrypoint = "app:app" title = "hello_app" @@ -644,20 +657,21 @@ def test_deploy_pyproject_honors_requirements_file_from_tool_rsconnect( assert captured["requirements_file"] == "uv.lock" +@pytest.mark.parametrize("table", ["posit.connect", "rsconnect"]) def test_deploy_pyproject_flag_overrides_tool_rsconnect_requirements_file( - runner: CliRunner, project_dir: pathlib.Path, monkeypatch: pytest.MonkeyPatch + runner: CliRunner, project_dir: pathlib.Path, monkeypatch: pytest.MonkeyPatch, table: str ): - """CLI ``-r`` wins over ``[tool.rsconnect].requirements_file``.""" + """CLI ``-r`` wins over the configured requirements file.""" captured = _capture_environment(monkeypatch) _write_pyproject( project_dir, - """ + f""" [project] name = "hello_app" version = "0.0.1" dependencies = ["flask"] - [tool.rsconnect] + [tool.{table}] app_mode = "python-api" entrypoint = "app:app" title = "hello_app" @@ -669,3 +683,78 @@ def test_deploy_pyproject_flag_overrides_tool_rsconnect_requirements_file( ["deploy", "pyproject", "-r", "pyproject.toml", str(project_dir), "-s", "http://x", "-k", "k"], ) assert captured["requirements_file"] == "pyproject.toml" + + +@pytest.mark.parametrize("command", ["deploy", "write-manifest"]) +@pytest.mark.parametrize("invalid_table", ["posit.connect", "rsconnect"]) +def test_pyproject_both_tables_fail_before_validation(runner, project_dir, command, invalid_table, monkeypatch): + warnings = [] + monkeypatch.setattr("rsconnect.main.logger.warning", warnings.append) + other = "rsconnect" if invalid_table == "posit.connect" else "posit.connect" + _write_pyproject( + project_dir, + f'[tool.{invalid_table}]\n[tool.{other}]\napp_mode = "python-api"\nentrypoint = "app:app"\n', + ) + result = runner.invoke(cli, [command, "pyproject", str(project_dir)]) + assert result.exit_code != 0 + assert "[tool.posit.connect]" in result.output + assert "[tool.rsconnect]" in result.output + assert "Keep only one" in result.output + assert not warnings + + +@pytest.mark.parametrize("command", ["deploy", "write-manifest"]) +@pytest.mark.parametrize("table", ["posit.connect", "rsconnect"]) +@pytest.mark.parametrize( + "field,value", + [("app_mode", '""'), ("entrypoint", "42"), ("app_mode", '"unknown"'), ("app_mode", '"python-dash"')], +) +def test_pyproject_invalid_fields_name_table_without_warning( + runner, project_dir, command, table, field, value, monkeypatch +): + warnings = [] + monkeypatch.setattr("rsconnect.main.logger.warning", warnings.append) + fields = {"app_mode": '"python-api"', "entrypoint": '"app:app"'} + fields[field] = value + _write_pyproject( + project_dir, f"[tool.{table}]\napp_mode = {fields['app_mode']}\nentrypoint = {fields['entrypoint']}\n" + ) + result = runner.invoke(cli, [command, "pyproject", str(project_dir)]) + assert result.exit_code != 0 + assert f"[tool.{table}]" in result.output + assert not warnings + + +@pytest.mark.parametrize("table", ["posit.connect", "rsconnect"]) +def test_pyproject_non_table_names_selected_table(project_dir, table): + from rsconnect.pyproject import InvalidPyprojectConfigError, read_tool_rsconnect + + _write_pyproject(project_dir, f'[tool]\n{table} = "not a table"\n') + with pytest.raises(InvalidPyprojectConfigError, match=rf"\[tool\.{re.escape(table)}\] is not a TOML table"): + read_tool_rsconnect(project_dir / "pyproject.toml") + + +@pytest.mark.parametrize("body", ['[tool]\nposit = "x"', '[tool.posit]\nconnect = "x"']) +def test_pyproject_posit_non_table(project_dir, body): + from rsconnect.pyproject import InvalidPyprojectConfigError, read_tool_rsconnect + + _write_pyproject(project_dir, body) + table = "[tool.posit.connect]" if "connect" in body else "[tool.posit]" + with pytest.raises(InvalidPyprojectConfigError) as excinfo: + read_tool_rsconnect(project_dir / "pyproject.toml") + assert f"{table} is not a TOML table" in str(excinfo.value) + + +@pytest.mark.parametrize("legacy", [False, True]) +def test_pyproject_posit_without_connect_is_ignored(project_dir, legacy): + from rsconnect.pyproject import InvalidPyprojectConfigError, read_tool_rsconnect + + body = '[tool.posit]\nother = "value"\n[tool.posit.another]\nsetting = true\n' + if legacy: + body += '[tool.rsconnect]\napp_mode = "python-api"\nentrypoint = "app:app"\n' + _write_pyproject(project_dir, body) + if legacy: + assert read_tool_rsconnect(project_dir / "pyproject.toml")["entrypoint"] == "app:app" + else: + with pytest.raises(InvalidPyprojectConfigError, match="section is missing"): + read_tool_rsconnect(project_dir / "pyproject.toml") diff --git a/tests/test_quickstart.py b/tests/test_quickstart.py index b66ef2611..c449d64b5 100644 --- a/tests/test_quickstart.py +++ b/tests/test_quickstart.py @@ -283,7 +283,7 @@ def test_quickstart_does_not_create_manifest_json(runner: CliRunner, in_tmp_cwd: # --------------------------------------------------------------------------- -def test_quickstart_pyproject_has_tool_rsconnect(runner: CliRunner, in_tmp_cwd: pathlib.Path): +def test_quickstart_pyproject_has_tool_posit_connect(runner: CliRunner, in_tmp_cwd: pathlib.Path): result = _invoke_quickstart(runner, "streamlit", "hello_app") assert result.exit_code == 0, result.output data = _read_pyproject(in_tmp_cwd / "hello_app") @@ -293,24 +293,25 @@ def test_quickstart_pyproject_has_tool_rsconnect(runner: CliRunner, in_tmp_cwd: expected_requires = ">={}.{}".format(*sys.version_info[:2]) assert data["project"]["requires-python"] == expected_requires assert data["project"]["dependencies"] == ["streamlit"] - tool_rsconnect = data["tool"]["rsconnect"] - assert tool_rsconnect["app_mode"] == "python-streamlit" - assert tool_rsconnect["entrypoint"] == "app.py" - assert tool_rsconnect["title"] == "hello_app" + assert "rsconnect" not in data["tool"] + tool_posit_connect = data["tool"]["posit"]["connect"] + assert tool_posit_connect["app_mode"] == "python-streamlit" + assert tool_posit_connect["entrypoint"] == "app.py" + assert tool_posit_connect["title"] == "hello_app" # Scaffolded projects ship a uv.lock from ``uv sync``; default deploys # use it so ``rsconnect deploy pyproject`` is reproducible out of the box. - assert tool_rsconnect["requirements_file"] == "uv.lock" + assert tool_posit_connect["requirements_file"] == "uv.lock" -def test_quickstart_does_not_duplicate_deps_in_tool_rsconnect(runner: CliRunner, in_tmp_cwd: pathlib.Path): - """``dependencies`` and ``requires-python`` live in ``[project]``, not in ``[tool.rsconnect]``.""" +def test_quickstart_does_not_duplicate_deps_in_tool_posit_connect(runner: CliRunner, in_tmp_cwd: pathlib.Path): + """``dependencies`` and ``requires-python`` live in ``[project]``, not in ``[tool.posit.connect]``.""" result = _invoke_quickstart(runner, "streamlit", "hello_app") assert result.exit_code == 0, result.output - tool_rsconnect = _read_pyproject(in_tmp_cwd / "hello_app")["tool"]["rsconnect"] - assert "dependencies" not in tool_rsconnect - assert "requires-python" not in tool_rsconnect - assert "requires_python" not in tool_rsconnect - assert set(tool_rsconnect.keys()) == {"app_mode", "entrypoint", "title", "requirements_file"} + tool_posit_connect = _read_pyproject(in_tmp_cwd / "hello_app")["tool"]["posit"]["connect"] + assert "dependencies" not in tool_posit_connect + assert "requires-python" not in tool_posit_connect + assert "requires_python" not in tool_posit_connect + assert set(tool_posit_connect.keys()) == {"app_mode", "entrypoint", "title", "requirements_file"} def test_quickstart_python_option_sets_requires_python( @@ -385,11 +386,11 @@ def test_quickstart_app_mode_for_each_type( args = [cli_args[0], *cli_args[1:], "hello_app"] result = _invoke_quickstart(runner, *args) assert result.exit_code == 0, result.output - tool_rsconnect = _read_pyproject(in_tmp_cwd / "hello_app")["tool"]["rsconnect"] - assert tool_rsconnect["app_mode"] == expected_mode + tool_posit_connect = _read_pyproject(in_tmp_cwd / "hello_app")["tool"]["posit"]["connect"] + assert tool_posit_connect["app_mode"] == expected_mode if expected_mode == "python-api": # Flask aliases to api: both module-style modes share entrypoint. - assert tool_rsconnect["entrypoint"] == "hello_app.__connect__:app" + assert tool_posit_connect["entrypoint"] == "hello_app.__connect__:app" # --------------------------------------------------------------------------- @@ -482,8 +483,8 @@ def test_quickstart_mode_file_set( def test_quickstart_fastapi_entrypoint_is_connect_app(runner: CliRunner, in_tmp_cwd: pathlib.Path): result = _invoke_quickstart(runner, "fastapi", "hello_app") assert result.exit_code == 0, result.output - tool_rsconnect = _read_pyproject(in_tmp_cwd / "hello_app")["tool"]["rsconnect"] - assert tool_rsconnect["entrypoint"] == "hello_app.__connect__:app" + tool_posit_connect = _read_pyproject(in_tmp_cwd / "hello_app")["tool"]["posit"]["connect"] + assert tool_posit_connect["entrypoint"] == "hello_app.__connect__:app" connect_py = (in_tmp_cwd / "hello_app" / "hello_app" / "__connect__.py").read_text() assert "create_app" in connect_py assert "app = " in connect_py @@ -757,7 +758,7 @@ def test_invariant_I1_I2_directory_and_pyproject(runner: CliRunner, in_tmp_cwd: data = _read_pyproject(project) assert data["project"]["name"] == "hello_app" for required in ("app_mode", "entrypoint", "title"): - assert required in data["tool"]["rsconnect"] + assert required in data["tool"]["posit"]["connect"] def test_invariant_I9_I10_failure_exit_and_message( @@ -806,7 +807,7 @@ def test_quickstart_registry_accepts_new_mode( 'requires-python = "$requires_python"\n' "dependencies = []\n" "\n" - "[tool.rsconnect]\n" + "[tool.posit.connect]\n" 'app_mode = "python-newmode"\n' 'entrypoint = "app.py"\n' 'title = "$name"\n' @@ -851,8 +852,8 @@ def fake_get_data(package: str, resource: str): assert result.exit_code == 0, result.output data = _read_pyproject(in_tmp_cwd / "hello_app") - assert data["tool"]["rsconnect"]["app_mode"] == "python-newmode" - assert data["tool"]["rsconnect"]["entrypoint"] == "app.py" + assert data["tool"]["posit"]["connect"]["app_mode"] == "python-newmode" + assert data["tool"]["posit"]["connect"]["entrypoint"] == "app.py" assert data["project"]["dependencies"] == [] @@ -904,3 +905,15 @@ def test_quickstart_per_mode_boot_smoke( target = _local_run.artifact_path(app_type, project_dir) with _local_run.spawn(cmd, cwd=project_dir) as proc: _local_run.wait_for_artifact(proc, target) + + +def test_quickstart_generated_project_writes_deployable_manifest(runner, in_tmp_cwd): + from rsconnect.bundle import make_manifest_bundle + + result = _invoke_quickstart(runner, "streamlit", "hello_app") + assert result.exit_code == 0, result.output + project = in_tmp_cwd / "hello_app" + result = runner.invoke(cli, ["write-manifest", "pyproject", str(project)]) + assert result.exit_code == 0, result.output + with make_manifest_bundle(str(project / "manifest.json")): + pass diff --git a/tests/test_write_manifest_pyproject.py b/tests/test_write_manifest_pyproject.py index e51d0391b..4a3d9635e 100644 --- a/tests/test_write_manifest_pyproject.py +++ b/tests/test_write_manifest_pyproject.py @@ -107,14 +107,14 @@ def _fake_quarto(monkeypatch: pytest.MonkeyPatch, engines: list[str]) -> None: _NOTEBOOK_JSON = '{"cells": [], "metadata": {}, "nbformat": 4, "nbformat_minor": 5}\n' -def _pyproject_body(app_mode: str, entrypoint: str) -> str: +def _pyproject_body(app_mode: str, entrypoint: str, table: str = "rsconnect") -> str: return f""" [project] name = "hello_app" version = "0.0.1" dependencies = ["flask"] - [tool.rsconnect] + [tool.{table}] app_mode = "{app_mode}" entrypoint = "{entrypoint}" title = "hello_app" @@ -137,6 +137,7 @@ def _pyproject_body(app_mode: str, entrypoint: str) -> str: @pytest.mark.parametrize("app_mode,entrypoint,expected_entrypoint", DISPATCH_MATRIX) +@pytest.mark.parametrize("table", ["posit.connect", "rsconnect"]) def test_write_manifest_pyproject_writes_manifest_per_app_mode( runner: CliRunner, project_dir: pathlib.Path, @@ -144,10 +145,13 @@ def test_write_manifest_pyproject_writes_manifest_per_app_mode( entrypoint: str, expected_entrypoint: str, monkeypatch: pytest.MonkeyPatch, + table: str, ): - """Each ``[tool.rsconnect].app_mode`` produces a manifest.json with the matching appmode.""" + """Each configured app mode produces a manifest.json with the matching appmode.""" + warnings = [] + monkeypatch.setattr("rsconnect.main.logger.warning", warnings.append) _fake_python_environment(monkeypatch) - _write_pyproject(project_dir, _pyproject_body(app_mode, entrypoint)) + _write_pyproject(project_dir, _pyproject_body(app_mode, entrypoint, table)) if entrypoint.endswith(".ipynb"): (project_dir / entrypoint).write_text(_NOTEBOOK_JSON) else: @@ -156,6 +160,12 @@ def test_write_manifest_pyproject_writes_manifest_per_app_mode( result = runner.invoke(cli, ["write-manifest", "pyproject", str(project_dir)]) assert result.exit_code == 0, result.output + if table == "rsconnect": + assert len(warnings) == 1 + assert "[tool.rsconnect]" in warnings[0] + assert "[tool.posit.connect]" in warnings[0] + else: + assert not warnings manifest = _read_manifest(project_dir) assert manifest["metadata"]["appmode"] == app_mode assert manifest["metadata"]["entrypoint"] == expected_entrypoint @@ -254,19 +264,20 @@ def test_write_manifest_pyproject_requirements_file_flag_overrides_default( pass +@pytest.mark.parametrize("table", ["posit.connect", "rsconnect"]) def test_write_manifest_pyproject_honors_requirements_file_from_tool_rsconnect( - runner: CliRunner, project_dir: pathlib.Path, monkeypatch: pytest.MonkeyPatch + runner: CliRunner, project_dir: pathlib.Path, monkeypatch: pytest.MonkeyPatch, table: str ): captured = _fake_python_environment(monkeypatch) _write_pyproject( project_dir, - """ + f""" [project] name = "hello_app" version = "0.0.1" dependencies = ["flask"] - [tool.rsconnect] + [tool.{table}] app_mode = "python-api" entrypoint = "app:app" title = "hello_app" @@ -537,12 +548,23 @@ def test_write_manifest_pyproject_errors_on_malformed_pyproject( ["no-such-mode", "python-dash", "nodejs-api"], ids=["unknown", "valid-but-unhandled", "aliased"], ) +@pytest.mark.parametrize("table", ["posit.connect", "rsconnect"]) def test_write_manifest_pyproject_errors_on_unsupported_app_mode( - runner: CliRunner, project_dir: pathlib.Path, app_mode: str + runner: CliRunner, project_dir: pathlib.Path, app_mode: str, table: str ): """Unsupported app modes fail with deploy's exact message and no quickstart hint.""" - _write_pyproject(project_dir, _pyproject_body(app_mode, "app.py")) + _write_pyproject(project_dir, _pyproject_body(app_mode, "app.py", table)) result = runner.invoke(cli, ["write-manifest", "pyproject", str(project_dir)]) assert result.exit_code != 0 - assert f"Unsupported app_mode '{app_mode}' in [tool.rsconnect]" in result.output + assert f"Unsupported app_mode '{app_mode}' in [tool.{table}]" in result.output assert "quickstart" not in result.output.lower() + + +@pytest.mark.parametrize("table", ["posit.connect", "rsconnect"]) +def test_write_manifest_pyproject_flag_overrides_configured_requirements(runner, project_dir, monkeypatch, table): + captured = _fake_python_environment(monkeypatch) + _write_pyproject(project_dir, _pyproject_body("python-api", "app:app", table) + '\nrequirements_file = "uv.lock"\n') + (project_dir / "app.py").write_text("app = None\n") + result = runner.invoke(cli, ["write-manifest", "pyproject", "-r", "pyproject.toml", str(project_dir)]) + assert result.exit_code == 0, result.output + assert captured["requirements_file"] == "pyproject.toml"