import unittest
from unittest.mock import patch, MagicMock

from helix.db.redis_manager import RedisManager


class RedisManagerTest(unittest.TestCase):
    def test_parses_vcap_environment_variable(self):
        valid_vcap_string = """
    {
      "rediscloud": [
        {
          "credentials": {
            "hostname": "fakehost",
            "password": "fakepassword",
            "port": "1234"
          },
          "syslog_drain_url": null,
          "label": "rediscloud",
          "provider": null,
          "plan": "30mb",
          "name": "helix-staging-redis",
          "tags": [
            "Data Stores",
            "Data Store",
            "Caching",
            "Messaging and Queuing",
            "key-value",
            "caching",
            "redis"
          ]
        }
      ]
    }
        """
        mock_redis = MagicMock()

        with patch('redis.Redis', mock_redis):
            RedisManager.get_redis_connection(valid_vcap_string, 'redis://example.org')
        mock_redis.assert_called_with(host='fakehost', password='fakepassword', port=1234)

    def test_uses_url_if_vcap_environment_is_not_set(self):
        mock_redis = MagicMock()

        with patch('redis.Redis', mock_redis):
            RedisManager.get_redis_connection(None, 'redis://example.org')
        mock_redis.from_url.assert_called_with('redis://example.org')

    def test_defaults_to_local_connection_if_vcap_environment_is_not_set_and_url_is_none(self):
        mock_redis = MagicMock()

        with patch('redis.Redis', mock_redis):
            RedisManager.get_redis_connection(None, None)
        mock_redis.assert_called_with(host='localhost', port=6379, db=0)
