pytest-类中测试方法、多文件批量执行

pytest-类中测试方法、多文件批量执行,完整、可直接复制运行的写法,覆盖:

  1. 测试类 + 类中方法执行
  2. 多文件批量执行
  3. 按标记(@pytest.mark)执行
  4. 常用组合用法

1. 测试类 + 类中方法在 main 中执行

完整代码

python

运行

复制代码
import pytest

# 测试类(必须 Test 开头)
class TestDemo:
    def test_case1(self):
        assert 1 + 1 == 2

    def test_case2(self):
        assert "pytest" in "hello pytest"

# 独立函数
def test_func1():
    assert True

if __name__ == '__main__':
    # 1. 执行当前文件所有用例(类+函数)
    pytest.main([__file__, "-v", "-s"])

    # 2. 只执行某个类
    # pytest.main([__file__ + "::TestDemo", "-v"])

    # 3. 只执行某个类里的某个方法
    # pytest.main([__file__ + "::TestDemo::test_case1", "-v"])

执行路径规则

plaintext

复制代码
文件.py::类名::方法名

2. 多文件批量执行

假设项目结构:

plaintext

复制代码
tests/
├── test_login.py
├── test_order.py
└── test_pay.py
main.py

main.py 中批量执行

python

运行

复制代码
import pytest

if __name__ == '__main__':
    # 1. 执行 tests 目录下所有测试
    pytest.main(["./tests", "-v", "-s"])

    # 2. 执行指定多个文件
    # pytest.main(["./tests/test_login.py", "./tests/test_order.py", "-v"])

    # 3. 只执行某个文件中的某个用例
    # pytest.main(["./tests/test_login.py::TestLogin::test_login_success", "-v"])

3. 按标记 @pytest.mark 执行(常用)

给用例打标记,例如 smokeapiui

示例代码

python

运行

复制代码
import pytest

@pytest.mark.smoke
def test_smoke1():
    assert True

@pytest.mark.smoke
def test_smoke2():
    assert True

@pytest.mark.api
def test_api1():
    assert True

if __name__ == '__main__':
    # 只执行标记为 smoke 的用例
    pytest.main([__file__, "-m", "smoke", "-v"])

    # 执行 smoke 或 api
    # pytest.main([__file__, "-m", "smoke or api", "-v"])

    # 执行非 api
    # pytest.main([__file__, "-m", "not api", "-v"])

4. 最常用完整 main 模板(直接拿去用)

python

运行

复制代码
import pytest

if __name__ == '__main__':
    pytest.main([
        "./tests",       # 测试目录
        "-v",            # 详细
        "-s",            # 显示 print
        "-x",            # 失败即停止
        "--html=report.html",  # 报告
        "--alluredir=./allure-results"
    ])

5. 常用执行语法汇总

表格

场景 写法
当前文件所有用例 pytest.main([__file__])
某个测试类 文件::TestClass
类中某个方法 文件::TestClass::test_func
某个函数 文件::test_func
执行目录 ["./tests"]
按标记执行 -m smoke
相关推荐
风吹夏回6 小时前
Python 全局异常处理:从“满屏 try-except”到优雅兜底
开发语言·python
Chengbei116 小时前
一站式源码安全检测工具、云安全 / APP / 小程序源码敏感信息递归多层目录扫描AK、JWT、手机号、身份证等敏感信息
java·开发语言·安全·web安全·网络安全·系统安全·安全架构
llz_1126 小时前
web-第一次课后作业
java·开发语言·idea
小熊Coding6 小时前
Python爬取当当网二手图书项目实战!
开发语言·爬虫·python·beautifulsoup·requests·二手图书
秋96 小时前
Java项目运行5天左右自动宕机:系统性定位与解决方案
java·开发语言·python
小江的记录本7 小时前
【JVM虚拟机】垃圾回收GC:垃圾收集器:CMS:核心原理、回收流程、优缺点、废弃原因(附《思维导图》+《面试高频考点清单》)
java·jvm·后端·python·spring·面试·maven
xiaoshuaishuai87 小时前
C# 内存管理与资源泄漏
开发语言·c#
lsx2024067 小时前
SVN 检出操作
开发语言
田里的水稻7 小时前
OE_ubuntu26.04与宿主机之间复制粘贴内容
人工智能·python·机器人
basketball6168 小时前
C++ NULL 和 nullptr 区别 以及 nullptr 的核心实现
java·开发语言·c++