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

import datetime

from django.test import TestCase
from django.utils import timezone

from debusine.db.models import Token, WorkRequest, Worker
from debusine.django.management.tests import call_command
from debusine.server.management import utils
from debusine.test import TestHelpersMixin


class ListWorkRequestsCommandTests(TestHelpersMixin, TestCase):
    """Test for list_work_requests management command.."""

    def setUp(self):
        """Create a Work Request and a Worker."""
        self.work_request = self.create_work_request(task_name="sbuild")

    def test_list_work_requests_not_assigned(self):
        """Test a non-assigned work request output."""
        stdout, stderr, _ = call_command("list_work_requests")

        self.assertIn(self.work_request.status, stdout)

        self.assertIn(
            utils.datetime_to_isoformat(self.work_request.created_at), stdout
        )

    def test_list_work_requests_assigned_finished(self):
        """Test an assigned work request output."""
        worker = Worker.objects.create_with_fqdn(
            "neptune", Token.objects.create()
        )
        self.work_request.worker = worker
        self.work_request.created_at = timezone.now()
        one_sec = datetime.timedelta(seconds=1)
        self.work_request.started_at = self.work_request.created_at + one_sec
        self.work_request.completed_at = self.work_request.started_at + one_sec
        self.work_request.result = WorkRequest.Results.SUCCESS
        self.work_request.save()

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

        self.assertIn("neptune", stdout)
        self.assertIn(
            utils.datetime_to_isoformat(self.work_request.created_at), stdout
        )
        self.assertIn(
            utils.datetime_to_isoformat(self.work_request.started_at), stdout
        )
        self.assertIn(
            utils.datetime_to_isoformat(self.work_request.completed_at), stdout
        )
        self.assertIn(self.work_request.result, stdout)

        self.assertIn('Number of work requests: 1', stdout)
