# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName:   test60
# FileName:      requsts_method.py
# Author:       lao_zhao
# Datetime:     2024/5/20 14:34
# Description:
# 
# ---------------------------------------------------------------------------
import base64
import requests

from InterfaceAutoTest import log_decorator
from InterfaceAutoTest.common.read_ini import ReadIni
from InterfaceAutoTest.data_config.settings import BPM_KEY


class RequestsMethod:
    @log_decorator
    def __init__(self):
        """关联token"""
        login_url = ReadIni().get_host(BPM_KEY)+"/auth"
        login_data = {"username": "admin", "password": base64.b64encode("123456".encode()).decode()}
        self.bpm_session = requests.sessions.Session()
        self.bpm_session.headers["Authorization"] = "Bearer "+self.bpm_session.post(url=login_url, json=login_data).json().get("token")

    @log_decorator
    def request_all(self, req_method, req_url, req_mime, case_data):
        """封装公共的请求方法"""
        if req_mime == "json" or req_mime == "application/json":
            return self.bpm_session.request(method=req_method, url=req_url, json=case_data)

        elif req_mime == "form" or req_mime == "application/x-www-form-urlencoded":
            return self.bpm_session.request(method=req_method, url=req_url, data=case_data)

        elif req_mime == "text" or req_mime == "text/plain":
            # 请求体中除了json类型传参和上传文件以外的数据如果需要在请求体中传参全部使用data传参
            return self.bpm_session.request(method=req_method, url=req_url, data=case_data)

        elif req_mime == "form-data" or req_mime == "multipart/form-data":
            return self.bpm_session.request(method=req_method, url=req_url, files=case_data)

        elif req_mime == "query" or req_mime == "params":
            # 任何请求如果在地址栏传参使用params关键字传参
            return self.bpm_session.request(method=req_method, url=req_url, params=case_data)

        elif req_mime is None:
            return self.bpm_session.request(method=req_method, url=req_url)

        # 判断请求的媒体类型是为query|json或者为json|query
        elif req_mime == "query|json" or req_mime == "json|query":
            query_data = case_data["query"]
            body_data = case_data["body"]
            # params和json同时传参时表示请求体和地址栏同时传参
            return self.bpm_session.request(method=req_method, url=req_url, params=query_data, json=body_data)

        else:
            raise ValueError("请求的媒体类型没封装")