使用python test测试http接口

使用python test测试http接口

  1. 获取token和控制session,后面大多数接口要带上这些信息

    python 复制代码
    import time
    import requests
    
    from common.aes_algorithm import AES
    from config.config import Config
    from config.log import log
    
    
    class Common:
        username = "admin"
        password = "888888"
        token = None
        user_id = None
        controlSession = None
    
        def __init__(self):
            pass
    
        @classmethod
        def login(cls):
            timestamp = int(time.time())
            password = AES.encrypt(cls.password, str(timestamp))
            data = {
                "username": cls.username,
                "password": password,
                "timestamp": timestamp,
            }
            response = requests.post(f"{Config.base_url}/user/login", json=data)
            response.raise_for_status()
            # 打印响应内容
            dataJson = response.json()
            log.debug(dataJson)
            if dataJson["status"] == 200:
                data = dataJson.get("data")
                cls.token = data.get("Authorization")
                cls.user_id = data.get("userID")
    
        @classmethod
        def get_control_session(cls):
            if cls.controlSession is None:
                timestamp = int(time.time())
                password = AES.encrypt(cls.password, str(timestamp))
                response = requests.post(
                    f"{Config.base_url}/user/verifyControlPasswd",
                    headers={"Authorization": cls.token},
                    json={
                        "userID": cls.user_id,
                        "password": password,
                        "timestamp": timestamp,
                    },
                )
                response.raise_for_status()
                dataJson = response.json()
                log.debug(dataJson)
                if dataJson["status"] == 200:
                    data = dataJson.get("data")
                    cls.controlSession = data.get("controlSession")
    
        def get_token(cls):
            cls.login()
            cls.get_control_session()
    
    if __name__ == "__main__":
        common = Common()
        common.get_token()
  2. 使用unittest编写单元测试

    python 复制代码
    import time
    import unittest
    
    import requests
    
    from common.login import Common
    from config.config import Config
    from config.log import log
    
    
    class StgyModeTest(unittest.TestCase):
        @classmethod
        def setUpClass(cls):
            cls.common = Common()
            cls.common.get_token()  # 只执行一次
    
            timestamp = int(time.time())
            cls.data = [
                {
                    "userID": Common.user_id,
                    "controlSession": Common.controlSession,
                    "timestamp": timestamp,
                    "mode": "powerBalanced",
                },
                {
                    "userID": Common.user_id,
                    "controlSession": Common.controlSession,
                    "timestamp": timestamp,
                    "mode": "socBalanced",
                },
                {
                    "userID": Common.user_id,
                    "controlSession": Common.controlSession,
                    "timestamp": timestamp,
                    "mode": "customRatio",
                    "powerWeights": [
                        {"pcsCode": "pcs1", "ratio": 0.3},
                        {"pcsCode": "pcs2", "ratio": 0.7},
                        {"pcsCode": "pcs3", "ratio": 0},
                    ],
                },
            ]
    
        def test_set_power_balanced_stgy(self):
            response = requests.post(
                f"{Config.base_url}/strategy/setStrategyMode",
                headers={"Authorization": Common.token},
                json=self.data[0],
            )
            log.info(f"set stgy mode response: {response.text}")
            response.raise_for_status()
            # 打印响应内容
            dataJson = response.json()
            if dataJson["status"] == 200:
                data = dataJson.get("data")
                log.info(f"set stgy mode success, data: {data}")
    
        def test_set_soc_balanced_stgy(self):
            response = requests.post(
                f"{Config.base_url}/strategy/setStrategyMode",
                headers={"Authorization": Common.token},
                json=self.data[1],
            )
            log.info(f"set stgy mode response: {response.text}")
            response.raise_for_status()
            # 打印响应内容
            dataJson = response.json()
            if dataJson["status"] == 200:
                data = dataJson.get("data")
                log.info(f"set stgy mode success, data: {data}")
    
        def test_set_custom_power_weights_stgy(self):
            response = requests.post(
                f"{Config.base_url}/strategy/setStrategyMode",
                headers={"Authorization": Common.token},
                json=self.data[2],
            )
            log.info(f"set stgy mode response: {response.text}")
            response.raise_for_status()
            # 打印响应内容
            dataJson = response.json()
            if dataJson["status"] == 200:
                data = dataJson.get("data")
                log.info(f"set stgy mode success, data: {data}")
    
        # 获取策略接口
        def test_get_stgy_mode(self):
            response = requests.get(
                f"{Config.base_url}/strategy/getStrategyMode",
                headers={"Authorization": Common.token},
            )
            log.info(f"get stgy mode response: {response.text}")
    
    
    if __name__ == "__main__":
        unittest.main()

vscode里面启用unittest插件

  1. 代开vscode设置,搜索python test,启用unittest

  2. 在左侧可以运行单个测试

相关推荐
jarreyer10 分钟前
python离线包安装方法总结
开发语言·python
李辰洋13 分钟前
go tools安装
开发语言·后端·golang
wanfeng_0918 分钟前
go lang
开发语言·后端·golang
绛洞花主敏明20 分钟前
go build -tags的其他用法
开发语言·后端·golang
ByteCraze25 分钟前
秋招被问到的常见问题
开发语言·javascript·原型模式
码银28 分钟前
【python】基于 生活方式与健康数据预测数据集(Lifestyle and Health Risk Prediction)的可视化练习,附数据集源文件。
开发语言·python·生活
Pluchon30 分钟前
硅基计划5.0 MySQL 叁 E-R关系图&联合/多表查询&三大连接&子查询&合并查询
开发语言·数据库·学习·mysql
kyle~37 分钟前
C++---嵌套类型(Nested Types)封装与泛型的基石
开发语言·c++·算法
sali-tec40 分钟前
C# 基于halcon的视觉工作流-章48-短路断路
开发语言·图像处理·人工智能·算法·计算机视觉
无敌最俊朗@1 小时前
解决 QML 中使用 Qt Charts 崩溃的三个关键步骤
开发语言·qt