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


from __future__ import division

from WorkCase import CaseBase
from WorkUtils.UtilsLog import UtilsLog
from WorkUtils.UtilsDataBase import UtilsDataBase
from WorkUtils.UtilsResponse import UtilsResponse
from WorkApi.API.DRule.drule_create import DRuleCreate
from WorkApi.API.DRule.drule_get import DRuleGet

from WorkData.Zabbix.drules import DataDrules
from WorkData.Zabbix.dchecks import DataDchecks

import allure


@allure.feature("测试模块：drule.get")
class TestDRuleGet(object):
    log = UtilsLog()
    env = CaseBase().environment_test
    host = env["host_zabbix"]
    db_url = env["db_url_zabbix"]
    db_port = env["db_port_zabbix"]
    db_user = env["db_user_zabbix"]
    db_pw = env["db_pw_zabbix"]
    db_base = env["db_base_zabbix"]
    base_name = "SS自动化测试发现规则"
    base_iprange = "192.168.0.1-254"
    base_delay = "1h"

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

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

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

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

    @allure.step("调用接口：drule.create")
    def drule_create(self, name=None, iprange=None, delay=None, nextcheck=None,
                     proxy_hostid=None, status=None, dchecks=None, dchecks_type=None, dchecks_name=None, dchecks_key_=None,
                     dchecks_snmp_community=None, dchecks_ports=None,
                     dchecks_host_source=None, dchecks_name_source=None):
        api = DRuleCreate(_host=self.host)
        api.iprange = iprange
        api.name = name
        api.delay = delay
        api.nextcheck = nextcheck
        api.proxy_hostid = proxy_hostid
        api.status = status
        api.dchecks = dchecks
        api.dchecks_type = dchecks_type
        api.dchecks_name = dchecks_name
        api.dchecks_key_ = dchecks_key_
        api.dchecks_snmp_community = dchecks_snmp_community
        api.dchecks_ports = dchecks_ports
        api.dchecks_host_source = dchecks_host_source
        api.dchecks_name_source = dchecks_name_source
        api.get_response()
        return api.response

    @allure.step("调用接口：drule.get")
    def drule_get(self, dhostids=None, druleids=None, dserviceids=None, limitSelects=None, countOutput=None,
                  editable=None, excludeSearch=None,
                  _filter=None, limit=None, output=None, preservekeys=None, search=None, searchByAny=None,
                  searchWildcardsEnabled=None, sortfield=None, sortorder=None, startSearch=None):
        api = DRuleGet(_host=self.host)
        api.dhostids = dhostids
        api.druleids = druleids
        api.dserviceids = dserviceids
        api.limitSelects = limitSelects
        api.countOutput = countOutput
        api.editable = editable
        api.excludeSearch = excludeSearch
        api.filter = _filter
        api.limit = limit
        api.output = output
        api.preservekeys = preservekeys
        api.search = search
        api.searchByAny = searchByAny
        api.searchWildcardsEnabled = searchWildcardsEnabled
        api.sortfield = sortfield
        api.sortorder = sortorder
        api.startSearch = startSearch
        api.get_response()
        return api.response

    @allure.step("连接数据库：zabbix")
    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("查询表：drules")
    def select_drules(self, druleid=None, name=None, iprange=None):
        session = self.db_session()
        sql = DataDrules().select_all_from_allKeys(session=session, druleid=druleid, name=name, iprange=iprange)
        return sql

    @allure.step("查询表：dchecks")
    def select_dchecks(self, druleid=None, dcheckid=None):
        session = self.db_session()
        sql = DataDchecks().select_all_from_allKeys(session=session, druleid=druleid, dcheckid=dcheckid)
        return sql

    @allure.step("校验查询结果")
    def check_select(self, response, dchecks_type, dchecks_key_, dchecks_snmp_community,
                     dchecks_ports, dchecks_host_source, dchecks_name_source):
        result = UtilsResponse().get_result(response=response)
        self.druleid = result["druleids"][0]
        sql = self.select_drules(druleid=self.druleid)
        for x, y in enumerate(sql):
            assert y.name == self.name
            assert y.iprange == self.base_iprange
            assert y.delay == self.base_delay
            assert x == 0

        sql = self.select_dchecks(druleid=self.druleid)
        for x, y in enumerate(sql):
            assert y.type == dchecks_type
            assert y.key_ == dchecks_key_
            assert y.snmp_community == dchecks_snmp_community
            assert int(y.ports) == dchecks_ports
            assert y.host_source == dchecks_host_source
            assert y.name_source == dchecks_name_source
            assert y.snmpv3_securitylevel == 0
            assert y.snmpv3_authprotocol == 0
            assert y.snmpv3_privprotocol == 0
            assert x == 0

    @allure.step("断言返回结果：校验排序")
    def check_sortfield(self, response, possible):
        result = UtilsResponse().get_result(response=response)
        UtilsResponse().check_sort(_list=result, key="druleid", possible=possible)

    @allure.step("断言返回结果：校验返回数据的数量")
    def check_num(self, response, num):
        result = UtilsResponse().get_result(response=response)
        assert len(result) == num

    @allure.step("断言返回结果")
    def check_code(self, response, code):
        _code = UtilsResponse().get_code(response=response)
        assert _code == code

    @allure.step("断言返回结果数据")
    def check_msg(self, response, msg):
        _msg = UtilsResponse().get_status(response=response)
        assert _msg == msg

    @allure.step("创建测试数据")
    def case_create(self, num):
        self.name = self.base_name + num
        response = self.drule_create(name=self.name, iprange=self.base_iprange, delay=self.base_delay,
                                     dchecks_type=[12], dchecks_ports=[0], dchecks_host_source=[1], dchecks_name_source=[0])
        result = UtilsResponse().get_result(response=response)
        self.druleid = result["druleids"][0]
        return self.druleid

    @allure.title("drule.get：无参数调用")
    @allure.story("查询发现规则：无参数调用")
    @allure.severity("blocker")
    def test_case_01(self):
        self.case_create(num="01")
        response = self.drule_get()

        self.check_code(response=response, code=0)

    @allure.title("drule.get：countOutput=true")
    @allure.story("查询发现规则：countOutput=true")
    def test_case_02(self):
        self.case_create(num="02")
        response = self.drule_get(countOutput="true")
        self.check_code(response=response, code=0)

    @allure.title("drule.get：druleids=特定IDs")
    @allure.story("查询发现规则：druleids=特定IDs")
    def test_case_03(self):
        self.case_create(num="03")
        response = self.drule_get(druleids=[self.druleid])
        self.check_code(response=response, code=0)

    @allure.title("hostinterface.get：druleids=特定IDs, output=[druleid, iprange, name, delay, status]")
    @allure.story("查询主机接口：druleids=特定IDs, output=[druleid, iprange, name, delay, status]")
    def test_case_04(self):
        self.case_create(num="04")
        response = self.drule_get(druleids=[self.druleid], output=["druleid", "iprange", "name", "delay", "status"])
        self.check_code(response=response, code=0)

    @allure.title("hostinterface.get：limit=1")
    @allure.story("查询主机接口：limit=1")
    def test_case_05(self):
        self.case_create(num="05")
        response = self.drule_get(limit=1)
        self.check_code(response=response, code=0)

    @allure.title("hostinterface.get：sortfield=druleid")
    @allure.story("查询主机接口：sortfield=druleid")
    def test_case_06(self):
        self.case_create(num="06")
        response = self.drule_get(sortfield=["druleid"])
        self.check_code(response=response, code=0)
        self.check_sortfield(response=response, possible=True)

    @allure.title("hostinterface.get：sortfield=druleid, sortorder=ASC")
    @allure.story("查询主机接口：sortfield=druleid, sortorder=ASC")
    def test_case_07(self):
        self.case_create(num="07")
        response = self.drule_get(sortfield=["druleid"], sortorder=["ASC"])
        self.check_code(response=response, code=0)
        self.check_sortfield(response=response, possible="ASC")

    @allure.title("hostinterface.get：sortfield=druleid, sortorder=DESC")
    @allure.story("查询主机接口：sortfield=druleid, sortorder=DESC")
    def test_case_08(self):
        self.case_create(num="08")
        response = self.drule_get(sortfield=["druleid"], sortorder=["DESC"])
        self.check_code(response=response, code=0)
        self.check_sortfield(response=response, possible="DESC")


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 = TestDRuleGet()
    # a.setup_class()
    # a.test_case_06()
