将命令行参数与 pytest --pyargs 一起使用 [英] Using Command Line Parameters with pytest --pyargs

查看:90
本文介绍了将命令行参数与 pytest --pyargs 一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经为我使用如下结构编写的包编写了 pytest 单元测试:

I have written pytest unit tests for a package I've written with a structure like below:

  • 包目录
    • setup.py
    • 我的包裹
      • __init__.py
      • 功能包
        • __init__.py
        • functionmodule.py
        • __init__.py
        • conftest.py
        • unit_tests
          • __init__.py
          • functionmodule_test.py

          现在 packagedir/mypackage/test/conftest.py 建立了两个必需的命令行参数,以作为测试的夹具.当我运行类似:

          Now packagedir/mypackage/test/conftest.py establishes two required command line parameters to be created as fixtures for the tests. When I run something like:

          pytest packagedir/mypackage/ --var1 foo --var2 bar
          

          所有测试都运行并且命令行参数被正确读入.但是,当我 pip install 包(它正确安装 test 和 unit_tests 包)然后尝试这样的事情时:

          All the tests run and the command line parameters are read in correctly. However, when I pip install the package (which installs the test and unit_tests packages correctly) and then try something like this:

          pytest --pyargs mypackage --var1 foo --var2 bar
          

          我收到这样的错误:

          usage: pytest [options] [file_or_dir] [file_or_dir] [...]
          pytest: error: unrecognized arguments: --var1 foo --var2 bar
          

          如果我跑:

          pytest --pyargs mypackage
          

          测试运行但失败,因为命令行参数不存在.

          the tests run but fail because the command line arguments are not present.

          有人可以向我解释这里可能出了什么问题吗?我可以猜测并说这是因为 --pyargs 参数改变了 pytest 的命令行参数的解释,但这只是一个猜测.我想知道是否有实际的方法可以解决这个问题.

          Can someone explain to me what might be going wrong here? I could guess and say this is because the --pyargs argument changes the interpretation of the command line parameters for pytest, but it's just a guess. I'd like to know if there is an actual way I could fix this.

          总体目标是允许某人通过 pip install mypackage 进行安装,然后无需导航到安装的站点包位置即可轻松对其进行测试.

          推荐答案

          我在mypackage/test目录下添加了一个__main__.py并写了

          I added a __main__.py to the mypackage/test directory and wrote

          import os
          import sys
          
          HERE = os.path.dirname(__file__)
          
          if __name__ == "__main__":
              import pytest
              errcode = pytest.main([HERE] + sys.argv[1:])
              sys.exit(errcode)
          

          现在,我可以用

          python -m mypackage.test --myoption=works
          

          这在安装包时有效.

          您可以使用 travis 构建查看此操作:

          You can view this in action with a travis build:

          这篇关于将命令行参数与 pytest --pyargs 一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆