如何对文件中的正则表达式样本进行单元测试?
自动检测文件中不匹配行的单元测试实现
背景信息
待检查的test.txt内容如下:
evince /media/ismail/SSDWorking/book-collection/_Books/kids/Coping Skills.pdf /usr/lib/libreoffice/program/soffice.bin --impress file:///home/ismail/Desktop/LibreOffice%20Impress.odp --splash-pipe=5 /usr/bin/gjs /usr/bin/com.github.johnfactotum.Foliate /media/ismail/SSDWorking/book-collection/_Books/kids/Coping Skills.epub mpv /media/ismail/8TBRaid0/_IslamNaseed/_JunaidJamshed/Mera Dil Badal De.mp3 evince /media/ismail/SSDWorking/book-collection/_Books/self-development-anxiety-self-talk/child/Freeing Your Child From Negative Thinking Powerful, Practical Strategies to Build a Lifetime of Resilience, Flexibility, and... (Tamar E. Chansky) My Library).pdf --splash-pipe=5 This is the line that does not match. /usr/bin/gjs /usr/bin/com.github.johnfactotum.Foliate /media/ismail/SSDWorking/book-collection/_Books/self-development-anxiety-self-talk/child/Freeing Your Child from Anxiety Powerful, Practical Solutions to Overcome Your Childs Fears, Worries, and Phobias (Tamar Chansky Ph.D.) (My Library).epub
用于识别不匹配行的grep命令:
grep -nvP '(file://)?(?<!\w)/(?!usr/).*?\.\w{3,4}+' test.txt
实现方案
可以编写一个Shell脚本作为单元测试,自动检测不匹配行并返回对应状态:
测试脚本代码
创建名为test_valid_lines.sh的脚本,内容如下:
#!/bin/bash # 配置参数 TEST_FILE="test.txt" VALID_PATTERN='(file://)?(?<!\w)/(?!usr/).*?\.\w{3,4}+' # 获取所有不匹配的行(带行号) invalid_entries=$(grep -nvP "$VALID_PATTERN" "$TEST_FILE") # 判断结果并输出 if [ -n "$invalid_entries" ]; then echo "❌ 测试失败!发现不符合格式的行:" echo "$invalid_entries" exit 1 # 返回非零状态码,表示测试失败 else echo "✅ 测试通过!所有行均符合格式要求。" exit 0 # 返回零状态码,表示测试成功 fi
使用步骤
- 给脚本添加执行权限:
chmod +x test_valid_lines.sh - 运行测试:
./test_valid_lines.sh
效果说明
- 当文件中存在不匹配行时,脚本会打印出行号和内容,并且以状态码
1退出(测试失败) - 当所有行都匹配规则时,脚本输出测试通过,以状态码
0退出(测试成功) - 该脚本可以直接集成到自动化测试流程中,CI/CD工具会根据退出码自动判断测试结果
内容的提问来源于stack exchange,提问作者Ahmad Ismail
相关产品推荐
相关产品推荐

