首页 > 技术文章 > pytest扫盲2--pytest.main()

xiaohuboke 2020-08-17 14:16 原文

直接上代码吧~~~~

# File  : test_demo_2.py
# IDE   : PyCharm

import pytest

def setup_function():
    print('*' * 10 +'用例开始!'+ '*' * 10)

def teardown_function():
    print('*' * 10 +'用例结束!' + '*' * 10)

def test_1():
    print('*' * 5 + 'test_1' + '*' * 5)
    a = 'hello world!'
    assert 'hello' in a

def test_2():
    print('*' * 5 + 'test_2' + '*' * 5)
    x = 'hello world!'
    assert hasattr(x, 'helloWorld')

@pytest.mark.smoke
def test_3():
    print('*' * 5 + 'test_3' + '*' * 5)
    b = 3
    assert b == 4
# File  : main.py
# IDE   : PyCharm

import pytest

## 1)不带参数执行用例:执行当前目录下所有测试用例
# pytest.main()

## 2)指定文件名:执行该文件中的测试用例
# pytest.main(['test_demo_2.py'])

## 3)指定参数和路径:pytest.main(['parameter', 'file.py'])
## parameter提供如下参数:
'''
    1:'-s': 关闭捕捉,显示程序中的print/logging输出。
    2:'-v': 丰富信息模式, 输出更详细的用例执行信息。
    3:'-m=xxx': 运行打标签的测试用例。
    4:'q':  安静模式, 不输出环境信息。
    5:'-x': 出现一条测试用例失败就退出测试。
    6:'--maxfail=x':当用例执行失败次数达到x次后,退出测试
    7:'--resultlog=./log.txt' 生成log
    8:'--junitxml=./result.xml' 生成xml报告
    9:'--html=./result.html' 生成html报告
'''
# pytest.main(['-m=smoke', 'test_demo_2.py'])   # 运行标签为 smoke 的用例
# pytest.main(['--maxfail=2', 'test_demo_2.py'])

## 4)指定目录:执行目录及子包的所有用例
# pytest.main(['pytest_basic'])

## 5)指定类:
# pytest.main(['test_demo_1.py::TestMethod'])

## 6)指定函数(函数名不需要带括号):
pytest.main(['test_demo_1.py::test_my_func'])

## 7)指定类下的方法
pytest.main(['test_demo_1.py::TestMethod::test_1'])

推荐阅读