FastAPI(43)- 基于 pytest + requests 进行单元测试 (下)

简介: FastAPI(43)- 基于 pytest + requests 进行单元测试 (下)

复杂的测试场景


服务端

#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
# author: 小菠萝测试笔记
# blog:  https://www.cnblogs.com/poloyy/
# time: 2021/9/29 10:55 下午
# file: s37_pytest.py
"""
import uvicorn
from fastapi import FastAPI
from fastapi.testclient import TestClient
app = FastAPI()
@app.get("/")
async def read_main():
    return {"msg": "Hello World"}
# 声明一个 TestClient,把 FastAPI() 实例对象传进去
client = TestClient(app)
# 测试用
def test_read_main():
    # 请求 127.0.0.1:8080/
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"msg": "Hello World"}
from typing import Optional
from fastapi import FastAPI, Header, HTTPException
from pydantic import BaseModel
# 模拟真实 token
fake_secret_token = "coneofsilence"
# 模拟真实数据库
fake_db = {
    "foo": {"id": "foo", "title": "Foo", "description": "There goes my hero"},
    "bar": {"id": "bar", "title": "Bar", "description": "The bartenders"},
}
app = FastAPI()
class Item(BaseModel):
    id: str
    title: str
    description: Optional[str] = None
# 接口一:查询数据
@app.get("/items/{item_id}", response_model=Item)
async def read_main(item_id: str, x_token: str = Header(...)):
    # 1、校验 token 失败
    if x_token != fake_secret_token:
        raise HTTPException(status_code=400, detail="x-token 错误")
    # 2、若数据库没有对应数据
    if item_id not in fake_db:
        raise HTTPException(status_code=404, detail="找不到 item_id")
    # 3、找到数据则返回
    return fake_db[item_id]
# 接口二:创建数据
@app.post("/items/", response_model=Item)
async def create_item(item: Item, x_token: str = Header(...)):
    # 1、校验 token 失败
    if x_token != fake_secret_token:
        raise HTTPException(status_code=400, detail="x-token 错误")
    # 2、若数据库已经存在相同 id 的数据
    if item.id in fake_db:
        raise HTTPException(status_code=400, detail="找不到 item_id")
    # 3、添加数据到数据库
    fake_db[item.id] = item
    # 4、返回添加的数据
    return item
if __name__ == '__main__':
    uvicorn.run(app="s37_test_pytest:app", reload=True, host="127.0.0.1", port=8080)


单元测试

#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
# author: 小菠萝测试笔记
# blog:  https://www.cnblogs.com/poloyy/
# time: 2021/9/29 10:55 下午
# file: s37_pytest.py
"""
from fastapi.testclient import TestClient
from .s37_test_pytest import app
client = TestClient(app)
def test_read_item():
    expect = {"id": "foo", "title": "Foo", "description": "There goes my hero"}
    headers = {"x-token": "coneofsilence"}
    resp = client.get("/items/foo", headers=headers)
    assert resp.status_code == 200
    assert resp.json() == expect
def test_read_item_error_header():
    expect = {"detail": "x-token 错误"}
    headers = {"x-token": "test"}
    resp = client.get("/items/foo", headers=headers)
    assert resp.status_code == 400
    assert resp.json() == expect
def test_read_item_error_id():
    expect = {"detail": "找不到 item_id"}
    headers = {"x-token": "coneofsilence"}
    resp = client.get("/items/foos", headers=headers)
    assert resp.status_code == 404
    assert resp.json() == expect
def test_create_item():
    body = {"id": "foos", "title": "Foo", "description": "There goes my hero"}
    headers = {"x-token": "coneofsilence"}
    resp = client.post("/items/", json=body, headers=headers)
    assert resp.status_code == 200
    assert resp.json() == body
def test_create_item_error_header():
    body = {"id": "foo", "title": "Foo", "description": "There goes my hero"}
    expect = {"detail": "x-token 错误"}
    headers = {"x-token": "test"}
    resp = client.post("/items/", json=body, headers=headers)
    assert resp.status_code == 400
    assert resp.json() == expect
def test_create_item_error_id():
    expect = {"detail": "找不到 item_id"}
    body = {"id": "foo", "title": "Foo", "description": "There goes my hero"}
    headers = {"x-token": "coneofsilence"}
    resp = client.post("/items/", json=body, headers=headers)
    assert resp.status_code == 400
    assert resp.json() == expect


命令行运行

pytest test.py -sq

 

运行结果

> pytest s37_pytest.py -sq

......

6 passed in 0.40s

 

相关文章
|
4天前
|
数据可视化 测试技术 持续交付
自动化测试神器:Python之Pytest库入门使用
自动化测试神器:Python之Pytest库入门使用
105 4
|
4天前
|
测试技术 iOS开发
pytest Mark标记测试用例
使用`pytest.mark`进行测试用例分组和筛选,如`@pytest.mark.webtest`。通过`pytest -m`参数执行特定标记的用例,例如`pytest -s test_command_param.py -m webtest`。同时,pytest支持内置的skip、skipif和xfail功能来管理特殊用例:skip始终跳过,skipif条件满足时跳过,xfail则标记预期失败的测试。
5 0
|
4天前
|
jenkins 测试技术 持续交付
Pytest测试框架
Pytest是一个功能强大的测试框架,支持单元测试和复杂功能测试,可结合Requests和Selenium等进行接口和自动化测试。它拥有超过315个插件,兼容unittest,并能与Allure、Jenkins集成实现持续集成。安装可通过pip或Pycharm。Pytest遵循特定命名规则,测试用例由名称、步骤和断言组成。断言用于验证预期结果,当失败时程序会终止。Pytest提供setup/teardown机制来管理测试前后的资源。
16 3
|
4天前
|
前端开发 测试技术 C++
Python自动化测试面试:unittest、pytest与Selenium详解
【4月更文挑战第19天】本文聚焦Python自动化测试面试,重点讨论unittest、pytest和Selenium三大框架。unittest涉及断言、TestSuite和覆盖率报告;易错点包括测试代码冗余和异常处理。pytest涵盖fixtures、参数化测试和插件系统,要注意避免过度依赖unittest特性。Selenium的核心是WebDriver操作、等待策略和测试报告生成,强调智能等待和元素定位策略。掌握这些关键点将有助于提升面试表现。
29 0
|
4天前
|
运维 测试技术
实用指南:使用Pytest Allure测试框架添加用例失败截图
本文介绍了如何在使用`allure+pytest`进行软件测试时,通过`pytest_runtest_makereport`钩子函数自动捕获失败用例的截图。在`conftest.py`中定义钩子,当用例失败时,保存截图并附加到Allure测试报告中。测试代码示例展示了登录豆瓣的场景,测试失败时会自动生成截图。这种方法有助于快速理解和解决测试问题,提升测试效率和软件质量。
19 0
|
4天前
|
测试技术 API Python
Python自动化测试:unittest与pytest的实战技巧
Python自动化测试:unittest与pytest的实战技巧
|
4天前
|
测试技术 Python
设置pycharm使用pytest执行测试用例时,输出print语句至控制台
设置pycharm使用pytest执行测试用例时,输出print语句至控制台
71 0
|
4天前
|
缓存
pytest 运行测试函数报错的解决办法 TypeError: calling <function xxx> returned None, not a test
pytest 运行测试函数报错的解决办法 TypeError: calling <function xxx> returned None, not a test
122 0
|
4天前
|
测试技术 Python
pycharm使用pytest运行测试用例,无法在控制台输出print语句、log语句的解决办法
pycharm使用pytest运行测试用例,无法在控制台输出print语句、log语句的解决办法
93 1
|
4天前
|
测试技术
软件测试/测试开发全日制|Pytest中yield的用法详解
软件测试/测试开发全日制|Pytest中yield的用法详解
28 0

热门文章

最新文章