Pytest 入门学习

Pytest 测试框架使用简单、插件丰富、功能强大,被广泛用于 Python 自动化测试。本文主要介绍一些 Pytest 的基本概念和使用方法。

1. 运行机制

第一步,Pytest 从命令行或文件中读取配置第二步,在指定目录下查找并导入 conftest.py 文件第三步,查找满足匹配条件的测试文件,通常是 test_ 开头的 py 文件第四步,执行 session 或 module 类型的 fixture第四步,查找并执行类、函数中,定义的测试用例

2. pytest.ini 和 conftest.py 文件

首先看下测试的文件组织方式:

相关推荐

站点声明:本站部分内容转载自网络,作品版权归原作者及来源网站所有,任何内容转载、商业用途等均须联系原作者并注明来源。

相关侵权、举报、投诉及建议等,请发邮件至E-mail:service@mryunwei.com

回到顶部
1
2
3
4
5
6
7
8
/ -
  | - pytest.ini  # pytest 的配置文件
  | - tests
    |
    | - conftest.py  # 全局通用的配置和功能
    | - fun_module   # 某个模块的测试
          | - test_a.py  # 该模块下的测试
          | - conftest.py  # 该模块下通用的配置和功能
path/pytest.ini
path/setup.cfg     # must also contain [pytest] section to match
path/tox.ini       # must also contain [pytest] section to match
pytest.ini
...                # all the way down to the root
[pytest]
1. 指定测试目录
testpaths  = tests
1. 指定测试用例文件的命名格式
python_files = test_*.py
1. 指定 conftest 文件的路径
pytest_plugins = tests
def pytest_configure():
    pass
# pytest . -s
@pytest.fixture()
def remote_api():
    return 'success'

def test_remote_api(remote_api):
    assert remote_api == 'success'
import pytest

@pytest.fixture()
def before():
    pass

@pytest.mark.usefixtures("before")
def test_1():
    pass
@pytest.fixture(scope='function')
def func_scope():
    pass

@pytest.fixture(scope='module')
def mod_scope():
    pass

@pytest.fixture(scope='session')
def sess_scope():
    pass

@pytest.fixture(scope='class')
def class_scope():
    pass
import pytest

A = pytest.mark.A

@A
def test_A():
    assert True
@pytest.mark.parametrize('name',
                      ['12345',
                       'abcdef',
                       '0a1b2c3'])
def test_name_length(passwd):
    assert len(passwd) == 6
# pytest --cov=myproj tests/
import os

class UnixFS:

    @staticmethod
    def rm(filename):
        os.remove(filename)

def test_unix_fs(mocker):
    mocker.patch('os.remove')
    UnixFS.rm('file')
    os.remove.assert_called_once_with('file')
# pytest --html=report.html