# -*- coding: utf-8; -*-

import os
from unittest import TestCase
from unittest.mock import MagicMock, patch, call

from wuttamess import util as mod


class TestExists(TestCase):

    def test_basic(self):
        c = MagicMock()
        mod.exists(c, '/foo')
        c.run.assert_called_once_with('test -e /foo', warn=True)


class TestHomePath(TestCase):

    def test_basic(self):
        c = MagicMock()
        c.run.return_value.stdout = '/home/foo'
        path = mod.get_home_path(c, user='foo')
        self.assertEqual(path, '/home/foo')


class TestIsSymlink(TestCase):

    def test_yes(self):
        c = MagicMock()
        c.run.return_value.failed = False
        self.assertTrue(mod.is_symlink(c, '/foo'))
        c.run.assert_called_once_with('test -L "$(echo /foo)"', warn=True)

    def test_no(self):
        c = MagicMock()
        c.run.return_value.failed = True
        self.assertFalse(mod.is_symlink(c, '/foo'))
        c.run.assert_called_once_with('test -L "$(echo /foo)"', warn=True)


class TestMakoRenderer(TestCase):

    def test_basic(self):
        c = MagicMock()
        renderer = mod.mako_renderer(c, env={'machine_is_live': True})
        here = os.path.dirname(__file__)
        path = os.path.join(here, 'files', 'bar', 'baz')
        rendered = renderer(path, vars={})
        self.assertEqual(rendered, 'machine_is_live = True')


class TestSetTimezone(TestCase):

    def test_symlink(self):
        c = MagicMock()
        with patch.object(mod, 'is_symlink') as is_symlink:
            is_symlink.return_value = True
            mod.set_timezone(c, 'America/Chicago')
            c.run.assert_has_calls([
                call("bash -c 'echo America/Chicago > /etc/timezone'"),
            ])
            c.run.assert_called_with('ln -sf /usr/share/zoneinfo/America/Chicago /etc/localtime')

    def test_not_symlink(self):
        c = MagicMock()
        with patch.object(mod, 'is_symlink') as is_symlink:
            is_symlink.return_value = False
            mod.set_timezone(c, 'America/Chicago')
            c.run.assert_has_calls([
                call("bash -c 'echo America/Chicago > /etc/timezone'"),
            ])
            c.run.assert_called_with('cp /usr/share/zoneinfo/America/Chicago /etc/localtime')