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


from __future__ import division
from WorkUtils.UtilsLog import UtilsLog
from WorkUtils.UtilsDataBase import UtilsDataBase
from WorkUtils.UtilsResponse import UtilsResponse
from WorkApi.API.HostPrototype.hostPrototype_create import HostPrototypeCreate
from WorkApi.API.HostPrototype.hostPrototype_get import HostPrototypeGet

from WorkData.Zabbix.hosts import DataHosts

from WorkCase import CaseBase

import allure


# allure.label("")


@allure.feature("测试模块：hostprototype.get")
class TestHostPrototypeGet(object):
    log = UtilsLog()
    env = CaseBase().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"]
    base_name = "SS测试主机原型"
    base_ip = "10.0.0.28"
    base_hostid = 10266
    base_dns = "sanshi.zmops.cn"
    base_port = "127"
    base_hosts = ["{#VM.NAME}", "{#HM.NAME}", "{#VM.UUID}", "{#HV.UUID}"]
    base_ruleids = [10009, 10010]
    groupLinks_groupid = 46

    new_name = "修改SS测试主机原型"

    @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_name(session=session, name=cls.base_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)
        DataHosts().delete_name(session=session, name=cls.new_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("调用接口：hostprototype.create")
    def hostprototype_create(self, host=None, name=None, ruleid=None, templateids=None, groupLinks_groupid=None, groupPrototypes_name=None):
        api = HostPrototypeCreate(_host=self.host)
        api.host = host
        api.name = name
        api.ruleid = ruleid
        api.templateids = templateids
        api.groupLinks_groupid = groupLinks_groupid
        api.groupPrototypes_name = groupPrototypes_name
        api.get_response()
        return api.response

    @allure.step("创建测试数据")
    def case_create(self, host, group_prototypes_name, ruleid):
        response = self.hostprototype_create(host=host, name=self.base_name, ruleid=ruleid, groupLinks_groupid=[self.groupLinks_groupid],
                                             groupPrototypes_name=[group_prototypes_name])
        self.check_code(response=response, code=0)
        hostid = UtilsResponse().get_result(response=response)["hostids"][0]
        return hostid

    @allure.step("调用接口：hostprototype.get")
    def hostprototype_get(self, hostids=None, discoveryids=None, inherited=None, selectDiscoveryRule=None, selectGroupLinks=None,
                          selectGroupPrototypes=None, selectInventory=None, selectParentHost=None, selectTemplates=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 = HostPrototypeGet(_host=self.host)
        api.hostids = hostids
        api.discoveryids = discoveryids
        api.inherited = inherited
        api.selectDiscoveryRule = selectDiscoveryRule
        api.selectGroupLinks = selectGroupLinks
        api.selectGroupPrototypes = selectGroupPrototypes
        api.selectInventory = selectInventory
        api.selectParentHost = selectParentHost
        api.selectTemplates = selectTemplates
        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("查询表：hosts")
    def select_hosts(self, hostid=None):
        session = self.db_session()
        sql = DataHosts().select_all_from_allKeys(session=session, hostid=hostid)
        return sql

    @allure.step("断言返回结果：校验排序")
    def check_sortfield(self, response, possible):
        result = UtilsResponse().get_result(response=response)
        UtilsResponse().check_sort(_list=result, key="hostid", 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_sql(self, response, hostid):
        sql = self.select_hosts(hostid=hostid)
        result = UtilsResponse().get_result(response=response)
        for x, y in enumerate(sql):
            assert y.host in UtilsResponse().get_values_from_key(_dict=result, key="host")
            assert y.name in UtilsResponse().get_values_from_key(_dict=result, key="name")
            assert y.status in UtilsResponse().get_values_from_key(_dict=result, key="status")
        for x, y in enumerate(result):
            assert y["host"] in UtilsResponse().get_values_from_sql(_sql=sql, key="host")
            assert y["name"] in UtilsResponse().get_values_from_sql(_sql=sql, key="name")
            assert y["status"] in UtilsResponse().get_values_from_sql(_sql=sql, key="status")

    @allure.title("hostprototype.get：无参数调用")
    @allure.story("查询主机原型：无参数调用")
    @allure.severity("blocker")
    def test_case_01(self):
        response = self.hostprototype_get()
        self.check_code(response=response, code=0)

    @allure.title("hostprototype.get：countOutput=true")
    @allure.story("查询主机原型：countOutput=true")
    def test_case_02(self):
        response = self.hostprototype_get(countOutput="true")
        self.check_code(response=response, code=0)

    @allure.title("hostprototype.get：hostids=特定IDs")
    @allure.story("查询主机原型：hostids=特定IDs")
    def test_case_03(self):
        response = self.hostprototype_get(hostids=[self.base_hostid])
        self.check_code(response=response, code=0)

    @allure.title("hostprototype.get：output=[name]")
    @allure.story("查询主机原型：output=[name]")
    def test_case_04(self):
        response = self.hostprototype_get(output=["name"])
        self.check_code(response=response, code=0)

    @allure.title("hostprototype.get：hostids=特定IDs, output=[ip, port, type, main, useip, bulk]")
    @allure.story("查询主机原型：hostids=特定IDs, output=[ip, port, type, main, useip, bulk]")
    def test_case_05(self):
        host = self.base_hosts[0]
        group_prototypes_name = self.base_hosts[0]
        ruleid = self.base_ruleids[0]
        hostid = self.case_create(host=host, group_prototypes_name=group_prototypes_name, ruleid=ruleid)

        response = self.hostprototype_get(hostids=[hostid], output=["host", "name", "status"])
        self.check_code(response=response, code=0)
        self.check_sql(response=response, hostid=hostid)

    @allure.title("hostprototype.get：limit=1")
    @allure.story("查询主机原型：limit=1")
    def test_case_06(self):
        host = self.base_hosts[1]
        group_prototypes_name = self.base_hosts[1]
        ruleid = self.base_ruleids[1]
        self.case_create(host=host, group_prototypes_name=group_prototypes_name, ruleid=ruleid)

        response = self.hostprototype_get(limit=1)
        self.check_code(response=response, code=0)
        result = UtilsResponse().get_result(response=response)
        assert len(result) == 1

    @allure.title("hostprototype.get：sortfield=hostid")
    @allure.story("查询主机原型：sortfield=hostid")
    def test_case_07(self):
        response = self.hostprototype_get(sortfield=["hostid"])
        self.check_code(response=response, code=0)
        self.check_sortfield(response=response, possible=True)

    @allure.title("hostprototype.get：sortfield=hostid, sortorder=ASC")
    @allure.story("查询主机原型：sortfield=hostid, sortorder=ASC")
    def test_case_8(self):
        response = self.hostprototype_get(sortfield=["hostid"], sortorder=["ASC"])
        self.check_code(response=response, code=0)
        self.check_sortfield(response=response, possible="ASC")

    @allure.title("hostprototype.get：sortfield=hostid, sortorder=DESC")
    @allure.story("查询主机原型：sortfield=hostid, sortorder=DESC")
    def test_case_9(self):
        response = self.hostprototype_get(sortfield=["hostid"], 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 = TestHostPrototypeGet()
    # a.setup_class()
    # a.test_case_07()
