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


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.Argus.members import DataMembers
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_get import ExperienceGet

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.get")
class TestExperienceGet(object):
    log = UtilsLog()
    env = CaseBase().app_environment
    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"]

    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_eventid = 91000000

    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_name(session=cls.session, name=cls.base_name)
        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)

    @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("查询表：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 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)
        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 check_select(self, response):
        data = UtilsResponse().get_data(response=response)
        ids = []
        for x, y in enumerate(data["list"]):
            ids.append(y["id"])
            sql = self.select_experience(experienceid=y["id"])
            for q, w in enumerate(sql):
                assert y["title"] == w.title
                assert y["content"] == w.content
            if y["id"] == self.experienceid:
                for e, d in enumerate(y["businessList"]):
                    assert d["experienceid"] == self.experienceid
                    assert d["businessid"] == self.businessid
                    assert d["name"] == self.name
                for e, d in enumerate(y["hostsTypeList"]):
                    assert d["typeId"] == self.base_type_snmp
                for e, d in enumerate(y["hostsList"]):
                    assert d["experienceid"] == self.experienceid
                    assert d["hostid"] == self.hostid
                    assert d["host_name"] == self.name
                for e, d in enumerate(y["itemList"]):
                    assert d["itemId"] == self.itemid
                for e, d in enumerate(y["manageIpList"]):
                    assert d["experienceid"] == self.experienceid
                    assert d["hostid"] == self.hostid
                for e, d in enumerate(y["problemDescriptionList"]):
                    assert d["problemId"] == self.eventid
                for e, d in enumerate(y["alarmRuleList"]):
                    assert d["experienceid"] == self.experienceid
                    assert d["alarm_ruleid"] == self.alarm_ruleid
                    assert d["name"] == self.name
                for e, d in enumerate(y["tagList"]):
                    assert d["experienceid"] == self.experienceid
                    assert d["tag"] == self.base_name

    @allure.title("experience.get：token未传")
    @allure.story("查询经验手册：token未传")
    @allure.severity("blocker")
    def test_case_01(self):
        response = self.app.experience_get()
        self.app.check_code(response=response, code=2001)
        self.app.check_msg(response=response, msg="无token，请重新登录")

    @allure.title("experience.get：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_get(token=self.token)
        self.app.check_code(response=response, code=2004)
        self.app.check_msg(response=response, msg="用户不存在")

    @allure.title("experience.get：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_get(token=self.token)
        self.app.check_code(response=response, code=2003)
        self.app.check_msg(response=response, msg="账户已被禁用")

    @allure.title("experience.get：无参数调用")
    @allure.story("查询经验手册：无参数调用")
    def test_case_04(self):
        response = self.app.experience_get(token=self.token)
        self.app.check_code(response=response, code=0)

    @allure.title("experience.get：hostType查询")
    @allure.story("查询经验手册：hostType查询")
    def test_case_05(self):
        title = self.base_title + "05"
        content = self.base_content + "05"
        description = self.base_description + "05"
        self.case_create(num="05")
        self.app.experience_create(token=self.token, title=title, content=content, hostTypes=[self.base_type_snmp],
                                   alarmRuleids=[self.alarm_ruleid], businessids=[self.businessid], hostids=[self.hostid],
                                   manageIpList=[self.hostid], itemids=[self.itemid], problemidList=[self.eventid],
                                   tagNameList=[self.base_name], description=description)

        response = self.app.experience_get(token=self.token, hostType=self.base_type_snmp)
        self.app.check_code(response=response, code=0)
        self.app.check_keyValue(_json=UtilsResponse().get_data_list(response=response), _key="hostsTypeList",
                                _value=[{"typeId": self.base_type_snmp}])

    @allure.title("experience.get：hostName查询")
    @allure.story("查询经验手册：hostName查询")
    def test_case_06(self):
        title = self.base_title + "06"
        content = self.base_content + "06"
        description = self.base_description + "06"
        self.case_create(num="06")
        self.app.experience_create(token=self.token, title=title, content=content, hostTypes=[self.base_type_snmp],
                                   alarmRuleids=[self.alarm_ruleid], businessids=[self.businessid], hostids=[self.hostid],
                                   manageIpList=[self.hostid], itemids=[self.itemid], problemidList=[self.eventid],
                                   tagNameList=[self.base_name], description=description)

        response = self.app.experience_get(token=self.token, hostName=self.name)
        self.app.check_code(response=response, code=0)
        self.app.check_keyValue(_json=UtilsResponse().get_data_list(response=response), _key="hostsList", _value=self.base_type_snmp)

    @allure.title("experience.get：manageLevel查询")
    @allure.story("查询经验手册：manageLevel查询")
    def test_case_07(self):
        title = self.base_title + "07"
        content = self.base_content + "07"
        description = self.base_description + "07"
        self.case_create(num="07")
        self.app.experience_create(token=self.token, title=title, content=content, hostTypes=[self.base_type_snmp],
                                   alarmRuleids=[self.alarm_ruleid], businessids=[self.businessid], hostids=[self.hostid],
                                   manageIpList=[self.hostid], itemids=[self.itemid], problemidList=[self.eventid],
                                   tagNameList=[self.base_name], description=description)

        response = self.app.experience_get(token=self.token, manageLevel=1)
        self.app.check_code(response=response, code=0)
        self.app.check_keyValue(_json=UtilsResponse().get_data_list(response=response), _key="hostsList", _value=self.base_type_snmp)

    @allure.title("experience.get：manageIp查询")
    @allure.story("查询经验手册：manageIp查询")
    def test_case_08(self):
        self.get_base_token()
        self.case_create(num="08")
        response = self.experience_get(token=self.token, manageIp=self.base_ip)
        self.check_code(response=response, code=0)
        self.check_select(response=response)

    @allure.title("experience.get：businessid查询")
    @allure.story("查询经验手册：businessid查询")
    def test_case_09(self):
        self.get_base_token()
        self.case_create(num="09")
        response = self.experience_get(token=self.token, businessid=self.businessid)
        self.check_code(response=response, code=0)
        self.check_select(response=response)

    @allure.title("experience.get：alarmRuleid查询")
    @allure.story("查询经验手册：alarmRuleid查询")
    def test_case_10(self):
        self.get_base_token()
        self.case_create(num="10")
        response = self.experience_get(token=self.token, alarmRuleid=self.alarm_ruleid)
        self.check_code(response=response, code=0)
        self.check_select(response=response)

    @allure.title("experience.get：itemid查询")
    @allure.story("查询经验手册：itemid查询")
    def test_case_11(self):
        self.get_base_token()
        self.case_create(num="11")
        response = self.experience_get(token=self.token, itemid=self.itemid)
        self.check_code(response=response, code=0)
        self.check_select(response=response)

    @allure.title("experience.get：title查询")
    @allure.story("查询经验手册：title查询")
    def test_case_12(self):
        self.get_base_token()
        self.case_create(num="12")
        response = self.experience_get(token=self.token, title=self.title)
        self.check_code(response=response, code=0)
        self.check_select(response=response)

    @allure.title("experience.get：tagName查询")
    @allure.story("查询经验手册：tagName查询")
    def test_case_13(self):
        self.get_base_token()
        self.case_create(num="13")
        response = self.experience_get(token=self.token, tagName=self.base_name)
        self.check_code(response=response, code=0)
        self.check_select(response=response)

    @allure.title("experience.get：description查询")
    @allure.story("查询经验手册：description查询")
    def test_case_14(self):
        self.get_base_token()
        self.case_create(num="14")
        response = self.experience_get(token=self.token, description=self.description)
        self.check_code(response=response, code=0)
        self.check_select(response=response)

    @allure.title("experience.get：所有字段查询")
    @allure.story("查询经验手册：所有字段查询")
    def test_case_15(self):
        self.get_base_token()
        self.case_create(num="15")
        response = self.experience_get(token=self.token, hostType=self.base_type_snmp, manageLevel=1,
                                       manageIp=self.base_ip, businessid=self.businessid, alarmRuleid=self.alarm_ruleid,
                                       itemid=self.itemid, title=self.title, tagName=self.base_name,
                                       description=self.description)
        self.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 = TestExperienceGet()
    a.setup_class()
    a.setup_method()
    a.test_case_06()
