# Copyright © 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 setup command."""

import contextlib
import io
from unittest import mock

from debusine.client.cli import Cli
from debusine.client.commands.tests.base import BaseCliTests
from debusine.client.config import ConfigHandler


class CliSetupTests(BaseCliTests):
    """Tests for the setup command."""

    def assertRunsSuccessfully(self, cli: Cli) -> None:
        """Ensure cli runs successfully."""
        stderr = io.StringIO()
        with contextlib.redirect_stderr(stderr):
            cli.execute()
        self.assertEqual(stderr.getvalue(), "")

    def test_without_args(self) -> None:
        """Call setup without arguments."""
        with mock.patch("debusine.client.setup.setup_server") as setup_server:
            cli = self.create_cli(["setup"], create_config=False)
            self.assertRunsSuccessfully(cli)
        setup_server.assert_called_with(
            config_file_path=ConfigHandler.DEFAULT_CONFIG_FILE_PATH,
            server=None,
            scope=None,
        )

    def test_with_config(self) -> None:
        """Call setup with --config-file."""
        with mock.patch("debusine.client.setup.setup_server") as setup_server:
            cli = self.create_cli(
                ["--config-file=debusine.cfg", "setup"], create_config=False
            )
            self.assertRunsSuccessfully(cli)
        setup_server.assert_called_with(
            config_file_path="debusine.cfg", server=None, scope=None
        )

    def test_with_server(self) -> None:
        """Call setup with --server."""
        with mock.patch("debusine.client.setup.setup_server") as setup_server:
            cli = self.create_cli(
                ["--server=debian", "setup"], create_config=False
            )
            self.assertRunsSuccessfully(cli)
        setup_server.assert_called_with(
            config_file_path=ConfigHandler.DEFAULT_CONFIG_FILE_PATH,
            server="debian",
            scope=None,
        )

    def test_with_scope(self) -> None:
        """Call setup with --scope."""
        with mock.patch("debusine.client.setup.setup_server") as setup_server:
            cli = self.create_cli(
                ["--scope=debian", "setup"], create_config=False
            )
            self.assertRunsSuccessfully(cli)
        setup_server.assert_called_with(
            config_file_path=ConfigHandler.DEFAULT_CONFIG_FILE_PATH,
            server=None,
            scope="debian",
        )
