diff --git a/.github/workflows/apt_wxgui.txt b/.github/workflows/apt_wxgui.txt new file mode 100644 index 00000000000..415c74f7805 --- /dev/null +++ b/.github/workflows/apt_wxgui.txt @@ -0,0 +1,6 @@ +# Run-time libraries of the wxPython wheels and a virtual display for +# testing the GUI. Package names are for Ubuntu 24.04. +libgtk-3-0t64 +libnotify4 +libsdl2-2.0-0 +xvfb diff --git a/.github/workflows/cmake.yml b/.github/workflows/cmake.yml index 7f39a68f427..65a6f42ea3c 100644 --- a/.github/workflows/cmake.yml +++ b/.github/workflows/cmake.yml @@ -71,7 +71,7 @@ jobs: gettext unixodbc-dev libnetcdf-dev python3-wxgtk4.0 LC_ALL=C.UTF-8 sudo add-apt-repository -y ppa:ubuntugis/ubuntugis-unstable sudo apt-get update -y - xargs -a <(awk '! /^ *(#|$)/' ".github/workflows/apt.txt") -r -- \ + xargs -a <(awk '! /^ *(#|$)/' ".github/workflows/apt.txt" ".github/workflows/apt_wxgui.txt") -r -- \ sudo apt-get install -y --no-install-recommends --no-install-suggests - name: Print build environment variables shell: bash -el {0} @@ -143,6 +143,17 @@ jobs: @.github/workflows/pytest_args_not_parallel.txt \ --junitxml=pytest.needs_solo_run.junit.xml \ -k 'not testsuite' + - name: Run pytest for the tests which need the wx.App + run: | + PYTHONPATH="$(grass --config python_path):${PYTHONPATH}" + LD_LIBRARY_PATH="$(grass --config path)/lib:${LD_LIBRARY_PATH}" + export PYTHONPATH + export LD_LIBRARY_PATH + xvfb-run -a pytest \ + @.github/workflows/pytest_args_ci.txt \ + -m needs_wx_app \ + --junitxml=pytest.needs_wx_app.junit.xml \ + gui/wxpython - name: Run pytest with a single worker (for gunittest-based tests) run: | PYTHONPATH="$(grass --config python_path):${PYTHONPATH}" diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml index bc74e415bf5..1661918cfa8 100644 --- a/.github/workflows/macos.yml +++ b/.github/workflows/macos.yml @@ -119,6 +119,18 @@ jobs: @.github/workflows/pytest_args_not_parallel.txt \ --junitxml=pytest.needs_solo_run.junit.xml \ -k 'not testsuite' + - name: Run pytest for the tests which need the wx.App + shell: micromamba-shell {0} + run: | + PYTHONPATH="$(grass --config python_path):${PYTHONPATH}" + LD_LIBRARY_PATH="$(grass --config path)/lib:${LD_LIBRARY_PATH}" + export PYTHONPATH + export LD_LIBRARY_PATH + pytest \ + @.github/workflows/pytest_args_ci.txt \ + -m needs_wx_app \ + --junitxml=pytest.needs_wx_app.junit.xml \ + gui/wxpython - name: Run pytest with a single worker (for gunittest-based tests) shell: micromamba-shell {0} run: | diff --git a/.github/workflows/osgeo4w.yml b/.github/workflows/osgeo4w.yml index f4996d8ac73..6afd72ca68a 100644 --- a/.github/workflows/osgeo4w.yml +++ b/.github/workflows/osgeo4w.yml @@ -161,6 +161,18 @@ jobs: -k "not testsuite" # Obfuscated usage of GitHub Actions features, Windows CMD shell limits analysis shell: cmd /D /E:ON /V:OFF /S /C "CALL C:/OSGeo4W/OSGeo4W.bat "{0}"" # zizmor: ignore[misfeature] + - name: Run pytest for the tests which need the wx.App + run: | + call %OSGEO4W_ROOT%\opt\grass\etc\env.bat + set PYTHONPATH=%GISBASE%\etc\python;%PYTHONPATH% + path %GISBASE%\lib;%GISBASE%\bin;%PATH% + pytest ^ + @.github/workflows/pytest_args_ci.txt ^ + -m needs_wx_app ^ + --junitxml=pytest.needs_wx_app.junit.xml ^ + gui/wxpython + # Obfuscated usage of GitHub Actions features, Windows CMD shell limits analysis + shell: cmd /D /E:ON /V:OFF /S /C "CALL C:/OSGeo4W/OSGeo4W.bat "{0}"" # zizmor: ignore[misfeature] - name: Run pytest with a single worker (for gunittest-based tests) run: | call %OSGEO4W_ROOT%\opt\grass\etc\env.bat diff --git a/.github/workflows/pytest.yml b/.github/workflows/pytest.yml index 4340efe0da1..44406a23956 100644 --- a/.github/workflows/pytest.yml +++ b/.github/workflows/pytest.yml @@ -39,6 +39,8 @@ jobs: FORCE_COLOR: 1 # for software including pip: https://force-color.org/ CLICOLOR_FORCE: 1 # for other software including ninja: https://bixense.com/clicolors/ PYTHONWARNINGS: always + # renovate: datasource=pypi depName=wxPython + WXPYTHON_VERSION: "4.3.2" steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -60,7 +62,7 @@ jobs: sudo apt-get install -y wget git gawk findutils LC_ALL=C.UTF-8 sudo add-apt-repository -y ppa:ubuntugis/ubuntugis-unstable sudo apt-get update -y - xargs -a <(awk '! /^ *(#|$)/' ".github/workflows/apt.txt") -r -- \ + xargs -a <(awk '! /^ *(#|$)/' ".github/workflows/apt.txt" ".github/workflows/apt_wxgui.txt") -r -- \ sudo apt-get install -y --no-install-recommends --no-install-suggests - uses: rui314/setup-mold@339e96b4ff1f3bd865856ba4cbbe8818a7acb038 # v1 @@ -73,6 +75,16 @@ jobs: python -m pip install --upgrade pip pip install --break-system-packages -r .github/workflows/python_requirements.txt pip install --break-system-packages -r .github/workflows/optional_requirements.txt + # PyPI has only the source distribution of wxPython for Linux. + # Ubuntu wheels are attached to the GitHub releases, with the Ubuntu + # version as local version, e.g., 4.3.2+ubuntu2404. Their metadata + # lack the local version, which pip rejects, so uv is used. + pip install --break-system-packages uv + ubuntu="ubuntu$(. /etc/os-release && echo "${VERSION_ID//./}")" + releases="https://github.com/wxWidgets/Phoenix/releases/expanded_assets" + uv pip install --system --break-system-packages \ + --find-links "${releases}/wxPython-${WXPYTHON_VERSION}" \ + "wxPython==${WXPYTHON_VERSION}+${ubuntu}" pip install --break-system-packages pytest pytest-timeout \ pytest-github-actions-annotate-failures pytest-xdist pytest-cov @@ -143,6 +155,22 @@ jobs: @.github/workflows/pytest_args_not_parallel.txt \ --junitxml=pytest.needs_solo_run.junit.xml \ -k 'not testsuite' + - name: Run pytest for the tests which need the wx.App + run: | + PYTHONPATH="$(grass --config python_path):${PYTHONPATH}" + LD_LIBRARY_PATH="$(grass --config path)/lib:${LD_LIBRARY_PATH}" + INITIAL_GISBASE="$(grass --config path)" + INITIAL_PWD="${PWD}" + export PYTHONPATH + export LD_LIBRARY_PATH + export INITIAL_GISBASE + export INITIAL_PWD + xvfb-run -a pytest \ + @.github/workflows/pytest_args_ci.txt \ + @.github/workflows/pytest_args_cov.txt \ + -m needs_wx_app \ + --junitxml=pytest.needs_wx_app.junit.xml \ + gui/wxpython - name: Run pytest with a single worker (for gunittest-based tests) run: | PYTHONPATH="$(grass --config python_path):${PYTHONPATH}" diff --git a/.github/workflows/pytest_args_not_parallel.txt b/.github/workflows/pytest_args_not_parallel.txt index e2c41218d07..b62ab9b4863 100644 --- a/.github/workflows/pytest_args_not_parallel.txt +++ b/.github/workflows/pytest_args_not_parallel.txt @@ -1 +1 @@ --m needs_solo_run +-m needs_solo_run and not needs_wx_app diff --git a/.github/workflows/pytest_args_parallel.txt b/.github/workflows/pytest_args_parallel.txt index c32742f5162..eb55490b7fe 100644 --- a/.github/workflows/pytest_args_parallel.txt +++ b/.github/workflows/pytest_args_parallel.txt @@ -1,2 +1,2 @@ --numprocesses=auto --m not needs_solo_run +-m not needs_solo_run and not needs_wx_app diff --git a/doc/development/testing.md b/doc/development/testing.md index 0384c98cfe9..af45e0dc972 100644 --- a/doc/development/testing.md +++ b/doc/development/testing.md @@ -170,6 +170,35 @@ environment. Mark such a test so it is run on its own: def test_something_which_changes_the_environment(xy_dataset_session): ... ``` +### Tests of the wxPython GUI + +The GUI modules can be imported only with a GRASS session in the global +environment and the GUI directory in `sys.path`. The `gui_session` fixture +from `gui/wxpython/conftest.py` sets up both, so a test using it must be +marked with `needs_solo_run`. Import the GUI modules inside the test. Tests +which create windows also need the `wx_app` fixture: + +```python +@pytest.mark.needs_solo_run +def test_dialog(gui_session, wx_app): + from gui_core.forms import GUI + + ... +``` + +Tests using `wx_app` are marked with `needs_wx_app` automatically and run in +their own pytest process in CI. Without a display, they are skipped, except in +CI, where they fail. To run them on Linux without showing the windows, use +a virtual display: + +```sh +xvfb-run -a pytest -m needs_wx_app gui/wxpython +``` + +The `wx.App` and some global settings changed by the GUI modules, such as +`grass.script.set_raise_on_error()`, stay for the rest of the process. Run the +other tests separately with `-m "not needs_wx_app"`. + ## More information - [grass.gunittest documentation](https://grass.osgeo.org/grass-devel/manuals/libpython/gunittest_testing.html) diff --git a/gui/wxpython/conftest.py b/gui/wxpython/conftest.py new file mode 100644 index 00000000000..b58e352797a --- /dev/null +++ b/gui/wxpython/conftest.py @@ -0,0 +1,68 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +"""pytest fixtures for the wxPython GUI tests + +The GUI modules need a GRASS session in the process environment when imported. +The tests need a display, which xvfb-run provides on Linux in CI. +""" + +import os +import sys + +import pytest + +import grass.script as gs + + +def pytest_collection_modifyitems(items): + """Mark the tests which use the wx.App to run them in their own process""" + for item in items: + if "wx_app" in getattr(item, "fixturenames", ()): + item.add_marker(pytest.mark.needs_wx_app) + + +@pytest.fixture(scope="module") +def gui_session(tmp_path_factory): + """Session mirrored to os.environ with the GUI directory in sys.path + + The environment, sys.path and the imported GUI modules are restored at the + end of the module. Tests using this fixture need needs_solo_run. + """ + project = tmp_path_factory.mktemp("gui_project") / "xy_test" + gs.create_project(project) + with ( + pytest.MonkeyPatch.context() as monkeypatch, + gs.setup.init(project, env=os.environ.copy()) as session, + ): + for name, value in session.env.items(): + monkeypatch.setenv(name, value) + gui_dir = session.env["GRASS_GUIWXDIR"] + monkeypatch.syspath_prepend(gui_dir) + try: + yield session + finally: + # Third-party modules are kept, they should not be imported twice. + prefix = os.path.normcase(gui_dir) + os.sep + for name, module in list(sys.modules.items()): + file = getattr(module, "__file__", None) + if file and os.path.normcase(file).startswith(prefix): + del sys.modules[name] + + +@pytest.fixture(scope="session") +def wx_app(): + """The wx.App, kept for the whole session + + wxPython can reliably have only one application per process. + """ + wx = pytest.importorskip("wx") + if not wx.App.IsDisplayAvailable(): + # In CI, skipping would hide the tests: the step runs only these. + if os.environ.get("CI"): + pytest.fail("No display available for the GUI tests") + pytest.skip("No display available for the GUI tests") + app = wx.App() + yield app + # The destroyed windows are deleted by the wx cleanup at exit. + for window in wx.GetTopLevelWindows(): + window.Destroy() diff --git a/gui/wxpython/gui_core/tests/gui_core_forms_test.py b/gui/wxpython/gui_core/tests/gui_core_forms_test.py new file mode 100644 index 00000000000..56df322af58 --- /dev/null +++ b/gui/wxpython/gui_core/tests/gui_core_forms_test.py @@ -0,0 +1,25 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +"""Tests of the dialogs generated from tool interfaces""" + +import pytest + +pytest.importorskip("wx") + +pytestmark = pytest.mark.needs_solo_run + + +def test_task_frame_creates_command_from_values(gui_session, wx_app): + """The command created by the dialog includes the values set in the dialog""" + # The GUI is importable only with the session fixture active. + from gui_core.forms import GUI # noqa: PLC0415 + + gui = GUI(show=True) + gui.ParseCommand(["g.region", "n=10", "res=2", "-p"]) + frame = gui.mf + try: + command = frame.createCmd() + assert command[0] == "g.region" + assert {"-p", "n=10", "res=2"} <= set(command) + finally: + frame._Destroy() # noqa: SLF001 diff --git a/gui/wxpython/tests/gui_import_test.py b/gui/wxpython/tests/gui_import_test.py new file mode 100644 index 00000000000..4bb9018fbfe --- /dev/null +++ b/gui/wxpython/tests/gui_import_test.py @@ -0,0 +1,63 @@ +# SPDX-License-Identifier: GPL-2.0-or-later + +"""Test that all wxPython GUI modules can be imported""" + +import importlib +from pathlib import Path + +import pytest + +pytest.importorskip("wx") + +# Modules are listed from the source tree, so that one missing from the +# installation fails instead of being left out. +SOURCE_DIR = Path(__file__).parents[1] + +# Files in the source tree which are not part of the installed GUI. +NOT_INSTALLED = { + "conftest.py", + # Generated by the build for translations. + "menustrings.py", + # Development scripts. + "docs", + "tools", +} + +pytestmark = pytest.mark.needs_solo_run + + +def _is_importable_module(path): + """Return true if the file is a module which should be imported""" + return path.parts[0] not in NOT_INSTALLED and not any( + # Compiled caches. + part == "__pycache__" + # Tests, such as mapdisp/test_mapdisp.py, are not part of the GUI. + or part.startswith("test") + # Tool launchers such as g.gui.gcp.py, which can't be imported by name. + or "." in part.removesuffix(".py") + for part in path.parts + ) + + +def _module_names(): + names = [] + for path in sorted(SOURCE_DIR.rglob("*.py")): + relative = path.relative_to(SOURCE_DIR) + if not _is_importable_module(relative): + continue + parts = relative.with_suffix("").parts + if parts[-1] == "__init__": + parts = parts[:-1] + names.append(".".join(parts)) + return names + + +@pytest.mark.parametrize("module_name", _module_names()) +def test_module_imports(gui_session, wx_app, module_name): + """Module can be imported in a GRASS session with a display""" + try: + importlib.import_module(module_name) + except ModuleNotFoundError as error: + if error.name and error.name.split(".")[0] == "matplotlib": + pytest.skip("Optional dependency matplotlib is not installed") + raise diff --git a/pyproject.toml b/pyproject.toml index d323e63fa17..0ea52048219 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -541,6 +541,7 @@ addopts = """ markers = [ "slow: marks tests as slow (deselect with '-m \"not slow\"')", "needs_solo_run: marks tests that must be run without any other tests running in parallel", + "needs_wx_app: marks tests that create the wx.App, which must be run in their own process", ] minversion = "8.2" python_files = """