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


from __future__ import division
from WorkUtils.UtilsLog import UtilsLog
from WorkUtils.UtilsDataBase import UtilsDataBase
from WorkUtils.UtilsResponse import UtilsResponse
from WorkApi.API.HostGroup.hostGroup_create import HostGroupCreate
from WorkApi.API.HostGroup.hostGroup_get import HostGroupGet

from WorkData.Zabbix.hstgrp import DataHstGrp

from WorkCase import CaseBase

import allure

# allure.label("")


@allure.feature("测试模块：hostgroup.get")
class TestHostGroupGet(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测试主机组"

    @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)
        DataHstGrp().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("调用接口：hostgroup.create")
    def hostgroup_create(self, name=None, groupid=None, flags=None, internal=None):
        api = HostGroupCreate(_host=self.host)
        api.name = name
        api.groupid = groupid
        api.flags = flags
        api.internal = internal
        api.get_response()
        return api.response

    @allure.step("调用接口：hostgroup.get")
    def hostgroup_get(self, graphids=None, groupids=None, hostids=None, maintenanceids=None, monitored_hosts=None,
                      real_hosts=None, templated_hosts=None, templateids=None, triggerids=None, with_applications=None,
                      with_graphs=None, with_hosts_and_templates=None, with_httptests=None, with_items=None,
                      with_monitored_httptests=None, with_monitored_items=None, with_monitored_triggers=None,
                      with_simple_graph_items=None, with_triggers=None, selectDiscoveryRule=None, selectGroupDiscovery=None,
                      selectHosts=None, selectTemplates=None, limitSelects=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 = HostGroupGet(_host=self.host)
        api.graphids = graphids
        api.groupids = groupids
        api.hostids = hostids
        api.maintenanceids = maintenanceids
        api.monitored_hosts = monitored_hosts
        api.real_hosts = real_hosts
        api.templated_hosts = templated_hosts
        api.templateids = templateids
        api.triggerids = triggerids
        api.with_applications = with_applications
        api.with_graphs = with_graphs
        api.with_hosts_and_templates = with_hosts_and_templates
        api.with_httptests = with_httptests
        api.with_items = with_items
        api.with_monitored_httptests = with_monitored_httptests
        api.with_monitored_items = with_monitored_items
        api.with_monitored_triggers = with_monitored_triggers
        api.with_simple_graph_items = with_simple_graph_items
        api.with_triggers = with_triggers
        api.selectDiscoveryRule = selectDiscoveryRule
        api.selectGroupDiscovery = selectGroupDiscovery
        api.selectHosts = selectHosts
        api.selectTemplates = selectTemplates
        api.limitSelects = limitSelects
        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("查询表：hstgrp")
    def select_hstgrp(self, groupid=None, name=None, internal=None, flags=None):
        session = self.db_session()
        sql = DataHstGrp().select_all_from_allKeys(session=session, groupid=groupid, name=name, internal=internal, flags=flags)
        return sql

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

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

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

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

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

    @allure.title("hostgroup.get：groupids=特定IDs, output=[name, internal, flags]")
    @allure.story("查询主机组：groupids=特定IDs, output=[name, internal, flags]")
    def test_case_05(self):
        name = self.base_name + "05"
        response = self.hostgroup_create(name=name)
        self.check_code(response=response, code=0)
        groupid = UtilsResponse().get_result(response=response)["groupids"][0]

        response = self.hostgroup_get(groupids=[groupid], output=["name", "internal", "flags"])
        self.check_code(response=response, code=0)
        self.check_sql(response=response, groupid=groupid)

    @allure.title("hostgroup.get：limit=1")
    @allure.story("查询主机组：limit=1")
    def test_case_06(self):
        name = self.base_name + "06"
        response = self.hostgroup_create(name=name)
        self.check_code(response=response, code=0)

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

    @allure.title("hostgroup.get：精确搜索")
    @allure.story("查询主机组：精确搜索")
    def test_case_07(self):
        name = self.base_name + "07"
        response = self.hostgroup_create(name=name)
        self.check_code(response=response, code=0)

        response = self.hostgroup_get(search={"name": [name]})
        self.check_code(response=response, code=0)
        result = UtilsResponse().get_result(response=response)
        assert len(result) == 1

    @allure.title("hostgroup.get：模糊搜索")
    @allure.story("查询主机组：模糊搜索")
    def test_case_08(self):
        name = self.base_name + "08"
        response = self.hostgroup_create(name=name)
        self.check_code(response=response, code=0)

        response = self.hostgroup_get(search={"name": ["*" + self.base_name + "*"]}, searchByAny=True, searchWildcardsEnabled=True)
        self.check_code(response=response, code=0)
        result = UtilsResponse().get_result(response=response)
        assert len(result) >= 1

    @allure.title("hostgroup.get：sortfield=groupid")
    @allure.story("查询主机组：sortfield=groupid")
    def test_case_09(self):
        response = self.hostgroup_get(sortfield=["groupid"])
        self.check_code(response=response, code=0)
        self.check_sortfield(response=response, possible=True)

    @allure.title("hostgroup.get：sortfield=groupid, sortorder=ASC")
    @allure.story("查询主机组：sortfield=groupid, sortorder=ASC")
    def test_case_10(self):
        response = self.hostgroup_get(sortfield=["groupid"], sortorder=["ASC"])
        self.check_code(response=response, code=0)
        self.check_sortfield(response=response, possible="ASC")

    @allure.title("hostgroup.get：sortfield=groupid, sortorder=DESC")
    @allure.story("查询主机组：sortfield=groupid, sortorder=DESC")
    def test_case_11(self):
        response = self.hostgroup_get(sortfield=["groupid"], 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 = TestHostGroupGet()
    # a.test_case_05()
