运行 单元测试发现忽略特定目录

Running unittest discover ignoring specific directory

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

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

似乎 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

来自他们的网站

Ignore paths during test collection

You can easily ignore certain test directories and modules during collection by passing the --ignore=path option on the cli. pytest allows multiple --ignore options

我 运行 遇到了同样的问题,并最终能够找到这些方便的参数传递给 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

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

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

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

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

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