Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python';通过-p参数传递的unittest库匹配模式?_Python_Regex_Python 3.x_Python Unittest - Fatal编程技术网

Python';通过-p参数传递的unittest库匹配模式?

Python';通过-p参数传递的unittest库匹配模式?,python,regex,python-3.x,python-unittest,Python,Regex,Python 3.x,Python Unittest,我正在运行以下命令,以仅运行名为test\u CO2.py的文件中的测试 python3.7-m单元测试发现-s一些路径/测试/-p“*CO2*” 我的文件夹结构如下所示: some_path/tests/ CO2 test_CO2.py battery test_battery.py tank test_tank.py 我想指定运行的测试。例如,如果我只想测试储罐和CO2代码,我该怎么做?我想通过以下正则表达式: 未能找到任何测试的\w*(CO2 |储罐)

我正在运行以下命令,以仅运行名为
test\u CO2.py的文件中的测试

python3.7-m单元测试发现-s一些路径/测试/-p“*CO2*”

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

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


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

通常,通过
-p
参数传递到
unittest
的所有内容都会通过该参数进行处理,然后调用函数链
fnmatch()
→ <代码>fnmatchcase()
→ <代码>\u编译\u模式()→ <代码>翻译()from

函数将原始的
-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
据我所见,这就是它所能做到的程度所有其他字符都将转义,以便按字面进行匹配

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


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

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

我可以使用
python3.7-m单元测试路径运行特定的测试

# 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[@]}

值得一提的是,这是
unittest
解析
-p
参数,而不是核心Python。这些通常是通过globbing完成的,而不是regex。