Commit d6e849ee authored by Thiago Kenji Okada's avatar Thiago Kenji Okada
Browse files

nixos-rebuild-ng: {assert_called_with,assert_has_calls} -> {call_args,call_args_list}

This allow usage of pytest's `assert`, allowing for better diffs when
there are errors, and also removes the need of asserting for `call_count`.
parent 5df5ff8f
Loading
Loading
Loading
Loading
+499 −532
Original line number Diff line number Diff line
@@ -4,7 +4,7 @@ import uuid
from pathlib import Path
from subprocess import PIPE, CompletedProcess
from typing import Any
from unittest.mock import ANY, call, patch
from unittest.mock import ANY, Mock, call, patch

import pytest

@@ -127,7 +127,7 @@ def test_parse_args() -> None:

@patch.dict(nr.process.os.environ, {}, clear=True)
@patch(get_qualified_name(nr.process.subprocess.run), autospec=True)
def test_execute_nix_boot(mock_run: Any, tmp_path: Path) -> None:
def test_execute_nix_boot(mock_run: Mock, tmp_path: Path) -> None:
    nixpkgs_path = tmp_path / "nixpkgs"
    nixpkgs_path.mkdir()
    config_path = tmp_path / "test"
@@ -147,9 +147,7 @@ def test_execute_nix_boot(mock_run: Any, tmp_path: Path) -> None:

    nr.execute(["nixos-rebuild", "boot", "--no-flake", "-vvv", "--no-reexec"])

    assert mock_run.call_count == 6
    mock_run.assert_has_calls(
        [
    assert mock_run.call_args_list == [
        call(
            ["nix-instantiate", "--find-file", "nixpkgs", "-vvv"],
            stdout=PIPE,
@@ -197,12 +195,11 @@ def test_execute_nix_boot(mock_run: Any, tmp_path: Path) -> None:
            **(DEFAULT_RUN_KWARGS | {"env": {"NIXOS_INSTALL_BOOTLOADER": "0"}}),
        ),
    ]
    )


@patch.dict(nr.process.os.environ, {}, clear=True)
@patch(get_qualified_name(nr.process.subprocess.run), autospec=True)
def test_execute_nix_build_vm(mock_run: Any, tmp_path: Path) -> None:
def test_execute_nix_build_vm(mock_run: Mock, tmp_path: Path) -> None:
    config_path = tmp_path / "test"
    config_path.touch()

@@ -227,9 +224,7 @@ def test_execute_nix_build_vm(mock_run: Any, tmp_path: Path) -> None:
        ]
    )

    assert mock_run.call_count == 1
    mock_run.assert_has_calls(
        [
    assert mock_run.call_args_list == [
        call(
            [
                "nix-build",
@@ -246,12 +241,11 @@ def test_execute_nix_build_vm(mock_run: Any, tmp_path: Path) -> None:
            **DEFAULT_RUN_KWARGS,
        )
    ]
    )


@patch.dict(nr.process.os.environ, {}, clear=True)
@patch(get_qualified_name(nr.process.subprocess.run), autospec=True)
def test_execute_nix_build_image_flake(mock_run: Any, tmp_path: Path) -> None:
def test_execute_nix_build_image_flake(mock_run: Mock, tmp_path: Path) -> None:
    config_path = tmp_path / "test"
    config_path.touch()

@@ -285,9 +279,7 @@ def test_execute_nix_build_image_flake(mock_run: Any, tmp_path: Path) -> None:
        ]
    )

    assert mock_run.call_count == 2
    mock_run.assert_has_calls(
        [
    assert mock_run.call_args_list == [
        call(
            [
                "nix",
@@ -315,12 +307,11 @@ def test_execute_nix_build_image_flake(mock_run: Any, tmp_path: Path) -> None:
            **DEFAULT_RUN_KWARGS,
        ),
    ]
    )


@patch.dict(nr.process.os.environ, {}, clear=True)
@patch(get_qualified_name(nr.process.subprocess.run), autospec=True)
def test_execute_nix_switch_flake(mock_run: Any, tmp_path: Path) -> None:
def test_execute_nix_switch_flake(mock_run: Mock, tmp_path: Path) -> None:
    config_path = tmp_path / "test"
    config_path.touch()

@@ -349,9 +340,7 @@ def test_execute_nix_switch_flake(mock_run: Any, tmp_path: Path) -> None:
        ]
    )

    assert mock_run.call_count == 3
    mock_run.assert_has_calls(
        [
    assert mock_run.call_args_list == [
        call(
            [
                "nix",
@@ -388,7 +377,6 @@ def test_execute_nix_switch_flake(mock_run: Any, tmp_path: Path) -> None:
            **(DEFAULT_RUN_KWARGS | {"env": {"NIXOS_INSTALL_BOOTLOADER": "1"}}),
        ),
    ]
    )


@patch.dict(nr.process.os.environ, {}, clear=True)
@@ -396,9 +384,9 @@ def test_execute_nix_switch_flake(mock_run: Any, tmp_path: Path) -> None:
@patch(get_qualified_name(nr.cleanup_ssh, nr), autospec=True)
@patch(get_qualified_name(nr.nix.uuid4, nr.nix), autospec=True)
def test_execute_nix_switch_build_target_host(
    mock_uuid4: Any,
    mock_cleanup_ssh: Any,
    mock_run: Any,
    mock_uuid4: Mock,
    mock_cleanup_ssh: Mock,
    mock_run: Mock,
    tmp_path: Path,
) -> None:
    config_path = tmp_path / "test"
@@ -442,9 +430,7 @@ def test_execute_nix_switch_build_target_host(
        ]
    )

    assert mock_run.call_count == 10
    mock_run.assert_has_calls(
        [
    assert mock_run.call_args_list == [
        call(
            [
                "nix-instantiate",
@@ -584,15 +570,14 @@ def test_execute_nix_switch_build_target_host(
            **DEFAULT_RUN_KWARGS,
        ),
    ]
    )


@patch.dict(nr.process.os.environ, {}, clear=True)
@patch(get_qualified_name(nr.process.subprocess.run), autospec=True)
@patch(get_qualified_name(nr.cleanup_ssh, nr), autospec=True)
def test_execute_nix_switch_flake_target_host(
    mock_cleanup_ssh: Any,
    mock_run: Any,
    mock_cleanup_ssh: Mock,
    mock_run: Mock,
    tmp_path: Path,
) -> None:
    config_path = tmp_path / "test"
@@ -619,9 +604,7 @@ def test_execute_nix_switch_flake_target_host(
        ]
    )

    assert mock_run.call_count == 4
    mock_run.assert_has_calls(
        [
    assert mock_run.call_args_list == [
        call(
            [
                "nix",
@@ -673,15 +656,14 @@ def test_execute_nix_switch_flake_target_host(
            **DEFAULT_RUN_KWARGS,
        ),
    ]
    )


@patch.dict(nr.process.os.environ, {}, clear=True)
@patch(get_qualified_name(nr.process.subprocess.run), autospec=True)
@patch(get_qualified_name(nr.cleanup_ssh, nr), autospec=True)
def test_execute_nix_switch_flake_build_host(
    mock_cleanup_ssh: Any,
    mock_run: Any,
    mock_cleanup_ssh: Mock,
    mock_run: Mock,
    tmp_path: Path,
) -> None:
    config_path = tmp_path / "test"
@@ -709,9 +691,7 @@ def test_execute_nix_switch_flake_build_host(
        ]
    )

    assert mock_run.call_count == 6
    mock_run.assert_has_calls(
        [
    assert mock_run.call_args_list == [
        call(
            [
                "nix",
@@ -775,11 +755,10 @@ def test_execute_nix_switch_flake_build_host(
            **DEFAULT_RUN_KWARGS,
        ),
    ]
    )


@patch(get_qualified_name(nr.process.subprocess.run), autospec=True)
def test_execute_switch_rollback(mock_run: Any, tmp_path: Path) -> None:
def test_execute_switch_rollback(mock_run: Mock, tmp_path: Path) -> None:
    nixpkgs_path = tmp_path / "nixpkgs"
    nixpkgs_path.touch()

@@ -804,9 +783,7 @@ def test_execute_switch_rollback(mock_run: Any, tmp_path: Path) -> None:
        ]
    )

    assert mock_run.call_count == 4
    mock_run.assert_has_calls(
        [
    assert mock_run.call_args_list == [
        call(
            ["nix-instantiate", "--find-file", "nixpkgs"],
            check=False,
@@ -845,11 +822,10 @@ def test_execute_switch_rollback(mock_run: Any, tmp_path: Path) -> None:
            **DEFAULT_RUN_KWARGS,
        ),
    ]
    )


@patch(get_qualified_name(nr.process.subprocess.run), autospec=True)
def test_execute_build(mock_run: Any, tmp_path: Path) -> None:
def test_execute_build(mock_run: Mock, tmp_path: Path) -> None:
    config_path = tmp_path / "test"
    config_path.touch()
    mock_run.side_effect = [
@@ -859,9 +835,7 @@ def test_execute_build(mock_run: Any, tmp_path: Path) -> None:

    nr.execute(["nixos-rebuild", "build", "--no-flake", "--no-reexec"])

    assert mock_run.call_count == 1
    mock_run.assert_has_calls(
        [
    assert mock_run.call_args_list == [
        call(
            [
                "nix-build",
@@ -874,11 +848,10 @@ def test_execute_build(mock_run: Any, tmp_path: Path) -> None:
            **DEFAULT_RUN_KWARGS,
        )
    ]
    )


@patch(get_qualified_name(nr.process.subprocess.run), autospec=True)
def test_execute_test_flake(mock_run: Any, tmp_path: Path) -> None:
def test_execute_test_flake(mock_run: Mock, tmp_path: Path) -> None:
    config_path = tmp_path / "test"
    config_path.touch()

@@ -894,9 +867,7 @@ def test_execute_test_flake(mock_run: Any, tmp_path: Path) -> None:
        ["nixos-rebuild", "test", "--flake", "github:user/repo#hostname", "--no-reexec"]
    )

    assert mock_run.call_count == 2
    mock_run.assert_has_calls(
        [
    assert mock_run.call_args_list == [
        call(
            [
                "nix",
@@ -916,16 +887,15 @@ def test_execute_test_flake(mock_run: Any, tmp_path: Path) -> None:
            **DEFAULT_RUN_KWARGS,
        ),
    ]
    )


@patch(get_qualified_name(nr.process.subprocess.run), autospec=True)
@patch(get_qualified_name(nr.nix.Path.exists, nr.nix), autospec=True, return_value=True)
@patch(get_qualified_name(nr.nix.Path.mkdir, nr.nix), autospec=True)
def test_execute_test_rollback(
    mock_path_mkdir: Any,
    mock_path_exists: Any,
    mock_run: Any,
    mock_path_mkdir: Mock,
    mock_path_exists: Mock,
    mock_run: Mock,
) -> None:
    def run_side_effect(args: list[str], **kwargs: Any) -> CompletedProcess[str]:
        if args[0] == "nix-env":
@@ -947,9 +917,7 @@ def test_execute_test_rollback(
        ["nixos-rebuild", "test", "--rollback", "--profile-name", "foo", "--no-reexec"]
    )

    assert mock_run.call_count == 2
    mock_run.assert_has_calls(
        [
    assert mock_run.call_args_list == [
        call(
            [
                "nix-env",
@@ -972,4 +940,3 @@ def test_execute_test_rollback(
            **DEFAULT_RUN_KWARGS,
        ),
    ]
    )
+6 −4
Original line number Diff line number Diff line
import platform
import subprocess
from pathlib import Path
from typing import Any
from unittest.mock import patch
from unittest.mock import Mock, patch

from pytest import MonkeyPatch

@@ -79,7 +78,9 @@ def test_flake_to_attr() -> None:


@patch(get_qualified_name(platform.node), autospec=True)
def test_flake_from_arg(mock_node: Any, monkeypatch: MonkeyPatch, tmpdir: Path) -> None:
def test_flake_from_arg(
    mock_node: Mock, monkeypatch: MonkeyPatch, tmpdir: Path
) -> None:
    mock_node.return_value = "hostname"

    # Flake string
@@ -161,11 +162,12 @@ def test_flake_from_arg(mock_node: Any, monkeypatch: MonkeyPatch, tmpdir: Path)


@patch(get_qualified_name(m.Path.mkdir, m), autospec=True)
def test_profile_from_arg(mock_mkdir: Any) -> None:
def test_profile_from_arg(mock_mkdir: Mock) -> None:
    assert m.Profile.from_arg("system") == m.Profile(
        "system",
        Path("/nix/var/nix/profiles/system"),
    )
    mock_mkdir.assert_not_called()

    assert m.Profile.from_arg("something") == m.Profile(
        "something",
+166 −161
Original line number Diff line number Diff line
@@ -3,7 +3,7 @@ import uuid
from pathlib import Path
from subprocess import PIPE, CompletedProcess
from typing import Any
from unittest.mock import ANY, call, patch
from unittest.mock import ANY, Mock, call, patch

import pytest
from pytest import MonkeyPatch
@@ -20,13 +20,13 @@ from .helpers import get_qualified_name
    autospec=True,
    return_value=CompletedProcess([], 0, stdout=" \n/path/to/file\n "),
)
def test_build(mock_run: Any) -> None:
def test_build(mock_run: Mock) -> None:
    assert n.build(
        "config.system.build.attr",
        m.BuildAttr("<nixpkgs/nixos>", None),
        {"nix_flag": "foo"},
    ) == Path("/path/to/file")
    mock_run.assert_called_with(
    assert mock_run.call_args == call(
        [
            "nix-build",
            "<nixpkgs/nixos>",
@@ -38,13 +38,17 @@ def test_build(mock_run: Any) -> None:
        stdout=PIPE,
    )

    mock_run.reset_mock()

    assert n.build(
        "config.system.build.attr", m.BuildAttr(Path("file"), "preAttr")
    ) == Path("/path/to/file")
    mock_run.assert_called_with(
    assert mock_run.call_args_list == [
        call(
            ["nix-build", Path("file"), "--attr", "preAttr.config.system.build.attr"],
            stdout=PIPE,
        )
    ]


@patch(
@@ -52,7 +56,7 @@ def test_build(mock_run: Any) -> None:
    autospec=True,
    return_value=CompletedProcess([], 0, stdout=" \n/path/to/file\n "),
)
def test_build_flake(mock_run: Any, monkeypatch: MonkeyPatch, tmpdir: Path) -> None:
def test_build_flake(mock_run: Mock, monkeypatch: MonkeyPatch, tmpdir: Path) -> None:
    monkeypatch.chdir(tmpdir)
    flake = m.Flake.parse(".#hostname")

@@ -61,7 +65,7 @@ def test_build_flake(mock_run: Any, monkeypatch: MonkeyPatch, tmpdir: Path) -> N
        flake,
        {"no_link": True, "nix_flag": "foo"},
    ) == Path("/path/to/file")
    mock_run.assert_called_with(
    assert mock_run.call_args == call(
        [
            "nix",
            "--extra-experimental-features",
@@ -79,7 +83,9 @@ def test_build_flake(mock_run: Any, monkeypatch: MonkeyPatch, tmpdir: Path) -> N

@patch(get_qualified_name(n.run_wrapper, n), autospec=True)
@patch(get_qualified_name(n.uuid4, n), autospec=True)
def test_build_remote(mock_uuid4: Any, mock_run: Any, monkeypatch: MonkeyPatch) -> None:
def test_build_remote(
    mock_uuid4: Mock, mock_run: Mock, monkeypatch: MonkeyPatch
) -> None:
    build_host = m.Remote("user@host", [], None)
    monkeypatch.setenv("NIX_SSHOPTS", "--ssh opts")

@@ -108,9 +114,7 @@ def test_build_remote(mock_uuid4: Any, mock_run: Any, monkeypatch: MonkeyPatch)
        instantiate_flags={"inst": True},
        copy_flags={"copy": True},
    ) == Path("/path/to/config")

    mock_run.assert_has_calls(
        [
    assert mock_run.call_args_list == [
        call(
            [
                "nix-instantiate",
@@ -131,9 +135,7 @@ def test_build_remote(mock_uuid4: Any, mock_run: Any, monkeypatch: MonkeyPatch)
                "user@host",
                Path("/path/to/file"),
            ],
                extra_env={
                    "NIX_SSHOPTS": " ".join([*p.SSH_DEFAULT_OPTS, "--ssh opts"])
                },
            extra_env={"NIX_SSHOPTS": " ".join([*p.SSH_DEFAULT_OPTS, "--ssh opts"])},
        ),
        call(
            ["mktemp", "-d", "-t", "nixos-rebuild.XXXXX"],
@@ -159,7 +161,6 @@ def test_build_remote(mock_uuid4: Any, mock_run: Any, monkeypatch: MonkeyPatch)
        ),
        call(["rm", "-rf", Path("/tmp/tmpdir")], remote=build_host, check=False),
    ]
    )


@patch(
@@ -168,7 +169,7 @@ def test_build_remote(mock_uuid4: Any, mock_run: Any, monkeypatch: MonkeyPatch)
    return_value=CompletedProcess([], 0, stdout=" \n/path/to/file\n "),
)
def test_build_remote_flake(
    mock_run: Any, monkeypatch: MonkeyPatch, tmpdir: Path
    mock_run: Mock, monkeypatch: MonkeyPatch, tmpdir: Path
) -> None:
    monkeypatch.chdir(tmpdir)
    flake = m.Flake.parse(".#hostname")
@@ -183,8 +184,7 @@ def test_build_remote_flake(
        copy_flags={"copy": True},
        flake_build_flags={"build": True},
    ) == Path("/path/to/file")
    mock_run.assert_has_calls(
        [
    assert mock_run.call_args_list == [
        call(
            [
                "nix",
@@ -205,9 +205,7 @@ def test_build_remote_flake(
                "user@host",
                Path("/path/to/file"),
            ],
                extra_env={
                    "NIX_SSHOPTS": " ".join([*p.SSH_DEFAULT_OPTS, "--ssh opts"])
                },
            extra_env={"NIX_SSHOPTS": " ".join([*p.SSH_DEFAULT_OPTS, "--ssh opts"])},
        ),
        call(
            [
@@ -223,7 +221,6 @@ def test_build_remote_flake(
            stdout=PIPE,
        ),
    ]
    )


def test_copy_closure(monkeypatch: MonkeyPatch) -> None:
@@ -236,7 +233,7 @@ def test_copy_closure(monkeypatch: MonkeyPatch) -> None:
    build_host = m.Remote("user@build.host", [], None)
    with patch(get_qualified_name(n.run_wrapper, n), autospec=True) as mock_run:
        n.copy_closure(closure, target_host)
        mock_run.assert_called_with(
        assert mock_run.call_args == call(
            ["nix-copy-closure", "--to", "user@target.host", closure],
            extra_env={"NIX_SSHOPTS": " ".join(p.SSH_DEFAULT_OPTS)},
        )
@@ -244,7 +241,7 @@ def test_copy_closure(monkeypatch: MonkeyPatch) -> None:
    monkeypatch.setenv("NIX_SSHOPTS", "--ssh build-opt")
    with patch(get_qualified_name(n.run_wrapper, n), autospec=True) as mock_run:
        n.copy_closure(closure, None, build_host, {"copy_flag": True})
        mock_run.assert_called_with(
        assert mock_run.call_args == call(
            ["nix-copy-closure", "--copy-flag", "--from", "user@build.host", closure],
            extra_env={
                "NIX_SSHOPTS": " ".join([*p.SSH_DEFAULT_OPTS, "--ssh build-opt"])
@@ -258,7 +255,7 @@ def test_copy_closure(monkeypatch: MonkeyPatch) -> None:
    }
    with patch(get_qualified_name(n.run_wrapper, n), autospec=True) as mock_run:
        n.copy_closure(closure, target_host, build_host, {"copy_flag": True})
        mock_run.assert_called_with(
        assert mock_run.call_args == call(
            [
                "nix",
                "copy",
@@ -275,8 +272,7 @@ def test_copy_closure(monkeypatch: MonkeyPatch) -> None:
    monkeypatch.setattr(n, "WITH_NIX_2_18", False)
    with patch(get_qualified_name(n.run_wrapper, n), autospec=True) as mock_run:
        n.copy_closure(closure, target_host, build_host)
        mock_run.assert_has_calls(
            [
        assert mock_run.call_args_list == [
            call(
                ["nix-copy-closure", "--from", "user@build.host", closure],
                extra_env=extra_env,
@@ -286,15 +282,14 @@ def test_copy_closure(monkeypatch: MonkeyPatch) -> None:
                extra_env=extra_env,
            ),
        ]
        )


@patch(get_qualified_name(n.run_wrapper, n), autospec=True)
def test_edit(mock_run: Any, monkeypatch: MonkeyPatch, tmpdir: Path) -> None:
def test_edit(mock_run: Mock, monkeypatch: MonkeyPatch, tmpdir: Path) -> None:
    # Flake
    flake = m.Flake.parse(f"{tmpdir}#attr")
    n.edit(flake, {"commit_lock_file": True})
    mock_run.assert_called_with(
    assert mock_run.call_args == call(
        [
            "nix",
            "--extra-experimental-features",
@@ -316,7 +311,7 @@ def test_edit(mock_run: Any, monkeypatch: MonkeyPatch, tmpdir: Path) -> None:
        mp.setenv("EDITOR", "editor")

        n.edit(None)
        mock_run.assert_called_with(["editor", default_nix], check=False)
        assert mock_run.call_args == call(["editor", default_nix], check=False)


@patch(
@@ -333,13 +328,13 @@ def test_edit(mock_run: Any, monkeypatch: MonkeyPatch, tmpdir: Path) -> None:
        """,
    ),
)
def test_get_build_image_variants(mock_run: Any, tmp_path: Path) -> None:
def test_get_build_image_variants(mock_run: Mock, tmp_path: Path) -> None:
    build_attr = m.BuildAttr("<nixpkgs/nixos>", None)
    assert n.get_build_image_variants(build_attr) == {
        "azure": "nixos-image-azure-25.05.20250102.6df2492-x86_64-linux.vhd",
        "vmware": "nixos-image-vmware-25.05.20250102.6df2492-x86_64-linux.vmdk",
    }
    mock_run.assert_called_with(
    assert mock_run.call_args == call(
        [
            "nix-instantiate",
            "--eval",
@@ -357,12 +352,14 @@ def test_get_build_image_variants(mock_run: Any, tmp_path: Path) -> None:
        stdout=PIPE,
    )

    mock_run.reset_mock()

    build_attr = m.BuildAttr(Path(tmp_path), "preAttr")
    assert n.get_build_image_variants(build_attr, {"inst_flag": True}) == {
        "azure": "nixos-image-azure-25.05.20250102.6df2492-x86_64-linux.vhd",
        "vmware": "nixos-image-vmware-25.05.20250102.6df2492-x86_64-linux.vmdk",
    }
    mock_run.assert_called_with(
    assert mock_run.call_args == call(
        [
            "nix-instantiate",
            "--eval",
@@ -396,13 +393,13 @@ def test_get_build_image_variants(mock_run: Any, tmp_path: Path) -> None:
        """,
    ),
)
def test_get_build_image_variants_flake(mock_run: Any) -> None:
def test_get_build_image_variants_flake(mock_run: Mock) -> None:
    flake = m.Flake(Path("flake.nix"), "myAttr")
    assert n.get_build_image_variants_flake(flake, {"eval_flag": True}) == {
        "azure": "nixos-image-azure-25.05.20250102.6df2492-x86_64-linux.vhd",
        "vmware": "nixos-image-vmware-25.05.20250102.6df2492-x86_64-linux.vmdk",
    }
    mock_run.assert_called_with(
    assert mock_run.call_args == call(
        [
            "nix",
            "eval",
@@ -427,7 +424,7 @@ def test_get_nixpkgs_rev() -> None:
        side_effect=[CompletedProcess([], 0, "")],
    ) as mock_run:
        assert n.get_nixpkgs_rev(path) is None
        mock_run.assert_called_with(
        assert mock_run.call_args == call(
            ["git", "-C", path, "rev-parse", "--short", "HEAD"],
            check=False,
            capture_output=True,
@@ -454,7 +451,7 @@ def test_get_nixpkgs_rev() -> None:
        ],
    ) as mock_run:
        assert n.get_nixpkgs_rev(path) == ".git.0f7c82403fd6"
        mock_run.assert_has_calls(expected_calls)
        assert mock_run.call_args_list == expected_calls

    with patch(
        get_qualified_name(n.run_wrapper, n),
@@ -465,7 +462,7 @@ def test_get_nixpkgs_rev() -> None:
        ],
    ) as mock_run:
        assert n.get_nixpkgs_rev(path) == ".git.0f7c82403fd6M"
        mock_run.assert_has_calls(expected_calls)
        assert mock_run.call_args_list == expected_calls


def test_get_generations(tmp_path: Path) -> None:
@@ -506,7 +503,7 @@ def test_get_generations_from_nix_env(tmp_path: Path) -> None:
            m.Generation(id=2083, current=False, timestamp="2024-11-07 22:59:41"),
            m.Generation(id=2084, current=True, timestamp="2024-11-07 23:54:17"),
        ]
        mock_run.assert_called_with(
        assert mock_run.call_args == call(
            ["nix-env", "-p", path, "--list-generations"],
            stdout=PIPE,
            remote=None,
@@ -524,7 +521,7 @@ def test_get_generations_from_nix_env(tmp_path: Path) -> None:
            m.Generation(id=2083, current=False, timestamp="2024-11-07 22:59:41"),
            m.Generation(id=2084, current=True, timestamp="2024-11-07 23:54:17"),
        ]
        mock_run.assert_called_with(
        assert mock_run.call_args == call(
            ["nix-env", "-p", path, "--list-generations"],
            stdout=PIPE,
            remote=remote,
@@ -548,7 +545,7 @@ def test_get_generations_from_nix_env(tmp_path: Path) -> None:
        ),
    ],
)
def test_list_generations(mock_get_generations: Any, tmp_path: Path) -> None:
def test_list_generations(mock_get_generations: Mock, tmp_path: Path) -> None:
    # Probably better to test this function in a real system, this test is
    # mostly to make sure it doesn't break horribly
    assert n.list_generations(m.Profile("system", tmp_path)) == [
@@ -574,18 +571,20 @@ def test_list_generations(mock_get_generations: Any, tmp_path: Path) -> None:


@patch(get_qualified_name(n.run_wrapper, n), autospec=True)
def test_repl(mock_run: Any) -> None:
def test_repl(mock_run: Mock) -> None:
    n.repl("attr", m.BuildAttr("<nixpkgs/nixos>", None), {"nix_flag": True})
    mock_run.assert_called_with(
    assert mock_run.call_args == call(
        ["nix", "repl", "--file", "<nixpkgs/nixos>", "--nix-flag"]
    )

    n.repl("attr", m.BuildAttr(Path("file.nix"), "myAttr"))
    mock_run.assert_called_with(["nix", "repl", "--file", Path("file.nix"), "myAttr"])
    assert mock_run.call_args == call(
        ["nix", "repl", "--file", Path("file.nix"), "myAttr"]
    )


@patch(get_qualified_name(n.run_wrapper, n), autospec=True)
def test_repl_flake(mock_run: Any) -> None:
def test_repl_flake(mock_run: Mock) -> None:
    n.repl_flake("attr", m.Flake(Path("flake.nix"), "myAttr"), {"nix_flag": True})
    # See nixos-rebuild-ng.tests.repl for a better test,
    # this is mostly for sanity check
@@ -593,14 +592,14 @@ def test_repl_flake(mock_run: Any) -> None:


@patch(get_qualified_name(n.run_wrapper, n), autospec=True)
def test_rollback(mock_run: Any, tmp_path: Path) -> None:
def test_rollback(mock_run: Mock, tmp_path: Path) -> None:
    path = tmp_path / "test"
    path.touch()

    profile = m.Profile("system", path)

    assert n.rollback(profile, None, False) == profile.path
    mock_run.assert_called_with(
    assert mock_run.call_args == call(
        ["nix-env", "--rollback", "-p", path],
        remote=None,
        sudo=False,
@@ -608,7 +607,7 @@ def test_rollback(mock_run: Any, tmp_path: Path) -> None:

    target_host = m.Remote("user@localhost", [], None)
    assert n.rollback(profile, target_host, True) == profile.path
    mock_run.assert_called_with(
    assert mock_run.call_args == call(
        ["nix-env", "--rollback", "-p", path],
        remote=target_host,
        sudo=True,
@@ -620,8 +619,10 @@ def test_rollback_temporary_profile(tmp_path: Path) -> None:
    path.touch()
    profile = m.Profile("system", path)

    with patch(get_qualified_name(n.run_wrapper, n), autospec=True) as mock_run:
        mock_run.return_value = CompletedProcess(
    with patch(
        get_qualified_name(n.run_wrapper, n),
        autospec=True,
        return_value=CompletedProcess(
            [],
            0,
            stdout=textwrap.dedent("""\
@@ -629,12 +630,13 @@ def test_rollback_temporary_profile(tmp_path: Path) -> None:
                2083   2024-11-07 22:59:41
                2084   2024-11-07 23:54:17   (current)
                """),
        )
        ),
    ) as mock_run:
        assert (
            n.rollback_temporary_profile(m.Profile("system", path), None, False)
            == path.parent / "system-2083-link"
        )
        mock_run.assert_called_with(
        assert mock_run.call_args == call(
            [
                "nix-env",
                "-p",
@@ -651,7 +653,7 @@ def test_rollback_temporary_profile(tmp_path: Path) -> None:
            n.rollback_temporary_profile(m.Profile("foo", path), target_host, True)
            == path.parent / "foo-2083-link"
        )
        mock_run.assert_called_with(
        assert mock_run.call_args == call(
            [
                "nix-env",
                "-p",
@@ -663,13 +665,16 @@ def test_rollback_temporary_profile(tmp_path: Path) -> None:
            sudo=True,
        )

    with patch(get_qualified_name(n.run_wrapper, n), autospec=True) as mock_run:
        mock_run.return_value = CompletedProcess([], 0, stdout="")
    with patch(
        get_qualified_name(n.run_wrapper, n),
        autospec=True,
        return_value=CompletedProcess([], 0, stdout=""),
    ) as mock_run:
        assert n.rollback_temporary_profile(profile, None, False) is None


@patch(get_qualified_name(n.run_wrapper, n), autospec=True)
def test_set_profile(mock_run: Any) -> None:
def test_set_profile(mock_run: Mock) -> None:
    profile_path = Path("/path/to/profile")
    config_path = Path("/path/to/config")
    n.set_profile(
@@ -679,7 +684,7 @@ def test_set_profile(mock_run: Any) -> None:
        sudo=False,
    )

    mock_run.assert_called_with(
    assert mock_run.call_args == call(
        ["nix-env", "-p", profile_path, "--set", config_path],
        remote=None,
        sudo=False,
@@ -687,7 +692,7 @@ def test_set_profile(mock_run: Any) -> None:


@patch(get_qualified_name(n.run_wrapper, n), autospec=True)
def test_switch_to_configuration(mock_run: Any, monkeypatch: MonkeyPatch) -> None:
def test_switch_to_configuration(mock_run: Mock, monkeypatch: MonkeyPatch) -> None:
    profile_path = Path("/path/to/profile")
    config_path = Path("/path/to/config")

@@ -702,7 +707,7 @@ def test_switch_to_configuration(mock_run: Any, monkeypatch: MonkeyPatch) -> Non
            specialisation=None,
            install_bootloader=False,
        )
    mock_run.assert_called_with(
    assert mock_run.call_args == call(
        [profile_path / "bin/switch-to-configuration", "switch"],
        extra_env={"NIXOS_INSTALL_BOOTLOADER": "0"},
        sudo=False,
@@ -736,7 +741,7 @@ def test_switch_to_configuration(mock_run: Any, monkeypatch: MonkeyPatch) -> Non
            install_bootloader=True,
            specialisation="special",
        )
    mock_run.assert_called_with(
    assert mock_run.call_args == call(
        [
            config_path / "specialisation/special/bin/switch-to-configuration",
            "test",
@@ -757,17 +762,17 @@ def test_switch_to_configuration(mock_run: Any, monkeypatch: MonkeyPatch) -> Non
    ],
)
@patch(get_qualified_name(n.Path.is_dir, n), autospec=True, return_value=True)
def test_upgrade_channels(mock_is_dir: Any, mock_glob: Any) -> None:
def test_upgrade_channels(mock_is_dir: Mock, mock_glob: Mock) -> None:
    with patch(get_qualified_name(n.run_wrapper, n), autospec=True) as mock_run:
        n.upgrade_channels(False)
    mock_run.assert_called_with(["nix-channel", "--update", "nixos"], check=False)
    assert mock_run.call_args == call(["nix-channel", "--update", "nixos"], check=False)

    mock_run.reset_mock()

    with patch(get_qualified_name(n.run_wrapper, n), autospec=True) as mock_run:
        n.upgrade_channels(True)
    mock_run.assert_has_calls(
        [
    assert mock_run.call_args_list == [
        call(["nix-channel", "--update", "nixos"], check=False),
        call(["nix-channel", "--update", "nixos-hardware"], check=False),
        call(["nix-channel", "--update", "home-manager"], check=False),
    ]
    )
+6 −7
Original line number Diff line number Diff line
from typing import Any
from unittest.mock import patch
from unittest.mock import Mock, call, patch

from pytest import MonkeyPatch

@@ -10,9 +9,9 @@ from .helpers import get_qualified_name


@patch(get_qualified_name(p.subprocess.run), autospec=True)
def test_run(mock_run: Any) -> None:
def test_run(mock_run: Mock) -> None:
    p.run_wrapper(["test", "--with", "flags"], check=True)
    mock_run.assert_called_with(
    assert mock_run.call_args == call(
        ["test", "--with", "flags"],
        check=True,
        text=True,
@@ -28,7 +27,7 @@ def test_run(mock_run: Any) -> None:
            sudo=True,
            extra_env={"FOO": "bar"},
        )
    mock_run.assert_called_with(
    assert mock_run.call_args == call(
        ["sudo", "test", "--with", "flags"],
        check=False,
        text=True,
@@ -45,7 +44,7 @@ def test_run(mock_run: Any) -> None:
        check=True,
        remote=m.Remote("user@localhost", ["--ssh", "opt"], "password"),
    )
    mock_run.assert_called_with(
    assert mock_run.call_args == call(
        [
            "ssh",
            "--ssh",
@@ -71,7 +70,7 @@ def test_run(mock_run: Any) -> None:
        extra_env={"FOO": "bar"},
        remote=m.Remote("user@localhost", ["--ssh", "opt"], "password"),
    )
    mock_run.assert_called_with(
    assert mock_run.call_args == call(
        [
            "ssh",
            "--ssh",