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


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_update import HostUpdate

from WorkData.Zabbix.hosts import DataHosts
from WorkData.Zabbix.interface import DataInterface
from WorkData.Zabbix.items import DataItems
from WorkData.Zabbix.hostmacro import DataHostsMacro

from WorkCase import CaseBase

import allure


@allure.feature("测试模块：host.update")
class TestHostUpdate(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 UPDATE"
    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.update")
    def host_update(self, groupids=None, hostid=None, countOutput=None, editable=None, excludeSearch=None,
                    _filter=None, limit=None, output=None, preservekeys=None, interfaces=None, macros_macro=None, macros_value=None,
                    ipmi_authtype=None, ipmi_privilege=None, ipmi_username=None, ipmi_password=None,
                    interfaces_type=None, interfaces_main=None, interfaces_useip=None, interfaces_ip=None,
                    interfaces_dns=None, interfaces_port=None, interfaces_bulk=None):
        api = HostUpdate(_host=self.host)
        api.groupids = groupids
        api.hostid = hostid
        api.countOutput = countOutput
        api.editable = editable
        api.excludeSearch = excludeSearch
        api.filter = _filter
        api.limit = limit
        api.output = output
        api.preservekeys = preservekeys
        api.interfaces = interfaces
        api.ipmi_authtype = ipmi_authtype
        api.ipmi_privilege = ipmi_privilege
        api.ipmi_username = ipmi_username
        api.ipmi_password = ipmi_password
        api.macros_macro = macros_macro
        api.macros_value = macros_value
        api.interfaces_type = interfaces_type
        api.interfaces_main = interfaces_main
        api.interfaces_useip = interfaces_useip
        api.interfaces_ip = interfaces_ip
        api.interfaces_dns = interfaces_dns
        api.interfaces_port = interfaces_port
        api.interfaces_bulk = interfaces_bulk
        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("查询表：interface")
    def select_interface(self, hostid):
        session = self.db_session()
        sql = DataInterface().select_all_from_allKeys(session=session, hostid=hostid)
        return sql

    @allure.step("查询表：hosts_macro")
    def select_macro(self, hostid):
        session = self.db_session()
        sql = DataHostsMacro().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)
        self.hostid = UtilsResponse().get_result(response=response)["hostids"][0]
        return self.hostid

    @allure.step("断言返回结果：与数据库结果是否一致")
    def check_sql(self):
        sql = self.select_hosts(hostid=self.hostid)
        for x, y in enumerate(sql):
            assert y.ipmi_authtype == 2
            assert y.ipmi_privilege == 3
            assert y.ipmi_username == "ipmi_username"
            assert y.ipmi_password == "ipmi_password"
            assert x == 0

        sql = self.select_macro(hostid=self.hostid)
        for x, y in enumerate(sql):
            assert y.macro == "{$SNMP_COMMUNITY}"
            assert y.value == "public"
            assert x == 0

        sql = self.select_interface(hostid=self.hostid)
        for x, y in enumerate(sql):
            assert y.type == 1
            assert y.main == 1
            assert y.useip == 1
            assert y.ip == self.base_ip
            assert y.dns == ""
            assert y.port == self.base_port
            assert x == 0

    @allure.title("host.update：需要的字段")
    @allure.story("更新主机：需要的字段")
    @allure.severity("blocker")
    def test_case_01(self):
        self.case_create(num="01")
        response = self.host_update(hostid=self.hostid, macros_macro=["{$SNMP_COMMUNITY}"], macros_value=["public"],
                                    ipmi_authtype=2, ipmi_password="ipmi_password",
                                    ipmi_privilege=3, ipmi_username="ipmi_username",
                                    interfaces_type=[1], interfaces_main=[1], interfaces_ip=[self.base_ip],
                                    interfaces_dns=[""], interfaces_useip=[1], interfaces_port=[self.base_port],
                                    interfaces_bulk=[1])

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


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 = TestHostUpdate()
    # a.setup_class()
    # a.test_case_01()
