import json
from unittest.mock import MagicMock, call
from django.test import TestCase

from kolekti import tasks, models
from .. import factories


class StoreResultTaskTests(TestCase):
    def setUp(self):
        self.check = factories.Check()
        self.client = factories.Client()
        self.func_store_measure = MagicMock()
        self.func_store_measure.delay = MagicMock()

    def test_empty_result(self):
        message = dict(
            stderr="",
            stdout="",
            rc=0,
            duration=120,
        )

        result_id = tasks.store_result(
            self.check.pk,
            self.client.pk,
            200,
            json.dumps(message),
            140,
            func_store_measure=self.func_store_measure,
        )
        assert not self.func_store_measure.called
        assert not self.func_store_measure.delay.called
        assert models.Result.objects.get(pk=result_id) is not None

    def test_one_check_result(self):
        measure_name = factories.faker.sentence().strip().replace(" ", ".")
        measure_value = factories.faker.pyfloat()
        measure_time = factories.faker.unix_time()
        message = dict(
            stderr="",
            stdout="{} {} {}".format(
                measure_name,
                measure_value,
                measure_time,
            ),
            rc=0,
            duration=120,
        )

        result_id = tasks.store_result(
            self.check.pk,
            self.client.pk,
            200,
            json.dumps(message),
            140,
            func_store_measure=self.func_store_measure,
        )
        assert [
            call(result_id, measure_name, measure_value, measure_time)
        ] == self.func_store_measure.delay.mock_calls
