【问题标题】:Running unittest discover ignoring specific directory运行 unittest 发现忽略特定目录
【发布时间】:2016-09-06 21:56:28
【问题描述】:

我正在寻找一种运行 python -m unittest discover 的方法,它会在目录 A、B 和 C 中发现测试。但是,目录 A、B 和 C 中的每个目录都有名为 dependencies 的目录,其中也有一些测试,但是我不想运行。

有没有办法运行我的测试以满足这些约束,而无需为此创建脚本?

【问题讨论】:

    标签: python python-2.7 python-unittest


    【解决方案1】:

    我已经设法做到了(在 *NIX 中):

    find `pwd` -name '*_test.py' -not -path '*unwanted_path*' \
      | xargs python3 -m unittest -v
    

    也就是说,测试由find 发现,它允许路径模式排除等选项,然后将它们作为参数列表传递给unittest 命令。

    请注意,我必须切换到find pwd,通常我可以写find .,因为unittest 不接受./xxx 形式的相对路径(未找到模块)。

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题,最终能够找到这些方便的参数传递给 unittest discover 解决了我的问题。

      在此处记录:https://docs.python.org/2/library/unittest.html#test-discovery

      -s, --start-directory directory
      Directory to start discovery (. default)
      
      -p, --pattern pattern
      Pattern to match test files (test*.py default)
      

      所以我将我的命令修改为:

      python -m unittest discover -s test
      

      因为我真正想要运行的所有测试都在一个模块中,test.您还可以使用 -p 来在理论上匹配只匹配您的测试的正则表达式,而忽略它可能找到的所有其余部分。

      【讨论】:

        【解决方案3】:

        似乎python -m unittest 下降到模块目录而不是其他目录。

        它很快尝试了以下结构

        temp
          + a
          - test_1.py
          + dependencies
            - test_a.py
        

        有了结果

        >python -m unittest discover -s temp\a
        test_1
        .
        ----------------------------------------------------------------------
        Ran 1 test in 0.002s
        
        OK
        

        但是,如果目录是模块目录(包含文件__init__.py),情况就不同了。

        temp
        + a
          - __init__.py
          - test_1.py
          + dependencies
            - __init__.py
            - test_a.py
        

        结果是

        >python -m unittest discover -s temp\a
        test_a
        .test_1
        .
        ----------------------------------------------------------------------
        Ran 2 tests in 0.009s
        
        OK
        

        这个答案对您的有用性现在取决于您的文件夹dependencies 不是模块目录是否可以接受。

        编辑:看到您的评论后

        可以选择使用pytest 吗?这个测试运行器有许多命令参数,一个专门用于排除测试。

        见Changing standard (Python) test discovery

        来自他们的网站

        在测试收集期间忽略路径

        通过在 cli 上传递 --ignore=path 选项,您可以在收集过程中轻松忽略某些测试目录和模块。 pytest 允许多个--ignore 选项

        【讨论】:

        • 遗憾的是,它确实有一个__init__.py 文件,而且不能有任何不同:(
        猜你喜欢
        • 1970-01-01
        • 2017-05-10
        • 2016-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-15
        • 1970-01-01
        • 2023-03-05
        相关资源
        最近更新 更多