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

相关推荐
神即道 道法自然 如来9 小时前
Pytest配置文件pytest.ini如何编写生成日志文件?
pytest
XXX-171 天前
1.pytest基础知识(默认的测试用例的规则以及基础应用)
软件测试·pytest
Mavis先生2 天前
PyTest装饰器
pytest
神即道 道法自然 如来5 天前
Python+Pytest框架,“main_run.py文件怎么编写“?
java·python·pytest
___Dream6 天前
【项目一】基于pytest的自动化测试框架———解读requests模块
python·计算机网络·pytest
ccy加油呀8 天前
pytest 接口测试
android·pytest
云泽野10 天前
一篇文章了解Pytest单元测试框架
服务器·单元测试·pytest
___Dream10 天前
【项目一】基于pytest的自动化测试框架day1
pytest
这不巧了11 天前
Faker在pytest中的应用
python·自动化·pytest
测试界的海飞丝11 天前
pytest运行方式及前置后置封装详解
开发语言·selenium·单元测试·pytest