You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何自动化可视化conftest.py中pytest fixtures与函数的调用关系?

解决pytest Fixture与依赖关系可视化的工具推荐

以下是几个能帮你梳理conftest.py中fixture、mock及导入函数交互关系的命令行工具,支持生成带箭头的2D调用图:

1. pytest-dependency-graph

  • 专为pytest生态设计,可直接解析conftest.py中的fixture依赖链
  • 命令行用法:安装后执行
    pytest --dependency-graph=fixture_graph.svg
    
    会生成SVG格式的可视化图,箭头清晰展示fixture之间的调用关系、mock对象与被mock函数的关联,完美适配多层级依赖场景。

2. pycallgraph

  • 虽非pytest专用,但能精准追踪fixture执行时的完整函数调用链
  • 命令行用法:安装后执行(替换为你的目标fixture)
    pycallgraph graphviz -- pytest -xvs your_test_module.py::target_fixture
    
    生成的图会包含fixture调用的所有内部函数、其他关联fixture的路径,适合聚焦单个fixture进行深度分析。

3. 自定义脚本 + Graphviz

  • 若需要高度定制化的输出,可自行编写脚本遍历conftest中的fixture,结合Graphviz生成图
  • 示例脚本(可扩展解析mock关联):
    import ast
    import graphviz
    
    def parse_fixture_dependencies(file_path):
        with open(file_path) as f:
            tree = ast.parse(f.read())
        fixtures = {}
        # 遍历AST提取fixture及其参数依赖
        for node in ast.walk(tree):
            if (isinstance(node, ast.FunctionDef) 
                and any(decorator.id == 'fixture' for decorator in node.decorator_list if hasattr(decorator, 'id'))):
                fixture_name = node.name
                # 提取fixture的参数(即依赖的其他fixture)
                dependencies = [arg.arg for arg in node.args.args]
                fixtures[fixture_name] = dependencies
        return fixtures
    
    def generate_dependency_graph(fixtures):
        dot = graphviz.Digraph(comment='Fixture Dependency Graph')
        for fixture, deps in fixtures.items():
            dot.node(fixture)
            for dep in deps:
                dot.edge(dep, fixture)
        # 生成SVG格式的图
        dot.render('custom_fixture_graph', format='svg')
    
    if __name__ == '__main__':
        fixture_deps = parse_fixture_dependencies('conftest.py')
        generate_dependency_graph(fixture_deps)
    
    运行脚本后会生成定制化的调用关系图,可根据需求添加解析mock、导入函数关联的逻辑。

额外提示

  • 若需要明确fixture的最终返回对象结构,可配合pytest -s运行单个fixture,打印返回值后结合可视化图分析流程。

内容的提问来源于stack exchange,提问作者Brandon Kieft

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 17:50:57