from __future__ import print_function, division, absolute_import
# Copyright (c) 2011 Red Hat, Inc.
#
# This software is licensed to you under the GNU General Public License,
# version 2 (GPLv2). There is NO WARRANTY for this software, express or
# implied, including the implied warranties of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2
# along with this software; if not, see
# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.
#
# Red Hat trademarks are not licensed under GPLv2. No permission is
# granted to use or replicate Red Hat trademarks that are incorporated
# in this software or its documentation.
#
try:
    import unittest2 as unittest
except ImportError:
    import unittest
#from gi.repository import Gtk
from datetime import datetime, timedelta
from rhsm.certificate import GMT
from subscription_manager.ga import Gtk as ga_Gtk
from subscription_manager.gui.storage import MappedTreeStore
from subscription_manager.gui.widgets import MachineTypeColumn, QuantitySelectionColumn, \
                                             SubDetailsWidget, ContractSubDetailsWidget, \
                                             DatePicker, HasSortableWidget
from dateutil.tz import tzlocal
from nose.plugins.attrib import attr
@attr('gui')
class TestSubDetailsWidget(unittest.TestCase):
    widget = SubDetailsWidget
    sku_text = "Some SKU"
    expected_sub_text = "All Available Subscription Text"
    def show(self, details):
        details.show(name="Some Product", contract="123123",
                     start=datetime.now(GMT()), end=datetime.now(GMT()) + timedelta(days=365),
                     highlight="some filter", support_level="Standard",
                     support_type="L1",
                     sku=self.sku_text)
    def test_show(self):
        details = self.widget(None)
        self.show(details)
    def test_clear(self):
        details = self.widget(None)
        self.show(details)
        details.clear()
    def test_a11y(self):
        details = self.widget(None)
        self.show(details)
        sub_text = details.subscription_text.get_accessible().get_name()
        self.assertEqual(self.expected_sub_text, sub_text)
@attr('gui')
class TestContractSubDetailsWidget(TestSubDetailsWidget):
    widget = ContractSubDetailsWidget
    expected_sub_text = "Subscription Text"
    def test_get_expired_bg(self):
        details = self.widget(None)
        self.show(details)
        yesterday = datetime.now(GMT()) - timedelta(days=1)
        bg_color = details._get_date_bg(yesterday, True)
        self.assertEqual(details.expired_color, bg_color)
    def test_get_warning_bg(self):
        details = self.widget(None)
        self.show(details)
        tomorrow = datetime.now(GMT()) + timedelta(days=1)
        bg_color = details._get_date_bg(tomorrow, True)
        self.assertEqual(details.warning_color, bg_color)
    def test_get_details(self):
        details = self.widget(None)
        reasons = ['reason 1', 'reason 2']
        details.show("Some Product", reasons=reasons, start=datetime.now(GMT()), end=datetime.now(GMT()) + timedelta(days=365))
        buff = details.details_view.get_buffer()
        result_list = buff.get_text(buff.get_bounds()[0],
                                    buff.get_bounds()[1],
                                    include_hidden_chars=False).split("\n")
        self.assertEqual(reasons, result_list)
    def testVirtOnly(self):
        details = self.widget(None)
        self.show(details)
        d = datetime(2011, 4, 16, tzinfo=tzlocal())
        start_date = datetime(d.year, d.month, d.day, tzinfo=tzlocal())
        end_date = datetime(d.year + 1, d.month, d.day, tzinfo=tzlocal())
        details.show('noname', contract='c', start=start_date, end=end_date, account='a',
                     management='m', support_level='s_l',
                     support_type='s_t', virt_only='v_o')
        s_iter = details.virt_only_text.get_buffer().get_start_iter()
        e_iter = details.virt_only_text.get_buffer().get_end_iter()
        self.assertEqual(details.virt_only_text.get_buffer().get_text(s_iter, e_iter, False), 'v_o')
@attr('gui')
class TestDatePicker(unittest.TestCase):
    def test_date_picker_date(self):
        d = datetime(2033, 12, 29, tzinfo=tzlocal())
        self._assert_is_isoformat(d)
    def test_date_validate_2000_12_1(self):
        d = datetime(2000, 12, 1, tzinfo=tzlocal())
        self._assert_is_isoformat(d)
    def test_date_validate_2000_1_22(self):
        d = datetime(2000, 1, 12, tzinfo=tzlocal())
        self._assert_is_isoformat(d)
    def test_date_validate_1_1_2000(self):
        d = datetime(2000, 1, 1, tzinfo=tzlocal())
        self._assert_is_isoformat(d)
    # why? because some locales fail to parse in dates with
    # double digt months
    def test_date_validate_12_29_2020(self):
        #with Capture(silent=True):
        d = datetime(2020, 12, 29, tzinfo=tzlocal())
        self._assert_is_isoformat(d)
    def _assert_is_isoformat(self, d):
        date_picker = DatePicker(d)
        valid = date_picker.date_entry_validate()
        self.assertTrue(valid)
        self.assertEqual(date_picker._date_entry.get_text(), d.date().isoformat())
class BaseColumnTest(unittest.TestCase):
    def _assert_column_value(self, column_class, model_bool_val, expected_text):
        model = ga_Gtk.ListStore(bool)
        model.append([model_bool_val])
        column = column_class(0)
        column._render_cell(None, column.renderer, model, model.get_iter_first())
        self.assertEqual(expected_text, column.renderer.get_property("text"))
@attr('gui')
class TestHasSortableWidget(unittest.TestCase):
    def _run_cases(self, cases, expected):
        for index, case in enumerate(cases):
            result = HasSortableWidget.compare_text(*case)
            self.assertEqual(result, expected[index])
    def test_compare_text_ints(self):
        # Two string representations of ints
        str1 = '1'
        str2 = '2'
        cases = [
            (str1, str2),  # x < y should return -1
            (str2, str1),  # x > y should return 1
            (str1, str1)  # x == y should return 0
        ]
        expected = [
            -1,
            1,
            0
        ]
        self._run_cases(cases, expected)
    def test_compare_text_unlimited(self):
        # Test unlimited comparison
        unlimited = 'Unlimited'
        str1 = '1'
        cases = [
            (unlimited, str1),  # Unlimited, 1 should return 1
            (str1, unlimited),  # 1, Unlimited should return -1
            (unlimited, unlimited)  # Unlimited, Unlimited should return 0
        ]
        expected = [
            1,
            -1,
            0
        ]
        self._run_cases(cases, expected)
    def test_compare_alphabetic_text(self):
        cases = [
            ('a', 'b'),
            ('b', 'a'),
            ('a', 'a')
        ]
        def _cmp(x1, x2):
            if x1 < x2:
                return -1
            elif x1 == x2:
                return 0
            else:
                return 1
        expected = [_cmp(*case) for case in cases]
        self._run_cases(cases, expected)
@attr('gui')
class TestMachineTypeColumn(BaseColumnTest):
    def test_render_virtual_when_virt_only(self):
        self._assert_column_value(MachineTypeColumn, True,
                                  MachineTypeColumn.VIRTUAL_MACHINE)
    def test_render_physical_when_not_virt_only(self):
        self._assert_column_value(MachineTypeColumn, False,
                                   MachineTypeColumn.PHYSICAL_MACHINE)
@attr('gui')
class TestQuantitySelectionColumnTests(unittest.TestCase):
    def test__update_cell_based_on_data_clears_cell_when_row_has_children(self):
        column, tree_model, tree_iter = self._setup_column(1, False)
        tree_model.add_map(tree_iter, self._create_store_map(1, False, 15, 2))
        column.quantity_renderer.set_property("text", "22")
        column._update_cell_based_on_data(None, column.quantity_renderer, tree_model, tree_iter)
        self.assertEqual("", column.quantity_renderer.get_property("text"))
    def test_update_cell_based_on_data_does_not_clear_cell_when_row_has_no_children(self):


Answer:         column, tree_model, tree_iter = self._setup_column(1, False)