自动化测试常用框架之pytest

运行方式

命令行模式
命令行中执行 pytest -s test_login.py
主函数模式
在 test_login.py 文件中增加主函数
if __name__ == '__main__':
  pytest.main(["-s", "login.py"]
-s 支持控制台打印

setup和teardown

函数级别

复制代码
import pytest 

class TestLogin:

# 函数级开始
  def setup(self):
    print("------->setup_method")
# 函数级结束
  def teardown(self):
    print("------->teardown_method")
  def test_a(self):
    print("------->test_a")
  def test_b(self):
    print("------->test_b")
复制代码
scripts/test_login.py ------->setup_method # 第一次 setup()
 ------->test_a .
------->teardown_method # 第一次 teardown() 
------->setup_method # 第二次 setup() 
------->test_b .
------->teardown_method # 第二次 teardown()

类级别

复制代码
class TestLogin: 
# 测试类级开始 
    def setup_class(self): 
        print("------->setup_class")
# 测试类级结束 
    def teardown_class(self): 
        print("------->teardown_class") 
    def test_a(self): 
        print("------->test_a") 
    def test_b(self): 
        print("------->test_b")                        
复制代码
scripts/test_login.py 
------->setup_class # 第一次 setup_class() 
------->test_a .
------->test_b .
------->teardown_class # 第一次 teardown_class()

配置文件

复制代码
[pytest] 
# 添加命令行参数 
addopts = -s 
# 文件搜索路径 
testpaths = ./scripts 
# 文件名称 
python_files = test_*.py 
# 类名称 
python_classes = Test* 
# 方法名称 
python_functions = test_*
# 测试报告

addopts = -s --html=report/report.html


addopts = -s
表示命令行参数
testpaths,python_files,python_classes,python_functions
表示 哪一个文件夹 下的 哪一个文件 下的 哪一个类 下的 哪一个函数
表示执行 scripts 文件夹下的 test 开头 .py 结尾的文件下的 Test 开头的类下的 test开头的函
复制代码

控制参数执行顺序

1. 标记于被测试函数,@pytest.mark.run(order=x)
2. 根据order传入的参数来解决运行顺序
3. order值全为正数或全为负数时,运行顺序:值越小,优先级越高
4. 正数和负数同时存在:正数优先级高
复制代码
import pytest 
class TestLogin: 
    def test_hello_001(self): 
        print("test_hello_001") 
    @pytest.mark.run(order=1) 
    def test_hello_002(self): 
        print("test_hello_002") 
    @pytest.mark.run(order=2)
    def test_hello_003(self): 
        print("test_hello_003") 

复制代码
scripts/test_login.py 
test_hello_002 # 先运行2 
.test_hello_003 # 再运行3 
.test_hello_001

失败重试

addopts = -s --reruns 3

跳过测试

复制代码
import pytest 
class TestLogin: 
    def test_a(self): 
# test开头的测试函数 
        print("------->test_a") 
        assert 1 # 断言成功 
    @pytest.mark.skipif(condition=True, reason="xxx") 
    def test_b(self): 
        print("------->test_b") 
        assert 0 # 断言失败                    
复制代码
scripts/test_login.py ------->test_a .s

数据参数化

import pytest 
class TestLogin: 
    @pytest.mark.parametrize("name", ["xiaoming", "xiaohong"]) 
    def test_a(self, name): 
        print(name) assert 1    

 

 

 

 

 

 

 

 

posted @   谁跟我提bug我跟谁急  阅读(86)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示