# -*-coding:utf-8 -*- #
# ---------------------------------------------------------------------------
# ProjectName:   test62
# FileName:      request_method.py
# Author:       lao_zhao
# Datetime:     2024/9/4 15:35
# Description:
# 
# ---------------------------------------------------------------------------
import requests

from apiAutoTest_v3.common.read_project_ini import ReadProjectIni


class RequestMethod:
    def __init__(self):
        """关联登录成功的token"""
        # 被测系统的域名存放在项目的ini配置文件中，所有需要ReadProjectIni对象，调用get_host方法获取被测系统的域名
        login_url = ReadProjectIni().get_host("bpm_host") + "/auth"
        login_data = {"username": "admin", "password": "bF6N3L93cX8pV6x2yEqxNjwIIPaEOYw9bNI5GuIY4g9MeoFyPFPL5WteHaV0LcxQ"
                                                      "qmDJWlhuCRMXzAPvrFcxJrA8BgGjJpmB1WMrQrazIJPbWbCfmDit2s2jzn+DRerV"
                                                      "lYIFojDM96y24drEniwWzHtaJKiWoc7LGL1csNmokvQ="}
        self.bpm_session = requests.sessions.Session()
        res = self.bpm_session.post(url=login_url, json=login_data)
        token = res.json().get("token")
        self.bpm_session.headers["Authorization"] = f"Bearer {token}"

    def request_all(self, req_method, req_url, req_mime, case_data):
        """
        封装公共的请求方法
        :param req_method:请求方法
        :param req_url:请求的url
        :param req_mime:媒体类型
        :param case_data:用例数据
        :return:Response type
        """
        if req_mime == "application/json" or req_mime == "json":
            return self.bpm_session.request(method=req_method, url=req_url, json=case_data)

        elif req_mime == "application/x-www-form-urlencoded" or req_mime == "form":
            # 除了上传文件和json类型在请求体中传参以外，其他类型的数据全部使用data关键字传参。
            return self.bpm_session.request(method=req_method, url=req_url, data=case_data)

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

        elif req_mime == "query" or req_mime == "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":
            # requests是支持地址栏和请求体同时传参的。地址栏使用params传参，请求体根据不同的媒体类型选择不同的关键字传参。
            return self.bpm_session.request(method=req_method, url=req_url, params=case_data["query"], json=case_data["body"])