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


from __future__ import division
from WorkUtils.UtilsLog import UtilsLog
from WorkUtils.UtilsDataBase import UtilsDataBase
from WorkUtils.UtilsResponse import UtilsResponse
from WorkApi.API.Host.host_create import HostCreate
from WorkApi.API.Host.host_get import HostGet

from WorkData.Zabbix.hosts import DataHosts
from WorkData.Zabbix.items import DataItems

from WorkCase import CaseBase

import allure

# allure.label("")


@allure.feature("测试模块：host.get")
class TestHostGet(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_groupid = 99
    base_name = "SS TEST HOST GET"
    base_ip = "172.16.3.170"
    base_port = "161"
    base_description = "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)
        sql = DataHosts().select_like_name(session=session, name=cls.base_name)

        for x, y in enumerate(sql):
            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)
            DataItems().delete_hostid(session=session, hostid=y.hostid)

        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_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("调用接口：host.create")
    def host_create(self, host=None, name=None, description=None, groupids=None, interfaces=None, tags=None, templateids=None, macros=None,
                    inventory=None, status=None, inventory_mode=None):
        api = HostCreate(_host=self.host)
        api.host = host
        api.name = name
        api.description = description
        api.groupids = groupids
        api.interfaces = interfaces
        api.tags = tags
        api.templateids = templateids
        api.macros = macros
        api.inventory = inventory
        api.status = status
        api.inventory_mode = inventory_mode
        api.tls_connect = 1
        api.tls_accept = 1
        api.tls_psk_identity = ""
        api.tls_psk = ""
        api.get_response()
        return api.response

    @allure.step("调用接口：host.get")
    def host_get(self, groupids=None, hostids=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 = HostGet(_host=self.host)
        api.groupids = groupids
        api.hostids = hostids
        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):
        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 case_create(self, num):
        templateid = 10001

        host = self.base_name + num
        description = self.base_description + num
        interfaces = {
            "type": 2,
            "main": 1,
            "useip": 1,
            "ip": self.base_ip,
            "dns": "",
            "port": self.base_port,
            "bulk": 1
        }
        response = self.host_create(host=host, description=description, groupids=[self.base_groupid],
                                    interfaces=[interfaces], status=0, templateids=[templateid],
                                    macros=[{
                                        "macro": "{$SNMP_COMMUNITY}",
                                        "value": "public"
                                    }])
        self.check_code(response=response, code=0)
        hostid = UtilsResponse().get_result(response=response)["hostids"][0]
        return hostid

    @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.name in UtilsResponse().get_values_from_key(_dict=result, key="name")
            assert y.host in UtilsResponse().get_values_from_key(_dict=result, key="host")
        for x, y in enumerate(result):
            assert y["name"] in UtilsResponse().get_values_from_sql(_sql=sql, key="name")
            assert y["host"] in UtilsResponse().get_values_from_sql(_sql=sql, key="host")

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

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

    @allure.title("host.get：groupids=特定IDs")
    @allure.story("查询主机：groupids=特定IDs")
    def test_case_03(self):
        response = self.host_get(groupids=[self.base_groupid])
        self.check_code(response=response, code=0)

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

    @allure.title("host.get：hostids=特定IDs, output=[name, internal, flags]")
    @allure.story("查询主机：hostids=特定IDs, output=[name, internal, flags]")
    def test_case_05(self):
        hostid = self.case_create(num="05")

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

    @allure.title("host.get：limit=1")
    @allure.story("查询主机：limit=1")
    def test_case_06(self):
        response = self.host_get(limit=1)
        self.check_code(response=response, code=0)
        result = UtilsResponse().get_result(response=response)
        assert len(result) == 1

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

    @allure.title("host.get：sortfield=hostid, sortorder=ASC")
    @allure.story("查询主机：sortfield=hostid, sortorder=ASC")
    def test_case_08(self):
        response = self.host_get(sortfield=["hostid"], sortorder=["ASC"])
        self.check_code(response=response, code=0)
        self.check_sortfield(response=response, possible="ASC")

    @allure.title("host.get：sortfield=hostid, sortorder=DESC")
    @allure.story("查询主机：sortfield=hostid, sortorder=DESC")
    def test_case_09(self):
        response = self.host_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 = TestHostGet()
    # a.setup_class()
    # a.test_case_09()
