pytest入门一:用例的执行范围

从一个或多个目录开始查找,可以在命令行指定文件名或目录名。如果未指定,则使用当前目录。

  • 测试文件以 test_ 开头或以 _test 结尾

  • 测试类以 Test 开头 ,并且不能带有 init 方法

  • 测试函数以 test_ 开头

  • 断言使用基本的 assert 即可

  • 所有的包 pakage 必须要有__init__.py 文件

复制代码
# test_2.py
import sys

import pytest

def add(x,y):
    return x + y

@pytest.mark.add
def test_add():
    assert add(1,2) == 3
    assert add(2,3) == 5
    assert add(10,2) == 12

def is_win32():
    return True if sys.platform == 'win32' else False

class TestDemo:

    def test_demo(self):
        x = "hello world"
        print(f"{x} python")
        assert 'h' in x

    @pytest.mark.skipif(sys.platform == 'win32',reason='win32跳过用例')
    def test_demo3(self):
        x = "hello world"
        print(f"{x} python")
        assert 'h' in x



    only_win32 = pytest.mark.skipif(is_win32(),reason='win32跳过用例')
    @only_win32
    def test_demo4(self):
        x = "hello world"
        print(f"{x} python")
        assert 'h' in x

    @pytest.mark.skip("变更")
    def test_demo2(self):
        x = 'hello'
        assert hasattr(x,"check")

    @pytest.mark.xfail(reason="bug待修复")
    def test_demo5(self):
        x = 'hello'
        assert hasattr(x, "check")

if __name__ == "__main__":
    pytest.main(['-v', '-s'])

1)执行全部

if name == "main" : pytest.main(['-v' , '-s'])

2)执行某个文件

if name == "main" :

pytest.main(['-v' , '-s' ,'test_2.py'])

3)执行某个类

if name == "main" :

pytest.main(['-v' , '-s' ,'test_2.py::TestDemo'])

4) 执行某个方法

if name == "main" :

pytest.main(['-v' , '-s' ,'test_2.py::TestDemo::test_demo'])

5) mark 打标执行 pytest.mark.add

6) skip忽略执行 @pytest.mark.skip("变更")

7) 条件忽略skipif @pytest.mark.skipif(sys.platform == 'win32' ,reason='win32跳过用例')

8)xfail:预期失败 @pytest.mark.xfail

真失败会显示xfailed,成功会显示xpassed,应用场景:已知bug标注,后续验证修复

相关推荐
西游音月12 小时前
(2)pytest+Selenium自动化测试-环境准备
selenium·测试工具·pytest
我的xiaodoujiao17 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 23--数据驱动--参数化处理 Yaml 文件
python·学习·测试工具·pytest
我的xiaodoujiao4 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 22--数据驱动--参数化处理 Json 文件
python·学习·测试工具·pytest
胜天半月子4 天前
Python自动化测试 | 快速认识并了解pytest的基本使用
服务器·python·pytest
北珣.8 天前
自动化框架pytest基础
自动化·pytest
程序员杰哥9 天前
Pytest之收集用例规则与运行指定用例
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·pytest
学习3人组10 天前
Python + requests + pytest + allure + Jenkins 构建完整的接口自动化测试框架
python·jenkins·pytest
shao91851613 天前
Gradio全解14——使用Gradio构建MCP的服务器与客户端(4)——Python包命令:uv与uvx实战
pytest·uv·1024程序员节·npx·uvx·uv pip·ruff
我的xiaodoujiao14 天前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 20--PO(POM) 设计模式和用例撰写
python·学习·测试工具·设计模式·pytest
sky0Lan14 天前
一个类似 pytest 的 html 报告
android·html·pytest