# -*- 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.Items.items_get import ItemsGet


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

from WorkCase import CaseBase

import allure

# allure.label("")


@allure.feature("测试模块：items.get")
class TestItemsGet(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_groupid = 101
    base_name = "SS TEST HOST ITEMS"
    base_ip = "10.0.0.10"
    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("创建测试数据")
    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": 100,
            "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("调用接口：items.get")
    def items_get(self, itemids=None, graphids=None, groupids=None, hostids=None, proxyids=None, interfaceids=None,
                  applicationids=None, templateids=None, triggerids=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 = ItemsGet(_host=self.host)
        api.itemids = itemids
        api.groupids = groupids
        api.templateids = templateids
        api.hostids = hostids
        api.proxyids = proxyids
        api.interfaceids = interfaceids
        api.graphids = graphids
        api.triggerids = triggerids
        api.applicationids = applicationids
        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("查询表：items")
    def select_items(self, hostid=None, itemid=None):
        session = self.db_session()
        sql = DataItems().select_all_from_allKeys(session=session, hostid=hostid, itemid=itemid)
        return sql

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

    @allure.title("items.get：无参数调用")
    @allure.story("查询监控项：无参数调用")
    @allure.severity("blocker")
    def test_case_01(self):
        response = self.items_get()
        self.check_code(response=response, code=0)

    @allure.title("items.get：countOutput=true")
    @allure.story("查询监控项：countOutput=true")
    def test_case_02(self):
        response = self.items_get(countOutput="true")
        self.check_code(response=response, code=0)

    @allure.title("items.get：hostids=特定IDs")
    @allure.story("查询监控项：hostids=特定IDs")
    def test_case_03(self):
        hostid = self.case_create(num="03")

        response = self.items_get(hostids=[hostid])
        self.check_code(response=response, code=0)

    @allure.title("items.get：output=[name]")
    @allure.story("查询监控项：output=[name]")
    def test_case_04(self):
        response = self.items_get(output=["name"])
        self.check_code(response=response, code=0)

    @allure.title("items.get：hostids=特定IDs, output=[hostid, name]")
    @allure.story("查询监控项：hostids=特定IDs, output=[hostid, name]")
    def test_case_05(self):
        hostid = self.case_create(num="05")

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

    @allure.title("items.get：limit=1")
    @allure.story("查询监控项：limit=1")
    def test_case_06(self):
        response = self.items_get(limit=1)
        self.check_code(response=response, code=0)
        result = UtilsResponse().get_result(response=response)
        assert len(result) == 1

    @allure.title("items.get：sortfield=itemid")
    @allure.story("查询监控项：sortfield=itemid")
    def test_case_07(self):
        response = self.items_get(sortfield=["itemid"])
        self.check_code(response=response, code=0)
        self.check_sortfield(response=response, possible=True)

    @allure.title("items.get：sortfield=itemid, sortorder=ASC")
    @allure.story("查询监控项：sortfield=itemid, sortorder=ASC")
    def test_case_08(self):
        response = self.items_get(sortfield=["itemid"], sortorder=["ASC"])
        self.check_code(response=response, code=0)
        self.check_sortfield(response=response, possible="ASC")

    @allure.title("items.get：sortfield=itemid, sortorder=DESC")
    @allure.story("查询监控项：sortfield=itemid, sortorder=DESC")
    def test_case_09(self):
        response = self.items_get(sortfield=["itemid"], 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 = TestItemsGet()
    # a.setup_class()
    # a.test_case_05()
