# -*- coding: utf-8 -*-
# 测试用例
# 作者: 陈磊
# 时间: 2019-11-28


from __future__ import division

from WorkApi.APP.Device.device_create import DeviceCreate
from WorkCase import CaseBase
from WorkCase.APP import AppBase
from WorkData.Zabbix.triggers import DataTriggers
from WorkUtils.UtilsLog import UtilsLog
from WorkUtils.UtilsDataBase import UtilsDataBase
from WorkUtils.UtilsResponse import UtilsResponse

from WorkApi.APP.Api.api_login import ApiLogin
from WorkApi.APP.Rule.rule_create import RuleCreate
from WorkApi.APP.Rule.rule_delete import RuleDelete

from WorkData.Argus.members import DataMembers
from WorkData.Argus.hosts_items import DataHostsItems
from WorkData.Argus.alarm_rule import DataAlarmRule
from WorkData.Argus.hosts import DataHosts

import allure


@allure.feature("测试模块：rule.delete")
class TestRuleDelete(object):
    log = UtilsLog()
    env = CaseBase().environment_test
    host = env["host"]
    db_url = env["db_url"]
    db_port = env["db_port"]
    db_user = env["db_user"]
    db_pw = env["db_pw"]
    db_base = env["db_base"]

    db_url_zabbix = env["db_url_zabbix"]
    db_port_zabbix = env["db_port_zabbix"]
    db_user_zabbix = env["db_user_zabbix"]
    db_pw_zabbix = env["db_pw_zabbix"]
    db_base_zabbix = env["db_base_zabbix"]

    login_name = "SS测试用户名"
    base_id = 10
    base_password = "123456"

    base_type_agent = 126
    base_type_snmp = 127
    base_business_id_1 = 12
    base_business_id_2 = 13
    base_ip = "172.16.3.170"
    base_dns = "sanshi.zmops.com"
    base_port = 161

    base_host_name = "SS 自动化专用"
    base_name = "SS 自动化告警规则"
    base_template_id_agent = 10001
    base_template_id_snmp = 10186

    @classmethod
    def setup_class(cls):
        cls.log.debug("开始执行测试套件.......")
        session = UtilsDataBase().conn_mysql(db_url=cls.db_url, db_port=cls.db_port, db_base=cls.db_base, db_user=cls.db_user, db_pw=cls.db_pw)
        DataHosts().delete_like_host_name(session=session, host_name=cls.base_host_name)

        session = UtilsDataBase().conn_mysql(db_url=cls.db_url, db_port=cls.db_port, db_base=cls.db_base, db_user=cls.db_user, db_pw=cls.db_pw)
        DataAlarmRule().delete_like_name(session=session, name=cls.base_name)

    @classmethod
    def teardown_class(cls):
        cls.log.debug("结束执行测试套件.......")

    def setup_method(self):
        self.log.debug("测试用例执行开始...")

        self.app = AppBase(host=self.host)
        self.app.update_members_del_flag(session=self.db_session(), members_id=self.base_id, value=CaseBase().del_flag["OFF"])
        self.app.update_members_status(session=self.db_session(), members_id=self.base_id, value=CaseBase().status["ON"])
        self.token = self.app.get_base_token(login_name=self.login_name, base_password=self.base_password)

    def teardown_method(self):
        self.log.debug("测试用例执行结束...")

        self.app.update_members_del_flag(session=self.db_session(), members_id=self.base_id, value=CaseBase().del_flag["OFF"])
        self.app.update_members_status(session=self.db_session(), members_id=self.base_id, value=CaseBase().status["ON"])

    @allure.step("连接数据库：Argus")
    def db_session(self):
        session = UtilsDataBase().conn_mysql(db_url=self.db_url, db_port=self.db_port, db_base=self.db_base, db_user=self.db_user, db_pw=self.db_pw)
        return session

    @allure.step("连接数据库：Zabbix")
    def db_session_zabbix(self):
        session = UtilsDataBase().conn_mysql(db_url=self.db_url_zabbix, db_port=self.db_port_zabbix, db_base=self.db_base_zabbix,
                                             db_user=self.db_user_zabbix, db_pw=self.db_pw_zabbix)
        return session

    @allure.step("查询表：alarm_rule")
    def select_alarm_rule(self, alarm_ruleid=None, name=None, triggerid=None):
        session = self.db_session()
        sql = DataAlarmRule().select_all_from_allKeys(session=session, alarm_ruleid=alarm_ruleid, name=name, triggerid=triggerid)
        return sql

    @allure.step("查询表：triggers")
    def select_triggers(self, description=None, triggerid=None):
        session = self.db_session_zabbix()
        sql = DataTriggers().select_all_from_allKeys(session=session, triggerid=triggerid, description=description)
        return sql

    @allure.step("查询表：hosts")
    def select_hosts(self, hostid=None, host_name=None, available=None, monitor_status=None):
        session = self.db_session()
        sql = DataHosts().select_all_from_allKeys(session=session, hostid=hostid, host_name=host_name, available=available, monitor_status=monitor_status)
        return sql

    @allure.step("查询表：hosts_items")
    def select_hosts_items(self, _id=None, host_id=None, name=None, key_=None):
        session = self.db_session()
        sql = DataHostsItems().select_all_from_allKeys(session=session, _id=_id, host_id=host_id, name=name, key_=key_)
        return sql

    @allure.step("校验查询结果")
    def check_select(self, alarm_ruleid, trigger_id):
        sql = self.select_alarm_rule(alarm_ruleid=alarm_ruleid)
        assert sql == []

        sql = self.select_triggers(triggerid=trigger_id)
        assert sql == []

    @allure.step("获取查询测试数据")
    def get_case(self, host_id, item_key):
        sql = self.select_hosts(hostid=host_id)
        assert sql != []
        for x, y in enumerate(sql):
            assert x == 0
            # 查询数据库得到zabbix的host_name
            self.host_name = y.asset_code

        sql = self.select_hosts_items(host_id=host_id, key_=item_key)
        assert sql != []
        for x, y in enumerate(sql):
            assert x == 0
            # 查询数据库得到item_name
            self.item_name = y.name
            self.item_id = y.id

    @allure.title("rule.delete：token未传")
    @allure.story("删除告警规则：token未传")
    @allure.severity("blocker")
    def test_case_01(self):
        response = self.app.rule_delete()
        self.app.check_code(response=response, code=2001)
        self.app.check_msg(response=response, msg="无token，请重新登录")

    @allure.title("rule.delete：token的用户已删除")
    @allure.story("删除告警规则：token的用户已删除")
    @allure.severity("blocker")
    def test_case_02(self):
        self.app.update_members_del_flag(session=self.db_session(), members_id=self.base_id, value=CaseBase().del_flag["ON"])
        response = self.app.rule_delete(token=self.token)
        self.app.check_code(response=response, code=2004)
        self.app.check_msg(response=response, msg="用户不存在")

    @allure.title("rule.delete：token的用户已禁用")
    @allure.story("删除告警规则：token的用户已禁用")
    @allure.severity("blocker")
    def test_case_03(self):
        self.app.update_members_status(session=self.db_session(), members_id=self.base_id, value=CaseBase().status["OFF"])
        response = self.app.rule_delete(token=self.token)
        self.app.check_code(response=response, code=2003)
        self.app.check_msg(response=response, msg="账户已被禁用")

    @allure.title("rule.delete：删除一个")
    @allure.story("删除告警规则：删除一个")
    @allure.severity("blocker")
    def test_case_04(self):
        host_name = self.base_host_name + "04"
        name = self.base_name + "04"
        host_id = self.app.case_create_host(name=host_name, host_type=self.base_type_agent,
                                            iplist=self.base_ip, port=self.base_port,
                                            businessIds=[self.base_business_id_1, self.base_business_id_2])

        item_key = "system.cpu.load[percpu,avg15]"
        self.get_case(host_id=host_id, item_key=item_key)

        rule_id = self.app.case_create_rule(name=name, status=CaseBase().status["ON"], host_id=host_id, host_name=self.host_name,
                                            item_key=item_key, itemid=self.item_id, severity=0)

        sql = self.select_alarm_rule(alarm_ruleid=rule_id)
        trigger_id = None
        for x, y in enumerate(sql):
            trigger_id = y.triggerid
        response = self.app.rule_delete(token=self.token, alarmRuleidList=[rule_id])
        self.app.check_code(response=response, code=0)
        self.check_select(alarm_ruleid=rule_id, trigger_id=trigger_id)

    @allure.title("rule.delete：删除多个")
    @allure.story("删除告警规则：删除多个")
    @allure.severity("blocker")
    def test_case_05(self):
        host_name = self.base_host_name + "05"
        name_1 = self.base_name + "051"
        name_2 = self.base_name + "052"
        name_3 = self.base_name + "053"
        host_id = self.app.case_create_host(name=host_name, host_type=self.base_type_agent,
                                            iplist=self.base_ip, port=self.base_port,
                                            businessIds=[self.base_business_id_1, self.base_business_id_2])

        item_key = "system.cpu.load[percpu,avg15]"
        self.get_case(host_id=host_id, item_key=item_key)

        rule_id_1 = self.app.case_create_rule(name=name_1, status=CaseBase().status["ON"], host_id=host_id, host_name=self.host_name,
                                              item_key=item_key, itemid=self.item_id, severity=0)
        rule_id_2 = self.app.case_create_rule(name=name_2, status=CaseBase().status["ON"], host_id=host_id, host_name=self.host_name,
                                              item_key=item_key, itemid=self.item_id, severity=0)
        rule_id_3 = self.app.case_create_rule(name=name_3, status=CaseBase().status["ON"], host_id=host_id, host_name=self.host_name,
                                              item_key=item_key, itemid=self.item_id, severity=0)

        sql = self.select_alarm_rule(alarm_ruleid=rule_id_1)
        trigger_id_1 = None
        for x, y in enumerate(sql):
            trigger_id_1 = y.triggerid

        sql = self.select_alarm_rule(alarm_ruleid=rule_id_2)
        trigger_id_2 = None
        for x, y in enumerate(sql):
            trigger_id_2 = y.triggerid

        sql = self.select_alarm_rule(alarm_ruleid=rule_id_3)
        trigger_id_3 = None
        for x, y in enumerate(sql):
            trigger_id_3 = y.triggerid

        response = self.app.rule_delete(token=self.token, alarmRuleidList=[rule_id_1, rule_id_2, rule_id_3])
        self.app.check_code(response=response, code=0)
        self.check_select(alarm_ruleid=rule_id_1, trigger_id=trigger_id_1)
        self.check_select(alarm_ruleid=rule_id_2, trigger_id=trigger_id_2)
        self.check_select(alarm_ruleid=rule_id_3, trigger_id=trigger_id_3)


if __name__ == "__main__":
    from WorkUtils.UtilsPyTest import UtilsPyTest
    from WorkUtils.UtilsCmd import UtilsCmd

    import os

    # 执行自动化测试用例
    case_info = os.path.split(__file__)
    case = UtilsCmd().pytest_cmd()
    r = UtilsPyTest(case=case, case_info=case_info)
    r.run_main()

    # a = TestRuleDelete()
    # a.setup_class()
    # a.test_case_05()
