每日面经分享(pytest测试案例,接口断言,多并发断言)

  1. pytest对用户登录接口进行自动化脚本设计
    a. 创建一个名为"test_login.py"的测试文件,编写以下测试脚本
python 复制代码
import pytest
import requests

# 测试用例1:验证登录成功的情况
# 第一个测试用例验证登录成功的情况,发送有效的用户名和密码,预期结果是返回状态码200和success字段为True。
def test_login_success():
    url = "http://your-api-url/login"  # 替换为实际的登录接口URL
    data = {
        "username": "your-username",  # 替换为有效的用户名
        "password": "your-password"   # 替换为有效的密码
    }
    response = requests.post(url, data=data)
    assert response.status_code == 200
    assert response.json()["success"] == True

# 测试用例2:验证登录失败的情况
# 第二个测试用例验证登录失败的情况,发送无效的用户名和密码,预期结果是返回状态码401和success字段为False。
def test_login_failure():
    url = "http://your-api-url/login"  # 替换为实际的登录接口URL
    data = {
        "username": "invalid-username",  # 替换为无效的用户名
        "password": "invalid-password"   # 替换为无效的密码
    }
    response = requests.post(url, data=data)
    assert response.status_code == 401
    assert response.json()["success"] == False

b. 在终端中进入测试文件所在的目录,并运行以下命令来执行这些测试用例

python 复制代码
pytest test_login.py
  1. pytest之多线程多并发自动化接口设计
    a. 安装pytest-parallel插件
python 复制代码
pip install pytest-parallel

b. 创建一个名为test_concurrent_api.py的测试文件,并编写以下测试脚本。定义一个测试用例来测试多并发接口的情况。使用concurrent.futures.ThreadPoolExecutor来创建一个线程池执行器,并使用executor.submit方法在线程池中并发执行接口请求。在每个请求的结果中,用断言来验证接口的返回结果是否符合预期。

python 复制代码
import pytest
import requests
from concurrent.futures import ThreadPoolExecutor

# 测试用例:验证多并发接口的情况
def test_concurrent_api():
    url = "http://your-api-url"  # 替换为实际的接口URL

    # 定义并发请求数量
    concurrency = 10

    # 创建一个线程池执行器
    executor = ThreadPoolExecutor(max_workers=concurrency)

    # 使用线程池并发执行接口请求
    with executor:
        results = [
            executor.submit(requests.get, url) for _ in range(concurrency)
        ]

        # 遍历结果,进行断言
        for result in results:
            response = result.result()
            assert response.status_code == 200
            assert response.json()["success"] == True

c. 在终端中进入测试文件所在的目录,并运行以下命令执行测试用例:<num_workers>是并发工作线程数量。pytest会使用pytest-parallel插件来并发执行测试用例,并输出每个测试用例的运行结果和总体的测试结果。

python 复制代码
pytest -n <num_workers> test_concurrent_api.py

互联网大厂测开经历,目前担任测试开发负责人,每天分享互联网面经,如果你有测试相关的问题,欢迎咨询,海鲜市场【简历优化】、【就业指导】、【模拟/辅导面试】,已辅导20位以上同学拿到心仪offer

相关推荐
我的xiaodoujiao3 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 48--本地环境部署Jenkins服务
python·学习·测试工具·pytest
我的xiaodoujiao3 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 49--CI/CD-开始探索使用Jenkins
python·学习·测试工具·ci/cd·jenkins·pytest
测试渣5 天前
测试左移实战:如何在需求阶段拦截80%缺陷?
selenium·pytest·测试覆盖率
一次旅行5 天前
测开每日AI提效指令(Python+pytest专属)
python·pytest·测试总结
一次旅行5 天前
接口自动化测试模板
数据库·python·pytest
Kingairy6 天前
Claude Python3+pytest Code Review skill.md
pytest·代码复审
姚青&7 天前
Pytest 参数化与调度执行
pytest
薯条不要番茄酱7 天前
【测试实战篇】“发好论坛”接口自动化测试
python·功能测试·测试工具·单元测试·测试用例·pytest·测试覆盖率
weixin_419658317 天前
当Pytest遇见AI:基于Trae的接口测试用例全自动生成实践
人工智能·python·测试工具·测试用例·pytest·ai编程
@zulnger9 天前
selenium+pytest 自动化测试实战项目(登录升级版)
selenium·测试工具·pytest