repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/tap_auditor_spec.rb | Library/Homebrew/test/tap_auditor_spec.rb | # frozen_string_literal: true
require "tap_auditor"
RSpec.describe Homebrew::TapAuditor do
let(:tap) { Tap.fetch("homebrew", "foo") }
let(:tap_path) { tap.path }
let(:auditor) { described_class.new(tap, strict: false) }
def write_cask(token, path = tap_path/"Casks"/"#{token}.rb")
path.dirname.mkpath
path.write <<~RUBY
cask "#{token}" do
version "1.0"
url "https://brew.sh/#{token}-1.0.dmg"
name "#{token.capitalize} Cask"
homepage "https://brew.sh"
end
RUBY
end
def write_formula(name, path = tap_path/"Formula"/"#{name}.rb")
path.dirname.mkpath
path.write <<~RUBY
class #{name.capitalize} < Formula
url "https://brew.sh/#{name}-1.0.tar.gz"
version "1.0"
end
RUBY
end
before do
tap_path.mkpath
tap.clear_cache
end
describe "#audit" do
subject(:problems) do
auditor.audit
auditor.problems
end
context "with cask_renames.json" do
let(:cask_renames_path) { tap_path/"cask_renames.json" }
let(:renames_data) { {} }
before do
cask_renames_path.write JSON.pretty_generate(renames_data)
end
context "when .rb extension in old cask name (key)" do
let(:renames_data) { { "oldcask.rb" => "newcask" } }
before do
write_cask("newcask")
end
it "detects the invalid format" do
expect(problems.count).to eq(1)
expect(problems.first[:message]).to eq(
<<~EOS,
cask_renames.json contains entries with '.rb' file extensions.
Rename entries should use formula/cask names only, without '.rb' extensions.
Invalid entries: "oldcask.rb": "newcask"
EOS
)
end
end
context "when .rb extension in new cask name (value)" do
let(:renames_data) { { "oldcask" => "newcask.rb" } }
before do
write_cask("newcask")
end
it "detects the invalid format" do
expect(problems.count).to eq(2)
invalid_format_problem = problems.find do |p|
p[:message].include?("entries with '.rb' file extensions")
end
expect(invalid_format_problem[:message]).to eq(
<<~EOS,
cask_renames.json contains entries with '.rb' file extensions.
Rename entries should use formula/cask names only, without '.rb' extensions.
Invalid entries: "oldcask": "newcask.rb"
EOS
)
invalid_target_problem = problems.find do |p|
p[:message].include?("Invalid targets")
end
expect(invalid_target_problem[:message]).to eq(
<<~EOS,
cask_renames.json contains renames to casks that do not exist in the homebrew/foo tap.
Invalid targets: newcask.rb
EOS
)
end
end
context "when missing target cask" do
let(:renames_data) { { "oldcask" => "nonexistent" } }
it "detects the missing target" do
expect(problems.count).to eq(1)
expect(problems.first[:message]).to eq(
<<~EOS,
cask_renames.json contains renames to casks that do not exist in the homebrew/foo tap.
Invalid targets: nonexistent
EOS
)
end
end
context "with chained renames" do
let(:renames_data) do
{
"oldcask" => "newcask",
"newcask" => "finalcask",
}
end
before do
write_cask("finalcask")
end
it "detects the chained renames" do
expect(problems.count).to eq(1)
expect(problems.first[:message]).to eq(
<<~EOS,
cask_renames.json contains chained renames that should be collapsed.
Chained renames don't work automatically; each old name should point directly to the final target:
"oldcask": "finalcask" (instead of chained rename)
EOS
)
end
end
context "with multi-level chained renames" do
let(:renames_data) do
{
"oldcask" => "newcask",
"newcask" => "intermediatecask",
"intermediatecask" => "finalcask",
}
end
before do
write_cask("intermediatecask")
write_cask("finalcask")
end
it "suggests final target" do
expect(problems.count).to eq(2)
chained_problem = problems.find { |p| p[:message].include?("chained renames") }
expect(chained_problem[:message]).to eq(
<<~EOS,
cask_renames.json contains chained renames that should be collapsed.
Chained renames don't work automatically; each old name should point directly to the final target:
"oldcask": "finalcask" (instead of chained rename)
"newcask": "finalcask" (instead of chained rename)
EOS
)
conflict_problem = problems.find { |p| p[:message].include?("conflict") }
expect(conflict_problem[:message]).to eq(
<<~EOS,
cask_renames.json contains old names that conflict with existing casks in the homebrew/foo tap.
Renames only work after the old casks are deleted. Conflicting names: intermediatecask
EOS
)
end
end
context "with chained renames where intermediates don't exist" do
let(:renames_data) do
{
"veryoldcask" => "intermediatecask",
"intermediatecask" => "finalcask",
}
end
before do
write_cask("finalcask")
end
it "reports chained rename error, not invalid target error" do
expect(problems.count).to eq(1)
expect(problems.first[:message]).to eq(
<<~EOS,
cask_renames.json contains chained renames that should be collapsed.
Chained renames don't work automatically; each old name should point directly to the final target:
"veryoldcask": "finalcask" (instead of chained rename)
EOS
)
end
end
context "when old name conflicts with existing cask" do
let(:renames_data) { { "newcask" => "anothercask" } }
before do
write_cask("newcask")
write_cask("anothercask")
end
it "detects the conflict" do
expect(problems.count).to eq(1)
expect(problems.first[:message]).to eq(
<<~EOS,
cask_renames.json contains old names that conflict with existing casks in the homebrew/foo tap.
Renames only work after the old casks are deleted. Conflicting names: newcask
EOS
)
end
end
context "with correct rename entries" do
let(:renames_data) { { "oldcask" => "newcask" } }
before do
write_cask("newcask")
end
it "passes validation" do
rename_problems = problems.select { |p| p[:message].include?("cask_renames") }
expect(rename_problems).to be_empty
end
end
end
context "with formula_renames.json" do
let(:formula_renames_path) { tap_path/"formula_renames.json" }
let(:renames_data) { {} }
before do
formula_renames_path.write JSON.pretty_generate(renames_data)
end
context "when .rb extension in formula rename keys" do
let(:renames_data) { { "oldformula.rb" => "newformula" } }
before do
write_formula("newformula")
end
it "detects the invalid format" do
expect(problems.count).to eq(1)
expect(problems.first[:message]).to eq(
<<~EOS,
formula_renames.json contains entries with '.rb' file extensions.
Rename entries should use formula/cask names only, without '.rb' extensions.
Invalid entries: "oldformula.rb": "newformula"
EOS
)
end
end
context "with chained formula renames" do
let(:renames_data) do
{
"oldformula" => "newformula",
"newformula" => "finalformula",
}
end
before do
write_formula("finalformula")
end
it "detects the chained renames" do
expect(problems.count).to eq(1)
expect(problems.first[:message]).to eq(
<<~EOS,
formula_renames.json contains chained renames that should be collapsed.
Chained renames don't work automatically; each old name should point directly to the final target:
"oldformula": "finalformula" (instead of chained rename)
EOS
)
end
end
context "with correct formula rename entries" do
let(:renames_data) { { "oldformula" => "newformula" } }
before do
write_formula("newformula")
end
it "passes validation" do
rename_problems = problems.select { |p| p[:message].include?("formula_renames") }
expect(rename_problems).to be_empty
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/formula_spec.rb | Library/Homebrew/test/formula_spec.rb | # frozen_string_literal: true
require "test/support/fixtures/testball"
require "formula"
PHASES = [:build, :postinstall, :test].freeze
RSpec.describe Formula do
alias_matcher :follow_installed_alias, :be_follow_installed_alias
alias_matcher :have_any_version_installed, :be_any_version_installed
alias_matcher :need_migration, :be_migration_needed
alias_matcher :have_changed_installed_alias_target, :be_installed_alias_target_changed
alias_matcher :supersede_an_installed_formula, :be_supersedes_an_installed_formula
alias_matcher :have_changed_alias, :be_alias_changed
alias_matcher :have_option_defined, :be_option_defined
alias_matcher :have_post_install_defined, :be_post_install_defined
alias_matcher :have_test_defined, :be_test_defined
alias_matcher :pour_bottle, :be_pour_bottle
describe "::new" do
let(:klass) do
Class.new(described_class) do
url "https://brew.sh/foo-1.0.tar.gz"
end
end
let(:name) { "formula_name" }
let(:path) { Formulary.core_path(name) }
let(:spec) { :stable }
let(:alias_name) { "baz@1" }
let(:alias_path) { CoreTap.instance.alias_dir/alias_name }
let(:f) { klass.new(name, path, spec) }
let(:f_alias) { klass.new(name, path, spec, alias_path:) }
specify "formula instantiation" do
expect(f.name).to eq(name)
expect(f.specified_name).to eq(name)
expect(f.full_name).to eq(name)
expect(f.full_specified_name).to eq(name)
expect(f.path).to eq(path)
expect(f.alias_path).to be_nil
expect(f.alias_name).to be_nil
expect(f.full_alias_name).to be_nil
expect(f.specified_path).to eq(path)
[:build, :test, :postinstall].each { |phase| expect(f.network_access_allowed?(phase)).to be(true) }
expect { klass.new }.to raise_error(ArgumentError)
end
specify "formula instantiation with alias" do
expect(f_alias.name).to eq(name)
expect(f_alias.full_name).to eq(name)
expect(f_alias.path).to eq(path)
expect(f_alias.alias_path).to eq(alias_path)
expect(f_alias.alias_name).to eq(alias_name)
expect(f_alias.specified_name).to eq(alias_name)
expect(f_alias.specified_path).to eq(Pathname(alias_path))
expect(f_alias.full_alias_name).to eq(alias_name)
expect(f_alias.full_specified_name).to eq(alias_name)
[:build, :test, :postinstall].each { |phase| expect(f_alias.network_access_allowed?(phase)).to be(true) }
expect { klass.new }.to raise_error(ArgumentError)
end
specify "formula instantiation without a subclass" do
expect { described_class.new(name, path, spec) }
.to raise_error(RuntimeError, "Do not call `Formula.new' directly without a subclass.")
end
context "when in a Tap" do
let(:tap) { Tap.fetch("foo", "bar") }
let(:path) { (tap.path/"Formula/#{name}.rb") }
let(:full_name) { "#{tap.user}/#{tap.repository}/#{name}" }
let(:full_alias_name) { "#{tap.user}/#{tap.repository}/#{alias_name}" }
specify "formula instantiation" do
expect(f.name).to eq(name)
expect(f.specified_name).to eq(name)
expect(f.full_name).to eq(full_name)
expect(f.full_specified_name).to eq(full_name)
expect(f.path).to eq(path)
expect(f.alias_path).to be_nil
expect(f.alias_name).to be_nil
expect(f.full_alias_name).to be_nil
expect(f.specified_path).to eq(path)
expect { klass.new }.to raise_error(ArgumentError)
end
specify "formula instantiation with alias" do
expect(f_alias.name).to eq(name)
expect(f_alias.full_name).to eq(full_name)
expect(f_alias.path).to eq(path)
expect(f_alias.alias_path).to eq(alias_path)
expect(f_alias.alias_name).to eq(alias_name)
expect(f_alias.specified_name).to eq(alias_name)
expect(f_alias.specified_path).to eq(Pathname(alias_path))
expect(f_alias.full_alias_name).to eq(full_alias_name)
expect(f_alias.full_specified_name).to eq(full_alias_name)
expect { klass.new }.to raise_error(ArgumentError)
end
end
end
describe "#follow_installed_alias?" do
let(:f) do
formula do
url "foo-1.0"
end
end
it "returns true by default" do
expect(f).to follow_installed_alias
end
it "can be set to true" do
f.follow_installed_alias = true
expect(f).to follow_installed_alias
end
it "can be set to false" do
f.follow_installed_alias = false
expect(f).not_to follow_installed_alias
end
end
describe "#versioned_formula?" do
let(:f) do
formula "foo" do
url "foo-1.0"
end
end
let(:f2) do
formula "foo@2.0" do
url "foo-2.0"
end
end
it "returns true for @-versioned formulae" do
expect(f2.versioned_formula?).to be true
end
it "returns false for non-@-versioned formulae" do # rubocop:todo RSpec/AggregateExamples
expect(f.versioned_formula?).to be false
end
end
describe "#versioned_formulae" do
let(:f) do
formula "foo" do
url "foo-1.0"
end
end
let(:f2) do
formula "foo@2.0" do
url "foo-2.0"
end
end
before do
# don't try to load/fetch gcc/glibc
allow(DevelopmentTools).to receive_messages(needs_libc_formula?: false, needs_compiler_formula?: false)
allow(Formulary).to receive(:load_formula_from_path).with(f2.name, f2.path).and_return(f2)
allow(Formulary).to receive(:factory).with(f2.name).and_return(f2)
allow(f).to receive(:versioned_formulae_names).and_return([f2.name])
end
it "returns array with versioned formulae" do
FileUtils.touch f.path
FileUtils.touch f2.path
expect(f.versioned_formulae).to eq [f2]
end
it "returns empty array for non-@-versioned formulae" do
FileUtils.touch f.path
FileUtils.touch f2.path
expect(f2.versioned_formulae).to be_empty
end
end
example "installed alias with core" do
f = formula do
url "foo-1.0"
end
build_values_with_no_installed_alias = [
BuildOptions.new(Options.new, f.options),
Tab.new(source: { "path" => f.path.to_s }),
]
build_values_with_no_installed_alias.each do |build|
f.build = build
expect(f.installed_alias_path).to be_nil
expect(f.installed_alias_name).to be_nil
expect(f.full_installed_alias_name).to be_nil
expect(f.installed_specified_name).to eq(f.name)
expect(f.full_installed_specified_name).to eq(f.name)
end
alias_name = "bar"
alias_path = CoreTap.instance.alias_dir/alias_name
CoreTap.instance.alias_dir.mkpath
FileUtils.ln_sf f.path, alias_path
f.build = Tab.new(source: { "path" => alias_path.to_s })
expect(f.installed_alias_path).to eq(alias_path)
expect(f.installed_alias_name).to eq(alias_name)
expect(f.full_installed_alias_name).to eq(alias_name)
expect(f.installed_specified_name).to eq(alias_name)
expect(f.full_installed_specified_name).to eq(alias_name)
end
example "installed alias with tap" do
tap = Tap.fetch("user", "repo")
name = "foo"
path = tap.path/"Formula/#{name}.rb"
f = formula(name, path:) do
url "foo-1.0"
end
build_values_with_no_installed_alias = [
BuildOptions.new(Options.new, f.options),
Tab.new(source: { "path" => f.path.to_s }),
]
build_values_with_no_installed_alias.each do |build|
f.build = build
expect(f.installed_alias_path).to be_nil
expect(f.installed_alias_name).to be_nil
expect(f.full_installed_alias_name).to be_nil
expect(f.installed_specified_name).to eq(f.name)
expect(f.full_installed_specified_name).to eq(f.full_name)
end
alias_name = "bar"
alias_path = tap.alias_dir/alias_name
full_alias_name = "#{tap.user}/#{tap.repository}/#{alias_name}"
tap.alias_dir.mkpath
FileUtils.ln_sf f.path, alias_path
f.build = Tab.new(source: { "path" => alias_path.to_s })
expect(f.installed_alias_path).to eq(alias_path)
expect(f.installed_alias_name).to eq(alias_name)
expect(f.full_installed_alias_name).to eq(full_alias_name)
expect(f.installed_specified_name).to eq(alias_name)
expect(f.full_installed_specified_name).to eq(full_alias_name)
FileUtils.rm_rf HOMEBREW_LIBRARY/"Taps/user"
end
specify "#prefix" do
f = Testball.new
expect(f.prefix).to eq(HOMEBREW_CELLAR/f.name/"0.1")
expect(f.prefix).to be_a(Pathname)
end
example "revised prefix" do
f = Class.new(Testball) { revision(1) }.new
expect(f.prefix).to eq(HOMEBREW_CELLAR/f.name/"0.1_1")
end
example "compatibility_version" do
f = Class.new(Testball) { compatibility_version(1) }.new
expect(f.class.compatibility_version).to eq(1)
end
specify "#any_version_installed?" do
f = formula do
url "foo"
version "1.0"
end
expect(f).not_to have_any_version_installed
prefix = HOMEBREW_CELLAR/f.name/"0.1"
prefix.mkpath
FileUtils.touch prefix/AbstractTab::FILENAME
expect(f).to have_any_version_installed
end
specify "#migration_needed" do
f = Testball.new("newname")
f.instance_variable_set(:@oldnames, ["oldname"])
f.instance_variable_set(:@tap, CoreTap.instance)
oldname_prefix = (HOMEBREW_CELLAR/"oldname/2.20")
newname_prefix = (HOMEBREW_CELLAR/"newname/2.10")
oldname_prefix.mkpath
oldname_tab = Tab.empty
oldname_tab.tabfile = oldname_prefix/AbstractTab::FILENAME
oldname_tab.write
expect(f).not_to need_migration
oldname_tab.tabfile.unlink
oldname_tab.source["tap"] = "homebrew/core"
oldname_tab.write
expect(f).to need_migration
newname_prefix.mkpath
expect(f).not_to need_migration
end
describe "#latest_version_installed?" do
let(:f) { Testball.new }
it "returns false if the #latest_installed_prefix is not a directory" do
allow(f).to receive(:latest_installed_prefix).and_return(instance_double(Pathname, directory?: false))
expect(f).not_to be_latest_version_installed
end
it "returns false if the #latest_installed_prefix does not have children" do
allow(f).to receive(:latest_installed_prefix)
.and_return(instance_double(Pathname, directory?: true, children: []))
expect(f).not_to be_latest_version_installed
end
it "returns true if the #latest_installed_prefix has children" do
allow(f).to receive(:latest_installed_prefix)
.and_return(instance_double(Pathname, directory?: true, children: [double]))
expect(f).to be_latest_version_installed
end
end
describe "#latest_installed_prefix" do
let(:f) do
formula do
url "foo"
version "1.9"
head "foo"
end
end
let(:stable_prefix) { HOMEBREW_CELLAR/f.name/f.version }
let(:head_prefix) { HOMEBREW_CELLAR/f.name/f.head.version }
it "is the same as #prefix by default" do
expect(f.latest_installed_prefix).to eq(f.prefix)
end
it "returns the stable prefix if it is installed" do
stable_prefix.mkpath
expect(f.latest_installed_prefix).to eq(stable_prefix)
end
it "returns the head prefix if it is installed" do
head_prefix.mkpath
expect(f.latest_installed_prefix).to eq(head_prefix)
end
it "returns the stable prefix if head is outdated" do
head_prefix.mkpath
tab = Tab.empty
tab.tabfile = head_prefix/AbstractTab::FILENAME
tab.source["versions"] = { "stable" => "1.0" }
tab.write
expect(f.latest_installed_prefix).to eq(stable_prefix)
end
it "returns the head prefix if the active specification is :head" do
f.active_spec = :head
expect(f.latest_installed_prefix).to eq(head_prefix)
end
end
describe "#latest_head_prefix" do
let(:f) { Testball.new }
it "returns the latest head prefix" do
stamps_with_revisions = [
[111111, 1],
[222222, 0],
[222222, 1],
[222222, 2],
]
stamps_with_revisions.each do |stamp, revision|
version = "HEAD-#{stamp}"
version = "#{version}_#{revision}" unless revision.zero?
prefix = f.rack/version
prefix.mkpath
tab = Tab.empty
tab.tabfile = prefix/AbstractTab::FILENAME
tab.source_modified_time = stamp
tab.write
end
prefix = HOMEBREW_CELLAR/f.name/"HEAD-222222_2"
expect(f.latest_head_prefix).to eq(prefix)
end
end
specify "equality" do
x = Testball.new
y = Testball.new
expect(x).to eq(y)
expect(x).to eql(y)
expect(x.hash).to eq(y.hash)
end
specify "inequality" do
x = Testball.new("foo")
y = Testball.new("bar")
expect(x).not_to eq(y)
expect(x).not_to eql(y)
expect(x.hash).not_to eq(y.hash)
end
specify "comparison with non formula objects does not raise" do
expect(Object.new).not_to eq(Testball.new)
end
specify "#<=>" do
expect(Testball.new <=> Object.new).to be_nil
end
describe "#installed_alias_path" do
example "alias paths with build options" do
alias_path = (CoreTap.instance.alias_dir/"another_name")
f = formula(alias_path:) do
url "foo-1.0"
end
f.build = BuildOptions.new(Options.new, f.options)
expect(f.alias_path).to eq(alias_path)
expect(f.installed_alias_path).to be_nil
end
example "alias paths with tab with non alias source path" do
alias_path = (CoreTap.instance.alias_dir/"another_name")
source_path = CoreTap.instance.new_formula_path("another_other_name")
f = formula(alias_path:) do
url "foo-1.0"
end
f.build = Tab.new(source: { "path" => source_path.to_s })
expect(f.alias_path).to eq(alias_path)
expect(f.installed_alias_path).to be_nil
end
example "alias paths with tab with alias source path" do
alias_path = (CoreTap.instance.alias_dir/"another_name")
source_path = (CoreTap.instance.alias_dir/"another_other_name")
f = formula(alias_path:) do
url "foo-1.0"
end
f.build = Tab.new(source: { "path" => source_path.to_s })
CoreTap.instance.alias_dir.mkpath
FileUtils.ln_sf f.path, source_path
expect(f.alias_path).to eq(alias_path)
expect(f.installed_alias_path).to eq(source_path)
end
end
describe "::inreplace" do
specify "raises build error on failure" do
f = formula do
url "https://brew.sh/test-1.0.tbz"
end
expect { f.inreplace([]) }.to raise_error(BuildError)
end
specify "replaces text in file" do
file = Tempfile.new("test")
File.binwrite(file, <<~EOS)
ab
bc
cd
EOS
f = formula do
url "https://brew.sh/test-1.0.tbz"
end
f.inreplace(file.path) do |s|
s.gsub!("bc", "yz")
end
expect(File.binread(file)).to eq <<~EOS
ab
yz
cd
EOS
end
end
describe "::installed_with_alias_path" do
specify "with alias path with nil" do
expect(described_class.installed_with_alias_path(nil)).to be_empty
end
specify "with alias path with a path" do
alias_path = CoreTap.instance.alias_dir/"alias"
different_alias_path = CoreTap.instance.alias_dir/"another_alias"
formula_with_alias = formula "foo" do
url "foo-1.0"
end
formula_with_alias.build = Tab.empty
formula_with_alias.build.source["path"] = alias_path.to_s
formula_without_alias = formula "bar" do
url "bar-1.0"
end
formula_without_alias.build = Tab.empty
formula_without_alias.build.source["path"] = formula_without_alias.path.to_s
formula_with_different_alias = formula "baz" do
url "baz-1.0"
end
formula_with_different_alias.build = Tab.empty
formula_with_different_alias.build.source["path"] = different_alias_path.to_s
formulae = [
formula_with_alias,
formula_without_alias,
formula_with_different_alias,
]
allow(described_class).to receive(:installed).and_return(formulae)
CoreTap.instance.alias_dir.mkpath
FileUtils.ln_sf formula_with_alias.path, alias_path
expect(described_class.installed_with_alias_path(alias_path))
.to eq([formula_with_alias])
end
end
specify ".url" do
f = formula do
url "foo-1.0"
end
expect(f.class.url).to eq("foo-1.0")
end
specify "spec integration" do
f = formula do
homepage "https://brew.sh"
url "https://brew.sh/test-0.1.tbz"
mirror "https://example.org/test-0.1.tbz"
sha256 TEST_SHA256
head "https://brew.sh/test.git", tag: "foo"
end
expect(f.homepage).to eq("https://brew.sh")
expect(f.version).to eq(Version.new("0.1"))
expect(f).to be_stable
expect(f.build).to be_a(BuildOptions)
expect(f.stable.version).to eq(Version.new("0.1"))
expect(f.head.version).to eq(Version.new("HEAD"))
end
specify "#active_spec=" do
f = formula do
url "foo"
version "1.0"
revision 1
end
expect(f.active_spec_sym).to eq(:stable)
expect(f.send(:active_spec)).to eq(f.stable)
expect(f.pkg_version.to_s).to eq("1.0_1")
expect { f.active_spec = :head }.to raise_error(FormulaSpecificationError)
end
specify "class specs are always initialized" do
f = formula do
url "foo-1.0"
end
expect(f.class.stable).to be_a(SoftwareSpec)
expect(f.class.head).to be_a(SoftwareSpec)
end
specify "instance specs have different references" do
f = Testball.new
f2 = Testball.new
expect(f.stable.owner).to equal(f)
expect(f2.stable.owner).to equal(f2)
end
specify "incomplete instance specs are not accessible" do
f = formula do
url "foo-1.0"
end
expect(f.head).to be_nil
end
it "honors attributes declared before specs" do
f = formula do
url "foo-1.0"
depends_on "foo"
end
expect(f.class.stable.deps.first.name).to eq("foo")
expect(f.class.head.deps.first.name).to eq("foo")
end
describe "#pkg_version" do
specify "simple version" do
f = formula do
url "foo-1.0.bar"
end
expect(f.pkg_version).to eq(PkgVersion.parse("1.0"))
end
specify "version with revision" do
f = formula do
url "foo-1.0.bar"
revision 1
end
expect(f.pkg_version).to eq(PkgVersion.parse("1.0_1"))
end
specify "head uses revisions" do
f = formula "test", spec: :head do
url "foo-1.0.bar"
revision 1
head "foo"
end
expect(f.pkg_version).to eq(PkgVersion.parse("HEAD_1"))
end
end
specify "#update_head_version" do
f = formula do
head "foo", using: :git
end
cached_location = f.head.downloader.cached_location
cached_location.mkpath
cached_location.cd do
FileUtils.touch "LICENSE"
system("git", "init")
system("git", "add", "--all")
system("git", "commit", "-m", "Initial commit")
end
f.update_head_version
expect(f.head.version).to eq(Version.new("HEAD-5658946"))
end
specify "#desc" do
f = formula do
desc "a formula"
url "foo-1.0"
end
expect(f.desc).to eq("a formula")
end
specify "#post_install_defined?" do
f1 = formula do
url "foo-1.0"
def post_install
# do nothing
end
end
f2 = formula do
url "foo-1.0"
end
expect(f1).to have_post_install_defined
expect(f2).not_to have_post_install_defined
end
specify "test fixtures" do
f1 = formula do
url "foo-1.0"
end
expect(f1.test_fixtures("foo")).to eq(Pathname.new("#{HOMEBREW_LIBRARY_PATH}/test/support/fixtures/foo"))
end
specify "#livecheck" do
f = formula do
url "https://brew.sh/test-1.0.tbz"
livecheck do
skip "foo"
url "https://brew.sh/test/releases"
regex(/test-v?(\d+(?:\.\d+)+)\.t/i)
end
end
expect(f.livecheck.skip?).to be true
expect(f.livecheck.skip_msg).to eq("foo")
expect(f.livecheck.url).to eq("https://brew.sh/test/releases")
expect(f.livecheck.regex).to eq(/test-v?(\d+(?:\.\d+)+)\.t/i)
end
describe "#livecheck_defined?" do
specify "no `livecheck` block defined" do
f = formula do
url "https://brew.sh/test-1.0.tbz"
end
expect(f.livecheck_defined?).to be false
end
specify "`livecheck` block defined" do
f = formula do
url "https://brew.sh/test-1.0.tbz"
livecheck do
regex(/test-v?(\d+(?:\.\d+)+)\.t/i)
end
end
expect(f.livecheck_defined?).to be true
end
specify "livecheck references Formula URL" do
f = formula do
homepage "https://brew.sh/test"
url "https://brew.sh/test-1.0.tbz"
livecheck do
url :homepage
regex(/test-v?(\d+(?:\.\d+)+)\.t/i)
end
end
expect(f.livecheck.url).to eq(:homepage)
end
end
describe "#service" do
specify "no service defined" do
f = formula do
url "https://brew.sh/test-1.0.tbz"
end
expect(f.service.to_hash).to eq({})
end
specify "service complicated" do
f = formula do
url "https://brew.sh/test-1.0.tbz"
service do
run [opt_bin/"beanstalkd"]
run_type :immediate
error_log_path var/"log/beanstalkd.error.log"
log_path var/"log/beanstalkd.log"
working_dir var
keep_alive true
end
end
expect(f.service.to_hash.keys)
.to contain_exactly(:run, :run_type, :error_log_path, :log_path, :working_dir, :keep_alive)
end
specify "service uses simple run" do
f = formula do
url "https://brew.sh/test-1.0.tbz"
service do
run opt_bin/"beanstalkd"
end
end
expect(f.service.to_hash.keys).to contain_exactly(:run, :run_type)
end
specify "service with only custom names" do
f = formula do
url "https://brew.sh/test-1.0.tbz"
service do
name macos: "custom.macos.beanstalkd", linux: "custom.linux.beanstalkd"
end
end
expect(f.plist_name).to eq("custom.macos.beanstalkd")
expect(f.service_name).to eq("custom.linux.beanstalkd")
expect(f.service.to_hash.keys).to contain_exactly(:name)
end
specify "service helpers return data" do
f = formula do
url "https://brew.sh/test-1.0.tbz"
end
expect(f.plist_name).to eq("homebrew.mxcl.formula_name")
expect(f.service_name).to eq("homebrew.formula_name")
expect(f.launchd_service_path).to eq(HOMEBREW_PREFIX/"opt/formula_name/homebrew.mxcl.formula_name.plist")
expect(f.systemd_service_path).to eq(HOMEBREW_PREFIX/"opt/formula_name/homebrew.formula_name.service")
expect(f.systemd_timer_path).to eq(HOMEBREW_PREFIX/"opt/formula_name/homebrew.formula_name.timer")
end
end
specify "dependencies" do
# don't try to load/fetch gcc/glibc
allow(DevelopmentTools).to receive_messages(needs_libc_formula?: false, needs_compiler_formula?: false)
f1 = formula "f1" do
url "f1-1.0"
end
f2 = formula "f2" do
url "f2-1.0"
end
f3 = formula "f3" do
url "f3-1.0"
depends_on "f1" => :build
depends_on "f2"
end
f4 = formula "f4" do
url "f4-1.0"
depends_on "f1"
end
stub_formula_loader(f1)
stub_formula_loader(f2)
stub_formula_loader(f3)
stub_formula_loader(f4)
f5 = formula "f5" do
url "f5-1.0"
depends_on "f3" => :build
depends_on "f4"
end
expect(f5.deps.map(&:name)).to eq(["f3", "f4"])
expect(f5.recursive_dependencies.map(&:name)).to eq(%w[f1 f2 f3 f4])
expect(f5.runtime_dependencies.map(&:name)).to eq(["f1", "f4"])
end
describe "#runtime_dependencies" do
specify "runtime dependencies with optional deps from tap" do
tap_loader = double
# don't try to load/fetch gcc/glibc
allow(DevelopmentTools).to receive_messages(needs_libc_formula?: false, needs_compiler_formula?: false)
allow(tap_loader).to receive(:get_formula).and_raise(RuntimeError, "tried resolving tap formula")
allow(Formulary).to receive(:loader_for).with("foo/bar/f1", from: nil).and_return(tap_loader)
f2_path = Tap.fetch("baz", "qux").path/"Formula/f2.rb"
stub_formula_loader(formula("f2", path: f2_path) { url("f2-1.0") }, "baz/qux/f2")
f3 = formula "f3" do
url "f3-1.0"
depends_on "foo/bar/f1" => :optional
depends_on "baz/qux/f2"
end
expect(f3.runtime_dependencies.map(&:name)).to eq(["baz/qux/f2"])
described_class.clear_cache
f1_path = Tap.fetch("foo", "bar").path/"Formula/f1.rb"
stub_formula_loader(formula("f1", path: f1_path) { url("f1-1.0") }, "foo/bar/f1")
f3.build = BuildOptions.new(Options.create(["--with-f1"]), f3.options)
expect(f3.runtime_dependencies.map(&:name)).to eq(["foo/bar/f1", "baz/qux/f2"])
end
it "includes non-declared direct dependencies" do
formula = Class.new(Testball).new
dependency = formula("dependency") { url "f-1.0" }
formula.brew { formula.install }
keg = Keg.for(formula.latest_installed_prefix)
keg.link
linkage_checker = instance_double(LinkageChecker, "linkage checker", undeclared_deps: [dependency.name])
allow(LinkageChecker).to receive(:new).and_return(linkage_checker)
expect(formula.runtime_dependencies.map(&:name)).to eq [dependency.name]
end
it "handles bad tab runtime_dependencies" do
formula = Class.new(Testball).new
formula.brew { formula.install }
tab = Tab.create(formula, DevelopmentTools.default_compiler, :libcxx)
tab.runtime_dependencies = ["foo"]
tab.write
keg = Keg.for(formula.latest_installed_prefix)
keg.link
expect(formula.runtime_dependencies.map(&:name)).to be_empty
end
end
specify "requirements" do
# don't try to load/fetch gcc/glibc
allow(DevelopmentTools).to receive_messages(needs_libc_formula?: false, needs_compiler_formula?: false)
f1 = formula "f1" do
url "f1-1"
depends_on xcode: ["1.0", :optional]
end
stub_formula_loader(f1)
xcode = XcodeRequirement.new(["1.0", :optional])
expect(Set.new(f1.recursive_requirements)).to eq(Set[])
f1.build = BuildOptions.new(Options.create(["--with-xcode"]), f1.options)
expect(Set.new(f1.recursive_requirements)).to eq(Set[xcode])
f1.build = f1.stable.build
f2 = formula "f2" do
url "f2-1"
depends_on "f1"
end
expect(Set.new(f2.recursive_requirements)).to eq(Set[])
expect(
f2.recursive_requirements do
# do nothing
end.to_set,
).to eq(Set[xcode])
requirements = f2.recursive_requirements do |_dependent, requirement|
Requirement.prune if requirement.is_a?(XcodeRequirement)
end
expect(Set.new(requirements)).to eq(Set[])
end
specify "#to_hash" do
f1 = formula "foo" do
url "foo-1.0"
bottle do
sha256 cellar: :any, Utils::Bottles.tag.to_sym => TEST_SHA256
end
end
stub_formula_loader(f1)
h = f1.to_hash
expect(h).to be_a(Hash)
expect(h["name"]).to eq("foo")
expect(h["full_name"]).to eq("foo")
expect(h["tap"]).to eq("homebrew/core")
expect(h["versions"]["stable"]).to eq("1.0")
expect(h["versions"]["bottle"]).to be_truthy
end
describe "#to_hash_with_variations", :needs_macos do
let(:formula_path) { CoreTap.instance.new_formula_path("foo-variations") }
let(:formula_content) do
<<~RUBY
class FooVariations < Formula
url "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz"
sha256 TESTBALL_SHA256
on_intel do
depends_on "intel-formula"
end
on_sequoia do
depends_on "sequoia-formula"
end
on_sonoma :or_older do
depends_on "sonoma-or-older-formula"
end
on_linux do
depends_on "linux-formula"
end
end
RUBY
end
let(:expected_variations) do
<<~JSON
{
"tahoe": {
"dependencies": [
"intel-formula"
]
},
"arm64_tahoe": {
"dependencies": []
},
"sequoia": {
"dependencies": [
"intel-formula",
"sequoia-formula"
]
},
"arm64_sequoia": {
"dependencies": [
"sequoia-formula"
]
},
"sonoma": {
"dependencies": [
"intel-formula",
"sonoma-or-older-formula"
]
},
"ventura": {
"dependencies": [
"intel-formula",
"sonoma-or-older-formula"
]
},
"x86_64_linux": {
"dependencies": [
"intel-formula",
"linux-formula"
]
},
"arm64_linux": {
"dependencies": [
"linux-formula"
]
}
}
JSON
end
before do
# Use a more limited os list to shorten the variations hash
os_list = [:tahoe, :sequoia, :sonoma, :ventura, :linux]
valid_tags = os_list.product(OnSystem::ARCH_OPTIONS).filter_map do |os, arch|
tag = Utils::Bottles::Tag.new(system: os, arch:)
next unless tag.valid_combination?
tag
end
stub_const("OnSystem::VALID_OS_ARCH_TAGS", valid_tags)
# For consistency, always run on Tahoe and ARM
allow(MacOS).to receive(:version).and_return(MacOSVersion.new("12"))
allow(Hardware::CPU).to receive(:type).and_return(:arm)
formula_path.dirname.mkpath
formula_path.write formula_content
end
it "returns the correct variations hash" do
h = Formulary.factory("foo-variations").to_hash_with_variations
expect(h).to be_a(Hash)
expect(JSON.pretty_generate(h["variations"])).to eq expected_variations.strip
end
end
describe "#eligible_kegs_for_cleanup" do
it "returns Kegs eligible for cleanup" do
f1 = Class.new(Testball) do
version("1.0")
end.new
f2 = Class.new(Testball) do
version("0.2")
version_scheme(1)
end.new
f3 = Class.new(Testball) do
version("0.3")
version_scheme(1)
end.new
f4 = Class.new(Testball) do
version("0.1")
version_scheme(2)
end.new
[f1, f2, f3, f4].each do |f|
f.brew { f.install }
Tab.create(f, DevelopmentTools.default_compiler, :libcxx).write
end
expect(f1).to be_latest_version_installed
expect(f2).to be_latest_version_installed
expect(f3).to be_latest_version_installed
expect(f4).to be_latest_version_installed
expect(f3.eligible_kegs_for_cleanup.sort_by(&:version))
.to eq([f2, f1].map { |f| Keg.new(f.prefix) })
end
specify "with pinned Keg" do
f1 = Class.new(Testball) { version("0.1") }.new
f2 = Class.new(Testball) { version("0.2") }.new
f3 = Class.new(Testball) { version("0.3") }.new
f1.brew { f1.install }
f1.pin
f2.brew { f2.install }
f3.brew { f3.install }
expect(f1.prefix).to eq((HOMEBREW_PINNED_KEGS/f1.name).resolved_path)
expect(f1).to be_latest_version_installed
expect(f2).to be_latest_version_installed
expect(f3).to be_latest_version_installed
expect(f3.eligible_kegs_for_cleanup).to eq([Keg.new(f2.prefix)])
end
specify "with HEAD installed" do
f = formula do
version("0.1")
head("foo")
end
["0.0.1", "0.0.2", "0.1", "HEAD-000000", "HEAD-111111", "HEAD-111111_1"].each do |version|
prefix = f.prefix(version)
prefix.mkpath
tab = Tab.empty
tab.tabfile = prefix/AbstractTab::FILENAME
tab.source_modified_time = 1
tab.write
end
eligible_kegs = f.installed_kegs - [Keg.new(f.prefix("HEAD-111111_1")), Keg.new(f.prefix("0.1"))]
expect(f.eligible_kegs_for_cleanup.sort_by(&:version)).to eq(eligible_kegs.sort_by(&:version))
end
end
describe "#pour_bottle?" do
it "returns false if set to false" do
f = formula "foo" do
url "foo-1.0"
def pour_bottle?
false
end
end
expect(f).not_to pour_bottle
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | true |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/patch_spec.rb | Library/Homebrew/test/patch_spec.rb | # frozen_string_literal: true
require "patch"
RSpec.describe Patch do
describe "#create" do
context "with a simple patch" do
subject(:patch) { described_class.create(:p2, nil) }
specify(:aggregate_failures) do
expect(subject).to be_a ExternalPatch # rubocop:todo RSpec/NamedSubject
expect(subject).to be_external # rubocop:todo RSpec/NamedSubject
end
it(:strip) { expect(patch.strip).to eq(:p2) }
end
context "with a string patch" do
subject(:patch) { described_class.create(:p0, "foo") }
it { is_expected.to be_a StringPatch }
it(:strip) { expect(patch.strip).to eq(:p0) }
end
context "with a string patch without strip" do
subject(:patch) { described_class.create("foo", nil) }
it { is_expected.to be_a StringPatch }
it(:strip) { expect(patch.strip).to eq(:p1) }
end
context "with a data patch" do
subject(:patch) { described_class.create(:p0, :DATA) }
it { is_expected.to be_a DATAPatch }
it(:strip) { expect(patch.strip).to eq(:p0) }
end
context "with a data patch without strip" do
subject(:patch) { described_class.create(:DATA, nil) }
it { is_expected.to be_a DATAPatch }
it(:strip) { expect(patch.strip).to eq(:p1) }
end
it "raises an error for unknown values" do
expect do
described_class.create(Object.new)
end.to raise_error(ArgumentError)
expect do
described_class.create(Object.new, Object.new)
end.to raise_error(ArgumentError)
end
end
describe "#patch_files" do
subject(:patch) { described_class.create(:p2, nil) }
context "when the patch is empty" do
it(:resource) { expect(patch.resource).to be_a Resource::Patch }
specify(:aggregate_failures) do
expect(patch.patch_files).to eq(patch.resource.patch_files)
expect(patch.patch_files).to eq([])
end
end
it "returns applied patch files" do
patch.resource.apply("patch1.diff")
expect(patch.patch_files).to eq(["patch1.diff"])
patch.resource.apply("patch2.diff", "patch3.diff")
expect(patch.patch_files).to eq(["patch1.diff", "patch2.diff", "patch3.diff"])
patch.resource.apply(["patch4.diff", "patch5.diff"])
expect(patch.patch_files.count).to eq(5)
patch.resource.apply("patch4.diff", ["patch5.diff", "patch6.diff"], "patch7.diff")
expect(patch.patch_files.count).to eq(7)
end
end
describe EmbeddedPatch do
describe "#new" do
subject(:patch) { described_class.new(:p1) }
it(:inspect) { expect(patch.inspect).to eq("#<EmbeddedPatch: :p1>") }
end
end
describe ExternalPatch do
subject(:patch) { described_class.new(:p1) { url "file:///my.patch" } }
describe "#url" do
it(:url) { expect(patch.url).to eq("file:///my.patch") }
end
describe "#inspect" do
it(:inspect) { expect(patch.inspect).to eq('#<ExternalPatch: :p1 "file:///my.patch">') }
end
describe "#cached_download" do
before do
allow(patch.resource).to receive(:cached_download).and_return("/tmp/foo.tar.gz")
end
it(:cached_download) { expect(patch.cached_download).to eq("/tmp/foo.tar.gz") }
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/locale_spec.rb | Library/Homebrew/test/locale_spec.rb | # frozen_string_literal: true
require "locale"
RSpec.describe Locale do
describe "::parse" do
it "parses a string in the correct format" do
expect(described_class.parse("zh")).to eql(described_class.new("zh", nil, nil))
expect(described_class.parse("zh-CN")).to eql(described_class.new("zh", nil, "CN"))
expect(described_class.parse("zh-Hans")).to eql(described_class.new("zh", "Hans", nil))
expect(described_class.parse("zh-Hans-CN")).to eql(described_class.new("zh", "Hans", "CN"))
end
it "correctly parses a string with a UN M.49 region code" do
expect(described_class.parse("es-419")).to eql(described_class.new("es", nil, "419"))
end
describe "raises a ParserError when given" do
it "an empty string" do
expect { described_class.parse("") }.to raise_error(Locale::ParserError)
end
it "a string in a wrong format" do
expect { described_class.parse("zh-CN-Hans") }.to raise_error(Locale::ParserError)
expect { described_class.parse("zh_CN_Hans") }.to raise_error(Locale::ParserError)
expect { described_class.parse("zhCNHans") }.to raise_error(Locale::ParserError)
expect { described_class.parse("zh-CN_Hans") }.to raise_error(Locale::ParserError)
expect { described_class.parse("zhCN") }.to raise_error(Locale::ParserError)
expect { described_class.parse("zh_Hans") }.to raise_error(Locale::ParserError)
expect { described_class.parse("zh-") }.to raise_error(Locale::ParserError)
expect { described_class.parse("ZH-CN") }.to raise_error(Locale::ParserError)
expect { described_class.parse("zh-cn") }.to raise_error(Locale::ParserError)
end
end
end
describe "::new" do
it "raises an ArgumentError when all arguments are nil" do
expect { described_class.new(nil, nil, nil) }.to raise_error(ArgumentError)
end
it "raises a ParserError when one of the arguments does not match the locale format" do
expect { described_class.new("ZH", nil, nil) }.to raise_error(Locale::ParserError)
expect { described_class.new(nil, "hans", nil) }.to raise_error(Locale::ParserError)
expect { described_class.new(nil, nil, "cn") }.to raise_error(Locale::ParserError)
end
end
describe "#include?" do
subject { described_class.new("zh", "Hans", "CN") }
specify(:aggregate_failures) do
expect(subject).to include("zh") # rubocop:todo RSpec/NamedSubject
expect(subject).to include("zh-CN") # rubocop:todo RSpec/NamedSubject
expect(subject).to include("CN") # rubocop:todo RSpec/NamedSubject
expect(subject).to include("Hans-CN") # rubocop:todo RSpec/NamedSubject
expect(subject).to include("Hans") # rubocop:todo RSpec/NamedSubject
expect(subject).to include("zh-Hans-CN") # rubocop:todo RSpec/NamedSubject
end
end
describe "#eql?" do
subject(:locale) { described_class.new("zh", "Hans", "CN") }
context "when all parts match" do
specify(:aggregate_failures) do
expect(subject).to eql("zh-Hans-CN") # rubocop:todo RSpec/NamedSubject
expect(subject).to eql(locale) # rubocop:todo RSpec/NamedSubject
end
end
context "when only some parts match" do
specify(:aggregate_failures) do
expect(subject).not_to eql("zh") # rubocop:todo RSpec/NamedSubject
expect(subject).not_to eql("zh-CN") # rubocop:todo RSpec/NamedSubject
expect(subject).not_to eql("CN") # rubocop:todo RSpec/NamedSubject
expect(subject).not_to eql("Hans-CN") # rubocop:todo RSpec/NamedSubject
expect(subject).not_to eql("Hans") # rubocop:todo RSpec/NamedSubject
end
end
it "does not raise if 'other' cannot be parsed" do
expect { locale.eql?("zh_CN_Hans") }.not_to raise_error
expect(locale.eql?("zh_CN_Hans")).to be false
end
end
describe "#detect" do
let(:locale_groups) { [["zh"], ["zh-TW"]] }
it "finds best matching language code, independent of order" do
expect(described_class.new("zh", nil, "TW").detect(locale_groups)).to eql(["zh-TW"])
expect(described_class.new("zh", nil, "TW").detect(locale_groups.reverse)).to eql(["zh-TW"])
expect(described_class.new("zh", "Hans", "CN").detect(locale_groups)).to eql(["zh"])
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/github_runner_matrix_spec.rb | Library/Homebrew/test/github_runner_matrix_spec.rb | # frozen_string_literal: true
require "github_runner_matrix"
require "test/support/fixtures/testball"
RSpec.describe GitHubRunnerMatrix, :no_api do
before do
allow(ENV).to receive(:fetch).and_call_original
allow(ENV).to receive(:fetch).with("HOMEBREW_LINUX_RUNNER").and_return("ubuntu-latest")
allow(ENV).to receive(:fetch).with("HOMEBREW_MACOS_LONG_TIMEOUT", "false").and_return("false")
allow(ENV).to receive(:fetch).with("HOMEBREW_MACOS_BUILD_ON_GITHUB_RUNNER", "false").and_return("false")
allow(ENV).to receive(:fetch).with("GITHUB_RUN_ID").and_return("12345")
allow(ENV).to receive(:fetch).with("HOMEBREW_EVAL_ALL", nil).and_call_original
allow(ENV).to receive(:fetch).with("HOMEBREW_SIMULATE_MACOS_ON_LINUX", nil).and_call_original
allow(ENV).to receive(:fetch).with("HOMEBREW_FORBID_PACKAGES_FROM_PATHS", nil).and_call_original
allow(ENV).to receive(:fetch).with("HOMEBREW_DEVELOPER", nil).and_call_original
allow(ENV).to receive(:fetch).with("HOMEBREW_NO_INSTALL_FROM_API", nil).and_call_original
end
let(:newest_supported_macos) do
MacOSVersion::SYMBOLS.find { |k, _| k == described_class::NEWEST_HOMEBREW_CORE_MACOS_RUNNER }
end
let(:testball) { setup_test_runner_formula("testball") }
let(:testball_depender) { setup_test_runner_formula("testball-depender", ["testball"]) }
let(:testball_depender_linux) { setup_test_runner_formula("testball-depender-linux", ["testball", :linux]) }
let(:testball_depender_macos) { setup_test_runner_formula("testball-depender-macos", ["testball", :macos]) }
let(:testball_depender_intel) do
setup_test_runner_formula("testball-depender-intel", ["testball", { arch: :x86_64 }])
end
let(:testball_depender_arm) { setup_test_runner_formula("testball-depender-arm", ["testball", { arch: :arm64 }]) }
let(:testball_depender_newest) do
symbol, = newest_supported_macos
setup_test_runner_formula("testball-depender-newest", ["testball", { macos: symbol }])
end
describe "OLDEST_HOMEBREW_CORE_MACOS_RUNNER" do
it "is not newer than HOMEBREW_MACOS_OLDEST_SUPPORTED" do
oldest_macos_runner = MacOSVersion.from_symbol(described_class::OLDEST_HOMEBREW_CORE_MACOS_RUNNER)
expect(oldest_macos_runner).to be <= HOMEBREW_MACOS_OLDEST_SUPPORTED
end
end
describe "#active_runner_specs_hash" do
it "returns an object that responds to `#to_json`" do
expect(
described_class.new([], ["deleted"], all_supported: false, dependent_matrix: false)
.active_runner_specs_hash
.respond_to?(:to_json),
).to be(true)
end
end
describe "#generate_runners!" do
it "is idempotent" do
matrix = described_class.new([], [], all_supported: false, dependent_matrix: false)
runners = matrix.runners.dup
matrix.send(:generate_runners!)
expect(matrix.runners).to eq(runners)
end
end
context "when there are no testing formulae and no deleted formulae" do
it "activates no test runners" do
expect(described_class.new([], [], all_supported: false, dependent_matrix: false).runners.any?(&:active))
.to be(false)
end
it "activates no dependent runners" do
expect(described_class.new([], [], all_supported: false, dependent_matrix: true).runners.any?(&:active))
.to be(false)
end
end
context "when passed `--all-supported`" do
it "activates all runners" do
expect(described_class.new([], [], all_supported: true, dependent_matrix: false).runners.all?(&:active))
.to be(true)
end
end
context "when there are testing formulae and no deleted formulae" do
context "when it is a matrix for the `tests` job" do
context "when testing formulae have no requirements" do
it "activates all runners" do
expect(described_class.new([testball], [], all_supported: false, dependent_matrix: false)
.runners
.all?(&:active))
.to be(true)
end
end
context "when testing formulae require Linux" do
it "activates only the Linux runners" do
runner_matrix = described_class.new([testball_depender_linux], [],
all_supported: false,
dependent_matrix: false)
expect(runner_matrix.runners.all?(&:active)).to be(false)
expect(runner_matrix.runners.any?(&:active)).to be(true)
expect(get_runner_names(runner_matrix)).to eq(["Linux x86_64", "Linux arm64"])
end
end
context "when testing formulae require macOS" do
it "activates only the macOS runners" do
runner_matrix = described_class.new([testball_depender_macos], [],
all_supported: false,
dependent_matrix: false)
expect(runner_matrix.runners.all?(&:active)).to be(false)
expect(runner_matrix.runners.any?(&:active)).to be(true)
expect(get_runner_names(runner_matrix)).to eq(get_runner_names(runner_matrix, :macos?))
end
end
context "when testing formulae require Intel" do
it "activates only the Intel runners" do
runner_matrix = described_class.new([testball_depender_intel], [],
all_supported: false,
dependent_matrix: false)
expect(runner_matrix.runners.all?(&:active)).to be(false)
expect(runner_matrix.runners.any?(&:active)).to be(true)
expect(get_runner_names(runner_matrix)).to eq(get_runner_names(runner_matrix, :x86_64?))
end
end
context "when testing formulae require ARM" do
it "activates only the ARM runners" do
runner_matrix = described_class.new([testball_depender_arm], [],
all_supported: false,
dependent_matrix: false)
expect(runner_matrix.runners.all?(&:active)).to be(false)
expect(runner_matrix.runners.any?(&:active)).to be(true)
expect(get_runner_names(runner_matrix)).to eq(get_runner_names(runner_matrix, :arm64?))
end
end
context "when testing formulae require a macOS version" do
it "activates the Linux runners and suitable macOS runners" do
_, v = newest_supported_macos
runner_matrix = described_class.new([testball_depender_newest], [],
all_supported: false,
dependent_matrix: false)
expect(runner_matrix.runners.all?(&:active)).to be(false)
expect(runner_matrix.runners.any?(&:active)).to be(true)
expect(get_runner_names(runner_matrix).sort).to eq(["Linux arm64", "Linux x86_64", "macOS #{v}-arm64"])
end
end
end
context "when it is a matrix for the `test_deps` job" do
context "when testing formulae have no dependents" do
it "activates no runners" do
allow(Homebrew::EnvConfig).to receive(:eval_all?).and_return(true)
allow(Formula).to receive(:all).and_return([testball].map(&:formula))
expect(described_class.new([testball], [], all_supported: false, dependent_matrix: true)
.runners
.any?(&:active))
.to be(false)
end
end
context "when testing formulae have dependents" do
context "when dependents have no requirements" do
it "activates all runners" do
allow(Homebrew::EnvConfig).to receive(:eval_all?).and_return(true)
allow(Formula).to receive(:all).and_return([testball, testball_depender].map(&:formula))
expect(described_class.new([testball], [], all_supported: false, dependent_matrix: true)
.runners
.all?(&:active))
.to be(true)
end
end
context "when dependents require Linux" do
it "activates only Linux runners" do
allow(Homebrew::EnvConfig).to receive(:eval_all?).and_return(true)
allow(Formula).to receive(:all).and_return([testball, testball_depender_linux].map(&:formula))
runner_matrix = described_class.new([testball], [], all_supported: false, dependent_matrix: true)
expect(runner_matrix.runners.all?(&:active)).to be(false)
expect(runner_matrix.runners.any?(&:active)).to be(true)
expect(get_runner_names(runner_matrix)).to eq(get_runner_names(runner_matrix, :linux?))
end
end
context "when dependents require macOS" do
it "activates only macOS runners" do
allow(Homebrew::EnvConfig).to receive(:eval_all?).and_return(true)
allow(Formula).to receive(:all).and_return([testball, testball_depender_macos].map(&:formula))
runner_matrix = described_class.new([testball], [], all_supported: false, dependent_matrix: true)
expect(runner_matrix.runners.all?(&:active)).to be(false)
expect(runner_matrix.runners.any?(&:active)).to be(true)
expect(get_runner_names(runner_matrix)).to eq(get_runner_names(runner_matrix, :macos?))
end
end
context "when dependents require an Intel architecture" do
it "activates only Intel runners" do
allow(Homebrew::EnvConfig).to receive(:eval_all?).and_return(true)
allow(Formula).to receive(:all).and_return([testball, testball_depender_intel].map(&:formula))
runner_matrix = described_class.new([testball], [], all_supported: false, dependent_matrix: true)
expect(runner_matrix.runners.all?(&:active)).to be(false)
expect(runner_matrix.runners.any?(&:active)).to be(true)
expect(get_runner_names(runner_matrix)).to eq(get_runner_names(runner_matrix, :x86_64?))
end
end
context "when dependents require an ARM architecture" do
it "activates only ARM runners" do
allow(Homebrew::EnvConfig).to receive(:eval_all?).and_return(true)
allow(Formula).to receive(:all).and_return([testball, testball_depender_arm].map(&:formula))
runner_matrix = described_class.new([testball], [], all_supported: false, dependent_matrix: true)
expect(runner_matrix.runners.all?(&:active)).to be(false)
expect(runner_matrix.runners.any?(&:active)).to be(true)
expect(get_runner_names(runner_matrix)).to eq(get_runner_names(runner_matrix, :arm64?))
end
end
end
end
end
context "when there are deleted formulae" do
context "when it is a matrix for the `tests` job" do
it "activates all runners" do
expect(described_class.new([], ["deleted"], all_supported: false, dependent_matrix: false)
.runners
.all?(&:active))
.to be(true)
end
end
context "when it is a matrix for the `test_deps` job" do
context "when there are no testing formulae" do
it "activates no runners" do
expect(described_class.new([], ["deleted"], all_supported: false, dependent_matrix: true)
.runners
.any?(&:active))
.to be(false)
end
end
context "when there are testing formulae with no dependents" do
it "activates no runners" do
testing_formulae = [testball]
runner_matrix = described_class.new(testing_formulae, ["deleted"],
all_supported: false,
dependent_matrix: true)
allow(Homebrew::EnvConfig).to receive(:eval_all?).and_return(true)
allow(Formula).to receive(:all).and_return(testing_formulae.map(&:formula))
expect(runner_matrix.runners.none?(&:active)).to be(true)
end
end
context "when there are testing formulae with dependents" do
context "when dependent formulae have no requirements" do
it "activates the applicable runners" do
allow(Homebrew::EnvConfig).to receive(:eval_all?).and_return(true)
allow(Formula).to receive(:all).and_return([testball, testball_depender].map(&:formula))
testing_formulae = [testball]
expect(described_class.new(testing_formulae, ["deleted"], all_supported: false, dependent_matrix: true)
.runners
.all?(&:active))
.to be(true)
end
end
context "when dependent formulae have requirements" do
context "when dependent formulae require Linux" do
it "activates the applicable runners" do
allow(Homebrew::EnvConfig).to receive(:eval_all?).and_return(true)
allow(Formula).to receive(:all).and_return([testball, testball_depender_linux].map(&:formula))
matrix = described_class.new([testball], ["deleted"], all_supported: false, dependent_matrix: true)
expect(get_runner_names(matrix)).to eq(["Linux x86_64", "Linux arm64"])
allow(ENV).to receive(:[]).with("HOMEBREW_LINUX_RUNNER").and_return("linux-self-hosted-1")
matrix = described_class.new([testball], ["deleted"], all_supported: false, dependent_matrix: true)
expect(get_runner_names(matrix)).to eq(["Linux x86_64"])
end
end
context "when dependent formulae require macOS" do
it "activates the applicable runners" do
allow(Homebrew::EnvConfig).to receive(:eval_all?).and_return(true)
allow(Formula).to receive(:all).and_return([testball, testball_depender_macos].map(&:formula))
matrix = described_class.new([testball], ["deleted"], all_supported: false, dependent_matrix: true)
expect(get_runner_names(matrix)).to eq(get_runner_names(matrix, :macos?))
end
end
end
end
end
end
def get_runner_names(runner_matrix, predicate = :active)
runner_matrix.runners
.select(&predicate)
.map { |runner| runner.spec.name }
end
def setup_test_runner_formula(name, dependencies = [], **kwargs)
f = formula name do
url "https://brew.sh/#{name}-1.0.tar.gz"
dependencies.each { |dependency| depends_on dependency }
kwargs.each do |k, v|
send(:"on_#{k}") do
v.each do |dep|
depends_on dep
end
end
end
end
stub_formula_loader f
TestRunnerFormula.new(f)
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/bottle_specification_spec.rb | Library/Homebrew/test/bottle_specification_spec.rb | # frozen_string_literal: true
require "bottle_specification"
RSpec.describe BottleSpecification do
subject(:bottle_spec) { described_class.new }
describe "#sha256" do
it "works without cellar" do
checksums = {
arm64_tahoe: "deadbeef" * 8,
tahoe: "faceb00c" * 8,
sequoia: "baadf00d" * 8,
sonoma: "8badf00d" * 8,
}
checksums.each_pair do |cat, digest|
bottle_spec.sha256(cat => digest)
tag_spec = bottle_spec.tag_specification_for(Utils::Bottles::Tag.from_symbol(cat))
expect(Checksum.new(digest)).to eq(tag_spec.checksum)
end
end
it "works with cellar" do
checksums = [
{ cellar: :any_skip_relocation, tag: :arm64_tahoe, digest: "deadbeef" * 8 },
{ cellar: :any, tag: :tahoe, digest: "faceb00c" * 8 },
{ cellar: "/usr/local/Cellar", tag: :sequoia, digest: "baadf00d" * 8 },
{ cellar: Homebrew::DEFAULT_CELLAR, tag: :sonoma, digest: "8badf00d" * 8 },
]
checksums.each do |checksum|
bottle_spec.sha256(cellar: checksum[:cellar], checksum[:tag] => checksum[:digest])
tag_spec = bottle_spec.tag_specification_for(Utils::Bottles::Tag.from_symbol(checksum[:tag]))
expect(Checksum.new(checksum[:digest])).to eq(tag_spec.checksum)
expect(checksum[:tag]).to eq(tag_spec.tag.to_sym)
checksum[:cellar] ||= Homebrew::DEFAULT_CELLAR
expect(checksum[:cellar]).to eq(tag_spec.cellar)
end
end
end
describe "#compatible_locations?" do
it "checks if the bottle cellar is relocatable" do
expect(bottle_spec.compatible_locations?).to be false
end
end
describe "#tag_to_cellar" do
it "returns the cellar for a tag" do
expect(bottle_spec.tag_to_cellar).to eq Utils::Bottles.tag.default_cellar
end
end
specify "#rebuild" do
bottle_spec.rebuild(1337)
expect(bottle_spec.rebuild).to eq(1337)
end
specify "#root_url" do
bottle_spec.root_url("https://example.com")
expect(bottle_spec.root_url).to eq("https://example.com")
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/formulary_spec.rb | Library/Homebrew/test/formulary_spec.rb | # frozen_string_literal: true
require "formula"
require "formula_installer"
require "utils/bottles"
# rubocop:todo RSpec/AggregateExamples
RSpec.describe Formulary do
let(:formula_name) { "testball_bottle" }
let(:formula_path) { CoreTap.instance.new_formula_path(formula_name) }
let(:formula_content) do
<<~RUBY
class #{described_class.class_s(formula_name)} < Formula
url "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz"
sha256 TESTBALL_SHA256
bottle do
root_url "file://#{bottle_dir}"
sha256 cellar: :any_skip_relocation, #{Utils::Bottles.tag}: "d7b9f4e8bf83608b71fe958a99f19f2e5e68bb2582965d32e41759c24f1aef97"
end
def install
prefix.install "bin"
prefix.install "libexec"
end
end
RUBY
end
let(:bottle_dir) { Pathname.new("#{TEST_FIXTURE_DIR}/bottles") }
let(:bottle) { bottle_dir/"testball_bottle-0.1.#{Utils::Bottles.tag}.bottle.tar.gz" }
describe "::class_s" do
it "replaces '+' with 'x'" do
expect(described_class.class_s("foo++")).to eq("Fooxx")
end
it "converts a string with dots to PascalCase" do
expect(described_class.class_s("shell.fm")).to eq("ShellFm")
end
it "converts a string with hyphens to PascalCase" do
expect(described_class.class_s("pkg-config")).to eq("PkgConfig")
end
it "converts a string with a single letter separated by a hyphen to PascalCase" do
expect(described_class.class_s("s-lang")).to eq("SLang")
end
it "converts a string with underscores to PascalCase" do
expect(described_class.class_s("foo_bar")).to eq("FooBar")
end
it "replaces '@' with 'AT'" do
expect(described_class.class_s("openssl@1.1")).to eq("OpensslAT11")
end
end
describe "::factory" do
context "without the API", :no_api do
before do
formula_path.dirname.mkpath
formula_path.write formula_content
end
it "returns a Formula" do
expect(described_class.factory(formula_name)).to be_a(Formula)
end
it "returns a Formula when given a fully qualified name" do
expect(described_class.factory("homebrew/core/#{formula_name}")).to be_a(Formula)
end
it "raises an error if the Formula cannot be found" do
expect do
described_class.factory("not_existed_formula")
end.to raise_error(FormulaUnavailableError)
end
it "raises an error if ref is nil" do
expect do
described_class.factory(nil)
end.to raise_error(TypeError)
end
context "with sharded Formula directory" do
let(:formula_name) { "testball_sharded" }
let(:formula_path) do
core_tap = CoreTap.instance
(core_tap.formula_dir/formula_name[0]).mkpath
core_tap.new_formula_path(formula_name)
end
it "returns a Formula" do
expect(described_class.factory(formula_name)).to be_a(Formula)
end
it "returns a Formula when given a fully qualified name" do
expect(described_class.factory("homebrew/core/#{formula_name}")).to be_a(Formula)
end
end
context "when the Formula has the wrong class" do
let(:formula_name) { "giraffe" }
let(:formula_content) do
<<~RUBY
class Wrong#{described_class.class_s(formula_name)} < Formula
end
RUBY
end
it "raises an error" do
expect do
described_class.factory(formula_name)
end.to raise_error(TapFormulaClassUnavailableError)
end
end
it "returns a Formula when given a path" do
expect(described_class.factory(formula_path)).to be_a(Formula)
end
it "errors when given a path but paths are disabled" do
ENV["HOMEBREW_FORBID_PACKAGES_FROM_PATHS"] = "1"
FileUtils.cp formula_path, HOMEBREW_TEMP
temp_formula_path = HOMEBREW_TEMP/formula_path.basename
expect do
described_class.factory(temp_formula_path)
ensure
temp_formula_path.unlink
end.to raise_error(RuntimeError, /requires formulae to be in a tap, rejecting/)
end
it "returns a Formula when given a URL", :needs_utils_curl do
formula = described_class.factory("file://#{formula_path}")
expect(formula).to be_a(Formula)
end
it "errors when given a URL but paths are disabled" do
ENV["HOMEBREW_FORBID_PACKAGES_FROM_PATHS"] = "1"
expect do
described_class.factory("file://#{formula_path}")
end.to raise_error(FormulaUnavailableError)
end
context "when given a cache path" do
let(:cache_dir) { HOMEBREW_CACHE/"test_formula_cache" }
let(:cache_formula_path) { cache_dir/formula_path.basename }
before do
cache_dir.mkpath
FileUtils.cp formula_path, cache_formula_path
end
after do
cache_formula_path.unlink if cache_formula_path.exist?
cache_dir.rmdir if cache_dir.exist?
end
it "disallows cache paths when paths are explicitly disabled" do
ENV["HOMEBREW_FORBID_PACKAGES_FROM_PATHS"] = "1"
expect do
described_class.factory(cache_formula_path)
end.to raise_error(/requires formulae to be in a tap/)
end
end
context "when given a bottle" do
subject(:formula) { described_class.factory(bottle) }
it "returns a Formula" do
expect(formula).to be_a(Formula)
end
it "calling #local_bottle_path on the returned Formula returns the bottle path" do
expect(formula.local_bottle_path).to eq(bottle.realpath)
end
end
context "when given an alias" do
subject(:formula) { described_class.factory("foo") }
let(:alias_dir) { CoreTap.instance.alias_dir }
let(:alias_path) { alias_dir/"foo" }
before do
alias_dir.mkpath
FileUtils.ln_s formula_path, alias_path
end
it "returns a Formula" do
expect(formula).to be_a(Formula)
end
it "calling #alias_path on the returned Formula returns the alias path" do
expect(formula.alias_path).to eq(alias_path)
end
end
context "with installed Formula" do
before do
# don't try to load/fetch gcc/glibc
allow(DevelopmentTools).to receive_messages(needs_libc_formula?: false, needs_compiler_formula?: false)
end
let(:installed_formula) { described_class.factory(formula_path) }
let(:installer) { FormulaInstaller.new(installed_formula) }
it "returns a Formula when given a rack" do
installer.fetch
installer.install
f = described_class.from_rack(installed_formula.rack)
expect(f).to be_a(Formula)
end
it "returns a Formula when given a Keg" do
installer.fetch
installer.install
keg = Keg.new(installed_formula.prefix)
f = described_class.from_keg(keg)
expect(f).to be_a(Formula)
end
end
context "when migrating from a Tap" do
let(:tap) { Tap.fetch("homebrew", "foo") }
let(:another_tap) { Tap.fetch("homebrew", "bar") }
let(:tap_migrations_path) { tap.path/"tap_migrations.json" }
let(:another_tap_formula_path) { another_tap.path/"Formula/#{formula_name}.rb" }
before do
tap.path.mkpath
another_tap_formula_path.dirname.mkpath
another_tap_formula_path.write formula_content
end
after do
FileUtils.rm_rf tap.path
FileUtils.rm_rf another_tap.path
end
it "returns a Formula that has gone through a tap migration into homebrew/core" do
tap_migrations_path.write <<~EOS
{
"#{formula_name}": "homebrew/core"
}
EOS
formula = described_class.factory("#{tap}/#{formula_name}")
expect(formula).to be_a(Formula)
expect(formula.tap).to eq(CoreTap.instance)
expect(formula.path).to eq(formula_path)
end
it "returns a Formula that has gone through a tap migration into another tap" do
tap_migrations_path.write <<~EOS
{
"#{formula_name}": "#{another_tap}"
}
EOS
formula = described_class.factory("#{tap}/#{formula_name}")
expect(formula).to be_a(Formula)
expect(formula.tap).to eq(another_tap)
expect(formula.path).to eq(another_tap_formula_path)
end
end
context "when loading from Tap" do
let(:tap) { Tap.fetch("homebrew", "foo") }
let(:another_tap) { Tap.fetch("homebrew", "bar") }
let(:formula_path) { tap.path/"Formula/#{formula_name}.rb" }
let(:alias_name) { "bar" }
let(:alias_dir) { tap.alias_dir }
let(:alias_path) { alias_dir/alias_name }
before do
alias_dir.mkpath
FileUtils.ln_s formula_path, alias_path
end
it "returns a Formula when given a name" do
expect(described_class.factory(formula_name)).to be_a(Formula)
end
it "returns a Formula from an Alias path" do
expect(described_class.factory(alias_name)).to be_a(Formula)
end
it "returns a Formula from a fully qualified Alias path" do
expect(described_class.factory("#{tap.name}/#{alias_name}")).to be_a(Formula)
end
it "raises an error when the Formula cannot be found" do
expect do
described_class.factory("#{tap}/not_existed_formula")
end.to raise_error(TapFormulaUnavailableError)
end
it "returns a Formula when given a fully qualified name" do
expect(described_class.factory("#{tap}/#{formula_name}")).to be_a(Formula)
end
it "raises an error if a Formula is in multiple Taps" do
(another_tap.path/"Formula").mkpath
(another_tap.path/"Formula/#{formula_name}.rb").write formula_content
expect do
described_class.factory(formula_name)
end.to raise_error(TapFormulaAmbiguityError)
end
end
end
context "with the API" do
def formula_json_contents(extra_items = {})
{
formula_name => {
"name" => formula_name,
"desc" => "testball",
"homepage" => "https://example.com",
"installed" => [],
"outdated" => false,
"pinned" => false,
"license" => "MIT",
"revision" => 0,
"version_scheme" => 0,
"versions" => { "stable" => "0.1" },
"urls" => {
"stable" => {
"url" => "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz",
"tag" => nil,
"revision" => nil,
},
},
"bottle" => {
"stable" => {
"rebuild" => 0,
"root_url" => "file://#{bottle_dir}",
"files" => {
Utils::Bottles.tag.to_s => {
"cellar" => ":any",
"url" => "file://#{bottle_dir}/#{formula_name}",
"sha256" => "d7b9f4e8bf83608b71fe958a99f19f2e5e68bb2582965d32e41759c24f1aef97",
},
},
},
},
"keg_only_reason" => {
"reason" => ":provided_by_macos",
"explanation" => "",
},
"build_dependencies" => ["build_dep"],
"dependencies" => ["dep"],
"test_dependencies" => ["test_dep"],
"recommended_dependencies" => ["recommended_dep"],
"optional_dependencies" => ["optional_dep"],
"uses_from_macos" => ["uses_from_macos_dep"],
"requirements" => [
{
"name" => "xcode",
"cask" => nil,
"download" => nil,
"version" => "1.0",
"contexts" => ["build"],
"specs" => ["stable"],
},
],
"conflicts_with" => ["conflicting_formula"],
"conflicts_with_reasons" => ["it does"],
"link_overwrite" => ["bin/abc"],
"linked_keg" => nil,
"caveats" => "example caveat string\n/$HOME\n$HOMEBREW_PREFIX",
"service" => {
"name" => { macos: "custom.launchd.name", linux: "custom.systemd.name" },
"run" => ["$HOMEBREW_PREFIX/opt/formula_name/bin/beanstalkd", "test"],
"run_type" => "immediate",
"working_dir" => "/$HOME",
},
"ruby_source_path" => "Formula/#{formula_name}.rb",
"ruby_source_checksum" => { "sha256" => "ABCDEFGHIJKLMNOPQRSTUVWXYZ" },
"tap_git_head" => "0000000000000000000000000000000000000000",
}.merge(extra_items),
}
end
let(:deprecate_json) do
{
"deprecated" => true,
"deprecation_date" => "2022-06-15",
"deprecation_reason" => "repo_archived",
"deprecation_replacement_formula" => nil,
"deprecation_replacement_cask" => nil,
"deprecate_args" => { date: "2022-06-15", because: :repo_archived },
}
end
let(:disable_json) do
{
"disabled" => true,
"disable_date" => "2022-06-15",
"disable_reason" => "requires something else",
"disable_replacement_formula" => nil,
"disable_replacement_cask" => nil,
"disable_args" => { date: "2022-06-15", because: "requires something else" },
}
end
let(:future_date) { Date.today + 365 }
let(:deprecate_future_json) do
{
"deprecated" => true,
"deprecation_date" => future_date.to_s,
"deprecation_reason" => nil,
"deprecation_replacement_formula" => nil,
"deprecation_replacement_cask" => nil,
"deprecate_args" => {
date: future_date.to_s,
because: :repo_archived,
replacement_cask: "bar",
},
}
end
let(:disable_future_json) do
{
"deprecated" => true,
"deprecation_date" => nil,
"deprecation_reason" => "requires something else",
"deprecation_replacement_formula" => "foo",
"deprecation_replacement_cask" => nil,
"deprecate_args" => nil,
"disabled" => false,
"disable_date" => future_date.to_s,
"disable_reason" => nil,
"disable_replacement_formula" => nil,
"disable_replacement_cask" => nil,
"disable_args" => {
date: future_date.to_s,
because: "requires something else",
replacement_formula: "foo",
},
}
end
let(:variations_json) do
{
"variations" => {
Utils::Bottles.tag.to_s => {
"dependencies" => ["dep", "variations_dep"],
},
},
}
end
let(:older_macos_variations_json) do
{
"variations" => {
Utils::Bottles.tag.to_s => {
"dependencies" => ["uses_from_macos_dep"],
},
},
}
end
let(:linux_variations_json) do
{
"variations" => {
"x86_64_linux" => {
"dependencies" => ["dep"],
},
},
}
end
before do
# avoid unnecessary network calls
allow(Homebrew::API::Formula).to receive_messages(all_aliases: {}, all_renames: {})
allow(CoreTap.instance).to receive(:tap_migrations).and_return({})
allow(CoreCaskTap.instance).to receive(:tap_migrations).and_return({})
# don't try to load/fetch gcc/glibc
allow(DevelopmentTools).to receive_messages(needs_libc_formula?: false, needs_compiler_formula?: false)
end
it "returns a Formula when given a name" do
allow(Homebrew::API::Formula).to receive(:all_formulae).and_return formula_json_contents
formula = described_class.factory(formula_name)
expect(formula).to be_a(Formula)
expect(formula.keg_only_reason.reason).to eq :provided_by_macos
expect(formula.declared_deps.count).to eq 6
if OS.mac?
expect(formula.deps.count).to eq 5
else
expect(formula.deps.count).to eq 6
end
expect(formula.requirements.count).to eq 1
req = formula.requirements.first
expect(req).to be_an_instance_of XcodeRequirement
expect(req.version).to eq "1.0"
expect(req.tags).to eq [:build]
expect(formula.conflicts.map(&:name)).to include "conflicting_formula"
expect(formula.conflicts.map(&:reason)).to include "it does"
expect(formula.class.link_overwrite_paths).to include "bin/abc"
expect(formula.caveats).to eq "example caveat string\n#{Dir.home}\n#{HOMEBREW_PREFIX}"
expect(formula).to be_a_service
expect(formula.service.command).to eq(["#{HOMEBREW_PREFIX}/opt/formula_name/bin/beanstalkd", "test"])
expect(formula.service.run_type).to eq(:immediate)
expect(formula.service.working_dir).to eq(Dir.home)
expect(formula.plist_name).to eq("custom.launchd.name")
expect(formula.service_name).to eq("custom.systemd.name")
expect(formula.ruby_source_checksum.hexdigest).to eq("abcdefghijklmnopqrstuvwxyz")
expect do
formula.install
end.to raise_error("Cannot build from source from abstract formula.")
end
it "returns a Formula that can regenerate its JSON API" do
allow(Homebrew::API::Formula).to receive(:all_formulae).and_return formula_json_contents
formula = described_class.factory(formula_name)
expect(formula).to be_a(Formula)
expect(formula.loaded_from_api?).to be true
expected_hash = formula_json_contents[formula_name]
expect(formula.to_hash_with_variations).to eq(expected_hash)
end
it "returns a deprecated Formula when given a name" do
allow(Homebrew::API::Formula).to receive(:all_formulae).and_return formula_json_contents(deprecate_json)
formula = described_class.factory(formula_name)
expect(formula).to be_a(Formula)
expect(formula.deprecated?).to be true
expect(formula.deprecation_date).to eq(Date.parse("2022-06-15"))
expect(formula.deprecation_reason).to eq :repo_archived
expect do
formula.install
end.to raise_error("Cannot build from source from abstract formula.")
end
it "returns a disabled Formula when given a name" do
allow(Homebrew::API::Formula).to receive(:all_formulae).and_return formula_json_contents(disable_json)
formula = described_class.factory(formula_name)
expect(formula).to be_a(Formula)
expect(formula.disabled?).to be true
expect(formula.disable_date).to eq(Date.parse("2022-06-15"))
expect(formula.disable_reason).to eq("requires something else")
expect do
formula.install
end.to raise_error("Cannot build from source from abstract formula.")
end
it "returns a future-deprecated Formula when given a name" do
contents = formula_json_contents(deprecate_future_json)
allow(Homebrew::API::Formula).to receive(:all_formulae).and_return contents
formula = described_class.factory(formula_name)
expect(formula).to be_a(Formula)
expect(formula.deprecated?).to be false
expect(formula.deprecation_date).to eq(future_date)
expect(formula.deprecation_reason).to be_nil
expect(formula.deprecation_replacement_formula).to be_nil
expect(formula.deprecation_replacement_cask).to be_nil
expect do
formula.install
end.to raise_error("Cannot build from source from abstract formula.")
end
it "returns a future-disabled Formula when given a name" do
allow(Homebrew::API::Formula).to receive(:all_formulae).and_return formula_json_contents(disable_future_json)
formula = described_class.factory(formula_name)
expect(formula).to be_a(Formula)
expect(formula.deprecated?).to be true
expect(formula.deprecation_date).to be_nil
expect(formula.deprecation_reason).to eq("requires something else")
expect(formula.deprecation_replacement_formula).to eq("foo")
expect(formula.deprecation_replacement_cask).to be_nil
expect(formula.disabled?).to be false
expect(formula.disable_date).to eq(future_date)
expect(formula.disable_reason).to be_nil
expect(formula.disable_replacement_formula).to be_nil
expect(formula.disable_replacement_cask).to be_nil
expect do
formula.install
end.to raise_error("Cannot build from source from abstract formula.")
end
it "returns a Formula with variations when given a name", :needs_macos do
allow(Homebrew::API::Formula).to receive(:all_formulae).and_return formula_json_contents(variations_json)
formula = described_class.factory(formula_name)
expect(formula).to be_a(Formula)
expect(formula.declared_deps.count).to eq 7
expect(formula.deps.count).to eq 6
expect(formula.deps.map(&:name).include?("variations_dep")).to be true
expect(formula.deps.map(&:name).include?("uses_from_macos_dep")).to be false
end
it "returns a Formula without duplicated deps and uses_from_macos with variations on Linux", :needs_linux do
allow(Homebrew::API::Formula)
.to receive(:all_formulae).and_return formula_json_contents(linux_variations_json)
formula = described_class.factory(formula_name)
expect(formula).to be_a(Formula)
expect(formula.declared_deps.count).to eq 6
expect(formula.deps.count).to eq 6
expect(formula.deps.map(&:name).include?("uses_from_macos_dep")).to be true
end
it "returns a Formula with the correct uses_from_macos dep on older macOS", :needs_macos do
allow(Homebrew::API::Formula)
.to receive(:all_formulae).and_return formula_json_contents(older_macos_variations_json)
formula = described_class.factory(formula_name)
expect(formula).to be_a(Formula)
expect(formula.declared_deps.count).to eq 6
expect(formula.deps.count).to eq 5
expect(formula.deps.map(&:name).include?("uses_from_macos_dep")).to be true
end
context "with core tap migration renames" do
let(:foo_tap) { Tap.fetch("homebrew", "foo") }
before do
allow(Homebrew::API::Formula).to receive(:all_formulae).and_return formula_json_contents
foo_tap.path.mkpath
end
after do
FileUtils.rm_rf foo_tap.path
end
it "returns the tap migration rename by old formula_name" do
old_formula_name = "#{formula_name}-old"
(foo_tap.path/"tap_migrations.json").write <<~JSON
{ "#{old_formula_name}": "homebrew/core/#{formula_name}" }
JSON
loader = described_class::FromNameLoader.try_new(old_formula_name)
expect(loader).to be_a(described_class::FromAPILoader)
expect(loader.name).to eq formula_name
expect(loader.path).not_to exist
end
it "returns the tap migration rename by old full name" do
old_formula_name = "#{formula_name}-old"
(foo_tap.path/"tap_migrations.json").write <<~JSON
{ "#{old_formula_name}": "homebrew/core/#{formula_name}" }
JSON
loader = described_class::FromTapLoader.try_new("#{foo_tap}/#{old_formula_name}")
expect(loader).to be_a(described_class::FromAPILoader)
expect(loader.name).to eq formula_name
expect(loader.path).not_to exist
end
end
end
context "when passed a URL" do
it "raises an error when given an https URL" do
expect do
described_class.factory("https://brew.sh/foo.rb")
end.to raise_error(UnsupportedInstallationMethod)
end
it "raises an error when given a bottle URL" do
expect do
described_class.factory("https://brew.sh/foo-1.0.arm64_catalina.bottle.tar.gz")
end.to raise_error(UnsupportedInstallationMethod)
end
it "raises an error when given an ftp URL" do
expect do
described_class.factory("ftp://brew.sh/foo.rb")
end.to raise_error(UnsupportedInstallationMethod)
end
it "raises an error when given an sftp URL" do
expect do
described_class.factory("sftp://brew.sh/foo.rb")
end.to raise_error(UnsupportedInstallationMethod)
end
it "does not raise an error when given a file URL", :needs_utils_curl do
expect do
described_class.factory("file://#{TEST_FIXTURE_DIR}/testball.rb")
end.not_to raise_error
end
end
context "when passed ref with spaces" do
it "raises a FormulaUnavailableError error" do
expect do
described_class.factory("foo bar")
end.to raise_error(FormulaUnavailableError)
end
end
end
specify "::from_contents" do
expect(described_class.from_contents(formula_name, formula_path, formula_content)).to be_a(Formula)
end
describe "::to_rack" do
alias_matcher :exist, :be_exist
let(:rack_path) { HOMEBREW_CELLAR/formula_name }
context "when the Rack does not exist" do
it "returns the Rack" do
expect(described_class.to_rack(formula_name)).to eq(rack_path)
end
end
context "when the Rack exists" do
before do
rack_path.mkpath
end
it "returns the Rack" do
expect(described_class.to_rack(formula_name)).to eq(rack_path)
end
end
it "raises an error if the Formula is not available" do
expect do
described_class.to_rack("a/b/#{formula_name}")
end.to raise_error(TapFormulaUnavailableError)
end
end
describe "::core_path" do
it "returns the path to a Formula in the core tap" do
name = "foo-bar"
expect(described_class.core_path(name))
.to eq(Pathname.new("#{HOMEBREW_LIBRARY}/Taps/homebrew/homebrew-core/Formula/#{name}.rb"))
end
end
describe "::loader_for" do
context "when given a relative path with two slashes" do
it "returns a `FromPathLoader`" do
mktmpdir.cd do
FileUtils.mkdir "Formula"
FileUtils.touch "Formula/gcc.rb"
expect(described_class.loader_for("./Formula/gcc.rb")).to be_a Formulary::FromPathLoader
end
end
end
context "when given a tapped name" do
it "returns a `FromTapLoader`", :no_api do
expect(described_class.loader_for("homebrew/core/gcc")).to be_a Formulary::FromTapLoader
end
end
context "when not using the API", :no_api do
context "when a formula is migrated" do
let(:token) { "foo" }
let(:core_tap) { CoreTap.instance }
let(:core_cask_tap) { CoreCaskTap.instance }
let(:tap_migrations) do
{
token => new_tap.name,
}
end
before do
old_tap.path.mkpath
new_tap.path.mkpath
(old_tap.path/"tap_migrations.json").write tap_migrations.to_json
end
context "to a cask in the default tap" do
let(:old_tap) { core_tap }
let(:new_tap) { core_cask_tap }
let(:cask_file) { new_tap.cask_dir/"#{token}.rb" }
before do
new_tap.cask_dir.mkpath
FileUtils.touch cask_file
end
it "warn only once" do
expect do
described_class.loader_for(token)
end.to output(
a_string_including("Warning: Formula #{token} was renamed to #{new_tap}/#{token}.").once,
).to_stderr
end
end
context "to the default tap" do
let(:old_tap) { core_cask_tap }
let(:new_tap) { core_tap }
let(:formula_file) { new_tap.formula_dir/"#{token}.rb" }
before do
new_tap.formula_dir.mkpath
FileUtils.touch formula_file
end
it "does not warn when loading the short token" do
expect do
described_class.loader_for(token)
end.not_to output.to_stderr
end
it "does not warn when loading the full token in the default tap" do
expect do
described_class.loader_for("#{new_tap}/#{token}")
end.not_to output.to_stderr
end
it "warns when loading the full token in the old tap" do
expect do
described_class.loader_for("#{old_tap}/#{token}")
end.to output(
a_string_including("Formula #{old_tap}/#{token} was renamed to #{token}.").once,
).to_stderr
end
# FIXME
# context "when there is an infinite tap migration loop" do
# before do
# (new_tap.path/"tap_migrations.json").write({
# token => old_tap.name,
# }.to_json)
# end
#
# it "stops recursing" do
# expect do
# described_class.loader_for("#{new_tap}/#{token}")
# end.not_to output.to_stderr
# end
# end
end
context "to a third-party tap" do
let(:old_tap) { Tap.fetch("another", "foo") }
let(:new_tap) { Tap.fetch("another", "bar") }
let(:formula_file) { new_tap.formula_dir/"#{token}.rb" }
before do
new_tap.formula_dir.mkpath
FileUtils.touch formula_file
end
after do
FileUtils.rm_rf HOMEBREW_TAP_DIRECTORY/"another"
end
# FIXME
# It would be preferable not to print a warning when installing with the short token
it "warns when loading the short token" do
expect do
described_class.loader_for(token)
end.to output(
a_string_including("Formula #{old_tap}/#{token} was renamed to #{new_tap}/#{token}.").once,
).to_stderr
end
it "does not warn when loading the full token in the new tap" do
expect do
described_class.loader_for("#{new_tap}/#{token}")
end.not_to output.to_stderr
end
it "warns when loading the full token in the old tap" do
expect do
described_class.loader_for("#{old_tap}/#{token}")
end.to output(
a_string_including("Formula #{old_tap}/#{token} was renamed to #{new_tap}/#{token}.").once,
).to_stderr
end
end
end
end
end
end
# rubocop:enable RSpec/AggregateExamples
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/utils_spec.rb | Library/Homebrew/test/utils_spec.rb | # frozen_string_literal: true
require "utils"
RSpec.describe Utils do
describe ".deconstantize" do
it "removes the rightmost segment from the constant expression in the string" do
expect(described_class.deconstantize("Net::HTTP")).to eq("Net")
expect(described_class.deconstantize("::Net::HTTP")).to eq("::Net")
expect(described_class.deconstantize("String")).to eq("")
expect(described_class.deconstantize("::String")).to eq("")
end
it "returns an empty string if the namespace is empty" do
expect(described_class.deconstantize("")).to eq("")
expect(described_class.deconstantize("::")).to eq("")
end
end
describe ".demodulize" do
it "removes the module part from the expression in the string" do
expect(described_class.demodulize("Foo::Bar")).to eq("Bar")
end
it "returns the string if it does not contain a module expression" do
expect(described_class.demodulize("FooBar")).to eq("FooBar")
end
it "returns an empty string if the namespace is empty" do
expect(described_class.demodulize("")).to eq("")
expect(described_class.demodulize("::")).to eq("")
end
it "raise an ArgumentError when passed nil" do
expect { described_class.demodulize(nil) }.to raise_error(ArgumentError)
end
end
specify ".parse_author!" do
parse_error_msg = /Unable to parse name and email/
expect(described_class.parse_author!("John Doe <john.doe@example.com>"))
.to eq({ name: "John Doe", email: "john.doe@example.com" })
expect { described_class.parse_author!("") }
.to raise_error(parse_error_msg)
expect { described_class.parse_author!("John Doe") }
.to raise_error(parse_error_msg)
expect { described_class.parse_author!("<john.doe@example.com>") }
.to raise_error(parse_error_msg)
end
describe ".pluralize" do
it "combines the stem with the default suffix based on the count" do
expect(described_class.pluralize("foo", 0)).to eq("foos")
expect(described_class.pluralize("foo", 1)).to eq("foo")
expect(described_class.pluralize("foo", 2)).to eq("foos")
end
it "combines the stem with the singular suffix based on the count" do
expect(described_class.pluralize("foo", 0, singular: "o")).to eq("foos")
expect(described_class.pluralize("foo", 1, singular: "o")).to eq("fooo")
expect(described_class.pluralize("foo", 2, singular: "o")).to eq("foos")
end
it "combines the stem with the plural suffix based on the count" do
expect(described_class.pluralize("foo", 0, plural: "es")).to eq("fooes")
expect(described_class.pluralize("foo", 1, plural: "es")).to eq("foo")
expect(described_class.pluralize("foo", 2, plural: "es")).to eq("fooes")
end
it "combines the stem with the singular and plural suffix based on the count" do
expect(described_class.pluralize("foo", 0, singular: "o", plural: "es")).to eq("fooes")
expect(described_class.pluralize("foo", 1, singular: "o", plural: "es")).to eq("fooo")
expect(described_class.pluralize("foo", 2, singular: "o", plural: "es")).to eq("fooes")
end
it "includes the count when requested" do
expect(described_class.pluralize("foo", 0, include_count: true)).to eq("0 foos")
expect(described_class.pluralize("foo", 1, include_count: true)).to eq("1 foo")
expect(described_class.pluralize("foo", 2, include_count: true)).to eq("2 foos")
end
end
describe ".underscore" do
# commented out entries require acronyms inflections
let(:words) do
[
["API", "api"],
["APIController", "api_controller"],
["Nokogiri::HTML", "nokogiri/html"],
# ["HTTPAPI", "http_api"],
["HTTP::Get", "http/get"],
["SSLError", "ssl_error"],
# ["RESTful", "restful"],
# ["RESTfulController", "restful_controller"],
# ["Nested::RESTful", "nested/restful"],
# ["IHeartW3C", "i_heart_w3c"],
# ["PhDRequired", "phd_required"],
# ["IRoRU", "i_ror_u"],
# ["RESTfulHTTPAPI", "restful_http_api"],
# ["HTTP::RESTful", "http/restful"],
# ["HTTP::RESTfulAPI", "http/restful_api"],
# ["APIRESTful", "api_restful"],
["Capistrano", "capistrano"],
["CapiController", "capi_controller"],
["HttpsApis", "https_apis"],
["Html5", "html5"],
["Restfully", "restfully"],
["RoRails", "ro_rails"],
]
end
it "converts strings to underscore case" do
words.each do |camel, under|
expect(described_class.underscore(camel)).to eq(under)
expect(described_class.underscore(under)).to eq(under)
end
end
end
describe ".convert_to_string_or_symbol" do
specify(:aggregate_failures) do
expect(described_class.convert_to_string_or_symbol(":example")).to eq(:example)
expect(described_class.convert_to_string_or_symbol("example")).to eq("example")
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/formatter_spec.rb | Library/Homebrew/test/formatter_spec.rb | # frozen_string_literal: true
require "utils/formatter"
require "utils/tty"
RSpec.describe Formatter do
describe "::columns" do
subject(:columns) { described_class.columns(input) }
let(:input) do
%w[
aa
bbb
ccc
dd
]
end
it "doesn't output columns if $stdout is not a TTY." do
allow_any_instance_of(IO).to receive(:tty?).and_return(false)
allow(Tty).to receive(:width).and_return(10)
expect(columns).to eq(
"aa\n" \
"bbb\n" \
"ccc\n" \
"dd\n",
)
end
describe "$stdout is a TTY" do
it "outputs columns" do
allow_any_instance_of(IO).to receive(:tty?).and_return(true)
allow(Tty).to receive(:width).and_return(10)
expect(columns).to eq(
"aa ccc\n" \
"bbb dd\n",
)
end
it "outputs only one line if everything fits" do
allow_any_instance_of(IO).to receive(:tty?).and_return(true)
allow(Tty).to receive(:width).and_return(20)
expect(columns).to eq(
"aa bbb ccc dd\n",
)
end
end
describe "with empty input" do
let(:input) { [] }
it { is_expected.to eq("\n") }
end
end
describe "::format_help_text" do
it "indents subcommand descriptions" do
# The following example help text was carefully crafted to test all five regular expressions in the method.
# Also, the text is designed in such a way such that options (e.g. `--foo`) would be wrapped to the
# beginning of new lines if normal wrapping was used. This is to test that the method works as expected
# and doesn't allow options to start new lines. Be careful when changing the text so these checks aren't lost.
text = <<~HELP
Usage: brew command [<options>] <formula>...
This is a test command.
Single line breaks are removed, but the entire line is still wrapped at the correct point.
Paragraphs are preserved but
are also wrapped at the right point. Here's some more filler text to get this line to be long enough.
Options, for example: --foo, are never placed at the start of a line.
`brew command` [`state`]:
Display the current state of the command.
`brew command` (`on`|`off`):
Turn the command on or off respectively.
-f, --foo This line is wrapped with a hanging indent. --test. The --test option isn't at the start of a line.
-b, --bar The following option is not left on its own: --baz
-h, --help Show this message.
HELP
expected = <<~HELP
Usage: brew command [<options>] <formula>...
This is a test command. Single line breaks are removed, but the entire line is
still wrapped at the correct point.
Paragraphs are preserved but are also wrapped at the right point. Here's some
more filler text to get this line to be long enough. Options, for
example: --foo, are never placed at the start of a line.
`brew command` [`state`]:
Display the current state of the command.
`brew command` (`on`|`off`):
Turn the command on or off respectively.
-f, --foo This line is wrapped with a hanging
indent. --test. The --test option isn't at
the start of a line.
-b, --bar The following option is not left on its
own: --baz
-h, --help Show this message.
HELP
expect(described_class.format_help_text(text, width: 80)).to eq expected
end
end
describe "::truncate" do
it "returns the original string if it's shorter than max length" do
expect(described_class.truncate("short", max: 10)).to eq("short")
end
it "truncates strings longer than max length" do
expect(described_class.truncate("this is a long string", max: 10)).to eq("this is...")
end
it "uses custom omission string" do
expect(described_class.truncate("this is a long string", max: 10, omission: " [...]")).to eq("this [...]")
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/formula_creator_spec.rb | Library/Homebrew/test/formula_creator_spec.rb | # frozen_string_literal: true
require "formula_creator"
RSpec.describe Homebrew::FormulaCreator do
describe ".new" do
tests = {
"generic tarball URL": {
url: "http://digit-labs.org/files/tools/synscan/releases/synscan-5.02.tar.gz",
expected_name: "synscan",
expected_version: "5.02",
},
"gitweb URL": {
url: "http://www.codesrc.com/gitweb/index.cgi?p=libzipper.git;a=summary",
expected_name: "libzipper",
},
"GitHub repository URL with .git": {
url: "https://github.com/Homebrew/brew.git",
fetch: true,
github_user_repository: ["Homebrew", "brew"],
expected_name: "brew",
expected_head: true,
},
"GitHub archive URL": {
url: "https://github.com/Homebrew/brew/archive/4.5.7.tar.gz",
fetch: true,
github_user_repository: ["Homebrew", "brew"],
expected_name: "brew",
expected_version: "4.5.7",
},
"GitHub releases URL": {
url: "https://github.com/stella-emu/stella/releases/download/6.7/stella-6.7-src.tar.xz",
fetch: true,
github_user_repository: ["stella-emu", "stella"],
expected_name: "stella",
expected_version: "6.7",
},
"GitHub latest release": {
url: "https://github.com/buildpacks/pack",
fetch: true,
github_user_repository: ["buildpacks", "pack"],
latest_release: { "tag_name" => "v0.37.0" },
expected_name: "pack",
expected_url: "https://github.com/buildpacks/pack/archive/refs/tags/v0.37.0.tar.gz",
expected_version: "v0.37.0",
},
"GitHub URL with name override": {
url: "https://github.com/RooVetGit/Roo-Code",
name: "roo",
expected_name: "roo",
},
}
tests.each do |description, test|
it "parses #{description}" do
fetch = test.fetch(:fetch, false)
if fetch
github_user_repository = test.fetch(:github_user_repository)
allow(GitHub).to receive(:repository).with(*github_user_repository)
if (latest_release = test[:latest_release])
expect(GitHub).to receive(:get_latest_release).with(*github_user_repository).and_return(latest_release)
end
end
formula_creator = described_class.new(url: test.fetch(:url), name: test[:name], fetch:)
expect(formula_creator.name).to eq(test.fetch(:expected_name))
if (expected_version = test[:expected_version])
expect(formula_creator.version).to eq(expected_version)
else
expect(formula_creator.version).to be_null
end
if (expected_url = test[:expected_url])
expect(formula_creator.url).to eq(expected_url)
end
expect(formula_creator.head).to eq(test.fetch(:expected_head, false))
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/free_port_spec.rb | Library/Homebrew/test/free_port_spec.rb | # frozen_string_literal: true
require "socket"
require "formula_free_port"
RSpec.describe Homebrew::FreePort do
# Sorbet and rubocop-rspec disagree here.
# rubocop:disable RSpec/DescribedClass
include Homebrew::FreePort
# rubocop:enable RSpec/DescribedClass
describe "#free_port" do
it "returns a free TCP/IP port" do
# IANA suggests user port from 1024 to 49151
# and dynamic port for 49152 to 65535
# http://www.iana.org/assignments/port-numbers
min_port = 1024
max_port = 65535
port = free_port
expect(port).to be_between(min_port, max_port)
expect { TCPServer.new(port).close }.not_to raise_error
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/compiler_selector_spec.rb | Library/Homebrew/test/compiler_selector_spec.rb | # frozen_string_literal: true
require "compilers"
require "software_spec"
RSpec.describe CompilerSelector do
subject(:selector) { described_class.new(software_spec, versions, compilers) }
let(:compilers) { [:clang, :gnu] }
let(:software_spec) { SoftwareSpec.new }
let(:cc) { :clang }
let(:versions) { class_double(DevelopmentTools, clang_build_version: Version.new("600")) }
before do
allow(versions).to receive(:gcc_version) do |name|
case name
when "gcc-12" then Version.new("12.1")
when "gcc-11" then Version.new("11.1")
when "gcc-10" then Version.new("10.1")
when "gcc-9" then Version.new("9.1")
else Version::NULL
end
end
end
describe "#compiler", :no_api do
it "defaults to cc" do
expect(selector.compiler).to eq(cc)
end
it "returns clang if it fails with non-Apple gcc" do
software_spec.fails_with(gcc: "12")
expect(selector.compiler).to eq(:clang)
end
it "still returns gcc-12 if it fails with gcc without a specific version" do
software_spec.fails_with(:clang)
expect(selector.compiler).to eq("gcc-12")
end
it "returns gcc-11 if gcc formula offers gcc-11 on mac", :needs_macos do
software_spec.fails_with(:clang)
allow(Formulary).to receive(:factory)
.with("gcc")
.and_return(instance_double(Formula, version: Version.new("11.0")))
expect(selector.compiler).to eq("gcc-11")
end
it "returns gcc-10 if gcc formula offers gcc-10 on linux", :needs_linux do
software_spec.fails_with(:clang)
allow(Formulary).to receive(:factory)
.with(OS::LINUX_PREFERRED_GCC_COMPILER_FORMULA)
.and_return(instance_double(Formula, version: Version.new("10.0")))
expect(selector.compiler).to eq("gcc-10")
end
it "returns gcc-11 if gcc formula offers gcc-10 and fails with gcc-10 and gcc-12 on linux", :needs_linux do
software_spec.fails_with(:clang)
software_spec.fails_with(gcc: "10")
software_spec.fails_with(gcc: "12")
allow(Formulary).to receive(:factory)
.with(OS::LINUX_PREFERRED_GCC_COMPILER_FORMULA)
.and_return(instance_double(Formula, version: Version.new("10.0")))
expect(selector.compiler).to eq("gcc-11")
end
it "returns gcc-12 if gcc formula offers gcc-11 and fails with gcc <= 11 on linux", :needs_linux do
software_spec.fails_with(:clang)
software_spec.fails_with(:gcc) { version "11" }
allow(Formulary).to receive(:factory)
.with(OS::LINUX_PREFERRED_GCC_COMPILER_FORMULA)
.and_return(instance_double(Formula, version: Version.new("11.0")))
expect(selector.compiler).to eq("gcc-12")
end
it "returns gcc-12 if gcc-12 is version 12.1 but spec fails with gcc-12 <= 12.0" do
software_spec.fails_with(:clang)
software_spec.fails_with(gcc: "12") { version "12.0" }
expect(selector.compiler).to eq("gcc-12")
end
it "returns gcc-11 if gcc-12 is version 12.1 but spec fails with gcc-12 <= 12.1" do
software_spec.fails_with(:clang)
software_spec.fails_with(gcc: "12") { version "12.1" }
expect(selector.compiler).to eq("gcc-11")
end
it "raises an error when gcc or llvm is missing (hash syntax)" do
software_spec.fails_with(:clang)
software_spec.fails_with(gcc: "12")
software_spec.fails_with(gcc: "11")
software_spec.fails_with(gcc: "10")
software_spec.fails_with(gcc: "9")
expect { selector.compiler }.to raise_error(CompilerSelectionError)
end
it "raises an error when gcc or llvm is missing (symbol syntax)" do
software_spec.fails_with(:clang)
software_spec.fails_with(:gcc)
expect { selector.compiler }.to raise_error(CompilerSelectionError)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/service_spec.rb | Library/Homebrew/test/service_spec.rb | # frozen_string_literal: true
require "formula"
require "service"
RSpec.describe Homebrew::Service do
let(:name) { "formula_name" }
def stub_formula(&block)
formula(name) do
url "https://brew.sh/test-1.0.tbz"
instance_eval(&block) if block
end
end
def stub_formula_with_service_sockets(sockets_var)
stub_formula do
service do
run opt_bin/"beanstalkd"
sockets sockets_var
end
end
end
describe "#std_service_path_env" do
it "returns valid std_service_path_env" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
run_type :immediate
environment_variables PATH: std_service_path_env
error_log_path var/"log/beanstalkd.error.log"
log_path var/"log/beanstalkd.log"
working_dir var
keep_alive true
end
end
path = f.service.std_service_path_env
expect(path).to eq("#{HOMEBREW_PREFIX}/bin:#{HOMEBREW_PREFIX}/sbin:/usr/bin:/bin:/usr/sbin:/sbin")
end
end
describe "#process_type" do
it "throws for unexpected type" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
process_type :cow
end
end
expect do
f.service.manual_command
end.to raise_error TypeError, "Service#process_type allows: 'background'/'standard'/'interactive'/'adaptive'"
end
end
describe "#throttle_interval" do
it "accepts a valid throttle_interval value" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
throttle_interval 5
end
end
expect(f.service.throttle_interval).to be(5)
end
it "includes throttle_interval value in plist output" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
throttle_interval 15
end
end
plist = f.service.to_plist
expect(plist).to include("<key>ThrottleInterval</key>")
expect(plist).to include("<integer>15</integer>")
end
# Launchd says that it ignores ThrottleInterval values of zero but it's not actually true.
# https://gist.github.com/dabrahams/4092951#:~:text=Set%20%3CThrottleInterval%3E%20to,than%2010%20seconds.
it "includes throttle_interval value of zero in plist output" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
throttle_interval 0
end
end
plist = f.service.to_plist
expect(plist).to include("<key>ThrottleInterval</key>")
expect(plist).to include("<integer>0</integer>")
end
it "does not include throttle_interval in plist when not set" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
end
end
plist = f.service.to_plist
expect(plist).not_to include("<key>ThrottleInterval</key>")
end
end
describe "#nice" do
it "accepts a valid nice level" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
nice 5
end
end
expect(f.service.nice).to be(5)
end
it "throws error for negative nice values without require_root" do
expect do
stub_formula do
service do
run opt_bin/"beanstalkd"
nice(-10)
end
end.service
end.to raise_error TypeError, "Service#nice: require_root true is required for negative nice values"
end
it "allows negative nice values when require_root is set" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
require_root true
nice(-10)
end
end
expect(f.service.requires_root?).to be(true)
expect { f.service.to_plist }.not_to raise_error
end
it "does not require require_root for positive nice values" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
nice 10
end
end
expect(f.service.requires_root?).to be(false)
expect { f.service.to_plist }.not_to raise_error
end
it "accepts nice value of zero" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
nice 0
end
end
expect(f.service.nice).to be(0)
expect(f.service.requires_root?).to be(false)
end
it "includes nice value in plist output" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
nice 5
end
end
plist = f.service.to_plist
expect(plist).to include("<key>Nice</key>")
expect(plist).to include("<integer>5</integer>")
end
it "includes nice value in systemd unit output" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
require_root true
nice(-5)
end
end
unit = f.service.to_systemd_unit
expect(unit).to include("Nice=-5")
end
it "does not include nice in plist when not set" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
end
end
plist = f.service.to_plist
expect(plist).not_to include("<key>Nice</key>")
end
it "does not include nice in systemd unit when not set" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
end
end
unit = f.service.to_systemd_unit
expect(unit).not_to include("Nice=")
end
it "throws for nice too low" do
expect do
stub_formula do
service do
run opt_bin/"beanstalkd"
nice(-21)
end
end.service
end.to raise_error TypeError, "Service#nice value should be in -20..19"
end
it "throws for nice too high" do
expect do
stub_formula do
service do
run opt_bin/"beanstalkd"
nice 20
end
end.service
end.to raise_error TypeError, "Service#nice value should be in -20..19"
end
end
describe "#keep_alive" do
it "throws for unexpected keys" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
keep_alive test: "key"
end
end
expect do
f.service.manual_command
end.to raise_error TypeError, "Service#keep_alive only allows: [:always, :successful_exit, :crashed, :path]"
end
end
describe "#requires_root?" do
it "returns status when set" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
require_root true
end
end
expect(f.service.requires_root?).to be(true)
end
it "returns status when not set" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
end
end
expect(f.service.requires_root?).to be(false)
end
end
describe "#run_type" do
it "throws for unexpected type" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
run_type :cow
end
end
expect do
f.service.manual_command
end.to raise_error TypeError, "Service#run_type allows: 'immediate'/'interval'/'cron'"
end
end
describe "#sockets" do
let(:sockets_type_error_message) { "Service#sockets a formatted socket definition as <type>://<host>:<port>" }
it "throws for missing type" do
[
stub_formula_with_service_sockets("127.0.0.1:80"),
stub_formula_with_service_sockets({ socket: "127.0.0.1:80" }),
].each do |f|
expect { f.service.manual_command }.to raise_error TypeError, sockets_type_error_message
end
end
it "throws for missing host" do
[
stub_formula_with_service_sockets("tcp://:80"),
stub_formula_with_service_sockets({ socket: "tcp://:80" }),
].each do |f|
expect { f.service.manual_command }.to raise_error TypeError, sockets_type_error_message
end
end
it "throws for missing port" do
[
stub_formula_with_service_sockets("tcp://127.0.0.1"),
stub_formula_with_service_sockets({ socket: "tcp://127.0.0.1" }),
].each do |f|
expect { f.service.manual_command }.to raise_error TypeError, sockets_type_error_message
end
end
it "throws for invalid host" do
[
stub_formula_with_service_sockets("tcp://300.0.0.1:80"),
stub_formula_with_service_sockets({ socket: "tcp://300.0.0.1:80" }),
].each do |f|
expect do
f.service.manual_command
end.to raise_error TypeError, "Service#sockets expects a valid ipv4 or ipv6 host address"
end
end
end
describe "#manual_command" do
it "returns valid manual_command" do
f = stub_formula do
service do
run "#{HOMEBREW_PREFIX}/bin/beanstalkd"
run_type :immediate
environment_variables PATH: std_service_path_env, ETC_DIR: etc/"beanstalkd"
error_log_path var/"log/beanstalkd.error.log"
log_path var/"log/beanstalkd.log"
working_dir var
keep_alive true
end
end
path = f.service.manual_command
expect(path).to eq("ETC_DIR=\"#{HOMEBREW_PREFIX}/etc/beanstalkd\" #{HOMEBREW_PREFIX}/bin/beanstalkd")
end
it "returns valid manual_command without variables" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
run_type :immediate
environment_variables PATH: std_service_path_env
error_log_path var/"log/beanstalkd.error.log"
log_path var/"log/beanstalkd.log"
working_dir var
keep_alive true
end
end
path = f.service.manual_command
expect(path).to eq("#{HOMEBREW_PREFIX}/opt/formula_name/bin/beanstalkd")
end
end
describe "#to_plist" do
it "returns valid plist" do
f = stub_formula do
service do
run [opt_bin/"beanstalkd", "test"]
run_type :immediate
environment_variables PATH: std_service_path_env, FOO: "BAR", ETC_DIR: etc/"beanstalkd"
error_log_path var/"log/beanstalkd.error.log"
log_path var/"log/beanstalkd.log"
input_path var/"in/beanstalkd"
require_root true
root_dir var
working_dir var
keep_alive true
launch_only_once true
process_type :interactive
restart_delay 30
throttle_interval 5
nice 5
interval 5
macos_legacy_timers true
end
end
plist = f.service.to_plist
plist_expect = <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
\t<key>EnvironmentVariables</key>
\t<dict>
\t\t<key>ETC_DIR</key>
\t\t<string>#{HOMEBREW_PREFIX}/etc/beanstalkd</string>
\t\t<key>FOO</key>
\t\t<string>BAR</string>
\t\t<key>PATH</key>
\t\t<string>#{HOMEBREW_PREFIX}/bin:#{HOMEBREW_PREFIX}/sbin:/usr/bin:/bin:/usr/sbin:/sbin</string>
\t</dict>
\t<key>KeepAlive</key>
\t<true/>
\t<key>Label</key>
\t<string>homebrew.mxcl.formula_name</string>
\t<key>LaunchOnlyOnce</key>
\t<true/>
\t<key>LegacyTimers</key>
\t<true/>
\t<key>LimitLoadToSessionType</key>
\t<array>
\t\t<string>Aqua</string>
\t\t<string>Background</string>
\t\t<string>LoginWindow</string>
\t\t<string>StandardIO</string>
\t\t<string>System</string>
\t</array>
\t<key>Nice</key>
\t<integer>5</integer>
\t<key>ProcessType</key>
\t<string>Interactive</string>
\t<key>ProgramArguments</key>
\t<array>
\t\t<string>#{HOMEBREW_PREFIX}/opt/formula_name/bin/beanstalkd</string>
\t\t<string>test</string>
\t</array>
\t<key>RootDirectory</key>
\t<string>#{HOMEBREW_PREFIX}/var</string>
\t<key>RunAtLoad</key>
\t<true/>
\t<key>StandardErrorPath</key>
\t<string>#{HOMEBREW_PREFIX}/var/log/beanstalkd.error.log</string>
\t<key>StandardInPath</key>
\t<string>#{HOMEBREW_PREFIX}/var/in/beanstalkd</string>
\t<key>StandardOutPath</key>
\t<string>#{HOMEBREW_PREFIX}/var/log/beanstalkd.log</string>
\t<key>ThrottleInterval</key>
\t<integer>5</integer>
\t<key>TimeOut</key>
\t<integer>30</integer>
\t<key>WorkingDirectory</key>
\t<string>#{HOMEBREW_PREFIX}/var</string>
</dict>
</plist>
EOS
expect(plist).to eq(plist_expect)
end
it "returns valid plist with socket" do
plist_expect = <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
\t<key>Label</key>
\t<string>homebrew.mxcl.formula_name</string>
\t<key>LimitLoadToSessionType</key>
\t<array>
\t\t<string>Aqua</string>
\t\t<string>Background</string>
\t\t<string>LoginWindow</string>
\t\t<string>StandardIO</string>
\t\t<string>System</string>
\t</array>
\t<key>ProgramArguments</key>
\t<array>
\t\t<string>#{HOMEBREW_PREFIX}/opt/formula_name/bin/beanstalkd</string>
\t</array>
\t<key>RunAtLoad</key>
\t<true/>
\t<key>Sockets</key>
\t<dict>
\t\t<key>listeners</key>
\t\t<dict>
\t\t\t<key>SockNodeName</key>
\t\t\t<string>127.0.0.1</string>
\t\t\t<key>SockProtocol</key>
\t\t\t<string>TCP</string>
\t\t\t<key>SockServiceName</key>
\t\t\t<string>80</string>
\t\t</dict>
\t</dict>
</dict>
</plist>
EOS
[
stub_formula_with_service_sockets("tcp://127.0.0.1:80"),
stub_formula_with_service_sockets({ listeners: "tcp://127.0.0.1:80" }),
].each do |f|
plist = f.service.to_plist
expect(plist).to eq(plist_expect)
end
end
it "returns valid plist with multiple sockets" do
f = stub_formula do
service do
run [opt_bin/"beanstalkd", "test"]
sockets socket: "tcp://0.0.0.0:80", socket_tls: "tcp://0.0.0.0:443"
end
end
plist = f.service.to_plist
plist_expect = <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
\t<key>Label</key>
\t<string>homebrew.mxcl.formula_name</string>
\t<key>LimitLoadToSessionType</key>
\t<array>
\t\t<string>Aqua</string>
\t\t<string>Background</string>
\t\t<string>LoginWindow</string>
\t\t<string>StandardIO</string>
\t\t<string>System</string>
\t</array>
\t<key>ProgramArguments</key>
\t<array>
\t\t<string>#{HOMEBREW_PREFIX}/opt/formula_name/bin/beanstalkd</string>
\t\t<string>test</string>
\t</array>
\t<key>RunAtLoad</key>
\t<true/>
\t<key>Sockets</key>
\t<dict>
\t\t<key>socket</key>
\t\t<dict>
\t\t\t<key>SockNodeName</key>
\t\t\t<string>0.0.0.0</string>
\t\t\t<key>SockProtocol</key>
\t\t\t<string>TCP</string>
\t\t\t<key>SockServiceName</key>
\t\t\t<string>80</string>
\t\t</dict>
\t\t<key>socket_tls</key>
\t\t<dict>
\t\t\t<key>SockNodeName</key>
\t\t\t<string>0.0.0.0</string>
\t\t\t<key>SockProtocol</key>
\t\t\t<string>TCP</string>
\t\t\t<key>SockServiceName</key>
\t\t\t<string>443</string>
\t\t</dict>
\t</dict>
</dict>
</plist>
EOS
expect(plist).to eq(plist_expect)
end
it "returns valid partial plist" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
run_type :immediate
end
end
plist = f.service.to_plist
plist_expect = <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
\t<key>Label</key>
\t<string>homebrew.mxcl.formula_name</string>
\t<key>LimitLoadToSessionType</key>
\t<array>
\t\t<string>Aqua</string>
\t\t<string>Background</string>
\t\t<string>LoginWindow</string>
\t\t<string>StandardIO</string>
\t\t<string>System</string>
\t</array>
\t<key>ProgramArguments</key>
\t<array>
\t\t<string>#{HOMEBREW_PREFIX}/opt/formula_name/bin/beanstalkd</string>
\t</array>
\t<key>RunAtLoad</key>
\t<true/>
</dict>
</plist>
EOS
expect(plist).to eq(plist_expect)
end
it "returns valid partial plist with run_at_load being false" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
run_type :immediate
run_at_load false
end
end
plist = f.service.to_plist
plist_expect = <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
\t<key>Label</key>
\t<string>homebrew.mxcl.formula_name</string>
\t<key>LimitLoadToSessionType</key>
\t<array>
\t\t<string>Aqua</string>
\t\t<string>Background</string>
\t\t<string>LoginWindow</string>
\t\t<string>StandardIO</string>
\t\t<string>System</string>
\t</array>
\t<key>ProgramArguments</key>
\t<array>
\t\t<string>#{HOMEBREW_PREFIX}/opt/formula_name/bin/beanstalkd</string>
\t</array>
\t<key>RunAtLoad</key>
\t<false/>
</dict>
</plist>
EOS
expect(plist).to eq(plist_expect)
end
it "returns valid interval plist" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
run_type :interval
interval 5
end
end
plist = f.service.to_plist
plist_expect = <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
\t<key>Label</key>
\t<string>homebrew.mxcl.formula_name</string>
\t<key>LimitLoadToSessionType</key>
\t<array>
\t\t<string>Aqua</string>
\t\t<string>Background</string>
\t\t<string>LoginWindow</string>
\t\t<string>StandardIO</string>
\t\t<string>System</string>
\t</array>
\t<key>ProgramArguments</key>
\t<array>
\t\t<string>#{HOMEBREW_PREFIX}/opt/formula_name/bin/beanstalkd</string>
\t</array>
\t<key>RunAtLoad</key>
\t<true/>
\t<key>StartInterval</key>
\t<integer>5</integer>
</dict>
</plist>
EOS
expect(plist).to eq(plist_expect)
end
it "returns valid cron plist" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
run_type :cron
cron "@daily"
end
end
plist = f.service.to_plist
plist_expect = <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
\t<key>Label</key>
\t<string>homebrew.mxcl.formula_name</string>
\t<key>LimitLoadToSessionType</key>
\t<array>
\t\t<string>Aqua</string>
\t\t<string>Background</string>
\t\t<string>LoginWindow</string>
\t\t<string>StandardIO</string>
\t\t<string>System</string>
\t</array>
\t<key>ProgramArguments</key>
\t<array>
\t\t<string>#{HOMEBREW_PREFIX}/opt/formula_name/bin/beanstalkd</string>
\t</array>
\t<key>RunAtLoad</key>
\t<true/>
\t<key>StartCalendarInterval</key>
\t<dict>
\t\t<key>Hour</key>
\t\t<integer>0</integer>
\t\t<key>Minute</key>
\t\t<integer>0</integer>
\t</dict>
</dict>
</plist>
EOS
expect(plist).to eq(plist_expect)
end
it "returns valid keepalive-exit plist" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
keep_alive successful_exit: false
end
end
plist = f.service.to_plist
plist_expect = <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
\t<key>KeepAlive</key>
\t<dict>
\t\t<key>SuccessfulExit</key>
\t\t<false/>
\t</dict>
\t<key>Label</key>
\t<string>homebrew.mxcl.formula_name</string>
\t<key>LimitLoadToSessionType</key>
\t<array>
\t\t<string>Aqua</string>
\t\t<string>Background</string>
\t\t<string>LoginWindow</string>
\t\t<string>StandardIO</string>
\t\t<string>System</string>
\t</array>
\t<key>ProgramArguments</key>
\t<array>
\t\t<string>#{HOMEBREW_PREFIX}/opt/formula_name/bin/beanstalkd</string>
\t</array>
\t<key>RunAtLoad</key>
\t<true/>
</dict>
</plist>
EOS
expect(plist).to eq(plist_expect)
end
it "returns valid keepalive-crashed plist" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
keep_alive crashed: true
end
end
plist = f.service.to_plist
plist_expect = <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
\t<key>KeepAlive</key>
\t<dict>
\t\t<key>Crashed</key>
\t\t<true/>
\t</dict>
\t<key>Label</key>
\t<string>homebrew.mxcl.formula_name</string>
\t<key>LimitLoadToSessionType</key>
\t<array>
\t\t<string>Aqua</string>
\t\t<string>Background</string>
\t\t<string>LoginWindow</string>
\t\t<string>StandardIO</string>
\t\t<string>System</string>
\t</array>
\t<key>ProgramArguments</key>
\t<array>
\t\t<string>#{HOMEBREW_PREFIX}/opt/formula_name/bin/beanstalkd</string>
\t</array>
\t<key>RunAtLoad</key>
\t<true/>
</dict>
</plist>
EOS
expect(plist).to eq(plist_expect)
end
it "returns valid keepalive-path plist" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
keep_alive path: opt_pkgshare/"test-path"
end
end
plist = f.service.to_plist
plist_expect = <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
\t<key>KeepAlive</key>
\t<dict>
\t\t<key>PathState</key>
\t\t<string>#{HOMEBREW_PREFIX}/opt/formula_name/share/formula_name/test-path</string>
\t</dict>
\t<key>Label</key>
\t<string>homebrew.mxcl.formula_name</string>
\t<key>LimitLoadToSessionType</key>
\t<array>
\t\t<string>Aqua</string>
\t\t<string>Background</string>
\t\t<string>LoginWindow</string>
\t\t<string>StandardIO</string>
\t\t<string>System</string>
\t</array>
\t<key>ProgramArguments</key>
\t<array>
\t\t<string>#{HOMEBREW_PREFIX}/opt/formula_name/bin/beanstalkd</string>
\t</array>
\t<key>RunAtLoad</key>
\t<true/>
</dict>
</plist>
EOS
expect(plist).to eq(plist_expect)
end
it "expands paths" do
f = stub_formula do
service do
run [opt_sbin/"sleepwatcher", "-V", "-s", "~/.sleep", "-w", "~/.wakeup"]
working_dir "~"
end
end
plist = f.service.to_plist
plist_expect = <<~EOS
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
\t<key>Label</key>
\t<string>homebrew.mxcl.formula_name</string>
\t<key>LimitLoadToSessionType</key>
\t<array>
\t\t<string>Aqua</string>
\t\t<string>Background</string>
\t\t<string>LoginWindow</string>
\t\t<string>StandardIO</string>
\t\t<string>System</string>
\t</array>
\t<key>ProgramArguments</key>
\t<array>
\t\t<string>#{HOMEBREW_PREFIX}/opt/formula_name/sbin/sleepwatcher</string>
\t\t<string>-V</string>
\t\t<string>-s</string>
\t\t<string>#{Dir.home}/.sleep</string>
\t\t<string>-w</string>
\t\t<string>#{Dir.home}/.wakeup</string>
\t</array>
\t<key>RunAtLoad</key>
\t<true/>
\t<key>WorkingDirectory</key>
\t<string>#{Dir.home}</string>
</dict>
</plist>
EOS
expect(plist).to eq(plist_expect)
end
end
describe "#to_systemd_unit" do
it "returns valid unit" do
f = stub_formula do
service do
run [opt_bin/"beanstalkd", "test"]
run_type :immediate
environment_variables PATH: std_service_path_env, FOO: "BAR"
error_log_path var/"log/beanstalkd.error.log"
log_path var/"log/beanstalkd.log"
input_path var/"in/beanstalkd"
require_root true
root_dir var
working_dir var
keep_alive true
process_type :interactive
restart_delay 30
nice(-15)
macos_legacy_timers true
end
end
unit = f.service.to_systemd_unit
std_path = "#{HOMEBREW_PREFIX}/bin:#{HOMEBREW_PREFIX}/sbin:/usr/bin:/bin:/usr/sbin:/sbin"
unit_expect = <<~SYSTEMD
[Unit]
Description=Homebrew generated unit for formula_name
[Install]
WantedBy=default.target
[Service]
Type=simple
ExecStart="#{HOMEBREW_PREFIX}/opt/#{name}/bin/beanstalkd" "test"
Restart=on-failure
RestartSec=30
Nice=-15
WorkingDirectory=#{HOMEBREW_PREFIX}/var
RootDirectory=#{HOMEBREW_PREFIX}/var
StandardInput=file:#{HOMEBREW_PREFIX}/var/in/beanstalkd
StandardOutput=append:#{HOMEBREW_PREFIX}/var/log/beanstalkd.log
StandardError=append:#{HOMEBREW_PREFIX}/var/log/beanstalkd.error.log
Environment="PATH=#{std_path}"
Environment="FOO=BAR"
SYSTEMD
expect(unit).to eq(unit_expect)
end
it "returns valid partial oneshot unit" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
run_type :immediate
launch_only_once true
end
end
unit = f.service.to_systemd_unit
unit_expect = <<~SYSTEMD
[Unit]
Description=Homebrew generated unit for formula_name
[Install]
WantedBy=default.target
[Service]
Type=oneshot
ExecStart="#{HOMEBREW_PREFIX}/opt/#{name}/bin/beanstalkd"
SYSTEMD
expect(unit).to eq(unit_expect)
end
it "expands paths" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
working_dir "~"
end
end
unit = f.service.to_systemd_unit
unit_expect = <<~SYSTEMD
[Unit]
Description=Homebrew generated unit for formula_name
[Install]
WantedBy=default.target
[Service]
Type=simple
ExecStart="#{HOMEBREW_PREFIX}/opt/#{name}/bin/beanstalkd"
WorkingDirectory=#{Dir.home}
SYSTEMD
expect(unit).to eq(unit_expect)
end
it "returns valid unit with keep_alive crashed" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
keep_alive crashed: true
end
end
unit = f.service.to_systemd_unit
unit_expect = <<~SYSTEMD
[Unit]
Description=Homebrew generated unit for formula_name
[Install]
WantedBy=default.target
[Service]
Type=simple
ExecStart="#{HOMEBREW_PREFIX}/opt/#{name}/bin/beanstalkd"
Restart=on-failure
SYSTEMD
expect(unit).to eq(unit_expect)
end
it "returns valid unit with keep_alive successful_exit" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
keep_alive successful_exit: true
end
end
unit = f.service.to_systemd_unit
unit_expect = <<~SYSTEMD
[Unit]
Description=Homebrew generated unit for formula_name
[Install]
WantedBy=default.target
[Service]
Type=simple
ExecStart="#{HOMEBREW_PREFIX}/opt/#{name}/bin/beanstalkd"
Restart=on-success
SYSTEMD
expect(unit).to eq(unit_expect)
end
it "returns valid unit without restart when keep_alive is false" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
keep_alive false
end
end
unit = f.service.to_systemd_unit
unit_expect = <<~SYSTEMD
[Unit]
Description=Homebrew generated unit for formula_name
[Install]
WantedBy=default.target
[Service]
Type=simple
ExecStart="#{HOMEBREW_PREFIX}/opt/#{name}/bin/beanstalkd"
SYSTEMD
expect(unit).to eq(unit_expect)
end
end
describe "#to_systemd_timer" do
it "returns valid timer" do
f = stub_formula do
service do
run [opt_bin/"beanstalkd", "test"]
run_type :interval
interval 5
end
end
unit = f.service.to_systemd_timer
unit_expect = <<~SYSTEMD
[Unit]
Description=Homebrew generated timer for formula_name
[Install]
WantedBy=timers.target
[Timer]
Unit=homebrew.formula_name
OnUnitActiveSec=5
SYSTEMD
expect(unit).to eq(unit_expect)
end
it "returns valid partial timer" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
run_type :immediate
end
end
unit = f.service.to_systemd_timer
unit_expect = <<~SYSTEMD
[Unit]
Description=Homebrew generated timer for formula_name
[Install]
WantedBy=timers.target
[Timer]
Unit=homebrew.formula_name
SYSTEMD
expect(unit).to eq(unit_expect)
end
it "throws on incomplete cron" do
f = stub_formula do
service do
run opt_bin/"beanstalkd"
run_type :cron
cron "1 2 3 4"
end
end
expect do
f.service.to_systemd_timer
end.to raise_error TypeError, "Service#parse_cron expects a valid cron syntax"
end
it "returns valid cron timers" do
styles = {
"@hourly": "*-*-*-* *:00:00",
"@daily": "*-*-*-* 00:00:00",
"@weekly": "0-*-*-* 00:00:00",
"@monthly": "*-*-*-1 00:00:00",
"@yearly": "*-*-1-1 00:00:00",
"@annually": "*-*-1-1 00:00:00",
"5 5 5 5 5": "5-*-5-5 05:05:00",
}
styles.each do |cron, calendar|
f = stub_formula do
service do
run opt_bin/"beanstalkd"
run_type :cron
cron cron.to_s
end
end
unit = f.service.to_systemd_timer
unit_expect = <<~SYSTEMD
[Unit]
Description=Homebrew generated timer for formula_name
[Install]
WantedBy=timers.target
[Timer]
Unit=homebrew.formula_name
Persistent=true
OnCalendar=#{calendar}
SYSTEMD
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | true |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/abstract_command_spec.rb | Library/Homebrew/test/abstract_command_spec.rb | # frozen_string_literal: true
require "abstract_command"
RSpec.describe Homebrew::AbstractCommand do
describe "subclasses" do
before do
test_cat = Class.new(described_class) do
cmd_args do
description "test"
switch "--foo"
flag "--bar="
end
def run; end
end
stub_const("TestCat", test_cat)
end
describe "parsing args" do
it "parses valid args" do
expect { TestCat.new(["--foo"]).run }.not_to raise_error
end
it "allows access to args" do
expect(TestCat.new(["--bar", "baz"]).args.bar).to eq("baz")
end
it "raises on invalid args" do
expect { TestCat.new(["--bat"]) }.to raise_error(OptionParser::InvalidOption)
end
end
describe "command names" do
it "has a default command name" do
expect(TestCat.command_name).to eq("test-cat")
end
it "can lookup command" do
expect(described_class.command("test-cat")).to be(TestCat)
end
it "removes -cmd suffix from command name" do
require "dev-cmd/formula"
expect(Homebrew::DevCmd::FormulaCmd.command_name).to eq("formula")
end
describe "when command name is overridden" do
before do
tac = Class.new(described_class) do
def self.command_name = "t-a-c"
def run; end
end
stub_const("Tac", tac)
end
it "can be looked up by command name" do
expect(described_class.command("t-a-c")).to be(Tac)
end
end
end
end
describe "command paths" do
it "match command name" do
["cmd", "dev-cmd"].each do |dir|
Dir[File.join(__dir__, "../#{dir}", "*.rb")].each do |file|
filename = File.basename(file, ".rb")
require(file)
command = described_class.command(filename)
expect(Pathname(File.join(__dir__, "../#{dir}/#{command.command_name}.rb"))).to exist
end
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/bottle_spec.rb | Library/Homebrew/test/bottle_spec.rb | # frozen_string_literal: true
require "bottle_specification"
require "test/support/fixtures/testball_bottle"
RSpec.describe Bottle do
describe "#filename" do
it "renders the bottle filename" do
bottle_spec = BottleSpecification.new
bottle_spec.sha256(arm64_big_sur: "deadbeef" * 8)
tag = Utils::Bottles::Tag.from_symbol :arm64_big_sur
bottle = described_class.new(TestballBottle.new, bottle_spec, tag)
expect(bottle.filename.to_s).to eq("testball_bottle--0.1.arm64_big_sur.bottle.tar.gz")
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/software_spec_spec.rb | Library/Homebrew/test/software_spec_spec.rb | # frozen_string_literal: true
require "software_spec"
RSpec.describe SoftwareSpec do
alias_matcher :have_defined_resource, :be_resource_defined
alias_matcher :have_defined_option, :be_option_defined
subject(:spec) { described_class.new }
let(:owner) { instance_double(Cask::Cask, name: "some_name", full_name: "some_name", tap: "homebrew/core") }
describe "#resource" do
it "defines a resource" do
spec.resource("foo") { url "foo-1.0" }
expect(spec).to have_defined_resource("foo")
end
it "sets itself to be the resource's owner" do
spec.resource("foo") { url "foo-1.0" }
spec.owner = owner
spec.resources.each_value do |r|
expect(r.owner).to eq(spec)
end
end
it "receives the owner's version if it has no own version" do
spec.url("foo-42")
spec.resource("bar") { url "bar" }
spec.owner = owner
expect(spec.resource("bar").version).to eq("42")
end
it "raises an error when duplicate resources are defined" do
spec.resource("foo") { url "foo-1.0" }
expect do
spec.resource("foo") { url "foo-1.0" }
end.to raise_error(DuplicateResourceError)
end
it "raises an error when accessing missing resources" do
spec.owner = owner
expect do
spec.resource("foo")
end.to raise_error(ResourceMissingError)
end
end
describe "#owner" do
it "sets the owner" do
spec.owner = owner
expect(spec.owner).to eq(owner)
end
it "sets the name" do
spec.owner = owner
expect(spec.name).to eq(owner.name)
end
end
describe "#option" do
it "defines an option" do
spec.option("foo")
expect(spec).to have_defined_option("foo")
end
it "raises an error when it begins with dashes" do
expect do
spec.option("--foo")
end.to raise_error(ArgumentError)
end
it "raises an error when name is empty" do
expect do
spec.option("")
end.to raise_error(ArgumentError)
end
it "supports options with descriptions" do
spec.option("bar", "description")
expect(spec.options.first.description).to eq("description")
end
it "defaults to an empty string when no description is given" do
spec.option("foo")
expect(spec.options.first.description).to eq("")
end
end
describe "#deprecated_option" do
it "allows specifying deprecated options" do
spec.deprecated_option("foo" => "bar")
expect(spec.deprecated_options).not_to be_empty
expect(spec.deprecated_options.first.old).to eq("foo")
expect(spec.deprecated_options.first.current).to eq("bar")
end
it "allows specifying deprecated options as a Hash from an Array/String to an Array/String" do
spec.deprecated_option(["foo1", "foo2"] => "bar1", "foo3" => ["bar2", "bar3"])
expect(spec.deprecated_options).to include(DeprecatedOption.new("foo1", "bar1"))
expect(spec.deprecated_options).to include(DeprecatedOption.new("foo2", "bar1"))
expect(spec.deprecated_options).to include(DeprecatedOption.new("foo3", "bar2"))
expect(spec.deprecated_options).to include(DeprecatedOption.new("foo3", "bar3"))
end
it "raises an error when empty" do
expect do
spec.deprecated_option({})
end.to raise_error(ArgumentError)
end
end
describe "#depends_on" do
it "allows specifying dependencies" do
spec.depends_on("foo")
expect(spec.deps.first.name).to eq("foo")
end
it "allows specifying optional dependencies" do
spec.depends_on "foo" => :optional
expect(spec).to have_defined_option("with-foo")
end
it "allows specifying recommended dependencies" do
spec.depends_on "bar" => :recommended
expect(spec).to have_defined_option("without-bar")
end
end
describe "#uses_from_macos", :needs_linux do
context "when running on Linux", :needs_linux do
it "allows specifying dependencies" do
spec.uses_from_macos("foo")
expect(spec.declared_deps).not_to be_empty
expect(spec.deps).not_to be_empty
expect(spec.deps.first.name).to eq("foo")
expect(spec.deps.first).to be_uses_from_macos
expect(spec.deps.first).not_to be_use_macos_install
end
it "works with tags" do
spec.uses_from_macos("foo" => :build)
expect(spec.declared_deps).not_to be_empty
expect(spec.deps).not_to be_empty
expect(spec.deps.first.name).to eq("foo")
expect(spec.deps.first.tags).to include(:build)
expect(spec.deps.first).to be_uses_from_macos
expect(spec.deps.first).not_to be_use_macos_install
end
it "handles dependencies with HOMEBREW_SIMULATE_MACOS_ON_LINUX" do
ENV["HOMEBREW_SIMULATE_MACOS_ON_LINUX"] = "1"
spec.uses_from_macos("foo")
expect(spec.deps).to be_empty
expect(spec.declared_deps.first.name).to eq("foo")
expect(spec.declared_deps.first.tags).to be_empty
expect(spec.declared_deps.first).to be_uses_from_macos
expect(spec.declared_deps.first).to be_use_macos_install
end
it "handles dependencies with tags with HOMEBREW_SIMULATE_MACOS_ON_LINUX" do
ENV["HOMEBREW_SIMULATE_MACOS_ON_LINUX"] = "1"
spec.uses_from_macos("foo" => :build)
expect(spec.deps).to be_empty
expect(spec.declared_deps.first.name).to eq("foo")
expect(spec.declared_deps.first.tags).to include(:build)
expect(spec.declared_deps.first).to be_uses_from_macos
expect(spec.declared_deps.first).to be_use_macos_install
end
it "ignores OS version specifications" do
spec.uses_from_macos("foo", since: :sequoia)
spec.uses_from_macos("bar" => :build, :since => :sequoia)
expect(spec.deps.count).to eq 2
expect(spec.deps.first.name).to eq("foo")
expect(spec.deps.first).to be_uses_from_macos
expect(spec.deps.first).not_to be_use_macos_install
expect(spec.deps.last.name).to eq("bar")
expect(spec.deps.last.tags).to include(:build)
expect(spec.deps.last).to be_uses_from_macos
expect(spec.deps.last).not_to be_use_macos_install
expect(spec.declared_deps.count).to eq 2
end
end
context "when running on macOS", :needs_macos do
before do
allow(OS).to receive(:mac?).and_return(true)
allow(OS::Mac).to receive(:version).and_return(MacOSVersion.from_symbol(:sonoma))
end
it "adds a macOS dependency if the OS version meets requirements" do
spec.uses_from_macos("foo", since: :sonoma)
expect(spec.deps).to be_empty
expect(spec.declared_deps).not_to be_empty
expect(spec.declared_deps.first).to be_uses_from_macos
expect(spec.declared_deps.first).to be_use_macos_install
end
it "adds a macOS dependency if the OS version doesn't meet requirements" do
spec.uses_from_macos("foo", since: :big_sur)
expect(spec.declared_deps).not_to be_empty
expect(spec.deps).not_to be_empty
expect(spec.deps.first.name).to eq("foo")
expect(spec.deps.first).to be_uses_from_macos
expect(spec.deps.first).not_to be_use_macos_install
end
it "works with tags" do
spec.uses_from_macos("foo" => :build, :since => :big_sur)
expect(spec.declared_deps).not_to be_empty
expect(spec.deps).not_to be_empty
dep = spec.deps.first
expect(dep.name).to eq("foo")
expect(dep.tags).to include(:build)
expect(dep.first).to be_uses_from_macos
expect(dep.first).not_to be_use_macos_install
end
it "doesn't add an effective dependency if no OS version is specified" do
spec.uses_from_macos("foo")
spec.uses_from_macos("bar" => :build)
expect(spec.deps).to be_empty
expect(spec.declared_deps).not_to be_empty
dep = spec.declared_deps.first
expect(dep.name).to eq("foo")
expect(dep.first).to be_uses_from_macos
expect(dep.first).to be_use_macos_install
dep = spec.declared_deps.last
expect(dep.name).to eq("bar")
expect(dep.tags).to include(:build)
expect(dep.first).to be_uses_from_macos
expect(dep.first).to be_use_macos_install
end
it "raises an error if passing invalid OS versions" do
expect do
spec.uses_from_macos("foo", since: :bar)
end.to raise_error(MacOSVersion::Error, "unknown or unsupported macOS version: :bar")
end
end
end
specify "explicit options override defaupt depends_on option description" do
spec.option("with-foo", "blah")
spec.depends_on("foo" => :optional)
expect(spec.options.first.description).to eq("blah")
end
describe "#patch" do
it "adds a patch" do
spec.patch(:p1, :DATA)
expect(spec.patches.count).to eq(1)
expect(spec.patches.first.strip).to eq(:p1)
end
it "doesn't add a patch with no url" do
spec.patch do
sha256 "7852a7a365f518b12a1afd763a6a80ece88ac7aeea3c9023aa6c1fe46ac5a1ae"
end
expect(spec.patches.empty?).to be true
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/settings_spec.rb | Library/Homebrew/test/settings_spec.rb | # frozen_string_literal: true
require "settings"
RSpec.describe Homebrew::Settings do
before do
HOMEBREW_REPOSITORY.cd do
system "git", "init"
end
end
def setup_setting
HOMEBREW_REPOSITORY.cd do
system "git", "config", "--replace-all", "homebrew.foo", "true"
end
end
describe ".read" do
it "returns the correct value for a setting" do
setup_setting
expect(described_class.read("foo")).to eq "true"
end
it "returns the correct value for a setting as a symbol" do
setup_setting
expect(described_class.read(:foo)).to eq "true"
end
it "returns nil when setting is not set" do
setup_setting
expect(described_class.read("bar")).to be_nil
end
it "runs on a repo without a configuration file" do
expect { described_class.read("foo", repo: HOMEBREW_REPOSITORY/"bar") }.not_to raise_error
end
end
describe ".write" do
it "writes over an existing value" do
setup_setting
described_class.write :foo, false
expect(described_class.read("foo")).to eq "false"
end
it "writes a new value" do
setup_setting
described_class.write :bar, "abcde"
expect(described_class.read("bar")).to eq "abcde"
end
it "returns if the repo doesn't have a configuration file" do
expect { described_class.write("foo", false, repo: HOMEBREW_REPOSITORY/"bar") }.not_to raise_error
end
end
describe ".delete" do
it "deletes an existing setting" do
setup_setting
described_class.delete(:foo)
expect(described_class.read("foo")).to be_nil
end
it "deletes a non-existing setting" do
setup_setting
expect { described_class.delete(:bar) }.not_to raise_error
end
it "returns if the repo doesn't have a configuration file" do
expect { described_class.delete("foo", repo: HOMEBREW_REPOSITORY/"bar") }.not_to raise_error
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/checksum_spec.rb | Library/Homebrew/test/checksum_spec.rb | # frozen_string_literal: true
require "checksum"
RSpec.describe Checksum do
describe "#empty?" do
subject { described_class.new("") }
it { is_expected.to be_empty }
end
describe "#==" do
subject { described_class.new(TEST_SHA256) }
let(:other) { described_class.new(TEST_SHA256) }
let(:other_reversed) { described_class.new(TEST_SHA256.reverse) }
specify(:aggregate_failures) do
expect(subject).to eq(other) # rubocop:todo RSpec/NamedSubject
expect(subject).not_to eq(other_reversed) # rubocop:todo RSpec/NamedSubject
expect(subject).not_to be_nil # rubocop:todo RSpec/NamedSubject
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/description_cache_store_spec.rb | Library/Homebrew/test/description_cache_store_spec.rb | # frozen_string_literal: true
require "cmd/update-report"
require "description_cache_store"
RSpec.describe DescriptionCacheStore do
subject(:cache_store) { described_class.new(database) }
let(:database) { instance_double(CacheStoreDatabase, "database") }
let(:formula_name) { "test_name" }
let(:description) { "test_description" }
before { allow(Homebrew::EnvConfig).to receive(:eval_all?).and_return(true) }
describe "#update!" do
it "sets the formula description" do
expect(database).to receive(:set).with(formula_name, description)
cache_store.update!(formula_name, description)
end
end
describe "#delete!" do
it "deletes the formula description" do
expect(database).to receive(:delete).with(formula_name)
cache_store.delete!(formula_name)
end
end
describe "#update_from_report!" do
let(:report) { instance_double(ReporterHub, select_formula_or_cask: [], empty?: false) }
it "reads from the report" do
expect(database).to receive(:empty?).at_least(:once).and_return(false)
cache_store.update_from_report!(report)
end
end
describe "#update_from_formula_names!" do
it "sets the formulae descriptions" do
f = formula do
url "url-1"
desc "desc"
end
expect(Formulary).to receive(:factory).with(f.name).and_return(f)
expect(database).to receive(:empty?).and_return(false)
expect(database).to receive(:set).with(f.name, f.desc)
cache_store.update_from_formula_names!([f.name])
end
end
describe "#delete_from_formula_names!" do
it "deletes the formulae descriptions" do
expect(database).to receive(:empty?).and_return(false)
expect(database).to receive(:delete).with(formula_name)
cache_store.delete_from_formula_names!([formula_name])
end
end
describe CaskDescriptionCacheStore do
subject(:cache_store) { described_class.new(database) }
let(:database) { instance_double(CacheStoreDatabase, "database") }
describe "#update_from_report!" do
let(:report) { instance_double(ReporterHub, select_formula_or_cask: [], empty?: false) }
it "reads from the report" do
expect(database).to receive(:empty?).at_least(:once).and_return(false)
cache_store.update_from_report!(report)
end
end
describe "#update_from_cask_tokens!" do
it "sets the cask descriptions" do
c = Cask::Cask.new("cask-names-desc") do
url "url-1"
name "Name 1"
name "Name 2"
desc "description"
end
expect(Cask::CaskLoader).to receive(:load).with("cask-names-desc", any_args).and_return(c)
expect(database).to receive(:empty?).and_return(false)
expect(database).to receive(:set).with(c.full_name, [c.name.join(", "), c.desc.presence])
cache_store.update_from_cask_tokens!([c.token])
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/commands_spec.rb | Library/Homebrew/test/commands_spec.rb | # frozen_string_literal: true
require "commands"
# These shared contexts starting with `when` don't make sense.
RSpec.shared_context "custom internal commands" do # rubocop:disable RSpec/ContextWording
let(:tmpdir) { mktmpdir }
let(:cmd_path) { tmpdir/"cmd" }
let(:dev_cmd_path) { tmpdir/"dev-cmd" }
let(:cmds) do
[
# internal commands
cmd_path/"rbcmd.rb",
cmd_path/"shcmd.sh",
# internal developer-commands
dev_cmd_path/"rbdevcmd.rb",
dev_cmd_path/"shdevcmd.sh",
]
end
before do
stub_const("Commands::HOMEBREW_CMD_PATH", cmd_path)
stub_const("Commands::HOMEBREW_DEV_CMD_PATH", dev_cmd_path)
end
around do |example|
cmd_path.mkpath
dev_cmd_path.mkpath
cmds.each do |f|
FileUtils.touch f
end
example.run
ensure
FileUtils.rm_f cmds
end
end
RSpec.describe Commands do
include_context "custom internal commands"
specify "::internal_commands" do
cmds = described_class.internal_commands
expect(cmds).to include("rbcmd"), "Ruby commands files should be recognized"
expect(cmds).to include("shcmd"), "Shell commands files should be recognized"
expect(cmds).not_to include("rbdevcmd"), "Dev commands shouldn't be included"
end
specify "::internal_developer_commands" do
cmds = described_class.internal_developer_commands
expect(cmds).to include("rbdevcmd"), "Ruby commands files should be recognized"
expect(cmds).to include("shdevcmd"), "Shell commands files should be recognized"
expect(cmds).not_to include("rbcmd"), "Non-dev commands shouldn't be included"
end
specify "::external_commands" do
mktmpdir do |dir|
%w[t0.rb brew-t1 brew-t2.rb brew-t3.py].each do |file|
path = "#{dir}/#{file}"
FileUtils.touch path
FileUtils.chmod 0755, path
end
FileUtils.touch "#{dir}/brew-t4"
allow(described_class).to receive(:tap_cmd_directories).and_return([dir])
cmds = described_class.external_commands
expect(cmds).to include("t0"), "Executable v2 Ruby files should be included"
expect(cmds).to include("t1"), "Executable files should be included"
expect(cmds).to include("t2"), "Executable Ruby files should be included"
expect(cmds).to include("t3"), "Executable files with a Ruby extension should be included"
expect(cmds).not_to include("t4"), "Non-executable files shouldn't be included"
end
end
describe "::path" do
specify "returns the path for an internal command" do
expect(described_class.path("rbcmd")).to eq(Commands::HOMEBREW_CMD_PATH/"rbcmd.rb")
expect(described_class.path("shcmd")).to eq(Commands::HOMEBREW_CMD_PATH/"shcmd.sh")
expect(described_class.path("idontexist1234")).to be_nil
end
specify "returns the path for an internal developer-command" do
expect(described_class.path("rbdevcmd")).to eq(Commands::HOMEBREW_DEV_CMD_PATH/"rbdevcmd.rb")
expect(described_class.path("shdevcmd")).to eq(Commands::HOMEBREW_DEV_CMD_PATH/"shdevcmd.sh")
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/rubocop_spec.rb | Library/Homebrew/test/rubocop_spec.rb | # frozen_string_literal: true
require "open3"
require "yaml"
RSpec.describe "RuboCop" do
context "when calling `rubocop` outside of the Homebrew environment" do
before do
ENV.each_key do |key|
allowlist = %w[
HOMEBREW_TESTS
HOMEBREW_USE_RUBY_FROM_PATH
HOMEBREW_BUNDLER_VERSION
]
ENV.delete(key) if key.start_with?("HOMEBREW_") && allowlist.exclude?(key)
end
ENV["XDG_CACHE_HOME"] = (HOMEBREW_CACHE.realpath/"style").to_s
end
it "loads all Formula cops without errors" do
# TODO: Remove these args once TestProf fixes their RuboCop plugin.
test_prof_rubocop_args = [
# Require "sorbet-runtime" to bring T into scope for warnings.rb
"-r", "sorbet-runtime",
# Require "extend/module" to include T::Sig in Module for warnings.rb
"-r", HOMEBREW_LIBRARY_PATH/"extend/module.rb",
# Work around TestProf RuboCop plugin issues
"-r", HOMEBREW_LIBRARY_PATH/"utils/test_prof_rubocop_stub.rb"
]
stdout, stderr, status = Open3.capture3(RUBY_PATH, "-W0", "-S", "rubocop", TEST_FIXTURE_DIR/"testball.rb",
*test_prof_rubocop_args)
expect(stderr).to be_empty
expect(stdout).to include("no offenses detected")
expect(status).to be_a_success
end
end
context "with TargetRubyVersion" do
it "matches .ruby-version" do
rubocop_config_path = HOMEBREW_LIBRARY_PATH.parent/".rubocop.yml"
rubocop_config = YAML.unsafe_load_file(rubocop_config_path)
target_ruby_version = rubocop_config.dig("AllCops", "TargetRubyVersion")
ruby_version_path = HOMEBREW_LIBRARY_PATH/".ruby-version"
ruby_version = ruby_version_path.read.strip.to_f
expect(target_ruby_version).to eq(ruby_version)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/cxxstdlib_spec.rb | Library/Homebrew/test/cxxstdlib_spec.rb | # frozen_string_literal: true
require "formula"
require "cxxstdlib"
RSpec.describe CxxStdlib do
let(:clang) { described_class.create(:libstdcxx, :clang) }
let(:lcxx) { described_class.create(:libcxx, :clang) }
describe "#type_string" do
specify "formatting" do
expect(clang.type_string).to eq("libstdc++")
expect(lcxx.type_string).to eq("libc++")
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/github_runner_spec.rb | Library/Homebrew/test/github_runner_spec.rb | # frozen_string_literal: true
require "github_runner"
RSpec.describe GitHubRunner do
let(:runner) do
spec = MacOSRunnerSpec.new(name: "macOS 11-arm64", runner: "11-arm64", timeout: 90, cleanup: true)
version = MacOSVersion.new("11")
described_class.new(platform: :macos, arch: :arm64, spec:, macos_version: version)
end
it "has immutable attributes" do
[:platform, :arch, :spec, :macos_version].each do |attribute|
expect(runner.respond_to?(:"#{attribute}=")).to be(false)
end
end
it "is inactive by default" do
expect(runner.active).to be(false)
end
describe "#macos?" do
it "returns true if the runner is a macOS runner" do
expect(runner.macos?).to be(true)
end
end
describe "#linux?" do
it "returns false if the runner is a macOS runner" do
expect(runner.linux?).to be(false)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/error_during_execution_spec.rb | Library/Homebrew/test/error_during_execution_spec.rb | # frozen_string_literal: true
RSpec.describe ErrorDuringExecution do
subject(:error) { described_class.new(command, status:, output:) }
let(:command) { ["false"] }
let(:status) { instance_double(Process::Status, exitstatus:, termsig: nil) }
let(:exitstatus) { 1 }
let(:output) { nil }
describe "#initialize" do
it "fails when only given a command" do
expect do
described_class.new(command)
end.to raise_error(ArgumentError)
end
it "fails when only given a status" do
expect do
described_class.new(status:)
end.to raise_error(ArgumentError)
end
it "does not raise an error when given both a command and a status" do
expect do
described_class.new(command, status:)
end.not_to raise_error
end
end
describe "#to_s" do
context "when only given a command and a status" do
it(:to_s) { expect(error.to_s).to eq "Failure while executing; `false` exited with 1." }
end
context "when additionally given the output" do
let(:output) do
[
[:stdout, "This still worked.\n"],
[:stderr, "Here something went wrong.\n"],
]
end
before do
allow($stdout).to receive(:tty?).and_return(true)
end
it(:to_s) do
expect(error.to_s).to eq <<~EOS
Failure while executing; `false` exited with 1. Here's the output:
This still worked.
#{Formatter.error("Here something went wrong.\n")}
EOS
end
end
context "when command arguments contain special characters" do
let(:command) { ["env", "PATH=/bin", "cat", "with spaces"] }
it(:to_s) do
expect(error.to_s)
.to eq 'Failure while executing; `env PATH=/bin cat with\ spaces` exited with 1.'
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/migrator_spec.rb | Library/Homebrew/test/migrator_spec.rb | # frozen_string_literal: true
require "migrator"
require "test/support/fixtures/testball"
require "tab"
require "keg"
RSpec.describe Migrator do
subject(:migrator) { described_class.new(new_formula, old_formula.name) }
let(:new_formula) { Testball.new("newname") }
let(:old_formula) { Testball.new("oldname") }
let(:new_keg_record) { HOMEBREW_CELLAR/"newname/0.1" }
let(:old_keg_record) { HOMEBREW_CELLAR/"oldname/0.1" }
let(:old_tab) { Tab.empty }
let(:keg) { Keg.new(old_keg_record) }
let(:old_pin) { HOMEBREW_PINNED_KEGS/"oldname" }
before do |example|
allow(new_formula).to receive(:oldnames).and_return(["oldname"])
allow(Formulary).to receive(:factory).with("homebrew/core/oldname", any_args).and_return(old_formula)
allow(Formulary).to receive(:factory).with("oldname", any_args).and_return(old_formula)
allow(Formulary).to receive(:factory).with("newname", any_args).and_return(new_formula)
# do not create directories for error tests
next if example.metadata[:description].start_with?("raises an error")
(old_keg_record/"bin").mkpath
%w[inside bindir].each do |file|
FileUtils.touch old_keg_record/"bin/#{file}"
end
old_tab.tabfile = HOMEBREW_CELLAR/"oldname/0.1/INSTALL_RECEIPT.json"
old_tab.source["path"] = "/oldname"
old_tab.write
keg.link
keg.optlink
old_pin.make_relative_symlink old_keg_record
migrator # needs to be evaluated eagerly
(HOMEBREW_PREFIX/"bin").mkpath
end
after do
keg.unlink if !old_keg_record.parent.symlink? && old_keg_record.directory?
if new_keg_record.directory?
new_keg = Keg.new(new_keg_record)
new_keg.unlink
end
end
describe "::new" do
it "raises an error if there is no old path" do
expect do
described_class.new(new_formula, "oldname")
end.to raise_error(Migrator::MigratorNoOldpathError)
end
it "raises an error if the Taps differ" do
keg = HOMEBREW_CELLAR/"oldname/0.1"
keg.mkpath
tab = Tab.empty
tab.tabfile = HOMEBREW_CELLAR/"oldname/0.1/INSTALL_RECEIPT.json"
tab.source["tap"] = "homebrew/core"
tab.write
expect do
described_class.new(new_formula, "oldname")
end.to raise_error(Migrator::MigratorDifferentTapsError)
end
end
specify "#move_to_new_directory" do
keg.unlink
migrator.move_to_new_directory
expect(new_keg_record).to be_a_directory
expect(new_keg_record/"bin").to be_a_directory
expect(new_keg_record/"bin/inside").to be_a_file
expect(new_keg_record/"bin/bindir").to be_a_file
expect(old_keg_record).not_to be_a_directory
end
specify "#backup_oldname_cellar" do
FileUtils.rm_r(old_keg_record.parent)
(new_keg_record/"bin").mkpath
migrator.backup_oldname_cellar
expect(old_keg_record/"bin").to be_a_directory
expect(old_keg_record/"bin").to be_a_directory
end
specify "#repin" do
(new_keg_record/"bin").mkpath
expected_relative = new_keg_record.relative_path_from HOMEBREW_PINNED_KEGS
migrator.repin
expect(migrator.new_pin_record).to be_a_symlink
expect(migrator.new_pin_record.readlink).to eq(expected_relative)
expect(migrator.old_pin_record).not_to exist
end
specify "#unlink_oldname" do
expect(HOMEBREW_LINKED_KEGS.children.count).to eq(1)
expect((HOMEBREW_PREFIX/"opt").children.count).to eq(1)
migrator.unlink_oldname
expect(HOMEBREW_LINKED_KEGS).not_to exist
expect(HOMEBREW_LIBRARY/"bin").not_to exist
end
specify "#link_newname" do
keg.unlink
keg.uninstall
(new_keg_record/"bin").mkpath
%w[inside bindir].each do |file|
FileUtils.touch new_keg_record/"bin"/file
end
migrator.link_newname
expect(HOMEBREW_LINKED_KEGS.children.count).to eq(1)
expect((HOMEBREW_PREFIX/"opt").children.count).to eq(1)
end
specify "#link_oldname_opt" do
new_keg_record.mkpath
migrator.link_oldname_opt
expect((HOMEBREW_PREFIX/"opt/oldname").realpath).to eq(new_keg_record.realpath)
end
specify "#link_oldname_cellar" do
(new_keg_record/"bin").mkpath
keg.unlink
keg.uninstall
migrator.link_oldname_cellar
expect((HOMEBREW_CELLAR/"oldname").realpath).to eq(new_keg_record.parent.realpath)
end
specify "#update_tabs" do
(new_keg_record/"bin").mkpath
tab = Tab.empty
tab.tabfile = HOMEBREW_CELLAR/"newname/0.1/INSTALL_RECEIPT.json"
tab.source["path"] = "/path/that/must/be/changed/by/update_tabs"
tab.write
migrator.update_tabs
expect(Tab.for_keg(new_keg_record).source["path"]).to eq(new_formula.path.to_s)
end
specify "#migrate" do
tab = Tab.empty
tab.tabfile = HOMEBREW_CELLAR/"oldname/0.1/INSTALL_RECEIPT.json"
tab.source["path"] = old_formula.path.to_s
tab.write
migrator.migrate
expect(new_keg_record).to exist
expect(old_keg_record.parent).to be_a_symlink
expect(HOMEBREW_LINKED_KEGS/"oldname").not_to exist
expect((HOMEBREW_LINKED_KEGS/"newname").realpath).to eq(new_keg_record.realpath)
expect(old_keg_record.realpath).to eq(new_keg_record.realpath)
expect((HOMEBREW_PREFIX/"opt/oldname").realpath).to eq(new_keg_record.realpath)
expect((HOMEBREW_CELLAR/"oldname").realpath).to eq(new_keg_record.parent.realpath)
expect((HOMEBREW_PINNED_KEGS/"newname").realpath).to eq(new_keg_record.realpath)
expect(Tab.for_keg(new_keg_record).source["path"]).to eq(new_formula.path.to_s)
end
specify "#unlinik_oldname_opt" do
new_keg_record.mkpath
old_opt_record = HOMEBREW_PREFIX/"opt/oldname"
old_opt_record.unlink if old_opt_record.symlink?
old_opt_record.make_relative_symlink(new_keg_record)
migrator.unlink_oldname_opt
expect(old_opt_record).not_to be_a_symlink
end
specify "#unlink_oldname_cellar" do
new_keg_record.mkpath
keg.unlink
keg.uninstall
old_keg_record.parent.make_relative_symlink(new_keg_record.parent)
migrator.unlink_oldname_cellar
expect(old_keg_record.parent).not_to be_a_symlink
end
specify "#backup_oldname_cellar after uninstall" do
(new_keg_record/"bin").mkpath
keg.unlink
keg.uninstall
migrator.backup_oldname_cellar
expect(old_keg_record.subdirs).not_to be_empty
end
specify "#backup_old_tabs" do
tab = Tab.empty
tab.tabfile = HOMEBREW_CELLAR/"oldname/0.1/INSTALL_RECEIPT.json"
tab.source["path"] = "/should/be/the/same"
tab.write
migrator = described_class.new(new_formula, "oldname")
tab.tabfile.delete
migrator.backup_old_tabs
expect(Tab.for_keg(old_keg_record).source["path"]).to eq("/should/be/the/same")
end
describe "#backup_oldname" do
context "when cellar exists" do
it "backs up the old name" do
migrator.backup_oldname
expect(old_keg_record.parent).to be_a_directory
expect(old_keg_record.parent.subdirs).not_to be_empty
expect(HOMEBREW_LINKED_KEGS/"oldname").to exist
expect(HOMEBREW_PREFIX/"opt/oldname").to exist
expect(HOMEBREW_PINNED_KEGS/"oldname").to be_a_symlink
expect(keg).to be_linked
end
end
context "when cellar is removed" do
it "backs up the old name" do
(new_keg_record/"bin").mkpath
keg.unlink
keg.uninstall
migrator.backup_oldname
expect(old_keg_record.parent).to be_a_directory
expect(old_keg_record.parent.subdirs).not_to be_empty
expect(HOMEBREW_LINKED_KEGS/"oldname").to exist
expect(HOMEBREW_PREFIX/"opt/oldname").to exist
expect(HOMEBREW_PINNED_KEGS/"oldname").to be_a_symlink
expect(keg).to be_linked
end
end
context "when cellar is linked" do
it "backs up the old name" do
(new_keg_record/"bin").mkpath
keg.unlink
keg.uninstall
old_keg_record.parent.make_relative_symlink(new_keg_record.parent)
migrator.backup_oldname
expect(old_keg_record.parent).to be_a_directory
expect(old_keg_record.parent.subdirs).not_to be_empty
expect(HOMEBREW_LINKED_KEGS/"oldname").to exist
expect(HOMEBREW_PREFIX/"opt/oldname").to exist
expect(HOMEBREW_PINNED_KEGS/"oldname").to be_a_symlink
expect(keg).to be_linked
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/diagnostic_checks_spec.rb | Library/Homebrew/test/diagnostic_checks_spec.rb | # frozen_string_literal: true
require "diagnostic"
RSpec.describe Homebrew::Diagnostic::Checks do
subject(:checks) { described_class.new }
specify "#inject_file_list" do
expect(checks.inject_file_list([], "foo:\n")).to eq("foo:\n")
expect(checks.inject_file_list(%w[/a /b], "foo:\n")).to eq("foo:\n /a\n /b\n")
end
specify "#check_access_directories" do
skip "User is root so everything is writable." if Process.euid.zero?
begin
dirs = [
HOMEBREW_CACHE,
HOMEBREW_CELLAR,
HOMEBREW_REPOSITORY,
HOMEBREW_LOGS,
HOMEBREW_LOCKS,
]
modes = {}
dirs.each do |dir|
modes[dir] = dir.stat.mode & 0777
dir.chmod 0555
expect(checks.check_access_directories).to match(dir.to_s)
end
ensure
modes.each do |dir, mode|
dir.chmod mode
end
end
end
specify "#check_user_path_1" do
bin = HOMEBREW_PREFIX/"bin"
sep = File::PATH_SEPARATOR
# ensure /usr/bin is before HOMEBREW_PREFIX/bin in the PATH
ENV["PATH"] = "/usr/bin#{sep}#{bin}#{sep}" +
ENV["PATH"].gsub(%r{(?:^|#{sep})(?:/usr/bin|#{bin})}, "")
# ensure there's at least one file with the same name in both /usr/bin/ and
# HOMEBREW_PREFIX/bin/
(bin/File.basename(Dir["/usr/bin/*"].first)).mkpath
expect(checks.check_user_path_1)
.to match("/usr/bin occurs before #{HOMEBREW_PREFIX}/bin")
end
specify "#check_user_path_2" do
ENV["PATH"] = ENV["PATH"].gsub \
%r{(?:^|#{File::PATH_SEPARATOR})#{HOMEBREW_PREFIX}/bin}o, ""
expect(checks.check_user_path_1).to be_nil
expect(checks.check_user_path_2)
.to match("Homebrew's \"bin\" was not found in your PATH.")
end
specify "#check_user_path_3" do
sbin = HOMEBREW_PREFIX/"sbin"
(sbin/"something").mkpath
homebrew_path =
"#{HOMEBREW_PREFIX}/bin#{File::PATH_SEPARATOR}" +
ENV["HOMEBREW_PATH"].gsub(/(?:^|#{Regexp.escape(File::PATH_SEPARATOR)})#{Regexp.escape(sbin)}/, "")
stub_const("ORIGINAL_PATHS", PATH.new(homebrew_path).filter_map { |path| Pathname.new(path).expand_path })
expect(checks.check_user_path_1).to be_nil
expect(checks.check_user_path_2).to be_nil
expect(checks.check_user_path_3)
.to match("Homebrew's \"sbin\" was not found in your PATH")
ensure
FileUtils.rm_rf(sbin)
end
specify "#check_for_symlinked_cellar" do
FileUtils.rm_r(HOMEBREW_CELLAR)
mktmpdir do |path|
FileUtils.ln_s path, HOMEBREW_CELLAR
expect(checks.check_for_symlinked_cellar).to match(path)
end
ensure
HOMEBREW_CELLAR.unlink
HOMEBREW_CELLAR.mkpath
end
specify "#check_tmpdir" do
ENV["TMPDIR"] = "/i/don/t/exis/t"
expect(checks.check_tmpdir).to match("doesn't exist")
end
specify "#check_for_external_cmd_name_conflict" do
mktmpdir do |path1|
mktmpdir do |path2|
[path1, path2].each do |path|
cmd = "#{path}/brew-foo"
FileUtils.touch cmd
FileUtils.chmod 0755, cmd
end
allow(Commands).to receive(:tap_cmd_directories).and_return([path1, path2])
expect(checks.check_for_external_cmd_name_conflict)
.to match("brew-foo")
end
end
end
specify "#check_homebrew_prefix" do
allow(Homebrew).to receive(:default_prefix?).and_return(false)
expect(checks.check_homebrew_prefix)
.to match("Your Homebrew's prefix is not #{Homebrew::DEFAULT_PREFIX}")
end
specify "#check_for_unnecessary_core_tap" do
ENV.delete("HOMEBREW_DEVELOPER")
expect_any_instance_of(CoreTap).to receive(:installed?).and_return(true)
expect(checks.check_for_unnecessary_core_tap).to match("You have an unnecessary local Core tap")
end
specify "#check_for_unnecessary_cask_tap" do
ENV.delete("HOMEBREW_DEVELOPER")
expect_any_instance_of(CoreCaskTap).to receive(:installed?).and_return(true)
expect(checks.check_for_unnecessary_cask_tap).to match("unnecessary local Cask tap")
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/tap_spec.rb | Library/Homebrew/test/tap_spec.rb | # frozen_string_literal: true
RSpec.describe Tap do
include FileUtils
alias_matcher :have_cask_file, :be_cask_file
alias_matcher :have_formula_file, :be_formula_file
alias_matcher :have_custom_remote, :be_custom_remote
subject(:homebrew_foo_tap) { described_class.fetch("Homebrew", "foo") }
let(:path) { HOMEBREW_TAP_DIRECTORY/"homebrew/homebrew-foo" }
let(:formula_file) { path/"Formula/foo.rb" }
let(:alias_file) { path/"Aliases/bar" }
let(:cmd_file) { path/"cmd/brew-tap-cmd.rb" }
let(:manpage_file) { path/"manpages/brew-tap-cmd.1" }
let(:bash_completion_file) { path/"completions/bash/brew-tap-cmd" }
let(:zsh_completion_file) { path/"completions/zsh/_brew-tap-cmd" }
let(:fish_completion_file) { path/"completions/fish/brew-tap-cmd.fish" }
before do
path.mkpath
(path/"audit_exceptions").mkpath
(path/"style_exceptions").mkpath
# requiring utils/output in tap.rb should be enough but it's not for no apparent reason.
$stderr.extend(Utils::Output::Mixin)
end
def setup_tap_files
formula_file.dirname.mkpath
formula_file.write <<~RUBY
class Foo < Formula
url "https://brew.sh/foo-1.0.tar.gz"
end
RUBY
alias_file.parent.mkpath
ln_s formula_file, alias_file
(path/"formula_renames.json").write <<~JSON
{ "oldname": "foo" }
JSON
(path/"tap_migrations.json").write <<~JSON
{ "removed-formula": "homebrew/foo" }
JSON
%w[audit_exceptions style_exceptions].each do |exceptions_directory|
(path/exceptions_directory).mkpath
(path/"#{exceptions_directory}/formula_list.json").write <<~JSON
[ "foo", "bar" ]
JSON
(path/"#{exceptions_directory}/formula_hash.json").write <<~JSON
{ "foo": "foo1", "bar": "bar1" }
JSON
end
[
cmd_file,
manpage_file,
bash_completion_file,
zsh_completion_file,
fish_completion_file,
].each do |f|
f.parent.mkpath
touch f
end
chmod 0755, cmd_file
end
def setup_git_repo
path.cd do
system "git", "init"
system "git", "remote", "add", "origin", "https://github.com/Homebrew/homebrew-foo"
system "git", "add", "--all"
system "git", "commit", "-m", "init"
end
end
def setup_completion(link:)
HOMEBREW_REPOSITORY.cd do
system "git", "init"
system "git", "config", "--replace-all", "homebrew.linkcompletions", link.to_s
system "git", "config", "--replace-all", "homebrew.completionsmessageshown", "true"
end
end
specify "::fetch" do
expect(described_class.fetch("Homebrew", "core")).to be_a(CoreTap)
expect(described_class.fetch("Homebrew", "homebrew")).to be_a(CoreTap)
tap = described_class.fetch("Homebrew", "foo")
expect(tap).to be_a(described_class)
expect(tap.name).to eq("homebrew/foo")
expect do
described_class.fetch("foo")
end.to raise_error(Tap::InvalidNameError, /Invalid tap name/)
expect do
described_class.fetch("homebrew/homebrew/bar")
end.to raise_error(Tap::InvalidNameError, /Invalid tap name/)
expect do
described_class.fetch("homebrew", "homebrew/baz")
end.to raise_error(Tap::InvalidNameError, /Invalid tap name/)
end
describe "::from_path" do
let(:tap) { described_class.fetch("Homebrew", "core") }
let(:path) { tap.path }
let(:formula_path) { path/"Formula/formula.rb" }
it "returns the Tap for a Formula path" do
expect(described_class.from_path(formula_path)).to eq tap
end
it "returns the Tap when given its exact path" do
expect(described_class.from_path(path)).to eq tap
end
context "when path contains a dot" do
let(:tap) { described_class.fetch("str4d.xyz", "rage") }
after do
tap.uninstall
end
it "returns the Tap when given its exact path" do
expect(described_class.from_path(path)).to eq tap
end
end
end
describe "::allowed_taps" do
before { allow(Homebrew::EnvConfig).to receive(:allowed_taps).and_return("homebrew/allowed") }
it "returns a set of allowed taps according to the environment" do
expect(described_class.allowed_taps)
.to contain_exactly(described_class.fetch("homebrew/allowed"))
end
end
describe "::forbidden_taps" do
before { allow(Homebrew::EnvConfig).to receive(:forbidden_taps).and_return("homebrew/forbidden") }
it "returns a set of forbidden taps according to the environment" do
expect(described_class.forbidden_taps)
.to contain_exactly(described_class.fetch("homebrew/forbidden"))
end
end
specify "attributes" do
expect(homebrew_foo_tap.user).to eq("Homebrew")
expect(homebrew_foo_tap.repository).to eq("foo")
expect(homebrew_foo_tap.name).to eq("homebrew/foo")
expect(homebrew_foo_tap.path).to eq(path)
expect(homebrew_foo_tap).to be_installed
expect(homebrew_foo_tap).to be_official
expect(homebrew_foo_tap).not_to be_a_core_tap
end
specify "#issues_url" do
t = described_class.fetch("someone", "foo")
path = HOMEBREW_TAP_DIRECTORY/"someone/homebrew-foo"
path.mkpath
cd path do
system "git", "init"
system "git", "remote", "add", "origin",
"https://github.com/someone/homebrew-foo"
end
expect(t.issues_url).to eq("https://github.com/someone/homebrew-foo/issues")
expect(homebrew_foo_tap.issues_url).to eq("https://github.com/Homebrew/homebrew-foo/issues")
(HOMEBREW_TAP_DIRECTORY/"someone/homebrew-no-git").mkpath
expect(described_class.fetch("someone", "no-git").issues_url).to be_nil
ensure
FileUtils.rm_rf(path.parent)
end
specify "files" do
setup_tap_files
expect(homebrew_foo_tap.formula_files).to eq([formula_file])
expect(homebrew_foo_tap.formula_names).to eq(["homebrew/foo/foo"])
expect(homebrew_foo_tap.alias_files).to eq([alias_file])
expect(homebrew_foo_tap.aliases).to eq(["homebrew/foo/bar"])
expect(homebrew_foo_tap.alias_table).to eq("homebrew/foo/bar" => "homebrew/foo/foo")
expect(homebrew_foo_tap.alias_reverse_table).to eq("homebrew/foo/foo" => ["homebrew/foo/bar"])
expect(homebrew_foo_tap.formula_renames).to eq("oldname" => "foo")
expect(homebrew_foo_tap.tap_migrations).to eq("removed-formula" => "homebrew/foo")
expect(homebrew_foo_tap.command_files).to eq([cmd_file])
expect(homebrew_foo_tap.to_hash).to be_a(Hash)
expect(homebrew_foo_tap).to have_formula_file("Formula/foo.rb")
expect(homebrew_foo_tap).not_to have_formula_file("bar.rb")
expect(homebrew_foo_tap).not_to have_formula_file("Formula/baz.sh")
end
describe "#remote" do
it "returns the remote URL", :needs_network do
setup_git_repo
expect(homebrew_foo_tap.remote).to eq("https://github.com/Homebrew/homebrew-foo")
expect(homebrew_foo_tap).not_to have_custom_remote
services_tap = described_class.fetch("Homebrew", "test-bot")
services_tap.path.mkpath
services_tap.path.cd do
system "git", "init"
system "git", "remote", "add", "origin", "https://github.com/Homebrew/homebrew-test-bot"
end
expect(services_tap).not_to be_private
end
it "returns nil if the Tap is not a Git repository" do
expect(homebrew_foo_tap.remote).to be_nil
end
it "returns nil if Git is not available" do
setup_git_repo
allow(Utils::Git).to receive(:available?).and_return(false)
expect(homebrew_foo_tap.remote).to be_nil
end
end
describe "#remote_repo" do
it "returns the remote https repository" do
setup_git_repo
expect(homebrew_foo_tap.remote_repository).to eq("Homebrew/homebrew-foo")
services_tap = described_class.fetch("Homebrew", "test-bot")
services_tap.path.mkpath
services_tap.path.cd do
system "git", "init"
system "git", "remote", "add", "origin", "https://github.com/Homebrew/homebrew-bar"
end
expect(services_tap.remote_repository).to eq("Homebrew/homebrew-bar")
end
it "returns the remote ssh repository" do
setup_git_repo
expect(homebrew_foo_tap.remote_repository).to eq("Homebrew/homebrew-foo")
services_tap = described_class.fetch("Homebrew", "test-bot")
services_tap.path.mkpath
services_tap.path.cd do
system "git", "init"
system "git", "remote", "add", "origin", "git@github.com:Homebrew/homebrew-bar"
end
expect(services_tap.remote_repository).to eq("Homebrew/homebrew-bar")
end
it "returns nil if the Tap is not a Git repository" do
expect(homebrew_foo_tap.remote_repository).to be_nil
end
it "returns nil if Git is not available" do
setup_git_repo
allow(Utils::Git).to receive(:available?).and_return(false)
expect(homebrew_foo_tap.remote_repository).to be_nil
end
end
describe "#custom_remote?" do
subject(:tap) { described_class.fetch("Homebrew", "test-bot") }
let(:remote) { nil }
before do
tap.path.mkpath
system "git", "-C", tap.path, "init"
system "git", "-C", tap.path, "remote", "add", "origin", remote if remote
end
context "if no remote is available" do
it "returns true" do
expect(tap.remote).to be_nil
expect(tap.custom_remote?).to be true
end
end
context "when using the default remote" do
let(:remote) { "https://github.com/Homebrew/homebrew-test-bot" }
it(:custom_remote?) { expect(tap.custom_remote?).to be false }
end
context "when using a non-default remote" do
let(:remote) { "git@github.com:Homebrew/homebrew-test-bot" }
it(:custom_remote?) { expect(tap.custom_remote?).to be true }
end
end
specify "Git variant" do
touch path/"README"
setup_git_repo
expect(homebrew_foo_tap.git_head).to eq("0453e16c8e3fac73104da50927a86221ca0740c2")
expect(homebrew_foo_tap.git_last_commit).to match(/\A\d+ .+ ago\Z/)
end
specify "#private?", :needs_network do
expect(homebrew_foo_tap).to be_private
end
describe "#install" do
it "raises an error when the Tap is already tapped" do
setup_git_repo
already_tapped_tap = described_class.fetch("Homebrew", "foo")
expect(already_tapped_tap).to be_installed
expect { already_tapped_tap.install }.to raise_error(TapAlreadyTappedError)
end
it "raises an error when the Tap is already tapped with the right remote" do
setup_git_repo
already_tapped_tap = described_class.fetch("Homebrew", "foo")
expect(already_tapped_tap).to be_installed
right_remote = homebrew_foo_tap.remote
expect { already_tapped_tap.install clone_target: right_remote }.to raise_error(TapAlreadyTappedError)
end
it "raises an error when the remote doesn't match" do
setup_git_repo
already_tapped_tap = described_class.fetch("Homebrew", "foo")
expect(already_tapped_tap).to be_installed
wrong_remote = "#{homebrew_foo_tap.remote}-oops"
expect do
already_tapped_tap.install clone_target: wrong_remote
end.to raise_error(TapRemoteMismatchError)
end
it "raises an error when the remote for Homebrew/core doesn't match HOMEBREW_CORE_GIT_REMOTE" do
core_tap = described_class.fetch("Homebrew", "core")
wrong_remote = "#{Homebrew::EnvConfig.core_git_remote}-oops"
expect do
core_tap.install clone_target: wrong_remote
end.to raise_error(TapCoreRemoteMismatchError)
end
it "raises an error when run `brew tap --custom-remote` without a custom remote (already installed)" do
setup_git_repo
already_tapped_tap = described_class.fetch("Homebrew", "foo")
expect(already_tapped_tap).to be_installed
expect do
already_tapped_tap.install clone_target: nil, custom_remote: true
end.to raise_error(TapNoCustomRemoteError)
end
it "raises an error when run `brew tap --custom-remote` without a custom remote (not installed)" do
not_tapped_tap = described_class.fetch("Homebrew", "bar")
expect(not_tapped_tap).not_to be_installed
expect do
not_tapped_tap.install clone_target: nil, custom_remote: true
end.to raise_error(TapNoCustomRemoteError)
end
specify "Git error" do
tap = described_class.fetch("user", "repo")
expect do
tap.install clone_target: "file:///not/existed/remote/url"
end.to raise_error(ErrorDuringExecution)
expect(tap).not_to be_installed
expect(HOMEBREW_TAP_DIRECTORY/"user").not_to exist
end
end
describe "#uninstall" do
it "raises an error if the Tap is not available" do
tap = described_class.fetch("Homebrew", "bar")
expect { tap.uninstall }.to raise_error(TapUnavailableError)
end
end
specify "#install and #uninstall" do
setup_tap_files
setup_git_repo
setup_completion link: true
tap = described_class.fetch("Homebrew", "bar")
tap.install clone_target: homebrew_foo_tap.path/".git"
expect(tap).to be_installed
expect(HOMEBREW_PREFIX/"share/man/man1/brew-tap-cmd.1").to be_a_file
expect(HOMEBREW_PREFIX/"etc/bash_completion.d/brew-tap-cmd").to be_a_file
expect(HOMEBREW_PREFIX/"share/zsh/site-functions/_brew-tap-cmd").to be_a_file
expect(HOMEBREW_PREFIX/"share/fish/vendor_completions.d/brew-tap-cmd.fish").to be_a_file
tap.uninstall
expect(tap).not_to be_installed
expect(HOMEBREW_PREFIX/"share/man/man1/brew-tap-cmd.1").not_to exist
expect(HOMEBREW_PREFIX/"share/man/man1").not_to exist
expect(HOMEBREW_PREFIX/"etc/bash_completion.d/brew-tap-cmd").not_to exist
expect(HOMEBREW_PREFIX/"share/zsh/site-functions/_brew-tap-cmd").not_to exist
expect(HOMEBREW_PREFIX/"share/fish/vendor_completions.d/brew-tap-cmd.fish").not_to exist
ensure
FileUtils.rm_r(HOMEBREW_PREFIX/"etc") if (HOMEBREW_PREFIX/"etc").exist?
FileUtils.rm_r(HOMEBREW_PREFIX/"share") if (HOMEBREW_PREFIX/"share").exist?
end
specify "#link_completions_and_manpages when completions are enabled for non-official tap" do
setup_tap_files
setup_git_repo
setup_completion link: true
tap = described_class.fetch("NotHomebrew", "baz")
tap.install clone_target: homebrew_foo_tap.path/".git"
(HOMEBREW_PREFIX/"share/man/man1/brew-tap-cmd.1").delete
(HOMEBREW_PREFIX/"etc/bash_completion.d/brew-tap-cmd").delete
(HOMEBREW_PREFIX/"share/zsh/site-functions/_brew-tap-cmd").delete
(HOMEBREW_PREFIX/"share/fish/vendor_completions.d/brew-tap-cmd.fish").delete
tap.link_completions_and_manpages
expect(HOMEBREW_PREFIX/"share/man/man1/brew-tap-cmd.1").to be_a_file
expect(HOMEBREW_PREFIX/"etc/bash_completion.d/brew-tap-cmd").to be_a_file
expect(HOMEBREW_PREFIX/"share/zsh/site-functions/_brew-tap-cmd").to be_a_file
expect(HOMEBREW_PREFIX/"share/fish/vendor_completions.d/brew-tap-cmd.fish").to be_a_file
tap.uninstall
ensure
FileUtils.rm_r(HOMEBREW_PREFIX/"etc") if (HOMEBREW_PREFIX/"etc").exist?
FileUtils.rm_r(HOMEBREW_PREFIX/"share") if (HOMEBREW_PREFIX/"share").exist?
end
specify "#link_completions_and_manpages when completions are disabled for non-official tap" do
setup_tap_files
setup_git_repo
setup_completion link: false
tap = described_class.fetch("NotHomebrew", "baz")
tap.install clone_target: homebrew_foo_tap.path/".git"
(HOMEBREW_PREFIX/"share/man/man1/brew-tap-cmd.1").delete
tap.link_completions_and_manpages
expect(HOMEBREW_PREFIX/"share/man/man1/brew-tap-cmd.1").to be_a_file
expect(HOMEBREW_PREFIX/"etc/bash_completion.d/brew-tap-cmd").not_to be_a_file
expect(HOMEBREW_PREFIX/"share/zsh/site-functions/_brew-tap-cmd").not_to be_a_file
expect(HOMEBREW_PREFIX/"share/fish/vendor_completions.d/brew-tap-cmd.fish").not_to be_a_file
tap.uninstall
ensure
FileUtils.rm_r(HOMEBREW_PREFIX/"etc") if (HOMEBREW_PREFIX/"etc").exist?
FileUtils.rm_r(HOMEBREW_PREFIX/"share") if (HOMEBREW_PREFIX/"share").exist?
end
specify "#link_completions_and_manpages when completions are enabled for official tap" do
setup_tap_files
setup_git_repo
setup_completion link: false
tap = described_class.fetch("Homebrew", "baz")
tap.install clone_target: homebrew_foo_tap.path/".git"
(HOMEBREW_PREFIX/"share/man/man1/brew-tap-cmd.1").delete
(HOMEBREW_PREFIX/"etc/bash_completion.d/brew-tap-cmd").delete
(HOMEBREW_PREFIX/"share/zsh/site-functions/_brew-tap-cmd").delete
(HOMEBREW_PREFIX/"share/fish/vendor_completions.d/brew-tap-cmd.fish").delete
tap.link_completions_and_manpages
expect(HOMEBREW_PREFIX/"share/man/man1/brew-tap-cmd.1").to be_a_file
expect(HOMEBREW_PREFIX/"etc/bash_completion.d/brew-tap-cmd").to be_a_file
expect(HOMEBREW_PREFIX/"share/zsh/site-functions/_brew-tap-cmd").to be_a_file
expect(HOMEBREW_PREFIX/"share/fish/vendor_completions.d/brew-tap-cmd.fish").to be_a_file
tap.uninstall
ensure
FileUtils.rm_r(HOMEBREW_PREFIX/"etc") if (HOMEBREW_PREFIX/"etc").exist?
FileUtils.rm_r(HOMEBREW_PREFIX/"share") if (HOMEBREW_PREFIX/"share").exist?
end
specify "#config" do
setup_git_repo
expect(homebrew_foo_tap.config[:foo]).to be_nil
homebrew_foo_tap.config[:foo] = true
expect(homebrew_foo_tap.config[:foo]).to be true
homebrew_foo_tap.config.delete(:foo)
expect(homebrew_foo_tap.config[:foo]).to be_nil
end
describe ".each" do
it "returns an enumerator if no block is passed" do
expect(described_class.each).to be_an_instance_of(Enumerator)
end
context "when the core tap is not installed" do
around do |example|
FileUtils.rm_rf CoreTap.instance.path
example.run
ensure
(CoreTap.instance.path/"Formula").mkpath
end
it "includes the core tap with the api" do
expect(described_class.to_a).to include(CoreTap.instance)
end
it "omits the core tap without the api", :no_api do
expect(described_class.to_a).not_to include(CoreTap.instance)
end
end
end
describe ".installed" do
it "includes only installed taps" do
expect(described_class.installed)
.to contain_exactly(CoreTap.instance, described_class.fetch("homebrew/foo"))
end
end
describe ".all" do
it "includes the core and cask taps by default", :needs_macos do
expect(described_class.all).to contain_exactly(
CoreTap.instance,
CoreCaskTap.instance,
described_class.fetch("homebrew/foo"),
described_class.fetch("third-party/tap"),
)
end
it "includes the core tap and excludes the cask tap by default", :needs_linux do
expect(described_class.all)
.to contain_exactly(CoreTap.instance, described_class.fetch("homebrew/foo"))
end
end
describe "Formula Lists" do
describe "#formula_renames" do
it "returns the formula_renames hash" do
setup_tap_files
expected_result = { "oldname" => "foo" }
expect(homebrew_foo_tap.formula_renames).to eq expected_result
end
end
describe "#tap_migrations" do
it "returns the tap_migrations hash" do
setup_tap_files
expected_result = { "removed-formula" => "homebrew/foo" }
expect(homebrew_foo_tap.tap_migrations).to eq expected_result
end
end
describe "tap migration renames" do
before do
(path/"tap_migrations.json").write <<~JSON
{
"adobe-air-sdk": "homebrew/cask",
"app-engine-go-32": "homebrew/cask/google-cloud-sdk",
"app-engine-go-64": "homebrew/cask/google-cloud-sdk",
"gimp": "homebrew/cask",
"horndis": "homebrew/cask",
"inkscape": "homebrew/cask",
"schismtracker": "homebrew/cask/schism-tracker"
}
JSON
end
describe "#reverse_tap_migration_renames" do
it "returns the expected hash" do
expect(homebrew_foo_tap.reverse_tap_migrations_renames).to eq({
"homebrew/cask/google-cloud-sdk" => %w[app-engine-go-32 app-engine-go-64],
"homebrew/cask/schism-tracker" => %w[schismtracker],
})
end
end
describe ".tap_migration_oldnames" do
let(:cask_tap) { CoreCaskTap.instance }
let(:core_tap) { CoreTap.instance }
it "returns expected renames", :no_api do
[
[cask_tap, "gimp", []],
[core_tap, "schism-tracker", []],
[cask_tap, "schism-tracker", %w[schismtracker]],
[cask_tap, "google-cloud-sdk", %w[app-engine-go-32 app-engine-go-64]],
].each do |tap, name, result|
expect(described_class.tap_migration_oldnames(tap, name)).to eq(result)
end
end
end
end
describe "#audit_exceptions" do
it "returns the audit_exceptions hash" do
setup_tap_files
expected_result = {
formula_list: ["foo", "bar"],
formula_hash: { "foo" => "foo1", "bar" => "bar1" },
}
expect(homebrew_foo_tap.audit_exceptions).to eq expected_result
end
end
describe "#style_exceptions" do
it "returns the style_exceptions hash" do
setup_tap_files
expected_result = {
formula_list: ["foo", "bar"],
formula_hash: { "foo" => "foo1", "bar" => "bar1" },
}
expect(homebrew_foo_tap.style_exceptions).to eq expected_result
end
end
describe "#formula_file?" do
it "matches files from Formula/" do
tap = described_class.fetch("hard/core")
FileUtils.mkdir_p(tap.path/"Formula")
%w[
kvazaar.rb
Casks/kvazaar.rb
Casks/k/kvazaar.rb
Formula/kvazaar.sh
HomebrewFormula/kvazaar.rb
HomebrewFormula/k/kvazaar.rb
].each do |relative_path|
expect(tap).not_to have_formula_file(relative_path)
end
%w[
Formula/kvazaar.rb
Formula/k/kvazaar.rb
].each do |relative_path|
expect(tap).to have_formula_file(relative_path)
end
ensure
FileUtils.rm_rf(tap.path.parent) if tap
end
it "matches files from HomebrewFormula/" do
tap = described_class.fetch("hard/core")
FileUtils.mkdir_p(tap.path/"HomebrewFormula")
%w[
kvazaar.rb
Casks/kvazaar.rb
Casks/k/kvazaar.rb
Formula/kvazaar.rb
Formula/k/kvazaar.rb
HomebrewFormula/kvazaar.sh
].each do |relative_path|
expect(tap).not_to have_formula_file(relative_path)
end
%w[
HomebrewFormula/kvazaar.rb
HomebrewFormula/k/kvazaar.rb
].each do |relative_path|
expect(tap).to have_formula_file(relative_path)
end
ensure
FileUtils.rm_rf(tap.path.parent) if tap
end
it "matches files from the top-level directory" do
tap = described_class.fetch("hard/core")
FileUtils.mkdir_p(tap.path)
%w[
kvazaar.sh
Casks/kvazaar.rb
Casks/k/kvazaar.rb
Formula/kvazaar.rb
Formula/k/kvazaar.rb
HomebrewFormula/kvazaar.rb
HomebrewFormula/k/kvazaar.rb
].each do |relative_path|
expect(tap).not_to have_formula_file(relative_path)
end
expect(tap).to have_formula_file("kvazaar.rb")
ensure
FileUtils.rm_rf(tap.path.parent) if tap
end
end
describe "#cask_file?" do
it "matches files from Casks/" do
tap = described_class.fetch("hard/core")
%w[
kvazaar.rb
Casks/kvazaar.sh
Formula/kvazaar.rb
Formula/k/kvazaar.rb
HomebrewFormula/kvazaar.rb
HomebrewFormula/k/kvazaar.rb
].each do |relative_path|
expect(tap).not_to have_cask_file(relative_path)
end
%w[
Casks/kvazaar.rb
Casks/k/kvazaar.rb
].each do |relative_path|
expect(tap).to have_cask_file(relative_path)
end
end
end
end
describe CoreTap do
subject(:core_tap) { described_class.instance }
specify "attributes" do
expect(core_tap.user).to eq("Homebrew")
expect(core_tap.repository).to eq("core")
expect(core_tap.name).to eq("homebrew/core")
expect(core_tap.command_files).to eq([])
expect(core_tap).to be_installed
expect(core_tap).to be_official
expect(core_tap).to be_a_core_tap
end
specify "forbidden operations", :no_api do
expect { core_tap.uninstall }.to raise_error(RuntimeError)
end
specify "files", :no_api do
path = HOMEBREW_TAP_DIRECTORY/"homebrew/homebrew-core"
formula_file = core_tap.formula_dir/"foo.rb"
core_tap.formula_dir.mkpath
formula_file.write <<~RUBY
class Foo < Formula
url "https://brew.sh/foo-1.0.tar.gz"
end
RUBY
formula_list_file_json = '{ "foo": "foo1", "bar": "bar1" }'
formula_list_file_contents = { "foo" => "foo1", "bar" => "bar1" }
%w[
formula_renames.json
tap_migrations.json
audit_exceptions/formula_list.json
style_exceptions/formula_hash.json
].each do |file|
(path/file).dirname.mkpath
(path/file).write formula_list_file_json
end
alias_file = core_tap.alias_dir/"bar"
alias_file.parent.mkpath
ln_s formula_file, alias_file
expect(core_tap.formula_files).to eq([formula_file])
expect(core_tap.formula_names).to eq(["foo"])
expect(core_tap.alias_files).to eq([alias_file])
expect(core_tap.aliases).to eq(["bar"])
expect(core_tap.alias_table).to eq("bar" => "foo")
expect(core_tap.alias_reverse_table).to eq("foo" => ["bar"])
expect(core_tap.formula_renames).to eq formula_list_file_contents
expect(core_tap.tap_migrations).to eq formula_list_file_contents
expect(core_tap.audit_exceptions).to eq({ formula_list: formula_list_file_contents })
expect(core_tap.style_exceptions).to eq({ formula_hash: formula_list_file_contents })
end
end
describe "#repository_var_suffix" do
it "converts the repo directory to an environment variable suffix" do
expect(CoreTap.instance.repository_var_suffix).to eq "_HOMEBREW_HOMEBREW_CORE"
end
it "converts non-alphanumeric characters to underscores" do # rubocop:todo RSpec/AggregateExamples
expect(described_class.fetch("my",
"tap-with-dashes").repository_var_suffix).to eq "_MY_HOMEBREW_TAP_WITH_DASHES"
expect(described_class.fetch("my",
"tap-with-@-symbol").repository_var_suffix).to eq "_MY_HOMEBREW_TAP_WITH___SYMBOL"
end
end
describe "::with_formula_name" do
it "returns the tap and formula name when given a full name" do
expect(described_class.with_formula_name("homebrew/core/gcc")).to eq [CoreTap.instance, "gcc"]
end
it "returns nil when given a relative path" do
expect(described_class.with_formula_name("./Formula/gcc.rb")).to be_nil
end
end
describe "::with_cask_token" do
it "returns the tap and cask token when given a full token" do
expect(described_class.with_cask_token("homebrew/cask/alfred")).to eq [CoreCaskTap.instance, "alfred"]
end
it "returns nil when given a relative path" do
expect(described_class.with_cask_token("./Casks/alfred.rb")).to be_nil
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/lock_file_spec.rb | Library/Homebrew/test/lock_file_spec.rb | # frozen_string_literal: true
require "lock_file"
RSpec.describe LockFile do
subject(:lock_file) { described_class.new(:lock, Pathname("foo")) }
let(:lock_file_copy) { described_class.new(:lock, Pathname("foo")) }
describe "#lock" do
it "ensures the lock file is created" do
expect(lock_file.path).not_to exist
lock_file.lock
expect(lock_file.path).to exist
end
it "does not raise an error when the same instance is locked multiple times" do
lock_file.lock
expect { lock_file.lock }.not_to raise_error
end
it "raises an error if another instance is already locked" do
lock_file.lock
expect do
lock_file_copy.lock
end.to raise_error(OperationInProgressError)
end
end
describe "#unlock" do
it "does not raise an error when already unlocked" do
expect { lock_file.unlock }.not_to raise_error
end
it "unlocks when locked" do
lock_file.lock
lock_file.unlock
expect { lock_file_copy.lock }.not_to raise_error
end
it "allows deleting a lock file only by the instance that locked it" do
lock_file.lock
expect(lock_file.path).to exist
expect(lock_file_copy.path).to exist
lock_file_copy.unlock(unlink: true)
expect(lock_file_copy.path).to exist
expect(lock_file.path).to exist
lock_file.unlock(unlink: true)
expect(lock_file.path).not_to exist
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/missing_formula_spec.rb | Library/Homebrew/test/missing_formula_spec.rb | # frozen_string_literal: true
require "missing_formula"
RSpec.describe Homebrew::MissingFormula do
describe "::reason" do
subject { described_class.reason("gem") }
it { is_expected.not_to be_nil }
end
describe "::disallowed_reason" do
matcher :disallow do |name|
match do |expected|
expected.disallowed_reason(name)
end
end
specify(:aggregate_failures) do
expect(subject).to disallow("gem") # rubocop:todo RSpec/NamedSubject
expect(subject).to disallow("pip") # rubocop:todo RSpec/NamedSubject
expect(subject).to disallow("pil") # rubocop:todo RSpec/NamedSubject
expect(subject).to disallow("macruby") # rubocop:todo RSpec/NamedSubject
expect(subject).to disallow("lzma") # rubocop:todo RSpec/NamedSubject
expect(subject).to disallow("gsutil") # rubocop:todo RSpec/NamedSubject
expect(subject).to disallow("gfortran") # rubocop:todo RSpec/NamedSubject
expect(subject).to disallow("play") # rubocop:todo RSpec/NamedSubject
expect(subject).to disallow("haskell-platform") # rubocop:todo RSpec/NamedSubject
expect(subject).to disallow("mysqldump-secure") # rubocop:todo RSpec/NamedSubject
expect(subject).to disallow("ngrok") # rubocop:todo RSpec/NamedSubject
end
it("disallows Xcode", :needs_macos) { is_expected.to disallow("xcode") }
end
describe "::tap_migration_reason" do
subject { described_class.tap_migration_reason(formula) }
before do
tap_path = HOMEBREW_TAP_DIRECTORY/"homebrew/homebrew-foo"
tap_path.mkpath
(tap_path/"tap_migrations.json").write <<~JSON
{ "migrated-formula": "homebrew/bar" }
JSON
end
context "with a migrated formula" do
let(:formula) { "migrated-formula" }
it { is_expected.not_to be_nil }
end
context "with a missing formula" do
let(:formula) { "missing-formula" }
it { is_expected.to be_nil }
end
end
describe "::deleted_reason" do
subject { described_class.deleted_reason(formula, silent: true) }
before do
tap_path = HOMEBREW_TAP_DIRECTORY/"homebrew/homebrew-foo"
(tap_path/"Formula").mkpath
(tap_path/"Formula/deleted-formula.rb").write "placeholder"
ENV.delete "GIT_AUTHOR_DATE"
ENV.delete "GIT_COMMITTER_DATE"
tap_path.cd do
system "git", "init"
system "git", "add", "--all"
system "git", "commit", "-m", "initial state"
system "git", "rm", "Formula/deleted-formula.rb"
system "git", "commit", "-m", "delete formula 'deleted-formula'"
end
end
shared_examples "it detects deleted formulae" do
context "with a deleted formula" do
let(:formula) { "homebrew/foo/deleted-formula" }
it { is_expected.not_to be_nil }
end
context "with a formula that never existed" do
let(:formula) { "homebrew/foo/missing-formula" }
it { is_expected.to be_nil }
end
end
include_examples "it detects deleted formulae"
describe "on the core tap" do
before do
allow_any_instance_of(Tap).to receive(:core_tap?).and_return(true)
end
include_examples "it detects deleted formulae"
end
end
describe "::cask_reason", :cask do
subject { described_class.cask_reason(formula, show_info:) }
context "with a formula name that is a cask and show_info: false" do
let(:formula) { "local-caffeine" }
let(:show_info) { false }
specify(:aggregate_failures) do
expect(subject).to match(/Found a cask named "local-caffeine" instead./) # rubocop:todo RSpec/NamedSubject
expect(subject).to match(/Try\n brew install --cask local-caffeine/) # rubocop:todo RSpec/NamedSubject
end
end
context "with a formula name that is a cask and show_info: true" do
let(:formula) { "local-caffeine" }
let(:show_info) { true }
it { is_expected.to match(/Found a cask named "local-caffeine" instead.\n\n==> local-caffeine: 1.2.3\n/) }
end
context "with a formula name that is not a cask" do
let(:formula) { "missing-formula" }
let(:show_info) { false }
it { is_expected.to be_nil }
end
end
describe "::suggest_command", :cask do
subject { described_class.suggest_command(name, command) }
context "when installing" do
let(:name) { "local-caffeine" }
let(:command) { "install" }
specify(:aggregate_failures) do
expect(subject).to match(/Found a cask named "local-caffeine" instead./) # rubocop:todo RSpec/NamedSubject
expect(subject).to match(/Try\n brew install --cask local-caffeine/) # rubocop:todo RSpec/NamedSubject
end
end
context "when uninstalling" do
let(:name) { "local-caffeine" }
let(:command) { "uninstall" }
it { is_expected.to be_nil }
context "with described cask installed" do
before do
allow(Cask::Caskroom).to receive(:casks).and_return(["local-caffeine"])
end
specify(:aggregate_failures) do
expect(subject).to match(/Found a cask named "local-caffeine" instead./) # rubocop:todo RSpec/NamedSubject
expect(subject).to match(/Try\n brew uninstall --cask local-caffeine/) # rubocop:todo RSpec/NamedSubject
end
end
end
context "when getting info" do
let(:name) { "local-caffeine" }
let(:command) { "info" }
specify(:aggregate_failures) do
expect(subject).to match(/Found a cask named "local-caffeine" instead./) # rubocop:todo RSpec/NamedSubject
expect(subject).to match(/local-caffeine: 1.2.3/) # rubocop:todo RSpec/NamedSubject
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/messages_spec.rb | Library/Homebrew/test/messages_spec.rb | # frozen_string_literal: true
require "messages"
require "spec_helper"
RSpec.describe Messages do
let(:messages) { described_class.new }
let(:test_formula) { formula("foo") { url("https://brew.sh/foo-0.1.tgz") } }
let(:elapsed_time) { 1.1 }
describe "#record_caveats" do
it "adds a caveat" do
expect do
messages.record_caveats(test_formula.name, "Zsh completions were installed")
end.to change(messages.caveats, :count).by(1)
end
end
describe "#package_installed" do
it "increases the package count" do
expect do
messages.package_installed(test_formula.name, elapsed_time)
end.to change(messages, :package_count).by(1)
end
it "adds to install_times" do
expect do
messages.package_installed(test_formula.name, elapsed_time)
end.to change(messages.install_times, :count).by(1)
end
end
describe "#display_messages" do
context "when package_count is less than two" do
before do
messages.record_caveats(test_formula.name, "Zsh completions were installed")
messages.package_installed(test_formula.name, elapsed_time)
end
it "doesn't print caveat details" do
expect { messages.display_messages }.not_to output.to_stdout
end
end
context "when caveats is empty" do
before do
messages.package_installed(test_formula.name, elapsed_time)
end
it "doesn't print caveat details" do
expect { messages.display_messages }.not_to output.to_stdout
end
end
context "when package_count is greater than one and caveats are present" do
let(:test_formula2) { formula("bar") { url("https://brew.sh/bar-0.1.tgz") } }
before do
messages.record_caveats(test_formula.name, "Zsh completions were installed")
messages.package_installed(test_formula.name, elapsed_time)
messages.package_installed(test_formula2.name, elapsed_time)
end
it "prints caveat details" do
expect { messages.display_messages }.to output(
<<~EOS,
==> Caveats
==> foo
Zsh completions were installed
EOS
).to_stdout
end
end
context "when the `display_times` argument is true" do
context "when `install_times` is empty" do
it "doesn't print anything" do
expect { messages.display_messages(display_times: true) }.not_to output.to_stdout
end
end
context "when `install_times` is present" do
before do
messages.package_installed(test_formula.name, elapsed_time)
end
it "prints installation times" do
expect { messages.display_messages(display_times: true) }.to output(
<<~EOS,
==> Installation times
foo 1.100 s
EOS
).to_stdout
end
end
end
context "when the `display_times` argument isn't specified" do
it "doesn't print installation times" do
expect { messages.display_messages }.not_to output.to_stdout
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/global_spec.rb | Library/Homebrew/test/global_spec.rb | # frozen_string_literal: true
RSpec.describe Homebrew, :integration_test do
it "does not require slow dependencies at startup" do
expect { brew "verify-undefined" }
.to not_to_output.to_stdout
.and not_to_output.to_stderr
.and be_a_success
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/keg_only_reason_spec.rb | Library/Homebrew/test/keg_only_reason_spec.rb | # frozen_string_literal: true
require "keg_only_reason"
RSpec.describe KegOnlyReason do
describe "#to_s" do
it "returns the reason provided" do
r = described_class.new :provided_by_macos, "test"
expect(r.to_s).to eq("test")
end
it "returns a default message when no reason is provided" do
r = described_class.new :provided_by_macos, ""
expect(r.to_s).to match(/^macOS already provides/)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/bundle_version_spec.rb | Library/Homebrew/test/bundle_version_spec.rb | # frozen_string_literal: true
require "bundle_version"
RSpec.describe Homebrew::BundleVersion do
describe "#<=>" do
it "compares both the `short_version` and `version`" do
expect(described_class.new("1.2.3", "3000")).to be < described_class.new("1.2.3", "4000")
expect(described_class.new("1.2.3", "4000")).to be <= described_class.new("1.2.3", "4000")
expect(described_class.new("1.2.3", "4000")).to be >= described_class.new("1.2.3", "4000")
expect(described_class.new("1.2.4", "4000")).to be > described_class.new("1.2.3", "4000")
end
it "compares `version` first" do
expect(described_class.new("1.2.4", "3000")).to be < described_class.new("1.2.3", "4000")
end
it "does not fail when `short_version` or `version` is missing" do
expect(described_class.new("1.06", nil)).to be < described_class.new("1.12", "1.12")
expect(described_class.new("1.06", "471")).to be > described_class.new(nil, "311")
expect(described_class.new("1.2.3", nil)).to be < described_class.new("1.2.4", nil)
expect(described_class.new(nil, "1.2.3")).to be < described_class.new(nil, "1.2.4")
expect(described_class.new("1.2.3", nil)).to be < described_class.new(nil, "1.2.3")
expect(described_class.new(nil, "1.2.3")).to be > described_class.new("1.2.3", nil)
end
end
describe "#nice_version" do
expected_mappings = {
["1.2", nil] => "1.2",
[nil, "1.2.3"] => "1.2.3",
["1.2", "1.2.3"] => "1.2.3",
["1.2.3", "1.2"] => "1.2.3",
["1.2.3", "8312"] => "1.2.3,8312",
["2021", "2006"] => "2021,2006",
["1.0", "1"] => "1.0",
["1.0", "0"] => "1.0",
["1.2.3.4000", "4000"] => "1.2.3.4000",
["5", "5.0.45"] => "5.0.45",
["2.5.2(3329)", "3329"] => "2.5.2,3329",
}
expected_mappings.each do |(short_version, version), expected_version|
it "maps (#{short_version.inspect}, #{version.inspect}) to #{expected_version.inspect}" do
expect(described_class.new(short_version, version).nice_version)
.to eq expected_version
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/cleanup_spec.rb | Library/Homebrew/test/cleanup_spec.rb | # frozen_string_literal: true
require "test/support/fixtures/testball"
require "cleanup"
require "cask/cache"
require "fileutils"
RSpec.describe Homebrew::Cleanup do
subject(:cleanup) { described_class.new }
let(:ds_store) { Pathname.new("#{HOMEBREW_CELLAR}/.DS_Store") }
let(:lock_file) { Pathname.new("#{HOMEBREW_LOCKS}/foo") }
around do |example|
FileUtils.touch ds_store
FileUtils.touch lock_file
FileUtils.mkdir_p HOMEBREW_LIBRARY/"Homebrew/vendor"
FileUtils.touch HOMEBREW_LIBRARY/"Homebrew/vendor/portable-ruby-version"
example.run
ensure
FileUtils.rm_f ds_store
FileUtils.rm_f lock_file
FileUtils.rm_rf HOMEBREW_LIBRARY/"Homebrew"
end
describe "::prune?" do
subject(:path) { HOMEBREW_CACHE/"foo" }
before do
path.mkpath
end
it "returns true when ctime and mtime < days_default" do
allow_any_instance_of(Pathname).to receive(:ctime).and_return((DateTime.now - 2).to_time)
allow_any_instance_of(Pathname).to receive(:mtime).and_return((DateTime.now - 2).to_time)
expect(described_class.prune?(path, 1)).to be true
end
it "returns false when ctime and mtime >= days_default" do
expect(described_class.prune?(path, 2)).to be false
end
end
describe "::cleanup" do
it "removes .DS_Store and lock files" do
cleanup.clean!
expect(ds_store).not_to exist
expect(lock_file).not_to exist
end
it "doesn't remove anything if `dry_run` is true" do
described_class.new(dry_run: true).clean!
expect(ds_store).to exist
expect(lock_file).to exist
end
it "doesn't remove the lock file if it is locked" do
lock_file.open(File::RDWR | File::CREAT).flock(File::LOCK_EX | File::LOCK_NB)
cleanup.clean!
expect(lock_file).to exist
end
context "when it can't remove a keg" do
let(:formula_zero_dot_one) { Class.new(Testball) { version "0.1" }.new }
let(:formula_zero_dot_two) { Class.new(Testball) { version "0.2" }.new }
before do
[formula_zero_dot_one, formula_zero_dot_two].each do |f|
f.brew do
f.install
end
Tab.create(f, DevelopmentTools.default_compiler, :libcxx).write
end
allow_any_instance_of(Keg)
.to receive(:uninstall)
.and_raise(Errno::EACCES)
end
it "doesn't remove any kegs" do
cleanup.cleanup_formula formula_zero_dot_one
expect(formula_zero_dot_one.installed_kegs.size).to eq(2)
end
it "lists the unremovable kegs" do
cleanup.cleanup_formula formula_zero_dot_two
expect(cleanup.unremovable_kegs).to contain_exactly(formula_zero_dot_one.installed_kegs[0])
end
end
end
describe "::prune_prefix_symlinks_and_directories" do
let(:lib) { HOMEBREW_PREFIX/"lib" }
before do
lib.mkpath
end
it "keeps required empty directories" do
cleanup.prune_prefix_symlinks_and_directories
expect(lib).to exist
expect(lib.children).to be_empty
end
it "removes broken symlinks" do
FileUtils.ln_s lib/"foo", lib/"bar"
FileUtils.touch lib/"baz"
cleanup.prune_prefix_symlinks_and_directories
expect(lib).to exist
expect(lib.children).to eq([lib/"baz"])
end
it "removes empty directories" do
dir = lib/"test"
dir.mkpath
file = lib/"keep/file"
file.dirname.mkpath
FileUtils.touch file
cleanup.prune_prefix_symlinks_and_directories
expect(dir).not_to exist
expect(file).to exist
end
context "when nested directories exist with only broken symlinks" do
let(:dir) { HOMEBREW_PREFIX/"lib/foo" }
let(:child_dir) { dir/"bar" }
let(:grandchild_dir) { child_dir/"baz" }
let(:broken_link) { dir/"broken" }
let(:link_to_broken_link) { child_dir/"another-broken" }
before do
grandchild_dir.mkpath
FileUtils.ln_s dir/"missing", broken_link
FileUtils.ln_s broken_link, link_to_broken_link
end
it "removes broken symlinks and resulting empty directories" do
cleanup.prune_prefix_symlinks_and_directories
expect(dir).not_to exist
end
it "doesn't remove anything and only prints removal steps if `dry_run` is true" do
expect do
described_class.new(dry_run: true).prune_prefix_symlinks_and_directories
end.to output(<<~EOS).to_stdout
Would remove (broken link): #{link_to_broken_link}
Would remove (broken link): #{broken_link}
Would remove (empty directory): #{grandchild_dir}
Would remove (empty directory): #{child_dir}
Would remove (empty directory): #{dir}
EOS
expect(broken_link).to be_a_symlink
expect(link_to_broken_link).to be_a_symlink
expect(grandchild_dir).to exist
end
end
it "removes broken symlinks for uninstalled migrated Casks" do
caskroom = Cask::Caskroom.path
old_cask_dir = caskroom/"old"
new_cask_dir = caskroom/"new"
unrelated_cask_dir = caskroom/"other"
unrelated_cask_dir.mkpath
FileUtils.ln_s new_cask_dir, old_cask_dir
cleanup.prune_prefix_symlinks_and_directories
expect(unrelated_cask_dir).to exist
expect(old_cask_dir).not_to be_a_symlink
expect(old_cask_dir).not_to exist
end
end
specify "::cleanup_formula" do
f1 = Class.new(Testball) do
version "1.0"
end.new
f2 = Class.new(Testball) do
version "0.2"
version_scheme 1
end.new
f3 = Class.new(Testball) do
version "0.3"
version_scheme 1
end.new
f4 = Class.new(Testball) do
version "0.1"
version_scheme 2
end.new
[f1, f2, f3, f4].each do |f|
f.brew do
f.install
end
Tab.create(f, DevelopmentTools.default_compiler, :libcxx).write
end
expect(f1).to be_latest_version_installed
expect(f2).to be_latest_version_installed
expect(f3).to be_latest_version_installed
expect(f4).to be_latest_version_installed
cleanup.cleanup_formula f3
expect(f1).not_to be_latest_version_installed
expect(f2).not_to be_latest_version_installed
expect(f3).to be_latest_version_installed
expect(f4).to be_latest_version_installed
end
describe "#cleanup_cask", :cask do
before do
Cask::Cache.path.mkpath
end
context "when given a versioned cask" do
let(:cask) { Cask::CaskLoader.load("local-transmission") }
it "removes the download if it is not for the latest version" do
download = Cask::Cache.path/"#{cask.token}--7.8.9"
FileUtils.touch download
cleanup.cleanup_cask(cask)
expect(download).not_to exist
end
it "does not remove downloads for the latest version" do
download = Cask::Cache.path/"#{cask.token}--#{cask.version}"
FileUtils.touch download
cleanup.cleanup_cask(cask)
expect(download).to exist
end
end
context "when given a `:latest` cask" do
let(:cask) { Cask::CaskLoader.load("latest") }
it "does not remove the download for the latest version" do
download = Cask::Cache.path/"#{cask.token}--#{cask.version}"
FileUtils.touch download
cleanup.cleanup_cask(cask)
expect(download).to exist
end
it "removes the download for the latest version after 30 days" do
download = Cask::Cache.path/"#{cask.token}--#{cask.version}"
allow(download).to receive_messages(ctime: (DateTime.now - 30).to_time - (60 * 60),
mtime: (DateTime.now - 30).to_time - (60 * 60))
cleanup.cleanup_cask(cask)
expect(download).not_to exist
end
end
end
describe "::cleanup_logs" do
let(:path) { (HOMEBREW_LOGS/"delete_me") }
before do
path.mkpath
end
it "cleans all logs if prune is 0" do
described_class.new(days: 0).cleanup_logs
expect(path).not_to exist
end
it "cleans up logs if older than 30 days" do
allow_any_instance_of(Pathname).to receive(:ctime).and_return((DateTime.now - 31).to_time)
allow_any_instance_of(Pathname).to receive(:mtime).and_return((DateTime.now - 31).to_time)
cleanup.cleanup_logs
expect(path).not_to exist
end
it "does not clean up logs less than 30 days old" do
allow_any_instance_of(Pathname).to receive(:ctime).and_return((DateTime.now - 15).to_time)
allow_any_instance_of(Pathname).to receive(:mtime).and_return((DateTime.now - 15).to_time)
cleanup.cleanup_logs
expect(path).to exist
end
end
describe "::cleanup_cache" do
it "cleans up incomplete downloads" do
incomplete = (HOMEBREW_CACHE/"something.incomplete")
incomplete.mkpath
cleanup.cleanup_cache
expect(incomplete).not_to exist
end
it "cleans up 'cargo_cache'" do
cargo_cache = (HOMEBREW_CACHE/"cargo_cache")
cargo_cache.mkpath
cleanup.cleanup_cache
expect(cargo_cache).not_to exist
end
it "cleans up 'go_cache'" do
go_cache = (HOMEBREW_CACHE/"go_cache")
go_cache.mkpath
cleanup.cleanup_cache
expect(go_cache).not_to exist
end
it "cleans up 'glide_home'" do
glide_home = (HOMEBREW_CACHE/"glide_home")
glide_home.mkpath
cleanup.cleanup_cache
expect(glide_home).not_to exist
end
it "cleans up 'java_cache'" do
java_cache = (HOMEBREW_CACHE/"java_cache")
java_cache.mkpath
cleanup.cleanup_cache
expect(java_cache).not_to exist
end
it "cleans up 'npm_cache'" do
npm_cache = (HOMEBREW_CACHE/"npm_cache")
npm_cache.mkpath
cleanup.cleanup_cache
expect(npm_cache).not_to exist
end
it "cleans up 'gclient_cache'" do
gclient_cache = (HOMEBREW_CACHE/"gclient_cache")
gclient_cache.mkpath
cleanup.cleanup_cache
expect(gclient_cache).not_to exist
end
it "cleans up all files and directories" do
git = (HOMEBREW_CACHE/"gist--git")
gist = (HOMEBREW_CACHE/"gist")
svn = (HOMEBREW_CACHE/"gist--svn")
git.mkpath
gist.mkpath
FileUtils.touch svn
described_class.new(days: 0).cleanup_cache
expect(git).not_to exist
expect(gist).to exist
expect(svn).not_to exist
end
it "does not clean up directories that are not VCS checkouts" do
git = (HOMEBREW_CACHE/"git")
git.mkpath
described_class.new(days: 0).cleanup_cache
expect(git).to exist
end
it "cleans up VCS checkout directories with modified time < prune time" do
foo = (HOMEBREW_CACHE/"--foo")
foo.mkpath
allow_any_instance_of(Pathname).to receive(:ctime).and_return(Time.now - (2 * 60 * 60 * 24))
allow_any_instance_of(Pathname).to receive(:mtime).and_return(Time.now - (2 * 60 * 60 * 24))
described_class.new(days: 1).cleanup_cache
expect(foo).not_to exist
end
it "does not clean up VCS checkout directories with modified time >= prune time" do
foo = (HOMEBREW_CACHE/"--foo")
foo.mkpath
described_class.new(days: 1).cleanup_cache
expect(foo).to exist
end
context "when cleaning old files in HOMEBREW_CACHE" do
let(:bottle) { (HOMEBREW_CACHE/"testball--0.0.1.tag.bottle.tar.gz") }
let(:testball) { (HOMEBREW_CACHE/"testball--0.0.1") }
let(:testball_resource) { (HOMEBREW_CACHE/"testball--rsrc--0.0.1.txt") }
before do
FileUtils.touch bottle
FileUtils.touch testball
FileUtils.touch testball_resource
(HOMEBREW_CELLAR/"testball"/"0.0.1").mkpath
# Create the latest version of testball so the older version is eligible for cleanup.
(HOMEBREW_CELLAR/"testball"/"0.1/bin").mkpath
FileUtils.touch(CoreTap.instance.new_formula_path("testball"))
end
it "cleans up file if outdated" do
allow(Utils::Bottles).to receive(:file_outdated?).with(any_args).and_return(true)
cleanup.cleanup_cache
expect(bottle).not_to exist
expect(testball).not_to exist
expect(testball_resource).not_to exist
end
it "cleans up file if `scrub` is true and formula not installed" do
described_class.new(scrub: true).cleanup_cache
expect(bottle).not_to exist
expect(testball).not_to exist
expect(testball_resource).not_to exist
end
it "cleans up file if stale" do
cleanup.cleanup_cache
expect(bottle).not_to exist
expect(testball).not_to exist
expect(testball_resource).not_to exist
end
end
end
describe "::cleanup_python_site_packages" do
context "when cleaning up Python modules" do
let(:foo_module) { (HOMEBREW_PREFIX/"lib/python3.99/site-packages/foo") }
let(:foo_pycache) { (foo_module/"__pycache__") }
let(:foo_pyc) { (foo_pycache/"foo.cypthon-399.pyc") }
before do
foo_pycache.mkpath
FileUtils.touch foo_pyc
end
it "cleans up stray `*.pyc` files" do
cleanup.cleanup_python_site_packages
expect(foo_pyc).not_to exist
end
it "retains `*.pyc` files of installed modules" do
FileUtils.touch foo_module/"__init__.py"
cleanup.cleanup_python_site_packages
expect(foo_pyc).to exist
end
end
it "cleans up stale `*.pyc` files in the top-level `__pycache__`" do
pycache = HOMEBREW_PREFIX/"lib/python3.99/site-packages/__pycache__"
foo_pyc = pycache/"foo.cypthon-3.99.pyc"
pycache.mkpath
FileUtils.touch foo_pyc
allow_any_instance_of(Pathname).to receive(:ctime).and_return(Time.now - (2 * 60 * 60 * 24))
allow_any_instance_of(Pathname).to receive(:mtime).and_return(Time.now - (2 * 60 * 60 * 24))
described_class.new(days: 1).cleanup_python_site_packages
expect(foo_pyc).not_to exist
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/formula_installer_spec.rb | Library/Homebrew/test/formula_installer_spec.rb | # frozen_string_literal: true
require "formula"
require "formula_installer"
require "keg"
require "sandbox"
require "tab"
require "cmd/install"
require "test/support/fixtures/testball"
require "test/support/fixtures/testball_bottle"
require "test/support/fixtures/failball"
require "test/support/fixtures/failball_offline_install"
RSpec.describe FormulaInstaller do
matcher :be_poured_from_bottle do
match(&:poured_from_bottle)
end
def temporary_install(formula, **options)
expect(formula).not_to be_latest_version_installed
installer = described_class.new(formula, **options)
installer.fetch
installer.install
keg = Keg.new(formula.prefix)
expect(formula).to be_latest_version_installed
begin
Tab.clear_cache
expect(keg.tab).not_to be_poured_from_bottle
yield formula if block_given?
ensure
Tab.clear_cache
keg.unlink
keg.uninstall
formula.clear_cache
# there will be log files when sandbox is enable.
FileUtils.rm_r(formula.logs) if formula.logs.directory?
end
expect(keg).not_to exist
expect(formula).not_to be_latest_version_installed
end
specify "basic installation" do
temporary_install(Testball.new) do |f|
# Test that things made it into the Keg
# "readme" is empty, so it should not be installed
expect(f.prefix/"readme").not_to exist
expect(f.bin).to be_a_directory
expect(f.bin.children.count).to eq(3)
expect(f.libexec).to be_a_directory
expect(f.libexec.children.count).to eq(1)
expect(f.prefix/"main.c").not_to exist
expect(f.prefix/"license").not_to exist
# Test that things make it into the Cellar
keg = Keg.new f.prefix
keg.link
bin = HOMEBREW_PREFIX/"bin"
expect(bin).to be_a_directory
expect(bin.children.count).to eq(3)
expect(f.prefix/".brew/testball.rb").to be_readable
end
end
specify "offline installation" do
expect { temporary_install(FailballOfflineInstall.new) }.to raise_error(BuildError) if Sandbox.available?
end
specify "Formula is not poured from bottle when compiler specified" do
temporary_install(TestballBottle.new, cc: "clang") do |f|
tab = Tab.for_formula(f)
expect(tab.compiler).to eq("clang")
end
end
describe "#check_install_sanity" do
it "raises on direct cyclic dependency" do
ENV["HOMEBREW_DEVELOPER"] = "1"
dep_name = "homebrew-test-cyclic"
dep_path = CoreTap.instance.new_formula_path(dep_name)
dep_path.write <<~RUBY
class #{Formulary.class_s(dep_name)} < Formula
url "foo"
version "0.1"
depends_on "#{dep_name}"
end
RUBY
Formulary.cache.delete(dep_path)
f = Formulary.factory(dep_name)
fi = described_class.new(f)
expect do
fi.check_install_sanity
end.to raise_error(CannotInstallFormulaError)
end
it "raises on indirect cyclic dependency" do
ENV["HOMEBREW_DEVELOPER"] = "1"
formula1_name = "homebrew-test-formula1"
formula2_name = "homebrew-test-formula2"
formula1_path = CoreTap.instance.new_formula_path(formula1_name)
formula1_path.write <<~RUBY
class #{Formulary.class_s(formula1_name)} < Formula
url "foo"
version "0.1"
depends_on "#{formula2_name}"
end
RUBY
Formulary.cache.delete(formula1_path)
formula1 = Formulary.factory(formula1_name)
formula2_path = CoreTap.instance.new_formula_path(formula2_name)
formula2_path.write <<~RUBY
class #{Formulary.class_s(formula2_name)} < Formula
url "foo"
version "0.1"
depends_on "#{formula1_name}"
end
RUBY
Formulary.cache.delete(formula2_path)
fi = described_class.new(formula1)
expect do
fi.check_install_sanity
end.to raise_error(CannotInstallFormulaError)
end
it "raises on pinned dependency" do
dep_name = "homebrew-test-dependency"
dep_path = CoreTap.instance.new_formula_path(dep_name)
dep_path.write <<~RUBY
class #{Formulary.class_s(dep_name)} < Formula
url "foo"
version "0.2"
end
RUBY
Formulary.cache.delete(dep_path)
dependency = Formulary.factory(dep_name)
dependent = formula do
url "foo"
version "0.5"
depends_on dependency.name.to_s
end
(dependency.prefix("0.1")/"bin"/"a").mkpath
HOMEBREW_PINNED_KEGS.mkpath
FileUtils.ln_s dependency.prefix("0.1"), HOMEBREW_PINNED_KEGS/dep_name
dependency_keg = Keg.new(dependency.prefix("0.1"))
dependency_keg.link
expect(dependency_keg).to be_linked
expect(dependency).to be_pinned
fi = described_class.new(dependent)
expect do
fi.check_install_sanity
end.to raise_error(CannotInstallFormulaError)
end
end
describe "#forbidden_license_check" do
it "raises on forbidden license on formula" do
ENV["HOMEBREW_FORBIDDEN_LICENSES"] = "AGPL-3.0"
f_name = "homebrew-forbidden-license"
f_path = CoreTap.instance.new_formula_path(f_name)
f_path.write <<~RUBY
class #{Formulary.class_s(f_name)} < Formula
url "foo"
version "0.1"
license "AGPL-3.0"
end
RUBY
Formulary.cache.delete(f_path)
f = Formulary.factory(f_name)
fi = described_class.new(f)
expect do
fi.forbidden_license_check
end.to raise_error(CannotInstallFormulaError, /#{f_name}'s licenses are all forbidden/)
end
it "raises on forbidden license on formula with contact instructions" do
ENV["HOMEBREW_FORBIDDEN_LICENSES"] = "AGPL-3.0"
ENV["HOMEBREW_FORBIDDEN_OWNER"] = owner = "your dog"
ENV["HOMEBREW_FORBIDDEN_OWNER_CONTACT"] = contact = "Woof loudly to get this unblocked."
f_name = "homebrew-forbidden-license"
f_path = CoreTap.instance.new_formula_path(f_name)
f_path.write <<~RUBY
class #{Formulary.class_s(f_name)} < Formula
url "foo"
version "0.1"
license "AGPL-3.0"
end
RUBY
Formulary.cache.delete(f_path)
f = Formulary.factory(f_name)
fi = described_class.new(f)
expect do
fi.forbidden_license_check
end.to raise_error(CannotInstallFormulaError, /#{owner}.+\n#{contact}/m)
end
it "raises on forbidden license on dependency" do
ENV["HOMEBREW_FORBIDDEN_LICENSES"] = "GPL-3.0"
dep_name = "homebrew-forbidden-dependency-license"
dep_path = CoreTap.instance.new_formula_path(dep_name)
dep_path.write <<~RUBY
class #{Formulary.class_s(dep_name)} < Formula
url "foo"
version "0.1"
license "GPL-3.0"
end
RUBY
Formulary.cache.delete(dep_path)
f_name = "homebrew-forbidden-dependent-license"
f_path = CoreTap.instance.new_formula_path(f_name)
f_path.write <<~RUBY
class #{Formulary.class_s(f_name)} < Formula
url "foo"
version "0.1"
depends_on "#{dep_name}"
end
RUBY
Formulary.cache.delete(f_path)
f = Formulary.factory(f_name)
fi = described_class.new(f)
expect do
fi.forbidden_license_check
end.to raise_error(CannotInstallFormulaError, /dependency on #{dep_name} where all/)
end
it "raises on forbidden symbol license on formula" do
ENV["HOMEBREW_FORBIDDEN_LICENSES"] = "public_domain"
f_name = "homebrew-forbidden-license"
f_path = CoreTap.instance.new_formula_path(f_name)
f_path.write <<~RUBY
class #{Formulary.class_s(f_name)} < Formula
url "foo"
version "0.1"
license :public_domain
end
RUBY
Formulary.cache.delete(f_path)
f = Formulary.factory(f_name)
fi = described_class.new(f)
expect do
fi.forbidden_license_check
end.to raise_error(CannotInstallFormulaError, /#{f_name}'s licenses are all forbidden/)
end
end
describe "#forbidden_tap_check" do
before do
allow(Tap).to receive_messages(allowed_taps: allowed_taps_set, forbidden_taps: forbidden_taps_set)
end
let(:homebrew_forbidden) { Tap.fetch("homebrew/forbidden") }
let(:allowed_third_party) { Tap.fetch("nothomebrew/allowed") }
let(:disallowed_third_party) { Tap.fetch("nothomebrew/notallowed") }
let(:allowed_taps_set) { Set.new([allowed_third_party]) }
let(:forbidden_taps_set) { Set.new([homebrew_forbidden]) }
it "raises on forbidden tap on formula" do
f_tap = homebrew_forbidden
f_name = "homebrew-forbidden-tap"
f_path = homebrew_forbidden.new_formula_path(f_name)
f_path.parent.mkpath
f_path.write <<~RUBY
class #{Formulary.class_s(f_name)} < Formula
url "foo"
version "0.1"
end
RUBY
Formulary.cache.delete(f_path)
f = Formulary.factory("#{f_tap}/#{f_name}")
fi = described_class.new(f)
expect do
fi.forbidden_tap_check
end.to raise_error(CannotInstallFormulaError, /has the tap #{f_tap}/)
ensure
FileUtils.rm_r(f_path.parent.parent)
end
it "raises on not allowed third-party tap on formula" do
f_tap = disallowed_third_party
f_name = "homebrew-not-allowed-tap"
f_path = disallowed_third_party.new_formula_path(f_name)
f_path.parent.mkpath
f_path.write <<~RUBY
class #{Formulary.class_s(f_name)} < Formula
url "foo"
version "0.1"
end
RUBY
Formulary.cache.delete(f_path)
f = Formulary.factory("#{f_tap}/#{f_name}")
fi = described_class.new(f)
expect do
fi.forbidden_tap_check
end.to raise_error(CannotInstallFormulaError, /has the tap #{f_tap}/)
ensure
FileUtils.rm_r(f_path.parent.parent.parent)
end
it "does not raise on allowed tap on formula" do
f_tap = allowed_third_party
f_name = "homebrew-allowed-tap"
f_path = allowed_third_party.new_formula_path(f_name)
f_path.parent.mkpath
f_path.write <<~RUBY
class #{Formulary.class_s(f_name)} < Formula
url "foo"
version "0.1"
end
RUBY
Formulary.cache.delete(f_path)
f = Formulary.factory("#{f_tap}/#{f_name}")
fi = described_class.new(f)
expect { fi.forbidden_tap_check }.not_to raise_error
ensure
FileUtils.rm_r(f_path.parent.parent.parent)
end
it "raises on forbidden tap on dependency" do
dep_tap = homebrew_forbidden
dep_name = "homebrew-forbidden-dependency-tap"
dep_path = homebrew_forbidden.new_formula_path(dep_name)
dep_path.parent.mkpath
dep_path.write <<~RUBY
class #{Formulary.class_s(dep_name)} < Formula
url "foo"
version "0.1"
end
RUBY
Formulary.cache.delete(dep_path)
f_name = "homebrew-forbidden-dependent-tap"
f_path = CoreTap.instance.new_formula_path(f_name)
f_path.write <<~RUBY
class #{Formulary.class_s(f_name)} < Formula
url "foo"
version "0.1"
depends_on "#{dep_name}"
end
RUBY
Formulary.cache.delete(f_path)
f = Formulary.factory(f_name)
fi = described_class.new(f)
expect do
fi.forbidden_tap_check
end.to raise_error(CannotInstallFormulaError, /from the #{dep_tap} tap but/)
ensure
FileUtils.rm_r(dep_path.parent.parent)
end
end
describe "#forbidden_formula_check" do
it "raises on forbidden formula" do
ENV["HOMEBREW_FORBIDDEN_FORMULAE"] = f_name = "homebrew-forbidden-formula"
f_path = CoreTap.instance.new_formula_path(f_name)
f_path.write <<~RUBY
class #{Formulary.class_s(f_name)} < Formula
url "foo"
version "0.1"
end
RUBY
Formulary.cache.delete(f_path)
f = Formulary.factory(f_name)
fi = described_class.new(f)
expect do
fi.forbidden_formula_check
end.to raise_error(CannotInstallFormulaError, /#{f_name} was forbidden/)
end
it "raises on forbidden dependency" do
ENV["HOMEBREW_FORBIDDEN_FORMULAE"] = dep_name = "homebrew-forbidden-dependency-formula"
dep_path = CoreTap.instance.new_formula_path(dep_name)
dep_path.write <<~RUBY
class #{Formulary.class_s(dep_name)} < Formula
url "foo"
version "0.1"
end
RUBY
Formulary.cache.delete(dep_path)
f_name = "homebrew-forbidden-dependent-formula"
f_path = CoreTap.instance.new_formula_path(f_name)
f_path.write <<~RUBY
class #{Formulary.class_s(f_name)} < Formula
url "foo"
version "0.1"
depends_on "#{dep_name}"
end
RUBY
Formulary.cache.delete(f_path)
f = Formulary.factory(f_name)
fi = described_class.new(f)
expect do
fi.forbidden_formula_check
end.to raise_error(CannotInstallFormulaError, /#{dep_name} formula was forbidden/)
end
end
specify "install fails with BuildError when a system() call fails" do
ENV["HOMEBREW_TEST_NO_EXIT_CLEANUP"] = "1"
ENV["FAILBALL_BUILD_ERROR"] = "1"
expect do
temporary_install(Failball.new)
end.to raise_error(BuildError)
end
specify "install fails with a RuntimeError when #install raises" do
ENV["HOMEBREW_TEST_NO_EXIT_CLEANUP"] = "1"
expect do
temporary_install(Failball.new)
end.to raise_error(RuntimeError)
end
describe "#caveats" do
subject(:formula_installer) { described_class.new(Testball.new) }
it "shows audit problems if HOMEBREW_DEVELOPER is set" do
ENV["HOMEBREW_DEVELOPER"] = "1"
formula_installer.fetch
formula_installer.install
expect(formula_installer).to receive(:audit_installed).and_call_original
formula_installer.caveats
end
end
describe "#install_service" do
it "works if service is set" do
formula = Testball.new
service = Homebrew::Service.new(formula)
launchd_service_path = formula.launchd_service_path
service_path = formula.systemd_service_path
formula.opt_prefix.mkpath
expect(formula).to receive(:service?).and_return(true)
expect(formula).to receive(:service).at_least(:once).and_return(service)
expect(formula).to receive(:launchd_service_path).and_call_original
expect(formula).to receive(:systemd_service_path).and_call_original
expect(service).to receive(:timed?).and_return(false)
expect(service).to receive(:command?).and_return(true)
expect(service).to receive(:to_plist).and_return("plist")
expect(service).to receive(:to_systemd_unit).and_return("unit")
installer = described_class.new(formula)
expect do
installer.install_service
end.not_to output(/Error: Failed to install service files/).to_stderr
expect(launchd_service_path).to exist
expect(service_path).to exist
end
it "works if timed service is set" do
formula = Testball.new
service = Homebrew::Service.new(formula)
launchd_service_path = formula.launchd_service_path
service_path = formula.systemd_service_path
timer_path = formula.systemd_timer_path
formula.opt_prefix.mkpath
expect(formula).to receive(:service?).and_return(true)
expect(formula).to receive(:service).at_least(:once).and_return(service)
expect(formula).to receive(:launchd_service_path).and_call_original
expect(formula).to receive(:systemd_service_path).and_call_original
expect(formula).to receive(:systemd_timer_path).and_call_original
expect(service).to receive(:timed?).and_return(true)
expect(service).to receive(:command?).and_return(true)
expect(service).to receive(:to_plist).and_return("plist")
expect(service).to receive(:to_systemd_unit).and_return("unit")
expect(service).to receive(:to_systemd_timer).and_return("timer")
installer = described_class.new(formula)
expect do
installer.install_service
end.not_to output(/Error: Failed to install service files/).to_stderr
expect(launchd_service_path).to exist
expect(service_path).to exist
expect(timer_path).to exist
end
it "returns without definition" do
formula = Testball.new
path = formula.launchd_service_path
formula.opt_prefix.mkpath
expect(formula).to receive(:service?).and_return(nil)
expect(formula).not_to receive(:launchd_service_path)
installer = described_class.new(formula)
expect do
installer.install_service
end.not_to output(/Error: Failed to install service files/).to_stderr
expect(path).not_to exist
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/lazy_object_spec.rb | Library/Homebrew/test/lazy_object_spec.rb | # frozen_string_literal: true
require "lazy_object"
RSpec.describe LazyObject do
describe "#initialize" do
it "does not evaluate the block" do
expect do |block|
described_class.new(&block)
end.not_to yield_control
end
end
describe "when receiving a message" do
it "evaluates the block" do
expect(described_class.new { 42 }.to_s).to eq "42"
end
end
describe "#!" do
it "delegates to the underlying object" do
expect(!described_class.new { false }).to be true
end
end
describe "#!=" do
it "delegates to the underlying object" do
expect(described_class.new { 42 }).not_to eq 13
end
end
describe "#==" do
it "delegates to the underlying object" do
expect(described_class.new { 42 }).to eq 42
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/descriptions_spec.rb | Library/Homebrew/test/descriptions_spec.rb | # frozen_string_literal: true
require "descriptions"
RSpec.describe Descriptions do
subject(:descriptions) { described_class.new(descriptions_hash) }
let(:descriptions_hash) { {} }
it "can print description for a core Formula" do
descriptions_hash["homebrew/core/foo"] = "Core foo"
expect { descriptions.print }.to output("foo: Core foo\n").to_stdout
end
it "can print description for an external Formula" do
descriptions_hash["somedev/external/foo"] = "External foo"
expect { descriptions.print }.to output("foo: External foo\n").to_stdout
end
it "can print descriptions for duplicate Formulae" do
descriptions_hash["homebrew/core/foo"] = "Core foo"
descriptions_hash["somedev/external/foo"] = "External foo"
expect { descriptions.print }.to output(
<<~EOS,
homebrew/core/foo: Core foo
somedev/external/foo: External foo
EOS
).to_stdout
end
it "can print descriptions for duplicate core and external Formulae" do
descriptions_hash["homebrew/core/foo"] = "Core foo"
descriptions_hash["somedev/external/foo"] = "External foo"
descriptions_hash["otherdev/external/foo"] = "Other external foo"
expect { descriptions.print }.to output(
<<~EOS,
homebrew/core/foo: Core foo
otherdev/external/foo: Other external foo
somedev/external/foo: External foo
EOS
).to_stdout
end
it "can print description for a cask" do
descriptions_hash["homebrew/cask/foo"] = ["Foo", "Cask foo"]
expect { descriptions.print }.to output("foo: (Foo) Cask foo\n").to_stdout
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/bash_spec.rb | Library/Homebrew/test/bash_spec.rb | # frozen_string_literal: true
require "open3"
RSpec.describe "Bash" do
matcher :have_valid_bash_syntax do
match do |file|
stdout, stderr, status = Open3.capture3("/bin/bash", "-n", file)
@actual = [file, stderr]
stdout.empty? && status.success?
end
failure_message do |(file, stderr)|
"expected that #{file} is a valid Bash file:\n#{stderr}"
end
end
describe "brew" do
subject { HOMEBREW_LIBRARY_PATH.parent.parent/"bin/brew" }
it { is_expected.to have_valid_bash_syntax }
end
describe "every `.sh` file" do
it "has valid Bash syntax" do
Pathname.glob("#{HOMEBREW_LIBRARY_PATH}/**/*.sh").each do |path|
relative_path = path.relative_path_from(HOMEBREW_LIBRARY_PATH)
next if relative_path.to_s.start_with?("shims/", "test/", "vendor/")
expect(path).to have_valid_bash_syntax
end
end
end
describe "Bash completion" do
subject { HOMEBREW_LIBRARY_PATH.parent.parent/"completions/bash/brew" }
it { is_expected.to have_valid_bash_syntax }
end
describe "every shim script" do
it "has valid Bash syntax" do
# These have no file extension, but can be identified by their shebang.
(HOMEBREW_LIBRARY_PATH/"shims").find do |path|
next if path.directory?
next if path.symlink?
next unless path.executable?
next if path.basename.to_s == "cc" # `bash -n` tries to parse the Ruby part
next if path.read(12) != "#!/bin/bash\n"
expect(path).to have_valid_bash_syntax
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/unpack_strategy_spec.rb | Library/Homebrew/test/unpack_strategy_spec.rb | # frozen_string_literal: true
RSpec.describe UnpackStrategy do
describe "#extract_nestedly" do
subject(:strategy) { described_class.detect(path) }
let(:unpack_dir) { mktmpdir }
context "when extracting a GZIP nested in a BZIP2" do
let(:file_name) { "file" }
let(:path) do
dir = mktmpdir
(dir/"file").write "This file was inside a GZIP inside a BZIP2."
system "gzip", dir.children.first
system "bzip2", dir.children.first
dir.children.first
end
it "can extract nested archives" do
strategy.extract_nestedly(to: unpack_dir)
expect(File.read(unpack_dir/file_name)).to eq("This file was inside a GZIP inside a BZIP2.")
end
end
context "when extracting a directory with nested directories" do
let(:directories) { "A/B/C" }
let(:executable) { "#{directories}/executable" }
let(:writable) { true }
let(:path) do
(mktmpdir/"file.tar").tap do |path|
Dir.mktmpdir do |dir|
dir = Pathname(dir)
(dir/directories).mkpath
FileUtils.touch dir/executable
FileUtils.chmod 0555, dir/executable
FileUtils.chmod "-w", dir/directories unless writable
begin
system "tar", "--create", "--file", path, "--directory", dir, "A/"
ensure
FileUtils.chmod "+w", dir/directories unless writable
end
end
end
end
it "does not recurse into nested directories" do
strategy.extract_nestedly(to: unpack_dir)
expect(Pathname.glob(unpack_dir/"**/*")).to include unpack_dir/directories
end
context "which are not writable" do
let(:writable) { false }
it "makes them writable but not world-writable" do
strategy.extract_nestedly(to: unpack_dir)
expect(unpack_dir/directories).to be_writable
expect(unpack_dir/directories).not_to be_world_writable
end
it "does not make other files writable" do
strategy.extract_nestedly(to: unpack_dir)
# We don't check `writable?` here as that's always true as root.
expect((unpack_dir/executable).stat.mode & 0222).to be_zero
end
end
end
context "when extracting a nested archive" do
let(:basename) { "file.xyz" }
let(:path) do
(mktmpdir/basename).tap do |path|
mktmpdir do |dir|
FileUtils.touch dir/"file.txt"
system "tar", "--create", "--file", path, "--directory", dir, "file.txt"
end
end
end
it "does not pass down the basename of the archive" do
strategy.extract_nestedly(to: unpack_dir, basename:)
expect(unpack_dir/"file.txt").to be_a_file
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/PATH_spec.rb | Library/Homebrew/test/PATH_spec.rb | # frozen_string_literal: true
require "PATH"
RSpec.describe PATH do
describe "#initialize" do
it "can take multiple arguments" do
expect(described_class.new("/path1", "/path2")).to eq("/path1:/path2")
end
it "can parse a mix of arrays and arguments" do
expect(described_class.new(["/path1", "/path2"], "/path3")).to eq("/path1:/path2:/path3")
end
it "splits an existing PATH" do
expect(described_class.new("/path1:/path2")).to eq(["/path1", "/path2"])
end
it "removes duplicates" do
expect(described_class.new("/path1", "/path1")).to eq("/path1")
end
end
describe "#to_ary" do
it "returns a PATH array" do
expect(described_class.new("/path1", "/path2").to_ary).to eq(["/path1", "/path2"])
end
it "does not allow mutating the original" do
path = described_class.new("/path1", "/path2")
path.to_ary << "/path3"
expect(path).not_to include("/path3")
end
end
describe "#to_str" do
it "returns a PATH string" do
expect(described_class.new("/path1", "/path2").to_str).to eq("/path1:/path2")
end
end
describe "#prepend" do
specify(:aggregate_failures) do
expect(described_class.new("/path1").prepend("/path2").to_str).to eq("/path2:/path1")
expect(described_class.new("/path1").prepend("/path1").to_str).to eq("/path1")
end
end
describe "#append" do
specify(:aggregate_failures) do
expect(described_class.new("/path1").append("/path2").to_str).to eq("/path1:/path2")
expect(described_class.new("/path1").append("/path1").to_str).to eq("/path1")
end
end
describe "#insert" do
specify(:aggregate_failures) do
expect(described_class.new("/path1").insert(0, "/path2").to_str).to eq("/path2:/path1")
expect(described_class.new("/path1").insert(0, "/path2", "/path3")).to eq("/path2:/path3:/path1")
end
end
describe "#==" do
it "always returns false when comparing against something which does not respond to `#to_ary` or `#to_str`" do
expect(described_class.new).not_to eq Object.new
end
end
describe "#include?" do
it "returns true if a path is included", :aggregate_failures do
path = described_class.new("/path1", "/path2")
expect(path).to include("/path1")
expect(path).to include("/path2")
expect(described_class.new("/path1", "/path2")).not_to include("/path1:")
end
it "returns false if a path is not included" do
expect(described_class.new("/path1")).not_to include("/path2")
end
end
describe "#each" do
it "loops through each path" do
enum = described_class.new("/path1", "/path2").each
expect(enum.next).to eq("/path1")
expect(enum.next).to eq("/path2")
end
end
describe "#select" do
it "returns an object of the same class instead of an Array" do
expect(described_class.new.select { true }).to be_a(described_class)
end
end
describe "#reject" do
it "returns an object of the same class instead of an Array" do
expect(described_class.new.reject { true }).to be_a(described_class)
end
end
describe "#existing" do
it "returns a new PATH without non-existent paths", :aggregate_failures do
allow(File).to receive(:directory?).with("/path1").and_return(true)
allow(File).to receive(:directory?).with("/path2").and_return(false)
path = described_class.new("/path1", "/path2")
expect(path.existing.to_ary).to eq(["/path1"])
expect(path.to_ary).to eq(["/path1", "/path2"])
end
it "returns nil instead of an empty #{described_class}" do
expect(described_class.new.existing).to be_nil
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/cache_store_spec.rb | Library/Homebrew/test/cache_store_spec.rb | # frozen_string_literal: true
require "cache_store"
RSpec.describe CacheStoreDatabase do
subject(:sample_db) { described_class.new(:sample) }
describe "self.use" do
let(:type) { :test }
it "creates a new `DatabaseCache` instance" do
cache_store = instance_double(described_class, "cache_store", write_if_dirty!: nil)
expect(described_class).to receive(:new).with(type).and_return(cache_store)
expect(cache_store).to receive(:write_if_dirty!)
described_class.use(type) do |_db|
# do nothing
end
end
end
describe "#set" do
let(:db) { instance_double(Hash, "db", :[]= => nil) }
it "sets the value in the `CacheStoreDatabase`" do
allow(File).to receive(:write)
allow(sample_db).to receive_messages(created?: true, db:)
expect(db).to receive(:has_key?).with(:foo).and_return(false)
expect(db).not_to have_key(:foo)
sample_db.set(:foo, "bar")
end
end
describe "#get" do
context "with a database created" do
let(:db) { instance_double(Hash, "db", :[] => "bar") }
it "gets value in the `CacheStoreDatabase` corresponding to the key" do
expect(db).to receive(:has_key?).with(:foo).and_return(true)
allow(sample_db).to receive_messages(created?: true, db:)
expect(db).to have_key(:foo)
expect(sample_db.get(:foo)).to eq("bar")
end
end
context "without a database created" do
let(:db) { instance_double(Hash, "db", :[] => nil) }
before do
allow(sample_db).to receive_messages(created?: false, db:)
end
it "does not get value in the `CacheStoreDatabase` corresponding to key" do
expect(sample_db.get(:foo)).not_to be("bar")
end
it "does not call `db[]` if `CacheStoreDatabase.created?` is `false`" do
expect(db).not_to receive(:[])
sample_db.get(:foo)
end
end
end
describe "#delete" do
context "with a database created" do
let(:db) { instance_double(Hash, "db", :[] => { foo: "bar" }) }
before do
allow(sample_db).to receive_messages(created?: true, db:)
end
it "deletes value in the `CacheStoreDatabase` corresponding to the key" do
expect(db).to receive(:delete).with(:foo)
sample_db.delete(:foo)
end
end
context "without a database created" do
let(:db) { instance_double(Hash, "db", delete: nil) }
before do
allow(sample_db).to receive_messages(created?: false, db:)
end
it "does not call `db.delete` if `CacheStoreDatabase.created?` is `false`" do
expect(db).not_to receive(:delete)
sample_db.delete(:foo)
end
end
end
describe "#write_if_dirty!" do
context "with an open database" do
it "does not raise an error when `close` is called on the database" do
expect { sample_db.write_if_dirty! }.not_to raise_error
end
end
context "without an open database" do
before do
sample_db.instance_variable_set(:@db, nil)
end
it "does not raise an error when `close` is called on the database" do
expect { sample_db.write_if_dirty! }.not_to raise_error
end
end
end
describe "#created?" do
let(:cache_path) { Pathname("path/to/homebrew/cache/sample.json") }
before do
allow(sample_db).to receive(:cache_path).and_return(cache_path)
end
context "when `cache_path.exist?` returns `true`" do
before do
allow(cache_path).to receive(:exist?).and_return(true)
end
it "returns `true`" do
expect(sample_db.created?).to be(true)
end
end
context "when `cache_path.exist?` returns `false`" do
before do
allow(cache_path).to receive(:exist?).and_return(false)
end
it "returns `false`" do
expect(sample_db.created?).to be(false)
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/env_config_spec.rb | Library/Homebrew/test/env_config_spec.rb | # frozen_string_literal: true
require "diagnostic"
RSpec.describe Homebrew::EnvConfig do
subject(:env_config) { described_class }
describe "ENVS" do
it "sorts alphabetically" do
expect(env_config::ENVS.keys).to eql(env_config::ENVS.keys.sort)
end
end
describe ".env_method_name" do
it "generates method names" do
expect(env_config.env_method_name("HOMEBREW_FOO", {})).to eql("foo")
end
it "generates boolean method names" do
expect(env_config.env_method_name("HOMEBREW_BAR", boolean: true)).to eql("bar?")
end
end
describe ".artifact_domain" do
it "returns value if set" do
ENV["HOMEBREW_ARTIFACT_DOMAIN"] = "https://brew.sh"
expect(env_config.artifact_domain).to eql("https://brew.sh")
end
it "returns nil if empty" do
ENV["HOMEBREW_ARTIFACT_DOMAIN"] = ""
expect(env_config.artifact_domain).to be_nil
end
end
describe ".cleanup_periodic_full_days" do
it "returns value if set" do
ENV["HOMEBREW_CLEANUP_PERIODIC_FULL_DAYS"] = "360"
expect(env_config.cleanup_periodic_full_days).to eql("360")
end
it "returns default if unset" do
ENV["HOMEBREW_CLEANUP_PERIODIC_FULL_DAYS"] = nil
expect(env_config.cleanup_periodic_full_days).to eql("30")
end
end
describe ".bat?" do
it "returns true if set" do
ENV["HOMEBREW_BAT"] = "1"
expect(env_config.bat?).to be(true)
end
it "returns false if unset" do
ENV["HOMEBREW_BAT"] = nil
expect(env_config.bat?).to be(false)
end
end
describe ".make_jobs" do
it "returns value if positive" do
ENV["HOMEBREW_MAKE_JOBS"] = "4"
expect(env_config.make_jobs).to eql("4")
end
it "returns default if negative" do
ENV["HOMEBREW_MAKE_JOBS"] = "-1"
expect(Hardware::CPU).to receive(:cores).and_return(16)
expect(env_config.make_jobs).to eql("16")
end
end
describe ".forbid_packages_from_paths?" do
before do
ENV["HOMEBREW_FORBID_PACKAGES_FROM_PATHS"] = nil
ENV["HOMEBREW_DEVELOPER"] = nil
ENV["HOMEBREW_TESTS"] = nil
end
it "returns true if HOMEBREW_FORBID_PACKAGES_FROM_PATHS is set" do
ENV["HOMEBREW_FORBID_PACKAGES_FROM_PATHS"] = "1"
expect(env_config.forbid_packages_from_paths?).to be(true)
end
it "returns true if HOMEBREW_DEVELOPER is not set" do
ENV["HOMEBREW_DEVELOPER"] = nil
expect(env_config.forbid_packages_from_paths?).to be(true)
end
it "returns false if HOMEBREW_DEVELOPER is set and HOMEBREW_FORBID_PACKAGES_FROM_PATHS is not set" do
ENV["HOMEBREW_DEVELOPER"] = "1"
ENV["HOMEBREW_FORBID_PACKAGES_FROM_PATHS"] = nil
expect(env_config.forbid_packages_from_paths?).to be(false)
end
it "returns true if both HOMEBREW_DEVELOPER and HOMEBREW_FORBID_PACKAGES_FROM_PATHS are set" do
ENV["HOMEBREW_DEVELOPER"] = "1"
ENV["HOMEBREW_FORBID_PACKAGES_FROM_PATHS"] = "1"
expect(env_config.forbid_packages_from_paths?).to be(true)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/pkg_version_spec.rb | Library/Homebrew/test/pkg_version_spec.rb | # frozen_string_literal: true
require "pkg_version"
RSpec.describe PkgVersion do
describe "::parse" do
it "parses versions from a string" do
expect(described_class.parse("1.0_1")).to eq(described_class.new(Version.new("1.0"), 1))
expect(described_class.parse("1.0_1")).to eq(described_class.new(Version.new("1.0"), 1))
expect(described_class.parse("1.0")).to eq(described_class.new(Version.new("1.0"), 0))
expect(described_class.parse("1.0_0")).to eq(described_class.new(Version.new("1.0"), 0))
expect(described_class.parse("2.1.4_0")).to eq(described_class.new(Version.new("2.1.4"), 0))
expect(described_class.parse("1.0.1e_1")).to eq(described_class.new(Version.new("1.0.1e"), 1))
end
end
specify "#==" do
expect(described_class.parse("1.0_0")).to eq described_class.parse("1.0")
version_to_compare = described_class.parse("1.0_1")
expect(version_to_compare == described_class.parse("1.0_1")).to be true
expect(version_to_compare == described_class.parse("1.0_2")).to be false
end
describe "#>" do
it "returns true if the left version is bigger than the right" do
expect(described_class.parse("1.1")).to be > described_class.parse("1.0_1")
end
it "returns true if the left version is HEAD" do
expect(described_class.parse("HEAD")).to be > described_class.parse("1.0")
end
it "raises an error if the other side isn't of the same class" do
expect do
described_class.new(Version.new("1.0"), 0) > Object.new
end.to raise_error(TypeError)
end
it "is not compatible with Version" do
expect do
described_class.new(Version.new("1.0"), 0) > Version.new("1.0")
end.to raise_error(TypeError)
end
end
describe "#<" do
it "returns true if the left version is smaller than the right" do
expect(described_class.parse("1.0_1")).to be < described_class.parse("2.0_1")
end
it "returns true if the right version is HEAD" do
expect(described_class.parse("1.0")).to be < described_class.parse("HEAD")
end
end
describe "#<=>" do
it "returns nil if the comparison fails" do
expect(Object.new <=> described_class.new(Version.new("1.0"), 0)).to be_nil
end
end
describe "#to_s" do
it "returns a string of the form 'version_revision'" do
expect(described_class.new(Version.new("1.0"), 0).to_s).to eq("1.0")
expect(described_class.new(Version.new("1.0"), 1).to_s).to eq("1.0_1")
expect(described_class.new(Version.new("1.0"), 0).to_s).to eq("1.0")
expect(described_class.new(Version.new("1.0"), 0).to_s).to eq("1.0")
expect(described_class.new(Version.new("HEAD"), 1).to_s).to eq("HEAD_1")
expect(described_class.new(Version.new("HEAD-ffffff"), 1).to_s).to eq("HEAD-ffffff_1")
end
end
describe "#hash" do
let(:version_one_revision_one) { described_class.new(Version.new("1.0"), 1) }
let(:version_one_dot_one_revision_one) { described_class.new(Version.new("1.1"), 1) }
let(:version_one_revision_zero) { described_class.new(Version.new("1.0"), 0) }
it "returns a hash based on the version and revision" do
expect(version_one_revision_one.hash).to eq(described_class.new(Version.new("1.0"), 1).hash)
expect(version_one_revision_one.hash).not_to eq(version_one_dot_one_revision_one.hash)
expect(version_one_revision_one.hash).not_to eq(version_one_revision_zero.hash)
end
end
describe "#version" do
it "returns package version" do
expect(described_class.parse("1.2.3_4").version).to eq Version.new("1.2.3")
end
end
describe "#revision" do
it "returns package revision" do
expect(described_class.parse("1.2.3_4").revision).to eq 4
end
end
describe "#major" do
it "returns major version token" do
expect(described_class.parse("1.2.3_4").major).to eq Version::Token.create("1")
end
end
describe "#minor" do
it "returns minor version token" do
expect(described_class.parse("1.2.3_4").minor).to eq Version::Token.create("2")
end
end
describe "#patch" do
it "returns patch version token" do
expect(described_class.parse("1.2.3_4").patch).to eq Version::Token.create("3")
end
end
describe "#major_minor" do
it "returns major.minor version" do
expect(described_class.parse("1.2.3_4").major_minor).to eq Version.new("1.2")
end
end
describe "#major_minor_patch" do
it "returns major.minor.patch version" do
expect(described_class.parse("1.2.3_4").major_minor_patch).to eq Version.new("1.2.3")
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/uninstall_spec.rb | Library/Homebrew/test/uninstall_spec.rb | # frozen_string_literal: true
require "uninstall"
RSpec.describe Homebrew::Uninstall do
let(:dependency) { formula("dependency") { url "f-1" } }
let(:dependent_formula) do
formula("dependent_formula") do
url "f-1"
depends_on "dependency"
end
end
let(:dependent_cask) do
Cask::CaskLoader.load(+<<-RUBY)
cask "dependent_cask" do
version "1.0.0"
url "c-1"
depends_on formula: "dependency"
end
RUBY
end
let(:kegs_by_rack) { { dependency.rack => [Keg.new(dependency.latest_installed_prefix)] } }
before do
[dependency, dependent_formula].each do |f|
f.latest_installed_prefix.mkpath
Keg.new(f.latest_installed_prefix).optlink
end
tab = Tab.empty
tab.homebrew_version = "1.1.6"
tab.tabfile = dependent_formula.latest_installed_prefix/AbstractTab::FILENAME
tab.runtime_dependencies = [
{ "full_name" => "dependency", "version" => "1" },
]
tab.write
Cask::Caskroom.path.join("dependent_cask", dependent_cask.version).mkpath
stub_formula_loader dependency
stub_formula_loader dependent_formula
stub_cask_loader dependent_cask
end
describe "::handle_unsatisfied_dependents" do
specify "when `ignore_dependencies` is false" do
expect do
described_class.handle_unsatisfied_dependents(kegs_by_rack)
end.to output(/Error/).to_stderr
expect(Homebrew).to have_failed
end
specify "when `ignore_dependencies` is true" do
expect do
described_class.handle_unsatisfied_dependents(kegs_by_rack, ignore_dependencies: true)
end.not_to output.to_stderr
expect(Homebrew).not_to have_failed
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/system_command_result_spec.rb | Library/Homebrew/test/system_command_result_spec.rb | # frozen_string_literal: true
require "system_command"
RSpec.describe SystemCommand::Result do
RSpec::Matchers.alias_matcher :a_string_containing, :include
subject(:result) do
described_class.new([], output_array, instance_double(Process::Status, exitstatus: 0, success?: true),
secrets: [])
end
let(:output_array) do
[
[:stdout, "output\n"],
[:stderr, "error\n"],
]
end
describe "#to_ary" do
it "can be destructed like `Open3.capture3`" do
out, err, status = result
expect(out).to eq "output\n"
expect(err).to eq "error\n"
expect(status).to be_a_success
end
end
describe "#stdout" do
it "returns the standard output" do
expect(result.stdout).to eq "output\n"
end
end
describe "#stderr" do
it "returns the standard error output" do
expect(result.stderr).to eq "error\n"
end
end
describe "#merged_output" do
it "returns the combined standard and standard error output" do
expect(result.merged_output).to eq "output\nerror\n"
end
end
describe "#plist" do
subject(:result_plist) { result.plist }
let(:output_array) { [[:stdout, stdout]] }
let(:garbage) do
<<~EOS
Hello there! I am in no way XML am I?!?!
That's a little silly... you were expecting XML here!
What is a parser to do?
Hopefully <not> explode!
EOS
end
let(:plist) do
<<~XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>system-entities</key>
<array>
<dict>
<key>content-hint</key>
<string>Apple_partition_map</string>
<key>dev-entry</key>
<string>/dev/disk3s1</string>
<key>potentially-mountable</key>
<false/>
<key>unmapped-content-hint</key>
<string>Apple_partition_map</string>
</dict>
<dict>
<key>content-hint</key>
<string>Apple_partition_scheme</string>
<key>dev-entry</key>
<string>/dev/disk3</string>
<key>potentially-mountable</key>
<false/>
<key>unmapped-content-hint</key>
<string>Apple_partition_scheme</string>
</dict>
<dict>
<key>content-hint</key>
<string>Apple_HFS</string>
<key>dev-entry</key>
<string>/dev/disk3s2</string>
<key>mount-point</key>
<string>/private/tmp/dmg.BhfS2g</string>
<key>potentially-mountable</key>
<true/>
<key>unmapped-content-hint</key>
<string>Apple_HFS</string>
<key>volume-kind</key>
<string>hfs</string>
</dict>
</array>
</dict>
</plist>
XML
end
context "when stdout contains garbage before XML" do
let(:stdout) do
<<~EOS
#{garbage}
#{plist}
EOS
end
it "ignores garbage" do
expect(result_plist["system-entities"].length).to eq(3)
end
context "when verbose" do
before do
allow(Context).to receive(:current).and_return(Context::ContextStruct.new(verbose: true))
end
it "warns about garbage" do
expect { result_plist }
.to output(a_string_containing(garbage)).to_stderr
end
end
end
context "when stdout contains garbage after XML" do
let(:stdout) do
<<~EOS
#{plist}
#{garbage}
EOS
end
it "ignores garbage" do
expect(result_plist["system-entities"].length).to eq(3)
end
context "when verbose" do
before do
allow(Context).to receive(:current).and_return(Context::ContextStruct.new(verbose: true))
end
it "warns about garbage" do
expect { result_plist }
.to output(a_string_containing(garbage)).to_stderr
end
end
end
context "when there's a hdiutil stdout" do
let(:stdout) { plist }
it "successfully parses it" do
expect(result_plist.keys).to eq(["system-entities"])
expect(result_plist["system-entities"].length).to eq(3)
expect(result_plist["system-entities"].map { |e| e["dev-entry"] })
.to eq(["/dev/disk3s1", "/dev/disk3", "/dev/disk3s2"])
end
end
context "when the stdout of the command is empty" do
let(:stdout) { "" }
it "returns nil" do
expect(result_plist).to be_nil
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/dependency_expansion_spec.rb | Library/Homebrew/test/dependency_expansion_spec.rb | # frozen_string_literal: true
require "dependency"
RSpec.describe Dependency do
def build_dep(name, tags = [], deps = [])
dep = described_class.new(name.to_s, tags)
allow(dep).to receive(:to_formula).and_return \
instance_double(Formula, deps:, name:, full_name: name)
dep
end
let(:foo) { build_dep(:foo) }
let(:bar) { build_dep(:bar) }
let(:baz) { build_dep(:baz) }
let(:qux) { build_dep(:qux) }
let(:deps) { [foo, bar, baz, qux] }
let(:formula) { instance_double(Formula, deps:, name: "f") }
describe "::expand" do
it "yields dependent and dependency pairs" do
i = 0
described_class.expand(formula) do |dependent, dep|
expect(dependent).to eq(formula)
expect(deps[i]).to eq(dep)
i += 1
end
end
it "returns the dependencies" do
expect(described_class.expand(formula)).to eq(deps)
end
it "prunes all when given a block with ::prune" do
expect(described_class.expand(formula) { described_class.prune }).to be_empty
end
it "can prune selectively" do
deps = described_class.expand(formula) do |_, dep|
described_class.prune if dep.name == "foo"
end
expect(deps).to eq([bar, baz, qux])
end
it "preserves dependency order" do
allow(foo).to receive(:to_formula).and_return \
instance_double(Formula, name: "foo", full_name: "foo", deps: [qux, baz])
expect(described_class.expand(formula)).to eq([qux, baz, foo, bar])
end
end
it "skips optionals by default" do
deps = [build_dep(:foo, [:optional]), bar, baz, qux]
f = instance_double(Formula, deps:, build: instance_double(BuildOptions, with?: false), name: "f")
expect(described_class.expand(f)).to eq([bar, baz, qux])
end
it "keeps recommended dependencies by default" do
deps = [build_dep(:foo, [:recommended]), bar, baz, qux]
f = instance_double(Formula, deps:, build: instance_double(BuildOptions, with?: true), name: "f")
expect(described_class.expand(f)).to eq(deps)
end
it "merges repeated dependencies with differing options" do
foo2 = build_dep(:foo, ["option"])
baz2 = build_dep(:baz, ["option"])
deps << foo2 << baz2
deps = [foo2, bar, baz2, qux]
deps.zip(described_class.expand(formula)) do |expected, actual|
expect(expected.tags).to eq(actual.tags)
expect(expected).to eq(actual)
end
end
it "merges tags without duplicating them" do
foo2 = build_dep(:foo, ["option"])
foo3 = build_dep(:foo, ["option"])
deps << foo2 << foo3
expect(described_class.expand(formula).first.tags).to eq(%w[option])
end
it "skips parent but yields children with ::skip" do
f = instance_double(
Formula,
name: "f",
deps: [
build_dep(:foo, [], [bar, baz]),
build_dep(:foo, [], [baz]),
],
)
deps = described_class.expand(f) do |_dependent, dep|
described_class.skip if %w[foo qux].include? dep.name
end
expect(deps).to eq([bar, baz])
end
it "keeps dependency but prunes recursive dependencies with ::keep_but_prune_recursive_deps" do
foo = build_dep(:foo, [:test], bar)
baz = build_dep(:baz, [:test])
f = instance_double(Formula, name: "f", deps: [foo, baz])
deps = described_class.expand(f) do |_dependent, dep|
described_class.keep_but_prune_recursive_deps if dep.test?
end
expect(deps).to eq([foo, baz])
end
it "returns only the dependencies given as a collection as second argument" do
expect(formula.deps).to eq([foo, bar, baz, qux])
expect(described_class.expand(formula, [bar, baz])).to eq([bar, baz])
end
it "doesn't raise an error when a dependency is cyclic" do
foo = build_dep(:foo)
bar = build_dep(:bar, [], [foo])
allow(foo).to receive(:to_formula).and_return \
instance_double(Formula, deps: [bar], name: foo.name, full_name: foo.name)
f = instance_double(Formula, name: "f", full_name: "f", deps: [foo, bar])
expect { described_class.expand(f) }.not_to raise_error
end
it "cleans the expand stack" do
foo = build_dep(:foo)
allow(foo).to receive(:to_formula).and_raise(FormulaUnavailableError, foo.name)
f = instance_double(Formula, name: "f", deps: [foo])
expect { described_class.expand(f) }.to raise_error(FormulaUnavailableError)
expect(described_class.instance_variable_get(:@expand_stack)).to be_empty
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/build_environment_spec.rb | Library/Homebrew/test/build_environment_spec.rb | # frozen_string_literal: true
require "build_environment"
RSpec.describe BuildEnvironment do
let(:env) { described_class.new }
describe "#<<" do
it "returns itself" do
expect(env << :foo).to be env
end
end
describe "#merge" do
it "returns itself" do
expect(env.merge([])).to be env
end
end
describe "#std?" do
it "returns true if the environment contains :std" do
env << :std
expect(env).to be_std
end
it "returns false if the environment does not contain :std" do
expect(env).not_to be_std
end
end
describe BuildEnvironment::DSL do
let(:build_environment_dsl) do
klass = described_class
Class.new do
extend(klass)
end
end
context "with a single argument" do
subject(:build_env) do
Class.new(build_environment_dsl) do
env :std
end
end
it(:env) { expect(build_env.env).to be_std }
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/dependencies_helpers_spec.rb | Library/Homebrew/test/dependencies_helpers_spec.rb | # frozen_string_literal: true
require "dependencies_helpers"
RSpec.describe DependenciesHelpers do
specify "#dependents" do
foo = formula "foo" do
url "foo"
version "1.0"
end
foo_cask = Cask::CaskLoader.load(+<<-RUBY)
cask "foo_cask" do
end
RUBY
bar = formula "bar" do
url "bar-url"
version "1.0"
end
bar_cask = Cask::CaskLoader.load(+<<-RUBY)
cask "bar-cask" do
end
RUBY
methods = [
:name,
:full_name,
:runtime_dependencies,
:deps,
:requirements,
:recursive_dependencies,
:recursive_requirements,
:any_version_installed?,
]
dependents = Class.new.extend(described_class).dependents([foo, foo_cask, bar, bar_cask])
dependents.each do |dependent|
methods.each do |method|
expect(dependent.respond_to?(method))
.to be true
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/resource_spec.rb | Library/Homebrew/test/resource_spec.rb | # frozen_string_literal: true
require "resource"
require "livecheck"
RSpec.describe Resource do
subject(:resource) { described_class.new("test") }
let(:livecheck_resource) do
described_class.new do
url "https://brew.sh/foo-1.0.tar.gz"
sha256 "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
livecheck do
url "https://brew.sh/test/releases"
regex(/foo[._-]v?(\d+(?:\.\d+)+)\.t/i)
end
end
end
describe "#url" do
it "sets the URL" do
resource.url("foo")
expect(resource.url).to eq("foo")
end
it "can set the URL with specifications" do
resource.url("foo", branch: "master")
expect(resource.url).to eq("foo")
expect(resource.specs).to eq(branch: "master")
end
it "can set the URL with a custom download strategy class" do
strategy = Class.new(AbstractDownloadStrategy)
resource.url("foo", using: strategy)
expect(resource.url).to eq("foo")
expect(resource.download_strategy).to eq(strategy)
end
it "can set the URL with specifications and a custom download strategy class" do
strategy = Class.new(AbstractDownloadStrategy)
resource.url("foo", using: strategy, branch: "master")
expect(resource.url).to eq("foo")
expect(resource.specs).to eq(branch: "master")
expect(resource.download_strategy).to eq(strategy)
end
it "can set the URL with a custom download strategy symbol" do
resource.url("foo", using: :git)
expect(resource.url).to eq("foo")
expect(resource.download_strategy).to eq(GitDownloadStrategy)
end
it "raises an error if the download strategy class is unknown" do
expect { resource.url("foo", using: Class.new) }.to raise_error(TypeError)
end
it "does not mutate the specifications hash" do
specs = { using: :git, branch: "master" }
resource.url("foo", **specs)
expect(resource.specs).to eq(branch: "master")
expect(resource.using).to eq(:git)
expect(specs).to eq(using: :git, branch: "master")
end
end
describe "#livecheck" do
specify "when `livecheck` block is set" do
expect(livecheck_resource.livecheck.url).to eq("https://brew.sh/test/releases")
expect(livecheck_resource.livecheck.regex).to eq(/foo[._-]v?(\d+(?:\.\d+)+)\.t/i)
end
end
describe "#livecheck_defined?" do
it "returns false if `livecheck` block is not set in resource" do
expect(resource.livecheck_defined?).to be false
end
specify "`livecheck` block defined in resources" do # rubocop:todo RSpec/AggregateExamples
expect(livecheck_resource.livecheck_defined?).to be true
end
end
describe "#version" do
it "sets the version" do
resource.version("1.0")
expect(resource.version).to eq(Version.parse("1.0"))
expect(resource.version).not_to be_detected_from_url
end
it "can detect the version from a URL" do
resource.url("https://brew.sh/foo-1.0.tar.gz")
expect(resource.version).to eq(Version.parse("1.0"))
expect(resource.version).to be_detected_from_url
end
it "can set the version with a scheme" do
klass = Class.new(Version)
resource.version klass.new("1.0")
expect(resource.version).to eq(Version.parse("1.0"))
expect(resource.version).to be_a(klass)
end
it "can set the version from a tag" do
resource.url("https://brew.sh/foo-1.0.tar.gz", tag: "v1.0.2")
expect(resource.version).to eq(Version.parse("1.0.2"))
expect(resource.version).to be_detected_from_url
end
it "rejects non-string versions" do
expect { resource.version(1) }.to raise_error(TypeError)
expect { resource.version(2.0) }.to raise_error(TypeError)
expect { resource.version(Object.new) }.to raise_error(TypeError)
end
it "returns nil if unset" do
expect(resource.version).to be_nil
end
end
describe "#mirrors" do
it "is empty by defaults" do
expect(resource.mirrors).to be_empty
end
it "returns an array of mirrors added with #mirror" do
resource.mirror("foo")
resource.mirror("bar")
expect(resource.mirrors).to eq(%w[foo bar])
end
end
describe "#checksum" do
it "returns nil if unset" do
expect(resource.checksum).to be_nil
end
it "returns the checksum set with #sha256" do
resource.sha256(TEST_SHA256)
expect(resource.checksum).to eq(Checksum.new(TEST_SHA256))
end
end
describe "#download_strategy" do
it "returns the download strategy" do
strategy = Class.new(AbstractDownloadStrategy)
expect(DownloadStrategyDetector)
.to receive(:detect).with("foo", nil).and_return(strategy)
resource.url("foo")
expect(resource.download_strategy).to eq(strategy)
end
end
describe "#owner" do
it "sets the owner" do
owner = Object.new
resource.owner = owner
expect(resource.owner).to eq(owner)
end
it "sets its owner to be the patches' owner" do
resource.patch(:p1) { url "file:///my.patch" }
owner = Object.new
resource.owner = owner
resource.patches.each do |p|
expect(p.resource.owner).to eq(owner)
end
end
end
describe "#patch" do
it "adds a patch" do
resource.patch(:p1, :DATA)
expect(resource.patches.count).to eq(1)
expect(resource.patches.first.strip).to eq(:p1)
end
end
specify "#verify_download_integrity_missing" do
fn = Pathname.new("test")
allow(fn).to receive(:file?).and_return(true)
expect(fn).to receive(:verify_checksum).and_raise(ChecksumMissingError)
expect(fn).to receive(:sha256)
resource.verify_download_integrity(fn)
end
specify "#verify_download_integrity_mismatch" do
fn = instance_double(Pathname, file?: true, basename: "foo")
checksum = resource.sha256(TEST_SHA256)
expect(fn).to receive(:verify_checksum)
.with(checksum)
.and_raise(ChecksumMismatchError.new(fn, checksum, Object.new))
expect do
resource.verify_download_integrity(fn)
end.to raise_error(ChecksumMismatchError)
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/checksum_verification_spec.rb | Library/Homebrew/test/checksum_verification_spec.rb | # frozen_string_literal: true
require "formula"
RSpec.describe Formula do
def formula(&block)
super do
url "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz"
instance_eval(&block)
end
end
describe "#brew" do
it "does not raise an error when the checksum matches" do
expect do
f = formula do
sha256 TESTBALL_SHA256
end
f.brew do
# do nothing
end
end.not_to raise_error
end
it "raises an error when the checksum doesn't match" do
expect do
f = formula do
sha256 "dcbf5f44743b74add648c7e35e414076632fa3b24463d68d1f6afc5be77024f8"
end
f.brew do
# do nothing
end
end.to raise_error(ChecksumMismatchError)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/spec_helper.rb | Library/Homebrew/test/spec_helper.rb | # frozen_string_literal: true
if ENV["HOMEBREW_TESTS_COVERAGE"]
require "simplecov"
require "simplecov-cobertura"
formatters = [
SimpleCov::Formatter::HTMLFormatter,
SimpleCov::Formatter::CoberturaFormatter,
]
SimpleCov.formatters = SimpleCov::Formatter::MultiFormatter.new(formatters)
# Needed for outputting coverage reporting only once for parallel_tests.
# Otherwise, "Coverage report generated" will get spammed for each process.
if ENV["TEST_ENV_NUMBER"]
SimpleCov.at_exit do
result = SimpleCov.result
# `SimpleCov.result` calls `ParallelTests.wait_for_other_processes_to_finish`
# internally for you on the last process.
result.format! if ParallelTests.last_process?
end
end
end
require_relative "../standalone"
require_relative "../warnings"
require "test-prof"
Warnings.ignore :parser_syntax do
require "rubocop"
end
# TODO: Remove this workaround once TestProf fixes their RuboCop plugin.
# This is needed because the RuboCop RSpec plugin attempts to load TestProf's RuboCop plugin.
require "utils/test_prof_rubocop_stub"
require "rspec/github"
require "rspec/retry"
require "rspec/sorbet"
require "rubocop/rspec/support"
require "find"
require "timeout"
$LOAD_PATH.unshift(File.expand_path("#{ENV.fetch("HOMEBREW_LIBRARY")}/Homebrew/test/support/lib"))
require_relative "support/extend/cachable"
require_relative "../global"
require "debug" if ENV["HOMEBREW_DEBUG"]
require "test/support/quiet_progress_formatter"
require "test/support/helper/cask"
require "test/support/helper/files"
require "test/support/helper/fixtures"
require "test/support/helper/formula"
require "test/support/helper/mktmpdir"
require "test/support/helper/spec/shared_context/homebrew_cask" if OS.mac?
require "test/support/helper/spec/shared_context/integration_test"
require "test/support/helper/spec/shared_examples/formulae_exist"
TEST_DIRECTORIES = [
CoreTap.instance.path/"Formula",
HOMEBREW_CACHE,
HOMEBREW_CACHE_FORMULA,
HOMEBREW_CACHE/"api",
HOMEBREW_CELLAR,
HOMEBREW_LOCKS,
HOMEBREW_LOGS,
HOMEBREW_TEMP,
HOMEBREW_TEMP_CELLAR,
HOMEBREW_ALIASES,
].freeze
# Make `instance_double` and `class_double`
# work when type-checking is active.
RSpec::Sorbet.allow_doubles!
RSpec.configure do |config|
config.order = :random
config.raise_errors_for_deprecations!
config.warnings = true
config.raise_on_warning = true
config.disable_monkey_patching!
config.filter_run_when_matching :focus
config.silence_filter_announcements = true if ENV["TEST_ENV_NUMBER"]
# Improve backtrace formatting
config.filter_gems_from_backtrace "rspec-retry", "sorbet-runtime"
config.backtrace_exclusion_patterns << %r{test/spec_helper\.rb}
config.expect_with :rspec do |c|
c.max_formatted_output_length = 200
end
# Use rspec-retry to handle flaky tests.
config.default_sleep_interval = 1
# Don't want the nicer default retry behaviour when using CodeCov to
# identify flaky tests.
config.default_retry_count = 2 unless ENV["CODECOV_TOKEN"]
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on
# a real object. This is generally recommended and will default to
# `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
config.shared_context_metadata_behavior = :apply_to_host_groups
# Increase timeouts for integration tests (as we expect them to take longer).
config.around(:each, :integration_test) do |example|
example.metadata[:timeout] ||= 120
example.run
end
config.around(:each, :needs_network) do |example|
example.metadata[:timeout] ||= 120
# Don't want the nicer default retry behaviour when using CodeCov to
# identify flaky tests.
example.metadata[:retry] ||= 4 unless ENV["CODECOV_TOKEN"]
example.metadata[:retry_wait] ||= 2
example.metadata[:exponential_backoff] ||= true
example.run
end
# Never truncate output objects.
RSpec::Support::ObjectFormatter.default_instance.max_formatted_output_length = nil
config.include(RuboCop::RSpec::ExpectOffense)
config.include(Test::Helper::Cask)
config.include(Test::Helper::Fixtures)
config.include(Test::Helper::Formula)
config.include(Test::Helper::MkTmpDir)
# Enable aggregate failures by default
config.define_derived_metadata do |metadata|
metadata[:aggregate_failures] = true unless metadata.key?(:aggregate_failures)
end
config.before(:each, :needs_linux) do
skip "Not running on Linux." unless OS.linux?
end
config.before(:each, :needs_macos) do
skip "Not running on macOS." unless OS.mac?
end
config.before(:each, :needs_ci) do
skip "Not running on CI." unless ENV["CI"]
end
config.before(:each, :needs_java) do
skip "Java is not installed." unless which("java")
end
config.before(:each, :needs_python) do
skip "Python is not installed." if !which("python3") && !which("python")
end
config.before(:each, :needs_network) do
skip "Requires network connection." unless ENV["HOMEBREW_TEST_ONLINE"]
end
config.before(:each, :needs_homebrew_core) do
core_tap_path = "#{ENV.fetch("HOMEBREW_LIBRARY")}/Taps/homebrew/homebrew-core"
skip "Requires homebrew/core to be tapped." unless Dir.exist?(core_tap_path)
end
config.before(:each, :needs_systemd) do
skip "No SystemD found." unless which("systemctl")
end
config.before(:each, :needs_daemon_manager) do
skip "No LaunchCTL or SystemD found." if !which("systemctl") && !which("launchctl")
end
config.before do |example|
next if example.metadata.key?(:needs_network)
next if example.metadata.key?(:needs_utils_curl)
allow(Utils::Curl).to receive(:curl_executable).and_raise(<<~ERROR)
Unexpected call to Utils::Curl.curl_executable without setting :needs_network or :needs_utils_curl.
ERROR
end
config.before(:each, :no_api) do
ENV["HOMEBREW_NO_INSTALL_FROM_API"] = "1"
end
config.before(:each, :needs_svn) do
svn_shim = HOMEBREW_SHIMS_PATH/"shared/svn"
skip "Subversion is not installed." unless quiet_system svn_shim, "--version"
svn_shim_path = Pathname(Utils.popen_read(svn_shim, "--homebrew=print-path").chomp.presence)
svn_paths = PATH.new(ENV.fetch("PATH"))
svn_paths.prepend(svn_shim_path.dirname)
if OS.mac?
xcrun_svn = Utils.popen_read("xcrun", "-f", "svn")
svn_paths.append(File.dirname(xcrun_svn)) if $CHILD_STATUS.success? && xcrun_svn.present?
end
svn = which("svn", svn_paths)
skip "svn is not installed." unless svn
svnadmin = which("svnadmin", svn_paths)
skip "svnadmin is not installed." unless svnadmin
ENV["PATH"] = PATH.new(ENV.fetch("PATH"))
.append(svn.dirname)
.append(svnadmin.dirname)
end
config.before(:each, :needs_homebrew_curl) do
ENV["HOMEBREW_CURL"] = HOMEBREW_BREWED_CURL_PATH
skip "A `curl` with TLS 1.3 support is required." unless Utils::Curl.curl_supports_tls13?
rescue FormulaUnavailableError
skip "No `curl` formula is available."
end
config.before(:each, :needs_unzip) do
skip "Unzip is not installed." unless which("unzip")
end
config.around do |example|
Homebrew.raise_deprecation_exceptions = true
Tap.installed.each(&:clear_cache)
Cachable::Registry.clear_all_caches
FormulaInstaller.clear_attempted
FormulaInstaller.clear_installed
FormulaInstaller.clear_fetched
Utils::Curl.clear_path_cache
TEST_DIRECTORIES.each(&:mkpath)
@__homebrew_failed = Homebrew.failed?
@__files_before_test = Test::Helper::Files.find_files
@__env = ENV.to_hash # dup doesn't work on ENV
@__stdout = $stdout.clone
@__stderr = $stderr.clone
@__stdin = $stdin.clone
# Link original API cache files to test cache directory.
Pathname("#{ENV.fetch("HOMEBREW_CACHE")}/api").glob("*.json").each do |path|
FileUtils.ln_s path, HOMEBREW_CACHE/"api/#{path.basename}"
end
begin
if example.metadata.keys.exclude?(:focus) && !ENV.key?("HOMEBREW_VERBOSE_TESTS")
$stdout.reopen(File::NULL)
$stderr.reopen(File::NULL)
$stdin.reopen(File::NULL)
else
# don't retry when focusing
config.default_retry_count = 0
end
begin
timeout = example.metadata.fetch(:timeout, 60)
Timeout.timeout(timeout) do
example.run
end
rescue Timeout::Error => e
example.example.set_exception(e)
end
rescue SystemExit => e
example.example.set_exception(e)
ensure
ENV.replace(@__env)
Context.current = Context::ContextStruct.new
$stdout.reopen(@__stdout)
$stderr.reopen(@__stderr)
$stdin.reopen(@__stdin)
@__stdout.close
@__stderr.close
@__stdin.close
Tap.all.each(&:clear_cache)
Cachable::Registry.clear_all_caches
FileUtils.rm_rf [
*TEST_DIRECTORIES,
*Keg.must_exist_subdirectories,
HOMEBREW_LINKED_KEGS,
HOMEBREW_PINNED_KEGS,
HOMEBREW_PREFIX/"Caskroom",
HOMEBREW_PREFIX/"Frameworks",
HOMEBREW_LIBRARY/"Taps/homebrew/homebrew-cask",
HOMEBREW_LIBRARY/"Taps/homebrew/homebrew-bar",
HOMEBREW_LIBRARY/"Taps/homebrew/homebrew-foo",
HOMEBREW_LIBRARY/"Taps/homebrew/homebrew-test-bot",
HOMEBREW_LIBRARY/"Taps/homebrew/homebrew-shallow",
HOMEBREW_LIBRARY/"PinnedTaps",
HOMEBREW_REPOSITORY/".git",
CoreTap.instance.path/".git",
CoreTap.instance.alias_dir,
CoreTap.instance.path/"formula_renames.json",
CoreTap.instance.path/"tap_migrations.json",
CoreTap.instance.path/"audit_exceptions",
CoreTap.instance.path/"style_exceptions",
*Pathname.glob("#{HOMEBREW_CELLAR}/*/"),
HOMEBREW_LIBRARY_PATH/"test/.vscode",
HOMEBREW_LIBRARY_PATH/"test/.cursor",
HOMEBREW_LIBRARY_PATH/"test/Library",
]
files_after_test = Test::Helper::Files.find_files
diff = Set.new(@__files_before_test) ^ Set.new(files_after_test)
expect(diff).to be_empty, <<~EOS
file leak detected:
#{diff.map { |f| " #{f}" }.join("\n")}
EOS
Homebrew.failed = @__homebrew_failed
end
end
end
RSpec::Matchers.define_negated_matcher :not_to_output, :output
RSpec::Matchers.alias_matcher :have_failed, :be_failed
# Match consecutive elements in an array.
RSpec::Matchers.define :array_including_cons do |*cons|
match do |actual|
expect(actual.each_cons(cons.size)).to include(cons)
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/formula_pin_spec.rb | Library/Homebrew/test/formula_pin_spec.rb | # frozen_string_literal: true
require "formula_pin"
RSpec.describe FormulaPin do
subject(:formula_pin) { described_class.new(formula) }
let(:name) { "double" }
let(:formula) { instance_double(Formula, name:, rack: HOMEBREW_CELLAR/name) }
before do
formula.rack.mkpath
allow(formula).to receive(:installed_prefixes) do
formula.rack.directory? ? formula.rack.subdirs.sort : []
end
allow(formula).to receive(:installed_kegs) do
formula.installed_prefixes.map { |prefix| Keg.new(prefix) }
end
end
it "is not pinnable by default" do
expect(formula_pin).not_to be_pinnable
end
it "is pinnable if the Keg exists" do
(formula.rack/"0.1").mkpath
expect(formula_pin).to be_pinnable
end
specify "#pin and #unpin" do
(formula.rack/"0.1").mkpath
formula_pin.pin
expect(formula_pin).to be_pinned
expect(HOMEBREW_PINNED_KEGS/name).to be_a_directory
expect(HOMEBREW_PINNED_KEGS.children.count).to eq(1)
formula_pin.unpin
expect(formula_pin).not_to be_pinned
expect(HOMEBREW_PINNED_KEGS).not_to be_a_directory
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/sandbox_spec.rb | Library/Homebrew/test/sandbox_spec.rb | # frozen_string_literal: true
require "sandbox"
RSpec.describe Sandbox, :needs_macos do
define_negated_matcher :not_matching, :matching
subject(:sandbox) { described_class.new }
let(:dir) { mktmpdir }
let(:file) { dir/"foo" }
before do
skip "Sandbox not implemented." unless described_class.available?
end
specify "#allow_write" do
sandbox.allow_write path: file
sandbox.run "touch", file
expect(file).to exist
end
describe "#path_filter" do
["'", '"', "(", ")", "\n", "\\"].each do |char|
it "fails if the path contains #{char}" do
expect do
sandbox.path_filter("foo#{char}bar", :subpath)
end.to raise_error(ArgumentError)
end
end
end
describe "#allow_write_cellar" do
it "fails when the formula has a name including )" do
f = formula do
url "https://brew.sh/foo-1.0.tar.gz"
version "1.0"
def initialize(*, **)
super
@name = "foo)bar"
end
end
expect do
sandbox.allow_write_cellar f
end.to raise_error(ArgumentError)
end
it "fails when the formula has a name including \"" do
f = formula do
url "https://brew.sh/foo-1.0.tar.gz"
version "1.0"
def initialize(*, **)
super
@name = "foo\"bar"
end
end
expect do
sandbox.allow_write_cellar f
end.to raise_error(ArgumentError)
end
end
describe "#run" do
it "fails when writing to file not specified with ##allow_write" do
expect do
sandbox.run "touch", file
end.to raise_error(ErrorDuringExecution)
expect(file).not_to exist
end
it "complains on failure" do
ENV["HOMEBREW_VERBOSE"] = "1"
allow(Utils).to receive(:popen_read).and_call_original
allow(Utils).to receive(:popen_read).with("syslog", any_args).and_return("foo")
expect { sandbox.run "false" }
.to raise_error(ErrorDuringExecution)
.and output(/foo/).to_stdout
end
it "ignores bogus Python error" do
ENV["HOMEBREW_VERBOSE"] = "1"
with_bogus_error = <<~EOS
foo
Mar 17 02:55:06 sandboxd[342]: Python(49765) deny file-write-unlink /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/distutils/errors.pyc
bar
EOS
allow(Utils).to receive(:popen_read).and_call_original
allow(Utils).to receive(:popen_read).with("syslog", any_args).and_return(with_bogus_error)
expect { sandbox.run "false" }
.to raise_error(ErrorDuringExecution)
.and output(a_string_matching(/foo/).and(matching(/bar/).and(not_matching(/Python/)))).to_stdout
end
end
describe "#disallow chmod on some directory" do
it "formula does a chmod to opt" do
expect { sandbox.run "chmod", "ug-w", HOMEBREW_PREFIX }.to raise_error(ErrorDuringExecution)
end
it "allows chmod on a path allowed to write" do
mktmpdir do |path|
FileUtils.touch path/"foo"
sandbox.allow_write_path(path)
expect { sandbox.run "chmod", "ug-w", path/"foo" }.not_to raise_error
end
end
end
describe "#disallow chmod SUID or SGID on some directory" do
it "formula does a chmod 4000 to opt" do
expect { sandbox.run "chmod", "4000", HOMEBREW_PREFIX }.to raise_error(ErrorDuringExecution)
end
it "allows chmod 4000 on a path allowed to write" do
mktmpdir do |path|
FileUtils.touch path/"foo"
sandbox.allow_write_path(path)
expect { sandbox.run "chmod", "4000", path/"foo" }.not_to raise_error
end
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/options_spec.rb | Library/Homebrew/test/options_spec.rb | # frozen_string_literal: true
require "options"
RSpec.describe Options do
subject(:options) { described_class.new }
it "removes duplicate options" do
options << Option.new("foo")
options << Option.new("foo")
expect(options).to include("--foo")
expect(options.count).to eq(1)
end
it "preserves existing member when adding a duplicate" do
a = Option.new("foo", "bar")
b = Option.new("foo", "qux")
options << a << b
expect(options.count).to eq(1)
expect(options.first).to be(a)
expect(options.first.description).to eq(a.description)
end
specify "#include?" do
options << Option.new("foo")
expect(options).to include("--foo")
expect(options).to include("foo")
expect(options).to include(Option.new("foo"))
end
describe "#+" do
it "returns options" do
expect(options + described_class.new).to be_an_instance_of(described_class)
end
end
describe "#-" do
it "returns options" do
expect(options - described_class.new).to be_an_instance_of(described_class)
end
end
specify "#&" do
foo, bar, baz = %w[foo bar baz].map { |o| Option.new(o) }
other_options = described_class.new << foo << bar
options << foo << baz
expect((options & other_options).to_a).to eq([foo])
end
specify "#|" do
foo, bar, baz = %w[foo bar baz].map { |o| Option.new(o) }
other_options = described_class.new << foo << bar
options << foo << baz
expect((options | other_options).sort).to eq([foo, bar, baz].sort)
end
specify "#*" do
options << Option.new("aa") << Option.new("bb") << Option.new("cc")
expect((options * "XX").split("XX").sort).to eq(%w[--aa --bb --cc])
end
describe "<<" do
it "returns itself" do
expect(options << Option.new("foo")).to be options
end
end
specify "#as_flags" do
options << Option.new("foo")
expect(options.as_flags).to eq(%w[--foo])
end
specify "#to_a" do
option = Option.new("foo")
options << option
expect(options.to_a).to eq([option])
end
specify "#to_ary" do
option = Option.new("foo")
options << option
expect(options.to_ary).to eq([option])
end
specify "::create_with_array" do
array = %w[--foo --bar]
option1 = Option.new("foo")
option2 = Option.new("bar")
expect(described_class.create(array).sort).to eq([option1, option2].sort)
end
specify "#to_s" do
expect(options.to_s).to eq("")
options << Option.new("first")
expect(options.to_s).to eq("--first")
options << Option.new("second")
expect(options.to_s).to eq("--first --second")
end
specify "#inspect" do
expect(options.inspect).to eq("#<Options: []>")
options << Option.new("foo")
expect(options.inspect).to eq("#<Options: [#<Option: \"--foo\">]>")
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/test_bot/step_spec.rb | Library/Homebrew/test/test_bot/step_spec.rb | # frozen_string_literal: true
require "test_bot"
require "ostruct"
RSpec.describe Homebrew::TestBot::Step do
subject(:step) { described_class.new(command, env:, verbose:) }
let(:command) { ["brew", "config"] }
let(:env) { {} }
let(:verbose) { false }
describe "#run" do
it "runs the command" do
expect(step).to receive(:system_command)
.with("brew", args: ["config"], env:, print_stderr: verbose, print_stdout: verbose)
.and_return(instance_double(SystemCommand::Result, success?: true, merged_output: ""))
step.run
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/test_bot/setup_spec.rb | Library/Homebrew/test/test_bot/setup_spec.rb | # frozen_string_literal: true
require "test_bot"
require "ostruct"
RSpec.describe Homebrew::TestBot::Setup do
subject(:setup) { described_class.new }
describe "#run!" do
it "is successful" do
expect(setup).to receive(:test)
.exactly(3).times
.and_return(instance_double(Homebrew::TestBot::Step, passed?: true))
expect(setup.run!(args: instance_double(Homebrew::CLI::Args)).passed?).to be(true)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/services/formula_wrapper_spec.rb | Library/Homebrew/test/services/formula_wrapper_spec.rb | # frozen_string_literal: true
require "services/system"
require "services/formula_wrapper"
require "tempfile"
RSpec.describe Homebrew::Services::FormulaWrapper do
subject(:service) { described_class.new(formula) }
let(:formula) do
instance_double(Formula,
name: "mysql",
plist_name: "plist-mysql-test",
service_name: "plist-mysql-test",
launchd_service_path: Pathname.new("/usr/local/opt/mysql/homebrew.mysql.plist"),
systemd_service_path: Pathname.new("/usr/local/opt/mysql/homebrew.mysql.service"),
opt_prefix: Pathname.new("/usr/local/opt/mysql"),
any_version_installed?: true,
service?: false)
end
let(:service_object) do
instance_double(Homebrew::Service,
requires_root?: false,
timed?: false,
keep_alive?: false,
command: "/bin/cmd",
manual_command: "/bin/cmd",
working_dir: nil,
root_dir: nil,
log_path: nil,
error_log_path: nil,
interval: nil,
cron: nil)
end
before do
allow(formula).to receive(:service).and_return(service_object)
ENV["HOME"] = "/tmp_home"
end
describe "#service_file" do
it "macOS - outputs the full service file path" do
allow(Homebrew::Services::System).to receive(:launchctl?).and_return(true)
expect(service.service_file.to_s).to eq("/usr/local/opt/mysql/homebrew.mysql.plist")
end
it "systemD - outputs the full service file path" do
allow(Homebrew::Services::System).to receive_messages(launchctl?: false, systemctl?: true)
expect(service.service_file.to_s).to eq("/usr/local/opt/mysql/homebrew.mysql.service")
end
it "Other - raises an error" do
allow(Homebrew::Services::System).to receive_messages(launchctl?: false, systemctl?: false)
expect do
service.service_file
end.to raise_error(UsageError,
"Invalid usage: `brew services` is supported only on macOS or Linux (with systemd)!")
end
end
describe "#name" do
it "outputs formula name" do
expect(service.name).to eq("mysql")
end
end
describe "#service_name" do
it "macOS - outputs the service name" do
allow(Homebrew::Services::System).to receive(:launchctl?).and_return(true)
expect(service.service_name).to eq("plist-mysql-test")
end
it "systemD - outputs the service name" do
allow(Homebrew::Services::System).to receive_messages(launchctl?: false, systemctl?: true)
expect(service.service_name).to eq("plist-mysql-test")
end
it "Other - raises an error" do
allow(Homebrew::Services::System).to receive_messages(launchctl?: false, systemctl?: false)
expect do
service.service_name
end.to raise_error(UsageError,
"Invalid usage: `brew services` is supported only on macOS or Linux (with systemd)!")
end
end
describe "#dest_dir" do
before do
allow(Homebrew::Services::System).to receive_messages(launchctl?: false, systemctl?: false)
end
it "macOS - user - outputs the destination directory for the service file" do
ENV["HOME"] = "/tmp_home"
allow(Homebrew::Services::System).to receive_messages(root?: false, launchctl?: true)
expect(service.dest_dir.to_s).to eq("/tmp_home/Library/LaunchAgents")
end
it "macOS - root - outputs the destination directory for the service file" do
allow(Homebrew::Services::System).to receive_messages(launchctl?: true, root?: true)
expect(service.dest_dir.to_s).to eq("/Library/LaunchDaemons")
end
it "systemD - user - outputs the destination directory for the service file" do
ENV["HOME"] = "/tmp_home"
allow(Homebrew::Services::System).to receive_messages(root?: false, launchctl?: false, systemctl?: true)
expect(service.dest_dir.to_s).to eq("/tmp_home/.config/systemd/user")
end
it "systemD - root - outputs the destination directory for the service file" do
allow(Homebrew::Services::System).to receive_messages(root?: true, launchctl?: false, systemctl?: true)
expect(service.dest_dir.to_s).to eq("/usr/lib/systemd/system")
end
end
describe "#dest" do
before do
ENV["HOME"] = "/tmp_home"
allow(Homebrew::Services::System).to receive_messages(launchctl?: false, systemctl?: false)
end
it "macOS - outputs the destination for the service file" do
allow(Homebrew::Services::System).to receive(:launchctl?).and_return(true)
expect(service.dest.to_s).to eq("/tmp_home/Library/LaunchAgents/homebrew.mysql.plist")
end
it "systemD - outputs the destination for the service file" do
allow(Homebrew::Services::System).to receive(:systemctl?).and_return(true)
expect(service.dest.to_s).to eq("/tmp_home/.config/systemd/user/homebrew.mysql.service")
end
end
describe "#installed?" do
it "outputs if the service formula is installed" do
expect(service.installed?).to be(true)
end
end
describe "#loaded?" do
it "macOS - outputs if the service is loaded" do
allow(Homebrew::Services::System).to receive_messages(launchctl?: true, systemctl?: false)
allow(Utils).to receive(:safe_popen_read)
expect(service.loaded?).to be(false)
end
it "systemD - outputs if the service is loaded" do
allow(Homebrew::Services::System).to receive_messages(launchctl?: false, systemctl?: true)
allow(Homebrew::Services::System::Systemctl).to receive(:quiet_run).and_return(false)
allow(Utils).to receive(:safe_popen_read)
expect(service.loaded?).to be(false)
end
it "Other - raises an error" do
allow(Homebrew::Services::System).to receive_messages(launchctl?: false, systemctl?: false)
expect do
service.loaded?
end.to raise_error(UsageError,
"Invalid usage: `brew services` is supported only on macOS or Linux (with systemd)!")
end
end
describe "#plist?" do
it "false if not installed" do
allow(service).to receive(:installed?).and_return(false)
expect(service.plist?).to be(false)
end
it "true if installed and file" do
tempfile = File.new("/tmp/foo", File::CREAT)
allow(service).to receive_messages(installed?: true, service_file: Pathname.new(tempfile))
expect(service.plist?).to be(true)
File.delete(tempfile)
end
it "false if opt_prefix missing" do
allow(service).to receive_messages(installed?: true,
service_file: Pathname.new(File::NULL),
formula: instance_double(Formula,
opt_prefix: Pathname.new("/dfslkfhjdsolshlk")))
expect(service.plist?).to be(false)
end
end
describe "#owner" do
it "root if file present" do
allow(service).to receive(:boot_path_service_file_present?).and_return(true)
expect(service.owner).to eq("root")
end
it "user if file present" do
allow(service).to receive_messages(boot_path_service_file_present?: false,
user_path_service_file_present?: true)
allow(Homebrew::Services::System).to receive(:user).and_return("user")
expect(service.owner).to eq("user")
end
it "nil if no file present" do
allow(service).to receive_messages(boot_path_service_file_present?: false,
user_path_service_file_present?: false)
expect(service.owner).to be_nil
end
end
describe "#service_file_present?" do
it "macOS - outputs if the service file is present" do
allow(Homebrew::Services::System).to receive_messages(launchctl?: true, systemctl?: false)
expect(service.service_file_present?).to be(false)
end
it "macOS - outputs if the service file is present for root" do
allow(Homebrew::Services::System).to receive_messages(launchctl?: true, systemctl?: false)
expect(service.service_file_present?(type: :root)).to be(false)
end
it "macOS - outputs if the service file is present for user" do
allow(Homebrew::Services::System).to receive_messages(launchctl?: true, systemctl?: false)
expect(service.service_file_present?(type: :user)).to be(false)
end
end
describe "#owner?" do
it "macOS - outputs the service file owner" do
allow(Homebrew::Services::System).to receive_messages(launchctl?: true, systemctl?: false)
expect(service.owner).to be_nil
end
end
describe "#pid?" do
it "outputs false because there is not PID" do
allow(service).to receive(:pid).and_return(nil)
expect(service.pid?).to be(false)
end
it "outputs false because there is a PID and it is zero" do
allow(service).to receive(:pid).and_return(0)
expect(service.pid?).to be(false)
end
it "outputs true because there is a PID and it is positive" do
allow(service).to receive(:pid).and_return(12)
expect(service.pid?).to be(true)
end
# This should never happen in practice, as PIDs cannot be negative.
it "outputs false because there is a PID and it is negative" do
allow(service).to receive(:pid).and_return(-1)
expect(service.pid?).to be(false)
end
end
describe "#pid", :needs_systemd do
it "outputs nil because there is not pid" do
expect(service.pid).to be_nil
end
end
describe "#error?" do
it "outputs false because there is no PID or exit code" do
allow(service).to receive_messages(pid: nil, exit_code: nil)
expect(service.error?).to be(false)
end
it "outputs false because there is a PID but no exit" do
allow(service).to receive_messages(pid: 12, exit_code: nil)
expect(service.error?).to be(false)
end
it "outputs false because there is a PID and a zero exit code" do
allow(service).to receive_messages(pid: 12, exit_code: 0)
expect(service.error?).to be(false)
end
it "outputs false because there is a PID and a positive exit code" do
allow(service).to receive_messages(pid: 12, exit_code: 1)
expect(service.error?).to be(false)
end
it "outputs false because there is no PID and a zero exit code" do
allow(service).to receive_messages(pid: nil, exit_code: 0)
expect(service.error?).to be(false)
end
it "outputs true because there is no PID and a positive exit code" do
allow(service).to receive_messages(pid: nil, exit_code: 1)
expect(service.error?).to be(true)
end
# This should never happen in practice, as exit codes cannot be negative.
it "outputs true because there is no PID and a negative exit code" do
allow(service).to receive_messages(pid: nil, exit_code: -1)
expect(service.error?).to be(true)
end
end
describe "#exit_code", :needs_systemd do
it "outputs nil because there is no exit code" do
expect(service.exit_code).to be_nil
end
end
describe "#unknown_status?", :needs_systemd do
it "outputs true because there is no PID" do
expect(service.unknown_status?).to be(true)
end
end
describe "#timed?" do
it "returns true if timed service" do
service_stub = instance_double(Homebrew::Service, timed?: true)
allow(service).to receive_messages(service?: true, load_service: service_stub)
allow(service_stub).to receive(:timed?).and_return(true)
expect(service.timed?).to be(true)
end
it "returns false if no timed service" do
service_stub = instance_double(Homebrew::Service, timed?: false)
allow(service).to receive(:service?).once.and_return(true)
allow(service).to receive(:load_service).once.and_return(service_stub)
allow(service_stub).to receive(:timed?).and_return(false)
expect(service.timed?).to be(false)
end
it "returns nil if no service" do
allow(service).to receive(:service?).once.and_return(false)
expect(service.timed?).to be_nil
end
end
describe "#keep_alive?" do
it "returns true if service needs to stay alive" do
service_stub = instance_double(Homebrew::Service, keep_alive?: true)
allow(service).to receive(:service?).once.and_return(true)
allow(service).to receive(:load_service).once.and_return(service_stub)
expect(service.keep_alive?).to be(true)
end
it "returns false if service does not need to stay alive" do
service_stub = instance_double(Homebrew::Service, keep_alive?: false)
allow(service).to receive(:service?).once.and_return(true)
allow(service).to receive(:load_service).once.and_return(service_stub)
expect(service.keep_alive?).to be(false)
end
it "returns nil if no service" do
allow(service).to receive(:service?).once.and_return(false)
expect(service.keep_alive?).to be_nil
end
end
describe "#service_startup?" do
it "outputs false since there is no startup" do
expect(service.service_startup?).to be(false)
end
it "outputs true since there is a startup service" do
allow(service).to receive(:service?).once.and_return(true)
allow(service).to receive(:load_service).and_return(instance_double(Homebrew::Service, requires_root?: true))
expect(service.service_startup?).to be(true)
end
end
describe "#to_hash" do
it "represents non-service values" do
allow(Homebrew::Services::System).to receive_messages(launchctl?: true, systemctl?: false)
allow_any_instance_of(described_class).to receive_messages(service?: false, service_file_present?: false)
expected = {
exit_code: nil,
file: Pathname.new("/usr/local/opt/mysql/homebrew.mysql.plist"),
loaded: false,
loaded_file: nil,
name: "mysql",
pid: nil,
registered: false,
running: false,
schedulable: nil,
service_name: "plist-mysql-test",
status: :none,
user: nil,
}
expect(service.to_hash).to eq(expected)
end
it "represents running non-service values" do
ENV["HOME"] = "/tmp_home"
allow(Homebrew::Services::System).to receive_messages(launchctl?: true, systemctl?: false)
expect(service).to receive(:service?).twice.and_return(false)
expect(service).to receive(:service_file_present?).twice.and_return(true)
expected = {
exit_code: nil,
file: Pathname.new("/tmp_home/Library/LaunchAgents/homebrew.mysql.plist"),
loaded: false,
loaded_file: nil,
name: "mysql",
pid: nil,
registered: true,
running: false,
schedulable: nil,
service_name: "plist-mysql-test",
status: :none,
user: nil,
}
expect(service.to_hash).to eq(expected)
end
it "represents service values" do
ENV["HOME"] = "/tmp_home"
allow(Homebrew::Services::System).to receive_messages(launchctl?: true, systemctl?: false)
expect(service).to receive(:service?).twice.and_return(true)
expect(service).to receive(:service_file_present?).twice.and_return(true)
expect(service).to receive(:load_service).twice.and_return(service_object)
expected = {
command: "/bin/cmd",
cron: nil,
error_log_path: nil,
exit_code: nil,
file: Pathname.new("/tmp_home/Library/LaunchAgents/homebrew.mysql.plist"),
interval: nil,
loaded: false,
loaded_file: nil,
log_path: nil,
name: "mysql",
pid: nil,
registered: true,
root_dir: nil,
running: false,
schedulable: false,
service_name: "plist-mysql-test",
status: :none,
user: nil,
working_dir: nil,
}
expect(service.to_hash).to eq(expected)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/services/formulae_spec.rb | Library/Homebrew/test/services/formulae_spec.rb | # frozen_string_literal: true
require "services/formulae"
RSpec.describe Homebrew::Services::Formulae do
describe "#services_list" do
it "empty list without available formulae" do
allow(described_class).to receive(:available_services).and_return({})
expect(described_class.services_list).to eq([])
end
it "list with available formulae" do
formula = instance_double(Homebrew::Services::FormulaWrapper)
expected = [
{
file: Pathname.new("/Library/LaunchDaemons/file.plist"),
name: "formula",
status: :known,
user: "root",
},
]
expect(formula).to receive(:to_hash).and_return(expected[0])
allow(described_class).to receive(:available_services).and_return([formula])
expect(described_class.services_list).to eq(expected)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/services/cli_spec.rb | Library/Homebrew/test/services/cli_spec.rb | # frozen_string_literal: true
require "services/cli"
require "services/system"
require "services/formula_wrapper"
RSpec.describe Homebrew::Services::Cli do
subject(:services_cli) { described_class }
let(:service_string) { "service" }
describe "#bin" do
it "outputs command name" do
expect(services_cli.bin).to eq("brew services")
end
end
describe "#running" do
it "macOS - returns the currently running services" do
allow(Homebrew::Services::System).to receive_messages(launchctl?: true, systemctl?: false)
allow(Utils).to receive(:popen_read).and_return <<~EOS
77513 50 homebrew.mxcl.php
495 0 homebrew.mxcl.node_exporter
1234 34 homebrew.mxcl.postgresql@14
EOS
expect(services_cli.running).to eq([
"homebrew.mxcl.php",
"homebrew.mxcl.node_exporter",
"homebrew.mxcl.postgresql@14",
])
end
it "systemD - returns the currently running services" do
allow(Homebrew::Services::System).to receive(:launchctl?).and_return(false)
allow(Homebrew::Services::System::Systemctl).to receive(:popen_read).and_return <<~EOS
homebrew.php.service loaded active running Homebrew PHP service
systemd-udevd.service loaded active running Rule-based Manager for Device Events and Files
udisks2.service loaded active running Disk Manager
user@1000.service loaded active running User Manager for UID 1000
EOS
expect(services_cli.running).to eq(["homebrew.php.service"])
end
end
describe "#check!" do
it "checks the input does not exist" do
expect do
services_cli.check!([])
end.to raise_error(UsageError,
"Invalid usage: Formula(e) missing, please provide a formula name or use `--all`.")
end
it "checks the input exists" do
service = instance_double(Homebrew::Services::FormulaWrapper, name: "name", installed?: false)
expect do
services_cli.check!([service])
end.not_to raise_error
end
end
describe "#kill_orphaned_services" do
it "skips unmanaged services" do
allow(services_cli).to receive(:running).and_return(["example_service"])
expect do
services_cli.kill_orphaned_services
end.to output("Warning: Service example_service not managed by `brew services` => skipping\n").to_stderr
end
it "tries but is unable to kill a non existing service" do
service = instance_double(
service_string,
name: "example_service",
service_name: "homebrew.example_service",
pid?: true,
dest: Pathname("this_path_does_not_exist"),
keep_alive?: false,
)
allow(service).to receive(:reset_cache!)
allow(Homebrew::Services::FormulaWrapper).to receive(:from).and_return(service)
allow(services_cli).to receive(:running).and_return(["example_service"])
expect do
services_cli.kill_orphaned_services
end.to output("Killing `example_service`... (might take a while)\n").to_stdout
end
end
describe "#run" do
it "checks missing file causes error" do
expect(Homebrew::Services::System).not_to receive(:root?)
service = instance_double(Homebrew::Services::FormulaWrapper, name: "service_name")
expect do
services_cli.start([service], "/non/existent/path")
end.to raise_error(UsageError, "Invalid usage: Provided service file does not exist.")
end
it "checks empty targets cause no error" do
expect(Homebrew::Services::System).not_to receive(:root?)
services_cli.run([])
end
it "checks if target service is already running and suggests restart instead" do
expected_output = "Service `example_service` already running, " \
"use `brew services restart example_service` to restart.\n"
service = instance_double(service_string, name: "example_service", pid?: true)
expect do
services_cli.run([service])
end.to output(expected_output).to_stdout
end
end
describe "#start" do
it "checks missing file causes error" do
expect(Homebrew::Services::System).not_to receive(:root?)
service = instance_double(Homebrew::Services::FormulaWrapper, name: "service_name")
expect do
services_cli.start([service], "/hfdkjshksdjhfkjsdhf/fdsjghsdkjhb")
end.to raise_error(UsageError, "Invalid usage: Provided service file does not exist.")
end
it "checks empty targets cause no error" do
expect(Homebrew::Services::System).not_to receive(:root?)
services_cli.start([])
end
it "checks if target service has already been started and suggests restart instead" do
expected_output = "Service `example_service` already started, " \
"use `brew services restart example_service` to restart.\n"
service = instance_double(service_string, name: "example_service", pid?: true)
expect do
services_cli.start([service])
end.to output(expected_output).to_stdout
end
end
describe "#stop" do
it "checks empty targets cause no error" do
expect(Homebrew::Services::System).not_to receive(:root?)
services_cli.stop([])
end
end
describe "#kill" do
it "checks empty targets cause no error" do
expect(Homebrew::Services::System).not_to receive(:root?)
services_cli.kill([])
end
it "prints a message if service is not running" do
expected_output = "Service `example_service` is not started.\n"
service = instance_double(service_string, name: "example_service", pid?: false)
expect do
services_cli.kill([service])
end.to output(expected_output).to_stdout
end
it "prints a message if service is set to keep alive" do
expected_output = "Service `example_service` is set to automatically restart and can't be killed.\n"
service = instance_double(service_string, name: "example_service", pid?: true, keep_alive?: true)
expect do
services_cli.kill([service])
end.to output(expected_output).to_stdout
end
end
describe "#install_service_file" do
it "checks service is installed" do
service = instance_double(Homebrew::Services::FormulaWrapper, name: "name", installed?: false)
expect do
services_cli.install_service_file(service, nil)
end.to raise_error(UsageError, "Invalid usage: Formula `name` is not installed.")
end
it "checks service file exists" do
service = instance_double(
Homebrew::Services::FormulaWrapper,
name: "name",
installed?: true,
service_file: instance_double(Pathname, exist?: false),
)
expect do
services_cli.install_service_file(service, nil)
end.to raise_error(
UsageError,
"Invalid usage: Formula `name` has not implemented #plist, #service or provided a locatable service file.",
)
end
end
describe "#systemd_load", :needs_linux do
it "checks non-enabling run" do
expect(Homebrew::Services::System::Systemctl).to receive(:run).once.and_return(true)
services_cli.systemd_load(
instance_double(Homebrew::Services::FormulaWrapper, service_name: "name"),
enable: false,
)
end
it "checks enabling run" do
expect(Homebrew::Services::System::Systemctl).to receive(:run).twice.and_return(true)
services_cli.systemd_load(
instance_double(Homebrew::Services::FormulaWrapper, service_name: "name"),
enable: true,
)
end
end
describe "#launchctl_load", :needs_macos do
it "checks non-enabling run" do
allow(Homebrew::Services::System).to receive(:launchctl).and_return(Pathname.new("/bin/launchctl"))
expect(Homebrew::Services::System).to receive(:domain_target).once.and_return("target")
expect(described_class).to receive(:safe_system).once.and_return(true)
services_cli.launchctl_load(instance_double(Homebrew::Services::FormulaWrapper), file: "a", enable: false)
end
it "checks enabling run" do
allow(Homebrew::Services::System).to receive(:launchctl).and_return(Pathname.new("/bin/launchctl"))
expect(Homebrew::Services::System).to receive(:domain_target).twice.and_return("target")
expect(described_class).to receive(:safe_system).twice.and_return(true)
services_cli.launchctl_load(instance_double(Homebrew::Services::FormulaWrapper, service_name: "name"),
file: "a",
enable: true)
end
end
describe "#service_load" do
it "checks non-root for login" do
expect(Homebrew::Services::System).to receive(:launchctl?).once.and_return(false)
expect(Homebrew::Services::System).to receive(:systemctl?).once.and_return(false)
expect(Homebrew::Services::System).to receive(:root?).once.and_return(true)
expect do
services_cli.service_load(
instance_double(
Homebrew::Services::FormulaWrapper,
name: "name",
service_name: "service.name",
service_startup?: false,
),
nil,
enable: false,
)
end.to output("==> Successfully ran `name` (label: service.name)\n").to_stdout
end
it "checks root for startup" do
expect(Homebrew::Services::System).to receive(:launchctl?).once.and_return(false)
expect(Homebrew::Services::System).to receive(:systemctl?).once.and_return(false)
expect(Homebrew::Services::System).to receive(:root?).twice.and_return(false)
expect do
services_cli.service_load(
instance_double(
Homebrew::Services::FormulaWrapper,
name: "name",
service_name: "service.name",
service_startup?: true,
),
nil,
enable: false,
)
end.to output("==> Successfully ran `name` (label: service.name)\n").to_stdout
end
it "triggers launchctl" do
expect(Homebrew::Services::System).to receive(:launchctl?).once.and_return(true)
expect(Homebrew::Services::System).not_to receive(:systemctl?)
expect(Homebrew::Services::System).to receive(:root?).twice.and_return(false)
expect(described_class).to receive(:launchctl_load).once.and_return(true)
expect do
services_cli.service_load(
instance_double(
Homebrew::Services::FormulaWrapper,
name: "name",
service_name: "service.name",
service_startup?: false,
service_file: instance_double(Pathname, exist?: false),
),
nil,
enable: false,
)
end.to output("==> Successfully ran `name` (label: service.name)\n").to_stdout
end
it "triggers systemctl" do
expect(Homebrew::Services::System).to receive(:launchctl?).once.and_return(false)
expect(Homebrew::Services::System).to receive(:systemctl?).once.and_return(true)
expect(Homebrew::Services::System).to receive(:root?).twice.and_return(false)
expect(Homebrew::Services::System::Systemctl).to receive(:run).once.and_return(true)
expect do
services_cli.service_load(
instance_double(
Homebrew::Services::FormulaWrapper,
name: "name",
service_name: "service.name",
service_startup?: false,
dest: instance_double(Pathname, exist?: true),
),
nil,
enable: false,
)
end.to output("==> Successfully ran `name` (label: service.name)\n").to_stdout
end
it "represents correct action" do
expect(Homebrew::Services::System).to receive(:launchctl?).once.and_return(false)
expect(Homebrew::Services::System).to receive(:systemctl?).once.and_return(true)
expect(Homebrew::Services::System).to receive(:root?).twice.and_return(false)
expect(Homebrew::Services::System::Systemctl).to receive(:run).twice.and_return(true)
expect do
services_cli.service_load(
instance_double(
Homebrew::Services::FormulaWrapper,
name: "name",
service_name: "service.name",
service_startup?: false,
dest: instance_double(Pathname, exist?: true),
),
nil,
enable: true,
)
end.to output("==> Successfully started `name` (label: service.name)\n").to_stdout
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/services/system_spec.rb | Library/Homebrew/test/services/system_spec.rb | # frozen_string_literal: true
require "services/system"
RSpec.describe Homebrew::Services::System do
describe "#launchctl" do
it "macOS - outputs launchctl command location", :needs_macos do
expect(described_class.launchctl).to eq(Pathname.new("/bin/launchctl"))
end
it "Other - outputs launchctl command location", :needs_linux do
expect(described_class.launchctl).to be_nil
end
end
describe "#launchctl?" do
it "macOS - outputs launchctl presence", :needs_macos do
expect(described_class.launchctl?).to be(true)
end
it "Other - outputs launchctl presence", :needs_linux do
expect(described_class.launchctl?).to be(false)
end
end
describe "#systemctl?" do
it "Linux with SystemD - outputs systemctl presence", :needs_systemd do
expect(described_class.systemctl?).to be(true)
end
it "Other - outputs systemctl presence", :needs_macos do
expect(described_class.systemctl?).to be(false)
end
end
describe "#root?" do
it "checks if the command is ran as root" do
expect(described_class.root?).to be(false)
end
end
describe "#user" do
it "returns the current username" do
expect(described_class.user).to eq(ENV.fetch("USER"))
end
end
describe "#user_of_process" do
it "returns the username for empty PID" do
expect(described_class.user_of_process(nil)).to eq(ENV.fetch("USER"))
end
it "returns the PID username" do
allow(Utils).to receive(:safe_popen_read).and_return <<~EOS
USER
user
EOS
expect(described_class.user_of_process(50)).to eq("user")
end
it "returns nil if unavailable" do
allow(Utils).to receive(:safe_popen_read).and_return <<~EOS
USER
EOS
expect(described_class.user_of_process(50)).to be_nil
end
end
describe "#domain_target" do
it "returns the current domain target" do
allow(described_class).to receive(:root?).and_return(false)
expect(described_class.domain_target).to match(%r{gui/(\d+)})
end
it "returns the root domain target" do
allow(described_class).to receive(:root?).and_return(true)
expect(described_class.domain_target).to match("system")
end
end
describe "#boot_path" do
it "macOS - returns the boot path" do
allow(described_class).to receive(:launchctl?).and_return(true)
expect(described_class.boot_path.to_s).to eq("/Library/LaunchDaemons")
end
it "SystemD - returns the boot path" do
allow(described_class).to receive_messages(launchctl?: false, systemctl?: true)
expect(described_class.boot_path.to_s).to eq("/usr/lib/systemd/system")
end
it "Unknown - raises an error" do
allow(described_class).to receive_messages(launchctl?: false, systemctl?: false)
expect do
described_class.boot_path.to_s
end.to raise_error(UsageError,
"Invalid usage: `brew services` is supported only on macOS or Linux (with systemd)!")
end
end
describe "#user_path" do
it "macOS - returns the user path" do
ENV["HOME"] = "/tmp_home"
allow(described_class).to receive_messages(launchctl?: true, systemctl?: false)
expect(described_class.user_path.to_s).to eq("/tmp_home/Library/LaunchAgents")
end
it "systemD - returns the user path" do
ENV["HOME"] = "/tmp_home"
allow(described_class).to receive_messages(launchctl?: false, systemctl?: true)
expect(described_class.user_path.to_s).to eq("/tmp_home/.config/systemd/user")
end
it "Unknown - raises an error" do
ENV["HOME"] = "/tmp_home"
allow(described_class).to receive_messages(launchctl?: false, systemctl?: false)
expect do
described_class.user_path.to_s
end.to raise_error(UsageError,
"Invalid usage: `brew services` is supported only on macOS or Linux (with systemd)!")
end
end
describe "#path" do
it "macOS - user - returns the current relevant path" do
ENV["HOME"] = "/tmp_home"
allow(described_class).to receive_messages(root?: false, launchctl?: true, systemctl?: false)
expect(described_class.path.to_s).to eq("/tmp_home/Library/LaunchAgents")
end
it "macOS - root- returns the current relevant path" do
ENV["HOME"] = "/tmp_home"
allow(described_class).to receive_messages(root?: true, launchctl?: true, systemctl?: false)
expect(described_class.path.to_s).to eq("/Library/LaunchDaemons")
end
it "systemD - user - returns the current relevant path" do
ENV["HOME"] = "/tmp_home"
allow(described_class).to receive_messages(root?: false, launchctl?: false, systemctl?: true)
expect(described_class.path.to_s).to eq("/tmp_home/.config/systemd/user")
end
it "systemD - root- returns the current relevant path" do
ENV["HOME"] = "/tmp_home"
allow(described_class).to receive_messages(root?: true, launchctl?: false, systemctl?: true)
expect(described_class.path.to_s).to eq("/usr/lib/systemd/system")
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/services/system/systemctl_spec.rb | Library/Homebrew/test/services/system/systemctl_spec.rb | # frozen_string_literal: true
require "services/system"
require "services/system/systemctl"
RSpec.describe Homebrew::Services::System::Systemctl do
describe ".scope" do
it "outputs systemctl scope for user" do
allow(Homebrew::Services::System).to receive(:root?).and_return(false)
expect(described_class.scope).to eq("--user")
end
it "outputs systemctl scope for root" do
allow(Homebrew::Services::System).to receive(:root?).and_return(true)
expect(described_class.scope).to eq("--system")
end
end
describe ".executable" do
it "outputs systemctl command location", :needs_linux do
systemctl = Pathname("/bin/systemctl")
expect(described_class).to receive(:which).and_return(systemctl)
described_class.reset_executable!
expect(described_class.executable).to eq(systemctl)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/services/commands/restart_spec.rb | Library/Homebrew/test/services/commands/restart_spec.rb | # frozen_string_literal: true
require "services/commands/restart"
RSpec.describe Homebrew::Services::Commands::Restart do
describe "#TRIGGERS" do
it "contains all restart triggers" do
expect(described_class::TRIGGERS).to eq(%w[restart relaunch reload r])
end
end
describe "#run" do
it "fails with empty list" do
expect do
described_class.run([], nil, verbose: false)
end.to raise_error UsageError,
"Invalid usage: Formula(e) missing, please provide a formula name or use `--all`."
end
it "starts if services are not loaded" do
expect(Homebrew::Services::Cli).not_to receive(:run)
expect(Homebrew::Services::Cli).not_to receive(:stop)
expect(Homebrew::Services::Cli).to receive(:start).once
service = instance_double(Homebrew::Services::FormulaWrapper, service_name: "name", loaded?: false)
expect { described_class.run([service], nil, verbose: false) }.not_to raise_error
end
it "starts if services are loaded with file" do
expect(Homebrew::Services::Cli).not_to receive(:run)
expect(Homebrew::Services::Cli).to receive(:start).once
expect(Homebrew::Services::Cli).to receive(:stop).once
service = instance_double(Homebrew::Services::FormulaWrapper, service_name: "name", loaded?: true,
service_file_present?: true)
expect { described_class.run([service], nil, verbose: false) }.not_to raise_error
end
it "runs if services are loaded without file" do
expect(Homebrew::Services::Cli).not_to receive(:start)
expect(Homebrew::Services::Cli).to receive(:run).once
expect(Homebrew::Services::Cli).to receive(:stop).once
service = instance_double(Homebrew::Services::FormulaWrapper, service_name: "name", loaded?: true,
service_file_present?: false)
expect { described_class.run([service], nil, verbose: false) }.not_to raise_error
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/services/commands/list_spec.rb | Library/Homebrew/test/services/commands/list_spec.rb | # frozen_string_literal: true
require "services/commands/list"
RSpec.describe Homebrew::Services::Commands::List do
describe "#TRIGGERS" do
it "contains all restart triggers" do
expect(described_class::TRIGGERS).to eq([nil, "list", "ls"])
end
end
describe "#run" do
it "fails with empty list" do
expect(Homebrew::Services::Formulae).to receive(:services_list).and_return([])
expect do
allow($stderr).to receive(:tty?).and_return(true)
described_class.run
end.to output(a_string_including("No services available to control with `brew services`")).to_stderr
end
it "succeeds with list" do
out = "Name Status User File\nservice started user /dev/null\n"
formula = {
name: "service",
user: "user",
status: :started,
file: "/dev/null",
loaded: true,
}
expect(Homebrew::Services::Formulae).to receive(:services_list).and_return([formula])
expect do
described_class.run
end.to output(out).to_stdout
end
it "succeeds with list - JSON" do
formula = {
name: "service",
user: "user",
status: :started,
file: "/dev/null",
running: true,
loaded: true,
schedulable: false,
}
filtered_formula = formula.slice(*described_class::JSON_FIELDS)
expected_output = "#{JSON.pretty_generate([filtered_formula])}\n"
expect(Homebrew::Services::Formulae).to receive(:services_list).and_return([formula])
expect do
described_class.run(json: true)
end.to output(expected_output).to_stdout
end
end
describe "#print_table" do
it "prints all standard values" do
formula = { name: "a", user: "u", file: Pathname.new("/tmp/file.file"), status: :stopped }
expect do
described_class.print_table([formula])
end.to output("Name Status User File\na stopped u \n").to_stdout
end
it "prints without user or file data" do
formula = { name: "a", user: nil, file: nil, status: :started, loaded: true }
expect do
described_class.print_table([formula])
end.to output("Name Status User File\na started \n").to_stdout
end
it "prints shortened home directory" do
ENV["HOME"] = "/tmp"
formula = { name: "a", user: "u", file: Pathname.new("/tmp/file.file"), status: :started, loaded: true }
expected_output = "Name Status User File\na started u ~/file.file\n"
expect do
described_class.print_table([formula])
end.to output(expected_output).to_stdout
end
it "prints an error code" do
file = Pathname.new("/tmp/file.file")
formula = { name: "a", user: "u", file:, status: :error, exit_code: 256, loaded: true }
expected_output = "Name Status User File\na error 256 u /tmp/file.file\n"
expect do
described_class.print_table([formula])
end.to output(expected_output).to_stdout
end
end
describe "#print_json" do
it "prints all standard values" do
formula = { name: "a", status: :stopped, user: "u", file: Pathname.new("/tmp/file.file") }
expected_output = "#{JSON.pretty_generate([formula])}\n"
expect do
described_class.print_json([formula])
end.to output(expected_output).to_stdout
end
it "prints without user or file data" do
formula = { name: "a", user: nil, file: nil, status: :started, loaded: true }
filtered_formula = formula.slice(*described_class::JSON_FIELDS)
expected_output = "#{JSON.pretty_generate([filtered_formula])}\n"
expect do
described_class.print_json([formula])
end.to output(expected_output).to_stdout
end
it "includes an exit code" do
file = Pathname.new("/tmp/file.file")
formula = { name: "a", user: "u", file:, status: :error, exit_code: 256, loaded: true }
filtered_formula = formula.slice(*described_class::JSON_FIELDS)
expected_output = "#{JSON.pretty_generate([filtered_formula])}\n"
expect do
described_class.print_json([formula])
end.to output(expected_output).to_stdout
end
end
describe "#get_status_string" do
it "returns started" do
expect(described_class.get_status_string(:started)).to eq("started")
end
it "returns stopped" do
expect(described_class.get_status_string(:stopped)).to eq("stopped")
end
it "returns error" do
expect(described_class.get_status_string(:error)).to eq("error ")
end
it "returns unknown" do
expect(described_class.get_status_string(:unknown)).to eq("unknown")
end
it "returns other" do
expect(described_class.get_status_string(:other)).to eq("other")
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/services/commands/cleanup_spec.rb | Library/Homebrew/test/services/commands/cleanup_spec.rb | # frozen_string_literal: true
require "services/commands/cleanup"
require "services/system"
require "services/cli"
RSpec.describe Homebrew::Services::Commands::Cleanup do
describe "#TRIGGERS" do
it "contains all restart triggers" do
expect(described_class::TRIGGERS).to eq(%w[cleanup clean cl rm])
end
end
describe "#run" do
it "root - prints on empty cleanup" do
expect(Homebrew::Services::System).to receive(:root?).once.and_return(true)
expect(Homebrew::Services::Cli).to receive(:kill_orphaned_services).once.and_return([])
expect(Homebrew::Services::Cli).to receive(:remove_unused_service_files).once.and_return([])
expect do
described_class.run
end.to output("All root services OK, nothing cleaned...\n").to_stdout
end
it "user - prints on empty cleanup" do
expect(Homebrew::Services::System).to receive(:root?).once.and_return(false)
expect(Homebrew::Services::Cli).to receive(:kill_orphaned_services).once.and_return([])
expect(Homebrew::Services::Cli).to receive(:remove_unused_service_files).once.and_return([])
expect do
described_class.run
end.to output("All user-space services OK, nothing cleaned...\n").to_stdout
end
it "prints nothing on cleanup" do
expect(Homebrew::Services::System).not_to receive(:root?)
expect(Homebrew::Services::Cli).to receive(:kill_orphaned_services).once.and_return(["a"])
expect(Homebrew::Services::Cli).to receive(:remove_unused_service_files).once.and_return(["b"])
expect do
described_class.run
end.not_to output("All user-space services OK, nothing cleaned...\n").to_stdout
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/services/commands/info_spec.rb | Library/Homebrew/test/services/commands/info_spec.rb | # frozen_string_literal: true
require "services/commands/info"
RSpec.describe Homebrew::Services::Commands::Info do
before do
allow_any_instance_of(IO).to receive(:tty?).and_return(false)
end
describe "#TRIGGERS" do
it "contains all restart triggers" do
expect(described_class::TRIGGERS).to eq(%w[info i])
end
end
describe "#run" do
it "fails with empty list" do
expect do
described_class.run([], verbose: false, json: false)
end.to raise_error UsageError,
"Invalid usage: Formula(e) missing, please provide a formula name or use `--all`."
end
it "succeeds with items" do
out = "service ()\nRunning: true\nLoaded: true\nSchedulable: false\n"
formula_wrapper = instance_double(Homebrew::Services::FormulaWrapper, to_hash: {
name: "service",
user: "user",
status: :started,
file: "/dev/null",
running: true,
loaded: true,
schedulable: false,
})
expect do
described_class.run([formula_wrapper], verbose: false, json: false)
end.to output(out).to_stdout
end
it "succeeds with items - JSON" do
formula = {
name: "service",
user: "user",
status: :started,
file: "/dev/null",
running: true,
loaded: true,
schedulable: false,
}
out = "#{JSON.pretty_generate([formula])}\n"
formula_wrapper = instance_double(Homebrew::Services::FormulaWrapper, to_hash: formula)
expect do
described_class.run([formula_wrapper], verbose: false, json: true)
end.to output(out).to_stdout
end
end
describe "#output" do
it "returns minimal output" do
out = "service ()\nRunning: true\n"
out += "Loaded: true\nSchedulable: false\n"
formula = {
name: "service",
user: "user",
status: :started,
file: "/dev/null",
running: true,
loaded: true,
schedulable: false,
}
expect(described_class.output(formula, verbose: false)).to eq(out)
end
it "returns normal output" do
out = "service ()\nRunning: true\n"
out += "Loaded: true\nSchedulable: false\n"
out += "User: user\nPID: 42\n"
formula = {
name: "service",
user: "user",
status: :started,
file: "/dev/null",
running: true,
loaded: true,
schedulable: false,
pid: 42,
}
expect(described_class.output(formula, verbose: false)).to eq(out)
end
it "returns verbose output" do
out = "service ()\nRunning: true\n"
out += "Loaded: true\nSchedulable: false\n"
out += "User: user\nPID: 42\nFile: /dev/null true\nRegistered at login: true\nCommand: /bin/command\n"
out += "Working directory: /working/dir\nRoot directory: /root/dir\nLog: /log/dir\nError log: /log/dir/error\n"
out += "Interval: 3600s\nCron: 5 * * * *\n"
formula = {
name: "service",
user: "user",
status: :started,
file: "/dev/null",
registered: true,
running: true,
loaded: true,
schedulable: false,
pid: 42,
command: "/bin/command",
working_dir: "/working/dir",
root_dir: "/root/dir",
log_path: "/log/dir",
error_log_path: "/log/dir/error",
interval: 3600,
cron: "5 * * * *",
}
expect(described_class.output(formula, verbose: true)).to eq(out)
end
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/quiet_progress_formatter.rb | Library/Homebrew/test/support/quiet_progress_formatter.rb | # typed: true
# frozen_string_literal: true
require "rspec/core/formatters/progress_formatter"
class QuietProgressFormatter < RSpec::Core::Formatters::ProgressFormatter
RSpec::Core::Formatters.register self, :seed
def dump_summary(notification); end
def seed(notification); end
def close(notification); end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/failball.rb | Library/Homebrew/test/support/fixtures/failball.rb | # typed: true
# frozen_string_literal: true
class Failball < Formula
def initialize(name = "failball", path = Pathname.new(__FILE__).expand_path, spec = :stable,
alias_path: nil, tap: nil, force_bottle: false)
super
end
DSL_PROC = proc do
url "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz"
sha256 TESTBALL_SHA256
end.freeze
private_constant :DSL_PROC
DSL_PROC.call
def self.inherited(other)
super
other.instance_eval(&DSL_PROC)
end
def install
prefix.install "bin"
prefix.install "libexec"
# This should get marshalled into a BuildError.
system "/usr/bin/false" if ENV["FAILBALL_BUILD_ERROR"]
# This should get marshalled into a RuntimeError.
raise "Something that isn't a build error happened!"
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/testball_bottle.rb | Library/Homebrew/test/support/fixtures/testball_bottle.rb | # typed: true
# frozen_string_literal: true
class TestballBottle < Formula
def initialize(name = "testball_bottle", path = Pathname.new(__FILE__).expand_path, spec = :stable,
alias_path: nil, tap: nil, force_bottle: false)
super
end
DSL_PROC = proc do
url "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz"
sha256 TESTBALL_SHA256
bottle do
root_url "file://#{TEST_FIXTURE_DIR}/bottles"
sha256 cellar: :any_skip_relocation, Utils::Bottles.tag.to_sym => "d7b9f4e8bf83608b71fe958a99f19f2e5e68bb2582965d32e41759c24f1aef97"
end
end.freeze
private_constant :DSL_PROC
DSL_PROC.call
def self.inherited(other)
super
other.instance_eval(&DSL_PROC)
end
def install
prefix.install "bin"
prefix.install "libexec"
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/testball.rb | Library/Homebrew/test/support/fixtures/testball.rb | # typed: true
# frozen_string_literal: true
class Testball < Formula
def initialize(name = "testball", path = Pathname.new(__FILE__).expand_path, spec = :stable,
alias_path: nil, tap: nil, force_bottle: false)
super
end
DSL_PROC = proc do
url "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz"
sha256 TESTBALL_SHA256
end.freeze
private_constant :DSL_PROC
DSL_PROC.call
def self.inherited(other)
super
other.instance_eval(&DSL_PROC)
end
def install
prefix.install "bin"
prefix.install "libexec"
Dir.chdir "doc"
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/testball_bottle_cellar.rb | Library/Homebrew/test/support/fixtures/testball_bottle_cellar.rb | # typed: true
# frozen_string_literal: true
class TestballBottleCellar < Formula
def initialize(name = "testball_bottle", path = Pathname.new(__FILE__).expand_path, spec = :stable,
alias_path: nil, tap: nil, force_bottle: false)
super
end
DSL_PROC = proc do
url "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz"
sha256 TESTBALL_SHA256
bottle do
root_url "file://#{TEST_FIXTURE_DIR}/bottles"
sha256 cellar: :any_skip_relocation, Utils::Bottles.tag.to_sym => "d7b9f4e8bf83608b71fe958a99f19f2e5e68bb2582965d32e41759c24f1aef97"
end
end.freeze
private_constant :DSL_PROC
DSL_PROC.call
def self.inherited(other)
super
other.instance_eval(&DSL_PROC)
end
def install
prefix.install "bin"
prefix.install "libexec"
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/failball_offline_install.rb | Library/Homebrew/test/support/fixtures/failball_offline_install.rb | # typed: true
# frozen_string_literal: true
class FailballOfflineInstall < Formula
def initialize(name = "failball_offline_install", path = Pathname.new(__FILE__).expand_path, spec = :stable,
alias_path: nil, tap: nil, force_bottle: false)
super
end
DSL_PROC = proc do
url "file://#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz"
sha256 TESTBALL_SHA256
deny_network_access! :build
end.freeze
private_constant :DSL_PROC
DSL_PROC.call
def self.inherited(other)
super
other.instance_eval(&DSL_PROC)
end
def install
system "curl", "example.org"
prefix.install "bin"
prefix.install "libexec"
Dir.chdir "doc"
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/auto-updates.rb | Library/Homebrew/test/support/fixtures/cask/Casks/auto-updates.rb | cask "auto-updates" do
version "2.61"
sha256 "5633c3a0f2e572cbf021507dec78c50998b398c343232bdfc7e26221d0a5db4d"
url "file://#{TEST_FIXTURE_DIR}/cask/MyFancyApp.zip"
name "Auto-Updates"
desc "Cask which auto-updates"
homepage "https://brew.sh/MyFancyApp"
auto_updates true
app "MyFancyApp/MyFancyApp.app"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/devmate-without-livecheck.rb | Library/Homebrew/test/support/fixtures/cask/Casks/devmate-without-livecheck.rb | cask "devmate-without-livecheck" do
version "1.0"
sha256 "a69e7357bea014f4c14ac9699274f559086844ffa46563c4619bf1addfd72ad9"
url "https://dl.devmate.com/com.my.fancyapp/app_#{version}.zip"
name "DevMate"
homepage "https://www.brew.sh/"
app "DevMate.app"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/will-fail-if-upgraded.rb | Library/Homebrew/test/support/fixtures/cask/Casks/will-fail-if-upgraded.rb | cask "will-fail-if-upgraded" do
version "1.2.3"
sha256 "5e96aeb365aa8fabd51bb0d85f5f2bfe0135d392bb2f4120aa6b8171415906da"
url "file://#{TEST_FIXTURE_DIR}/cask/transmission-2.61.zip"
homepage "https://brew.sh/"
app "container"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/sourceforge-with-livecheck.rb | Library/Homebrew/test/support/fixtures/cask/Casks/sourceforge-with-livecheck.rb | cask "sourceforge-with-livecheck" do
version "1.2.3"
url "https://downloads.sourceforge.net/something/Something-1.2.3.dmg"
homepage "https://sourceforge.net/projects/something/"
livecheck do
url "https://sourceforge.net/projects/something/rss"
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/pkg-without-uninstall.rb | Library/Homebrew/test/support/fixtures/cask/Casks/pkg-without-uninstall.rb | cask "pkg-without-uninstall" do
version "1.2.3"
sha256 "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
url "file://#{TEST_FIXTURE_DIR}/cask/MyFancyPkg.zip"
name "PKG without Uninstall"
desc "Cask with a package installer and no uninstall stanza"
homepage "https://brew.sh/fancy-pkg"
pkg "Fancy.pkg"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/test-opera-mail.rb | Library/Homebrew/test/support/fixtures/cask/Casks/test-opera-mail.rb | cask "test-opera-mail" do
version "1.0"
sha256 "afd192e308f8ea8ddb3d426fd6663d97078570417ee78b8e1fa15f515ae3d677"
url "https://get-ash-1.opera.com/pub/opera/mail/1.0/mac/Opera-Mail-1.0-1040.i386.dmg"
homepage "https://www.opera.com/computer/mail"
app "Opera Mail.app"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/missing-homepage.rb | Library/Homebrew/test/support/fixtures/cask/Casks/missing-homepage.rb | cask "missing-homepage" do
version "1.2.3"
url "https://localhost/something.dmg"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/generic-artifact-user-relative-target.rb | Library/Homebrew/test/support/fixtures/cask/Casks/generic-artifact-user-relative-target.rb | cask "generic-artifact-user-relative-target" do
version "1.2.3"
sha256 "d5b2dfbef7ea28c25f7a77cd7fa14d013d82b626db1d82e00e25822464ba19e2"
url "file://#{TEST_FIXTURE_DIR}/cask/AppWithBinary.zip"
name "With Binary"
desc "Cask with a binary stanza"
homepage "https://brew.sh/with-binary"
artifact "Caffeine.app", target: "~/Desktop/Caffeine.app"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/with-uninstall-signal-on-upgrade.rb | Library/Homebrew/test/support/fixtures/cask/Casks/with-uninstall-signal-on-upgrade.rb | cask "with-uninstall-signal-on-upgrade" do
version "1.2.3"
sha256 "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
url "file://#{TEST_FIXTURE_DIR}/cask/MyFancyPkg.zip"
homepage "https://brew.sh/fancy-pkg"
pkg "MyFancyPkg/Fancy.pkg"
uninstall signal: [
["TERM", "my.fancy.package.app"],
["KILL", "my.fancy.package.app"],
],
on_upgrade: :signal
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/many-renames.rb | Library/Homebrew/test/support/fixtures/cask/Casks/many-renames.rb | cask "many-renames" do
version "1.2.3"
sha256 "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
url "file://#{TEST_FIXTURE_DIR}/cask/ManyArtifacts.zip"
homepage "https://brew.sh/many-artifacts"
rename "Foobar.app", "Foo.app"
rename "Foo.app", "Bar.app"
app "Bar.app"
preflight do
# do nothing
end
postflight do
# do nothing
end
uninstall_preflight do
# do nothing
end
uninstall_postflight do
# do nothing
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/with-uninstall-postflight.rb | Library/Homebrew/test/support/fixtures/cask/Casks/with-uninstall-postflight.rb | cask "with-uninstall-postflight" do
version "1.2.3"
sha256 "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
url "file://#{TEST_FIXTURE_DIR}/cask/MyFancyPkg.zip"
homepage "https://brew.sh/fancy-pkg"
pkg "MyFancyPkg/Fancy.pkg"
uninstall_postflight do
# do nothing
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/with-postflight.rb | Library/Homebrew/test/support/fixtures/cask/Casks/with-postflight.rb | cask "with-postflight" do
version "1.2.3"
sha256 "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
url "file://#{TEST_FIXTURE_DIR}/cask/MyFancyPkg.zip"
homepage "https://brew.sh/fancy-pkg"
pkg "MyFancyPkg/Fancy.pkg"
postflight do
# do nothing
end
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/latest-with-livecheck.rb | Library/Homebrew/test/support/fixtures/cask/Casks/latest-with-livecheck.rb | cask "latest-with-livecheck" do
version :latest
sha256 :no_check
url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip"
homepage "https://brew.sh/with-livecheck"
livecheck do
url "https://brew.sh/with-livecheck/changelog"
end
app "Caffeine.app"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/appdir-interpolation.rb | Library/Homebrew/test/support/fixtures/cask/Casks/appdir-interpolation.rb | cask "appdir-interpolation" do
version "2.61"
sha256 "e44ffa103fbf83f55c8d0b1bea309a43b2880798dae8620b1ee8da5e1095ec68"
url "file://#{TEST_FIXTURE_DIR}/cask/transmission-2.61.dmg"
homepage "https://brew.sh/appdir-interpolation"
binary "#{appdir}/some/path"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/version-latest-string.rb | Library/Homebrew/test/support/fixtures/cask/Casks/version-latest-string.rb | cask "version-latest-string" do
version "latest"
sha256 :no_check
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/many-artifacts.rb | Library/Homebrew/test/support/fixtures/cask/Casks/many-artifacts.rb | cask "many-artifacts" do
version "1.2.3"
sha256 "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
url "file://#{TEST_FIXTURE_DIR}/cask/ManyArtifacts.zip"
homepage "https://brew.sh/many-artifacts"
app "ManyArtifacts/ManyArtifacts.app"
pkg "ManyArtifacts/ManyArtifacts.pkg"
preflight do
# do nothing
end
postflight do
# do nothing
end
uninstall_preflight do
# do nothing
end
uninstall_postflight do
# do nothing
end
uninstall trash: ["#{TEST_TMPDIR}/foo", "#{TEST_TMPDIR}/bar"],
rmdir: "#{TEST_TMPDIR}/empty_directory_path"
zap trash: "~/Library/Logs/ManyArtifacts.log",
rmdir: ["~/Library/Caches/ManyArtifacts", "~/Library/Application Support/ManyArtifacts"]
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/with-depends-on-cask-multiple.rb | Library/Homebrew/test/support/fixtures/cask/Casks/with-depends-on-cask-multiple.rb | cask "with-depends-on-cask-multiple" do
version "1.2.3"
sha256 "67cdb8a02803ef37fdbf7e0be205863172e41a561ca446cd84f0d7ab35a99d94"
url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip"
homepage "https://brew.sh/with-depends-on-cask-multiple"
depends_on cask: "local-caffeine"
depends_on cask: "local-transmission-zip"
app "Caffeine.app"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/hockeyapp-without-livecheck.rb | Library/Homebrew/test/support/fixtures/cask/Casks/hockeyapp-without-livecheck.rb | cask "hockeyapp-without-livecheck" do
version "1.0,123"
sha256 "a69e7357bea014f4c14ac9699274f559086844ffa46563c4619bf1addfd72ad9"
url "https://rink.hockeyapp.net/api/2/apps/67503a7926431872c4b6c1549f5bd6b1/app_versions/#{version.csv.second}?format=zip"
name "HockeyApp"
homepage "https://www.brew.sh/"
app "HockeyApp.app"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/with-installer-manual.rb | Library/Homebrew/test/support/fixtures/cask/Casks/with-installer-manual.rb | cask "with-installer-manual" do
version "1.2.3"
sha256 "67cdb8a02803ef37fdbf7e0be205863172e41a561ca446cd84f0d7ab35a99d94"
url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip"
name "With Installer Manual"
desc "Cask with a manual installer"
homepage "https://brew.sh/"
installer manual: "Caffeine.app"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/invalid-sha256.rb | Library/Homebrew/test/support/fixtures/cask/Casks/invalid-sha256.rb | cask "invalid-sha256" do
version "1.2.3"
sha256 "not a valid shasum"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/container-xar.rb | Library/Homebrew/test/support/fixtures/cask/Casks/container-xar.rb | cask "container-xar" do
version "1.2.3"
sha256 "5bb8e09a6fc630ebeaf266b1fd2d15e2ae7d32d7e4da6668a8093426fa1ba509"
url "file://#{TEST_FIXTURE_DIR}/cask/container.xar"
homepage "https://brew.sh/container-xar"
app "container"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/container-tar-gz.rb | Library/Homebrew/test/support/fixtures/cask/Casks/container-tar-gz.rb | cask "container-tar-gz" do
version "1.2.3"
sha256 "fab685fabf73d5a9382581ce8698fce9408f5feaa49fa10d9bc6c510493300f5"
url "file://#{TEST_FIXTURE_DIR}/cask/container.tar.gz"
homepage "https://brew.sh/container-tar-gz"
app "container"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/with-uninstall-quit-on-upgrade.rb | Library/Homebrew/test/support/fixtures/cask/Casks/with-uninstall-quit-on-upgrade.rb | cask "with-uninstall-quit-on-upgrade" do
version "1.2.3"
sha256 "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
url "file://#{TEST_FIXTURE_DIR}/cask/MyFancyPkg.zip"
homepage "https://brew.sh/fancy-pkg"
pkg "MyFancyPkg/Fancy.pkg"
uninstall quit: "my.fancy.package.app",
on_upgrade: :quit
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/with-depends-on-macos-symbol.rb | Library/Homebrew/test/support/fixtures/cask/Casks/with-depends-on-macos-symbol.rb | cask "with-depends-on-macos-symbol" do
version "1.2.3"
sha256 "67cdb8a02803ef37fdbf7e0be205863172e41a561ca446cd84f0d7ab35a99d94"
url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip"
homepage "https://brew.sh/with-depends-on-macos-symbol"
depends_on macos: MacOS.version.to_sym
app "Caffeine.app"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/sha256-for-empty-string.rb | Library/Homebrew/test/support/fixtures/cask/Casks/sha256-for-empty-string.rb | cask "sha256-for-empty-string" do
version "1.2.3"
sha256 "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/missing-checksum.rb | Library/Homebrew/test/support/fixtures/cask/Casks/missing-checksum.rb | cask "missing-checksum" do
version "1.2.3"
url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip"
homepage "https://brew.sh/"
app "Caffeine.app"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/with-uninstall-launchctl.rb | Library/Homebrew/test/support/fixtures/cask/Casks/with-uninstall-launchctl.rb | cask "with-uninstall-launchctl" do
version "1.2.3"
sha256 "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
url "file://#{TEST_FIXTURE_DIR}/cask/MyFancyApp.zip"
homepage "https://brew.sh/fancy"
app "Fancy.app"
uninstall launchctl: "my.fancy.package.service"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/container-apfs-dmg.rb | Library/Homebrew/test/support/fixtures/cask/Casks/container-apfs-dmg.rb | cask "container-apfs-dmg" do
version "1.2.3"
sha256 "0630aa1145e8c3fa77aeb6ec414fee35204e90f224d6d06cb23e18a4d6112a5d"
url "file://#{TEST_FIXTURE_DIR}/cask/container-apfs.dmg"
homepage "https://brew.sh/container-apfs-dmg"
app "container"
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/support/fixtures/cask/Casks/with-uninstall-early-script.rb | Library/Homebrew/test/support/fixtures/cask/Casks/with-uninstall-early-script.rb | cask "with-uninstall-early-script" do
version "1.2.3"
sha256 "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
url "file://#{TEST_FIXTURE_DIR}/cask/MyFancyPkg.zip"
homepage "https://brew.sh/fancy-pkg"
pkg "MyFancyPkg/Fancy.pkg"
uninstall early_script: { executable: "MyFancyPkg/FancyUninstaller.tool", args: ["--please"] }
end
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.