Python的unittest库如何匹配通过p参数传递的模式?

2024-10-08 18:22:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行以下命令,以仅运行位于名为test_CO2.py的文件中的测试

python3.7 -m unittest discover -s some_path/tests/ -p "*CO2*"

我的文件夹结构如下所示:

some_path/tests/
  CO2
    test_CO2.py
  battery
    test_battery.py
  tank
    test_tank.py

我想指定运行的测试。例如,如果我只想测试储罐和CO2代码,我该怎么做?我想通过以下正则表达式: \w*(CO2|tank)\w*.py找不到任何测试

我认为传递给-p选项的模式不接受正则表达式。那么,如何指定希望运行的测试


Tags: 文件pathpytest命令文件夹testssome
2条回答

通常,通过-p参数传递到unittest的所有内容都通过^{} method处理,然后调用函数链fnmatch()fnmatchcase()_compile_pattern()translate()来自^{} library

函数translate()将原始-p参数转换为正则表达式,然后用于名称匹配。

fnmatch()函数的文档说明:

Patterns are Unix shell style:
*       matches everything
?       matches any single character
[seq]   matches any character in seq
[!seq]  matches any char not in seq

据我所见,这就是它所能做到的程度所有其他字符都将转义,以便按字面进行匹配

示例:我将regexa|b作为模式传递。translate()函数返回形式为(?s:p\|m)\Z的最终正则表达式。管道字符在那里被转义

如果您特别好奇,请查看fnmatchlib的translate()函数here——如果您想知道将“glob-like”模式转换为最终正则表达式的确切过程

我从unittest中找到了绕过这个限制的方法

我可以使用python3.7 -m unittest path_to_some_test运行特定的测试

# take regex and find all files that match
# clean up results. i.e. remove './' from output
test_paths_result=()
test_paths=$(find . -regextype posix-extended -regex "${regex}")
for file_path in ${test_paths}; do
  # save clean results to array variable
  test_paths_result+=("${file_path:2}")
done

echo "Running test files that match the following expression: '${regex}'"
python3.7 -m unittest ${test_paths_result[@]}

相关问题 更多 >

    热门问题