使用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. 在左侧可以运行单个测试

相关推荐
孟健10 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞12 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽14 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程19 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪19 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook19 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
不可能的是19 小时前
前端 SSE 流式请求三种实现方案全解析
前端·http
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img