新手区 pytest 有没有和 unittest 一样获取 testMethodName 的方法啊

小本淡淡 · 2018年09月13日 · 最后由 Rick_Zhang 回复于 2018年12月20日 · 1896 次阅读

最近在学习 pytest,需要获取每个测试函数的名字,在 unittest 里可以直接用 self._testMethodName 来方便的获取,pytest 有没有相似的方法啊

共收到 4 条回复 时间 点赞
def case_id(func):
    @wraps(func)
    def id(*args, **kwargs):
        log.info('Test case ID: %s ,time %s' % (func.__name__, now))
        return func(*args, **kwargs)
    return id

通过 Reporting hook 的 pytest_collectreport 方法来取

sys._getframe().f_code.co_name
或者 inspect 模块

fixture 函数可以传入 request 对象,通过 request._pyfuncitem.name 可以取到方法名,可以参考https://docs.pytest.org/en/latest/fixture.html#fixtures-can-introspect-the-requesting-test-context

小本淡淡 关闭了讨论 12月20日 10:17
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册