# Copyright 2022 The Debusine developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.

"""Tests for the debusine Cli class."""

import contextlib
import http
import io
import json
import logging
import math
import os
import signal
import stat
import textwrap
from datetime import datetime, timedelta
from itertools import count
from pathlib import Path
from typing import Any, Callable, Literal, Optional, Union
from unittest import TestCase, mock
from unittest.mock import MagicMock

import yaml

from debusine.artifacts import LocalArtifact
from debusine.client import exceptions
from debusine.client.cli import Cli
from debusine.client.config import ConfigHandler
from debusine.client.debusine import Debusine
from debusine.client.exceptions import DebusineError, NotFoundError
from debusine.client.models import (
    ArtifactResponse,
    RemoteArtifact,
    WorkRequestRequest,
    model_to_json_serializable_dict,
)
from debusine.test import TestHelpersMixin
from debusine.test.utils import (
    create_artifact_response,
    create_work_request_response,
)


class BaseCliTests(TestHelpersMixin, TestCase):
    """Basic functionality to implement tests for the Cli class."""

    def setUp(self):
        """Configure test object."""
        debian_server = {
            'api-url': 'https://debusine.debian.org/api',
            'token': 'token-for-debian',
        }
        kali_server = {
            'api-url': 'https://debusine.kali.org/api',
            'token': 'token-for-kali',
        }

        self.servers = {"debian": debian_server, "kali": kali_server}
        self.default_server = "debian"

        self.default_sigint_handler = signal.getsignal(signal.SIGINT)
        self.default_sigterm_handler = signal.getsignal(signal.SIGTERM)

    def tearDown(self):
        """Cleanup after executing a test."""
        # Restore signal handlers. Cli.execute() changes them
        signal.signal(signal.SIGINT, self.default_sigint_handler)
        signal.signal(signal.SIGTERM, self.default_sigterm_handler)

    def create_cli(self, argv, create_config=True) -> Cli:
        """
        Return a Cli object using argv, self.stdout and self.stderr.

        :param argv: arguments passed to the Cli class.
        :param create_config: True for creating a config file and adding
          --config config_file_path into CLI's argv.
        """
        if create_config:
            if '--config' in argv:  # pragma: no cover
                raise ValueError(
                    'Incompatible options: create_config cannot be True if '
                    '--config is in argv'
                )
            config = self.create_config_file()

            argv = ['--config', config] + argv

        return Cli(argv)

    def create_config_file(self):
        """Write a config file and returns the path."""
        config_directory = self.create_temp_config_directory(
            {
                'General': {'default-server': self.default_server},
                'server:debian': self.servers["debian"],
                'server:kali': self.servers["kali"],
            }
        )

        return os.path.join(config_directory, 'config.ini')

    def capture_output(
        self,
        func: Callable[..., Any],
        args: Optional[list[Any]] = None,
        assert_system_exit_code: Optional[int] = None,
    ) -> tuple[str, str]:
        """
        Execute func() and return stderr and stdout output.

        :param func: functor to be executed
        :param args: list of arguments to be passed to func() (or None if
          no arguments are passed when calling func()
        :param assert_system_exit_code: if not None assert that SystemExit
          is raised
        """
        if args is None:
            args = []

        stderr = io.StringIO()
        stdout = io.StringIO()

        with contextlib.redirect_stderr(stderr), contextlib.redirect_stdout(
            stdout
        ):
            if assert_system_exit_code is not None:
                with self.assertRaisesSystemExit(assert_system_exit_code):
                    func(*args)
            else:
                func(*args)

        return stderr.getvalue(), stdout.getvalue()

    def patch_sys_stdin_read(self) -> MagicMock:
        """Patch sys.stdin.read to return what a user might write / input."""
        patcher_sys_stdin = mock.patch('sys.stdin.read', autospec=True)
        mocked_sys_stdin = patcher_sys_stdin.start()
        self.addCleanup(patcher_sys_stdin.stop)

        return mocked_sys_stdin

    def patch_sys_stderr_write(self) -> MagicMock:
        """Patch sys.stderr.write to check what was written."""
        patcher_sys_stderr = mock.patch("sys.stderr.write")
        mocked_sys_stderr = patcher_sys_stderr.start()
        self.addCleanup(patcher_sys_stderr.stop)

        return mocked_sys_stderr

    def patch_build_debusine_object(self) -> MagicMock:
        """
        Patch _build_debusine_object. Return mock.

        The mocked object return_value is a MagicMock(spec=Debusine).
        """
        patcher = mock.patch.object(
            Cli, "_build_debusine_object", autospec=True
        )
        mocked = patcher.start()
        mocked.return_value = mock.create_autospec(spec=Debusine)
        self.addCleanup(patcher.stop)

        return mocked

    def patch_api_call_or_fail(self, cli: Cli) -> MagicMock:
        """Patch cli._api_call_or_fail. Return its mock."""
        patcher = mock.patch.object(cli, "_api_call_or_fail", autospec=True)
        mocked = patcher.start()
        self.addCleanup(patcher.stop)

        return mocked


class CliTests(BaseCliTests):
    """Tests for the debusine command line interface generic functionality."""

    def test_client_without_parameters(self):
        """
        Executing the client without any parameter returns an error.

        At least one subcommands is required. argparse prints help
        and exit.
        """
        cli = self.create_cli([], create_config=False)
        stderr = io.StringIO()

        with contextlib.redirect_stderr(stderr):
            with self.assertRaisesSystemExit(2):
                # Argparse prints help and exits with exit_code=2
                cli.execute()

        self.assertTrue(len(stderr.getvalue()) > 80)

    def test_client_help_include_default_setting(self):
        """Cli.execute() help include ConfigHandler.DEFAULT_CONFIG_FILE_PATH."""
        stdout = io.StringIO()

        cli = self.create_cli(['--help'], create_config=False)

        with contextlib.redirect_stdout(stdout):
            with self.assertRaisesSystemExit(0):
                # Argparse prints help and exits with exit_code=0
                cli.execute()

        # argparse might add \n and spaces (for indentation) in the
        # output to align the text. In this case
        # ConfigHandler.DEFAULT_CONFIG_FILE_PATH could not be found
        output = stdout.getvalue().replace('\n', '').replace(' ', '')

        self.assertIn(
            str(ConfigHandler.DEFAULT_CONFIG_FILE_PATH).replace(' ', ''), output
        )

    def assert_client_object_use_specific_server(self, args, server_config):
        """Assert that Cli uses Debusine with the correct endpoint."""
        cli = self.create_cli(args)

        cli._parse_args()

        debusine = cli._build_debusine_object()

        self.assertEqual(debusine.base_api_url, server_config['api-url'])
        self.assertEqual(debusine.token, server_config['token'])

    def test_use_default_server(self):
        """Ensure debusine object uses the default server."""
        self.assert_client_object_use_specific_server(
            ['show-work-request', '10'], self.servers[self.default_server]
        )

    def test_use_explicit_server(self):
        """Ensure debusine object uses the Kali server when requested."""
        self.assert_client_object_use_specific_server(
            ['--server', 'kali', 'show-work-request', '10'],
            self.servers["kali"],
        )

    def test_build_debusine_object_logging_warning(self):
        """Cli with --silent create and pass logger level WARNING."""
        cli = self.create_cli(["--silent", "show-work-request", "10"])

        cli._parse_args()

        mocked_sys_stderr = self.patch_sys_stderr_write()

        debusine = cli._build_debusine_object()

        self.assertEqual(debusine._logger.level, logging.WARNING)
        self.assertFalse(debusine._logger.propagate)

        msg = "This is a test"

        # Test the logger
        debusine._logger.warning(msg)
        mocked_sys_stderr.assert_called_with(msg + "\n")

    def test_build_debusine_object_logging_info(self):
        """Cli without --silent create and pass logger level INFO."""
        cli = self.create_cli(["show-work-request", "10"])

        cli._parse_args()

        debusine = cli._build_debusine_object()

        self.assertEqual(debusine._logger.level, logging.INFO)

    def test_debug(self):
        """Cli with --debug."""
        cli = self.create_cli(["--debug", "show-work-request", "10"])

        with mock.patch.object(cli, "_show_work_request", autospec=True):
            cli.execute()
        self.assertEqual(http.client.HTTPConnection.debuglevel, 1)

        # Test the logger
        msg = "This is a test"
        mocked_sys_stderr = self.patch_sys_stderr_write()
        http.client.print(msg)
        mocked_sys_stderr.assert_called_with("DEBUG:requests:" + msg + "\n")

    def test_api_call_or_fail_not_found(self):
        """_api_call_or_fail print error message for not found and exit."""
        cli = self.create_cli([], create_config=False)

        def raiseNotFound():
            raise NotFoundError('Not found')

        stderr, stdout = self.capture_output(
            cli._api_call_or_fail,
            args=[raiseNotFound],
            assert_system_exit_code=3,
        )

        self.assertEqual(stderr, "Not found\n")

    def test_api_call_or_fail_unexpected_error(self):
        """_api_call_or_fail print error message for not found and exit."""
        cli = self.create_cli([], create_config=False)

        def raiseUnexpectedResponseError():
            raise exceptions.UnexpectedResponseError('Not available')

        stderr, stdout = self.capture_output(
            cli._api_call_or_fail,
            [raiseUnexpectedResponseError],
            assert_system_exit_code=3,
        )

        self.assertEqual(stderr, "Not available\n")

    def test_api_call_or_fail_client_forbidden_error(self):
        """
        _api_call_or_fail print error message and exit.

        ClientForbiddenError was raised.
        """
        cli = self.create_cli([], create_config=False)

        def raiseClientForbiddenError():
            raise exceptions.ClientForbiddenError('Invalid token')

        stderr, stdout = self.capture_output(
            cli._api_call_or_fail,
            args=[raiseClientForbiddenError],
            assert_system_exit_code=3,
        )

        self.assertEqual(stderr, "Server rejected connection: Invalid token\n")

    def test_api_call_or_fail_client_connection_error(self):
        """
        _api_call_or_fail print error message and exit.

        ClientConnectionError was raised.
        """
        cli = self.create_cli([], create_config=False)

        def raiseClientConnectionError():
            raise exceptions.ClientConnectionError('Connection refused')

        stderr, stdout = self.capture_output(
            cli._api_call_or_fail,
            args=[raiseClientConnectionError],
            assert_system_exit_code=3,
        )

        self.assertEqual(
            stderr,
            'Error connecting to debusine: Connection refused\n',
        )

    def test_api_call_or_fail_success(self):
        """
        _api_call_or_fail print error message.

        ClientConnectionError was raised.
        """
        cli = self.create_cli([], create_config=False)

        data = cli._api_call_or_fail(lambda: 'some data from the server')

        self.assertEqual(data, 'some data from the server')

    def test_signal_handlers_set_on_exec(self):
        """Test that the signal handlers are set on exec()."""
        cli = self.create_cli(["show-work-request", "1"])

        # Cli.__init__() is not changing the signal handlers for SIG{INT,TERM}
        self.assertEqual(
            signal.getsignal(signal.SIGINT), self.default_sigint_handler
        )
        self.assertEqual(
            signal.getsignal(signal.SIGTERM), self.default_sigterm_handler
        )

        patcher = mock.patch.object(cli, "_show_work_request", autospec=True)
        patcher.start()
        self.addCleanup(patcher.stop)

        cli.execute()

        # cli.execute() changed the signal handlers for SIG{INT,TERM}
        self.assertEqual(signal.getsignal(signal.SIGINT), cli._exit)
        self.assertEqual(signal.getsignal(signal.SIGTERM), cli._exit)

    def test_exit_raise_system_exit_0(self):
        """Cli._exit raise SystemExit(0)."""
        with self.assertRaisesSystemExit(0):
            Cli._exit(None, None)

    def test_print_yaml(self):
        """Cli._print_yaml prints yaml to stdout."""
        cli = self.create_cli([])
        data = {"message": "x" * 100}

        stderr, stdout = self.capture_output(cli._print_yaml, args=[data])

        self.assertEqual(stdout.count("\n"), 1)


class CliCreateArtifactTests(BaseCliTests):
    """Tests for the Cli functionality related to create artifacts."""

    def create_files_to_upload(self):
        """Create three files to upload in the temp directory."""
        return [
            self.create_temporary_file(prefix="pkg_1.0.dsc", contents=b"test"),
            self.create_temporary_file(
                prefix="pkg_1.0.tar.gz", contents=b"test2"
            ),
            self.create_temporary_file(prefix="empty.txt", contents=b""),
        ]

    def patch_create_artifact(self) -> MagicMock:
        """Patch Debusine.create_artifact."""
        patcher_create_artifact = mock.patch.object(
            Debusine, "artifact_create", autospec=True
        )
        mocked_create_artifact = patcher_create_artifact.start()

        self.addCleanup(patcher_create_artifact.stop)
        return mocked_create_artifact

    def assert_artifact_is_created(
        self,
        mocked_create_artifact,
        expected_workspace: str,
        expected_artifact_id: int,
        expected_files_to_upload_count: int,
        stdout: str,
        stderr: str,
        expected_expire_at: Optional[datetime] = None,
    ) -> LocalArtifact[Any]:
        """
        Assert that mocked_create_artifact was called only once and stdout.

        In stdout expects that CLI printed into stdout the information
        about the recently created artifact.

        Return LocalArtifact that would be sent to the server.

        :param mocked_create_artifact: mock to assert that was called only once.
        :param expected_workspace: expected created workspace.
        :param expected_artifact_id: expected created artifact id.
        :param expected_files_to_upload_count: expected files to upload.
        :param stdout: contains Cli.execute() output to verify expected output.
        :param stderr: contains Cli.execute() output to verify expected output.
        """
        mocked_create_artifact.assert_called_once()

        server_url = self.servers[self.default_server]["api-url"]

        expected = yaml.safe_dump(
            {
                "result": "success",
                "message": f"New artifact created in {server_url} "
                f"in workspace {expected_workspace} "
                f"with id {expected_artifact_id}.",
                "artifact_id": expected_artifact_id,
                "files_to_upload": expected_files_to_upload_count,
                "expire_at": expected_expire_at,
            },
            sort_keys=False,
            width=math.inf,
        )

        self.assertEqual(stdout, expected)
        self.assertEqual(stderr, "")

        local_artifact = mocked_create_artifact.call_args[0][1]
        self.assertIsInstance(local_artifact, LocalArtifact)

        return local_artifact

    def create_artifact_via_cli(
        self,
        category: str,
        *,
        workspace: Optional[str] = None,
        files_to_upload: Optional[list[str]] = None,
        upload_base_directory: Optional[Path] = None,
        expire_at: Optional[datetime] = None,
        data: Optional[bytes] = None,
        data_file: Optional[Union[Path, Literal["-"]]] = None,
        stdin: Optional[dict[str, Any]] = None,
        create_artifact_return_value=None,
        create_artifact_side_effect=None,
        assert_system_exit_code: Optional[int] = None,
    ) -> tuple[str, str, MagicMock]:
        """
        Call CLI create-artifact with the correct parameters.

        Patch Debusine.create_artifact before executing the command.

        :param category: category of the artifact.
        :param workspace: add ["--workspace", workspace] options.
        :param files_to_upload: list of file paths to upload.
        :param expire_at: datetime (for --expire-at option).
        :param data: data passed to the artifact (creates a temporary file
          and passes the temporary file path via --data).
        :param data_file: data file (for --data options).
        :param stdin: dump stdin into YAML and writes it into stdin.
        :param create_artifact_return_value: return value for the
          Debusine.create_artifact mock.
        :param create_artifact_side_effect: side effect for the
          Debusine.create_artifact mock.
        :param assert_system_exit_code: assert that the create-artifact
          command raises SystemExit(X).

        Return tuple with stderr, stdout and the patched
        Debusine.create_artifact
        """
        mocked_create_artifact = self.patch_create_artifact()

        if create_artifact_return_value is not None:
            mocked_create_artifact.return_value = create_artifact_return_value

        if create_artifact_side_effect is not None:
            mocked_create_artifact.side_effect = create_artifact_side_effect

        create_cli_options = [category]

        if workspace is not None:
            create_cli_options.extend(["--workspace", workspace])

        if expire_at is not None:
            create_cli_options.extend([f"--expire-at={expire_at}"])

        if data is not None:
            data_file_temp = self.create_temporary_file(
                prefix="create-artifact", contents=data
            )
            create_cli_options.extend(["--data", str(data_file_temp)])

        if data_file is not None:
            if data is not None:
                raise ValueError(
                    "'data_file' parameter cannot be used with 'data'"
                )  # pragma: no cover
            create_cli_options.extend(["--data", str(data_file)])

        if files_to_upload is not None:
            create_cli_options.extend(["--upload", *files_to_upload])

        if upload_base_directory is not None:
            create_cli_options.extend(
                ["--upload-base-directory", upload_base_directory.as_posix()]
            )

        if stdin is not None:
            mocked_sys_stdin_read = self.patch_sys_stdin_read()
            mocked_sys_stdin_read.return_value = yaml.safe_dump(stdin)

        cli = self.create_cli(["create-artifact", *create_cli_options])

        if assert_system_exit_code is None:
            stderr, stdout = self.capture_output(cli.execute)
        else:
            stderr, stdout = self.capture_output(
                cli.execute, assert_system_exit_code=assert_system_exit_code
            )

        return stderr, stdout, mocked_create_artifact

    def assert_create_artifact_success(
        self,
        files_to_upload: list[Path],
        upload_base_directory: Optional[Path] = None,
        expire_at: Optional[datetime] = None,
    ):
        """
        Cli parse the command line and calls Debusine.create_artifact.

        Verify that the correct files_to_upload has been used.
        """
        artifact_category = "debusine:work-request-debug-logs"
        artifact_id = 2
        workspace = "test"

        # Mock Debusine.upload_files: will be used to verify the arguments
        # that debusine client used to try to upload the files
        upload_files_patcher = mock.patch.object(
            Debusine, "upload_files", autospec=True
        )
        upload_files_patcher.start()
        self.addCleanup(upload_files_patcher.stop)

        # Prepare dictionary with the paths in the artifact and the
        # FileModelRequest objects
        paths_in_artifact_to_file_models = {}
        for file_to_upload in files_to_upload:
            if file_to_upload.is_absolute():
                local_file_path = file_to_upload
                artifact_path = file_to_upload.name
            else:
                local_file_path = Path(os.getcwd()).joinpath(file_to_upload)
                artifact_path = str(file_to_upload.name)

            paths_in_artifact_to_file_models[artifact_path] = local_file_path

        create_artifact_return_value = create_artifact_response(
            id=artifact_id,
            workspace=workspace,
            files_to_upload=list(paths_in_artifact_to_file_models.keys()),
        )

        (
            stderr_actual,
            stdout_actual,
            mocked_create_artifact,
        ) = self.create_artifact_via_cli(
            artifact_category,
            workspace=workspace,
            create_artifact_return_value=create_artifact_return_value,
            files_to_upload=list(map(str, files_to_upload)),
            upload_base_directory=upload_base_directory,
            expire_at=expire_at,
        )

        # Assert the call happened as expected
        artifact_request = self.assert_artifact_is_created(
            mocked_create_artifact,
            workspace,
            artifact_id,
            len(paths_in_artifact_to_file_models),
            stdout_actual,
            stderr_actual,
            expire_at,
        )
        self.assertEqual(artifact_request.category, artifact_category)
        self.assertEqual(
            artifact_request.files, paths_in_artifact_to_file_models
        )

    def test_create_artifact_absolute_file_paths(self):
        """Test create an artifact uploading files by absolute path."""
        self.assert_create_artifact_success(self.create_files_to_upload())

    def test_create_artifact_relative_file_path(self):
        """Test create an artifact uploading a file by relative to cwd."""
        file_path = self.create_temporary_file(directory=os.getcwd())

        file_name = file_path.name

        self.assert_create_artifact_success([Path(file_name)])

    def test_create_artifact_relative_file_path_in_subdirectory(self):
        """Test create an artifact uploading a file from a subdir of cwd."""
        temp_directory = self.create_temporary_directory(directory=os.getcwd())
        file_path = temp_directory / "file1.data"
        file_path.write_bytes(b"test")

        self.assert_create_artifact_success(
            [file_path.relative_to(os.getcwd())]
        )

    def test_create_artifact_upload_base_directory(self):
        """Create artifact with an abs file path in a abs path directory."""
        temp_directory = self.create_temporary_directory()

        (file := temp_directory / "file1.data").write_bytes(b"")

        self.assert_create_artifact_success([file], temp_directory)

    def test_create_artifact_expire_at(self):
        """Test create an artifact uploading files by absolute path."""
        expire_at = datetime.now() + timedelta(days=1)
        self.assert_create_artifact_success(
            self.create_files_to_upload(), expire_at=expire_at
        )

    def test_create_artifact_debusine_upload_files_fail(self):
        """Debusine.create_artifact fails: cannot connect to the server."""
        files_to_upload = self.create_files_to_upload()

        upload_files_patcher = mock.patch.object(
            Debusine, "upload_files", autospec=True
        )
        mocked_upload_files = upload_files_patcher.start()

        # Debusine.upload_files cannot connect to the server
        mocked_upload_files.side_effect = exceptions.ClientConnectionError
        self.addCleanup(upload_files_patcher.stop)

        workspace = "workspace"
        create_artifact_return_value = create_artifact_response(
            id=2,
            workspace=workspace,
            files_to_upload=list(map(lambda p: p.name, files_to_upload)),
        )

        stderr, stdout, _ = self.create_artifact_via_cli(
            "debusine:work-request-debug-logs",
            workspace=workspace,
            create_artifact_return_value=create_artifact_return_value,
            files_to_upload=list(map(str, files_to_upload)),
            assert_system_exit_code=3,
        )
        self.assertTrue(stderr.startswith("Error connecting to debusine:"))

    def test_create_artifact_read_stdin(self):
        """Cli create an artifact reading the data from stdin."""
        artifact_id = 2
        artifact_category = "debusine:work-request-debug-logs"
        workspace = "default"
        data = {}

        create_artifact_return_value = create_artifact_response(
            id=artifact_id,
            workspace=workspace,
        )

        stderr, stdout, mocked_create_artifact = self.create_artifact_via_cli(
            artifact_category,
            workspace=workspace,
            create_artifact_return_value=create_artifact_return_value,
            stdin=data,
            data_file="-",
        )

        artifact_request = self.assert_artifact_is_created(
            mocked_create_artifact, workspace, artifact_id, 0, stdout, stderr
        )
        self.assertEqual(artifact_request.data, data)

    def test_create_artifact_invalid_data_file_type(self):
        """Cli try to create an artifact, data file does not contain a dict."""
        stderr, stdout, mocked_create_artifact = self.create_artifact_via_cli(
            "debian:source-package",
            data=b"some-text",
            assert_system_exit_code=3,
        )

        self.assertEqual(
            stderr, "Error: data must be a dictionary. It is: str\n"
        )

    def test_create_artifact_invalid_yaml_in_data_file(self):
        """Cli try to create an artifact, data file contains invalid YAML."""
        stderr, stdout, mocked_create_artifact = self.create_artifact_via_cli(
            "debian:source-package", data=b'"', assert_system_exit_code=3
        )

        self.assertRegex(stderr, "^Error parsing YAML:")
        self.assertRegex(stderr, r"Fix the YAML data\n$")

    def test_create_artifact_cannot_read_data(self):
        """Cli try to create an artifact with a data file cannot be read."""
        data_file = "/tmp/debusine-test-file-does-not-exist"
        stderr, stdout, mocked_create_artifact = self.create_artifact_via_cli(
            "debian:source-package",
            data_file=Path(data_file),
            assert_system_exit_code=2,
        )

        # argparse will show an error message containing the file path
        # (the rest of the message is up to argparse)
        self.assertRegex(stderr, data_file)

    def test_create_artifact_without_workspace_success(self):
        """Cli try to create an artifact with workspace=None."""
        artifact_id = 2
        expected_workspace = "default"
        data = {
            "name": "name",
            "version": "1.0",
            "type": "dpkg",
            "dsc_fields": {},
        }
        files_to_upload = []

        create_artifact_return_value = create_artifact_response(
            id=artifact_id,
            workspace=expected_workspace,
            files_to_upload=files_to_upload,
        )
        artifact_category = "debian:source-package"
        (
            stderr_actual,
            stdout_actual,
            mocked_create_artifact,
        ) = self.create_artifact_via_cli(
            artifact_category,
            data=yaml.safe_dump(data).encode("utf-8"),
            create_artifact_return_value=create_artifact_return_value,
        )

        self.assert_artifact_is_created(
            mocked_create_artifact,
            expected_workspace,
            artifact_id,
            len(files_to_upload),
            stdout_actual,
            stderr_actual,
        )

    def test_create_artifact_workspace_not_found(self):
        """Cli try to create an artifact for a non-existing workspace."""
        workspace_name = "does-not-exist"
        title_error = f'Workspace "{workspace_name}" cannot be found'

        create_artifact_side_effect = DebusineError({"title": title_error})

        (
            stderr_actual,
            stdout_actual,
            mocked_create_artifact,
        ) = self.create_artifact_via_cli(
            "debusine:work-request-debug-logs",
            workspace=workspace_name,
            create_artifact_side_effect=create_artifact_side_effect,
        )

        stdout_expected = yaml.safe_dump(
            {"result": "failure", "error": {"title": title_error}},
            sort_keys=False,
        )

        self.assertEqual(stderr_actual, "")
        self.assertEqual(stdout_actual, stdout_expected)

    def test_create_artifact_with_two_files_of_same_name(self):
        """Cannot create an artifact with two files having the same path."""
        file_name = "file1"
        # Create a file to be uploaded in a directory
        directory_to_upload1 = self.create_temporary_directory()
        file_in_dir1 = Path(directory_to_upload1) / Path(file_name)
        file_in_dir1.write_bytes(b"test")

        # And create another file, same name, in another directory
        directory_to_upload2 = self.create_temporary_directory()
        file_in_dir2 = Path(directory_to_upload2) / Path(file_name)
        file_in_dir2.write_bytes(b"test")

        paths_to_upload = [str(file_in_dir1), str(file_in_dir2)]

        stderr, stdout, _ = self.create_artifact_via_cli(
            "debusine:work-request-debug-logs",
            workspace="some-workspace",
            files_to_upload=paths_to_upload,
            assert_system_exit_code=3,
        )

        self.assertEqual(
            stderr,
            f"Cannot create artifact: File with the same path ({file_name}) "
            f"is already in the artifact "
            f'("{file_in_dir1}" and "{file_in_dir2}")\n',
        )

    def test_create_artifact_invalid_category(self):
        """Cli try to create an artifact, data file does not contain a dict."""
        stderr, stdout, mocked_create_artifact = self.create_artifact_via_cli(
            "missing:does-not-exist",
            assert_system_exit_code=3,
        )

        self.assertEqual(
            stderr, "Error: invalid artifact category: missing:does-not-exist\n"
        )


class CliImportDebianArtifactTests(BaseCliTests):
    """
    Tests for the debian artifact import CLI.

    Mocking at the upload_artifact level.

    Remote sources are tested through the DGet test suite, so not repeated here.
    """

    def create_dsc(self, directory: Optional[Path] = None) -> list[Path]:
        """
        Create a simple Debian source package in a temporary directory.

        Return a list of the created Paths. The first item is the dsc.
        """
        if not directory:
            directory = self.create_temporary_directory()
        orig = directory / "pkg_1.0.orig.tar.gz"
        orig.write_bytes(b"I'm a tarball")
        dsc = directory / "pkg_1.0.dsc"
        self.write_dsc_file(dsc, [orig], version="1.0")
        return [dsc, orig]

    def create_upload(
        self,
        source: bool,
        binary: bool,
        extra_dsc: bool = False,
        binnmu: bool = False,
    ) -> list[Path]:
        """
        Create a simple Debian upload in a temporary directory.

        Return a list of the created Paths. The first item is the changes.
        """
        directory = self.create_temporary_directory()
        files = []
        if source:
            files += self.create_dsc(directory)
        if extra_dsc:
            extra = directory / "foo_1.0.dsc"
            self.write_dsc_file(extra, [], version="1.0")
            files.append(extra)
        if binary:
            deb_version = "1.0"
            if binnmu:
                deb_version += "+b1"
            deb = directory / f"pkg_{deb_version}_all.deb"
            self.write_deb_file(deb, source_version="1.0")
            files.append(deb)
        changes = directory / "pkg.changes"
        self.write_changes_file(changes, files, version="1.0", binnmu=binnmu)
        return [changes] + files

    def patch_upload_artifact(self) -> MagicMock:
        """
        Patch Debusine.upload_artifact.

        Return different RemoteArtifacts for each request.
        """
        patcher_upload_artifact = mock.patch.object(
            Debusine, "upload_artifact", autospec=True
        )
        mocked_upload_artifact = patcher_upload_artifact.start()

        id_counter = count(10)

        def upload_artifact(
            self,
            local_artifact,  # noqa: U100
            *,
            workspace: Optional[str],  # noqa: U100
            expire_at: Optional[datetime],  # noqa: U100
        ) -> RemoteArtifact:
            if workspace is None:  # pragma: no cover
                workspace = "System"
            return RemoteArtifact(id=next(id_counter), workspace=workspace)

        mocked_upload_artifact.side_effect = upload_artifact

        self.addCleanup(patcher_upload_artifact.stop)
        return mocked_upload_artifact

    def patch_relation_create(self) -> MagicMock:
        """Patch Debusine.relation_create."""
        patcher_relation_create = mock.patch.object(
            Debusine, "relation_create", autospec=True
        )
        mocked_relation_create = patcher_relation_create.start()
        self.addCleanup(patcher_relation_create.stop)
        return mocked_relation_create

    def assert_artifacts_are_uploaded(
        self,
        mocked_upload_artifact,
        expected_workspace: str,
        expected_artifacts: int,
        expected_files: int,
        stdout: str,
        stderr: str,
        extended_artifacts: Optional[list[str]] = None,
        related_artifacts: Optional[list[str]] = None,
        expected_expire_at: Optional[datetime] = None,
    ) -> list[LocalArtifact[Any]]:
        """
        Assert that mocked_upload_artifact uploaded expected_artifacts only.

        In stdout we expect that CLI printed the uploaded artifacts.

        Return LocalArtifacts that would have been uploaded.

        :param mocked_upload_artifact: mock of upload_artifact.
        :param expected_workspace: expected created workspace.
        :param expected_artifacts: expected number of artifacts created.
        :param expected_files: expected number of files uploaded.
        :param extended_artifacts: expected artifact IDs extending the main
            artifact.
        :param related_artifacts: expected artifact IDs relating to the main
            artifact.
        :param stdout: contains Cli.execute() output to verify expected output.
        :param stderr: contains Cli.execute() output to verify expected output.
        """
        self.assertEqual(mocked_upload_artifact.call_count, expected_artifacts)

        server_url = self.servers[self.default_server]["api-url"]

        expected = {
            "result": "success",
            "message": (
                f"New artifact created in {server_url} in workspace "
                f"{expected_workspace} with id 10."
            ),
            "artifact_id": 10,
        }
        if extended_artifacts:
            expected["extends"] = [
                {"artifact_id": id_} for id_ in extended_artifacts
            ]
        if related_artifacts:
            expected["relates_to"] = [
                {"artifact_id": id_} for id_ in related_artifacts
            ]
        expected_str = yaml.safe_dump(
            expected,
            sort_keys=False,
            width=math.inf,
        )

        self.assertEqual(stdout, expected_str)
        self.assertEqual(stderr, "")

        local_artifacts = []
        uploaded_files = set()
        for args, kwargs in mocked_upload_artifact.call_args_list:
            self.assertEqual(len(args), 2)
            debusine, local_artifact = args
            self.assertEqual(kwargs["workspace"], expected_workspace)
            self.assertEqual(kwargs["expire_at"], expected_expire_at)
            self.assertIsInstance(local_artifact, LocalArtifact)
            for file in local_artifact.files:
                uploaded_files.add(file)
            local_artifacts.append(local_artifact)

        self.assertEqual(len(uploaded_files), expected_files)

        return local_artifacts

    def import_debian_artifact(
        self,
        *,
        workspace: Optional[str] = None,
        upload: Optional[str] = None,
        expire_at: Optional[datetime] = None,
        upload_artifact_side_effect: Union[
            BaseException, type[BaseException], None
        ] = None,
        assert_system_exit_code: Optional[int] = None,
    ) -> tuple[str, str, MagicMock]:
        """
        Call CLI import-debian-artifact with the correct parameters.

        Patch Debusine.upload_artifact before executing the command.

        :param workspace: add ["--workspace", workspace] options.
        :param upload: file path / URL to upload.
        :param expire_at: datetime (for --expire-at option).
        :param upload_artifact_side_effect: side effect for the
          Debusine.create_artifact mock.
        :param assert_system_exit_code: assert that the import-debian-artifact
          command raises SystemExit(X).

        Return tuple with stderr, stdout and the patched
        Debusine.upload_artifact
        """
        mocked_upload_artifact = self.patch_upload_artifact()

        if upload_artifact_side_effect is not None:
            mocked_upload_artifact.side_effect = upload_artifact_side_effect

        args = []

        if workspace is not None:
            args += ["--workspace", workspace]

        if expire_at is not None:
            args += ["--expire-at", str(expire_at)]

        args.append(str(upload))

        cli = self.create_cli(["import-debian-artifact", *args])

        if assert_system_exit_code is None:
            stderr, stdout = self.capture_output(cli.execute)
        else:
            stderr, stdout = self.capture_output(
                cli.execute, assert_system_exit_code=assert_system_exit_code
            )

        return stderr, stdout, mocked_upload_artifact

    def assert_import_dsc(
        self,
        dsc: Path,
        files: list[Path],
        workspace: str = "test",
        expire_at: Optional[datetime] = None,
    ):
        """
        Call import-debian-artifact to import a source package.

        Verify that the right artifacts are created and files uploaded.

        Return the uploaded artifacts.
        """
        # Make the request
        (
            stderr_actual,
            stdout_actual,
            mocked_upload_artifact,
        ) = self.import_debian_artifact(
            workspace=workspace,
            upload=str(dsc),
            expire_at=expire_at,
        )

        # Assert the call happened as expected
        artifacts = self.assert_artifacts_are_uploaded(
            mocked_upload_artifact,
            expected_workspace=workspace,
            expected_artifacts=1,
            expected_files=len(files),
            stdout=stdout_actual,
            stderr=stderr_actual,
            expected_expire_at=expire_at,
        )
        self.assertEqual(len(artifacts), 1)
        self.assertSourcePackage(artifacts[0])

    def assertSourcePackage(self, artifact: LocalArtifact[Any]):
        """Assert that artifact is a .dsc with expected metadata."""
        self.assertEqual(artifact.category, "debian:source-package")
        self.assertEqual(artifact.data.name, "hello-traditional")
        self.assertEqual(artifact.data.type, "dpkg")
        self.assertEqual(artifact.data.version, "1.0")
        self.assertEqual(
            artifact.data.dsc_fields["Source"], "hello-traditional"
        )
        self.assertEqual(
            set(artifact.files), {"pkg_1.0.dsc", "pkg_1.0.orig.tar.gz"}
        )

    def assertBinaryPackage(
        self, artifact: LocalArtifact[Any], binnmu: bool = False
    ):
        """Assert that artifact is a .deb with expected metadata."""
        self.assertEqual(artifact.category, "debian:binary-package")
        version = "1.0"
        if binnmu:
            version += "+b1"
        expected_deb_fields = {
            "Package": "pkg",
            "Version": version,
            "Architecture": "all",
            "Maintainer": "Example Person <person@example.org>",
            "Description": "Example description",
        }
        if binnmu:
            expected_deb_fields["Source"] = "pkg (1.0)"
        expected = {
            "srcpkg_name": "pkg",
            "srcpkg_version": "1.0",
            "deb_fields": expected_deb_fields,
            "deb_control_files": ["control"],
        }
        self.assertEqual(artifact.data, expected)
        self.assertEqual(set(artifact.files), {f"pkg_{version}_all.deb"})

    def assertBinaryPackages(
        self, artifact: LocalArtifact[Any], binnmu: bool = False
    ):
        """Assert that artifact is a deb set with expected metadata."""
        self.assertEqual(artifact.category, "debian:binary-packages")
        deb_version = "1.0"
        if binnmu:
            deb_version += "+b1"
        expected = {
            "srcpkg_name": "hello-traditional",
            "srcpkg_version": "1.0",
            "version": deb_version,
            "architecture": "all",
            "packages": ["pkg"],
        }
        self.assertEqual(artifact.data, expected)
        self.assertEqual(set(artifact.files), {f"pkg_{deb_version}_all.deb"})

    def assertUpload(
        self, artifact: LocalArtifact[Any], file_names: set[str], binnmu=False
    ):
        """Assert that artifact is an Upload with expected metadata."""
        self.assertEqual(artifact.category, "debian:upload")
        self.assertEqual(artifact.data.type, "dpkg")
        expected = "hello-traditional"
        if binnmu:
            expected += " (1.0)"
        self.assertEqual(artifact.data.changes_fields["Source"], expected)
        self.assertEqual(set(artifact.files), file_names)

    def test_import_debian_artifact_dsc(self):
        """Test import a .dsc from a local path."""
        files = self.create_dsc()
        self.assert_import_dsc(files[0], files)

    def test_import_debian_artifact_expire_at(self):
        """Test import a .dsc from a local path, with expiry."""
        expire_at = datetime.now() + timedelta(days=1)
        files = self.create_dsc()
        self.assert_import_dsc(files[0], files, expire_at=expire_at)

    def test_import_debian_artifact_workspace(self):
        """Test import a .dsc from a local path, with a workspace."""
        files = self.create_dsc()
        self.assert_import_dsc(files[0], files, workspace="different")

    def test_import_debian_artifact_source_changes(self):
        """Test import a source upload from a local path."""
        files = self.create_upload(source=True, binary=False)
        workspace = "test"
        self.patch_relation_create()
        stderr, stdout, mocked_upload_artifact = self.import_debian_artifact(
            upload=str(files[0]),
            workspace=workspace,
        )

        # Assert the call happened as expected
        artifacts = self.assert_artifacts_are_uploaded(
            mocked_upload_artifact,
            expected_workspace=workspace,
            expected_artifacts=2,
            expected_files=len(files),
            stdout=stdout,
            stderr=stderr,
            extended_artifacts=[11],
            related_artifacts=[11],
        )
        self.assertUpload(artifacts[0], {file.name for file in files})
        self.assertSourcePackage(artifacts[1])

    def test_import_debian_artifact_binary_changes(self):
        """Test import a binary upload from a local path."""
        files = self.create_upload(source=False, binary=True)
        workspace = "test"
        self.patch_relation_create()
        stderr, stdout, mocked_upload_artifact = self.import_debian_artifact(
            upload=str(files[0]),
            workspace=workspace,
        )

        # Assert the call happened as expected
        artifacts = self.assert_artifacts_are_uploaded(
            mocked_upload_artifact,
            expected_workspace=workspace,
            expected_artifacts=3,
            expected_files=len(files),
            stdout=stdout,
            stderr=stderr,
            extended_artifacts=[11, 12],
            related_artifacts=[11, 12],
        )
        self.assertUpload(artifacts[0], {file.name for file in files})
        self.assertBinaryPackage(artifacts[1])
        self.assertBinaryPackages(artifacts[2])

    def test_import_debian_artifact_binnmu_changes(self):
        """Test import a binnmu binary upload from a local path."""
        files = self.create_upload(source=False, binary=True, binnmu=True)
        workspace = "test"
        self.patch_relation_create()
        stderr, stdout, mocked_upload_artifact = self.import_debian_artifact(
            upload=str(files[0]),
            workspace=workspace,
        )

        # Assert the call happened as expected
        artifacts = self.assert_artifacts_are_uploaded(
            mocked_upload_artifact,
            expected_workspace=workspace,
            expected_artifacts=3,
            expected_files=len(files),
            stdout=stdout,
            stderr=stderr,
            extended_artifacts=[11, 12],
            related_artifacts=[11, 12],
        )
        self.assertUpload(
            artifacts[0], {file.name for file in files}, binnmu=True
        )
        self.assertBinaryPackage(artifacts[1], binnmu=True)
        self.assertBinaryPackages(artifacts[2], binnmu=True)

    def test_import_debian_artifact_mixed_changes(self):
        """Test import a source+binary upload from a local path."""
        files = self.create_upload(source=True, binary=True)
        workspace = "test"
        self.patch_relation_create()
        stderr, stdout, mocked_upload_artifact = self.import_debian_artifact(
            upload=str(files[0]),
            workspace=workspace,
        )

        # Assert the call happened as expected
        artifacts = self.assert_artifacts_are_uploaded(
            mocked_upload_artifact,
            expected_workspace=workspace,
            expected_artifacts=4,
            expected_files=len(files),
            stdout=stdout,
            stderr=stderr,
            extended_artifacts=[11, 12, 13],
            related_artifacts=[11, 12, 13],
        )
        self.assertUpload(artifacts[0], {file.name for file in files})
        self.assertBinaryPackage(artifacts[1])
        self.assertBinaryPackages(artifacts[2])
        self.assertSourcePackage(artifacts[3])

    def test_import_debian_artifact_fails_to_connect(self):
        """Debusine.upload_artifact fails: cannot connect to the server."""
        files = self.create_dsc()

        stderr, stdout, mocked_upload_artifact = self.import_debian_artifact(
            workspace="test",
            upload=str(files[0]),
            upload_artifact_side_effect=exceptions.ClientConnectionError,
            assert_system_exit_code=3,
        )
        self.assertTrue(stderr.startswith("Error connecting to debusine:"))

    def test_import_debian_artifact_multiple_dsc(self):
        """import-debian-artifact fails when given two .dscs."""
        files = self.create_upload(source=True, binary=False, extra_dsc=True)
        stderr, stdout, mocked_create_artifact = self.import_debian_artifact(
            upload=files[0], assert_system_exit_code=3
        )

        self.assertRegex(
            stderr, r"^Expecting exactly 1 \.dsc in source package, found 2$"
        )

    def test_import_debian_artifact_binary_changes_without_debs(self):
        """import-debian-artifact fails with a binary upload without debs."""
        changes = self.create_temporary_file(suffix=".changes")
        changes.write_bytes(
            textwrap.dedent(
                """\
                Format: 3.0 (quilt)
                Source: hello-traditional
                Binary: hello-traditional
                Version: 2.10-5
                Maintainer: Santiago Vila <sanvila@debian.org>
                Homepage: http://www.gnu.org/software/hello/
                Standards-Version: 4.3.0
                Architecture: all
                Package-List:
                 hello-traditional deb devel optional arch=any
                Files:
                """
            ).encode("utf-8")
        )
        stderr, stdout, mocked_create_artifact = self.import_debian_artifact(
            upload=changes, assert_system_exit_code=3
        )

        self.assertRegex(
            stderr,
            r"^Expecting at least one \.deb per arch in binary packages$",
        )

    def test_import_debian_artifact_deb_extension(self):
        """import-debian-artifact fails when given a .deb file directly."""
        file = self.create_temporary_file(suffix=".deb")
        stderr, stdout, mocked_create_artifact = self.import_debian_artifact(
            upload=file, assert_system_exit_code=3
        )

        self.assertEqual(
            stdout,
            (
                "result: failure\n"
                "error: Direct uploads of individual .deb files aren't yet "
                "possible. However they can be uploaded by using a .changes "
                "file.\n"
            ),
        )

    def test_import_debian_artifact_unknown_extension(self):
        """import-debian-artifact fails when given a .foo file."""
        file = self.create_temporary_file(suffix=".foo")
        stderr, stdout, mocked_create_artifact = self.import_debian_artifact(
            upload=file, assert_system_exit_code=3
        )

        self.assertEqual(
            stdout,
            (
                "result: failure\n"
                "error: Only source packages (.dsc) and source/binary uploads "
                "(.changes) can be directly imported with this command. "
                f"{file} is not supported.\n"
            ),
        )

    def test_import_debian_artifact_missing_file(self):
        """import-debian-artifact fails when a named file is missing."""
        file = "/tmp/nonexistent.dsc"
        stderr, stdout, mocked_create_artifact = self.import_debian_artifact(
            upload=file, assert_system_exit_code=3
        )
        self.assertEqual(
            stdout,
            (
                "result: failure\n"
                "error: '[Errno 2] No such file or directory: "
                "''/tmp/nonexistent.dsc'''\n"
            ),
        )

    def test_import_debian_artifact_missing_referenced_file(self):
        """import-debian-artifact fails when a referenced file is missing."""
        files = self.create_dsc()
        files[1].unlink()
        stderr, stdout, mocked_create_artifact = self.import_debian_artifact(
            upload=files[0], assert_system_exit_code=3
        )
        stdout_expected = yaml.safe_dump(
            {
                "result": "failure",
                "error": f'"{files[1]}" does not exist',
            },
            sort_keys=False,
        )
        self.assertEqual(stdout, stdout_expected)

    def test_import_debian_artifact_workspace_not_found(self):
        """import-debian-artifact fails when the named workspace is missing."""
        workspace_name = "does-not-exist"
        title_error = f'Workspace "{workspace_name}" cannot be found'
        files = self.create_dsc()

        stderr, stdout, mocked_upload_artifact = self.import_debian_artifact(
            workspace="test",
            upload=str(files[0]),
            upload_artifact_side_effect=DebusineError({"title": title_error}),
            assert_system_exit_code=3,
        )

        stdout_expected = yaml.safe_dump(
            {"result": "failure", "error": {"title": title_error}},
            sort_keys=False,
        )

        self.assertEqual(stderr, "")
        self.assertEqual(stdout, stdout_expected)


class CliCreateWorkRequestTests(BaseCliTests):
    """Tests for the Cli functionality related to create work requests."""

    def patch_work_request_create(self) -> MagicMock:
        """
        Patch Debusine.work_request_create.

        Does not set return_value / side_effect.
        """
        patcher_work_request_create = mock.patch.object(
            Debusine, 'work_request_create', autospec=True
        )
        mocked_work_request_create = patcher_work_request_create.start()
        self.addCleanup(patcher_work_request_create.stop)

        return mocked_work_request_create

    def test_create_work_request_invalid_task_name(self):
        """Cli parse the CLI and stdin to create a WorkRequest bad task_name."""
        mocked_work_request_create = self.patch_work_request_create()
        task_name = "task-name"
        mocked_work_request_create.side_effect = DebusineError(
            {"title": f"invalid {task_name}"}
        )

        mocked_sys_stdin_read = self.patch_sys_stdin_read()

        mocked_sys_stdin_read.return_value = (
            'distribution: jessie\npackage: http://..../package_1.2-3.dsc\n'
        )

        cli = self.create_cli(['create-work-request', task_name])

        stderr, stdout = self.capture_output(cli.execute)

        expected = yaml.safe_dump(
            {
                "result": "failure",
                "error": {"title": f"invalid {task_name}"},
            },
            sort_keys=False,
        )
        self.assertEqual(stdout, expected)

    def assert_create_work_request(
        self,
        cli: Cli,
        mocked_post_work_request: MagicMock,
        work_request_request: WorkRequestRequest,
    ):
        """
        Call cli.execute() and assert the work request is created.

        Assert expected stderr/stdout and network call.
        """
        stderr, stdout = self.capture_output(cli.execute)

        work_request_id = mocked_post_work_request.return_value.id

        expected = yaml.safe_dump(
            {
                'result': 'success',
                'message': (
                    'Work request registered on '
                    'https://debusine.debian.org/api with id '
                    f'{work_request_id}.'
                ),
                'work_request_id': work_request_id,
            },
            sort_keys=False,
        )
        self.assertEqual(stdout, expected)
        self.assertEqual(stderr, "")

        actual_work_request_request = mocked_post_work_request.mock_calls[0][1][
            1
        ]

        # Verify WorkRequestRequest is as expected
        self.assertEqual(actual_work_request_request, work_request_request)

    def verify_create_work_request_scenario(
        self,
        cli_args: list[str],
        workspace: Optional[str] = None,
        use_stdin: bool = False,
    ):
        """
        Test create-work-request using workspace/stdin/stdin-data.

        :param cli_args: first parameter is task_name. create-work-request
          is prepended to them.
        :param workspace: workspace to use or None if not specified in the
          cli_args
        :param use_stdin: to pass the generated data: use_stdin or a file.
        """
        task_name = cli_args[0]

        mocked_post_work_request = self.patch_work_request_create()
        work_request_id = 11
        data = {
            "distribution": "jessie",
            "package": "http://..../package_1.2-3.dsc",
        }
        mocked_post_work_request.return_value = create_work_request_response(
            id=work_request_id
        )

        serialized_data = yaml.safe_dump(data)

        if use_stdin:
            mocked_sys_stdin_read = self.patch_sys_stdin_read()
            mocked_sys_stdin_read.return_value = serialized_data
            data_option = "-"
        else:
            data_file = self.create_temporary_file(
                contents=serialized_data.encode("utf-8")
            )
            data_option = str(data_file)

        cli = self.create_cli(
            ["create-work-request"] + cli_args + (["--data", data_option])
        )

        expected_work_request_request = WorkRequestRequest(
            task_name=task_name, workspace=workspace, task_data=data
        )
        self.assert_create_work_request(
            cli, mocked_post_work_request, expected_work_request_request
        )

    def test_create_work_request_specific_workspace(self):
        """Cli parse the command line and use workspace."""
        workspace_name = "Testing"
        args = ["sbuild", "--workspace", workspace_name]
        self.verify_create_work_request_scenario(args, workspace=workspace_name)

    def test_create_work_request_success_data_from_file(self):
        """Cli parse the command line and read file to create a work request."""
        args = ["sbuild"]
        self.verify_create_work_request_scenario(args)

    def test_create_work_request_success_data_from_stdin(self):
        """Cli parse the command line and stdin to create a work request."""
        args = ["sbuild"]
        self.verify_create_work_request_scenario(args, use_stdin=True)

    def test_create_work_request_data_is_empty(self):
        """Cli parse command line to create a work request with empty data."""
        empty_file = self.create_temporary_file()
        cli = self.create_cli(
            ["create-work-request", "sbuild", "--data", str(empty_file)]
        )

        stderr, stdout = self.capture_output(
            cli.execute, assert_system_exit_code=3
        )

        self.assertEqual(
            stderr, "Error: data must be a dictionary. It is empty\n"
        )
        self.assertEqual(stdout, "")

    def test_create_work_request_yaml_errors_failed(self):
        """cli.execute() deal with different invalid task_data."""
        work_requests = [
            {
                "task_data": "test:\n  name: a-name\n"
                "    first-name: some first name",
                "comment": "yaml.safe_load raises ScannerError",
            },
            {
                "task_data": "input:\n  source_url: https://example.com\n"
                " sbuild_options:\n - --post=some_command\n",
                "comment": "yaml.safe_load raises ParserError",
            },
        ]

        mocked_sys_stdin = self.patch_sys_stdin_read()

        for work_request in work_requests:
            task_data = work_request["task_data"]
            with self.subTest(task_data):
                mocked_sys_stdin.return_value = task_data

                cli = self.create_cli(["create-work-request", "task-name"])
                stderr, stdout = self.capture_output(
                    cli.execute, assert_system_exit_code=3
                )

                self.assertRegex(stderr, "^Error parsing YAML:")
                self.assertRegex(
                    stderr,
                    "Fix the YAML data\n$",
                )


class CliWorkRequestListTests(BaseCliTests):
    """Tests for CLI list-work-requests method."""

    def setUp(self):
        """Set up test."""
        self.artifact = create_artifact_response(
            id=1,
        )
        super().setUp()

    def test_list_work_requests_success(self):
        """CLI lists work requests and prints them."""
        work_request_response_1 = create_work_request_response(id=1)
        work_request_response_2 = create_work_request_response(id=2)

        def work_request_iter(self):
            yield work_request_response_1
            yield work_request_response_2

        patcher = mock.patch.object(
            Debusine, "work_request_iter", autospec=True
        )
        mocked_work_request_iter = patcher.start()
        mocked_work_request_iter.side_effect = work_request_iter
        self.addCleanup(patcher.stop)

        cli = self.create_cli(["list-work-requests"])

        stderr, stdout = self.capture_output(cli.execute)

        expected = yaml.safe_dump(
            {
                "results": [
                    {
                        "id": work_request_response.id,
                        "created_at": work_request_response.created_at,
                        "started_at": work_request_response.started_at,
                        "completed_at": work_request_response.completed_at,
                        "duration": work_request_response.duration,
                        "status": work_request_response.status,
                        "result": work_request_response.result,
                        "worker": work_request_response.worker,
                        "task_name": work_request_response.task_name,
                        "task_data": work_request_response.task_data,
                        "artifacts": [],
                        "workspace": work_request_response.workspace,
                    }
                    for work_request_response in (
                        work_request_response_1,
                        work_request_response_2,
                    )
                ]
            },
            sort_keys=False,
        )
        self.assertEqual(stdout, expected)


class CliWorkRequestStatusTests(BaseCliTests):
    """Tests for the Cli functionality related to work request status."""

    def setUp(self):
        """Set up test."""
        self.artifact = create_artifact_response(
            id=1,
        )
        super().setUp()

    def artifact_get(
        self, debusine: None, artifact_id: int  # noqa: U100
    ) -> ArtifactResponse:
        """
        Return copy of self.artifact changing its id to artifact_id.

        :param debusine: unused, only to have the same function signature
          as Debusine.artifact_get() (so it can be used in a mock)
        :param artifact_id: if of the returned artifact.
        """
        artifact = self.artifact.copy()
        artifact.id = artifact_id
        return artifact

    def test_show_work_request_success(self):
        """Cli use Debusine to fetch a WorkRequest and prints it to stdout."""
        patcher = mock.patch.object(Debusine, 'work_request_get', autospec=True)
        created_at = datetime.now()
        mocked_task_status = patcher.start()
        work_request_id = 10
        artifact_ids = [1, 2]
        work_request_response = create_work_request_response(
            id=work_request_id,
            created_at=created_at,
            artifacts=artifact_ids,
            task_data={"architecture": "amd64"},
            status="running",
        )
        mocked_task_status.return_value = work_request_response
        self.addCleanup(patcher.stop)

        # Patch artifact_get
        artifact_get_patcher = mock.patch.object(
            Debusine, "artifact_get", autospec=True
        )
        artifact_get_mocked = artifact_get_patcher.start()
        artifact_get_mocked.side_effect = self.artifact_get
        self.addCleanup(artifact_get_patcher.stop)

        cli = self.create_cli(['show-work-request', str(work_request_id)])

        stderr, stdout = self.capture_output(cli.execute)

        expected_artifacts = []

        for artifact_id in artifact_ids:
            expected_artifacts.append(
                model_to_json_serializable_dict(
                    self.artifact_get(None, artifact_id)
                )
            )

        expected = yaml.safe_dump(
            {
                'id': work_request_response.id,
                'created_at': work_request_response.created_at,
                'started_at': work_request_response.started_at,
                'completed_at': work_request_response.completed_at,
                'duration': work_request_response.duration,
                'status': work_request_response.status,
                'result': work_request_response.result,
                'worker': work_request_response.worker,
                'task_name': work_request_response.task_name,
                'task_data': work_request_response.task_data,
                "artifacts": expected_artifacts,
                "workspace": work_request_response.workspace,
            },
            sort_keys=False,
        )
        self.assertEqual(stdout, expected)


class CliDownloadArtifact(BaseCliTests):
    """Tests for the Cli functionality related to downloading an artifact."""

    def test_download_artifact(self):
        """download-artifact call debusine.download_artifact()."""
        artifact_id = str(10)

        debusine = self.patch_build_debusine_object()

        tests = [
            {
                "args": ["download-artifact", artifact_id, "--tarball"],
                "tarball": True,
                "destination": Path.cwd(),
            },
            {
                "args": ["download-artifact", artifact_id],
                "tarball": False,
                "destination": Path.cwd(),
            },
            {
                "args": ["-s", "download-artifact", artifact_id, "--tarball"],
                "tarball": True,
                "destination": Path.cwd(),
            },
            {
                "args": ["-s", "download-artifact", artifact_id],
                "tarball": False,
                "destination": Path.cwd(),
            },
        ]

        for test in tests:
            with self.subTest(test=test):
                cli = self.create_cli(test["args"])

                cli.execute()

                debusine.return_value.download_artifact.assert_called_with(
                    int(artifact_id),
                    destination=test["destination"],
                    tarball=test["tarball"],
                )

    def test_download_artifact_target_directory_no_write_access(self):
        """_download_artifact target_directory no write access."""
        # Similar as other tests: avoid building the debusine object
        # (not relevant for this test)
        self.patch_build_debusine_object()

        target_directory = self.create_temporary_directory()
        os.chmod(target_directory, 0)

        cli = self.create_cli(
            [
                "download-artifact",
                "10",
                "--target-directory",
                str(target_directory),
            ],
            create_config=False,
        )

        stderr, stdout = self.capture_output(
            cli.execute, assert_system_exit_code=3
        )

        self.assertEqual(stderr, f"Error: Cannot write to {target_directory}\n")
        self.assertEqual(stdout, "")


class CliShowArtifactTests(BaseCliTests):
    """Tests for Cli show-artifact."""

    def test_show_artifact(self):
        """Test show-artifact shows the information."""
        artifact_id = 11
        debusine = self.patch_build_debusine_object()
        cli = self.create_cli(["show-artifact", str(artifact_id)])

        api_call_or_fail_mocked = self.patch_api_call_or_fail(cli)
        api_call_or_fail_mocked.return_value = create_artifact_response(
            id=artifact_id
        )

        stderr, stdout = self.capture_output(cli.execute)

        api_call_or_fail_mocked.assert_called_with(
            debusine.return_value.artifact_get, int(artifact_id)
        )

        self.assertEqual(stderr, "")

        _, expected_output = self.capture_output(
            Cli._print_yaml,
            [
                model_to_json_serializable_dict(
                    api_call_or_fail_mocked.return_value
                )
            ],
        )

        self.assertEqual(stdout, expected_output)


class CliOnWorkRequestTests(BaseCliTests):
    """Tests for Cli on-work-request-completed."""

    def test_command_does_not_exist(self):
        """Cli report that command does not exist."""
        command = "/some/file/does/not/exist"
        cli = self.create_cli(["on-work-request-completed", command])

        stderr, stdout = self.capture_output(
            cli.execute, assert_system_exit_code=3
        )

        self.assertEqual(
            stderr, f'Error: "{command}" does not exist or is not executable\n'
        )
        self.assertEqual(stdout, "")

    def test_command_is_not_executable(self):
        """Cli report that command is not executable."""
        command = self.create_temporary_file()
        cli = self.create_cli(["on-work-request-completed", str(command)])

        stderr, stdout = self.capture_output(
            cli.execute, assert_system_exit_code=3
        )

        self.assertEqual(
            stderr, f'Error: "{command}" does not exist or is not executable\n'
        )
        self.assertEqual(stdout, "")

    def debusine_on_work_request_completed_is_called(
        self,
        *,
        workspaces: Optional[list[str]] = None,
        last_completed_at: Optional[Path] = None,
        silent: Optional[bool] = False,
    ):
        """Cli call debusine.on_work_request_completed."""
        command = self.create_temporary_file()
        command.chmod(stat.S_IXUSR | stat.S_IRUSR)

        debusine = self.patch_build_debusine_object()

        cli_args = []

        if silent:
            cli_args.extend(["--silent"])

        cli_args.extend(["on-work-request-completed", str(command)])

        if workspaces:
            cli_args.extend(["--workspace", *workspaces])

        if last_completed_at:
            cli_args.extend(["--last-completed-at", str(last_completed_at)])

        cli = self.create_cli(cli_args)

        stderr, stdout = self.capture_output(cli.execute)

        self.assertEqual(stderr, "")
        self.assertEqual(stdout, "")

        debusine.return_value.on_work_request_completed.assert_called_with(
            workspaces=workspaces,
            last_completed_at=last_completed_at,
            command=str(command),
            working_directory=Path.cwd(),
        )

    def test_debusine_on_work_request_completed(self):
        """Cli call debusine.on_work_request_completed."""
        self.debusine_on_work_request_completed_is_called(silent=True)

    def test_debusine_on_work_request_completed_with_workspace(self):
        """Cli call debusine.on_work_request_completed."""
        self.debusine_on_work_request_completed_is_called(workspaces=["System"])

    def test_debusine_on_work_request_completed_create_last_completed(self):
        """
        Cli call debusine.on_work_request_completed.

        File last_completed_at is created.
        """
        last_completed_at = self.create_temporary_file()
        last_completed_at.unlink()

        self.debusine_on_work_request_completed_is_called(
            last_completed_at=last_completed_at
        )

        expected = json.dumps({"last_completed_at": None}, indent=2) + "\n"
        self.assertEqual(last_completed_at.read_text(), expected)

    def test_debusine_on_work_request_completed_last_completed_existed(self):
        """Cli call debusine.on_work_request_completed."""
        contents = json.dumps({"last_completed_at": None}).encode("utf-8")
        last_completed_at = self.create_temporary_file(contents=contents)

        self.debusine_on_work_request_completed_is_called(
            last_completed_at=last_completed_at
        )

    def test_debusine_on_work_request_last_completed_no_write_permission(self):
        """Cli cannot write to last-completed-at file."""
        cannot_write = self.create_temporary_file()
        cannot_write.chmod(0o444)
        cli = self.create_cli(
            [
                "on-work-request-completed",
                "/bin/echo",
                "--last-completed-at",
                str(cannot_write),
            ]
        )

        stderr, stdout = self.capture_output(
            cli.execute,
            assert_system_exit_code=3,
        )
        self.assertEqual(
            stderr,
            'Error: write or read access '
            f'denied for "{str(cannot_write)}"\n',
        )

    def test_debusine_on_work_request_last_completed_no_read_permission(self):
        """Cli cannot write to last-completed-at file."""
        cannot_write = self.create_temporary_file()
        cannot_write.chmod(0o333)
        cli = self.create_cli(
            [
                "on-work-request-completed",
                "/bin/echo",
                "--last-completed-at",
                str(cannot_write),
            ]
        )

        stderr, stdout = self.capture_output(
            cli.execute,
            assert_system_exit_code=3,
        )
        self.assertEqual(
            stderr,
            'Error: write or read access '
            f'denied for "{str(cannot_write)}"\n',
        )

    def test_debusine_on_work_request_dir_last_completed_no_permission(self):
        """Cli cannot write to last-completed-at directory."""
        directory = self.create_temporary_directory()
        directory.chmod(0o000)
        cli = self.create_cli(
            [
                "on-work-request-completed",
                "/bin/echo",
                "--last-completed-at",
                str(directory / "file.json"),
            ]
        )

        stderr, stdout = self.capture_output(
            cli.execute,
            assert_system_exit_code=3,
        )
        self.assertEqual(
            stderr,
            f'Error: write access denied for directory "{str(directory)}"\n',
        )
