"""
@autor:Yue
@date::15:49
@file:asertcase.py
@project:autoInterface

"""
import jsonpath,copy,json,re
from blueprints.tools.dealbody import requesturl,dealbodyHeaderType,deal_globalParam
from blueprints.tools.dealCasefile import readCaseFile
from blueprints.requestResult import requestResult
from blueprints.tools.dealDatabase import dealParamSql,delDatabase
from blueprints.tools.deals import separate_deallsql
from blueprints.tools import debugtalk
#from blueprints.exec import  getinfo
def asertcase(jsoncase,result,config=None):
    '''
    :param jsoncase: 通过json文件找到断言条件
    :param result: response
    :return:
    '''
    #print(jsoncase,result)

    f=deal_globalParam(config,readCaseFile(jsoncase))
    basis=f.get("result")
    #print(f)
    needCommand = f.get('needCommand')
    t=[]



    if isinstance(result,dict):
        if result.get('code')=='0' or result.get('code')=='0000':
            return 1
        else:
            return 0
    try:
        aresult=copy.deepcopy(result.json())
    except:
        #print("result 转json失败",result.status_code,basis,f)
        if result.status_code==200 and basis and basis.get('tebieinfo')=='error':
            return 1
        if  result.status_code==200 and (result.text.lower()=='success' or 'html' in result.text.lower() or 'stream' in result.text):
            return 1
        return 0

    if result.status_code==200:



        if basis and isinstance(basis,dict):
            for k,v in basis.items():
                acv=v
                #print('acv===',acv,k)
                b= jsonpath.jsonpath(aresult,"$..{0}".format(k))

                ##处理，当json文件中的result断言里有sql或者函数时，直接从sql或者函数得到值

                #print(basis.get('code')=='0' or basis.get('code')=='0000')
                if 'select' in v:
                    v1 = separate_deallsql(v)
                    # print("断崖字段===：", v)
                    v = delDatabase(config, v1)
                    # print("断崖结果===：",v,k,b)
                else:
                    try:
                        # print(v)
                        v = eval('debugtalk.{0}'.format(v))
                        print('####', v)
                    except:
                        # print(v)
                        try:
                            v = json.loads(v)
                        except:
                            pass


                if b:

                    print("[预期][{0}:{1}],实际{2}".format(k, v, b))
                    print("<br/>")
                    bt=[str(i) for i in b ]

                    ##单独判断code的值，因为禅道上code改成0000，都会变成0

                    if k=='code':

                        if len(bt[0])>1 and '0000' == str(bt[0]) and (str(v)=='0' or str(v)=='0000'):
                        #if '0000' in str(bt) :
                            #print(11)
                            #print('11:', t)
                            t.append(1)
                            # if str(v) in bt:
                            #     t.append(1)
                            # else:
                            #     # print('00:', t)
                            #     t.append(0)
                            if aresult.get('businessCode'):
                                if aresult.get('businessCode') == '0000':
                                    t.append(1)
                                else:
                                    t.append(0)
                        elif len(bt[0])==1 and '0' == str(bt[0]) and (str(v)=='0' or str(v)=='0000'):
                            t.append(1)
                            if aresult.get('businessCode'):
                                if aresult.get('businessCode') == '0000':
                                    t.append(1)
                                else:
                                    t.append(0)
                            # if str(v) in bt:
                            #     t.append(1)
                            # else:
                            #     #print('00:', t)
                            #     t.append(0)
                        else:

                            if str(v) in bt:
                                t.append(1)
                            else:
                                #print('00:', t)
                                t.append(0)
                        #print("1==",t)
                    else:

                        if isinstance(v,list):

                            for vv in v:
                                try:
                                    vv=str(eval(vv))
                                except:
                                    vv=str(vv)


                                if vv in bt:
                                    t.append(1)
                                else:
                                    print("断言失败1== 预期[{0}],实际{1}".format(vv,bt),k,v)

                                    t.append(0)
                        else:
                            if  v in bt or str(v) in bt:
                                t.append(1)
                            else:
                                print("断言失败2== 预期[{0}],实际{1}".format(v, bt), k)
                                t.append(0)



                if needCommand and (basis.get('code')=='0' or basis.get('code')=='0000'):
                    for assertk, assertv in needCommand.items():


                        if assertk.lower() ==k.lower() :
                            if 'select' in assertk.lower():
                                assertsqlValue=delDatabase(config,assertv)
                            else:
                                try:
                                    assertsqlValue=eval('debugtalk.{0}'.format(assertv))#eval()
                                except:
                                    assertsqlValue=json.loads(assertv)
                                    pass

                            if type(assertsqlValue)==type(v):
                                try:

                                    t.append(1) if sorted(str(assertsqlValue))==sorted(str(v)) else t.append(0)
                                    #print("====="*10, t,assertsqlValue,v)
                                except:
                                    raise  Exception('{assertsqlValue}排序失败或者{v}排序失败'.format(v=v,assertsqlValue=assertsqlValue))


                        else:
                            if 'select' in assertk.lower():
                                assertsqlValue=delDatabase(config,assertv)
                            else:
                                try:
                                    assertsqlValue=eval('debugtalk.{0}'.format(assertv))#eval()
                                except:
                                    assertsqlValue=json.loads(assertv)
                                    pass
                        #print("中间信息==", assertsqlValue)
                            #t.append(0)
                            #print('[{assertk}]没有用处，需要确认'.format(assertk=assertk))


                if k.split('_')[0]=='exist' and (basis.get('code')=='0' or basis.get('code')=='0000'):
                    table_position = [index + 1 for index, i in enumerate(acv.split()) if i == 'from']
                    #print("table_position====",v)
                    if v and v[0]!=0:
                        print("断言成功==[{0}]表存在数据[{1}]".format(acv.split()[table_position[0] if table_position else acv],v))
                        #print('1:',t)
                        t.append(1)
                    else:
                        print("断言失败==[{0}]表不存在数据[{1}]".format(
                            acv.split()[table_position[0] if table_position else acv], v))
                        #print('2:', t)
                        t.append(0)


                elif k.split('_')[0]=='exist' and (basis.get('code')!='0' or basis.get('code')!='0000'):
                    pass

                #else:
                ###判断响应中的必须存在的字段
                elif basis and basis.get('mustexist') and  (basis.get('code')=='0' or basis.get('code')=='0000'):#and isinstance(basis.get('mustexist'),list):
                    mustexist=eval(basis.get('mustexist'))
                    temp_mustexist={}

                    for i in mustexist:
                        #temp_mustexist.setdefault()
                        if temp_mustexist.get(i):
                            temp_mustexist[i]+=1
                        else:
                            temp_mustexist.setdefault(i, 1)

                    #print('temp_mustexist================',temp_mustexist)
                    for k,v in temp_mustexist.items():

                        if jsonpath.jsonpath(aresult,"$..{0}".format(k)) and  len(jsonpath.jsonpath(aresult,"$..{0}".format(k)))>=v:
                            t.append(1)
                        else:
                            print('<br/>')
                            print('必须字段断言处理== 响应中缺少必须字段【{0}】'.format(k))
                            print('<br/>')
                            t.append(0)
                else:
                    if isinstance(v, list):
                        for vv in v:
                            # print('vv===', vv,str(result.text))
                            if str(vv) in str(result.text).split(','):
                                t.append(1)
                            else:
                                print("断言失败3", vv, v, t)
                                t.append(0)

                    else:
                        if v in str(result.text).split(','):
                            t.append(1)

        if 0 in t and len(t)>0:
            return 0

        return 1

    return 0


if __name__ == '__main__':
    jsoncase='/Users/dm/Desktop/python_script/autoInterface/testCase/passportapi/388.json'
    res={
    "msg": "",
    "code": "0000",
    "businessCode": "0000",
    "data": {
        "token": "7f67e393-5dee-4c06-8b2d-9df28ca578bf",
        "phoneNo": "18606900878",
        "uuid": "33682d02-dcb6-46fb-8a92-1aab30d0b4a5",
        "hasPassword": False
    },
    "success": True
}
    t=asertcase(jsoncase,res)

    #print(t)




