# -*- coding: utf-8 -*-
import json
from mock import patch

from . import ResourceTestCase


BACKEND_HEALTH_MOCK = {
    "error": None,
    "status": "green"
}


class HealthTestCase(ResourceTestCase):

    def get_health(self, show_sources=None, expected_status=200):

        url = '/health/'
        if show_sources is not None:
            url = '{}?show_sources={}'.format(url, show_sources)

        res = self.app.get(url)
        self.assertEqual(res.status_code, expected_status)

        return json.loads(res.data)

    @patch('distribution.controllers.health.current_backend.health',
           return_value=BACKEND_HEALTH_MOCK)
    def test_get(self, mock_backend_health):
        result = self.get_health()

        mock_backend_health.assert_called_once_with()
        self.assertEqual(result['status'], 'green')
        self.assertEqual(result['manager'], BACKEND_HEALTH_MOCK)
        self.assertFalse('sources' in result)

    @patch('distribution.controllers.health.current_backend.health',
           return_value=BACKEND_HEALTH_MOCK)
    @patch('distribution.controllers.health.FeedItem', autospec=True)
    def test_get_with_sources(self, mock_feeditem, mock_backend_health):
        mock_sources = {'xxx': 42}
        mock_feeditem.manager.count_sources.return_value = mock_sources.copy()
        result = self.get_health(show_sources=1)

        mock_backend_health.assert_called_once_with()
        mock_feeditem.manager.count_sources.assert_called_once_with()

        self.assertEqual(result['status'], 'green')
        self.assertEqual(result['manager'], BACKEND_HEALTH_MOCK)
        self.assertTrue(result['sources'], mock_sources)
