class TestLoadCreate(unittest2.TestCase):
    def setUp(self):
        self.dmg = DataManager(alignak_webui.app.app)
        print('Data manager', self.dmg)

    def test_3_1_load(self):
        """ Datamanager load """
        print('test load as admin')

        # Initialize and load ... no reset
        assert self.dmg.user_login('admin', 'admin')
        result = self.dmg.load()
        print("Result:", result)
        # self.assertEqual(result, 0)  # No new objects created ...

        # Initialize and load ... with reset
        result = self.dmg.load(reset=True)
        print("Result:", result)
        # Must not have loaded any objects ... behavior changed, no more objects loading on login
        # self.assertEqual(result, 0)

    def test_3_3_get_errors(self):
        """ Datamanager objects get errors """
        print('test get errors')

        # Initialize and load ... no reset
        assert self.dmg.user_login('admin', 'admin')
        result = self.dmg.load()
        print("Result:", result)
        assert result == 0  # No new objects created ...

        # Get elements error
        item = self.dmg.get_user('unknown')
        assert not item
        item = self.dmg.get_userrestrictrole('unknown')
        assert not item
        item = self.dmg.get_realm('unknown')
        assert not item
        item = self.dmg.get_host('unknown')
        assert not item
        item = self.dmg.get_hostgroup('unknown')
        assert not item
        item = self.dmg.get_hostdependency('unknown')
        assert not item
        item = self.dmg.get_service('unknown')
        assert not item
        item = self.dmg.get_servicegroup('unknown')
        assert not item
        item = self.dmg.get_servicedependency('unknown')
        assert not item
        item = self.dmg.get_command('unknown')
        assert not item
        item = self.dmg.get_history('unknown')
        assert not item
        item = self.dmg.get_logcheckresult('unknown')
        assert not item
        item = self.dmg.get_timeperiod('unknown')
        assert not item
class TestRelations(unittest2.TestCase):
    def setUp(self):
        print("setting up ...")
        self.dmg = DataManager(alignak_webui.app.app)
        print('Data manager', self.dmg)

        # Initialize and do not load
        assert self.dmg.user_login('admin', 'admin', load=False)

    def tearDown(self):
        print("tearing down ...")
        # Logout
        self.dmg.reset(logout=True)

    def test_relation_host_command(self):
        """ Datamanager objects get - host/command relation """
        print("--- test Item")

        # Get main realm
        self.dmg.get_realm({'where': {'name': 'All'}})

        # Get main TP
        self.dmg.get_timeperiod({'where': {'name': '24x7'}})

        # Get host
        host = self.dmg.get_host({'where': {'name': 'localhost'}})

        print(host.__dict__)
        print(host.check_period)
        assert isinstance(host.check_command, Command)
        assert host.check_command

    def test_relation_host_service(self):
        """ Datamanager objects get - host/services relation """
        print("--- test Item")

        # Get main realm
        self.dmg.get_realm({'where': {'name': 'All'}})

        # Get main TP
        self.dmg.get_timeperiod({'where': {'name': '24x7'}})

        # Get host
        host = self.dmg.get_host({'where': {'name': 'localhost'}})
        print("Host: ", host.__dict__)

        # Get services of this host
        service = self.dmg.get_service(
            {'where': {
                'name': 'Shinken2-broker',
                'host_name': host.id
            }})
        print("Services: ", service)
    def test_recheck(self):
        """ Actions - recheck"""
        print('test recheck')

        print('get page /recheck/form/add')
        response = self.app.get('/recheck/form/add')
        response.mustcontain(
            '<form class="form-horizontal" data-item="recheck" data-action="add" '
        )

        # Current user is admin
        session = response.request.environ['beaker.session']
        assert 'current_user' in session and session['current_user']
        assert session['current_user'].get_username() == 'admin'

        # Data manager
        datamgr = DataManager(alignak_webui.app.app, session=session)

        # Get host, user and realm in the backend
        host = datamgr.get_host({'where': {'name': 'localhost'}})
        user = datamgr.get_user({'where': {'name': 'admin'}})

        # -------------------------------------------
        # Add a recheck
        # Missing livestate_id!
        data = {
            "host": host.id,
            "service": None,
            "sticky": True,
            "persistent": True,
            "notify": True,
            "comment": "User comment",
        }
        response = self.app.post('/recheck/add', data, status=400)

        # Recheck an host
        data = {
            "elements_type": 'host',
            "element_id": host.id,
            "comment": "User comment",
        }
        response = self.app.post('/recheck/add', data)
        assert response.json['status'] == "ok"
        assert response.json['message'] == "Check request sent for localhost. "

        # Recheck a service
        service = datamgr.get_service(
            {'where': {
                'host': host.id,
                'name': 'Cpu'
            }})
        data = {
            "elements_type": 'service',
            "element_id": service.id,
            "comment": "User comment",
        }
        response = self.app.post('/recheck/add', data)
        assert response.json['status'] == "ok"
        assert response.json[
            'message'] == "Check request sent for localhost/Cpu. "

        # Recheck several services
        service1 = datamgr.get_service(
            {'where': {
                'host': host.id,
                'name': 'Cpu'
            }})
        service2 = datamgr.get_service(
            {'where': {
                'host': host.id,
                'name': 'Memory'
            }})
        data = {
            "action": "add",
            "elements_type": 'service',
            "element_id": [service1.id, service2.id, 'test'],
            "comment": "User comment",
        }
        response = self.app.post('/recheck/add', data)
        assert response.json['status'] == "ok"
        assert response.json[
            'message'] == "Check request sent for localhost/Cpu. Check request sent for localhost/Memory. service element test does not exist. "
    def test_downtime(self):
        """ Actions - downtime"""
        print('test actions')

        print('get page /downtime/form/add')
        response = self.app.get('/downtime/form/add')
        response.mustcontain(
            '<form class="form-horizontal" data-item="downtime" data-action="add"'
        )

        # Current user is admin
        session = response.request.environ['beaker.session']
        assert 'current_user' in session and session['current_user']
        assert session['current_user'].get_username() == 'admin'

        # Data manager
        datamgr = DataManager(alignak_webui.app.app, session=session)

        # Get host, user and realm in the backend
        host = datamgr.get_host({'where': {'name': 'localhost'}})
        user = datamgr.get_user({'where': {'name': 'admin'}})

        now = datetime.utcnow()
        later = now + timedelta(days=2, hours=4, minutes=3, seconds=12)
        now = timegm(now.timetuple())
        later = timegm(later.timetuple())

        # -------------------------------------------
        # Add an downtime
        # Missing livestate_id!
        data = {
            "action": "add",
            "host": host.id,
            "service": None,
            "start_time": now,
            "end_time": later,
            "fixed": False,
            'duration': 86400,
            "comment": "User comment",
        }
        self.app.post('/downtime/add', data, status=400)

        # downtime an host
        data = {
            "action": "add",
            "element_id": host.id,
            "start_time": now,
            "end_time": later,
            "fixed": False,
            'duration': 86400,
            "comment": "User comment",
        }
        response = self.app.post('/downtime/add', data)
        assert response.json['status'] == "ok"
        assert response.json['message'] == \
                         "Downtime sent for localhost. "

        # downtime a service
        service = datamgr.get_service(
            {'where': {
                'host': host.id,
                'name': 'Cpu'
            }})
        data = {
            "action": "add",
            "elements_type": 'service',
            "element_id": service.id,
            "start_time": now,
            "end_time": later,
            "fixed": False,
            'duration': 86400,
            "comment": "User comment",
        }
        response = self.app.post('/downtime/add', data)
        assert response.json['status'] == "ok"
        assert response.json['message'] == \
                         "Downtime sent for localhost/Cpu. "

        # downtime several services
        service1 = datamgr.get_service(
            {'where': {
                'host': host.id,
                'name': 'Cpu'
            }})
        service2 = datamgr.get_service(
            {'where': {
                'host': host.id,
                'name': 'Memory'
            }})
        data = {
            "action": "add",
            "elements_type": 'service',
            "element_id": [service1.id, service2.id, 'test'],
            "start_time": now,
            "end_time": later,
            "fixed": False,
            'duration': 86400,
            "comment": "User comment",
        }
        response = self.app.post('/downtime/add', data)
        assert response.json['status'] == "ok"
        assert response.json['message'] == \
                         "Downtime sent for localhost/Cpu. " \
                         "Downtime sent for localhost/Memory. " \
                         "service element test does not exist. "
    def test_acknowledge(self):
        """ Actions - acknowledge"""
        print('test actions')

        print('get page /acknowledge/form/add')
        response = self.app.get('/acknowledge/form/add')
        response.mustcontain(
            '<form class="form-horizontal" data-item="acknowledge" data-action="add" '
        )

        # Get Data manager in the session
        session = response.request.environ['beaker.session']
        assert 'current_user' in session and session['current_user']
        assert session['current_user'].get_username() == 'admin'

        datamgr = DataManager(alignak_webui.app.app, session=session)

        # Get host and user in the backend
        host = datamgr.get_host({'where': {'name': 'localhost'}})
        user = datamgr.get_user({'where': {'name': 'admin'}})

        # -------------------------------------------
        # Add an acknowledge
        # Missing element_id!
        data = {
            "elements_type": "host",
            "element_id": host.id,
            "service": None,
            "sticky": True,
            "persistent": True,
            "notify": True,
            "comment": "User comment",
        }
        self.app.post('/acknowledge/add', data, status=400)

        # Acknowledge an host
        data = {
            "action": "add",
            "elements_type": 'host',  # Default value, can be omitted ...
            "element_id": host.id,
            "sticky": True,
            "persistent": True,
            "notify": True,
            "comment": "User comment",
        }
        response = self.app.post('/acknowledge/add', data)
        assert response.json['status'] == "ok"
        assert response.json['message'] == \
                         "Acknowledge sent for localhost. "

        # Acknowledge a service
        service = datamgr.get_service(
            {'where': {
                'host': host.id,
                'name': 'Cpu'
            }})
        data = {
            "action": "add",
            "elements_type": 'service',
            "element_id": service.id,
            "sticky": True,
            "persistent": True,
            "notify": True,
            "comment": "User comment",
        }
        response = self.app.post('/acknowledge/add', data)
        assert response.json['status'] == "ok"
        assert response.json['message'] == \
                         "Acknowledge sent for localhost/Cpu. "

        # Acknowledge several services
        service1 = datamgr.get_service(
            {'where': {
                'host': host.id,
                'name': 'Cpu'
            }})
        service2 = datamgr.get_service(
            {'where': {
                'host': host.id,
                'name': 'Memory'
            }})
        data = {
            "action": "add",
            "elements_type": 'service',
            "element_id": [service1.id, service2.id],
            "sticky": True,
            "persistent": True,
            "notify": True,
            "comment": "User comment",
        }
        response = self.app.post('/acknowledge/add', data)
        assert response.json['status'] == "ok"
        assert response.json['message'] == \
                         "Acknowledge sent for localhost/Cpu. " \
                         "Acknowledge sent for localhost/Memory. " \

        # Acknowledge several services
        service1 = datamgr.get_service(
            {'where': {
                'host': host.id,
                'name': 'Cpu'
            }})
        service2 = datamgr.get_service(
            {'where': {
                'host': host.id,
                'name': 'Memory'
            }})
        data = {
            "action": "add",
            "elements_type": 'service',
            "element_id": [service1.id, service2.id, 'test'],
            "sticky": True,
            "persistent": True,
            "notify": True,
            "comment": "User comment",
        }
        response = self.app.post('/acknowledge/add', data)
        assert response.json['status'] == "ok"
        assert response.json['message'] == \
                         "Acknowledge sent for localhost/Cpu. " \
                         "Acknowledge sent for localhost/Memory. " \
                         "service element test does not exist. "