# 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 list_workers."""

from django.test import TestCase

from debusine.db.models import Token, Worker
from debusine.server.management.commands.tests import call_command


class ListWorkersCommandTests(TestCase):
    """Test for list_workers management command."""

    def test_list_workers_connected(self):
        """
        List worker command prints worker information.

        The worker is connected.
        """
        token = Token.objects.create()

        worker_1 = Worker.objects.create_with_fqdn('recent-ping', token)
        worker_1.mark_connected()

        stdout, stderr, _ = call_command('list_workers')

        self.assertIn(worker_1.name, stdout)
        self.assertIn(worker_1.registered_at.isoformat(), stdout)
        self.assertIn(worker_1.connected_at.isoformat(), stdout)
        self.assertIn(token.hash, stdout)
        self.assertEqual(stdout.count(str(token.enabled)), 1)
        self.assertIn('Number of workers: 1', stdout)

    def test_list_workers_not_connected(self):
        """
        List worker command prints worker information.

        The worker is not connected.
        """
        token = Token.objects.create()

        worker_1 = Worker.objects.create_with_fqdn('recent-ping', token=token)
        stdout, stderr, _ = call_command('list_workers')

        registered_at = worker_1.registered_at.isoformat()

        self.assertIn(worker_1.name, stdout)
        self.assertIn(registered_at, stdout)

        # Connected column has a "-"
        self.assertIn(registered_at + '  -', stdout)

        self.assertIn(token.hash, stdout)
        self.assertIn('Number of workers: 1', stdout)

    def test_list_workers_internal(self):
        """list_workers handles internal workers, which have no tokens."""
        worker = Worker.objects.get_or_create_celery()
        worker.mark_connected()

        stdout, stderr, _ = call_command("list_workers")

        self.assertEqual(
            stdout.splitlines()[2].split(),
            [
                worker.name,
                worker.registered_at.isoformat(),
                worker.connected_at.isoformat(),
                "-",
                "True",
            ],
        )
