From 919ca285ca5c8af5c8bac0308f74bababeca9b47 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Paul=20M=C3=BCller?= Date: Thu, 5 Nov 2026 11:48:16 +0100 Subject: [PATCH] tests: add simple tests for most of dcor_control - fix: do not crash when declining to create a missing directory - ci: measure coverage of dcor_control and report to Codecov Co-Authored-By: Claude Opus 5.5 --- .github/workflows/check.yml | 12 +- CHANGELOG | 4 + dcor_control/inspect/common.py | 3 + tests/conftest.py | 9 ++ tests/test_backup.py | 67 +++++++++++ tests/test_cli.py | 210 +++++++++++++++++++++++++++++++++ tests/test_config_ckan.py | 178 ++++++++++++++++++++++++++++ tests/test_inspect_common.py | 78 ++++++++++++ tests/test_update.py | 72 ++++++++++- tests/test_util.py | 49 ++++++++ 10 files changed, 680 insertions(+), 2 deletions(-) create mode 100644 tests/conftest.py create mode 100644 tests/test_backup.py create mode 100644 tests/test_cli.py create mode 100644 tests/test_config_ckan.py create mode 100644 tests/test_inspect_common.py create mode 100644 tests/test_util.py diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 6cbb1a2..424d670 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -112,7 +112,17 @@ jobs: - name: Run tests run: | pytest -v --ckan-ini=/srv/app/ckan.ini \ - --cov=ckanext.dcor_schemas \ + --cov=dcor_control \ --cov-report=xml \ + --cov-report=term-missing \ --cov-append \ tests + + - name: Install Codecov requirements + run: apt-get update && apt-get install -y curl gpg + + - name: Upload coverage to Codecov + uses: codecov/codecov-action@v5 + with: + files: ./coverage.xml + flags: ${{ matrix.dcor_control }} diff --git a/CHANGELOG b/CHANGELOG index 76d8fa1..217398f 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,6 +1,10 @@ 1.17.5 - ref: `dcor inspect` does not check the permissions of the local resource upload directory anymore (resources are only stored on S3) + - fix: `dcor inspect` crashed when declining to create a missing directory + - tests: add tests for the CLI, `update`, `inspect`, `backup`, and `util` + - ci: measure coverage of `dcor_control` (not `ckanext.dcor_schemas`) + and report it to Codecov 1.17.4 - update compatible versions list for CKAN 2.11.7 (also listing CKAN 2.11.5 and 2.11.6, which are compatible with the same releases) diff --git a/dcor_control/inspect/common.py b/dcor_control/inspect/common.py index fa8702a..bb3b1da 100644 --- a/dcor_control/inspect/common.py +++ b/dcor_control/inspect/common.py @@ -81,6 +81,9 @@ def check_permission(path: str | pathlib.Path, except BaseException: warnings.warn( f"Failed to set ownership '{uid}:{gid}' for '{path}'") + else: + # The user decided not to create the directory + return did_something # Check mode pmode = stat.S_IMODE(path.stat().st_mode) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..667b115 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,9 @@ +import pytest + + +@pytest.fixture +def dcor_control_config_dir(monkeypatch, tmp_path): + """Store dcor_control configuration keys in a temporary directory""" + cpath = tmp_path / "dcor_control_config" + monkeypatch.setattr("appdirs.user_config_dir", lambda name: str(cpath)) + return cpath diff --git a/tests/test_backup.py b/tests/test_backup.py new file mode 100644 index 0000000..ac79657 --- /dev/null +++ b/tests/test_backup.py @@ -0,0 +1,67 @@ +import pathlib +import re +import types + +from dcor_control import backup + + +def test_delete_old_backups(tmp_path): + regex = re.compile(r"^backup_(.*)_test\.txt$") + paths = [] + for ii in range(10): + path = tmp_path / f"backup_2026-01-{ii + 10}_test.txt" + path.touch() + paths.append(path) + other = tmp_path / "other.txt" + other.touch() + backup.delete_old_backups(backup_root=tmp_path, + latest_backup=paths[-1], + regex=regex, + num=3) + # only the three newest backups are kept + assert sorted(tmp_path.glob("backup_*")) == paths[-3:] + assert other.exists() + + +def test_gpg_encrypt(monkeypatch, tmp_path): + calls = [] + + def check_output(cmd, shell): + calls.append(cmd) + path_out.write_text("encrypted") + + monkeypatch.setattr(backup.sp, "check_output", check_output) + path_in = tmp_path / "data.tar" + path_in.write_text("data") + path_out = tmp_path / "encrypted" / "data.tar.gpg" + backup.gpg_encrypt(path_in, path_out, key_id="ABCDEF") + cmd, = calls + assert "--recipient 'ABCDEF'" in cmd + assert path_out.parent.stat().st_mode & 0o777 == 0o700 + assert path_out.stat().st_mode & 0o777 == 0o400 + + +def test_db_backup(monkeypatch, tmp_path): + calls = [] + + def check_output(cmd, shell): + calls.append(cmd) + # pg_dump writes the backup file + path = cmd.split(" > ")[1].rstrip('"') + pathlib.Path(path).write_text("database") + + monkeypatch.setattr(backup.pwd, "getpwnam", + lambda name: types.SimpleNamespace(pw_uid=1234)) + monkeypatch.setattr(backup.os, "chown", lambda *args: None) + monkeypatch.setattr(backup.sp, "check_output", check_output) + old = tmp_path / "database" / \ + "backup_db_ckan_default_2020-01-01_00-00-00_dcor-control.pgc" + old.parent.mkdir() + old.touch() + path = backup.db_backup(path=tmp_path) + assert path.parent == tmp_path / "database" + assert path.read_text() == "database" + assert path.stat().st_mode & 0o777 == 0o400 + assert "pg_dump --format=custom -d ckan_default" in calls[0] + # less than 20 backups, so the old one is kept + assert old.exists() diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..783a0a1 --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,210 @@ +import os +import pathlib +import uuid + +from click.testing import CliRunner +import pytest + +from dcor_shared import get_ckan_config_option, s3 + +from dcor_control import cli +from dcor_control.cli import ( + backup, common, develop, inspect, reset, status, update +) + + +#: Some commands write to hard-coded locations such as `/backups` +requires_root = pytest.mark.skipif(os.geteuid() != 0, + reason="requires root permissions") + + +@pytest.fixture +def mock_check_output(monkeypatch): + calls = [] + + def check_output(cmd, shell): + calls.append(cmd) + return b"" + + for mod in [common, develop, reset, update]: + monkeypatch.setattr(mod.sp, "check_output", check_output) + return calls + + +@pytest.fixture +def no_supervisord(monkeypatch): + reloads = [] + for mod in [develop, inspect, reset, update]: + monkeypatch.setattr(mod, "reload_supervisord", + lambda: reloads.append(True)) + return reloads + + +def test_cli_main(): + result = CliRunner().invoke(cli.main, ["--help"]) + assert result.exit_code == 0 + for cmd in ["develop", "inspect", "reset", "status", "update", + "encrypted-instance-backup"]: + assert cmd in result.output + + +def test_is_supervisord_running(mock_check_output): + assert common.is_supervisord_running() + assert mock_check_output[0].endswith("supervisorctl status") + + +def test_reload_supervisord(monkeypatch, mock_check_output): + monkeypatch.setattr(common, "is_supervisord_running", lambda: True) + common.reload_supervisord() + assert mock_check_output[0].endswith("supervisorctl reload") + + +def test_reload_supervisord_not_running(monkeypatch, capsys, + mock_check_output): + monkeypatch.setattr(common, "is_supervisord_running", lambda: False) + common.reload_supervisord() + assert not mock_check_output + assert "supervisord not running" in capsys.readouterr().out + + +@requires_root +def test_cli_encrypted_instance_backup(monkeypatch, tmp_path): + db_path = tmp_path / "db.pgc" + db_path.write_text("database") + storage_path = tmp_path / "storage" + storage_path.mkdir() + (storage_path / "image.png").write_text("image") + + def gpg_encrypt(path_in, path_out, key_id): + path_out.write_bytes(path_in.read_bytes()) + + monkeypatch.setattr(backup, "db_backup", lambda: db_path) + monkeypatch.setattr(backup, "gpg_encrypt", gpg_encrypt) + monkeypatch.setattr( + backup, "get_ckan_config_option", + lambda key: (str(storage_path) if key == "ckan.storage_path" + else get_ckan_config_option(key))) + key_id = "PYTEST" + str(uuid.uuid4())[:8].upper() + result = CliRunner().invoke(backup.encrypted_instance_backup, + ["--key-id", key_id]) + assert result.exit_code == 0, result.output + eout, = pathlib.Path("/backups/instance-encrypted/").glob( + f"*_{key_id}_dcor-control.tar.bz2.gpg") + # the backup was uploaded to S3 + bucket_prefix = get_ckan_config_option( + "dcor_object_store.bucket_name").format(organization_id="") + info = status.get_bucket_info(f"{bucket_prefix}000000000-backup", + ret_object_keys=True) + assert any(key.endswith(eout.name) for key in info["object_keys"]) + + +@pytest.mark.usefixtures("no_supervisord") +def test_cli_develop(monkeypatch, mock_check_output): + migrated = [] + monkeypatch.setattr(develop, "migrate_to_editable", + lambda name: migrated.append(name)) + monkeypatch.setattr(develop.config_ckan, "check_ckan_ini_option", + lambda **kwargs: 0) + result = CliRunner().invoke(develop.develop, ["--yes"]) + assert result.exit_code == 0, result.output + assert "dcor_shared" in migrated + assert "ckanext-dcor_schemas" in migrated + assert mock_check_output[-1].endswith("dcor-theme-main-css-branding") + + +@requires_root +def test_migrate_to_editable(mock_check_output): + wd = os.getcwd() + develop.migrate_to_editable("dcor_peter") + assert mock_check_output[0] == \ + "git clone https://github.com/DCOR-dev/dcor_peter" + assert mock_check_output[1].endswith("install -e /dcor-repos/dcor_peter") + assert os.getcwd() == wd + + +def test_cli_inspect(monkeypatch, no_supervisord): + checked = [] + monkeypatch.setattr(inspect.inspect_mod, "check_ckan_ini", + lambda **kwargs: 0) + monkeypatch.setattr(inspect.inspect_mod, "check_permission", + lambda path, **kwargs: checked.append(str(path)) or 0) + monkeypatch.setattr(inspect.inspect_mod, "check_dcor_theme_i18n_hack", + lambda autocorrect: 0) + monkeypatch.setattr(inspect.inspect_mod, "check_dcor_theme_main_css", + lambda autocorrect: 1) + result = CliRunner().invoke(inspect.inspect, ["--assume-yes"]) + assert result.exit_code == 0, result.output + assert "/var/log/ckan" in checked + # a change was made, so CKAN is reloaded + assert no_supervisord == [True] + + +@pytest.mark.usefixtures("no_supervisord") +def test_cli_reset(monkeypatch, tmp_path, mock_check_output, + dcor_control_config_dir): + dcor_control_config_dir.mkdir() + result = CliRunner().invoke( + reset.reset, ["--cache", "--search-index", "--control", "--yes"]) + assert result.exit_code == 0, result.output + assert mock_check_output[0].endswith("asset clean") + assert mock_check_output[1].endswith("search-index clear") + assert not dcor_control_config_dir.exists() + + +@pytest.mark.usefixtures("no_supervisord") +def test_cli_reset_zombie_users(monkeypatch, tmp_path, mock_check_output): + monkeypatch.setattr(reset, "db_backup", lambda: tmp_path / "backup.pgc") + result = CliRunner().invoke( + reset.reset, ["--zombie-users", "--keep-user", "peter", "--yes"]) + assert result.exit_code == 0, result.output + assert "Created backup" in result.output + cmd, = mock_check_output + assert "list-zombie-users | grep -v ^peter$ | xargs" in cmd + + +def test_cli_reset_database_and_datasets(): + result = CliRunner().invoke( + reset.reset, ["--database", "--datasets", "--yes"]) + assert isinstance(result.exception, ValueError) + + +@pytest.mark.usefixtures("no_supervisord") +def test_cli_update(monkeypatch, mock_check_output): + updated = [] + monkeypatch.setattr(update, "update_package", + lambda name: updated.append(name)) + result = CliRunner().invoke(update.update, ["--yes"]) + assert result.exit_code == 0, result.output + assert updated[0] == "dcor_shared" + assert updated[-1] == "dcor_control" + assert mock_check_output[0].endswith("install --upgrade pip") + + +def test_get_bucket_info(tmp_path): + bucket_name = f"test-circle-{uuid.uuid4()}" + path = tmp_path / "file.txt" + path.write_text("0123456789") + for object_name in ["resource/abc/def/123", "condensed/abc/def/123", + "preview/abc/def/123"]: + s3.upload_file(bucket_name=bucket_name, + object_name=object_name, + path=path) + info = status.get_bucket_info(bucket_name, ret_object_keys=True) + assert info == { + "num_resources": 1, + "num_other": 2, + "size_resources": 10, + "size_other": 20, + "object_keys": ["condensed/abc/def/123", "preview/abc/def/123", + "resource/abc/def/123"], + } + + +@pytest.mark.usefixtures("dcor_control_config_dir") +def test_cli_status(monkeypatch): + monkeypatch.setattr(status, "get_package_version", lambda name: "1.0") + result = CliRunner().invoke(status.status) + assert result.exit_code == 0, result.output + assert "DCOR installation:" in result.output + assert "Module dcor_shared 1.0" in result.output + assert "S3 buckets:" in result.output diff --git a/tests/test_config_ckan.py b/tests/test_config_ckan.py new file mode 100644 index 0000000..3bc51f3 --- /dev/null +++ b/tests/test_config_ckan.py @@ -0,0 +1,178 @@ +import json +import socket + +import pytest + +from dcor_control import util +from dcor_control.inspect import config_ckan +from dcor_shared.parse import ConfigOptionNotFoundError + + +def make_site_config_dir(path, hostname=None): + """Create a site configuration directory that matches this machine""" + path.mkdir() + (path / "branding" / "templates").mkdir(parents=True) + (path / "branding" / "public").mkdir(parents=True) + (path / "dcor_config.json").write_text(json.dumps({ + "name": "pytest-site", + "requirements": { + "ip": "unknown", + "hostname": hostname or socket.gethostname()}, + "branding_paths": ["branding"], + "ckan.ini": { + "ckan.site_title": "Pytest ", + "ckan.site_url": "http://", + }, + })) + return path + + +@pytest.fixture +def mock_check_output(monkeypatch): + calls = [] + monkeypatch.setattr(config_ckan.sp, "check_output", + lambda cmd, shell: calls.append(cmd)) + return calls + + +@pytest.fixture +def ckan_options(monkeypatch): + """Pretend to be ckan.ini with options stored in a dictionary""" + options = {} + + def get_ckan_config_option(key): + if key not in options: + raise ConfigOptionNotFoundError(key) + return options[key] + + monkeypatch.setattr(config_ckan, "get_ckan_config_option", + get_ckan_config_option) + return options + + +def test_get_actual_ckan_option(ckan_options): + ckan_options["ckan.site_title"] = "DCOR" + assert config_ckan.get_actual_ckan_option("ckan.site_title") == "DCOR" + assert config_ckan.get_actual_ckan_option("ckan.nope") == "NOT SET!" + + +def test_check_ckan_ini_option(ckan_options, mock_check_output): + ckan_options["ckan.site_title"] = "DCOR" + assert config_ckan.check_ckan_ini_option("ckan.site_title", "DCOR") == 0 + assert not mock_check_output + assert config_ckan.check_ckan_ini_option( + "ckan.site_title", "Peter", autocorrect=True) == 1 + cmd, = mock_check_output + assert cmd.startswith("ckan config-tool ") + assert cmd.endswith("'ckan.site_title=Peter'") + + +def test_check_ckan_ini_option_declined(monkeypatch, ckan_options, + mock_check_output): + monkeypatch.setattr("builtins.input", lambda prompt: "n") + assert config_ckan.check_ckan_ini_option("ckan.site_title", "Peter") == 0 + assert not mock_check_output + + +def test_check_dcor_theme_i18n_hack(ckan_options, mock_check_output): + ckan_options["ckan.locale_default"] = "en_US" + assert config_ckan.check_dcor_theme_i18n_hack(autocorrect=True) == 0 + assert not mock_check_output + ckan_options["ckan.locale_default"] = "en" + assert config_ckan.check_dcor_theme_i18n_hack(autocorrect=True) == 1 + assert mock_check_output[0].endswith("dcor-theme-i18n-branding") + assert mock_check_output[1].endswith("'ckan.locale_default=en_US'") + + +def test_check_dcor_theme_main_css(ckan_options, mock_check_output): + ckan_options["ckan.theme"] = "dcor_theme_main/dcor_theme_main" + assert config_ckan.check_dcor_theme_main_css(autocorrect=True) == 0 + assert not mock_check_output + ckan_options["ckan.theme"] = "css/main" + assert config_ckan.check_dcor_theme_main_css(autocorrect=True) == 1 + assert mock_check_output[0].endswith("dcor-theme-main-css-branding") + assert mock_check_output[1].endswith( + "'ckan.theme=dcor_theme_main/dcor_theme_main'") + assert mock_check_output[2].endswith("dcor-patch-ckan-templates") + + +def test_get_dcor_site_config_dir(monkeypatch, tmp_path): + monkeypatch.delenv("DCOR_SITE_CONFIG_DIR", raising=False) + site_dir = make_site_config_dir(tmp_path / "site") + assert config_ckan.get_dcor_site_config_dir(site_dir) == site_dir + monkeypatch.setenv("DCOR_SITE_CONFIG_DIR", str(site_dir)) + assert config_ckan.get_dcor_site_config_dir() == site_dir + + +def test_get_dcor_site_config_dir_not_applicable(tmp_path): + site_dir = make_site_config_dir(tmp_path / "site", + hostname="not-this-host") + with pytest.raises(ValueError, match="is not applicable"): + config_ckan.get_dcor_site_config_dir(site_dir) + + +def test_get_dcor_site_config_dir_none(monkeypatch): + monkeypatch.delenv("DCOR_SITE_CONFIG_DIR", raising=False) + monkeypatch.setattr(config_ckan, "is_site_config_dir_applicable", + lambda path: False) + assert config_ckan.get_dcor_site_config_dir() is None + assert config_ckan.get_expected_site_options(None) is None + + +def test_get_expected_site_options(tmp_path, dcor_control_config_dir): + site_dir = make_site_config_dir(tmp_path / "site") + util.set_dcor_control_config("pgsqlpass", "s3cr3t") + cfg = config_ckan.get_expected_site_options(site_dir) + assert cfg["name"] == "pytest-site" + assert cfg["dcor_site_config_dir"] == site_dir + opts = cfg["ckan.ini"] + # templates are filled in + assert opts["ckan.site_title"] == f"Pytest {socket.gethostname()}" + assert opts["ckan.site_url"] == f"http://{config_ckan.get_ip()}" + # branding paths + assert opts["extra_template_paths"] == str( + site_dir / "branding" / "templates") + assert opts["extra_public_paths"] == str( + site_dir / "branding" / "public") + # defaults from dcor_defaults.ini.template + assert "ckan.plugins" in opts + assert opts["sqlalchemy.url"] == \ + "postgresql://ckan_default:s3cr3t@localhost/ckan_default" + # setup identifier is stored + assert (dcor_control_config_dir / "setup-identifier").read_text() \ + == "pytest-site" + + +@pytest.mark.usefixtures("dcor_control_config_dir") +def test_check_ckan_ini(monkeypatch, tmp_path): + site_dir = make_site_config_dir(tmp_path / "site") + util.set_dcor_control_config("pgsqlpass", "s3cr3t") + checked = {} + + def check_ckan_ini_option(key, value, autocorrect=False): + checked[key] = value + return int(key == "ckan.site_title") + + monkeypatch.setattr(config_ckan, "check_ckan_ini_option", + check_ckan_ini_option) + assert config_ckan.check_ckan_ini(site_dir, autocorrect=True) == 1 + assert checked["ckan.site_title"] == f"Pytest {socket.gethostname()}" + + +def test_check_ckan_ini_not_managed(monkeypatch): + monkeypatch.setattr(config_ckan, "get_expected_site_options", + lambda path: None) + assert config_ckan.check_ckan_ini() == 0 + + +def test_update_expected_ckan_options_templates(): + cfg = {"a": " is ", + "b": {"c": "", "d": 1}} + config_ckan.update_expected_ckan_options_templates( + cfg, templates={"NAME": [str.upper, ["peter"]], + "AGE": [len, ["four"]]}) + assert cfg == {"a": "PETER is 4", "b": {"c": "PETER", "d": 1}} + + +def test_get_ip(): + assert config_ckan.get_ip().count(".") == 3 diff --git a/tests/test_inspect_common.py b/tests/test_inspect_common.py new file mode 100644 index 0000000..0043a91 --- /dev/null +++ b/tests/test_inspect_common.py @@ -0,0 +1,78 @@ +import os +import pwd +import grp + +from dcor_control.inspect import common + + +def test_check_permission_create_directory(tmp_path): + path = tmp_path / "a" / "b" + assert common.check_permission(path, mode_dir=0o750, autocorrect=True) + assert path.is_dir() + assert path.stat().st_mode & 0o777 == 0o750 + + +def test_check_permission_create_directory_declined(monkeypatch, tmp_path): + monkeypatch.setattr("builtins.input", lambda prompt: "n") + path = tmp_path / "a" + assert common.check_permission(path, mode_dir=0o750) == 0 + assert not path.exists() + + +def test_check_permission_mode(tmp_path): + pdir = tmp_path / "dir" + pdir.mkdir() + pfile = pdir / "file.txt" + pfile.write_text("hello") + os.chmod(pdir, 0o700) + os.chmod(pfile, 0o600) + # recursive check corrects both directory and file + assert common.check_permission(pdir, mode_dir=0o755, mode_file=0o644, + recursive=True, autocorrect=True) == 2 + assert pdir.stat().st_mode & 0o777 == 0o755 + assert pfile.stat().st_mode & 0o777 == 0o644 + # nothing to do anymore + assert common.check_permission(pdir, mode_dir=0o755, mode_file=0o644, + recursive=True, autocorrect=True) == 0 + + +def test_check_permission_mode_ask(monkeypatch, tmp_path): + pfile = tmp_path / "file.txt" + pfile.write_text("hello") + os.chmod(pfile, 0o600) + monkeypatch.setattr("builtins.input", lambda prompt: "n") + assert common.check_permission(pfile, mode_file=0o644) == 0 + assert pfile.stat().st_mode & 0o777 == 0o600 + monkeypatch.setattr("builtins.input", lambda prompt: "y") + assert common.check_permission(pfile, mode_file=0o644) == 1 + assert pfile.stat().st_mode & 0o777 == 0o644 + + +def test_check_permission_owner(monkeypatch, tmp_path): + pfile = tmp_path / "file.txt" + pfile.write_text("hello") + user = pwd.getpwuid(os.getuid()).pw_name + group = grp.getgrgid(os.getgid()).gr_name + # owner is correct + assert common.check_permission(pfile, user=user, group=group) == 0 + # owner is wrong (pretend another uid), but user declines + chown_calls = [] + monkeypatch.setattr(os, "chown", + lambda *args: chown_calls.append(args)) + monkeypatch.setattr(pwd, "getpwnam", lambda name: pwd.struct_passwd( + ("other", "x", 12345, 12345, "", "/", "/bin/sh"))) + monkeypatch.setattr(grp, "getgrnam", lambda name: grp.struct_group( + ("other", "x", 12345, []))) + monkeypatch.setattr("builtins.input", lambda prompt: "n") + assert common.check_permission(pfile, user="other") == 0 + assert not chown_calls + assert common.check_permission(pfile, user="other", + autocorrect=True) == 1 + assert chown_calls == [(pfile, 12345, 12345)] + + +def test_recursive_update_dict(): + d = {"a": 1, "b": {"c": 2, "d": 3}} + u = {"b": {"c": 4, "e": {"f": 5}}, "g": 6} + assert common.recursive_update_dict(d, u) == { + "a": 1, "b": {"c": 4, "d": 3, "e": {"f": 5}}, "g": 6} diff --git a/tests/test_update.py b/tests/test_update.py index 731281c..b55e80e 100644 --- a/tests/test_update.py +++ b/tests/test_update.py @@ -1,6 +1,10 @@ -import pytest +import os +import subprocess as sp +import types import uuid +import pytest + import numpy as np from dcor_control import update @@ -103,3 +107,69 @@ def test_version_greater(va, vb, result): ]) def test_version_greater_equal(va, vb, result): assert update.version_greater_equal(va, vb) == result + + +def test_get_package_version_git(tmp_path): + repo = tmp_path / "ckanext-peter" + repo.mkdir() + git = f"git -C {repo} -c user.name=pytest -c user.email=pytest@localhost" + sp.check_output(f"{git} init -q", shell=True) + sp.check_output(f"{git} commit -q --allow-empty -m init", shell=True) + sp.check_output(f"{git} tag -a 1.2.3 -m 1.2.3", shell=True) + # the "." in the name is replaced with "-" + assert update.get_package_version_git("ckanext.peter", tmp_path) \ + == "1.2.3" + with pytest.raises(ValueError, match="Could not find ckanext.hans"): + update.get_package_version_git("ckanext.hans", tmp_path) + + +@pytest.fixture +def mock_update_package(monkeypatch, tmp_path): + """Pretend to be a package installed in `tmp_path / "pkg"`""" + calls = [] + pkg_dir = tmp_path / "pkg" / "dcor_peter" + pkg_dir.mkdir(parents=True) + module = types.SimpleNamespace(__file__=str(pkg_dir / "__init__.py")) + monkeypatch.setattr(update.importlib, "import_module", + lambda name: module) + monkeypatch.setattr(update.sp, "check_output", + lambda cmd, shell: calls.append(cmd)) + versions = iter(["1.0.0", "1.1.0"]) + monkeypatch.setattr(update, "get_package_version", + lambda name: next(versions)) + monkeypatch.setattr(update, "get_pip_executable_path", lambda: "pip") + return calls, tmp_path / "pkg" + + +@pytest.mark.parametrize("req_version,pin", [(None, ""), ("1.0.5", "==1.0.5")]) +def test_update_package_pip(monkeypatch, capsys, mock_update_package, + req_version, pin): + calls, _ = mock_update_package + monkeypatch.setattr(update, "get_max_compatible_version", + lambda name: req_version) + assert update.update_package("dcor_peter") == "1.1.0" + assert calls == [f"pip install --upgrade dcor_peter{pin}"] + assert "updated dcor_peter from 1.0.0 to 1.1.0" in capsys.readouterr().out + + +def test_update_package_git(mock_update_package): + calls, pkg_root = mock_update_package + (pkg_root / ".git").mkdir() + wd = os.getcwd() + assert update.update_package("dcor_peter") == "1.1.0" + assert calls == ["git pull", "pip install -e ."] + assert os.getcwd() == wd + + +def test_update_package_git_pull_fails(monkeypatch, mock_update_package): + calls, pkg_root = mock_update_package + (pkg_root / ".git").mkdir() + + def check_output(cmd, shell): + calls.append(cmd) + raise sp.CalledProcessError(1, cmd) + + monkeypatch.setattr(update.sp, "check_output", check_output) + update.update_package("dcor_peter") + # pip is not called when git pull failed + assert calls == ["git pull"] diff --git a/tests/test_util.py b/tests/test_util.py new file mode 100644 index 0000000..6bdddc2 --- /dev/null +++ b/tests/test_util.py @@ -0,0 +1,49 @@ +import sys + +import pytest + +from dcor_control import util + + +def test_dcor_control_config(dcor_control_config_dir): + assert util.set_dcor_control_config("email", "peter@example.com") \ + == "peter@example.com" + assert util.get_dcor_control_config("email") == "peter@example.com" + assert (dcor_control_config_dir / "email").stat().st_mode & 0o777 \ + == 0o600 + + +@pytest.mark.usefixtures("dcor_control_config_dir") +def test_dcor_control_config_not_interactive(): + assert util.get_dcor_control_config("email", interactive=False) is None + + +def test_dcor_control_config_prompt(monkeypatch, capsys, + dcor_control_config_dir): + monkeypatch.setattr("builtins.input", lambda prompt: "hans@example.com") + data = util.get_dcor_control_config("email", + custom_message="Hello Hans") + assert data == "hans@example.com" + assert "Hello Hans" in capsys.readouterr().out + # stored for later use + assert (dcor_control_config_dir / "email").read_text() \ + == "hans@example.com" + + +def test_get_module_installation_path(): + assert util.get_module_installation_path("dcor_control").endswith( + "dcor_control") + assert util.get_module_installation_path( + "dcor_control_nonexistent_module") == "/tmp/unknown" + + +def test_get_pip_executable_path(monkeypatch, tmp_path): + (tmp_path / "pip").touch() + monkeypatch.setattr(sys, "path", [str(tmp_path / "nope"), str(tmp_path)]) + assert util.get_pip_executable_path() == tmp_path / "pip" + + +def test_get_pip_executable_path_not_found(monkeypatch, tmp_path): + monkeypatch.setattr(sys, "path", [str(tmp_path)]) + with pytest.raises(ValueError, match="Could not find `pip`"): + util.get_pip_executable_path()