You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为自定义Homebrew Formula编写测试?附示例参考

为你的Match Homebrew Formula编写测试

你已经完成了本地可用的match工具Formula和对应的Ruby脚本,现在需要编写测试来满足homebrew-core的提交要求。结合你提供的示例测试逻辑,我们可以围绕工具的核心功能设计几个关键测试用例,下面是完整的实现方案:


先明确你的脚本行为

测试的前提是清楚工具的预期输出,先梳理你的match脚本的核心逻辑:

  • 无参数调用时,输出usage: match <keyword>并退出
  • 传入关键词后,遍历当前目录的所有文件和目录:
    • 遇到目录:输出[目录名]_ found directory,随后输出分隔符***
    • 遇到文件:逐行搜索关键词,找到匹配行时输出[文件名]_ [行号] [匹配行内容],文件处理完后如果有匹配,输出***
    • 无匹配内容的文件:不会输出任何内容(除了目录的处理)

完整的测试代码

把下面的代码添加到你的Match Formula的test块中:

class Match < Formula
  desc "Browse all files inside any directory for a keyword"
  homepage "https://github.com/aatalyk/homebrew-match"
  url "你的项目源码URL" # 记得填充实际URL
  sha256 "对应的sha256哈希值" # 记得填充实际哈希

  def install
    bin.install "match"
  end

  test do
    # 测试用例1:无参数调用,验证使用提示
    output = shell_output("#{bin}/match 2>&1")
    assert_match "usage: match <keyword>", output

    # 测试用例2:创建测试环境,验证关键词匹配功能
    # 创建包含目标关键词的测试文件
    (testpath/"sample.txt").write <<~CONTENT
      First line of sample
      This line contains the target_keyword we're searching for
      Final line
    CONTENT
    # 创建一个测试目录
    testpath.mkdir("test_folder")

    # 调用工具并捕获输出
    match_output = shell_output("#{bin}/match target_keyword")
    # 验证匹配内容的输出格式正确
    assert_match "sample.txt_ 2 This line contains the target_keyword we're searching for", match_output
    # 验证分隔符***存在
    assert_match "***", match_output
    # 验证目录的处理输出正确
    assert_match "test_folder_ found directory", match_output

    # 测试用例3:搜索不存在的关键词,验证无匹配输出
    no_match_output = shell_output("#{bin}/match non_existent_term")
    # 确认没有文件匹配的输出
    refute_match "sample.txt_", no_match_output
    # 目录的处理输出依然正常显示
    assert_match "test_folder_ found directory", no_match_output
  end
end

测试用例解释

每个测试用例都针对工具的一个核心场景:

  1. 无参数提示测试:确保用户未传关键词时,工具能给出清晰的使用指引,符合脚本的逻辑。
  2. 匹配成功测试:利用Homebrew提供的testpath临时目录,创建模拟的文件和目录,验证工具能正确识别匹配内容,并输出符合预期的格式。
  3. 匹配失败测试:验证当搜索的关键词不存在时,工具不会输出错误内容,同时仍能正确处理目录。

额外注意事项

  • 务必填充Formula里的url和sha256字段,否则Homebrew无法拉取源码进行测试和安装。
  • testpath是Homebrew自动创建的临时工作目录,每次测试都会重置,不用担心干扰系统或其他文件。
  • 如果你的脚本需要处理特殊情况(比如空文件、二进制文件),可以额外添加测试用例,比如创建空文件并调用工具,确保不会抛出错误。

内容的提问来源于stack exchange,提问作者Atalyk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:20:15