简介
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