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标注,后续验证修复

相关推荐
昔我往昔3 天前
pytest日志问题排查记录
python·pytest
黄昏恋慕黎明6 天前
博客论坛技术迭代
python·pytest
2601_962078236 天前
Python接口自动化流程(pytest)
python·pytest·接口自动化·测试框架·断言
杨女士YRJ6 天前
python+pytest+01
python·pytest
2601_962078237 天前
Python接口自动化框架:pytest
python·pytest·接口自动化·测试框架·restfulapi
2601_962078197 天前
Appium+Python+pytest自动化测试框架详解
自动化测试·python·appium·pytest·移动应用
2601_962284509 天前
安卓APP UI自动化测试:Python + UiAutomator2 + pytest + pytest-html
python·pytest·uiautomator2·ui自动化测试·安卓app
2601_962300819 天前
基于pytest的接口自动化测试:使用requests模块的实战项目与接口关联方法详解
接口自动化测试·测试用例·pytest·接口关联·requests模块
2601_962300819 天前
Python + Requests + Pytest + Excel + Allure:接口自动化测试项目实战
python·excel·pytest·allure·requests
11路没有终点10 天前
Pytest 安装、版本与第一个测试用例
测试用例·pytest