# Copyright 2021-2023 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 management command manage_token."""

from django.core.management import CommandError
from django.test import TestCase

from debusine.db.models import Token
from debusine.server.tests.commands import call_command


class ManageTokenCommandTests(TestCase):
    """Tests for manage_token management command."""

    def setUp(self):
        """Create a default Token."""
        self.token = Token.objects.create()

    def test_enable_token(self):
        """'manage_token enable <token>' enables the token."""
        self.assertFalse(self.token.enabled)

        call_command('manage_token', 'enable', self.token.key)
        self.token.refresh_from_db()
        self.assertTrue(self.token.enabled)

    def test_disable_token(self):
        """'manage_token disable <token>' disables the token."""
        self.token.enable()

        self.assertTrue(self.token.enabled)

        call_command('manage_token', 'disable', self.token.key)
        self.token.refresh_from_db()
        self.assertFalse(self.token.enabled)

    def test_enable_token_not_found(self):
        """Token not found raise CommandError."""
        with self.assertRaisesRegex(CommandError, "^Token not found$"):
            call_command('manage_token', 'enable', 'token-key-does-not-exist')
