代码之家  ›  专栏  ›  技术社区  ›  bigreddot

如何在顶级conftest之外添加pytest选项?

  •  0
  • bigreddot  · 技术社区  · 7 年前

    我有一个项目,它定义了测试支持模块,包括包子目录中的py.test插件,如下所示:

    bokeh/_testing
    ├── __init__.py
    ├── plugins
    │   ├── __init__.py
    │   ├── bokeh_server.py
    │   ├── examples_report.jinja
    │   ├── examples_report.py
    │   ├── file_server.py
    │   ├── implicit_mark.py
    │   ├── integration_tests.py
    │   ├── jupyter_notebook.py
    │   ├── log_file.py
    │   └── pandas.py
    └── util
        ├── __init__.py
        ├── api.py
        ├── examples.py
        ├── filesystem.py
        ├── git.py
        └── travis.py
    

    几个插件需要定义新的选项 parser.addoption .我希望这些调用在各自的插件模块内进行。但是,如果我这样做了,并且在测试文件中包含这些插件,例如。

    # test_examples.py
    pytest_plugins = (
        "bokeh.testing.plugins.bokeh_server",
        "bokeh.testing.plugins.examples_report",
    )
    
    # pytest.mark.examples test code here 
    

    然后pytest抱怨任何自定义命令行选项都未定义:

    (base) ❯ py.test -s -v -m examples --diff-ref FETCH_HEAD --report-path=examples.html
    usage: py.test [options] [file_or_dir] [file_or_dir] [...]
    py.test: error: unrecognized arguments: --diff-ref --report-path=examples.html
      inifile: /Users/bryanv/work/bokeh/setup.cfg
      rootdir: /Users/bryanv/work/bokeh
    

    我找到的唯一办法就是 全部 单个自定义选项 pytest_addoption 在最高层 conftest.py 以下内容:

    # conftest.py
    pytest_plugins = (
        "bokeh.testing.plugins.implicit_mark",
        "bokeh.testing.plugins.pandas",
    )
    
    # Unfortunately these seem to all need to be centrally defined at the top level
    def pytest_addoption(parser):
        parser.addoption(
            "--upload", dest="upload", action="store_true", default=False, help="..."
        )
    
        # ... ALL other addoptions calls for all plugins here ...
    

    正如我所说,这是有效的,但是在代码组织方面是非常不灵活的。最好有一种方法来选择 examples.py 插件到 在里面 这个 示例.py 模块,以及与之相关的代码。

    另一种可能是把所有的插件都放在顶层 conftest.py确认 ,但是有些插件非常重,例如依赖于selenium,我不想要求安装所有插件只是为了运行基本测试。

    有没有其他方法来实现这一点,如果有,如何实现?

    1 回复  |  直到 7 年前
        1
  •  1
  •   bigreddot    7 年前

    如上所述,从pytest开始 3.6.2 ,必须添加选项 “由于pytest在启动期间如何发现插件,因此只能在位于tests根目录的plugins或conftest.py文件中。”