接口自动化测试工具-----pytest

首先确保安装了Python环境,首先,你需要确保已安装 Python 和 Pip。如果还没有安装,可以从 Python 官方网站下载并安装最新版本的 Python。安装过程中请确保选中“Add Python to PATH”选项。

安装pytest:打开命令提示符(Command Prompt)或 PowerShell,运行以下命令来安装 Pytest 和 Requests 库:

pip install pytest requests

之后查看是否安装成功

pip show pytest

 之后搭建一个后端项目,以springboot项目为例

编写一个简单的模拟登录的接口,之后启动项目

@RestController
@RequestMapping("/aa")
public class TestController {

    @Autowired
    private UserPoService userPoService;

    @GetMapping("/testLogin")
    @LogExecutionTime
    public String test(String name,String password){

       if(userPoService.testLogin(name,password)){
           return "success!!";
       }
       return "error";
    }

以上代码的逻辑就是 根据用户传过来的name字段查询数据库,之后拿到用户信息之后和password字段作对比,如果密码正确就返回success 失败就是 error

之后编写python脚本:

1. 用错误的密码尝试

import requests
import pytest


@pytest.fixture
def api_url():
    return "http://localhost:8080/aa"  # 假设你的接口地址是这个


def test_login(api_url):
    response = requests.get(f"{api_url}/testLogin?name=平安&password=111")

    # 打印响应详细信息
    print("Status Code:", response.status_code)
    print("Headers:", response.headers)
    print("Response Text:", response.text)

    # 断言部分
    assert response.status_code == 200
    assert response.headers["Content-Type"] == "application/json"
    assert "success!!" in response.text

查看运行结果

2.关掉后端服务(模拟服务器宕机) 

3. 使用正确的账号密码

import requests
import pytest


@pytest.fixture
def api_url():
    return "http://localhost:8080/aa"  # 假设你的接口地址是这个


def test_login(api_url):
    response = requests.get(f"{api_url}/testLogin?name=平安&password=7,23")

    # 打印响应详细信息
    print("Status Code:", response.status_code)
    print("Headers:", response.headers)
    print("Response Text:", response.text)

    # 断言部分
    assert response.status_code == 200
    assert response.headers["Content-Type"] == "text/plain;charset=UTF-8"
    assert "success!!" in response.text

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ADRU

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值