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


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.Host.host_create import HostCreate

from WorkData.Zabbix.hosts import DataHosts
from WorkData.Zabbix.items import DataItems
from WorkData.Zabbix.triggers import DataTriggers
from WorkData.Zabbix.functions import DataFunctions
from WorkData.Zabbix.hosts_groups import DataHostsGroups
from WorkData.Zabbix.hostmacro import DataHostsMacro
from WorkData.Zabbix.interface import DataInterface

import allure


@allure.feature("测试模块：host.create")
class TestHostCreate(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_group_id = 101
    base_name = "SS TEST HOST"
    base_ip = "10.0.0.10"
    base_host = "SS测试主机"
    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 = "Test"
        api.tls_psk = "Test"
        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_group")
    def select_hosts_group(self, groupid=None, hostid=None):
        session = self.db_session()
        sql = DataHostsGroups().select_all_from_allKeys(session=session, groupid=groupid, hostid=hostid)
        return sql

    @allure.step("查询表：interface")
    def select_interface(self, interfaceid=None, hostid=None):
        session = self.db_session()
        sql = DataInterface().select_all_from_allKeys(session=session, interfaceid=interfaceid, hostid=hostid)
        return sql

    @allure.step("查询表：items")
    def select_items(self, hostid=None, templateid=None):
        session = self.db_session()
        sql = DataItems().select_all_from_allKeys(session=session, hostid=hostid, templateid=templateid)
        return sql

    @allure.step("查询表：functions")
    def select_functions(self, triggerid=None, itemid=None):
        session = self.db_session()
        sql = DataFunctions().select_all_from_allKeys(session=session, triggerid=triggerid, itemid=itemid)
        return sql

    @allure.step("查询表：templateid")
    def select_triggers(self, templateid=None):
        session = self.db_session()
        sql = DataTriggers().select_all_from_allKeys(session=session, templateid=templateid)
        return sql

    @allure.step("查询表：hostmacro")
    def select_hostmacro(self, hostid=None):
        session = self.db_session()
        sql = DataHostsMacro().select_all_from_allKeys(session=session, hostid=hostid)
        return sql

    @allure.step("校验查询结果")
    def check_select(self, hostid, _type):
        sql = self.select_hosts_group(groupid=self.base_group_id, hostid=hostid)
        for x, y in enumerate(sql):
            assert y.groupid == self.base_group_id
            assert y.hostid == hostid

        sql = self.select_interface(hostid=hostid)
        for x, y in enumerate(sql):
            assert y.ip == self.base_ip
            assert y.port == "100"
            assert y.type == _type
            assert y.main == 1

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

    @allure.title("host.create：创建agent主机")
    @allure.story("创建主机：创建agent主机")
    @allure.severity("blocker")
    def test_case_01(self):
        host = self.base_name + "01"
        description = self.base_description + "01"
        interfaces = {
                "type": 1,
                "main": 1,
                "useip": 1,
                "ip": self.base_ip,
                "dns": "",
                "port": 100,
                "bulk": 1
        }
        response = self.host_create(host=host, description=description, groupids=[self.base_group_id], interfaces=[interfaces], status=0)
        self.check_code(response=response, code=0)
        hostid = UtilsResponse().get_result(response=response)["hostids"][0]
        self.check_select(hostid=hostid, _type=1)

    @allure.title("host.create：创建snmp主机")
    @allure.story("创建主机：创建snmp主机")
    @allure.severity("blocker")
    def test_case_02(self):
        host = self.base_name + "02"
        description = self.base_description + "02"
        interfaces = {
            "type": 2,
            "main": 1,
            "useip": 1,
            "ip": self.base_ip,
            "dns": "",
            "port": 100,
            "bulk": 1
        }
        response = self.host_create(host=host, description=description, groupids=[self.base_group_id], interfaces=[interfaces], status=0)
        self.check_code(response=response, code=0)
        hostid = UtilsResponse().get_result(response=response)["hostids"][0]
        self.check_select(hostid=hostid, _type=2)

    @allure.title("host.create：重复创建")
    @allure.story("创建主机：重复创建")
    def test_case_03(self):
        host = self.base_name + "03"
        description = self.base_description + "03"
        interfaces = {
            "type": 1,
            "main": 1,
            "useip": 1,
            "ip": self.base_ip,
            "dns": "",
            "port": 100,
            "bulk": 1
        }
        response = self.host_create(host=host, description=description, groupids=[101], interfaces=[interfaces], status=0)
        self.check_code(response=response, code=0)
        response = self.host_create(host=host, description=description, groupids=[101], interfaces=[interfaces], status=0)
        self.check_code(response=response, code=100)

    @allure.title("host.create：模板创建")
    @allure.story("创建主机：模板创建")
    def test_case_04(self):
        templateid = 10001

        host = self.base_name + "04"
        description = self.base_description + "04"
        interfaces = {
            "type": 2,
            "main": 1,
            "useip": 1,
            "ip": self.base_ip,
            "dns": "",
            "port": 100,
            "bulk": 1
        }
        response = self.host_create(host=host, description=description, groupids=[101], 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]
        self.check_host(hostid=hostid, templateid=templateid)

    @allure.step("校验创建host的相关数据")
    def check_host(self, hostid, templateid):
        self.log.debug("根据templateid= %s, 获取模板监控项IDs" % templateid)
        itemids = []
        sql = self.select_items(hostid=templateid)
        for x, y in enumerate(sql):
            itemids.append(y.itemid)

        self.log.debug("根据模板监控项IDs, 获取模板触发器IDs")
        triggers = []
        for x, y in enumerate(itemids):
            sql = self.select_functions(itemid=y)
            if sql:
                triggers.append(sql[0].triggerid)

        new_itemids = []
        self.log.info("校验监控项是否根据模板监控器已创建")
        for x, y in enumerate(itemids):
            sql = self.select_items(hostid=hostid, templateid=y)
            assert sql != []
            new_itemids.append(sql[0].itemid)

        new_triggers = []
        self.log.info("校验触发器是否根据模板触发器已创建")
        for x, y in enumerate(triggers):
            sql = self.select_triggers(templateid=y)
            assert sql != []
            new_triggers.append(sql[0].triggerid)

        self.log.info("校验监控器与触发器关系是否已创建")
        for x, y in enumerate(new_triggers):
            sql = self.select_functions(triggerid=y)
            assert sql != []

        self.log.info("校验主机宏是否已创建")
        sql = self.select_hostmacro(hostid=hostid)
        for x, y in enumerate(sql):
            assert y.macro == "{$SNMP_COMMUNITY}"
            assert y.value == "public"


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