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 天前
AI 帮我写单测:pytest 覆盖率提升 40% 的协作日志
人工智能·pytest·测试驱动开发·代码覆盖率·ai协作开发
lucia_zl6 天前
pytest并发测试,资源问题导致用例失败解决办法
pytest
鱼鱼说测试6 天前
Selenium4+Pytest自动化测试框架实战
pytest
XYiFfang12 天前
【Pytest】解决Pytest中Teardown钩子的TypeError:实例方法与类方法的调用差异
python·pytest
Kingairy14 天前
Pytest 插件:pytest_runtest_protocol
python·pytest
AIZHINAN14 天前
Pytest 插件介绍和开发
测试工具·pytest·插件开发
灰阳阳16 天前
替身演员的艺术:pytest-mock 从入门到飙戏
自动化测试·python·pytest·unit testing·pytest-mock
年年测试20 天前
Playwright与PyTest结合指南
pytest
focksorCr20 天前
pytest 并发执行用例(基于受限的测试资源)
python·pytest