[pytest]基础

简介: [pytest]基础

简介

The pytest framework makes it easy to write small, readable tests, and can scale to support complex functional testing for applications and libraries.

pytest是一个成熟的python测试框架,易于编写,小巧易读,扩展性高。

  • 安装:python -m pip install pytest(需要python 3.7+)

规范

在pytest测试框架中,需要遵循以下规范:

  • 测试文件名要符合test_*.py*_test.py
  • 如果团队内之前没用过pytest,建议固定使用其中一个
  • 示例:test_login.py
  • 测试类要以Test开头,且不能带有__init__()方法
  • 示例:class TestLogin:
  • 在单个测试类中,可以有多个测试函数。测试函数名符合test_*

示例代码1

  • 编写test_sample.py
def inc(x):
    # 入参值加1
    return x + 1
def test_inc_1():
    # 断言
    assert inc(3) == 4
def test_inc_2():
    # 断言
    assert inc(3) == 5
  • 在代码所在目录下执行命令:python -m pytest

示例代码2

  • 编写test_sample.py
import pytest
def test_001():
    print("test_001")
def test_002():
    print("test_002")
if __name__ == '__main__':
    # 使用pytest.main()可以传入可执行参数,通过[]进行分割,[]内多个参数使用半角逗号分割
    pytest.main(["-v", "test_sample.py"])
  • 在代码所在目录下执行命令:python test_sample.py

示例代码3-生成html格式的测试报告

  • 编写test_sample.py
import pytest
def inc(x):
    return x + 1
def test_inc_1():
    # 断言成功
    assert inc(3) == 4
def test_inc_2():
    # 断言失败
    assert inc(3) == 5
users = ["zhaoda", "qianer", "sunsan", "lisi"]
def test_userin():
    # 断言失败
    assert "zhouwu" in users
if __name__ == '__main__':
    # 测试test_sample.py文件,并生成html格式的测试报告
    # 需要使用pip安装pytest-html
    pytest.main(["--html=./report.html", "test_sample.py"])
  • 在代码所在目录下执行命令:python test_sample.py
  • 可以通过浏览器打开生成的html文件

示例代码4-接口测试

  • 先用go语言写了一个简单的接口,传参userId,返回username等用户信息。
package main
import (
  "context"
  "log"
  "net/http"
  "os"
  "os/signal"
  "syscall"
  "time"
  "github.com/gin-gonic/gin"
)
type ReqUserInfo struct {
  UserId int `json:userId`
}
func f2(c *gin.Context) {
  // 解析请求体
  var req ReqUserInfo
  if err := c.ShouldBindJSON(&req); err != nil {
    c.JSON(http.StatusBadRequest, gin.H{
      "ERROR": err.Error(),
    })
    return
  }
  var rsp struct {
    UserId   int    `json:"userId"`
    Username string `json:"username"`
    UserSex  int    `json:"userSex"`
  }
  rsp.UserId = req.UserId
  rsp.Username = "zhangsan"
  rsp.UserSex = 0
  c.JSON(http.StatusOK, rsp)
}
func main() {
  // gin.SetMode(gin.ReleaseMode)
  r := gin.Default()
  r.GET("/user", f2)
  // 设置程序优雅退出
  srv := &http.Server{
    Addr:    "127.0.0.1:8000",
    Handler: r,
  }
  go func() {
    if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
      log.Fatalf("listen failed, %v\n", err)
    }
  }()
  quit := make(chan os.Signal, 1)
  signal.Notify(quit, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
  <-quit
  ctx, cancel := context.WithTimeout(context.Background(), time.Second)
  defer cancel()
  if err := srv.Shutdown(ctx); err != nil {
    log.Fatalf("server shutdown failed, err: %v\n", err)
  }
  select {
  case <-ctx.Done():
    log.Println("timeout of 1 seconds")
  }
  log.Println("server shutdown")
}
  • 运行服务端:go run main.go
  • 编写测试代码:test_user.py
import pytest
import requests
import json
def test_user():
    url = "http://127.0.0.1:8000/user"
    headers = {
        "Content-Type": "application/json"
    }
    data = {
        "userId": 123456,
    }
    req = requests.get(url=url, headers=headers, data=json.dumps(data))
    print(req.text)
    assert req.json()["username"] == "zhangsan"
if __name__ == '__main__':
    pytest.main(["-v", "-s","test_user.py"])
  • 执行测试:python test_user.py

参考

相关文章
|
4月前
|
测试技术 API Python
Python自动化测试:unittest与pytest的实战技巧
Python自动化测试:unittest与pytest的实战技巧
|
测试技术
46-pytest-分布式插件pytest-xdist使用
46-pytest-分布式插件pytest-xdist使用
|
测试技术 Python
Pytest系列(16)- 分布式测试插件之pytest-xdist的详细使用
Pytest系列(16)- 分布式测试插件之pytest-xdist的详细使用
625 0
|
JSON 测试技术 数据格式
19-pytest-allure-pytest环境搭建
19-pytest-allure-pytest环境搭建
|
测试技术 Python
01-pytest-安装及入门
01-pytest-安装及入门
|
负载均衡 监控 测试技术
pytest学习和使用20-pytest如何进行分布式测试?(pytest-xdist)
pytest学习和使用20-pytest如何进行分布式测试?(pytest-xdist)
176 0
pytest学习和使用20-pytest如何进行分布式测试?(pytest-xdist)
|
自然语言处理 Java 测试技术
pytest学习和使用21-测试报告插件allure-pytest如何使用?
pytest学习和使用21-测试报告插件allure-pytest如何使用?
149 0
pytest学习和使用21-测试报告插件allure-pytest如何使用?
|
测试技术
pytest学习和使用5-Pytest和Unittest中的断言如何使用?
pytest学习和使用5-Pytest和Unittest中的断言如何使用?
84 0
pytest学习和使用5-Pytest和Unittest中的断言如何使用?
|
Linux 测试技术 Python
pytest学习和使用1-pytest安装和版本查看
pytest学习和使用1-pytest安装和版本查看
457 0
pytest学习和使用1-pytest安装和版本查看
|
Python
pytest学习和使用3-对比unittest和pytest脚本在pycharm中运行的方式
pytest学习和使用3-对比unittest和pytest脚本在pycharm中运行的方式
106 0
pytest学习和使用3-对比unittest和pytest脚本在pycharm中运行的方式