# Copyright 2024 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.

"""Unit tests for base signing task classes."""

from pathlib import Path

from django.db import connections
from django.test import TestCase, TransactionTestCase

from debusine.signing.tasks import BaseSigningTask
from debusine.tasks.models import BaseDynamicTaskData, BaseTaskData, WorkerType
from debusine.tasks.tests.helper_mixin import TestTaskMixin


class TestBaseSigningTask(
    TestTaskMixin, BaseSigningTask[BaseTaskData, BaseDynamicTaskData]
):
    """Sample class to test BaseSigningTask class."""

    def run(self, execute_directory: Path) -> bool:  # noqa: U100
        """Succeed if this task is running in a transaction."""
        return connections["default"].in_atomic_block


class TestBaseSigningTask2Data(TestTaskMixin, BaseTaskData):
    """Data representation for TestBaseSigningTask2."""

    __test__ = False

    foo: str


class TestBaseSigningTask2(
    TestTaskMixin,
    BaseSigningTask[TestBaseSigningTask2Data, BaseDynamicTaskData],
):
    """Test BaseSigningTask class with jsonschema validation."""

    TASK_VERSION = 1

    def run(self, execute_directory: Path) -> bool:  # noqa: U100
        """Unused abstract method from BaseExternalTask."""
        raise NotImplementedError()


class BaseSigningTaskTests(TestCase):
    """Unit tests for :class:`BaseSigningTask`."""

    def setUp(self) -> None:
        """Create the shared attributes."""
        self.task = TestBaseSigningTask({})
        self.task2 = TestBaseSigningTask2({"foo": "bar"})
        self.worker_metadata = {"system:worker_type": WorkerType.SIGNING}

    def test_can_run_on_no_version(self):
        """Ensure can_run_on returns True if no version is specified."""
        self.assertIsNone(self.task.TASK_VERSION)
        metadata = {**self.worker_metadata, **self.task.analyze_worker()}
        self.assertEqual(self.task.can_run_on(metadata), True)

    def test_can_run_on_with_different_versions(self):
        """Ensure can_run_on returns False if versions differ."""
        self.assertIsNone(self.task.TASK_VERSION)
        metadata = {**self.worker_metadata, **self.task.analyze_worker()}
        metadata["signing:testbasesigningtask:version"] = 1
        self.assertEqual(self.task.can_run_on(metadata), False)


class BaseSigningTaskTransactionTests(TransactionTestCase):
    """Test transactional behaviour of :class:`BaseSigningTask`."""

    def test_runs_in_transaction(self):
        """Tasks are executed in a transaction."""
        task = TestBaseSigningTask({}, {})
        self.assertTrue(task.execute())
