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


from __future__ import division

from WorkApi.APP.Api.api_login import ApiLogin
from WorkApi.APP.Device.device_create import DeviceCreate
from WorkCase import CaseBase
from WorkCase.APP import AppBase
from WorkData.Zabbix.problem import DataProblem as ZabbixDataProblem
from WorkData.Zabbix.events import DataEvents
from WorkUtils.UtilsLog import UtilsLog
from WorkUtils.UtilsResponse import UtilsResponse
from WorkUtils.UtilsDataBase import UtilsDataBase

from WorkApi.APP.Experience.experience_create import ExperienceCreate
from WorkApi.APP.Experience.experience_update import ExperienceUpdate

from WorkData.Argus.experience import DataExperience
from WorkData.Argus.experience_alarm_rule import DataExperienceAlarmRule
from WorkData.Argus.experience_businesses import DataExperienceBusinesses
from WorkData.Argus.experience_hosts import DataExperienceHosts
from WorkData.Argus.experience_hosts_type import DataExperienceHostsType
from WorkData.Argus.experience_tag import DataExperienceTag
from WorkData.Argus.experience_items import DataExperienceItems
from WorkData.Argus.experience_ips import DataExperienceIps
from WorkData.Argus.experience_problem import DataExperienceProblem

from WorkData.Argus.alarm_rule import DataAlarmRule
from WorkData.Argus.businesses import DataBusinesses
from WorkData.Argus.hosts import DataHosts
from WorkData.Argus.hosts_items import DataHostsItems
from WorkData.Argus.problem import DataProblem
from WorkData.Argus.tag import DataTag

import allure


@allure.feature("测试模块：experience.update")
class TestExperienceUpdate(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"]

    host_zabbix = env["host_zabbix"]
    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_port = 161
    base_title = "SS测试经验标题"
    base_content = "SS测试经验内容"
    base_description = "SS测试经验描述"

    base_name = "SS 自动化专用 经验手册相关"
    base_update_name = "SS 自动化专用 经验手册相关 修改"
    base_eventid = 91000000
    base_update_eventid = 91000010

    session_zabbix = UtilsDataBase().conn_mysql(db_url=db_url_zabbix, db_port=db_port_zabbix, db_base=db_base_zabbix,
                                                db_user=db_user_zabbix, db_pw=db_pw_zabbix)
    session = UtilsDataBase().conn_mysql(db_url=db_url, db_port=db_port, db_base=db_base, db_user=db_user, db_pw=db_pw)

    @classmethod
    def setup_class(cls):
        cls.log.debug("开始执行测试套件.......")

        DataAlarmRule().delete_like_name(session=cls.session, name=cls.base_name)
        DataBusinesses().delete_like_name(session=cls.session, name=cls.base_name)

        sql = DataHosts().select_all_like_host_name(session=cls.session, host_name=cls.base_name)
        for x, y in enumerate(sql):
            DataHostsItems().delete_host_id(session=cls.session, host_id=y.hostid)
        DataProblem().delete_like_eventid(session=cls.session, eventid=cls.base_eventid)
        DataHosts().delete_like_host_name(session=cls.session, host_name=cls.base_name)
        DataTag().delete_like_tag(session=cls.session, tag=cls.base_name)
        DataExperience().delete_like_title(session=cls.session, title=cls.base_title)

        ZabbixDataProblem().delete_like_eventid(session=cls.session_zabbix, eventid=cls.base_eventid)
        DataEvents().delete_like_eventid(session=cls.session_zabbix, eventid=cls.base_eventid)

    @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("查询表：experience")
    def select_experience(self, experienceid=None, title=None, content=None):
        session = self.db_session()
        sql = DataExperience().select_all_from_allKeys(session=session, experienceid=experienceid, title=title, content=content)
        return sql

    @allure.step("查询表：experience_alarm_rule")
    def select_experience_alarm_rule(self, experienceid=None):
        session = self.db_session()
        sql = DataExperienceAlarmRule().select_all_from_allKeys(session=session, experienceid=experienceid)
        return sql

    @allure.step("查询表：experience_businesses")
    def select_experience_businesses(self, experienceid=None):
        session = self.db_session()
        sql = DataExperienceBusinesses().select_all_from_allKeys(session=session, experienceid=experienceid)
        return sql

    @allure.step("查询表：experience_hosts")
    def select_experience_hosts(self, experienceid=None):
        session = self.db_session()
        sql = DataExperienceHosts().select_all_from_allKeys(session=session, experienceid=experienceid)
        return sql

    @allure.step("查询表：experience_hosts_type")
    def select_experience_hosts_type(self, experienceid=None):
        session = self.db_session()
        sql = DataExperienceHostsType().select_all_from_allKeys(session=session, experienceid=experienceid)
        return sql

    @allure.step("查询表：experience_tag")
    def select_experience_tag(self, experienceid=None):
        session = self.db_session()
        sql = DataExperienceTag().select_all_from_allKeys(session=session, experienceid=experienceid)
        return sql

    @allure.step("查询表：tag")
    def select_tag(self, tag=None):
        session = self.db_session()
        sql = DataTag().select_all_from_allKeys(session=session, tag=tag)
        return sql

    @allure.step("查询表：experience_items")
    def select_experience_items(self, experienceid=None):
        session = self.db_session()
        sql = DataExperienceItems().select_all_from_allKeys(session=session, experienceid=experienceid)
        return sql

    @allure.step("查询表：experience_ips")
    def select_experience_ips(self, experienceid=None):
        session = self.db_session()
        sql = DataExperienceIps().select_all_from_allKeys(session=session, experienceid=experienceid)
        return sql

    @allure.step("查询表：experience_problem")
    def select_experience_problem(self, experienceid=None):
        session = self.db_session()
        sql = DataExperienceProblem().select_all_from_allKeys(session=session, experienceid=experienceid)
        return sql

    @allure.step("创建测试数据")
    def case_create(self, num):
        self.name = self.base_name + num
        self.eventid = self.base_eventid + int(num)

        session = self.db_session()
        self.alarm_ruleid = DataAlarmRule().insert_one(session=session, name=self.name, status=1, severity=1,
                                                       manual_close=0, enable_time_default=1, create_time=1,
                                                       description="description")
        session = self.db_session()
        self.businessid = DataBusinesses().insert_one(session=session, name=self.name, _type=1)

        self.hostid = self.app.case_create_host(
            name=self.name, host_type=self.base_type_snmp, iplist=self.base_ip, port=self.base_port,
            businessIds=[self.base_business_id_1, self.base_business_id_2]
        )

        sql = self.select_hosts_items(host_id=self.hostid)
        itemids = []
        for x, y in enumerate(sql):
            itemids.append(y.id)
        self.itemid = itemids[0]
        session = self.db_session()
        DataProblem().insert_one(session=session, eventid=self.eventid, source=0, _object=0, objectid=0, clock=0, ns=0,
                                 r_clock=0, r_ns=0, acknowledged=0, acknowledged_time=0, severity=0,
                                 status=0, hostid=self.hostid, name=self.name)

    @allure.step("创建测试数据")
    def case_create_update(self, num):
        self.update_name = self.base_name + num + "修改"
        self.update_eventid = self.base_update_eventid + int(num)

        session = self.db_session()
        self.update_alarm_ruleid = DataAlarmRule().insert_one(session=session, name=self.name, status=1, severity=1,
                                                              manual_close=0, enable_time_default=1, create_time=1,
                                                              description="description")
        session = self.db_session()
        self.update_businessid = DataBusinesses().insert_one(session=session, name=self.name, _type=1)

        self.update_hostid = self.app.case_create_host(
            name=self.name, host_type=self.base_type_snmp, iplist=self.base_ip, port=self.base_port,
            businessIds=[self.base_business_id_1, self.base_business_id_2]
        )

        sql = self.select_hosts_items(host_id=self.hostid)
        itemids = []
        for x, y in enumerate(sql):
            itemids.append(y.id)
        self.update_itemid = itemids[0]
        session = self.db_session()
        DataProblem().insert_one(session=session, eventid=self.update_eventid, source=0, _object=0, objectid=0, clock=0, ns=0,
                                 r_clock=0, r_ns=0, acknowledged=0, acknowledged_time=0, severity=0,
                                 status=0, hostid=self.hostid, name=self.update_name)

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

    @allure.step("校验数据")
    def check_select(self, response):
        data = UtilsResponse().get_data(response=response)
        sql = self.select_experience(experienceid=data)
        for x, y in enumerate(sql):
            assert y.title == self.update_title
            assert y.content == self.update_content

            # 校验第一个表
            sql = self.select_experience_alarm_rule(experienceid=self.experienceid)
            assert sql != []
            for q, w in enumerate(sql):
                assert w.alarm_ruleid == self.update_alarm_ruleid
            # 校验第二个表
            sql = self.select_experience_businesses(experienceid=self.experienceid)
            for q, w in enumerate(sql):
                assert w.businessid == self.update_businessid
            # 校验第三个表
            sql = self.select_experience_hosts(experienceid=self.experienceid)
            assert sql != []
            for q, w in enumerate(sql):
                assert w.hostid == self.update_hostid
            # 校验第四个表
            sql = self.select_experience_hosts_type(experienceid=self.experienceid)
            assert sql != []
            for q, w in enumerate(sql):
                assert w.hosts_type == self.base_type_snmp
            # 校验第五个表
            sql = self.select_experience_ips(experienceid=self.experienceid)
            assert sql != []
            for q, w in enumerate(sql):
                assert w.hostid == self.update_hostid
            # 校验第六个表
            sql = self.select_experience_items(experienceid=self.experienceid)
            assert sql != []
            for q, w in enumerate(sql):
                assert w.itemid == self.update_itemid
            # 校验第七个表
            sql = self.select_experience_problem(experienceid=self.experienceid)
            assert sql != []
            for q, w in enumerate(sql):
                assert w.problemid == self.update_eventid
            # 校验第八个表
            sql = self.select_tag(tag=self.base_update_name)
            assert sql != []
            tagids = []
            for q, w in enumerate(sql):
                assert w.tag == self.base_update_name
                assert q == 0
                tagids.append(w.tagid)

            sql = self.select_experience_tag(experienceid=self.experienceid)
            assert sql != []
            for q, w in enumerate(sql):
                assert w.tagid == tagids[0]

    @allure.title("experience.update：token未传")
    @allure.story("更新经验手册：token未传")
    @allure.severity("blocker")
    def test_case_01(self):
        response = self.app.experience_update()
        self.app.check_code(response=response, code=2001)
        self.app.check_msg(response=response, msg="token不存在")

    @allure.title("experience.update：token的用户已删除")
    @allure.story("更新经验手册：token的用户已删除")
    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.experience_update(token=self.token)
        self.app.check_code(response=response, code=2004)
        self.app.check_msg(response=response, msg="用户不存在")

    @allure.title("experience.update：token的用户已禁用")
    @allure.story("更新经验手册：token的用户已禁用")
    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.experience_update(token=self.token)
        self.app.check_code(response=response, code=2003)
        self.app.check_msg(response=response, msg="账户已被禁用")

    @allure.title("experience.update：更新所有字段")
    @allure.story("更新经验手册：更新所有字段")
    def test_case_04(self):
        title = self.base_title + "04"
        content = self.base_content + "04"
        description = self.base_description + "04"

        self.update_title = title + "修改"
        self.update_content = content + "修改"
        self.update_description = description + "修改"
        self.case_create(num="04")
        self.case_create_update(num="041")
        self.experienceid = self.app.case_create_experience(title=title, content=content, description=description, host_types=[self.base_type_agent])
        response = self.app.experience_update(token=self.token, _id=self.experienceid, title=self.update_title, content=self.update_content,
                                              description=self.update_description, businessids=[self.update_businessid], hostTypes=[self.base_type_snmp],
                                              hostids=[self.update_hostid], itemids=[self.update_itemid], manageIpList=[self.update_hostid],
                                              alarmRuleids=[self.update_alarm_ruleid], tagNameList=[self.base_update_name],
                                              problemidList=[self.update_eventid])
        self.app.check_code(response=response, code=0)
        self.check_select(response=response)


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 = TestExperienceUpdate()
    # a.setup_class()
    # a.test_case_04()
