每日面经分享(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

相关推荐
我一定会有钱2 天前
pytest基础
python·测试工具·测试用例·pytest
西游音月2 天前
(6)pytest+Selenium自动化测试-测试用例编写
selenium·测试用例·pytest
兴趣使然黄小黄4 天前
【Pytest】Pytest框架快速入门
python·pytest
m0_632482505 天前
Jenkins + Pytest +allure接口自动化测试配置与操作
jenkins·集成测试·pytest·jenkins配置
李星星BruceL5 天前
Pytest第三章(参考指南1)
python·自动化·pytest
哎呀呦呵5 天前
pytest基本使用
python·pytest
Kristen_YXQDN5 天前
PyCharm 中 pytest 运行 python 测试文件报错:D:\Python_file\.venv\Scripts\python.exe: No module named pytest
运维·开发语言·python·pycharm·pytest
Low--Key5 天前
pytest框架快速入门
python·自动化·pytest
姜西西_5 天前
自动化测试框架pytest之fixture
android·java·pytest
测试开发Kevin5 天前
超级实用!汇总pytest中那些常用的参数
单元测试·pytest