美文网首页
pytest插件探索——pytest-repeat

pytest插件探索——pytest-repeat

作者: 小餐包 | 来源:发表于2019-03-13 13:45 被阅读0次

简介

pytest-repeat允许用户重复执行单个用例或多个测试用例,并指定重复次数。提供marker功能,允许单独指定某些测试用例的执行次数。

GitHub地址:https://github.com/pytest-dev/pytest-repeat

源码解析:

pytest-repeat.py:

pytest_addoption(parser): 添加一个command line的option

def pytest_addoption(parser):
    parser.addoption(
        '--count',
        action='store',
        default=1,
        type=int,
        help='Number of times to repeat each test')

pytest_configure(config): 一般用来注册marker,这样当用户使用pytest --markers就能了解有哪些可用的marker了,如果不加这个hook,本身功能上没什么影响,只是规范的建议做法。

def pytest_configure(config):
    config.addinivalue_line(
        'markers',
        'repeat(n): run the given test function `n` times.')

pytest_generate_tests(metafunc): 参数化生成test case的hook

@pytest.fixture(autouse=True)
def __pytest_repeat_step_number(request):
    if request.config.option.count > 1:
        try:
            return request.param
        except AttributeError:
            if issubclass(request.cls, TestCase):
                warnings.warn(
                    "Repeating unittest class tests not supported")
            else:
                raise UnexpectedError(
                    "This call couldn't work with pytest-repeat. "
                    "Please consider raising an issue with your usage.")


@pytest.hookimpl(trylast=True)
def pytest_generate_tests(metafunc):
    count = metafunc.config.option.count
    m = metafunc.definition.get_closest_marker('repeat')
    if m is not None:
        count = int(m.args[0])
    if count > 1:
        def make_progress_id(i, n=count):
            return '{0}-{1}'.format(i + 1, n)

        scope = metafunc.config.option.repeat_scope
        metafunc.parametrize(
            '__pytest_repeat_step_number',
            range(count),
            indirect=True,
            ids=make_progress_id,
            scope=scope
        )

config.option.xx和marker.args[n]或者marker.kwargs(xx)优先级处理代码:

count = metafunc.config.option.count
m = metafunc.definition.get_closest_marker('repeat')
if m is not None:
    count = int(m.args[0])
if count > 1:
     # do something here

利用parametrize fixture的hook function生成repeat的test case items:

    metafunc.parametrize(
        '__pytest_repeat_step_number',
        range(count),
        indirect=True,
        ids=make_progress_id,
        scope=scope
    )

相关文章

网友评论

      本文标题:pytest插件探索——pytest-repeat

      本文链接:https://www.haomeiwen.com/subject/hpizpqtx.html