import pytest, json
import jsonpath
from utils import get_excel as gexcel
from utils.send import ApiClient
from utils.write_log import write_log,clear_log
from dic.global_value import GlobalInfo
client = ApiClient()

clear_log("url")
clear_log("headers")
clear_log("params")
clear_log("data")
clear_log("json")
clear_log("respose")
clear_log("globalInfo.txt")
@pytest.mark.login
def test_excel_path():
    print("login")
    assert 1 == 1

@pytest.mark.parametrize("case_info", gexcel.get_excel("demo", 0))
def test_case(case_info):
    #初始化全局变量
    dic = GlobalInfo().show_info()

    # 拼接请求参数
    url = case_info["url"]
    method = case_info["method"]
    headers = eval(case_info["headers"]) if case_info["headers"] else {}
    params = eval(case_info["params"]) if case_info["params"] else {}
    data = eval(case_info["data"]) if case_info["data"] else {}
    _json = eval(case_info["json"]) if case_info["json"] else {}



    # 前置操作


    # 写日志
    write_log("url",url)
    write_log("headers",headers)
    write_log("params",params)
    write_log("data",data)
    ## 变量替换

    res = client.send_request(method, url, headers=headers, params=params, data=data, json=_json)
    write_log("respose", res.json())


    # assert res.status_code == 200


    # 后置操作
    ## 提取变量
    if case_info["提取变量"] != "":
        vars_to_extract = [v.strip() for v in case_info["提取变量"].split(",") if v.strip()]
        for var in vars_to_extract:
            value = jsonpath.jsonpath(res.json(), f"$..{var}")
            if value:
                GlobalInfo().set_info(var, value[0])
        write_log("globalInfo.txt", json.dumps(GlobalInfo().show_info()))

    print(_json)