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

相关推荐
旦莫16 小时前
Pytest教程:为什么Pytest要用插件模式?
python·单元测试·自动化·pytest
三次握手四次挥手2 天前
基于Python+Pytest实现自动化测试(全栈实战指南)
开发语言·python·自动化·k8s·apache·pytest·代码规范
世界的尽头在哪里3 天前
python测试框架之pytest
开发语言·python·测试工具·单元测试·pytest
胆大的3 天前
怎样才能设计好的自动化测试用例
自动化·测试用例·pytest
雨中夜归人6 天前
自动化测试工具playwright中文文档-------14.Chrome 插件
python·测试工具·自动化·pytest·playwright
小马哥编程11 天前
【软件测试】自动化测试框架Pytest + Selenium的使用
selenium·测试工具·pytest
明月与玄武13 天前
Pytest多环境切换实战:测试框架配置的最佳实践!
pytest·pytest框架环境切换
<花开花落>22 天前
将Python第三方库转换为真正的 pytest 插件
pytest