Cleaned Up tests

This commit is contained in:
Kevin Veen-Birkenbach committed 2025-12-09 14:33:32 +01:00
1 parent d50891dfe5
commit a4efb847ba
47 files changed
+4 -8

No files matched your search

View File
Whitespace-only changes.
Whitespace-only changes.
@@ -0,0 +1,206 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Unit tests for pkgmgr.cli.commands.release.
These tests focus on the wiring layer:
- Argument handling for the release command as defined by the
top-level parser (cli.parser.create_parser).
- Correct invocation of pkgmgr.actions.release.release(...) for the
selected repositories.
- Behaviour of --preview, --list, --close, and -f/--force.
"""
from __future__ import annotations
from types import SimpleNamespace
from typing import List
from unittest.mock import patch, call
import argparse
import unittest
class TestReleaseCommand(unittest.TestCase):
"""
Tests for the `pkgmgr release` CLI wiring.
"""
def _make_ctx(self, all_repos: List[dict]) -> SimpleNamespace:
"""
Create a minimal CLIContext-like object for tests.
Only the attributes that handle_release() uses are provided.
"""
return SimpleNamespace(
config_merged={},
repositories_base_dir="/base/dir",
all_repositories=all_repos,
binaries_dir="/bin",
user_config_path="/tmp/config.yaml",
)
def _parse_release_args(self, argv: List[str]) -> argparse.Namespace:
"""
Build a real top-level parser and parse the given argv list
to obtain the Namespace for the `release` command.
"""
from pkgmgr.cli.parser import create_parser
parser = create_parser("test parser")
args = parser.parse_args(argv)
self.assertEqual(args.command, "release")
return args
@patch("pkgmgr.cli.commands.release.os.path.isdir", return_value=True)
@patch("pkgmgr.cli.commands.release.run_release")
@patch("pkgmgr.cli.commands.release.get_repo_dir")
@patch("pkgmgr.cli.commands.release.get_repo_identifier")
@patch("pkgmgr.cli.commands.release.os.chdir")
@patch("pkgmgr.cli.commands.release.os.getcwd", return_value="/cwd")
def test_release_with_close_and_message(
self,
mock_getcwd,
mock_chdir,
mock_get_repo_identifier,
mock_get_repo_dir,
mock_run_release,
mock_isdir,
) -> None:
"""
The release handler should call pkgmgr.actions.release.release() with:
- release_type (e.g. minor)
- provided message
- preview flag
- force flag
- close flag
It must change into the repository directory and then back.
"""
from pkgmgr.cli.commands.release import handle_release
repo = {"name": "dummy-repo"}
selected = [repo]
ctx = self._make_ctx(selected)
mock_get_repo_identifier.return_value = "dummy-id"
mock_get_repo_dir.return_value = "/repos/dummy"
argv = [
"release",
"minor",
"dummy-id",
"-m",
"Close branch after minor release",
"--close",
"-f",
]
args = self._parse_release_args(argv)
handle_release(args, ctx, selected)
# We should have changed into the repo dir and then back.
mock_chdir.assert_has_calls(
[call("/repos/dummy"), call("/cwd")]
)
# And run_release should be invoked once with the expected parameters.
mock_run_release.assert_called_once_with(
pyproject_path="pyproject.toml",
changelog_path="CHANGELOG.md",
release_type="minor",
message="Close branch after minor release",
preview=False,
force=True,
close=True,
)
@patch("pkgmgr.cli.commands.release.os.path.isdir", return_value=True)
@patch("pkgmgr.cli.commands.release.run_release")
@patch("pkgmgr.cli.commands.release.get_repo_dir")
@patch("pkgmgr.cli.commands.release.get_repo_identifier")
@patch("pkgmgr.cli.commands.release.os.chdir")
@patch("pkgmgr.cli.commands.release.os.getcwd", return_value="/cwd")
def test_release_preview_mode(
self,
mock_getcwd,
mock_chdir,
mock_get_repo_identifier,
mock_get_repo_dir,
mock_run_release,
mock_isdir,
) -> None:
"""
In preview mode, the handler should pass preview=True to the
release helper and force=False by default.
"""
from pkgmgr.cli.commands.release import handle_release
repo = {"name": "dummy-repo"}
selected = [repo]
ctx = self._make_ctx(selected)
mock_get_repo_identifier.return_value = "dummy-id"
mock_get_repo_dir.return_value = "/repos/dummy"
argv = [
"release",
"patch",
"dummy-id",
"--preview",
]
args = self._parse_release_args(argv)
handle_release(args, ctx, selected)
mock_run_release.assert_called_once_with(
pyproject_path="pyproject.toml",
changelog_path="CHANGELOG.md",
release_type="patch",
message=None,
preview=True,
force=False,
close=False,
)
@patch("pkgmgr.cli.commands.release.run_release")
@patch("pkgmgr.cli.commands.release.get_repo_dir")
@patch("pkgmgr.cli.commands.release.get_repo_identifier")
def test_release_list_mode_does_not_invoke_helper(
self,
mock_get_repo_identifier,
mock_get_repo_dir,
mock_run_release,
) -> None:
"""
When --list is provided, the handler should print the list of affected
repositories and must NOT invoke run_release().
"""
from pkgmgr.cli.commands.release import handle_release
repo1 = {"name": "repo-1"}
repo2 = {"name": "repo-2"}
selected = [repo1, repo2]
ctx = self._make_ctx(selected)
mock_get_repo_identifier.side_effect = ["id-1", "id-2"]
argv = [
"release",
"major",
"--list",
]
args = self._parse_release_args(argv)
handle_release(args, ctx, selected)
mock_run_release.assert_not_called()
self.assertEqual(
mock_get_repo_identifier.call_args_list,
[call(repo1, selected), call(repo2, selected)],
)
if __name__ == "__main__":
unittest.main()
+112
View File
@@ -0,0 +1,112 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Unit tests for the `pkgmgr branch` CLI wiring.
These tests verify that:
- The argument parser creates the correct structure for
`branch open` and `branch close`.
- `handle_branch` calls the corresponding helper functions
with the expected arguments (including base branch and cwd).
"""
from __future__ import annotations
import unittest
from unittest.mock import patch
from pkgmgr.cli.parser import create_parser
from pkgmgr.cli.commands.branch import handle_branch
class TestBranchCLI(unittest.TestCase):
"""
Tests for the branch subcommands implemented in cli.
"""
def _create_parser(self):
"""
Create the top-level parser with a minimal description.
"""
return create_parser("pkgmgr test parser")
@patch("pkgmgr.cli.commands.branch.open_branch")
def test_branch_open_with_name_and_base(self, mock_open_branch):
"""
Ensure that `pkgmgr branch open <name> --base <branch>` calls
open_branch() with the correct parameters.
"""
parser = self._create_parser()
args = parser.parse_args(
["branch", "open", "feature/test-branch", "--base", "develop"]
)
# Sanity check: parser wiring
self.assertEqual(args.command, "branch")
self.assertEqual(args.subcommand, "open")
self.assertEqual(args.name, "feature/test-branch")
self.assertEqual(args.base, "develop")
# ctx is currently unused by handle_branch, so we can pass None
handle_branch(args, ctx=None)
mock_open_branch.assert_called_once()
_args, kwargs = mock_open_branch.call_args
self.assertEqual(kwargs.get("name"), "feature/test-branch")
self.assertEqual(kwargs.get("base_branch"), "develop")
self.assertEqual(kwargs.get("cwd"), ".")
@patch("pkgmgr.cli.commands.branch.close_branch")
def test_branch_close_with_name_and_base(self, mock_close_branch):
"""
Ensure that `pkgmgr branch close <name> --base <branch>` calls
close_branch() with the correct parameters.
"""
parser = self._create_parser()
args = parser.parse_args(
["branch", "close", "feature/old-branch", "--base", "main"]
)
# Sanity check: parser wiring
self.assertEqual(args.command, "branch")
self.assertEqual(args.subcommand, "close")
self.assertEqual(args.name, "feature/old-branch")
self.assertEqual(args.base, "main")
handle_branch(args, ctx=None)
mock_close_branch.assert_called_once()
_args, kwargs = mock_close_branch.call_args
self.assertEqual(kwargs.get("name"), "feature/old-branch")
self.assertEqual(kwargs.get("base_branch"), "main")
self.assertEqual(kwargs.get("cwd"), ".")
@patch("pkgmgr.cli.commands.branch.close_branch")
def test_branch_close_without_name_uses_none(self, mock_close_branch):
"""
Ensure that `pkgmgr branch close` without a name passes name=None
into close_branch(), leaving branch resolution to the helper.
"""
parser = self._create_parser()
args = parser.parse_args(["branch", "close"])
# Parser wiring: no name → None
self.assertEqual(args.command, "branch")
self.assertEqual(args.subcommand, "close")
self.assertIsNone(args.name)
handle_branch(args, ctx=None)
mock_close_branch.assert_called_once()
_args, kwargs = mock_close_branch.call_args
self.assertIsNone(kwargs.get("name"))
self.assertEqual(kwargs.get("base_branch"), "main")
self.assertEqual(kwargs.get("cwd"), ".")
if __name__ == "__main__":
unittest.main()
+247
View File
@@ -0,0 +1,247 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Unit tests for the pkgmgr CLI (version command).
These tests focus on the 'version' subcommand and its interaction with:
- git tags (SemVer),
- pyproject.toml version,
- and the mismatch warning logic.
Important:
- Uses only the Python standard library unittest framework.
- Does not use pytest.
- Does not rely on a real git repository or real config files.
"""
from __future__ import annotations
import io
import os
import sys
import tempfile
import textwrap
import unittest
from contextlib import redirect_stdout
from typing import Any, Dict, List
from unittest import mock
from pkgmgr import cli
def _fake_config() -> Dict[str, Any]:
"""
Provide a minimal configuration dict sufficient for cli.main()
to start without touching real config files.
"""
return {
"directories": {
"repositories": "/tmp/pkgmgr-repos",
"binaries": "/tmp/pkgmgr-bin",
"workspaces": "/tmp/pkgmgr-workspaces",
},
# The actual list of repositories is not used directly by the tests,
# because we mock the selection logic. It must exist, though.
"repositories": [],
}
class TestCliVersion(unittest.TestCase):
"""
Tests for the 'pkgmgr version' command.
Each test:
- Runs in a temporary working directory.
- Uses a fake configuration via load_config().
- Uses the same selection logic as the new CLI:
* dispatch_command() calls _select_repo_for_current_directory()
when there is no explicit selection.
"""
def setUp(self) -> None:
# Create a temporary directory and switch into it
self._tmp_dir = tempfile.TemporaryDirectory()
self._old_cwd = os.getcwd()
os.chdir(self._tmp_dir.name)
# Define a fake repo pointing to our temp dir
self._fake_repo = {
"provider": "github.com",
"account": "test",
"repository": "pkgmgr-test",
"directory": self._tmp_dir.name,
}
# Patch load_config so cli.main() does not read real config files
self._patch_load_config = mock.patch(
"pkgmgr.cli.load_config", return_value=_fake_config()
)
self.mock_load_config = self._patch_load_config.start()
# Patch the "current directory" selection used by dispatch_command().
# This matches the new behaviour: without explicit identifiers,
# version uses _select_repo_for_current_directory(ctx).
self._patch_select_repo_for_current_directory = mock.patch(
"pkgmgr.cli.dispatch._select_repo_for_current_directory",
return_value=[self._fake_repo],
)
self.mock_select_repo_for_current_directory = (
self._patch_select_repo_for_current_directory.start()
)
# Keep a reference to the original sys.argv, so we can restore it
self._old_argv = list(sys.argv)
def tearDown(self) -> None:
# Restore sys.argv
sys.argv = self._old_argv
# Stop all patches
self._patch_select_repo_for_current_directory.stop()
self._patch_load_config.stop()
# Restore working directory
os.chdir(self._old_cwd)
# Cleanup temp directory
self._tmp_dir.cleanup()
# ------------------------------------------------------------
# Helpers
# ------------------------------------------------------------
def _write_pyproject(self, version: str) -> str:
"""
Write a minimal PEP 621-style pyproject.toml into the temp directory.
"""
content = textwrap.dedent(
f"""
[project]
name = "pkgmgr-test"
version = "{version}"
"""
).strip() + "\n"
path = os.path.join(self._tmp_dir.name, "pyproject.toml")
with open(path, "w", encoding="utf-8") as f:
f.write(content)
return path
def _run_cli_version_and_capture(
self,
extra_args: List[str] | None = None,
) -> str:
"""
Run 'pkgmgr version [extra_args]' via cli.main() and return captured stdout.
"""
if extra_args is None:
extra_args = []
sys.argv = ["pkgmgr", "version"] + list(extra_args)
buf = io.StringIO()
with redirect_stdout(buf):
try:
cli.main()
except SystemExit as exc:
# Re-raise as AssertionError to make failures easier to read
raise AssertionError(
f"'pkgmgr version' exited with code {exc.code}"
) from exc
return buf.getvalue()
# ------------------------------------------------------------
# Tests
# ------------------------------------------------------------
def test_version_matches_tag(self) -> None:
"""
If the latest SemVer tag matches the pyproject.toml version,
the CLI should:
- show both values
- NOT emit a mismatch warning.
"""
# Arrange: pyproject.toml with version 1.2.3
self._write_pyproject("1.2.3")
# Arrange: mock git tags used by handle_version
with mock.patch(
"pkgmgr.cli.commands.version.get_tags",
return_value=["v1.2.0", "v1.2.3", "v1.0.0"],
):
# Act
stdout = self._run_cli_version_and_capture()
# Basic header
self.assertIn("pkgmgr version info", stdout)
self.assertIn("Repository:", stdout)
# Git SemVer tag line
self.assertIn("Git (latest SemVer tag):", stdout)
self.assertIn("v1.2.3", stdout)
self.assertIn("(parsed: 1.2.3)", stdout)
# pyproject line
self.assertIn("pyproject.toml:", stdout)
self.assertIn("1.2.3", stdout)
# No warning expected if versions are equal
self.assertNotIn("[WARN]", stdout)
def test_version_mismatch_warns(self) -> None:
"""
If the latest SemVer tag differs from the pyproject.toml version,
the CLI should emit a mismatch warning.
"""
# Arrange: pyproject.toml says 1.2.4
self._write_pyproject("1.2.4")
# Arrange: mock git tags (latest is 1.2.3)
with mock.patch(
"pkgmgr.cli.commands.version.get_tags",
return_value=["v1.2.3"],
):
stdout = self._run_cli_version_and_capture()
# Git line
self.assertIn("Git (latest SemVer tag):", stdout)
self.assertIn("v1.2.3", stdout)
# pyproject line
self.assertIn("pyproject.toml:", stdout)
self.assertIn("1.2.4", stdout)
# Mismatch warning must be printed
self.assertIn("[WARN]", stdout)
self.assertIn("Version mismatch", stdout)
def test_version_no_tags(self) -> None:
"""
If no tags exist at all, the CLI should handle this gracefully,
show "<none found>" for tags and still display the pyproject version.
No mismatch warning should be emitted because there is no tag.
"""
# Arrange: pyproject.toml exists
self._write_pyproject("0.0.1")
# Arrange: no tags returned
with mock.patch(
"pkgmgr.cli.commands.version.get_tags",
return_value=[],
):
stdout = self._run_cli_version_and_capture()
# Indicates that no SemVer tag was found
self.assertIn("Git (latest SemVer tag): <none found>", stdout)
# pyproject version is still shown
self.assertIn("pyproject.toml:", stdout)
self.assertIn("0.0.1", stdout)
# No mismatch warning expected
self.assertNotIn("Version mismatch", stdout)
self.assertNotIn("[WARN]", stdout)
if __name__ == "__main__":
unittest.main()
+135
View File
@@ -0,0 +1,135 @@
from __future__ import annotations
import unittest
from types import SimpleNamespace
from unittest.mock import patch
from pkgmgr.cli.commands.branch import handle_branch
from pkgmgr.cli.context import CLIContext
class TestCliBranch(unittest.TestCase):
def _dummy_ctx(self) -> CLIContext:
"""
Minimal CLIContext; handle_branch does not actually use it,
but we keep the type consistent.
"""
return CLIContext(
config_merged={},
repositories_base_dir="/tmp/repos",
all_repositories=[],
binaries_dir="/tmp/bin",
user_config_path="/tmp/config.yaml",
)
@patch("pkgmgr.cli.commands.branch.open_branch")
def test_handle_branch_open_forwards_args_to_open_branch(self, mock_open_branch) -> None:
"""
handle_branch('open') should call open_branch with name, base and cwd='.'.
"""
args = SimpleNamespace(
command="branch",
subcommand="open",
name="feature/cli-test",
base="develop",
)
ctx = self._dummy_ctx()
handle_branch(args, ctx)
mock_open_branch.assert_called_once()
call_args, call_kwargs = mock_open_branch.call_args
self.assertEqual(call_kwargs.get("name"), "feature/cli-test")
self.assertEqual(call_kwargs.get("base_branch"), "develop")
self.assertEqual(call_kwargs.get("cwd"), ".")
@patch("pkgmgr.cli.commands.branch.open_branch")
def test_handle_branch_open_uses_default_base_when_not_set(self, mock_open_branch) -> None:
"""
If --base is not passed, argparse gives base='main' (default),
and handle_branch should propagate that to open_branch.
"""
args = SimpleNamespace(
command="branch",
subcommand="open",
name=None,
base="main",
)
ctx = self._dummy_ctx()
handle_branch(args, ctx)
mock_open_branch.assert_called_once()
_, call_kwargs = mock_open_branch.call_args
self.assertIsNone(call_kwargs.get("name"))
self.assertEqual(call_kwargs.get("base_branch"), "main")
self.assertEqual(call_kwargs.get("cwd"), ".")
# ------------------------------------------------------------------
# close subcommand
# ------------------------------------------------------------------
@patch("pkgmgr.cli.commands.branch.close_branch")
def test_handle_branch_close_forwards_args_to_close_branch(self, mock_close_branch) -> None:
"""
handle_branch('close') should call close_branch with name, base and cwd='.'.
"""
args = SimpleNamespace(
command="branch",
subcommand="close",
name="feature/cli-close",
base="develop",
)
ctx = self._dummy_ctx()
handle_branch(args, ctx)
mock_close_branch.assert_called_once()
_, call_kwargs = mock_close_branch.call_args
self.assertEqual(call_kwargs.get("name"), "feature/cli-close")
self.assertEqual(call_kwargs.get("base_branch"), "develop")
self.assertEqual(call_kwargs.get("cwd"), ".")
@patch("pkgmgr.cli.commands.branch.close_branch")
def test_handle_branch_close_uses_default_base_when_not_set(self, mock_close_branch) -> None:
"""
If --base is not passed for 'close', argparse gives base='main'
(default), and handle_branch should propagate that to close_branch.
"""
args = SimpleNamespace(
command="branch",
subcommand="close",
name=None,
base="main",
)
ctx = self._dummy_ctx()
handle_branch(args, ctx)
mock_close_branch.assert_called_once()
_, call_kwargs = mock_close_branch.call_args
self.assertIsNone(call_kwargs.get("name"))
self.assertEqual(call_kwargs.get("base_branch"), "main")
self.assertEqual(call_kwargs.get("cwd"), ".")
def test_handle_branch_unknown_subcommand_exits_with_code_2(self) -> None:
"""
Unknown branch subcommand should result in SystemExit(2).
"""
args = SimpleNamespace(
command="branch",
subcommand="unknown",
)
ctx = self._dummy_ctx()
with self.assertRaises(SystemExit) as cm:
handle_branch(args, ctx)
self.assertEqual(cm.exception.code, 2)
if __name__ == "__main__":
unittest.main()