# 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 generic notifications."""
from django.test import TestCase

from debusine.db.models import Token, WorkRequest, Worker
from debusine.test.django import ChannelsHelpersMixin


class NotifyWorkerTokenDisabledTests(TestCase, ChannelsHelpersMixin):
    """Tests for notify_worker_token_disabled."""

    def setUp(self):
        """Initialise test."""
        self.token = Token.objects.create()

    def test_message_is_not_sent(self):
        """Test Token with an associated worker: message is sent."""
        channel = self.create_channel(self.token.key)

        self.token.disable()

        self.assert_channel_nothing_received(channel)

    def test_message_is_sent(self):
        """Test Token with an associated worker: message is sent."""
        Worker.objects.create_with_fqdn(fqdn="debusine", token=self.token)

        channel = self.create_channel(self.token.key)

        self.token.disable()

        self.assert_channel_received(channel, {"type": "worker.disabled"})


class NotifyWorkRequestAssigned(TestCase, ChannelsHelpersMixin):
    """Tests for notify_work_request_assigned."""

    def setUp(self):
        """Initialise test."""
        self.work_request = WorkRequest()

    def test_message_is_not_sent(self):
        """Test WorkRequest.assign_worker(None) is a no-operation."""
        # Asserts that no exception is raised. notify_work_request_assigned
        # is checking that worker is None and not trying to access the
        # worker's token.
        self.work_request.assign_worker(None)

    def test_message_is_sent(self):
        """Test WorkRequest.assign_worker(worker) sends msg to the channel."""
        token = Token.objects.create()
        worker = Worker.objects.create_with_fqdn("debusine", token=token)

        channel = self.create_channel(token.key)

        self.work_request.assign_worker(worker)

        self.assert_channel_received(channel, {"type": "work_request.assigned"})
