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/dev-cmd/update-perl-resources_spec.rb | Library/Homebrew/test/dev-cmd/update-perl-resources_spec.rb | # frozen_string_literal: true
require "cmd/shared_examples/args_parse"
require "dev-cmd/update-perl-resources"
RSpec.describe Homebrew::DevCmd::UpdatePerlResources do
it_behaves_like "parseable arguments"
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/dev-cmd/audit_spec.rb | Library/Homebrew/test/dev-cmd/audit_spec.rb | # frozen_string_literal: true
require "dev-cmd/audit"
require "cmd/shared_examples/args_parse"
RSpec.describe Homebrew::DevCmd::Audit do
it_behaves_like "parseable arguments"
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/dev-cmd/bump-revision_spec.rb | Library/Homebrew/test/dev-cmd/bump-revision_spec.rb | # frozen_string_literal: true
require "cmd/shared_examples/args_parse"
require "dev-cmd/bump-revision"
RSpec.describe Homebrew::DevCmd::BumpRevision do
it_behaves_like "parseable arguments"
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/dev-cmd/extract_spec.rb | Library/Homebrew/test/dev-cmd/extract_spec.rb | # frozen_string_literal: true
require "cmd/shared_examples/args_parse"
require "dev-cmd/extract"
RSpec.describe Homebrew::DevCmd::Extract do
it_behaves_like "parseable arguments"
context "when extracting a formula" do
let!(:target) do
path = HOMEBREW_TAP_DIRECTORY/"homebrew/homebrew-foo"
(path/"Formula").mkpath
target = Tap.from_path(path)
core_tap = CoreTap.instance
core_tap.path.cd do
system "git", "init"
# Start with deprecated bottle syntax
setup_test_formula "testball", bottle_block: <<~EOS
bottle do
cellar :any
end
EOS
system "git", "add", "--all"
system "git", "commit", "-m", "testball 0.1"
# Replace with a valid formula for the next version
formula_file = setup_test_formula "testball"
contents = File.read(formula_file)
contents.gsub!("testball-0.1", "testball-0.2")
File.write(formula_file, contents)
system "git", "add", "--all"
system "git", "commit", "-m", "testball 0.2"
end
{ name: target.name, path: }
end
it "retrieves the most recent version of formula", :integration_test do
path = target[:path]/"Formula/testball@0.2.rb"
expect { brew "extract", "testball", target[:name] }
.to output(/^#{path}$/).to_stdout
.and not_to_output.to_stderr
.and be_a_success
expect(path).to exist
expect(Formulary.factory(path).version).to eq "0.2"
end
it "retrieves the specified version of formula", :integration_test do
path = target[:path]/"Formula/testball@0.1.rb"
expect { brew "extract", "testball", target[:name], "--version=0.1" }
.to output(/^#{path}$/).to_stdout
.and not_to_output.to_stderr
.and be_a_success
expect(path).to exist
expect(Formulary.factory(path).version).to eq "0.1"
end
it "retrieves the compatible version of formula", :integration_test do
path = target[:path]/"Formula/testball@0.rb"
expect { brew "extract", "testball", target[:name], "--version=0" }
.to output(/^#{path}$/).to_stdout
.and not_to_output.to_stderr
.and be_a_success
expect(path).to exist
expect(Formulary.factory(path).version).to eq "0.2"
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/dev-cmd/vendor-gems_spec.rb | Library/Homebrew/test/dev-cmd/vendor-gems_spec.rb | # frozen_string_literal: true
require "cmd/shared_examples/args_parse"
require "dev-cmd/vendor-gems"
RSpec.describe Homebrew::DevCmd::VendorGems do
it_behaves_like "parseable arguments"
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/dev-cmd/determine-test-runners_spec.rb | Library/Homebrew/test/dev-cmd/determine-test-runners_spec.rb | # frozen_string_literal: true
require "dev-cmd/determine-test-runners"
require "cmd/shared_examples/args_parse"
RSpec.describe Homebrew::DevCmd::DetermineTestRunners do
def get_runners(file)
runner_line = File.open(file).first
json_text = runner_line[/runners=(.*)/, 1]
runner_hash = JSON.parse(json_text)
runner_hash.map { |item| item["runner"].delete_suffix(ephemeral_suffix) }
.sort
end
after do
FileUtils.rm_f github_output
end
let(:linux_runner) { "ubuntu-22.04" }
# We need to make sure we write to a different path for each example.
let(:github_output) { "#{TEST_TMPDIR}/github_output#{DetermineRunnerTestHelper.new.number}" }
let(:ephemeral_suffix) { "-12345" }
let(:runner_env) do
{
"HOMEBREW_LINUX_RUNNER" => linux_runner,
"HOMEBREW_MACOS_LONG_TIMEOUT" => "false",
"GITHUB_RUN_ID" => ephemeral_suffix.split("-").second,
}.freeze
end
let(:all_runners) do
out = []
MacOSVersion::SYMBOLS.each_value do |v|
macos_version = MacOSVersion.new(v)
next if macos_version < GitHubRunnerMatrix::OLDEST_HOMEBREW_CORE_MACOS_RUNNER
next if macos_version > GitHubRunnerMatrix::NEWEST_HOMEBREW_CORE_MACOS_RUNNER
out << "#{v}-arm64"
next if macos_version > GitHubRunnerMatrix::NEWEST_HOMEBREW_CORE_INTEL_MACOS_RUNNER
out << "#{v}-x86_64"
end
out << linux_runner
out << "#{linux_runner}-arm"
out
end
it_behaves_like "parseable arguments"
it "assigns all runners for formulae without any requirements", :integration_test do
setup_test_formula "testball"
expect { brew "determine-test-runners", "testball", runner_env.merge({ "GITHUB_OUTPUT" => github_output }) }
.to not_to_output.to_stderr
.and be_a_success
expect(File.read(github_output)).not_to be_empty
expect(get_runners(github_output).sort).to eq(all_runners.sort)
end
end
class DetermineRunnerTestHelper
@instances = 0
class << self
attr_accessor :instances
end
attr_reader :number
def initialize
self.class.instances += 1
@number = self.class.instances
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/dev-cmd/pr-publish_spec.rb | Library/Homebrew/test/dev-cmd/pr-publish_spec.rb | # frozen_string_literal: true
require "cmd/shared_examples/args_parse"
require "dev-cmd/pr-publish"
RSpec.describe Homebrew::DevCmd::PrPublish do
it_behaves_like "parseable arguments"
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/dev-cmd/formula-analytics_spec.rb | Library/Homebrew/test/dev-cmd/formula-analytics_spec.rb | # frozen_string_literal: true
require "cmd/shared_examples/args_parse"
require "dev-cmd/formula-analytics"
RSpec.describe Homebrew::DevCmd::FormulaAnalytics do
it_behaves_like "parseable arguments"
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/dev-cmd/edit_spec.rb | Library/Homebrew/test/dev-cmd/edit_spec.rb | # frozen_string_literal: true
require "cmd/shared_examples/args_parse"
require "dev-cmd/edit"
RSpec.describe Homebrew::DevCmd::Edit do
it_behaves_like "parseable arguments"
it "opens a given Formula in an editor", :integration_test do
HOMEBREW_REPOSITORY.cd do
system "git", "init"
end
setup_test_formula "testball"
expect { brew "edit", "testball", "HOMEBREW_EDITOR" => "/bin/cat", "HOMEBREW_NO_ENV_HINTS" => "1" }
.to output(/# something here/).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/dev-cmd/unbottled_spec.rb | Library/Homebrew/test/dev-cmd/unbottled_spec.rb | # frozen_string_literal: true
require "cmd/shared_examples/args_parse"
require "dev-cmd/unbottled"
RSpec.describe Homebrew::DevCmd::Unbottled do
it_behaves_like "parseable arguments"
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/dev-cmd/pr-upload_spec.rb | Library/Homebrew/test/dev-cmd/pr-upload_spec.rb | # frozen_string_literal: true
require "cmd/shared_examples/args_parse"
require "dev-cmd/pr-upload"
RSpec.describe Homebrew::DevCmd::PrUpload do
it_behaves_like "parseable arguments"
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/dev-cmd/release_spec.rb | Library/Homebrew/test/dev-cmd/release_spec.rb | # frozen_string_literal: true
require "cmd/shared_examples/args_parse"
require "dev-cmd/release"
RSpec.describe Homebrew::DevCmd::Release do
it_behaves_like "parseable arguments"
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/dev-cmd/lgtm_spec.rb | Library/Homebrew/test/dev-cmd/lgtm_spec.rb | # frozen_string_literal: true
require "cmd/shared_examples/args_parse"
require "dev-cmd/lgtm"
RSpec.describe Homebrew::DevCmd::Lgtm do
it_behaves_like "parseable arguments"
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/dev-cmd/cat_spec.rb | Library/Homebrew/test/dev-cmd/cat_spec.rb | # frozen_string_literal: true
require "cmd/shared_examples/args_parse"
require "dev-cmd/cat"
RSpec.describe Homebrew::DevCmd::Cat do
it_behaves_like "parseable arguments"
it "prints the content of a given Formula", :integration_test do
formula_file = setup_test_formula "testball"
content = formula_file.read
expect { brew "cat", "testball" }
.to output(content).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/dev-cmd/bump_spec.rb | Library/Homebrew/test/dev-cmd/bump_spec.rb | # frozen_string_literal: true
require "cmd/shared_examples/args_parse"
require "dev-cmd/bump"
RSpec.describe Homebrew::DevCmd::Bump do
it_behaves_like "parseable arguments"
describe "formula", :integration_test, :needs_homebrew_curl, :needs_network do
it "returns no data and prints a message for HEAD-only formulae" do
content = <<~RUBY
desc "HEAD-only test formula"
homepage "https://brew.sh"
head "https://github.com/Homebrew/brew.git", branch: "main"
RUBY
setup_test_formula("headonly", content)
expect { brew "bump", "headonly" }
.to output(/Formula is HEAD-only./).to_stdout
.and not_to_output.to_stderr
.and be_a_success
end
end
it "gives an error for `--tap` with official taps", :integration_test do
expect { brew "bump", "--tap", "Homebrew/core" }
.to output(/Invalid usage/).to_stderr
.and not_to_output.to_stdout
.and be_a_failure
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/dev-cmd/install-bundler-gems_spec.rb | Library/Homebrew/test/dev-cmd/install-bundler-gems_spec.rb | # frozen_string_literal: true
require "cmd/shared_examples/args_parse"
require "dev-cmd/install-bundler-gems"
RSpec.describe Homebrew::DevCmd::InstallBundlerGems do
it_behaves_like "parseable arguments"
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/dev-cmd/test_spec.rb | Library/Homebrew/test/dev-cmd/test_spec.rb | # frozen_string_literal: true
require "cmd/shared_examples/args_parse"
require "dev-cmd/test"
require "sandbox"
RSpec.describe Homebrew::DevCmd::Test do
it_behaves_like "parseable arguments"
it "tests a given Formula", :integration_test do
install_test_formula "testball", <<~'RUBY'
test do
assert_equal "test", shell_output("#{bin}/test")
end
RUBY
expect { brew "test", "--verbose", "testball" }
.to output(/Testing testball/).to_stdout
.and not_to_output.to_stderr
.and be_a_success
end
it "blocks network access when test phase is offline", :integration_test do
if Sandbox.available?
install_test_formula "testball_offline_test", <<~RUBY
deny_network_access! :test
test do
system "curl", "example.org"
end
RUBY
expect { brew "test", "--verbose", "testball_offline_test" }
.to output(/curl: \(6\) Could not resolve host: example\.org/).to_stdout
.and be_a_failure
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/hardware/cpu_spec.rb | Library/Homebrew/test/hardware/cpu_spec.rb | # frozen_string_literal: true
require "hardware"
RSpec.describe Hardware::CPU do
describe "::type" do
let(:cpu_types) do
[
:arm,
:intel,
:ppc,
:dunno,
]
end
it "returns the current CPU's type as a symbol, or :dunno if it cannot be detected" do
expect(cpu_types).to include(described_class.type)
end
end
describe "::family" do
let(:cpu_families) do
[
:alderlake,
:amd_k7,
:amd_k8,
:amd_k8_k10_hybrid,
:amd_k10,
:amd_k10_llano,
:arm,
:arm_blizzard_avalanche,
:arm_brava,
:arm_donan,
:arm_firestorm_icestorm,
:arm_hurricane_zephyr,
:arm_ibiza,
:arm_lightning_thunder,
:arm_lobos,
:arm_monsoon_mistral,
:arm_palma,
:arm_twister,
:arm_typhoon,
:arm_vortex_tempest,
:arrowlake,
:atom,
:bobcat,
:broadwell,
:bulldozer,
:cannonlake,
:cometlake,
:core,
:core2,
:dothan,
:graniterapids,
:haswell,
:icelake,
:ivybridge,
:jaguar,
:kabylake,
:merom,
:nehalem,
:pantherlake,
:penryn,
:ppc,
:prescott,
:presler,
:rocketlake,
:sandybridge,
:sapphirerapids,
:skylake,
:tigerlake,
:westmere,
:zen,
:zen2,
:zen3,
:zen4,
:zen5,
:dunno,
]
end
it "returns the current CPU's family name as a symbol, or :dunno if it cannot be detected" do
expect(cpu_families).to include described_class.family
end
context "when hw.cpufamily is 0x573b5eec on a Mac", :needs_macos do
before do
allow(described_class)
.to receive(:sysctl_int)
.with("hw.cpufamily")
.and_return(0x573b5eec)
end
it "returns :arm_firestorm_icestorm on ARM" do
allow(described_class).to receive_messages(arm?: true, intel?: false)
expect(described_class.family).to eq(:arm_firestorm_icestorm)
end
it "returns :westmere on Intel" do
allow(described_class).to receive_messages(arm?: false, intel?: true)
expect(described_class.family).to eq(:westmere)
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/cask/macos_spec.rb | Library/Homebrew/test/cask/macos_spec.rb | # frozen_string_literal: true
RSpec.describe MacOS, :cask do
it "says '/' is undeletable" do
expect(described_class).to be_undeletable(
"/",
)
expect(described_class).to be_undeletable(
"/.",
)
expect(described_class).to be_undeletable(
"/usr/local/Library/Taps/../../../..",
)
end
it "says '/Applications' is undeletable" do # rubocop:todo RSpec/AggregateExamples
expect(described_class).to be_undeletable(
"/Applications",
)
expect(described_class).to be_undeletable(
"/Applications/",
)
expect(described_class).to be_undeletable(
"/Applications/.",
)
expect(described_class).to be_undeletable(
"/Applications/Mail.app/..",
)
end
it "says the home directory is undeletable" do # rubocop:todo RSpec/AggregateExamples
expect(described_class).to be_undeletable(
Dir.home,
)
expect(described_class).to be_undeletable(
"#{Dir.home}/",
)
expect(described_class).to be_undeletable(
"#{Dir.home}/Documents/..",
)
end
it "says the user library directory is undeletable" do # rubocop:todo RSpec/AggregateExamples
expect(described_class).to be_undeletable(
"#{Dir.home}/Library",
)
expect(described_class).to be_undeletable(
"#{Dir.home}/Library/",
)
expect(described_class).to be_undeletable(
"#{Dir.home}/Library/.",
)
expect(described_class).to be_undeletable(
"#{Dir.home}/Library/Preferences/..",
)
end
it "says '/Applications/.app' is deletable" do # rubocop:todo RSpec/AggregateExamples
expect(described_class).not_to be_undeletable(
"/Applications/.app",
)
end
it "says '/Applications/SnakeOil Professional.app' is deletable" do # rubocop:todo RSpec/AggregateExamples
expect(described_class).not_to be_undeletable(
"/Applications/SnakeOil Professional.app",
)
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/cask/cask_spec.rb | Library/Homebrew/test/cask/cask_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Cask, :cask do
let(:cask) { described_class.new("versioned-cask") }
context "when multiple versions are installed" do
describe "#installed_version" do
context "when there are duplicate versions" do
it "uses the last unique version" do
allow(cask).to receive(:timestamped_versions).and_return([
["1.2.2", "0999"],
["1.2.3", "1000"],
["1.2.2", "1001"],
])
# Installed caskfile must exist to count as installed.
allow_any_instance_of(Pathname).to receive(:exist?).and_return(true)
expect(cask).to receive(:timestamped_versions)
expect(cask.installed_version).to eq("1.2.2")
end
end
end
end
describe "load" do
let(:tap_path) { CoreCaskTap.instance.path }
let(:file_dirname) { Pathname.new(__FILE__).dirname }
let(:relative_tap_path) { tap_path.relative_path_from(file_dirname) }
it "returns an instance of the Cask for the given token" do
c = Cask::CaskLoader.load("local-caffeine")
expect(c).to be_a(described_class)
expect(c.token).to eq("local-caffeine")
end
it "returns an instance of the Cask from a specific file location" do
c = Cask::CaskLoader.load("#{tap_path}/Casks/local-caffeine.rb")
expect(c).to be_a(described_class)
expect(c.token).to eq("local-caffeine")
end
it "returns an instance of the Cask from a JSON file" do
c = Cask::CaskLoader.load("#{TEST_FIXTURE_DIR}/cask/caffeine.json")
expect(c).to be_a(described_class)
expect(c.token).to eq("caffeine")
end
it "returns an instance of the Cask from a URL", :needs_utils_curl do
c = Cask::CaskLoader.load("file://#{tap_path}/Casks/local-caffeine.rb")
expect(c).to be_a(described_class)
expect(c.token).to eq("local-caffeine")
end
it "raises an error when failing to download a Cask from a URL", :needs_utils_curl do
expect do
Cask::CaskLoader.load("file://#{tap_path}/Casks/notacask.rb")
end.to raise_error(Cask::CaskUnavailableError)
end
it "returns an instance of the Cask from a relative file location" do
c = Cask::CaskLoader.load(relative_tap_path/"Casks/local-caffeine.rb")
expect(c).to be_a(described_class)
expect(c.token).to eq("local-caffeine")
end
it "uses exact match when loading by token" do
expect(Cask::CaskLoader.load("test-opera").token).to eq("test-opera")
expect(Cask::CaskLoader.load("test-opera-mail").token).to eq("test-opera-mail")
end
it "raises an error when attempting to load a Cask that doesn't exist" do
expect do
Cask::CaskLoader.load("notacask")
end.to raise_error(Cask::CaskUnavailableError)
end
end
describe "metadata" do
it "proposes a versioned metadata directory name for each instance" do
cask_token = "local-caffeine"
c = Cask::CaskLoader.load(cask_token)
metadata_timestamped_path = Cask::Caskroom.path.join(cask_token, ".metadata", c.version)
expect(c.metadata_versioned_path.to_s).to eq(metadata_timestamped_path.to_s)
end
end
describe "outdated" do
it "ignores the Casks that have auto_updates true (without --greedy)" do
c = Cask::CaskLoader.load("auto-updates")
expect(c).not_to be_outdated
expect(c.outdated_version).to be_nil
end
it "ignores the Casks that have version :latest (without --greedy)" do
c = Cask::CaskLoader.load("version-latest-string")
expect(c).not_to be_outdated
expect(c.outdated_version).to be_nil
end
describe "versioned casks" do
subject { cask.outdated_version }
let(:cask) { described_class.new("basic-cask") }
shared_examples "versioned casks" do |tap_version, expectations|
expectations.each do |installed_version, expected_output|
context "when version #{installed_version.inspect} is installed and the tap version is #{tap_version}" do
it {
allow(cask).to receive_messages(installed_version:,
version: Cask::DSL::Version.new(tap_version))
expect(cask).to receive(:outdated_version).and_call_original
expect(subject).to eq expected_output
}
end
end
end
describe "installed version is equal to tap version => not outdated" do
include_examples "versioned casks", "1.2.3",
"1.2.3" => nil
end
describe "installed version is different than tap version => outdated" do
include_examples "versioned casks", "1.2.4",
"1.2.3" => "1.2.3",
"1.2.4" => nil
end
end
describe ":latest casks" do
let(:cask) { described_class.new("basic-cask") }
shared_examples ":latest cask" do |greedy, outdated_sha, tap_version, expectations|
expectations.each do |installed_version, expected_output|
context "when versions #{installed_version} are installed and the " \
"tap version is #{tap_version}, #{"not " unless greedy}greedy " \
"and sha is #{"not " unless outdated_sha}outdated" do
subject { cask.outdated_version(greedy:) }
it {
allow(cask).to receive_messages(installed_version:,
version: Cask::DSL::Version.new(tap_version),
outdated_download_sha?: outdated_sha)
expect(cask).to receive(:outdated_version).and_call_original
expect(subject).to eq expected_output
}
end
end
end
describe ":latest version installed, :latest version in tap" do
include_examples ":latest cask", false, false, "latest",
"latest" => nil
include_examples ":latest cask", true, false, "latest",
"latest" => nil
include_examples ":latest cask", true, true, "latest",
"latest" => "latest"
end
describe "numbered version installed, :latest version in tap" do
include_examples ":latest cask", false, false, "latest",
"1.2.3" => nil
include_examples ":latest cask", true, false, "latest",
"1.2.3" => nil
include_examples ":latest cask", true, true, "latest",
"1.2.3" => "1.2.3"
end
describe "latest version installed, numbered version in tap" do
include_examples ":latest cask", false, false, "1.2.3",
"latest" => "latest"
include_examples ":latest cask", true, false, "1.2.3",
"latest" => "latest"
include_examples ":latest cask", true, true, "1.2.3",
"latest" => "latest"
end
end
end
describe "full_name" do
context "when it is a core cask" do
it "is the cask token" do
c = Cask::CaskLoader.load("local-caffeine")
expect(c.full_name).to eq("local-caffeine")
end
end
context "when it is from a non-core tap" do
it "returns the fully-qualified name of the cask" do
c = Cask::CaskLoader.load("third-party/tap/third-party-cask")
expect(c.full_name).to eq("third-party/tap/third-party-cask")
end
end
context "when it is from no known tap" do
it "returns the cask token" do
file = Tempfile.new(%w[tapless-cask .rb])
begin
cask_name = File.basename(file.path, ".rb")
file.write "cask '#{cask_name}'"
file.close
c = Cask::CaskLoader.load(file.path)
expect(c.full_name).to eq(cask_name)
ensure
file.close
file.unlink
end
end
end
end
describe "#artifacts_list" do
subject(:cask) { Cask::CaskLoader.load("many-artifacts") }
it "returns all artifacts when no options are given" do
expected_artifacts = [
{ uninstall_preflight: nil },
{ preflight: nil },
{ uninstall: [{
rmdir: "#{TEST_TMPDIR}/empty_directory_path",
trash: ["#{TEST_TMPDIR}/foo", "#{TEST_TMPDIR}/bar"],
}] },
{ pkg: ["ManyArtifacts/ManyArtifacts.pkg"] },
{ app: ["ManyArtifacts/ManyArtifacts.app"] },
{ uninstall_postflight: nil },
{ postflight: nil },
{ zap: [{
rmdir: ["~/Library/Caches/ManyArtifacts", "~/Library/Application Support/ManyArtifacts"],
trash: "~/Library/Logs/ManyArtifacts.log",
}] },
]
expect(cask.artifacts_list).to eq(expected_artifacts)
end
it "returns only uninstall artifacts when uninstall_only is true" do
expected_artifacts = [
{ uninstall_preflight: nil },
{ uninstall: [{
rmdir: "#{TEST_TMPDIR}/empty_directory_path",
trash: ["#{TEST_TMPDIR}/foo", "#{TEST_TMPDIR}/bar"],
}] },
{ app: ["ManyArtifacts/ManyArtifacts.app"] },
{ uninstall_postflight: nil },
{ zap: [{
rmdir: ["~/Library/Caches/ManyArtifacts", "~/Library/Application Support/ManyArtifacts"],
trash: "~/Library/Logs/ManyArtifacts.log",
}] },
]
expect(cask.artifacts_list(uninstall_only: true)).to eq(expected_artifacts)
end
end
describe "#rename_list" do
subject(:cask) { Cask::CaskLoader.load("many-renames") }
it "returns the correct rename list" do
expect(cask.rename_list).to eq([
{ from: "Foobar.app", to: "Foo.app" },
{ from: "Foo.app", to: "Bar.app" },
])
end
end
describe "#uninstall_flight_blocks?" do
matcher :have_uninstall_flight_blocks do
match do |actual|
actual.uninstall_flight_blocks? == true
end
end
it "returns true when there are uninstall_preflight blocks" do
cask = Cask::CaskLoader.load("with-uninstall-preflight")
expect(cask).to have_uninstall_flight_blocks
end
it "returns true when there are uninstall_postflight blocks" do
cask = Cask::CaskLoader.load("with-uninstall-postflight")
expect(cask).to have_uninstall_flight_blocks
end
it "returns false when there are only preflight blocks" do
cask = Cask::CaskLoader.load("with-preflight")
expect(cask).not_to have_uninstall_flight_blocks
end
it "returns false when there are only postflight blocks" do
cask = Cask::CaskLoader.load("with-postflight")
expect(cask).not_to have_uninstall_flight_blocks
end
it "returns false when there are no flight blocks" do
cask = Cask::CaskLoader.load("local-caffeine")
expect(cask).not_to have_uninstall_flight_blocks
end
end
describe "#to_h" do
let(:expected_json) { (TEST_FIXTURE_DIR/"cask/everything.json").read.strip }
context "when loaded from cask file" do
it "returns expected hash" do
allow(MacOS).to receive(:version).and_return(MacOSVersion.new("14"))
cask = Cask::CaskLoader.load("everything")
expect(cask.tap).to receive(:git_head).and_return("abcdef1234567890abcdef1234567890abcdef12")
hash = cask.to_h
expect(hash).to be_a(Hash)
expect(JSON.pretty_generate(hash)).to eq(expected_json)
end
end
context "when loaded from json file" do
it "returns expected hash" do
expect(Homebrew::API::Cask).not_to receive(:source_download)
hash = Cask::CaskLoader::FromAPILoader.new(
"everything", from_json: JSON.parse(expected_json)
).load(config: nil).to_h
expect(hash).to be_a(Hash)
expect(JSON.pretty_generate(hash)).to eq(expected_json)
end
end
end
describe "#to_hash_with_variations" do
let!(:original_macos_version) { MacOS.full_version.to_s }
let(:expected_versions_variations) do
<<~JSON
{
"tahoe": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine/darwin/1.2.3/intel.zip"
},
"sequoia": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine/darwin/1.2.3/intel.zip"
},
"sonoma": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine/darwin/1.2.3/intel.zip"
},
"ventura": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine/darwin/1.2.3/intel.zip"
},
"monterey": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine/darwin/1.2.3/intel.zip"
},
"big_sur": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine/darwin/1.2.0/intel.zip",
"version": "1.2.0",
"sha256": "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
},
"arm64_big_sur": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine/darwin-arm64/1.2.0/arm.zip",
"version": "1.2.0",
"sha256": "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
},
"catalina": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine/darwin/1.0.0/intel.zip",
"version": "1.0.0",
"sha256": "1866dfa833b123bb8fe7fa7185ebf24d28d300d0643d75798bc23730af734216"
}
}
JSON
end
let(:expected_sha256_variations) do
<<~JSON
{
"tahoe": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine-intel.zip",
"sha256": "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
},
"sequoia": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine-intel.zip",
"sha256": "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
},
"sonoma": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine-intel.zip",
"sha256": "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
},
"ventura": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine-intel.zip",
"sha256": "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
},
"monterey": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine-intel.zip",
"sha256": "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
},
"big_sur": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine-intel.zip",
"sha256": "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
},
"catalina": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine-intel.zip",
"sha256": "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
}
}
JSON
end
let(:expected_sha256_variations_os) do
<<~JSON
{
"tahoe": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine-intel-darwin.zip",
"sha256": "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
},
"sequoia": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine-intel-darwin.zip",
"sha256": "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
},
"sonoma": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine-intel-darwin.zip",
"sha256": "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
},
"ventura": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine-intel-darwin.zip",
"sha256": "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
},
"monterey": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine-intel-darwin.zip",
"sha256": "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
},
"big_sur": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine-intel-darwin.zip",
"sha256": "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
},
"catalina": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine-intel-darwin.zip",
"sha256": "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
},
"x86_64_linux": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine-intel-linux.zip",
"sha256": "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"
},
"arm64_linux": {
"url": "file://#{TEST_FIXTURE_DIR}/cask/caffeine-arm-linux.zip"
}
}
JSON
end
before do
# For consistency, always run on Monterey and ARM
MacOS.full_version = "12"
allow(Hardware::CPU).to receive(:type).and_return(:arm)
end
after do
MacOS.full_version = original_macos_version
end
it "returns the correct variations hash for a cask with multiple versions" do
c = Cask::CaskLoader.load("multiple-versions")
h = c.to_hash_with_variations
expect(h).to be_a(Hash)
expect(JSON.pretty_generate(h["variations"])).to eq expected_versions_variations.strip
end
it "returns the correct variations hash for a cask different sha256s on each arch" do
c = Cask::CaskLoader.load("sha256-arch")
h = c.to_hash_with_variations
expect(h).to be_a(Hash)
expect(JSON.pretty_generate(h["variations"])).to eq expected_sha256_variations.strip
end
it "returns the correct variations hash for a cask different sha256s on each arch and os" do
c = Cask::CaskLoader.load("sha256-os")
h = c.to_hash_with_variations
expect(h).to be_a(Hash)
expect(JSON.pretty_generate(h["variations"])).to eq expected_sha256_variations_os.strip
end
# NOTE: The calls to `Cask.generating_hash!` and `Cask.generated_hash!`
# are not idempotent so they can only be used in one test.
it "returns the correct hash placeholders" do
described_class.generating_hash!
expect(described_class).to be_generating_hash
c = Cask::CaskLoader.load("placeholders")
h = c.to_hash_with_variations
described_class.generated_hash!
expect(described_class).not_to be_generating_hash
expect(h).to be_a(Hash)
expect(h["artifacts"].first[:binary].first).to eq "$APPDIR/some/path"
expect(h["caveats"]).to eq "$HOMEBREW_PREFIX and /$HOME\n"
end
context "when loaded from json file" do
let(:expected_json) { (TEST_FIXTURE_DIR/"cask/everything-with-variations.json").read.strip }
it "returns expected hash with variations" do
expect(Homebrew::API::Cask).not_to receive(:source_download)
cask = Cask::CaskLoader::FromAPILoader.new("everything-with-variations", from_json: JSON.parse(expected_json))
.load(config: nil)
hash = cask.to_hash_with_variations
expect(cask.loaded_from_api?).to be true
expect(hash).to be_a(Hash)
expect(JSON.pretty_generate(hash)).to eq(expected_json)
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/cask/tab_spec.rb | Library/Homebrew/test/cask/tab_spec.rb | # frozen_string_literal: true
require "cask"
RSpec.describe Cask::Tab, :cask do
matcher :be_installed_as_dependency do
match do |actual|
actual.installed_as_dependency == true
end
end
matcher :be_installed_on_request do
match do |actual|
actual.installed_on_request == true
end
end
matcher :be_loaded_from_api do
match do |actual|
actual.loaded_from_api == true
end
end
matcher :have_uninstall_flight_blocks do
match do |actual|
actual.uninstall_flight_blocks == true
end
end
subject(:tab) do
described_class.new(
"homebrew_version" => HOMEBREW_VERSION,
"loaded_from_api" => false,
"uninstall_flight_blocks" => true,
"installed_as_dependency" => false,
"installed_on_request" => true,
"time" => time,
"runtime_dependencies" => {
"cask" => [{ "full_name" => "bar", "version" => "2.0", "declared_directly" => false }],
},
"source" => {
"path" => CoreCaskTap.instance.path.to_s,
"tap" => CoreCaskTap.instance.to_s,
"tap_git_head" => "8b79aa759500f0ffdf65a23e12950cbe3bf8fe17",
"version" => "1.2.3",
},
"arch" => Hardware::CPU.arch,
"uninstall_artifacts" => [{ "app" => ["Foo.app"] }],
"built_on" => DevelopmentTools.build_system_info,
)
end
let(:time) { Time.now.to_i }
let(:f) { formula { url "foo-1.0" } }
let(:f_tab_path) { f.prefix/"INSTALL_RECEIPT.json" }
let(:f_tab_content) { (TEST_FIXTURE_DIR/"receipt.json").read }
specify "defaults" do
stub_const("HOMEBREW_VERSION", "4.3.7")
tab = described_class.empty
expect(tab.homebrew_version).to eq(HOMEBREW_VERSION)
expect(tab).not_to be_installed_as_dependency
expect(tab).not_to be_installed_on_request
expect(tab).not_to be_loaded_from_api
expect(tab).not_to have_uninstall_flight_blocks
expect(tab.tap).to be_nil
expect(tab.time).to be_nil
expect(tab.runtime_dependencies).to be_nil
expect(tab.source["path"]).to be_nil
end
specify "#runtime_dependencies" do
tab = described_class.new
expect(tab.runtime_dependencies).to be_nil
tab.runtime_dependencies = {}
expect(tab.runtime_dependencies).not_to be_nil
tab.runtime_dependencies = {
"cask" => [{ "full_name" => "bar", "version" => "2.0", "declared_directly" => false }],
}
expect(tab.runtime_dependencies).not_to be_nil
end
describe "::runtime_deps_hash" do
specify "with no dependencies" do
cask = Cask::CaskLoader.load("local-transmission")
expect(described_class.runtime_deps_hash(cask)).to eq({})
end
specify "with cask dependencies" do
cask = Cask::CaskLoader.load("with-depends-on-cask")
expected_hash = {
cask: [
{ "full_name"=>"local-transmission-zip", "version"=>"2.61", "declared_directly"=>true },
],
}
expect(described_class.runtime_deps_hash(cask)).to eq(expected_hash)
end
it "ignores macos symbol dependencies" do
cask = Cask::CaskLoader.load("with-depends-on-macos-symbol")
expect(described_class.runtime_deps_hash(cask)).to eq({})
end
it "ignores macos array dependencies" do
cask = Cask::CaskLoader.load("with-depends-on-macos-array")
expect(described_class.runtime_deps_hash(cask)).to eq({})
end
it "ignores arch dependencies" do
cask = Cask::CaskLoader.load("with-depends-on-arch")
expect(described_class.runtime_deps_hash(cask)).to eq({})
end
specify "with all types of dependencies" do
cask = Cask::CaskLoader.load("with-depends-on-everything")
unar = Class.new(Formula) do
url "my_url"
version "1.2"
end.new("unar", Pathname.new(__FILE__).expand_path, :stable)
expect(Formulary).to receive(:factory).with("unar").and_return(unar)
expected_hash = {
cask: [
{ "full_name"=>"local-caffeine", "version"=>"1.2.3", "declared_directly"=>true },
{ "full_name"=>"with-depends-on-cask", "version"=>"1.2.3", "declared_directly"=>true },
{ "full_name"=>"local-transmission-zip", "version"=>"2.61", "declared_directly"=>false },
],
formula: [
{ "full_name"=>"unar", "version"=>"1.2", "revision"=>0, "pkg_version"=>"1.2", "declared_directly"=>true },
],
}
runtime_deps_hash = described_class.runtime_deps_hash(cask)
tab = described_class.new
tab.runtime_dependencies = runtime_deps_hash
expect(tab.runtime_dependencies).to eql(expected_hash)
end
end
specify "other attributes" do
expect(tab.tap.name).to eq("homebrew/cask")
expect(tab.time).to eq(time)
expect(tab).not_to be_loaded_from_api
expect(tab).to have_uninstall_flight_blocks
expect(tab).not_to be_installed_as_dependency
expect(tab).to be_installed_on_request
expect(tab).not_to be_loaded_from_api
end
describe "::from_file" do
it "parses a cask Tab from a file" do
path = Pathname.new("#{TEST_FIXTURE_DIR}/cask_receipt.json")
tab = described_class.from_file(path)
source_path = "/opt/homebrew/Library/Taps/homebrew/homebrew-cask/Casks/f/foo.rb"
runtime_dependencies = {
"cask" => [
{
"full_name" => "bar",
"version" => "2.0",
"declared_directly" => true,
},
],
"formula" => [
{
"full_name" => "baz",
"version" => "3.0",
"revision" => 0,
"pkg_version" => "3.0",
"declared_directly" => true,
},
],
"macos" => {
">=" => [
"12",
],
},
}
expect(tab).not_to be_loaded_from_api
expect(tab).to have_uninstall_flight_blocks
expect(tab).not_to be_installed_as_dependency
expect(tab).to be_installed_on_request
expect(tab.time).to eq(Time.at(1_719_289_256).to_i)
expect(tab.runtime_dependencies).to eq(runtime_dependencies)
expect(tab.source["path"]).to eq(source_path)
expect(tab.version).to eq("1.2.3")
expect(tab.tap.name).to eq("homebrew/cask")
end
end
describe "::from_file_content" do
it "parses a cask Tab from a file" do
path = Pathname.new("#{TEST_FIXTURE_DIR}/cask_receipt.json")
tab = described_class.from_file_content(path.read, path)
source_path = "/opt/homebrew/Library/Taps/homebrew/homebrew-cask/Casks/f/foo.rb"
runtime_dependencies = {
"cask" => [
{
"full_name" => "bar",
"version" => "2.0",
"declared_directly" => true,
},
],
"formula" => [
{
"full_name" => "baz",
"version" => "3.0",
"revision" => 0,
"pkg_version" => "3.0",
"declared_directly" => true,
},
],
"macos" => {
">=" => [
"12",
],
},
}
expect(tab).not_to be_loaded_from_api
expect(tab).to have_uninstall_flight_blocks
expect(tab).not_to be_installed_as_dependency
expect(tab).to be_installed_on_request
expect(tab.tabfile).to eq(path)
expect(tab.time).to eq(Time.at(1_719_289_256).to_i)
expect(tab.runtime_dependencies).to eq(runtime_dependencies)
expect(tab.source["path"]).to eq(source_path)
expect(tab.version).to eq("1.2.3")
expect(tab.tap.name).to eq("homebrew/cask")
end
it "raises a parse exception message including the Tab filename" do
expect { described_class.from_file_content("''", "cask_receipt.json") }.to raise_error(
JSON::ParserError,
/receipt.json:/,
)
end
end
describe "::create" do
it "creates a cask Tab" do
cask = Cask::CaskLoader.load("local-caffeine")
expected_artifacts = [
{ app: ["Caffeine.app"] },
{ zap: [{ trash: "#{TEST_FIXTURE_DIR}/cask/caffeine/org.example.caffeine.plist" }] },
]
tab = described_class.create(cask)
expect(tab).not_to be_loaded_from_api
expect(tab).not_to have_uninstall_flight_blocks
expect(tab).not_to be_installed_as_dependency
expect(tab).not_to be_installed_on_request
expect(tab.source).to eq({
"path" => "#{CoreCaskTap.instance.path}/Casks/local-caffeine.rb",
"tap" => CoreCaskTap.instance.name,
"tap_git_head" => nil,
"version" => "1.2.3",
})
expect(tab.runtime_dependencies).to eq({})
expect(tab.uninstall_artifacts).to eq(expected_artifacts)
end
end
describe "::for_cask" do
let(:cask) { Cask::CaskLoader.load("local-transmission") }
let(:cask_tab_path) { cask.metadata_main_container_path/AbstractTab::FILENAME }
let(:cask_tab_content) { (TEST_FIXTURE_DIR/"cask_receipt.json").read }
it "creates a Tab for a given cask" do
tab = described_class.for_cask(cask)
expect(tab.source["path"]).to eq(cask.sourcefile_path.to_s)
end
it "creates a Tab for a given cask with existing Tab" do
cask_tab_path.dirname.mkpath
cask_tab_path.write cask_tab_content
tab = described_class.for_cask(cask)
expect(tab.tabfile).to eq(cask_tab_path)
end
it "can create a Tab for a non-existent cask" do
cask_tab_path.dirname.mkpath
tab = described_class.for_cask(cask)
expect(tab.tabfile).to be_nil
end
end
specify "#to_json" do
json_tab = described_class.new(JSON.parse(tab.to_json))
expect(json_tab.homebrew_version).to eq(tab.homebrew_version)
expect(json_tab.loaded_from_api).to eq(tab.loaded_from_api)
expect(json_tab.uninstall_flight_blocks).to eq(tab.uninstall_flight_blocks)
expect(json_tab.installed_as_dependency).to eq(tab.installed_as_dependency)
expect(json_tab.installed_on_request).to eq(tab.installed_on_request)
expect(json_tab.time).to eq(tab.time)
expect(json_tab.runtime_dependencies).to eq(tab.runtime_dependencies)
expect(json_tab.source["path"]).to eq(tab.source["path"])
expect(json_tab.tap).to eq(tab.tap)
expect(json_tab.source["tap_git_head"]).to eq(tab.source["tap_git_head"])
expect(json_tab.version).to eq(tab.version)
expect(json_tab.arch).to eq(tab.arch.to_s)
expect(json_tab.uninstall_artifacts).to eq(tab.uninstall_artifacts)
expect(json_tab.built_on["os"]).to eq(tab.built_on["os"])
end
describe "#to_s" do
let(:time_string) { Time.at(1_720_189_863).strftime("%Y-%m-%d at %H:%M:%S") }
it "returns install information for a Tab with a time that was loaded from the API" do
tab = described_class.new(
loaded_from_api: true,
time: 1_720_189_863,
)
output = "Installed using the formulae.brew.sh API on #{time_string}"
expect(tab.to_s).to eq(output)
end
it "returns install information for a Tab with a time that was not loaded from the API" do
tab = described_class.new(
loaded_from_api: false,
time: 1_720_189_863,
)
output = "Installed on #{time_string}"
expect(tab.to_s).to eq(output)
end
it "returns install information for a Tab without a time that was loaded from the API" do
tab = described_class.new(
loaded_from_api: true,
time: nil,
)
output = "Installed using the formulae.brew.sh API"
expect(tab.to_s).to eq(output)
end
it "returns install information for a Tab without a time that was not loaded from the API" do
tab = described_class.new(
loaded_from_api: false,
time: nil,
)
output = "Installed"
expect(tab.to_s).to eq(output)
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/cask/dsl_spec.rb | Library/Homebrew/test/cask/dsl_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::DSL, :cask, :no_api do
let(:cask) { Cask::CaskLoader.load(token) }
let(:token) { "basic-cask" }
describe "stanzas" do
it "lets you set url, homepage and version" do
expect(cask.url.to_s).to eq("https://brew.sh/TestCask-1.2.3.dmg")
expect(cask.homepage).to eq("https://brew.sh/")
expect(cask.version.to_s).to eq("1.2.3")
end
end
describe "when a Cask includes an unknown method" do
let(:attempt_unknown_method) do
Cask::Cask.new("unexpected-method-cask") do
future_feature :not_yet_on_your_machine
end
end
it "prints an error that it has encountered an unexpected method" do
expected = Regexp.compile(<<~EOS.lines.map(&:chomp).join)
(?m)
Error: Unexpected method 'future_feature' called on Cask unexpected-method-cask\\.
.*
https://github.com/Homebrew/homebrew-cask#reporting-bugs
EOS
expect do
expect { attempt_unknown_method }.not_to output.to_stdout
end.to output(expected).to_stderr
end
it "simply warns, instead of throwing an exception" do
expect do
attempt_unknown_method
end.not_to raise_error
end
end
describe "header line" do
context "when invalid" do
let(:token) { "invalid-header-format" }
it "raises an error" do
expect { cask }.to raise_error(Cask::CaskUnreadableError)
end
end
context "when token does not match the file name" do
let(:token) { "invalid-header-token-mismatch" }
it "raises an error" do
expect do
cask
end.to raise_error(Cask::CaskTokenMismatchError, /header line does not match the file name/)
end
end
context "when it contains no DSL version" do
let(:token) { "no-dsl-version" }
it "does not require a DSL version in the header" do
expect(cask.token).to eq("no-dsl-version")
expect(cask.url.to_s).to eq("https://brew.sh/TestCask-1.2.3.dmg")
expect(cask.homepage).to eq("https://brew.sh/")
expect(cask.version.to_s).to eq("1.2.3")
end
end
end
describe "name stanza" do
it "lets you set the full name via a name stanza" do
cask = Cask::Cask.new("name-cask") do
name "Proper Name"
end
expect(cask.name).to eq([
"Proper Name",
])
end
it "Accepts an array value to the name stanza" do
cask = Cask::Cask.new("array-name-cask") do
name ["Proper Name", "Alternate Name"]
end
expect(cask.name).to eq([
"Proper Name",
"Alternate Name",
])
end
it "Accepts multiple name stanzas" do
cask = Cask::Cask.new("multi-name-cask") do
name "Proper Name"
name "Alternate Name"
end
expect(cask.name).to eq([
"Proper Name",
"Alternate Name",
])
end
end
describe "desc stanza" do
it "lets you set the description via a desc stanza" do
cask = Cask::Cask.new("desc-cask") do
desc "The package's description"
end
expect(cask.desc).to eq("The package's description")
end
end
describe "sha256 stanza" do
it "lets you set checksum via sha256" do
cask = Cask::Cask.new("checksum-cask") do
sha256 "imasha2"
end
expect(cask.sha256).to eq("imasha2")
end
context "with a different arm and intel checksum" do
let(:cask) do
Cask::Cask.new("checksum-cask") do
sha256 arm: "imasha2arm", intel: "imasha2intel"
end
end
context "when running on arm" do
before do
allow(Hardware::CPU).to receive(:type).and_return(:arm)
end
it "stores only the arm checksum" do
expect(cask.sha256).to eq("imasha2arm")
end
end
context "when running on intel" do
before do
allow(Hardware::CPU).to receive(:type).and_return(:intel)
end
it "stores only the intel checksum" do
expect(cask.sha256).to eq("imasha2intel")
end
end
end
end
describe "no_autobump! stanze" do
it "returns true if no_autobump! is not set" do
expect(cask.autobump?).to be(true)
end
context "when no_autobump! is set" do
let(:cask) do
Cask::Cask.new("checksum-cask") do
no_autobump! because: "some reason"
end
end
it "returns false" do
expect(cask.autobump?).to be(false)
expect(cask.no_autobump_message).to eq("some reason")
end
end
end
describe "language stanza" do
context "when language is set explicitly" do
subject(:cask) do
Cask::Cask.new("cask-with-apps") do
language "zh" do
sha256 "abc123"
"zh-CN"
end
language "en", default: true do
sha256 "xyz789"
"en-US"
end
url "https://example.org/#{language}.zip"
end
end
matcher :be_the_chinese_version do
match do |cask|
expect(cask.language).to eq("zh-CN")
expect(cask.sha256).to eq("abc123")
expect(cask.url.to_s).to eq("https://example.org/zh-CN.zip")
end
end
matcher :be_the_english_version do
match do |cask|
expect(cask.language).to eq("en-US")
expect(cask.sha256).to eq("xyz789")
expect(cask.url.to_s).to eq("https://example.org/en-US.zip")
end
end
before do
config = cask.config
config.languages = languages
cask.config = config
end
describe "to 'zh'" do
let(:languages) { ["zh"] }
it { is_expected.to be_the_chinese_version }
end
describe "to 'zh-XX'" do
let(:languages) { ["zh-XX"] }
it { is_expected.to be_the_chinese_version }
end
describe "to 'en'" do
let(:languages) { ["en"] }
it { is_expected.to be_the_english_version }
end
describe "to 'xx-XX'" do
let(:languages) { ["xx-XX"] }
it { is_expected.to be_the_english_version }
end
describe "to 'xx-XX,zh,en'" do
let(:languages) { ["xx-XX", "zh", "en"] }
it { is_expected.to be_the_chinese_version }
end
describe "to 'xx-XX,en-US,zh'" do
let(:languages) { ["xx-XX", "en-US", "zh"] }
it { is_expected.to be_the_english_version }
end
end
it "returns an empty array if no languages are specified" do
cask = lambda do
Cask::Cask.new("cask-with-apps") do
url "https://example.org/file.zip"
end
end
expect(cask.call.languages).to be_empty
end
it "returns an array of available languages" do
cask = lambda do
Cask::Cask.new("cask-with-apps") do
language "zh" do
sha256 "abc123"
"zh-CN"
end
language "en-US", default: true do
sha256 "xyz789"
"en-US"
end
url "https://example.org/file.zip"
end
end
expect(cask.call.languages).to eq(["zh", "en-US"])
end
end
describe "app stanza" do
it "allows you to specify app stanzas" do
cask = Cask::Cask.new("cask-with-apps") do
app "Foo.app"
app "Bar.app"
end
expect(cask.artifacts.map(&:to_s)).to eq(["Foo.app (App)", "Bar.app (App)"])
end
it "allow app stanzas to be empty" do
cask = Cask::Cask.new("cask-with-no-apps")
expect(cask.artifacts).to be_empty
end
end
describe "caveats stanza" do
it "allows caveats to be specified via a method define" do
cask = Cask::Cask.new("plain-cask")
expect(cask.caveats).to be_empty
cask = Cask::Cask.new("cask-with-caveats") do
def caveats
<<~EOS
When you install this Cask, you probably want to know this.
EOS
end
end
expect(cask.caveats).to eq("When you install this Cask, you probably want to know this.\n")
end
end
describe "pkg stanza" do
it "allows installable pkgs to be specified" do
cask = Cask::Cask.new("cask-with-pkgs") do
pkg "Foo.pkg"
pkg "Bar.pkg"
end
expect(cask.artifacts.map(&:to_s)).to eq(["Foo.pkg (Pkg)", "Bar.pkg (Pkg)"])
end
end
describe "url stanza" do
let(:token) { "invalid-two-url" }
it "prevents defining multiple urls" do
expect { cask }.to raise_error(Cask::CaskInvalidError, /'url' stanza may only appear once/)
end
end
describe "homepage stanza" do
let(:token) { "invalid-two-homepage" }
it "prevents defining multiple homepages" do
expect { cask }.to raise_error(Cask::CaskInvalidError, /'homepage' stanza may only appear once/)
end
end
describe "version stanza" do
let(:token) { "invalid-two-version" }
it "prevents defining multiple versions" do
expect { cask }.to raise_error(Cask::CaskInvalidError, /'version' stanza may only appear once/)
end
end
describe "arch stanza" do
let(:token) { "invalid-two-arch" }
it "prevents defining multiple arches" do
expect { cask }.to raise_error(Cask::CaskInvalidError, /'arch' stanza may only appear once/)
end
context "when no intel value is specified" do
let(:token) { "arch-arm-only" }
context "when running on arm" do
before do
allow(Hardware::CPU).to receive(:type).and_return(:arm)
end
it "returns the value" do
expect(cask.url.to_s).to eq "file://#{TEST_FIXTURE_DIR}/cask/caffeine-arm.zip"
end
end
context "when running on intel" do
before do
allow(Hardware::CPU).to receive(:type).and_return(:intel)
end
it "defaults to `nil` for the other when no arrays are passed" do
expect(cask.url.to_s).to eq "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip"
end
end
end
end
describe "depends_on stanza" do
let(:token) { "invalid-depends-on-key" }
it "refuses to load with an invalid depends_on key" do
expect { cask }.to raise_error(Cask::CaskInvalidError)
end
end
describe "depends_on formula" do
context "with one Formula" do
let(:token) { "with-depends-on-formula" }
it "allows depends_on formula to be specified" do
expect(cask.depends_on.formula).not_to be_nil
end
end
context "with multiple Formulae" do
let(:token) { "with-depends-on-formula-multiple" }
it "allows multiple depends_on formula to be specified" do
expect(cask.depends_on.formula).not_to be_nil
end
end
end
describe "depends_on cask" do
context "with a single cask" do
let(:token) { "with-depends-on-cask" }
it "is allowed" do
expect(cask.depends_on.cask).not_to be_nil
end
end
context "when specifying multiple" do
let(:token) { "with-depends-on-cask-multiple" }
it "is allowed" do
expect(cask.depends_on.cask).not_to be_nil
end
end
end
describe "depends_on macos" do
context "when the depends_on macos value is invalid" do
let(:token) { "invalid-depends-on-macos-bad-release" }
it "refuses to load" do
expect { cask }.to raise_error(Cask::CaskInvalidError)
end
end
context "when there are conflicting depends_on macos forms" do
let(:token) { "invalid-depends-on-macos-conflicting-forms" }
it "refuses to load" do
expect { cask }.to raise_error(Cask::CaskInvalidError)
end
end
end
describe "depends_on arch" do
context "when valid" do
let(:token) { "with-depends-on-arch" }
it "is allowed to be specified" do
expect(cask.depends_on.arch).not_to be_nil
end
end
context "with invalid depends_on arch value" do
let(:token) { "invalid-depends-on-arch-value" }
it "refuses to load" do
expect { cask }.to raise_error(Cask::CaskInvalidError)
end
end
end
describe "conflicts_with cask" do
let(:local_caffeine) do
Cask::CaskLoader.load(cask_path("local-caffeine"))
end
let(:with_conflicts_with) do
Cask::CaskLoader.load(cask_path("with-conflicts-with"))
end
it "installs the dependency of a Cask and the Cask itself" do
Cask::Installer.new(local_caffeine).install
expect(local_caffeine).to be_installed
expect do
Cask::Installer.new(with_conflicts_with).install
end.to raise_error(Cask::CaskConflictError, "Cask 'with-conflicts-with' conflicts with 'local-caffeine'.")
expect(with_conflicts_with).not_to be_installed
end
end
describe "conflicts_with stanza" do
context "when valid" do
let(:token) { "with-conflicts-with" }
it "allows conflicts_with stanza to be specified" do
expect(cask.conflicts_with[:formula]).to be_empty
end
end
context "with invalid conflicts_with key" do
let(:token) { "invalid-conflicts-with-key" }
it "refuses to load invalid conflicts_with key" do
expect { cask }.to raise_error(Cask::CaskInvalidError)
end
end
context "with disabled conflicts_with key" do
let(:token) { "conflicts-with-disabled-key" }
it "loads but shows disabled warning for disabled key" do
expect { cask.conflicts_with }.to raise_error(Cask::CaskInvalidError, /is disabled/)
end
end
end
describe "installer stanza" do
context "when script" do
let(:token) { "with-installer-script" }
it "allows installer script to be specified" do
expect(cask.artifacts.to_a.first.path).to eq(Pathname("/usr/bin/true"))
expect(cask.artifacts.to_a.first.args[:args]).to eq(["--flag"])
expect(cask.artifacts.to_a.second.path).to eq(Pathname("/usr/bin/false"))
expect(cask.artifacts.to_a.second.args[:args]).to eq(["--flag"])
end
end
context "when manual" do
let(:token) { "with-installer-manual" }
it "allows installer manual to be specified" do
installer = cask.artifacts.first
expect(installer.instance_variable_get(:@manual_install)).to be true
expect(installer.path).to eq(Pathname("Caffeine.app"))
end
end
end
describe "stage_only stanza" do
context "when there is no other activatable artifact" do
let(:token) { "stage-only" }
it "allows stage_only stanza to be specified" do
expect(cask.artifacts).to contain_exactly a_kind_of Cask::Artifact::StageOnly
end
end
context "when there is are activatable artifacts" do
let(:token) { "invalid-stage-only-conflict" }
it "prevents specifying stage_only" do
expect { cask }.to raise_error(Cask::CaskInvalidError, /'stage_only' must be the only activatable artifact/)
end
end
end
describe "auto_updates stanza" do
let(:token) { "auto-updates" }
it "allows auto_updates stanza to be specified" do
expect(cask.auto_updates).to be true
end
end
describe "#appdir" do
context "with interpolation of the appdir in stanzas" do
let(:token) { "appdir-interpolation" }
it "is allowed" do
expect(cask.artifacts.first.source).to eq(cask.config.appdir/"some/path")
end
end
it "does not include a trailing slash" do
config = Cask::Config.new(explicit: {
appdir: "/Applications/",
})
cask = Cask::Cask.new("appdir-trailing-slash", config:) do
binary "#{appdir}/some/path"
end
expect(cask.artifacts.first.source).to eq(Pathname("/Applications/some/path"))
end
end
describe "#artifacts" do
it "sorts artifacts according to the preferable installation order" do
cask = Cask::Cask.new("appdir-trailing-slash") do
postflight do
next
end
preflight do
next
end
binary "binary"
app "App.app"
end
expect(cask.artifacts.map { |artifact| artifact.class.dsl_key }).to eq [
:preflight,
:app,
:binary,
:postflight,
]
end
end
describe "rename stanza" do
it "allows setting single rename operation" do
cask = Cask::Cask.new("rename-cask") do
rename "Source*.pkg", "Target.pkg"
end
expect(cask.rename.length).to eq(1)
expect(cask.rename.first.from).to eq("Source*.pkg")
expect(cask.rename.first.to).to eq("Target.pkg")
end
it "allows setting multiple rename operations" do
cask = Cask::Cask.new("multi-rename-cask") do
rename "App*.pkg", "App.pkg"
rename "Doc*.dmg", "Doc.dmg"
end
expect(cask.rename.length).to eq(2)
expect(cask.rename.first.from).to eq("App*.pkg")
expect(cask.rename.first.to).to eq("App.pkg")
expect(cask.rename.last.from).to eq("Doc*.dmg")
expect(cask.rename.last.to).to eq("Doc.dmg")
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/cask/cask_loader_spec.rb | Library/Homebrew/test/cask/cask_loader_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::CaskLoader, :cask do
describe "::for" do
let(:tap) { CoreCaskTap.instance }
context "when a cask is renamed" do
let(:old_token) { "version-newest" }
let(:new_token) { "version-latest" }
let(:api_casks) do
[old_token, new_token].to_h do |token|
hash = described_class.load(new_token).to_hash_with_variations
json = JSON.pretty_generate(hash)
cask_json = JSON.parse(json)
[token, cask_json.except("token")]
end
end
let(:cask_renames) do
{ old_token => new_token }
end
before do
allow(Homebrew::API::Cask)
.to receive(:all_casks)
.and_return(api_casks)
allow(tap).to receive(:cask_renames)
.and_return(cask_renames)
end
context "when not using the API", :no_api do
it "warns when using the short token" do
expect do
expect(described_class.for("version-newest")).to be_a Cask::CaskLoader::FromPathLoader
end.to output(/version-newest was renamed to version-latest/).to_stderr
end
it "warns when using the full token" do
expect do
expect(described_class.for("homebrew/cask/version-newest")).to be_a Cask::CaskLoader::FromPathLoader
end.to output(/version-newest was renamed to version-latest/).to_stderr
end
end
context "when using the API" do
it "warns when using the short token" do
expect do
expect(described_class.for("version-newest")).to be_a Cask::CaskLoader::FromAPILoader
end.to output(/version-newest was renamed to version-latest/).to_stderr
end
it "warns when using the full token" do
expect do
expect(described_class.for("homebrew/cask/version-newest")).to be_a Cask::CaskLoader::FromAPILoader
end.to output(/version-newest was renamed to version-latest/).to_stderr
end
end
end
context "when not using the API", :no_api do
context "when a cask is migrated" do
let(:token) { "local-caffeine" }
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 an other tap" do
# Can't use local-caffeine. It is a fixture in the :core_cask_tap and would take precedence over :new_tap.
let(:token) { "some-cask" }
let(:old_tap) { Tap.fetch("homebrew", "foo") }
let(:new_tap) { Tap.fetch("homebrew", "bar") }
let(:cask_file) { new_tap.cask_dir/"#{token}.rb" }
before do
new_tap.cask_dir.mkpath
FileUtils.touch cask_file
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.for(token)
end.to output(%r{Cask #{old_tap}/#{token} was renamed to #{new_tap}/#{token}\.}).to_stderr
end
it "does not warn when loading the full token in the new tap" do
expect do
described_class.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.for("#{old_tap}/#{token}")
end.to output(%r{Cask #{old_tap}/#{token} was renamed to #{new_tap}/#{token}\.}).to_stderr
end
end
context "to a formula in 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 "warn only once" do
expect do
described_class.for(token)
end.to output(
a_string_including("Warning: Cask #{token} was renamed to #{new_tap}/#{token}.").once,
).to_stderr
end
end
context "to 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 "does not warn when loading the short token" do
expect do
described_class.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.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.for("#{old_tap}/#{token}")
end.to output(%r{Cask #{old_tap}/#{token} was renamed to #{token}\.}).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.for("#{new_tap}/#{token}")
# end.not_to output.to_stderr
# end
# end
end
end
end
end
describe "::load_prefer_installed" do
let(:foo_tap) { Tap.fetch("user", "foo") }
let(:bar_tap) { Tap.fetch("user", "bar") }
let(:blank_tab) { instance_double(Cask::Tab, tap: nil) }
let(:installed_tab) { instance_double(Cask::Tab, tap: bar_tap) }
let(:cask_with_foo_tap) { instance_double(Cask::Cask, token: "test-cask", tap: foo_tap) }
let(:cask_with_bar_tap) { instance_double(Cask::Cask, token: "test-cask", tap: bar_tap) }
let(:load_args) { { config: nil, warn: true } }
before do
allow(described_class).to receive(:load).with("test-cask", load_args).and_return(cask_with_foo_tap)
allow(described_class).to receive(:load).with("user/foo/test-cask", load_args).and_return(cask_with_foo_tap)
allow(described_class).to receive(:load).with("user/bar/test-cask", load_args).and_return(cask_with_bar_tap)
end
it "returns the correct cask when no tap is specified and no tab exists" do
allow_any_instance_of(Cask::Cask).to receive(:tab).and_return(blank_tab)
expect(described_class).to receive(:load).with("test-cask", load_args)
expect(described_class.load_prefer_installed("test-cask").tap).to eq(foo_tap)
end
it "returns the correct cask when no tap is specified but a tab exists" do
allow_any_instance_of(Cask::Cask).to receive(:tab).and_return(installed_tab)
expect(described_class).to receive(:load).with("user/bar/test-cask", load_args)
expect(described_class.load_prefer_installed("test-cask").tap).to eq(bar_tap)
end
it "returns the correct cask when a tap is specified and no tab exists" do
allow_any_instance_of(Cask::Cask).to receive(:tab).and_return(blank_tab)
expect(described_class).to receive(:load).with("user/bar/test-cask", load_args)
expect(described_class.load_prefer_installed("user/bar/test-cask").tap).to eq(bar_tap)
end
it "returns the correct cask when no tap is specified and a tab exists" do
allow_any_instance_of(Cask::Cask).to receive(:tab).and_return(installed_tab)
expect(described_class).to receive(:load).with("user/foo/test-cask", load_args)
expect(described_class.load_prefer_installed("user/foo/test-cask").tap).to eq(foo_tap)
end
it "returns the correct cask when no tap is specified and the tab lists an tap that isn't installed" do
allow_any_instance_of(Cask::Cask).to receive(:tab).and_return(installed_tab)
expect(described_class).to receive(:load).with("user/bar/test-cask", load_args)
.and_raise(Cask::CaskUnavailableError.new("test-cask", bar_tap))
expect(described_class).to receive(:load).with("test-cask", load_args)
expect(described_class.load_prefer_installed("test-cask").tap).to eq(foo_tap)
end
end
describe "FromPathLoader with symlinked taps" do
let(:cask_token) { "testcask" }
let(:tmpdir) { mktmpdir }
let(:real_tap_path) { tmpdir / "real_tap" }
let(:homebrew_prefix) { tmpdir / "homebrew" }
let(:taps_dir) { homebrew_prefix / "Library" / "Taps" / "testuser" }
let(:symlinked_tap_path) { taps_dir / "homebrew-testtap" }
let(:cask_file_path) { symlinked_tap_path / "Casks" / "#{cask_token}.rb" }
let(:cask_content) do
<<~RUBY
cask "#{cask_token}" do
version "1.0.0"
sha256 "1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
url "https://example.com/#{cask_token}-\#{version}.dmg"
name "Test Cask"
desc "A test cask for symlink testing"
homepage "https://example.com"
app "TestCask.app"
end
RUBY
end
after do
tmpdir.rmtree if tmpdir.exist?
end
before do
# Create real tap directory structure
(real_tap_path / "Casks").mkpath
(real_tap_path / "Casks" / "#{cask_token}.rb").write(cask_content)
# Create homebrew prefix structure
taps_dir.mkpath
# Create symlink to the tap (this simulates what setup-homebrew does)
symlinked_tap_path.make_symlink(real_tap_path)
# Set HOMEBREW_LIBRARY to our test prefix for the security check
stub_const("HOMEBREW_LIBRARY", homebrew_prefix / "Library")
allow(Homebrew::EnvConfig).to receive(:forbid_packages_from_paths?).and_return(true)
end
context "when HOMEBREW_FORBID_PACKAGES_FROM_PATHS is enabled" do
it "allows loading casks from symlinked taps" do
loader = Cask::CaskLoader::FromPathLoader.try_new(cask_file_path)
expect(loader).not_to be_nil
expect(loader).to be_a(Cask::CaskLoader::FromPathLoader)
cask = loader.load(config: nil)
expect(cask.token).to eq(cask_token)
expect(cask.version).to eq(Version.new("1.0.0"))
end
end
context "when HOMEBREW_FORBID_PACKAGES_FROM_PATHS is disabled" do
before do
allow(Homebrew::EnvConfig).to receive(:forbid_packages_from_paths?).and_return(false)
end
it "allows loading casks from symlinked taps" do
loader = Cask::CaskLoader::FromPathLoader.try_new(cask_file_path)
expect(loader).not_to be_nil
expect(loader).to be_a(Cask::CaskLoader::FromPathLoader)
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/cask/utils_spec.rb | Library/Homebrew/test/cask/utils_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Utils do
let(:command) { NeverSudoSystemCommand }
let(:dir) { mktmpdir }
let(:path) { dir/"a/b/c" }
let(:link) { dir/"link" }
describe "::gain_permissions_mkpath" do
it "creates a directory" do
expect(path).not_to exist
described_class.gain_permissions_mkpath(path, command:)
expect(path).to be_a_directory
described_class.gain_permissions_mkpath(path, command:)
expect(path).to be_a_directory
end
context "when parent directory is not writable" do
it "creates a directory with `sudo`" do
FileUtils.chmod "-w", dir
expect(dir).not_to be_writable
expect(command).to receive(:run!).exactly(:once).and_wrap_original do |original, *args, **options|
FileUtils.chmod "+w", dir
original.call(*args, **options)
FileUtils.chmod "-w", dir
end
expect(path).not_to exist
described_class.gain_permissions_mkpath(path, command:)
expect(path).to be_a_directory
described_class.gain_permissions_mkpath(path, command:)
expect(path).to be_a_directory
expect(dir).not_to be_writable
FileUtils.chmod "+w", dir
end
end
end
describe "::gain_permissions_remove" do
it "removes the symlink, not the file it points to" do
path.dirname.mkpath
FileUtils.touch path
FileUtils.ln_s path, link
expect(path).to be_a_file
expect(link).to be_a_symlink
expect(link.readlink).to eq path
described_class.gain_permissions_remove(link, command:)
expect(path).to be_a_file
expect(link).not_to exist
described_class.gain_permissions_remove(path, command:)
expect(path).not_to exist
end
it "removes the symlink, not the directory it points to" do
path.mkpath
FileUtils.ln_s path, link
expect(path).to be_a_directory
expect(link).to be_a_symlink
expect(link.readlink).to eq path
described_class.gain_permissions_remove(link, command:)
expect(path).to be_a_directory
expect(link).not_to exist
described_class.gain_permissions_remove(path, command:)
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/cask/reinstall_spec.rb | Library/Homebrew/test/cask/reinstall_spec.rb | # frozen_string_literal: true
require "cask/installer"
require "cask/reinstall"
RSpec.describe Cask::Reinstall, :cask do
it "displays the reinstallation progress" do
caffeine = Cask::CaskLoader.load(cask_path("local-caffeine"))
Cask::Installer.new(caffeine).install
output = Regexp.new <<~EOS
==> Fetching downloads for:.*caffeine
==> Uninstalling Cask local-caffeine
==> Backing App 'Caffeine.app' up to '.*Caffeine.app'
==> Removing App '.*Caffeine.app'
==> Purging files for version 1.2.3 of Cask local-caffeine
==> Installing Cask local-caffeine
==> Moving App 'Caffeine.app' to '.*Caffeine.app'
.*local-caffeine was successfully installed!
EOS
expect do
described_class.reinstall_casks(Cask::CaskLoader.load("local-caffeine"))
end.to output(output).to_stdout
end
it "displays the reinstallation progress with zapping" do
caffeine = Cask::CaskLoader.load(cask_path("local-caffeine"))
Cask::Installer.new(caffeine).install
output = Regexp.new <<~EOS
==> Fetching downloads for:.*caffeine
==> Backing App 'Caffeine.app' up to '.*Caffeine.app'
==> Removing App '.*Caffeine.app'
==> Dispatching zap stanza
==> Trashing files:
.*org.example.caffeine.plist
==> Removing all staged versions of Cask 'local-caffeine'
==> Installing Cask local-caffeine
==> Moving App 'Caffeine.app' to '.*Caffeine.app'
.*local-caffeine was successfully installed!
EOS
expect do
described_class.reinstall_casks(Cask::CaskLoader.load("local-caffeine"), zap: true)
end.to output(output).to_stdout
end
it "allows reinstalling a Cask" do
Cask::Installer.new(Cask::CaskLoader.load(cask_path("local-transmission-zip"))).install
expect(Cask::CaskLoader.load(cask_path("local-transmission-zip"))).to be_installed
described_class.reinstall_casks(Cask::CaskLoader.load("local-transmission-zip"))
expect(Cask::CaskLoader.load(cask_path("local-transmission-zip"))).to be_installed
end
it "allows reinstalling a non installed Cask" do
expect(Cask::CaskLoader.load(cask_path("local-transmission-zip"))).not_to be_installed
described_class.reinstall_casks(Cask::CaskLoader.load("local-transmission-zip"))
expect(Cask::CaskLoader.load(cask_path("local-transmission-zip"))).to be_installed
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/cask/audit_spec.rb | Library/Homebrew/test/cask/audit_spec.rb | # frozen_string_literal: true
require "cask/audit"
RSpec.describe Cask::Audit, :cask do
def include_msg?(problems, msg)
if msg.is_a?(Regexp)
Array(problems).any? { |problem| msg.match?(problem[:message]) }
else
Array(problems).any? { |problem| problem[:message] == msg }
end
end
def passed?(audit)
!audit.errors?
end
def outcome(audit)
if passed?(audit)
"passed"
else
"errored with #{audit.errors.map { |e| e.fetch(:message).inspect }.join(",")}"
end
end
matcher :pass do
match do |audit|
passed?(audit)
end
failure_message do |audit|
"expected to pass, but #{outcome(audit)}"
end
end
matcher :error_with do |message|
match do |audit|
include_msg?(audit.errors, message)
end
failure_message do |audit|
"expected to error with message #{message.inspect} but #{outcome(audit)}"
end
end
let(:cask) { instance_double(Cask::Cask) }
let(:new_cask) { nil }
let(:online) { nil }
let(:only) { [] }
let(:except) { [] }
let(:strict) { nil }
let(:signing) { nil }
let(:audit) do
described_class.new(cask, online:,
strict:,
new_cask:,
signing:,
only:,
except:)
end
describe "#new" do
context "when `new_cask` is specified" do
let(:new_cask) { true }
it "implies `online`" do
expect(audit).to be_online
end
it "implies `strict`" do # rubocop:todo RSpec/AggregateExamples
expect(audit).to be_strict
end
end
context "when `online` is specified" do
let(:online) { true }
it "implies `download`" do
expect(audit.download).to be_truthy
end
end
context "when `signing` is specified" do
let(:signing) { true }
it "implies `download`" do
expect(audit.download).to be_truthy
end
end
end
describe "#result" do
subject { audit.result }
context "when there are no errors and `--strict` is not passed so we should not show anything" do
before do
audit.add_error("eh", strict_only: true)
end
it { is_expected.not_to match(/failed/) }
end
context "when there are errors" do
before do
audit.add_error "bad"
end
it { is_expected.to match(/failed/) }
end
context "when there are errors and warnings" do
before do
audit.add_error "bad"
audit.add_error("eh", strict_only: true)
end
it { is_expected.to match(/failed/) }
end
context "when there are errors and warnings and `--strict` is passed" do
let(:strict) { true }
before do
audit.add_error "very bad"
audit.add_error("a little bit bad", strict_only: true)
end
it { is_expected.to match(/failed/) }
end
context "when there are warnings and `--strict` is not passed" do
before do
audit.add_error("a little bit bad", strict_only: true)
end
it { is_expected.not_to match(/failed/) }
end
context "when there are warnings and `--strict` is passed" do
let(:strict) { true }
before do
audit.add_error("a little bit bad", strict_only: true)
end
it { is_expected.to match(/failed/) }
end
end
describe "#run!" do
subject(:run) { audit.run! }
def tmp_cask(name, text)
path = Pathname.new "#{dir}/#{name}.rb"
path.open("w") do |f|
f.write text
end
Cask::CaskLoader.load(path)
end
let(:dir) { mktmpdir }
let(:cask) { Cask::CaskLoader.load(cask_token) }
describe "required stanzas" do
let(:only) { ["required_stanzas"] }
%w[version sha256 url name homepage].each do |stanza|
context "when missing #{stanza}" do
let(:cask_token) { "missing-#{stanza}" }
it { is_expected.to error_with(/#{stanza} stanza is required/) }
end
end
end
describe "token validation" do
let(:strict) { true }
let(:only) { ["token"] }
let(:cask) do
tmp_cask cask_token.to_s, <<~RUBY
cask '#{cask_token}' do
version '1.0'
sha256 '8dd95daa037ac02455435446ec7bc737b34567afe9156af7d20b2a83805c1d8a'
url "https://brew.sh/"
name 'Audit'
homepage 'https://brew.sh/'
app 'Audit.app'
end
RUBY
end
context "when cask token is not lowercase" do
let(:cask_token) { "Upper-Case" }
it "fails" do
expect(run).to error_with(/not contain uppercase/)
end
end
context "when cask token is not ascii" do
let(:cask_token) { "ascii⌘" }
it "fails" do
expect(run).to error_with(/not contain non-ASCII characters/)
end
end
context "when cask token is @-versioned with number" do
let(:cask_token) { "app@10" }
it "does not fail" do
expect(run).to pass
end
end
context "when cask token is @-versioned with word" do
let(:cask_token) { "app@beta" }
it "does not fail" do
expect(run).to pass
end
end
context "when cask token has multiple @" do
let(:cask_token) { "app@stuff@beta" }
it "fails" do
expect(run).to error_with(/not contain multiple @ symbols/)
end
end
context "when cask token has a hyphen followed by @" do
let(:cask_token) { "app-@beta" }
it "fails" do
expect(run).to error_with(/not contain a hyphen followed by an @/)
end
end
context "when cask token has @ followed by a hyphen" do
let(:cask_token) { "app@-beta" }
it "fails" do
expect(run).to error_with(/not contain an @ followed by a hyphen/)
end
end
context "when cask token has whitespace" do
let(:cask_token) { "app stuff" }
it "fails" do
expect(run).to error_with(/not contain whitespace/)
end
end
context "when cask token has double hyphens" do
let(:cask_token) { "app--stuff" }
it "fails" do
expect(run).to error_with(/not contain double hyphens/)
end
end
context "when cask token has leading hyphens" do
let(:cask_token) { "-app" }
it "fails" do
expect(run).to error_with(/not contain a leading hyphen/)
end
end
context "when cask token has trailing hyphens" do
let(:cask_token) { "app-" }
it "fails" do
expect(run).to error_with(/not contain a trailing hyphen/)
end
end
end
describe "token bad words" do
let(:new_cask) { true }
let(:only) { ["token_bad_words", "reverse_migration"] }
let(:online) { false }
let(:cask) do
tmp_cask cask_token.to_s, <<~RUBY
cask "#{cask_token}" do
version "1.0"
sha256 "8dd95daa037ac02455435446ec7bc737b34567afe9156af7d20b2a83805c1d8a"
url "https://brew.sh/v\#{version}.zip"
name "Audit"
desc "Cask for testing tokens"
homepage "https://brew.sh/"
app "Audit.app"
end
RUBY
end
context "when cask token contains .app" do
let(:cask_token) { "token.app" }
it "fails" do
expect(run).to error_with(/token contains .app/)
end
end
context "when cask token contains launcher" do
let(:cask_token) { "token-launcher" }
it "fails" do
expect(run).to error_with(/token mentions launcher/)
end
end
context "when cask token contains desktop" do
let(:cask_token) { "token-desktop" }
it "fails" do
expect(run).to error_with(/token mentions desktop/)
end
end
context "when cask token contains platform" do
let(:cask_token) { "token-osx" }
it "fails" do
expect(run).to error_with(/token mentions platform/)
end
end
context "when cask token contains architecture" do
let(:cask_token) { "token-x86" }
it "fails" do
expect(run).to error_with(/token mentions architecture/)
end
end
context "when cask token contains framework" do
let(:cask_token) { "token-java" }
it "fails" do
expect(run).to error_with(/cask token mentions framework/)
end
end
context "when cask token is framework" do
let(:cask_token) { "java" }
it "does not fail" do
expect(run).to pass
end
end
context "when cask token is in tap_migrations.json and" do
let(:cask_token) { "token-migrated" }
let(:tap) { CoreCaskTap.instance }
before do
allow(tap).to receive(:tap_migrations).and_return({ cask_token => "homebrew/core" })
allow(cask).to receive(:tap).and_return(tap)
end
context "when `new_cask` is true" do
let(:new_cask) { true }
it "fails" do
expect(run).to error_with("#{cask_token} is listed in tap_migrations.json")
end
end
context "when `new_cask` is false" do
let(:new_cask) { false }
it "does not fail" do
expect(run).to pass
end
end
end
end
describe "locale validation" do
let(:only) { ["languages"] }
let(:cask) do
tmp_cask "locale-cask-test", <<~RUBY
cask 'locale-cask-test' do
version '1.0'
url "https://brew.sh/"
name 'Audit'
homepage 'https://brew.sh/'
app 'Audit.app'
language 'en', default: true do
sha256 '96574251b885c12b48a3495e843e434f9174e02bb83121b578e17d9dbebf1ffb'
'zh-CN'
end
language 'zh-CN' do
sha256 '96574251b885c12b48a3495e843e434f9174e02bb83121b578e17d9dbebf1ffb'
'zh-CN'
end
language 'ZH-CN' do
sha256 '96574251b885c12b48a3495e843e434f9174e02bb83121b578e17d9dbebf1ffb'
'zh-CN'
end
language 'zh-' do
sha256 '96574251b885c12b48a3495e843e434f9174e02bb83121b578e17d9dbebf1ffb'
'zh-CN'
end
language 'zh-cn' do
sha256 '96574251b885c12b48a3495e843e434f9174e02bb83121b578e17d9dbebf1ffb'
'zh-CN'
end
end
RUBY
end
context "when cask locale is invalid" do
it "error with invalid locale" do
expect(run).to error_with(/Locale 'ZH-CN' is invalid\./)
expect(run).to error_with(/Locale 'zh-' is invalid\./)
expect(run).to error_with(/Locale 'zh-cn' is invalid\./)
end
end
end
describe "pkg allow_untrusted checks" do
let(:only) { ["untrusted_pkg"] }
let(:message) { "allow_untrusted is not permitted in official Homebrew Cask taps" }
context "when the Cask has no pkg stanza" do
let(:cask_token) { "basic-cask" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask does not have allow_untrusted" do
let(:cask_token) { "with-uninstall-pkgutil" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask has allow_untrusted" do
let(:cask_token) { "with-allow-untrusted" }
it { is_expected.to error_with(message) }
end
end
describe "signing checks" do
let(:only) { ["signing"] }
let(:tap) { CoreCaskTap.instance }
let(:download_double) { instance_double(Cask::Download) }
let(:unpack_double) { instance_double(UnpackStrategy::Zip) }
before do
allow(audit).to receive_messages(download: download_double, signing?: true)
end
context "when cask is not using a signed artifact" do
let(:cask) do
tmp_cask "signing-cask-test", <<~RUBY
cask 'signing-cask-test' do
version '1.0'
url "https://brew.sh/index.html"
artifact "example.pdf", target: "/Library/Application Support/example"
end
RUBY
end
it "does not fail" do
expect(download_double).not_to receive(:fetch)
expect(UnpackStrategy).not_to receive(:detect)
expect(run).not_to error_with(/Audit\.app/)
end
end
context "when cask is using a signed artifact" do
let(:cask) do
tmp_cask "signing-cask-test", <<~RUBY
cask 'signing-cask-test' do
version '1.0'
url "https://brew.sh/"
pkg 'Audit.app'
end
RUBY
end
it "does not fail since no extract" do
allow(download_double).to receive(:fetch).and_return(Pathname.new("/tmp/test.zip"))
allow(UnpackStrategy).to receive(:detect).and_return(nil)
expect(run).not_to error_with(/Audit\.app/)
end
end
context "when quarantine support is not available" do
let(:cask) do
tmp_cask "signing-cask-test", <<~RUBY
cask 'signing-cask-test' do
version '1.0'
url "https://brew.sh/"
app 'Audit.app'
end
RUBY
end
before do
allow(cask).to receive(:tap).and_return(tap)
allow(Cask::Quarantine).to receive(:available?).and_return(false)
end
it "skips signing audit with warning" do
allow(cask).to receive(:tap).and_return(tap)
expect(audit).to receive(:odebug).with("Quarantine support is not available, skipping signing audit")
expect(run).not_to error_with(/Signature verification failed/)
end
end
end
describe "livecheck should be skipped", :no_api do
let(:only) { ["livecheck_version"] }
let(:online) { true }
let(:message) { /Version '[^']*' differs from '[^']*' retrieved by livecheck\./ }
context "when the Cask has a `livecheck` block using skip" do
let(:cask_token) { "livecheck-skip" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask has a `livecheck` block referencing a Cask using skip" do
let(:cask_token) { "livecheck-skip-reference" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask is deprecated" do
let(:cask_token) { "livecheck-deprecated" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask has a `livecheck` block referencing a deprecated Cask" do
let(:cask_token) { "livecheck-deprecated-reference" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask is disabled" do
let(:cask_token) { "livecheck-disabled" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask has a `livecheck` block referencing a disabled Cask" do
let(:cask_token) { "livecheck-disabled-reference" }
it { is_expected.not_to error_with(message) }
end
context "when version is :latest" do
let(:cask_token) { "livecheck-version-latest" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask has a `livecheck` block referencing a Cask where version is :latest" do
let(:cask_token) { "livecheck-version-latest-reference" }
it { is_expected.not_to error_with(message) }
end
context "when url is unversioned" do
let(:cask_token) { "livecheck-url-unversioned" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask has a `livecheck` block referencing a Cask with an unversioned url" do
let(:cask_token) { "livecheck-url-unversioned-reference" }
it { is_expected.not_to error_with(message) }
end
end
describe "when the Cask stanza requires uninstall" do
let(:only) { ["stanza_requires_uninstall"] }
let(:message) { "installer and pkg stanzas require an uninstall stanza" }
context "when the Cask does not require an uninstall" do
let(:cask_token) { "basic-cask" }
it { is_expected.not_to error_with(message) }
end
context "when the pkg Cask has an uninstall" do
let(:cask_token) { "with-uninstall-pkgutil" }
it { is_expected.not_to error_with(message) }
end
context "when the installer Cask has an uninstall" do
let(:cask_token) { "installer-with-uninstall" }
it { is_expected.not_to error_with(message) }
end
context "when the installer Cask does not have an uninstall" do
let(:cask_token) { "with-installer-manual" }
it { is_expected.to error_with(message) }
end
context "when the pkg Cask does not have an uninstall" do
let(:cask_token) { "pkg-without-uninstall" }
it { is_expected.to error_with(message) }
end
end
describe "preflight stanza checks" do
let(:message) { "only a single preflight stanza is allowed" }
context "when the Cask has no preflight stanza" do
let(:cask_token) { "with-zap-rmdir" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask has only one preflight stanza" do
let(:cask_token) { "with-preflight" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask has multiple preflight stanzas" do
let(:cask_token) { "with-preflight-multi" }
it { is_expected.to error_with(message) }
end
end
describe "postflight stanza checks" do
let(:message) { "only a single postflight stanza is allowed" }
context "when the Cask has no postflight stanza" do
let(:cask_token) { "with-zap-rmdir" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask has only one postflight stanza" do
let(:cask_token) { "with-postflight" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask has multiple postflight stanzas" do
let(:cask_token) { "with-postflight-multi" }
it { is_expected.to error_with(message) }
end
end
describe "uninstall_preflight stanza checks" do
let(:message) { "only a single uninstall_preflight stanza is allowed" }
context "when the Cask has no uninstall_preflight stanza" do
let(:cask_token) { "with-zap-rmdir" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask has only one uninstall_preflight stanza" do
let(:cask_token) { "with-uninstall-preflight" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask has multiple uninstall_preflight stanzas" do
let(:cask_token) { "with-uninstall-preflight-multi" }
it { is_expected.to error_with(message) }
end
end
describe "uninstall_postflight stanza checks" do
let(:message) { "only a single uninstall_postflight stanza is allowed" }
context "when the Cask has no uninstall_postflight stanza" do
let(:cask_token) { "with-zap-rmdir" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask has only one uninstall_postflight stanza" do
let(:cask_token) { "with-uninstall-postflight" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask has multiple uninstall_postflight stanzas" do
let(:cask_token) { "with-uninstall-postflight-multi" }
it { is_expected.to error_with(message) }
end
end
describe "zap stanza checks" do
let(:message) { "only a single zap stanza is allowed" }
context "when the Cask has no zap stanza" do
let(:cask_token) { "with-uninstall-rmdir" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask has only one zap stanza" do
let(:cask_token) { "with-zap-rmdir" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask has multiple zap stanzas" do
let(:cask_token) { "with-zap-multi" }
it { is_expected.to error_with(message) }
end
end
describe "version checks" do
let(:message) { "you should use version :latest instead of version 'latest'" }
context "when version is 'latest'" do
let(:only) { ["no_string_version_latest"] }
let(:cask_token) { "version-latest-string" }
it { is_expected.to error_with(message) }
end
context "when version is :latest" do
let(:only) { ["sha256_no_check_if_latest"] }
let(:cask_token) { "version-latest-with-checksum" }
it { is_expected.not_to error_with(message) }
end
context "when version contains a colon" do
let(:only) { ["version_special_characters"] }
let(:cask_token) { "version-colon" }
let(:message) { "version should not contain colons or slashes" }
it { is_expected.to error_with(message) }
end
end
describe "sha256 checks" do
context "when version is :latest and sha256 is not :no_check" do
let(:only) { ["sha256_no_check_if_latest"] }
let(:cask_token) { "version-latest-with-checksum" }
it { is_expected.to error_with("you should use sha256 :no_check when version is :latest") }
end
context "when sha256 is not a legal SHA-256 digest" do
let(:only) { ["sha256_actually_256"] }
let(:cask_token) { "invalid-sha256" }
it { is_expected.to error_with("sha256 string must be of 64 hexadecimal characters") }
end
context "when sha256 is sha256 for empty string" do
let(:only) { ["sha256_invalid"] }
let(:cask_token) { "sha256-for-empty-string" }
it { is_expected.to error_with(/cannot use the sha256 for an empty string/) }
end
end
describe "hosting with livecheck checks" do
let(:only) { ["hosting_with_livecheck"] }
let(:message) { /please add a livecheck/ }
context "when the download does not use hosting with a livecheck" do
let(:cask_token) { "basic-cask" }
it { is_expected.not_to error_with(message) }
end
context "when the download is hosted on SourceForge and has a livecheck" do
let(:cask_token) { "sourceforge-with-livecheck" }
it { is_expected.not_to error_with(message) }
end
context "when the download is hosted on SourceForge and does not have a livecheck" do
let(:cask_token) { "sourceforge-correct-url-format" }
let(:online) { true }
it { is_expected.to error_with(message) }
end
context "when the download is hosted on DevMate and has a livecheck" do
let(:cask_token) { "devmate-with-livecheck" }
it { is_expected.not_to error_with(message) }
end
context "when the download is hosted on DevMate and does not have a livecheck" do
let(:cask_token) { "devmate-without-livecheck" }
it { is_expected.to error_with(message) }
end
context "when the download is hosted on HockeyApp and has a livecheck" do
let(:cask_token) { "hockeyapp-with-livecheck" }
it { is_expected.not_to error_with(message) }
end
context "when the download is hosted on HockeyApp and does not have a livecheck" do
let(:cask_token) { "hockeyapp-without-livecheck" }
it { is_expected.to error_with(message) }
end
end
describe "latest with livecheck checks" do
let(:only) { ["latest_with_livecheck"] }
let(:message) { "Casks with a `livecheck` should not use `version :latest`." }
context "when the Cask is :latest and does not have a livecheck" do
let(:cask_token) { "version-latest" }
it { is_expected.not_to error_with(message) }
end
context "when the Cask is versioned and has a livecheck with skip information" do
let(:cask_token) { "latest-with-livecheck-skip" }
it { is_expected.to pass }
end
context "when the Cask is versioned and has a livecheck" do
let(:cask_token) { "latest-with-livecheck" }
it { is_expected.to error_with(message) }
end
end
describe "conflicts with" do
let(:only) { ["conflicts_with"] }
let(:tap) { CoreCaskTap.instance }
context "when the Cask has no conflicts" do
let(:cask_token) { "basic-cask" }
it { is_expected.to pass }
end
context "when all conflicting casks exist" do
let(:cask) do
tmp_cask "test-conflicts-cask", <<~RUBY
cask 'test-conflicts-cask' do
version '1.0'
url "https://brew.sh/index.html"
artifact "example.pdf", target: "/Library/Application Support/example"
conflicts_with cask: ["foo", "bar"]
end
RUBY
end
before do
allow(audit).to receive(:core_cask_tokens).and_return(%w[foo bar baz qux])
allow(cask).to receive(:tap).and_return(tap)
end
it { is_expected.to pass }
end
context "when conflicting casks are missing" do
let(:cask) do
tmp_cask "test-conflicts-cask", <<~RUBY
cask 'test-conflicts-cask' do
version '1.0'
url "https://brew.sh/index.html"
artifact "example.pdf", target: "/Library/Application Support/example"
conflicts_with cask: ["foo", "foo@1", "bar", "baz"]
end
RUBY
end
before do
allow(audit).to receive(:core_cask_tokens).and_return(["foo", "baz"])
allow(cask).to receive(:tap).and_return(tap)
end
it { is_expected.to error_with(/cask conflicts with non-existing cask/) }
end
end
describe "denylist checks" do
let(:only) { ["denylist"] }
context "when the Cask is not on the denylist" do
let(:cask_token) { "adobe-air" }
it { is_expected.to pass }
end
context "when the Cask is on the denylist and" do
context "when it's in the official Homebrew tap" do
let(:cask_token) { "adobe-illustrator" }
it { is_expected.to error_with(/#{cask_token} is not allowed: \w+/) }
end
context "when it isn't in the official Homebrew tap" do
let(:cask_token) { "pharo" }
it { is_expected.to pass }
end
end
end
describe "latest with auto_updates checks" do
let(:only) { ["latest_with_auto_updates"] }
let(:message) { "Casks with `version :latest` should not use `auto_updates`." }
context "when the Cask is :latest and does not have auto_updates" do
let(:cask_token) { "version-latest" }
it { is_expected.to pass }
end
context "when the Cask is versioned and does not have auto_updates" do
let(:cask_token) { "basic-cask" }
it { is_expected.to pass }
end
context "when the Cask is versioned and has auto_updates" do
let(:cask_token) { "auto-updates" }
it { is_expected.to pass }
end
context "when the Cask is :latest and has auto_updates" do
let(:cask_token) { "latest-with-auto-updates" }
it { is_expected.to error_with(message) }
end
end
describe "preferred download URL formats" do
let(:only) { ["download_url_format"] }
let(:message) { /URL format incorrect/ }
context "with incorrect SourceForge URL format" do
let(:cask_token) { "sourceforge-incorrect-url-format" }
it { is_expected.to error_with(message) }
end
context "with correct SourceForge URL format" do
let(:cask_token) { "sourceforge-correct-url-format" }
it { is_expected.not_to error_with(message) }
end
context "with correct SourceForge URL format for version :latest" do
let(:cask_token) { "sourceforge-version-latest-correct-url-format" }
it { is_expected.not_to error_with(message) }
end
end
describe "disable OSDN download url" do
let(:only) { ["download_url_is_osdn"] }
let(:message) { /OSDN download urls are disabled./ }
let(:cask_token) { "osdn-urls" }
context "when --strict is not passed" do
it { is_expected.not_to error_with(message) }
end
context "when --strict is passed" do
let(:strict) { true }
it { is_expected.to error_with(message) }
end
end
describe "generic artifact checks" do
let(:only) { ["generic_artifacts"] }
context "with relative target" do
let(:cask_token) { "generic-artifact-relative-target" }
it { is_expected.to error_with(/target must be.*absolute/) }
end
context "with user-relative target" do
let(:cask_token) { "generic-artifact-user-relative-target" }
it { is_expected.not_to error_with(/target must be.*absolute/) }
end
context "with absolute target" do
let(:cask_token) { "generic-artifact-absolute-target" }
it { is_expected.not_to error_with(/target must be.*absolute/) }
end
end
describe "token conflicts" do
let(:cask_token) { "with-binary" }
context "when cask token conflicts with a core formula" do
let(:formula_names) { %w[with-binary other-formula] }
it "warns about conflicts" do
expect(audit).to receive(:core_formula_names).and_return(formula_names)
expect(run).to error_with(/cask token conflicts/)
end
end
end
describe "audit of downloads" do
let(:only) { ["download"] }
let(:cask_token) { "basic-cask" }
let(:cask) { Cask::CaskLoader.load(cask_token) }
let(:download_double) { instance_double(Cask::Download) }
let(:message) { "Download Failed" }
before do
allow(audit).to receive(:download).and_return(download_double)
allow(UnpackStrategy).to receive(:detect).and_return(nil)
end
it "when download and verification succeed it does not fail" do
expect(download_double).to receive(:fetch).and_return(Pathname.new("/tmp/test.zip"))
expect(run).to pass
end
it "when download fails it fails" do # rubocop:todo RSpec/AggregateExamples
expect(download_double).to receive(:fetch).and_raise(StandardError.new(message))
expect(run).to error_with(/#{message}/)
end
end
context "when an exception is raised" do
let(:cask) { instance_double(Cask::Cask) }
let(:only) { ["description"] }
it "fails the audit" do
expect(cask).to receive(:tap).and_raise(StandardError.new)
expect(run).to error_with(/exception while auditing/)
end
end
describe "checking description" do
let(:only) { ["description"] }
let(:cask_token) { "without-description" }
let(:cask) do
tmp_cask cask_token.to_s, <<~RUBY
cask '#{cask_token}' do
version '1.0'
sha256 '8dd95daa037ac02455435446ec7bc737b34567afe9156af7d20b2a83805c1d8a'
url "https://brew.sh/"
name 'Audit'
homepage 'https://brew.sh/'
app 'Audit.app'
end
RUBY
end
context "when `new_cask` is true" do
let(:new_cask) { true }
it "fails" do
expect(run).to error_with(/should have a description/)
end
end
context "when `new_cask` is false" do
let(:new_cask) { false }
it "does not warn" do
expect(run).not_to error_with(/should have a description/)
end
end
context "with description" do
let(:cask_token) { "with-description" }
let(:cask) do
tmp_cask cask_token.to_s, <<~RUBY
cask "#{cask_token}" do
version "1.0"
sha256 "8dd95daa037ac02455435446ec7bc737b34567afe9156af7d20b2a83805c1d8a"
url "https://brew.sh/\#{version}.zip"
name "Audit"
desc "Cask Auditor"
homepage "https://brew.sh/"
app "Audit.app"
end
RUBY
end
it "passes" do
expect(run).to pass
end
end
end
describe "checking verified" do
| ruby | BSD-2-Clause | fe0a384e3a04605192726c149570fbe33a8996b0 | 2026-01-04T15:37:27.366412Z | true |
Homebrew/brew | https://github.com/Homebrew/brew/blob/fe0a384e3a04605192726c149570fbe33a8996b0/Library/Homebrew/test/cask/upgrade_spec.rb | Library/Homebrew/test/cask/upgrade_spec.rb | # frozen_string_literal: true
require "cask/upgrade"
RSpec.describe Cask::Upgrade, :cask do
let(:version_latest_paths) do
[
version_latest.config.appdir.join("Caffeine Mini.app"),
version_latest.config.appdir.join("Caffeine Pro.app"),
]
end
let(:version_latest) { Cask::CaskLoader.load("version-latest") }
let(:auto_updates_path) { auto_updates.config.appdir.join("MyFancyApp.app") }
let(:auto_updates) { Cask::CaskLoader.load("auto-updates") }
let(:local_transmission_path) { local_transmission.config.appdir.join("Transmission.app") }
let(:local_transmission) { Cask::CaskLoader.load("local-transmission-zip") }
let(:local_caffeine_path) { local_caffeine.config.appdir.join("Caffeine.app") }
let(:local_caffeine) { Cask::CaskLoader.load("local-caffeine") }
let(:renamed_app) { Cask::CaskLoader.load("renamed-app") }
let(:renamed_app_old_path) { renamed_app.config.appdir.join("OldApp.app") }
let(:renamed_app_new_path) { renamed_app.config.appdir.join("NewApp.app") }
let(:args) do
parser = Homebrew::CLI::Parser.new(Homebrew::Cmd::Brew)
parser.cask_options
parser.args
end
before do
installed.each do |cask|
Cask::Installer.new(Cask::CaskLoader.load(cask_path(cask))).install
end
end
context "when the upgrade is a dry run" do
let(:installed) do
[
"outdated/local-caffeine",
"outdated/local-transmission-zip",
"outdated/auto-updates",
"outdated/version-latest",
"outdated/renamed-app",
]
end
describe 'without --greedy it ignores the Casks with "version latest" or "auto_updates true"' do
it "would update all the installed Casks when no token is provided" do
expect(described_class).not_to receive(:upgrade_cask)
expect(local_caffeine).to be_installed
expect(local_caffeine_path).to be_a_directory
expect(local_caffeine.installed_version).to eq "1.2.2"
expect(local_transmission).to be_installed
expect(local_transmission_path).to be_a_directory
expect(local_transmission.installed_version).to eq "2.60"
expect(renamed_app).to be_installed
expect(renamed_app_old_path).to be_a_directory
expect(renamed_app_new_path).not_to be_a_directory
expect(renamed_app.installed_version).to eq "1.0.0"
described_class.upgrade_casks!(dry_run: true, args:)
expect(local_caffeine).to be_installed
expect(local_caffeine_path).to be_a_directory
expect(local_caffeine.installed_version).to eq "1.2.2"
expect(local_transmission).to be_installed
expect(local_transmission_path).to be_a_directory
expect(local_transmission.installed_version).to eq "2.60"
expect(renamed_app).to be_installed
expect(renamed_app_old_path).to be_a_directory
expect(renamed_app_new_path).not_to be_a_directory
expect(renamed_app.installed_version).to eq "1.0.0"
end
it "would update only the Casks specified in the command line" do
expect(described_class).not_to receive(:upgrade_cask)
expect(local_caffeine).to be_installed
expect(local_caffeine_path).to be_a_directory
expect(local_caffeine.installed_version).to eq "1.2.2"
expect(local_transmission).to be_installed
expect(local_transmission_path).to be_a_directory
expect(local_transmission.installed_version).to eq "2.60"
described_class.upgrade_casks!(local_caffeine, dry_run: true, args:)
expect(local_caffeine).to be_installed
expect(local_caffeine_path).to be_a_directory
expect(local_caffeine.installed_version).to eq "1.2.2"
expect(local_transmission).to be_installed
expect(local_transmission_path).to be_a_directory
expect(local_transmission.installed_version).to eq "2.60"
end
it 'would update "auto_updates" and "latest" Casks when their tokens are provided in the command line' do
expect(described_class).not_to receive(:upgrade_cask)
expect(local_caffeine).to be_installed
expect(local_caffeine_path).to be_a_directory
expect(local_caffeine.installed_version).to eq "1.2.2"
expect(auto_updates).to be_installed
expect(auto_updates_path).to be_a_directory
expect(auto_updates.installed_version).to eq "2.57"
expect(renamed_app).to be_installed
expect(renamed_app_old_path).to be_a_directory
expect(renamed_app_new_path).not_to be_a_directory
expect(renamed_app.installed_version).to eq "1.0.0"
described_class.upgrade_casks!(local_caffeine, auto_updates, dry_run: true, args:)
expect(local_caffeine).to be_installed
expect(local_caffeine_path).to be_a_directory
expect(local_caffeine.installed_version).to eq "1.2.2"
expect(auto_updates).to be_installed
expect(auto_updates_path).to be_a_directory
expect(auto_updates.installed_version).to eq "2.57"
expect(renamed_app).to be_installed
expect(renamed_app_old_path).to be_a_directory
expect(renamed_app_new_path).not_to be_a_directory
expect(renamed_app.installed_version).to eq "1.0.0"
end
end
describe "with --greedy it checks additional Casks" do
it 'would include the Casks with "auto_updates true" or "version latest"' do
expect(described_class).not_to receive(:upgrade_cask)
expect(local_caffeine).to be_installed
expect(local_caffeine_path).to be_a_directory
expect(local_caffeine.installed_version).to eq "1.2.2"
expect(auto_updates).to be_installed
expect(auto_updates_path).to be_a_directory
expect(auto_updates.installed_version).to eq "2.57"
expect(local_transmission).to be_installed
expect(local_transmission_path).to be_a_directory
expect(local_transmission.installed_version).to eq "2.60"
expect(renamed_app).to be_installed
expect(renamed_app_old_path).to be_a_directory
expect(renamed_app_new_path).not_to be_a_directory
expect(renamed_app.installed_version).to eq "1.0.0"
expect(version_latest).to be_installed
# Change download sha so that :latest cask decides to update itself
version_latest.download_sha_path.write("fake download sha")
expect(version_latest.outdated_download_sha?).to be(true)
described_class.upgrade_casks!(greedy: true, dry_run: true, args:)
expect(local_caffeine).to be_installed
expect(local_caffeine_path).to be_a_directory
expect(local_caffeine.installed_version).to eq "1.2.2"
expect(auto_updates).to be_installed
expect(auto_updates_path).to be_a_directory
expect(auto_updates.installed_version).to eq "2.57"
expect(local_transmission).to be_installed
expect(local_transmission_path).to be_a_directory
expect(local_transmission.installed_version).to eq "2.60"
expect(renamed_app).to be_installed
expect(renamed_app_old_path).to be_a_directory
expect(renamed_app_new_path).not_to be_a_directory
expect(renamed_app.installed_version).to eq "1.0.0"
expect(version_latest).to be_installed
expect(version_latest.outdated_download_sha?).to be(true)
end
it 'would update outdated Casks with "auto_updates true"' do
expect(described_class).not_to receive(:upgrade_cask)
expect(auto_updates).to be_installed
expect(auto_updates_path).to be_a_directory
expect(auto_updates.installed_version).to eq "2.57"
described_class.upgrade_casks!(auto_updates, dry_run: true, greedy: true, args:)
expect(auto_updates).to be_installed
expect(auto_updates_path).to be_a_directory
expect(auto_updates.installed_version).to eq "2.57"
end
it 'would update outdated Casks with "version latest"' do
expect(described_class).not_to receive(:upgrade_cask)
expect(version_latest).to be_installed
expect(version_latest_paths).to all be_a_directory
expect(version_latest.installed_version).to eq "latest"
# Change download sha so that :latest cask decides to update itself
version_latest.download_sha_path.write("fake download sha")
expect(version_latest.outdated_download_sha?).to be(true)
described_class.upgrade_casks!(version_latest, dry_run: true, greedy: true, args:)
expect(version_latest).to be_installed
expect(version_latest_paths).to all be_a_directory
expect(version_latest.installed_version).to eq "latest"
expect(version_latest.outdated_download_sha?).to be(true)
end
end
end
context "when an upgrade failed" do
let(:installed) do
[
"outdated/bad-checksum",
"outdated/will-fail-if-upgraded",
]
end
let(:output_reverted) do
Regexp.new <<~EOS
Warning: Reverting upgrade for Cask .*
EOS
end
it "restores the old Cask if the upgrade failed" do
will_fail_if_upgraded = Cask::CaskLoader.load("will-fail-if-upgraded")
will_fail_if_upgraded_path = will_fail_if_upgraded.config.appdir.join("container")
expect(will_fail_if_upgraded).to be_installed
expect(will_fail_if_upgraded_path).to be_a_file
expect(will_fail_if_upgraded.installed_version).to eq "1.2.2"
expect do
described_class.upgrade_casks!(will_fail_if_upgraded, args:)
end.to raise_error(Cask::CaskError).and output(output_reverted).to_stderr
expect(will_fail_if_upgraded).to be_installed
expect(will_fail_if_upgraded_path).to be_a_file
expect(will_fail_if_upgraded.installed_version).to eq "1.2.2"
expect(will_fail_if_upgraded.staged_path).not_to exist
end
it "does not restore the old Cask if the upgrade failed pre-install" do
bad_checksum = Cask::CaskLoader.load("bad-checksum")
bad_checksum_path = bad_checksum.config.appdir.join("Caffeine.app")
expect(bad_checksum).to be_installed
expect(bad_checksum_path).to be_a_directory
expect(bad_checksum.installed_version).to eq "1.2.2"
expect do
described_class.upgrade_casks!(bad_checksum, args:)
end.to raise_error(ChecksumMismatchError).and(not_to_output(output_reverted).to_stderr)
expect(bad_checksum).to be_installed
expect(bad_checksum_path).to be_a_directory
expect(bad_checksum.installed_version).to eq "1.2.2"
expect(bad_checksum.staged_path).not_to exist
end
end
context "when there were multiple failures" do
let(:installed) do
[
"outdated/bad-checksum",
"outdated/local-transmission-zip",
"outdated/bad-checksum2",
]
end
it "does not end the upgrade process" do
bad_checksum = Cask::CaskLoader.load("bad-checksum")
bad_checksum_path = bad_checksum.config.appdir.join("Caffeine.app")
bad_checksum_2 = Cask::CaskLoader.load("bad-checksum2")
bad_checksum_2_path = bad_checksum_2.config.appdir.join("container")
expect(bad_checksum).to be_installed
expect(bad_checksum_path).to be_a_directory
expect(bad_checksum.installed_version).to eq "1.2.2"
expect(local_transmission).to be_installed
expect(local_transmission_path).to be_a_directory
expect(local_transmission.installed_version).to eq "2.60"
expect(bad_checksum_2).to be_installed
expect(bad_checksum_2_path).to be_a_file
expect(bad_checksum_2.installed_version).to eq "1.2.2"
expect do
described_class.upgrade_casks!(args:)
end.to raise_error(Cask::MultipleCaskErrors)
expect(bad_checksum).to be_installed
expect(bad_checksum_path).to be_a_directory
expect(bad_checksum.installed_version).to eq "1.2.2"
expect(bad_checksum.staged_path).not_to exist
expect(local_transmission).to be_installed
expect(local_transmission_path).to be_a_directory
expect(local_transmission.installed_version).to eq "2.61"
expect(bad_checksum_2).to be_installed
expect(bad_checksum_2_path).to be_a_file
expect(bad_checksum_2.installed_version).to eq "1.2.2"
expect(bad_checksum_2.staged_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/cask/list_spec.rb | Library/Homebrew/test/cask/list_spec.rb | # frozen_string_literal: true
require "cask/list"
RSpec.describe Cask::List, :cask do
it "lists the installed Casks in a pretty fashion" do
casks = %w[local-caffeine local-transmission].map { |c| Cask::CaskLoader.load(c) }
casks.each do |c|
InstallHelper.install_with_caskfile(c)
end
expect do
described_class.list_casks
end.to output(<<~EOS).to_stdout
local-caffeine
local-transmission
EOS
end
it "lists oneline" do
casks = %w[
local-caffeine
third-party/tap/third-party-cask
local-transmission
].map { |c| Cask::CaskLoader.load(c) }
casks.each do |c|
InstallHelper.install_with_caskfile(c)
end
expect do
described_class.list_casks(one: true)
end.to output(<<~EOS).to_stdout
local-caffeine
local-transmission
third-party-cask
EOS
end
it "lists full names" do
casks = %w[
local-caffeine
third-party/tap/third-party-cask
local-transmission
].map { |c| Cask::CaskLoader.load(c) }
casks.each do |c|
InstallHelper.install_with_caskfile(c)
end
expect do
described_class.list_casks(full_name: true)
end.to output(<<~EOS).to_stdout
local-caffeine
local-transmission
third-party/tap/third-party-cask
EOS
end
describe "lists versions" do
let(:casks) do
[
"local-caffeine",
"local-transmission",
].map { |token| Cask::CaskLoader.load(token) }
end
let(:expected_output) do
<<~EOS
local-caffeine 1.2.3
local-transmission 2.61
EOS
end
before do
casks.each do |cask|
InstallHelper.install_with_caskfile(cask)
end
end
it "of all installed Casks" do
expect do
described_class.list_casks(versions: true)
end.to output(expected_output).to_stdout
end
it "of given Casks" do
expect do
described_class.list_casks(*casks, versions: true)
end.to output(expected_output).to_stdout
end
end
describe "given a set of installed Casks" do
let(:caffeine) { Cask::CaskLoader.load(cask_path("local-caffeine")) }
let(:transmission) { Cask::CaskLoader.load(cask_path("local-transmission-zip")) }
let(:casks) { [caffeine, transmission] }
it "lists the installed files for those Casks" do
casks.each { InstallHelper.install_without_artifacts_with_caskfile(it) }
transmission.artifacts.select { |a| a.is_a?(Cask::Artifact::App) }.each do |artifact|
artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end
expect do
described_class.list_casks(transmission, caffeine)
end.to output(<<~EOS).to_stdout
==> App
#{transmission.config.appdir.join("Transmission.app")} (#{transmission.config.appdir.join("Transmission.app").abv})
==> App
Missing App: #{caffeine.config.appdir.join("Caffeine.app")}
EOS
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/cask/denylist_spec.rb | Library/Homebrew/test/cask/denylist_spec.rb | # frozen_string_literal: true
require "cask/denylist"
RSpec.describe Cask::Denylist, :cask do
describe "::reason" do
matcher :disallow do |name|
match do |expected|
expected.reason(name)
end
end
specify(:aggregate_failures) do
expect(subject).not_to disallow("adobe-air") # rubocop:todo RSpec/NamedSubject
expect(subject).to disallow("adobe-after-effects") # rubocop:todo RSpec/NamedSubject
expect(subject).to disallow("adobe-illustrator") # rubocop:todo RSpec/NamedSubject
expect(subject).to disallow("adobe-indesign") # rubocop:todo RSpec/NamedSubject
expect(subject).to disallow("adobe-photoshop") # rubocop:todo RSpec/NamedSubject
expect(subject).to disallow("adobe-premiere") # rubocop:todo RSpec/NamedSubject
expect(subject).to disallow("pharo") # rubocop:todo RSpec/NamedSubject
expect(subject).not_to disallow("allowed-cask") # 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/cask/pkg_spec.rb | Library/Homebrew/test/cask/pkg_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Pkg, :cask do
describe "#uninstall" do
let(:fake_system_command) { NeverSudoSystemCommand }
let(:empty_response) do
instance_double(
SystemCommand::Result,
stdout: "",
plist: { "volume" => "/", "install-location" => "", "paths" => {} },
)
end
let(:pkg) { described_class.new("my.fake.pkg", fake_system_command) }
it "removes files and dirs referenced by the pkg" do
some_files = Array.new(3) { Pathname.new(Tempfile.new("plain_file").path) }
some_specials = Array.new(3) { Pathname.new(Tempfile.new("special_file").path) }
some_dirs = Array.new(3) { mktmpdir }
root_dir = Pathname.new(mktmpdir)
allow(pkg).to receive_messages(pkgutil_bom_files: some_files, pkgutil_bom_specials: some_specials,
pkgutil_bom_dirs: some_dirs, root: root_dir)
allow(pkg).to receive(:forget)
pkg.uninstall
some_files.each do |file|
expect(file).not_to exist
end
some_specials.each do |file|
expect(file).not_to exist
end
some_dirs.each do |dir|
expect(dir).not_to exist
end
expect(root_dir).not_to exist
ensure
some_files&.each { |path| FileUtils.rm_rf(path) }
some_specials&.each { |path| FileUtils.rm_rf(path) }
some_dirs&.each { |path| FileUtils.rm_rf(path) }
FileUtils.rm_rf(root_dir) if root_dir
end
describe "pkgutil" do
it "forgets the pkg" do
allow(fake_system_command).to receive(:run!).with(
"/usr/sbin/pkgutil",
args: ["--pkg-info-plist", "my.fake.pkg"],
).and_return(empty_response)
expect(fake_system_command).to receive(:run!).with(
"/usr/sbin/pkgutil",
args: ["--files", "my.fake.pkg"],
).and_return(empty_response)
expect(fake_system_command).to receive(:run!).with(
"/usr/sbin/pkgutil",
args: ["--forget", "my.fake.pkg"],
sudo: true,
sudo_as_root: true,
)
pkg.uninstall
end
end
it "removes broken symlinks" do
fake_root = mktmpdir
fake_dir = mktmpdir
fake_file = fake_dir.join("ima_file").tap do |path|
FileUtils.touch(path)
end
intact_symlink = fake_dir.join("intact_symlink").tap { |path| path.make_symlink(fake_file) }
broken_symlink = fake_dir.join("broken_symlink").tap { |path| path.make_symlink("im_nota_file") }
allow(pkg).to receive_messages(pkgutil_bom_specials: [], pkgutil_bom_files: [], pkgutil_bom_dirs: [fake_dir],
root: fake_root)
allow(pkg).to receive(:forget)
pkg.uninstall
expect(intact_symlink).to exist
expect(broken_symlink).not_to exist
expect(fake_dir).to exist
expect(fake_root).not_to exist
ensure
FileUtils.rm_rf(fake_dir) if fake_dir
FileUtils.rm_rf(fake_root) if fake_root
end
it "snags permissions on ornery dirs, but returns them afterwards" do
fake_root = mktmpdir
fake_dir = mktmpdir
fake_file = fake_dir.join("ima_unrelated_file").tap { |path| FileUtils.touch(path) }
fake_dir.chmod(0000)
allow(pkg).to receive_messages(pkgutil_bom_specials: [], pkgutil_bom_files: [], pkgutil_bom_dirs: [fake_dir],
root: fake_root)
allow(pkg).to receive(:forget)
# This is expected to fail in tests since we don't use `sudo`.
allow(fake_system_command).to receive(:run!).and_call_original
expect(fake_system_command).to receive(:run!).with(
"/usr/bin/xargs",
args: ["-0", "--", a_string_including("rmdir")],
input: [fake_dir].join("\0"),
sudo: true,
sudo_as_root: true,
).and_return(instance_double(SystemCommand::Result, stdout: ""))
pkg.uninstall
expect(fake_dir).to be_a_directory
expect(fake_dir.stat.mode % 01000).to eq(0)
fake_dir.chmod(0777)
expect(fake_file).to be_a_file
ensure
if fake_dir
fake_dir.chmod(0777)
FileUtils.rm_rf(fake_dir)
end
FileUtils.rm_rf(fake_root) if fake_root
end
end
describe "#info" do
let(:fake_system_command) { class_double(SystemCommand) }
let(:volume) { "/" }
let(:install_location) { "tmp" }
let(:pkg_id) { "my.fancy.package.main" }
let(:pkg_files) do
%w[
fancy/bin/fancy.exe
fancy/var/fancy.data
]
end
let(:pkg_directories) do
%w[
fancy
fancy/bin
fancy/var
]
end
let(:pkg_info_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>install-location</key>
<string>#{install_location}</string>
<key>volume</key>
<string>#{volume}</string>
<key>paths</key>
<dict>
#{(pkg_files + pkg_directories).map { |f| "<key>#{f}</key><dict></dict>" }.join}
</dict>
</dict>
</plist>
XML
end
it "correctly parses a Property List" do
pkg = described_class.new(pkg_id, fake_system_command)
expect(fake_system_command).to receive(:run!).with(
"/usr/sbin/pkgutil",
args: ["--pkg-info-plist", pkg_id],
).and_return(
SystemCommand::Result.new(
["/usr/sbin/pkgutil", "--pkg-info-plist", pkg_id],
[[:stdout, pkg_info_plist]],
instance_double(Process::Status, exitstatus: 0),
secrets: [],
),
)
info = pkg.info
expect(info["install-location"]).to eq(install_location)
expect(info["volume"]).to eq(volume)
expect(info["paths"].keys).to eq(pkg_files + pkg_directories)
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/cask/depends_on_spec.rb | Library/Homebrew/test/cask/depends_on_spec.rb | # frozen_string_literal: true
# TODO: this test should be named after the corresponding class, once
# that class is abstracted from installer.rb
# rubocop:disable RSpec/DescribeClass
RSpec.describe "Satisfy Dependencies and Requirements", :cask do
# rubocop:enable RSpec/DescribeClass
subject(:install) do
Cask::Installer.new(cask).install
end
describe "depends_on cask" do
let(:dependency) { Cask::CaskLoader.load(cask.depends_on.cask.first) }
let(:cask) { Cask::CaskLoader.load(cask_path("with-depends-on-cask")) }
it "installs the dependency of a Cask and the Cask itself" do
expect { install }.not_to raise_error
expect(cask).to be_installed
expect(dependency).to be_installed
end
context "when depends_on cask is cyclic" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-depends-on-cask-cyclic")) }
it {
expect { install }.to raise_error(
Cask::CaskCyclicDependencyError,
"Cask 'with-depends-on-cask-cyclic' includes cyclic dependencies " \
"on other Casks: with-depends-on-cask-cyclic-helper",
)
}
end
end
describe "depends_on macos" do
context "with an array" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-depends-on-macos-array")) }
it "does not raise an error" do
expect { install }.not_to raise_error
end
end
context "with a comparison" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-depends-on-macos-comparison")) }
it "does not raise an error" do
expect { install }.not_to raise_error
end
end
context "with a symbol" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-depends-on-macos-symbol")) }
it "does not raise an error" do
expect { install }.not_to raise_error
end
end
context "when not satisfied" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-depends-on-macos-failure")) }
it "raises an error" do
expect { install }.to raise_error(Cask::CaskError)
end
end
end
describe "depends_on arch" do
context "when satisfied" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-depends-on-arch")) }
it "does not raise an error" do
expect { install }.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/cask/download_spec.rb | Library/Homebrew/test/cask/download_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Download, :cask do
describe "#download_name" do
subject(:download_name) { described_class.new(cask).send(:download_name) }
let(:download) { described_class.new(cask) }
let(:token) { "example-cask" }
let(:full_token) { token }
let(:url) { instance_double(URL, to_s: url_to_s, specs: {}) }
let(:url_to_s) { "https://example.com/app.dmg" }
let(:cask) { instance_double(Cask::Cask, token:, full_token:, version:, url:) }
before { allow(download).to receive(:determine_url).and_return(url) }
context "when cask has no version" do
let(:version) { nil }
it "returns the URL basename" do
expect(download_name).to eq "app.dmg"
end
end
context "when the URL basename would create a short symlink name" do
let(:version) { "1.0.0" }
it "returns the URL basename" do
expect(download_name).to eq "app.dmg"
end
end
context "when the URL basename would create a long symlink name" do
let(:version) do
"1.2.3,kch23dmbz6whmoogcbss45yi4c2kkq15gmemwys0hgwd3l7cahmx2ciagrlrgppatxaxarzazmdoerzmiisuf7mul4lgcays2dl3nl"
end
let(:url_to_s) { "https://example.com/app.dmg?#{Array.new(50) { |i| "param#{i}=value#{i}" }.join("&")}" }
it "returns the cask token when symlink would be too long" do
expect(download_name).to eq "example-cask"
end
context "when the cask is in a third-party tap" do
let(:full_token) { "third-party/tap/example-cask" }
it "returns the full token with slashes replaced by dashes" do
expect(download_name).to eq "third-party--tap--example-cask"
end
end
end
end
describe "#verify_download_integrity" do
subject(:verification) { described_class.new(cask).verify_download_integrity(downloaded_path) }
let(:tap) { nil }
let(:cask) { instance_double(Cask::Cask, token: "cask", sha256: expected_sha256, tap:) }
let(:cafebabe) { "cafebabecafebabecafebabecafebabecafebabecafebabecafebabecafebabe" }
let(:deadbeef) { "deadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef" }
let(:computed_sha256) { cafebabe }
let(:downloaded_path) { Pathname.new("cask.zip") }
before do
allow(downloaded_path).to receive_messages(file?: true, sha256: computed_sha256)
end
context "when the expected checksum is :no_check" do
let(:expected_sha256) { :no_check }
it "warns about skipping the check" do
expect { verification }.to output(/skipping verification/).to_stderr
end
context "with an official tap" do
let(:tap) { CoreCaskTap.instance }
it "does not warn about skipping the check" do
expect { verification }.not_to output(/skipping verification/).to_stderr
end
end
end
context "when expected and computed checksums match" do
let(:expected_sha256) { Checksum.new(cafebabe) }
it "does not raise an error" do
expect { verification }.not_to raise_error
end
end
context "when the expected checksum is nil" do
let(:expected_sha256) { nil }
it "outputs an error" do
expect { verification }.to output(/sha256 "#{computed_sha256}"/).to_stderr
end
end
context "when the expected checksum is empty" do
let(:expected_sha256) { Checksum.new("") }
it "outputs an error" do
expect { verification }.to output(/sha256 "#{computed_sha256}"/).to_stderr
end
end
context "when expected and computed checksums do not match" do
let(:expected_sha256) { Checksum.new(deadbeef) }
it "raises an error" do
expect { verification }.to raise_error ChecksumMismatchError
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/cask/uninstall_spec.rb | Library/Homebrew/test/cask/uninstall_spec.rb | # frozen_string_literal: true
require "cask/uninstall"
RSpec.describe Cask::Uninstall, :cask do
describe ".uninstall_casks" do
it "displays the uninstallation progress" do
caffeine = Cask::CaskLoader.load(cask_path("local-caffeine"))
Cask::Installer.new(caffeine).install
output = Regexp.new <<~EOS
==> Uninstalling Cask local-caffeine
==> Backing App 'Caffeine.app' up to '.*Caffeine.app'
==> Removing App '.*Caffeine.app'
==> Purging files for version 1.2.3 of Cask local-caffeine
EOS
expect do
described_class.uninstall_casks(caffeine)
end.to output(output).to_stdout
end
it "shows an error when a Cask is provided that's not installed" do
caffeine = Cask::CaskLoader.load(cask_path("local-caffeine"))
expect { described_class.uninstall_casks(caffeine) }
.to raise_error(Cask::CaskNotInstalledError, /is not installed/)
end
it "tries anyway on a non-present Cask when --force is given" do
caffeine = Cask::CaskLoader.load(cask_path("local-caffeine"))
expect do
described_class.uninstall_casks(caffeine, force: true)
end.not_to raise_error
end
it "can uninstall and unlink multiple Casks at once" do
caffeine = Cask::CaskLoader.load(cask_path("local-caffeine"))
transmission = Cask::CaskLoader.load(cask_path("local-transmission-zip"))
Cask::Installer.new(caffeine).install
Cask::Installer.new(transmission).install
expect(caffeine).to be_installed
expect(transmission).to be_installed
described_class.uninstall_casks(caffeine, transmission)
expect(caffeine).not_to be_installed
expect(caffeine.config.appdir.join("Transmission.app")).not_to exist
expect(transmission).not_to be_installed
expect(transmission.config.appdir.join("Caffeine.app")).not_to exist
end
it "can uninstall Casks when the uninstall script is missing, but only when using `--force`" do
cask = Cask::CaskLoader.load(cask_path("with-uninstall-script-app"))
Cask::Installer.new(cask).install
expect(cask).to be_installed
FileUtils.rm_r(cask.config.appdir.join("MyFancyApp.app"))
expect { described_class.uninstall_casks(cask) }
.to raise_error(Cask::CaskError, /uninstall script .* does not exist/)
expect(cask).to be_installed
expect do
described_class.uninstall_casks(cask, force: true)
end.not_to raise_error
expect(cask).not_to be_installed
end
describe "when multiple versions of a cask are installed" do
let(:token) { "versioned-cask" }
let(:first_installed_version) { "1.2.3" }
let(:last_installed_version) { "4.5.6" }
let(:timestamped_versions) do
[
[first_installed_version, "123000"],
[last_installed_version, "456000"],
]
end
let(:caskroom_path) { Cask::Caskroom.path.join(token).tap(&:mkpath) }
before do
timestamped_versions.each do |timestamped_version|
caskroom_path.join(".metadata", *timestamped_version, "Casks").tap(&:mkpath)
.join("#{token}.rb").open("w") do |caskfile|
caskfile.puts <<~RUBY
cask '#{token}' do
version '#{timestamped_version[0]}'
end
RUBY
end
caskroom_path.join(timestamped_version[0]).mkpath
end
end
it "uninstalls one version at a time" do
described_class.uninstall_casks(Cask::Cask.new("versioned-cask"))
expect(caskroom_path.join(first_installed_version)).to exist
expect(caskroom_path.join(last_installed_version)).not_to exist
expect(caskroom_path).to exist
described_class.uninstall_casks(Cask::Cask.new("versioned-cask"))
expect(caskroom_path.join(first_installed_version)).not_to exist
expect(caskroom_path).not_to exist
end
end
context "when Casks in Taps have been renamed or removed" do
let(:app) { Cask::Config.new.appdir.join("ive-been-renamed.app") }
let(:caskroom_path) { Cask::Caskroom.path.join("ive-been-renamed").tap(&:mkpath) }
let(:saved_caskfile) do
caskroom_path.join(".metadata", "latest", "timestamp", "Casks").join("ive-been-renamed.rb")
end
before do
app.tap(&:mkpath)
.join("Contents")
.tap(&:mkpath)
.join("Info.plist")
.tap { |file| FileUtils.touch(file) }
caskroom_path.mkpath
saved_caskfile.dirname.mkpath
File.write saved_caskfile, <<~RUBY
cask 'ive-been-renamed' do
version :latest
app 'ive-been-renamed.app'
end
RUBY
end
it "can still uninstall them" do
described_class.uninstall_casks(Cask::Cask.new("ive-been-renamed"))
expect(app).not_to exist
expect(caskroom_path).not_to exist
end
end
end
describe ".check_dependent_casks" do
it "shows error message when trying to uninstall a cask with dependents" do
depends_on_cask = Cask::CaskLoader.load(cask_path("with-depends-on-cask"))
local_transmission = Cask::CaskLoader.load(cask_path("local-transmission-zip"))
allow(Cask::Caskroom).to receive(:casks).and_return([depends_on_cask, local_transmission])
output = <<~EOS
Error: Refusing to uninstall local-transmission-zip
because it is required by with-depends-on-cask, which is currently installed.
You can override this and force removal with:
brew uninstall --ignore-dependencies local-transmission-zip
EOS
expect do
described_class.check_dependent_casks(local_transmission, named_args: ["local-transmission-zip"])
end.to output(output).to_stderr
end
it "shows error message when trying to uninstall a cask with multiple dependents" do
depends_on_cask = Cask::CaskLoader.load(cask_path("with-depends-on-cask"))
depends_on_cask_multiple = Cask::CaskLoader.load(cask_path("with-depends-on-cask-multiple"))
local_transmission = Cask::CaskLoader.load(cask_path("local-transmission-zip"))
allow(Cask::Caskroom).to receive(:casks).and_return([
depends_on_cask,
depends_on_cask_multiple,
local_transmission,
])
output = <<~EOS
Error: Refusing to uninstall local-transmission-zip
because it is required by with-depends-on-cask and with-depends-on-cask-multiple, which are currently installed.
You can override this and force removal with:
brew uninstall --ignore-dependencies local-transmission-zip
EOS
expect do
described_class.check_dependent_casks(local_transmission, named_args: ["local-transmission-zip"])
end.to output(output).to_stderr
end
it "shows error message when trying to uninstall multiple casks with dependents" do
depends_on_cask = Cask::CaskLoader.load(cask_path("with-depends-on-cask"))
depends_on_everything = Cask::CaskLoader.load(cask_path("with-depends-on-everything"))
local_caffeine = Cask::CaskLoader.load(cask_path("local-caffeine"))
local_transmission = Cask::CaskLoader.load(cask_path("local-transmission-zip"))
named_args = %w[local-transmission-zip local-caffeine]
allow(Cask::Caskroom).to receive(:casks).and_return([
depends_on_cask,
depends_on_everything,
local_caffeine,
local_transmission,
])
output = <<~EOS
Error: Refusing to uninstall local-transmission-zip and local-caffeine
because they are required by with-depends-on-cask and with-depends-on-everything, which are currently installed.
You can override this and force removal with:
brew uninstall --ignore-dependencies local-transmission-zip local-caffeine
EOS
expect do
described_class.check_dependent_casks(local_transmission, local_caffeine, named_args:)
end.to output(output).to_stderr
end
it "does not output an error if no dependents found" do
depends_on_cask = Cask::CaskLoader.load(cask_path("with-depends-on-cask"))
local_transmission = Cask::CaskLoader.load(cask_path("local-transmission"))
allow(Cask::Caskroom).to receive(:casks).and_return([depends_on_cask, local_transmission])
expect do
described_class.check_dependent_casks(depends_on_cask, named_args: ["with-depends-on-cask"])
end.not_to output.to_stderr
end
it "lists other named args when showing the error message" do
depends_on_cask = Cask::CaskLoader.load(cask_path("with-depends-on-cask"))
local_transmission = Cask::CaskLoader.load(cask_path("local-transmission-zip"))
named_args = %w[local-transmission-zip foo bar baz qux]
allow(Cask::Caskroom).to receive(:casks).and_return([depends_on_cask, local_transmission])
output = <<~EOS
Error: Refusing to uninstall local-transmission-zip
because it is required by with-depends-on-cask, which is currently installed.
You can override this and force removal with:
brew uninstall --ignore-dependencies local-transmission-zip foo bar baz qux
EOS
expect do
described_class.check_dependent_casks(local_transmission, named_args:)
end.to output(output).to_stderr
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/cask/installer_spec.rb | Library/Homebrew/test/cask/installer_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Installer, :cask do
describe "install" do
it "downloads and installs a nice fresh Cask" do
caffeine = Cask::CaskLoader.load(cask_path("local-caffeine"))
described_class.new(caffeine).install
expect(Cask::Caskroom.path.join("local-caffeine", caffeine.version)).to be_a_directory
expect(caffeine.config.appdir.join("Caffeine.app")).to be_a_directory
end
it "works with HFS+ dmg-based Casks" do
asset = Cask::CaskLoader.load(cask_path("container-dmg"))
described_class.new(asset).install
expect(Cask::Caskroom.path.join("container-dmg", asset.version)).to be_a_directory
expect(asset.config.appdir.join("container")).to be_a_file
end
it "works with tar-gz-based Casks" do
asset = Cask::CaskLoader.load(cask_path("container-tar-gz"))
described_class.new(asset).install
expect(Cask::Caskroom.path.join("container-tar-gz", asset.version)).to be_a_directory
expect(asset.config.appdir.join("container")).to be_a_file
end
it "works with xar-based Casks" do
asset = Cask::CaskLoader.load(cask_path("container-xar"))
described_class.new(asset).install
expect(Cask::Caskroom.path.join("container-xar", asset.version)).to be_a_directory
expect(asset.config.appdir.join("container")).to be_a_file
end
it "works with pure bzip2-based Casks" do
asset = Cask::CaskLoader.load(cask_path("container-bzip2"))
described_class.new(asset).install
expect(Cask::Caskroom.path.join("container-bzip2", asset.version)).to be_a_directory
expect(asset.config.appdir.join("container")).to be_a_file
end
it "works with pure gzip-based Casks" do
asset = Cask::CaskLoader.load(cask_path("container-gzip"))
described_class.new(asset).install
expect(Cask::Caskroom.path.join("container-gzip", asset.version)).to be_a_directory
expect(asset.config.appdir.join("container")).to be_a_file
end
it "blows up on a bad checksum" do
bad_checksum = Cask::CaskLoader.load(cask_path("bad-checksum"))
expect do
described_class.new(bad_checksum).install
end.to raise_error(ChecksumMismatchError)
end
it "blows up on a missing checksum" do
missing_checksum = Cask::CaskLoader.load(cask_path("missing-checksum"))
expect do
described_class.new(missing_checksum).install
end.to output(/Cannot verify integrity/).to_stderr
end
it "installs fine if sha256 :no_check is used" do
no_checksum = Cask::CaskLoader.load(cask_path("no-checksum"))
described_class.new(no_checksum).install
expect(no_checksum).to be_installed
end
it "fails to install if sha256 :no_check is used with --require-sha" do
no_checksum = Cask::CaskLoader.load(cask_path("no-checksum"))
expect do
described_class.new(no_checksum, require_sha: true).install
end.to raise_error(/--require-sha/)
end
it "installs fine if sha256 :no_check is used with --require-sha and --force" do
no_checksum = Cask::CaskLoader.load(cask_path("no-checksum"))
described_class.new(no_checksum, require_sha: true, force: true).install
expect(no_checksum).to be_installed
end
it "prints caveats if they're present" do
with_caveats = Cask::CaskLoader.load(cask_path("with-caveats"))
expect do
described_class.new(with_caveats).install
end.to output(/Here are some things you might want to know/).to_stdout
expect(with_caveats).to be_installed
end
it "prints installer :manual instructions when present" do
with_installer_manual = Cask::CaskLoader.load(cask_path("with-installer-manual"))
expect do
described_class.new(with_installer_manual).install
end.to output(
<<~EOS,
==> Downloading file://#{HOMEBREW_LIBRARY_PATH}/test/support/fixtures/cask/caffeine.zip
==> Installing Cask with-installer-manual
Cask with-installer-manual only provides a manual installer. To run it and complete the installation:
open #{with_installer_manual.staged_path.join("Caffeine.app")}
🍺 with-installer-manual was successfully installed!
EOS
).to_stdout
expect(with_installer_manual).to be_installed
end
it "does not extract __MACOSX directories from zips" do
with_macosx_dir = Cask::CaskLoader.load(cask_path("with-macosx-dir"))
described_class.new(with_macosx_dir).install
expect(with_macosx_dir.staged_path.join("__MACOSX")).not_to be_a_directory
end
it "allows already-installed Casks which auto-update to be installed if force is provided" do
with_auto_updates = Cask::CaskLoader.load(cask_path("auto-updates"))
expect(with_auto_updates).not_to be_installed
described_class.new(with_auto_updates).install
expect do
described_class.new(with_auto_updates, force: true).install
end.not_to raise_error
end
it "allows already-installed Casks to be installed if force is provided" do
transmission = Cask::CaskLoader.load(cask_path("local-transmission-zip"))
expect(transmission).not_to be_installed
described_class.new(transmission).install
expect do
described_class.new(transmission, force: true).install
end.not_to raise_error
end
it "installs a cask from a dmg file" do
transmission = Cask::CaskLoader.load(cask_path("local-transmission"))
expect(transmission).not_to be_installed
described_class.new(transmission).install
expect(transmission).to be_installed
end
it "works naked-pkg-based Casks" do
naked_pkg = Cask::CaskLoader.load(cask_path("container-pkg"))
described_class.new(naked_pkg).install
expect(Cask::Caskroom.path.join("container-pkg", naked_pkg.version, "container.pkg")).to be_a_file
end
it "works properly with an overridden container :type" do
naked_executable = Cask::CaskLoader.load(cask_path("naked-executable"))
described_class.new(naked_executable).install
expect(Cask::Caskroom.path.join("naked-executable", naked_executable.version, "naked_executable")).to be_a_file
end
it "works fine with a nested container" do
nested_app = Cask::CaskLoader.load(cask_path("nested-app"))
described_class.new(nested_app).install
expect(nested_app.config.appdir.join("MyNestedApp.app")).to be_a_directory
end
it "generates and finds a timestamped metadata directory for an installed Cask" do
caffeine = Cask::CaskLoader.load(cask_path("local-caffeine"))
described_class.new(caffeine).install
m_path = caffeine.metadata_timestamped_path(timestamp: :now, create: true)
expect(caffeine.metadata_timestamped_path(timestamp: :latest)).to eq(m_path)
end
it "generates and finds a metadata subdirectory for an installed Cask" do
caffeine = Cask::CaskLoader.load(cask_path("local-caffeine"))
described_class.new(caffeine).install
subdir_name = "Casks"
m_subdir = caffeine.metadata_subdir(subdir_name, timestamp: :now, create: true)
expect(caffeine.metadata_subdir(subdir_name, timestamp: :latest)).to eq(m_subdir)
end
it "don't print cask installed message with --quiet option" do
caffeine = Cask::CaskLoader.load(cask_path("local-caffeine"))
expect do
described_class.new(caffeine, quiet: true).install
end.to output(nil).to_stdout
end
it "does NOT generate LATEST_DOWNLOAD_SHA256 file for installed Cask without version :latest" do
caffeine = Cask::CaskLoader.load(cask_path("local-caffeine"))
described_class.new(caffeine).install
expect(caffeine.download_sha_path).not_to be_a_file
end
it "generates and finds LATEST_DOWNLOAD_SHA256 file for installed Cask with version :latest" do
latest_cask = Cask::CaskLoader.load(cask_path("version-latest"))
described_class.new(latest_cask).install
expect(latest_cask.download_sha_path).to be_a_file
end
context "when loaded from the api and caskfile is required" do
let(:path) { cask_path("local-caffeine") }
let(:content) { File.read(path) }
it "installs cask" do
source_caffeine = Cask::CaskLoader.load(path)
expect(Homebrew::API::Cask).to receive(:source_download_cask).once.and_return(source_caffeine)
caffeine = Cask::CaskLoader.load(path)
expect(caffeine).to receive(:loaded_from_api?).once.and_return(true)
expect(caffeine).to receive(:caskfile_only?).once.and_return(true)
described_class.new(caffeine).install
expect(Cask::CaskLoader.load(path)).to be_installed
end
end
it "zap method reinstall cask" do
caffeine = Cask::CaskLoader.load(cask_path("local-caffeine"))
described_class.new(caffeine).install
expect(caffeine).to be_installed
described_class.new(caffeine).zap
expect(caffeine).not_to be_installed
expect(caffeine.config.appdir.join("Caffeine.app")).not_to be_a_symlink
end
end
describe "uninstall" do
it "fully uninstalls a Cask" do
caffeine = Cask::CaskLoader.load(cask_path("local-caffeine"))
installer = described_class.new(caffeine)
installer.install
installer.uninstall
expect(Cask::Caskroom.path.join("local-caffeine", caffeine.version, "Caffeine.app")).not_to be_a_directory
expect(Cask::Caskroom.path.join("local-caffeine", caffeine.version)).not_to be_a_directory
expect(Cask::Caskroom.path.join("local-caffeine")).not_to be_a_directory
end
it "uninstalls all versions if force is set" do
caffeine = Cask::CaskLoader.load(cask_path("local-caffeine"))
mutated_version = "#{caffeine.version}.1"
described_class.new(caffeine).install
expect(Cask::Caskroom.path.join("local-caffeine", caffeine.version)).to be_a_directory
expect(Cask::Caskroom.path.join("local-caffeine", mutated_version)).not_to be_a_directory
FileUtils.mv(Cask::Caskroom.path.join("local-caffeine", caffeine.version),
Cask::Caskroom.path.join("local-caffeine", mutated_version))
expect(Cask::Caskroom.path.join("local-caffeine", caffeine.version)).not_to be_a_directory
expect(Cask::Caskroom.path.join("local-caffeine", mutated_version)).to be_a_directory
described_class.new(caffeine, force: true).uninstall
expect(Cask::Caskroom.path.join("local-caffeine", caffeine.version)).not_to be_a_directory
expect(Cask::Caskroom.path.join("local-caffeine", mutated_version)).not_to be_a_directory
expect(Cask::Caskroom.path.join("local-caffeine")).not_to be_a_directory
end
context "when loaded from the api, caskfile is required and installed caskfile is invalid" do
let(:path) { cask_path("local-caffeine") }
let(:content) { File.read(path) }
let(:invalid_path) { instance_double(Pathname) }
before do
allow(invalid_path).to receive(:exist?).and_return(false)
end
it "uninstalls cask" do
source_caffeine = Cask::CaskLoader.load(path)
expect(Homebrew::API::Cask).to receive(:source_download_cask).twice.and_return(source_caffeine)
caffeine = Cask::CaskLoader.load(path)
expect(caffeine).to receive(:loaded_from_api?).twice.and_return(true)
expect(caffeine).to receive(:caskfile_only?).twice.and_return(true)
expect(caffeine).to receive(:installed_caskfile).once.and_return(invalid_path)
described_class.new(caffeine).install
expect(Cask::CaskLoader.load(path)).to be_installed
described_class.new(caffeine).uninstall
expect(Cask::CaskLoader.load(path)).not_to be_installed
end
end
end
describe "uninstall_existing_cask" do
it "uninstalls when cask file is outdated" do
caffeine = Cask::CaskLoader.load(cask_path("local-caffeine"))
described_class.new(caffeine).install
expect(Cask::CaskLoader.load(cask_path("local-caffeine"))).to be_installed
expect(caffeine).to receive(:installed?).once.and_return(true)
outdate_caskfile = cask_path("invalid/invalid-depends-on-macos-bad-release")
expect(caffeine).to receive(:installed_caskfile).once.and_return(outdate_caskfile)
described_class.new(caffeine).uninstall_existing_cask
expect(Cask::CaskLoader.load(cask_path("local-caffeine"))).not_to be_installed
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 cask" do
cask = Cask::Cask.new("homebrew-forbidden-tap", tap: homebrew_forbidden) do
url "file://#{TEST_FIXTURE_DIR}/cask/container.tar.gz"
end
expect do
described_class.new(cask).forbidden_tap_check
end.to raise_error(Cask::CaskCannotBeInstalledError, /has the tap #{homebrew_forbidden}/)
end
it "raises on not allowed third-party tap on cask" do
cask = Cask::Cask.new("homebrew-not-allowed-tap", tap: disallowed_third_party) do
url "file://#{TEST_FIXTURE_DIR}/cask/container.tar.gz"
end
expect do
described_class.new(cask).forbidden_tap_check
end.to raise_error(Cask::CaskCannotBeInstalledError, /has the tap #{disallowed_third_party}/)
end
it "does not raise on allowed tap on cask" do
cask = Cask::Cask.new("third-party-allowed-tap", tap: allowed_third_party) do
url "file://#{TEST_FIXTURE_DIR}/cask/container.tar.gz"
end
expect { described_class.new(cask).forbidden_tap_check }.not_to raise_error
end
it "raises on forbidden tap on dependency" do
dep_tap = homebrew_forbidden
dep_name = "homebrew-forbidden-dependency-tap"
dep_path = dep_tap.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)
cask = Cask::Cask.new("homebrew-forbidden-dependent-tap") do
url "file://#{TEST_FIXTURE_DIR}/cask/container.tar.gz"
depends_on formula: dep_name
end
expect do
described_class.new(cask).forbidden_tap_check
end.to raise_error(Cask::CaskCannotBeInstalledError, /from the #{dep_tap} tap but/)
ensure
FileUtils.rm_r(dep_path.parent.parent)
end
end
describe "#forbidden_cask_and_formula_check" do
it "raises on forbidden cask" do
ENV["HOMEBREW_FORBIDDEN_CASKS"] = cask_name = "homebrew-forbidden-cask"
cask = Cask::Cask.new(cask_name) do
url "file://#{TEST_FIXTURE_DIR}/cask/container.tar.gz"
end
expect do
described_class.new(cask).forbidden_cask_and_formula_check
end.to raise_error(Cask::CaskCannotBeInstalledError, /forbidden for installation/)
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)
cask = Cask::Cask.new("homebrew-forbidden-dependent-cask") do
url "file://#{TEST_FIXTURE_DIR}/cask/container.tar.gz"
depends_on formula: dep_name
end
expect do
described_class.new(cask).forbidden_cask_and_formula_check
end.to raise_error(Cask::CaskCannotBeInstalledError, /#{dep_name} formula was forbidden/)
end
end
describe "#forbidden_cask_artifacts_check" do
it "raises when cask contains forbidden pkg artifact" do
ENV["HOMEBREW_FORBIDDEN_CASK_ARTIFACTS"] = "pkg"
cask = Cask::Cask.new("homebrew-pkg-cask") do
url "file://#{TEST_FIXTURE_DIR}/cask/container.tar.gz"
pkg "MyInstaller.pkg"
end
expect do
described_class.new(cask).forbidden_cask_artifacts_check
end.to raise_error(Cask::CaskCannotBeInstalledError, /contains a 'pkg' artifact/)
end
it "raises when cask contains forbidden installer artifact" do
ENV["HOMEBREW_FORBIDDEN_CASK_ARTIFACTS"] = "installer"
cask = Cask::Cask.new("homebrew-installer-cask") do
url "file://#{TEST_FIXTURE_DIR}/cask/container.tar.gz"
installer script: {
executable: "MyInstaller.sh",
args: ["--silent"],
}
end
expect do
described_class.new(cask).forbidden_cask_artifacts_check
end.to raise_error(Cask::CaskCannotBeInstalledError, /contains a 'installer' artifact/)
end
it "raises when cask contains multiple forbidden artifacts" do
ENV["HOMEBREW_FORBIDDEN_CASK_ARTIFACTS"] = "pkg installer"
cask = Cask::Cask.new("homebrew-multi-forbidden-cask") do
url "file://#{TEST_FIXTURE_DIR}/cask/container.tar.gz"
pkg "MyInstaller.pkg"
end
expect do
described_class.new(cask).forbidden_cask_artifacts_check
end.to raise_error(Cask::CaskCannotBeInstalledError, /contains a 'pkg' artifact/)
end
it "does not raise when cask does not contain forbidden artifacts" do
ENV["HOMEBREW_FORBIDDEN_CASK_ARTIFACTS"] = "pkg installer"
cask = Cask::Cask.new("homebrew-allowed-cask") do
url "file://#{TEST_FIXTURE_DIR}/cask/container.tar.gz"
app "MyApp.app"
end
expect { described_class.new(cask).forbidden_cask_artifacts_check }.not_to raise_error
end
end
describe "rename operations" do
let(:tmpdir) { mktmpdir }
let(:staged_path) { Pathname(tmpdir) }
after do
FileUtils.rm_rf(tmpdir) if tmpdir && File.exist?(tmpdir)
end
it "processes rename operations after extraction" do
# Create test files
(staged_path / "Original App.app").mkpath
(staged_path / "Original App.app" / "Contents").mkpath
cask = Cask::Cask.new("rename-test-cask") do
url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip"
rename "Original App.app", "Renamed App.app"
app "Renamed App.app"
end
# Mock the staged_path to point to our test directory
allow(cask).to receive(:staged_path).and_return(staged_path)
installer = described_class.new(cask)
installer.send(:process_rename_operations)
expect(staged_path / "Renamed App.app").to be_a_directory
expect(staged_path / "Original App.app").not_to exist
end
it "handles multiple rename operations in order" do
# Create test file
(staged_path / "Original.app").mkpath
cask = Cask::Cask.new("multi-rename-test-cask") do
url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip"
rename "Original.app", "First Rename.app"
rename "First Rename.app", "Final Name.app"
app "Final Name.app"
end
allow(cask).to receive(:staged_path).and_return(staged_path)
installer = described_class.new(cask)
installer.send(:process_rename_operations)
expect(staged_path / "Final Name.app").to be_a_directory
expect(staged_path / "Original.app").not_to exist
expect(staged_path / "First Rename.app").not_to exist
end
it "handles glob patterns in rename operations" do
# Create test file with version
(staged_path / "Test App v1.2.3.pkg").write("test content")
cask = Cask::Cask.new("glob-rename-test-cask") do
url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip"
rename "Test App*.pkg", "Test App.pkg"
pkg "Test App.pkg"
end
allow(cask).to receive(:staged_path).and_return(staged_path)
installer = described_class.new(cask)
installer.send(:process_rename_operations)
expect(staged_path / "Test App.pkg").to be_a_file
expect((staged_path / "Test App.pkg").read).to eq("test content")
expect(staged_path / "Test App v1.2.3.pkg").not_to exist
end
it "does nothing when no files match rename pattern" do
# Create a different file
(staged_path / "Different.app").mkpath
cask = Cask::Cask.new("no-match-rename-test-cask") do
url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip"
rename "NonExistent*.app", "Target.app"
app "Different.app"
end
allow(cask).to receive(:staged_path).and_return(staged_path)
installer = described_class.new(cask)
expect { installer.send(:process_rename_operations) }.not_to raise_error
expect(staged_path / "Different.app").to be_a_directory
expect(staged_path / "Target.app").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/cask/config_spec.rb | Library/Homebrew/test/cask/config_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Config, :cask do
subject(:config) { described_class.new }
describe "::from_json" do
it "deserializes a configuration in JSON format" do
config = described_class.from_json <<~EOS
{
"default": {
"appdir": "/path/to/apps"
},
"env": {},
"explicit": {}
}
EOS
expect(config.appdir).to eq(Pathname("/path/to/apps"))
end
end
describe "#default" do
it "returns the default directories" do
expect(config.default[:appdir]).to eq(Pathname(TEST_TMPDIR).join("cask-appdir"))
end
end
describe "#appdir" do
it "returns the default value if no HOMEBREW_CASK_OPTS is unset" do
expect(config.appdir).to eq(Pathname(TEST_TMPDIR).join("cask-appdir"))
end
specify "environment overwrites default" do
ENV["HOMEBREW_CASK_OPTS"] = "--appdir=/path/to/apps"
expect(config.appdir).to eq(Pathname("/path/to/apps"))
end
specify "specific overwrites default" do
config = described_class.new(explicit: { appdir: "/explicit/path/to/apps" })
expect(config.appdir).to eq(Pathname("/explicit/path/to/apps"))
end
specify "explicit overwrites environment" do
ENV["HOMEBREW_CASK_OPTS"] = "--appdir=/path/to/apps"
config = described_class.new(explicit: { appdir: "/explicit/path/to/apps" })
expect(config.appdir).to eq(Pathname("/explicit/path/to/apps"))
end
end
describe "#env" do
it "returns directories specified with the HOMEBREW_CASK_OPTS variable" do
ENV["HOMEBREW_CASK_OPTS"] = "--appdir=/path/to/apps"
expect(config.env).to eq(appdir: Pathname("/path/to/apps"))
end
end
describe "#explicit" do
let(:config) do
described_class.new(explicit: { appdir: "/explicit/path/to/apps",
languages: ["zh-TW", "en"] })
end
it "returns directories explicitly given as arguments" do
expect(config.explicit[:appdir]).to eq(Pathname("/explicit/path/to/apps"))
end
it "returns array of preferred languages" do
expect(config.explicit[:languages]).to eq(["zh-TW", "en"])
end
end
context "when installing a cask and then adding a global default dir" do
let(:config) do
json = <<~EOS
{
"default": {
"appdir": "/default/path/before/adding/fontdir"
},
"env": {},
"explicit": {}
}
EOS
described_class.from_json(json)
end
describe "#appdir" do
it "honors metadata of the installed cask" do
expect(config.appdir).to eq(Pathname("/default/path/before/adding/fontdir"))
end
end
describe "#fontdir" do
it "falls back to global default on incomplete metadata" do
expect(config.default).to include(fontdir: Pathname(TEST_TMPDIR).join("cask-fontdir"))
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/cask/info_spec.rb | Library/Homebrew/test/cask/info_spec.rb | # frozen_string_literal: true
require "utils"
require "cask/info"
RSpec.describe Cask::Info, :cask do
include Utils::Output::Mixin
let(:args) { instance_double(Homebrew::Cmd::Info::Args) }
def uninstalled(string)
"#{Tty.bold}#{string} #{Formatter.error("✘")}#{Tty.reset}"
end
def installed(string)
"#{Tty.bold}#{string} #{Formatter.success("✔")}#{Tty.reset}"
end
def mock_cask_installed(cask_name)
cask = Cask::CaskLoader.load(cask_name)
allow(cask).to receive(:installed?).and_return(true)
allow(Cask::CaskLoader).to receive(:load).and_call_original
allow(Cask::CaskLoader).to receive(:load).with(cask_name).and_return(cask)
end
before do
# Prevent unnecessary network requests in `Utils::Analytics.cask_output`
ENV["HOMEBREW_NO_ANALYTICS"] = "1"
end
it "displays some nice info about the specified Cask" do
expect do
described_class.info(Cask::CaskLoader.load("local-transmission"), args:)
end.to output(<<~EOS).to_stdout
==> local-transmission: 2.61
https://transmissionbt.com/
Not installed
From: https://github.com/Homebrew/homebrew-cask/blob/HEAD/Casks/l/local-transmission.rb
==> Name
Transmission
==> Description
BitTorrent client
==> Artifacts
Transmission.app (App)
EOS
end
it "prints cask dependencies if the Cask has any" do
allow_any_instance_of(StringIO).to receive(:tty?).and_return(true)
mock_cask_installed("local-transmission-zip")
expect do
described_class.info(Cask::CaskLoader.load("with-depends-on-cask-multiple"), args:)
end.to output(<<~EOS).to_stdout
#{oh1_title "with-depends-on-cask-multiple"}: 1.2.3
#{Formatter.url("https://brew.sh/with-depends-on-cask-multiple")}
Not installed
From: #{Formatter.url("https://github.com/Homebrew/homebrew-cask/blob/HEAD/Casks/w/with-depends-on-cask-multiple.rb")}
#{ohai_title "Name"}
#{Formatter.error("None")}
#{ohai_title "Description"}
#{Formatter.error("None")}
#{ohai_title "Dependencies"}
#{uninstalled("local-caffeine (cask)")}, #{installed("local-transmission-zip (cask)")}
#{ohai_title "Artifacts"}
Caffeine.app (App)
EOS
end
it "prints cask and formulas dependencies if the Cask has both" do
allow_any_instance_of(StringIO).to receive(:tty?).and_return(true)
expect do
described_class.info(Cask::CaskLoader.load("with-depends-on-everything"), args:)
end.to output(<<~EOS).to_stdout
#{oh1_title "with-depends-on-everything"}: 1.2.3
#{Formatter.url("https://brew.sh/with-depends-on-everything")}
Not installed
From: #{Formatter.url("https://github.com/Homebrew/homebrew-cask/blob/HEAD/Casks/w/with-depends-on-everything.rb")}
#{ohai_title "Name"}
#{Formatter.error("None")}
#{ohai_title "Description"}
#{Formatter.error("None")}
#{ohai_title "Dependencies"}
#{uninstalled("unar")}, #{uninstalled("local-caffeine (cask)")}, #{uninstalled("with-depends-on-cask (cask)")}
#{ohai_title "Artifacts"}
Caffeine.app (App)
EOS
end
it "prints auto_updates if the Cask has `auto_updates true`" do
expect do
described_class.info(Cask::CaskLoader.load("with-auto-updates"), args:)
end.to output(<<~EOS).to_stdout
==> with-auto-updates: 1.0 (auto_updates)
https://brew.sh/autoupdates
Not installed
From: https://github.com/Homebrew/homebrew-cask/blob/HEAD/Casks/w/with-auto-updates.rb
==> Name
AutoUpdates
==> Description
None
==> Artifacts
AutoUpdates.app (App)
EOS
end
it "prints caveats if the Cask provided one" do
expect do
described_class.info(Cask::CaskLoader.load("with-caveats"), args:)
end.to output(<<~EOS).to_stdout
==> with-caveats: 1.2.3
https://brew.sh/
Not installed
From: https://github.com/Homebrew/homebrew-cask/blob/HEAD/Casks/w/with-caveats.rb
==> Name
None
==> Description
None
==> Artifacts
Caffeine.app (App)
==> Caveats
Here are some things you might want to know.
Cask token: with-caveats
Custom text via puts followed by DSL-generated text:
To use with-caveats, you may need to add the /custom/path/bin directory
to your PATH environment variable, e.g. (for Bash shell):
export PATH=/custom/path/bin:"$PATH"
EOS
end
it 'does not print "Caveats" section divider if the caveats block has no output' do
expect do
described_class.info(Cask::CaskLoader.load("with-conditional-caveats"), args:)
end.to output(<<~EOS).to_stdout
==> with-conditional-caveats: 1.2.3
https://brew.sh/
Not installed
From: https://github.com/Homebrew/homebrew-cask/blob/HEAD/Casks/w/with-conditional-caveats.rb
==> Name
None
==> Description
None
==> Artifacts
Caffeine.app (App)
EOS
end
it "prints languages specified in the Cask" do
expect do
described_class.info(Cask::CaskLoader.load("with-languages"), args:)
end.to output(<<~EOS).to_stdout
==> with-languages: 1.2.3
https://brew.sh/
Not installed
From: https://github.com/Homebrew/homebrew-cask/blob/HEAD/Casks/w/with-languages.rb
==> Name
None
==> Description
None
==> Languages
zh, en-US
==> Artifacts
Caffeine.app (App)
EOS
end
it 'does not print "Languages" section divider if the languages block has no output' do
expect do
described_class.info(Cask::CaskLoader.load("without-languages"), args:)
end.to output(<<~EOS).to_stdout
==> without-languages: 1.2.3
https://brew.sh/
Not installed
From: https://github.com/Homebrew/homebrew-cask/blob/HEAD/Casks/w/without-languages.rb
==> Name
None
==> Description
None
==> Artifacts
Caffeine.app (App)
EOS
end
it "prints install information for an installed Cask" do
mktmpdir do |caskroom|
FileUtils.mkdir caskroom/"2.61"
cask = Cask::CaskLoader.load("local-transmission")
time = 1_720_189_863
tab = Cask::Tab.new(loaded_from_api: true, tabfile: TEST_FIXTURE_DIR/"cask_receipt.json", time:)
expect(cask).to receive(:installed?).and_return(true)
expect(cask).to receive(:caskroom_path).and_return(caskroom)
expect(cask).to receive(:installed_version).and_return("2.61")
expect(Cask::Tab).to receive(:for_cask).with(cask).and_return(tab)
expect do
described_class.info(cask, args:)
end.to output(<<~EOS).to_stdout
==> local-transmission: 2.61
https://transmissionbt.com/
Installed
#{caskroom}/2.61 (0B)
Installed using the formulae.brew.sh API on #{Time.at(time).strftime("%Y-%m-%d at %H:%M:%S")}
From: https://github.com/Homebrew/homebrew-cask/blob/HEAD/Casks/l/local-transmission.rb
==> Name
Transmission
==> Description
BitTorrent client
==> Artifacts
Transmission.app (App)
EOS
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/cask/dsl/uninstall_preflight_spec.rb | Library/Homebrew/test/cask/dsl/uninstall_preflight_spec.rb | # frozen_string_literal: true
require "test/cask/dsl/shared_examples/base"
require "test/cask/dsl/shared_examples/staged"
RSpec.describe Cask::DSL::UninstallPreflight, :cask do
let(:cask) { Cask::CaskLoader.load(cask_path("basic-cask")) }
let(:fake_system_command) { class_double(SystemCommand) }
let(:dsl) { described_class.new(cask, fake_system_command) }
it_behaves_like Cask::DSL::Base
it_behaves_like Cask::Staged do
let(:staged) { dsl }
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/cask/dsl/version_spec.rb | Library/Homebrew/test/cask/dsl/version_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::DSL::Version, :cask do
shared_examples "expectations hash" do |input_name, expectations|
expectations.each do |input_value, expected_output|
context "when #{input_name} is #{input_value.inspect}" do
let(input_name.to_sym) { input_value }
it { is_expected.to eq expected_output }
end
end
end
shared_examples "version equality" do
let(:raw_version) { "1.2.3" }
context "when other is nil" do
let(:other) { nil }
it { is_expected.to be false }
end
context "when other is a String" do
context "when other == self.raw_version" do
let(:other) { "1.2.3" }
it { is_expected.to be true }
end
context "when other != self.raw_version" do
let(:other) { "1.2.3.4" }
it { is_expected.to be false }
end
end
context "when other is a #{described_class}" do
context "when other.raw_version == self.raw_version" do
let(:other) { described_class.new("1.2.3") }
it { is_expected.to be true }
end
context "when other.raw_version != self.raw_version" do
let(:other) { described_class.new("1.2.3.4") }
it { is_expected.to be false }
end
end
end
let(:version) { described_class.new(raw_version) }
describe "#initialize" do
it "raises an error when the version contains a slash" do
expect do
described_class.new("0.1,../../directory/traversal")
end.to raise_error(TypeError, %r{invalid characters: /})
end
end
describe "#==" do
subject { version == other }
include_examples "version equality"
end
describe "#eql?" do
subject { version.eql?(other) }
include_examples "version equality"
end
shared_examples "version expectations hash" do |method, hash|
subject { version.send(method) }
include_examples "expectations hash", :raw_version,
{ :latest => "latest",
"latest" => "latest",
"" => "",
nil => "" }.merge(hash)
end
describe "#latest?" do
include_examples "version expectations hash", :latest?,
:latest => true,
"latest" => true,
"" => false,
nil => false,
"1.2.3" => false
end
describe "string manipulation helpers" do
describe "#major" do
include_examples "version expectations hash", :major,
"1" => "1",
"1.2" => "1",
"1.2.3" => "1",
"1.2.3-4,5:6" => "1"
end
describe "#minor" do
include_examples "version expectations hash", :minor,
"1" => "",
"1.2" => "2",
"1.2.3" => "2",
"1.2.3-4,5:6" => "2"
end
describe "#patch" do
include_examples "version expectations hash", :patch,
"1" => "",
"1.2" => "",
"1.2.3" => "3",
"1.2.3-4,5:6" => "3-4"
end
describe "#major_minor" do
include_examples "version expectations hash", :major_minor,
"1" => "1",
"1.2" => "1.2",
"1.2.3" => "1.2",
"1.2.3-4,5:6" => "1.2"
end
describe "#major_minor_patch" do
include_examples "version expectations hash", :major_minor_patch,
"1" => "1",
"1.2" => "1.2",
"1.2.3" => "1.2.3",
"1.2.3-4,5:6" => "1.2.3-4"
end
describe "#minor_patch" do
include_examples "version expectations hash", :minor_patch,
"1" => "",
"1.2" => "2",
"1.2.3" => "2.3",
"1.2.3-4,5:6" => "2.3-4"
end
describe "#csv" do
subject { version.csv }
include_examples "expectations hash", :raw_version,
:latest => ["latest"],
"latest" => ["latest"],
"" => [],
nil => [],
"1.2.3" => ["1.2.3"],
"1.2.3," => ["1.2.3"],
",abc" => ["", "abc"],
"1.2.3,abc" => ["1.2.3", "abc"]
end
describe "#before_comma" do
include_examples "version expectations hash", :before_comma,
"1.2.3" => "1.2.3",
"1.2.3," => "1.2.3",
",abc" => "",
"1.2.3,abc" => "1.2.3"
end
describe "#after_comma" do
include_examples "version expectations hash", :after_comma,
"1.2.3" => "",
"1.2.3," => "",
",abc" => "abc",
"1.2.3,abc" => "abc"
end
describe "#dots_to_hyphens" do
include_examples "version expectations hash", :dots_to_hyphens,
"1.2.3_4-5" => "1-2-3_4-5"
end
describe "#dots_to_underscores" do
include_examples "version expectations hash", :dots_to_underscores,
"1.2.3_4-5" => "1_2_3_4-5"
end
describe "#hyphens_to_dots" do
include_examples "version expectations hash", :hyphens_to_dots,
"1.2.3_4-5" => "1.2.3_4.5"
end
describe "#hyphens_to_underscores" do
include_examples "version expectations hash", :hyphens_to_underscores,
"1.2.3_4-5" => "1.2.3_4_5"
end
describe "#underscores_to_dots" do
include_examples "version expectations hash", :underscores_to_dots,
"1.2.3_4-5" => "1.2.3.4-5"
end
describe "#underscores_to_hyphens" do
include_examples "version expectations hash", :underscores_to_hyphens,
"1.2.3_4-5" => "1.2.3-4-5"
end
describe "#no_dots" do
include_examples "version expectations hash", :no_dots,
"1.2.3_4-5" => "123_4-5"
end
describe "#no_hyphens" do
include_examples "version expectations hash", :no_hyphens,
"1.2.3_4-5" => "1.2.3_45"
end
describe "#no_underscores" do
include_examples "version expectations hash", :no_underscores,
"1.2.3_4-5" => "1.2.34-5"
end
describe "#no_dividers" do
include_examples "version expectations hash", :no_dividers,
"1.2.3_4-5" => "12345"
end
end
describe "#unstable?" do
[
"0.0.11-beta.7",
"0.0.23b-alpha",
"0.1-beta",
"0.1.0-beta.6",
"0.10.0b",
"0.2.0-alpha",
"0.2.0-beta",
"0.2.4-beta.9",
"0.2.588-dev",
"0.3-beta",
"0.3.0-SNAPSHOT-624369f",
"0.4.1-alpha",
"0.4.9-alpha",
"0.5.3,beta",
"0.6-alpha1,a",
"0.7.1b2",
"0.7a19",
"0.8.0b8",
"0.8b3",
"0.9.10-alpha",
"0.9.3b",
"08b2",
"1.0-b9",
"1.0-beta",
"1.0-beta-7.0",
"1.0-beta.3",
"1.0.0-alpha.5",
"1.0.0-alpha5",
"1.0.0-beta-2.2,20160421",
"1.0.0-beta.16",
"1.0.0-rc",
"1.0.6b1",
"1.0.beta-43",
"1.004,alpha",
"1.0b10",
"1.0b12",
"1.1-alpha-20181201a",
"1.1.16-beta-rc2",
"1.1.58.BETA",
"1.10.1,b87:8941241e",
"1.13.0-beta.7",
"1.13beta8",
"1.15.0.b20190302001",
"1.16.2-Beta",
"1.1b23",
"1.2.0,b200",
"1.2.1pre1",
"1.2.2-beta.2845",
"1.20.0-beta.3",
"1.2b24",
"1.3.0,b102",
"1.3.7a",
"1.36.0-beta0",
"1.4.3a",
"1.6.0_65-b14-468",
"1.6.4-beta0-4e46f007",
"1.7,b566",
"1.7b5",
"1.9.3a",
"1.9.3b8",
"17.03.1-beta",
"18.0-Leia_rc4",
"18.2-rc-3",
"1875Beta",
"19.3.2,b4188-155116",
"2.0-rc.22",
"2.0.0-beta.2",
"2.0.0-beta14",
"2.0.0-dev.11,1902221558.a6b3c4a8",
"2.0.12,b1807-50472cde",
"2.0b",
"2.0b2",
"2.0b3-2020",
"2.0b5",
"2.1.1-dev.3",
"2.12.12beta3",
"2.12b1",
"2.2-Beta",
"2.2.0-RC1",
"2.2b2",
"2.3.0-beta1u1",
"2.3.1,rc4",
"2.3b19",
"2.4.0-beta2",
"2.4.6-beta3u2",
"2.6.1-dev_2019-02-09_14-04_git-master-c1f194a",
"2.7.4a1",
"2.79b",
"2.99pre5",
"2019.1-Beta2",
"2019.1-b112",
"2019.1-beta1",
"2019a",
"26.1-rc1-1",
"3.0.0-beta.5",
"3.0.0-beta19",
"3.0.0-canary.8",
"3.0.0-preview-27122-01",
"3.0.0-rc.14",
"3.0.1-beta.19",
"3.0.100-preview-010184",
"3.0.6a",
"3.00b5",
"3.1.0-beta.1",
"3.1.0_b15007",
"3.2.8beta1",
"3.21-beta",
"3.7.9beta03,5210",
"3b19",
"4.0.0a",
"4.2.0-preview",
"4.3-beta5",
"4.3b3",
"4.99beta",
"5.0.0-RC7",
"5.5.0-beta-9",
"6.0.0-beta3,20181228T124823",
"6.0.0_BETA3,127054",
"6.1.1b176",
"6.2.0-preview.4",
"6.2.0.0.beta1",
"6.3.9_b16229",
"6.44b",
"7.0.6-7A69",
"7.3.BETA-3",
"8.5a8",
"8u202,b08:1961070e4c9b4e26a04e7f5a083f551e",
].each do |unstable_version|
it "detects #{unstable_version.inspect} as unstable" do
expect(described_class.new(unstable_version)).to be_unstable
end
end
[
"0.20.1,63d9b84e-bbcf-4a00-9427-0bb3f713c769",
"1.5.4,13:53d8a307-a8ae-4f9b-9a59-a1adb8c67012",
"b226",
].each do |stable_version|
it "does not detect #{stable_version.inspect} as unstable" do
expect(described_class.new(stable_version)).not_to be_unstable
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/cask/dsl/caveats_spec.rb | Library/Homebrew/test/cask/dsl/caveats_spec.rb | # frozen_string_literal: true
require "test/cask/dsl/shared_examples/base"
RSpec.describe Cask::DSL::Caveats, :cask do
subject(:caveats) { described_class.new(cask) }
let(:cask) { Cask::CaskLoader.load(cask_path("basic-cask")) }
let(:dsl) { caveats }
it_behaves_like Cask::DSL::Base
# TODO: add tests for Caveats DSL methods
describe "#kext" do
let(:cask) { instance_double(Cask::Cask) }
it "returns System Settings on macOS Ventura or later" do
allow(MacOS).to receive(:version).and_return(MacOSVersion.from_symbol(:ventura))
caveats.eval_caveats do
kext
end
expect(caveats.to_s).to be_empty
end
it "returns System Preferences on macOS Sonoma and earlier" do
allow(MacOS).to receive(:version).and_return(MacOSVersion.from_symbol(:sonoma))
caveats.eval_caveats do
kext
end
expect(caveats.to_s).to include("System Settings → Privacy & Security")
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/cask/dsl/postflight_spec.rb | Library/Homebrew/test/cask/dsl/postflight_spec.rb | # frozen_string_literal: true
require "test/cask/dsl/shared_examples/base"
require "test/cask/dsl/shared_examples/staged"
RSpec.describe Cask::DSL::Postflight, :cask do
let(:cask) { Cask::CaskLoader.load(cask_path("basic-cask")) }
let(:fake_system_command) { class_double(SystemCommand) }
let(:dsl) { described_class.new(cask, fake_system_command) }
it_behaves_like Cask::DSL::Base
it_behaves_like Cask::Staged do
let(:staged) { dsl }
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/cask/dsl/uninstall_postflight_spec.rb | Library/Homebrew/test/cask/dsl/uninstall_postflight_spec.rb | # frozen_string_literal: true
require "test/cask/dsl/shared_examples/base"
RSpec.describe Cask::DSL::UninstallPostflight, :cask do
let(:cask) { Cask::CaskLoader.load(cask_path("basic-cask")) }
let(:dsl) { described_class.new(cask, class_double(SystemCommand)) }
it_behaves_like Cask::DSL::Base
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/cask/dsl/rename_spec.rb | Library/Homebrew/test/cask/dsl/rename_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::DSL::Rename do
subject(:rename) { described_class.new(from, to) }
let(:from) { "Source File*.pkg" }
let(:to) { "Target File.pkg" }
describe "#initialize" do
it "sets the from and to attributes" do
expect(rename.from).to eq("Source File*.pkg")
expect(rename.to).to eq("Target File.pkg")
end
end
describe "#pairs" do
it "returns the attributes as a hash" do
expect(rename.pairs).to eq(from: "Source File*.pkg", to: "Target File.pkg")
end
end
describe "#to_s" do
it "returns the stringified attributes" do
expect(rename.to_s).to eq(rename.pairs.inspect)
end
end
describe "#perform_rename" do
let(:tmpdir) { mktmpdir }
let(:staged_path) { Pathname(tmpdir) }
context "when staged_path does not exist" do
let(:staged_path) { Pathname("/nonexistent/path") }
it "does nothing" do
expect { rename.perform_rename(staged_path) }.not_to raise_error
end
end
context "when using glob patterns" do
let(:from) { "Test App*.pkg" }
let(:to) { "Test App.pkg" }
before do
(staged_path / "Test App v1.2.3.pkg").write("test content")
(staged_path / "Test App v2.0.0.pkg").write("other content")
end
it "renames the first matching file" do
rename.perform_rename(staged_path)
expect(staged_path / "Test App.pkg").to exist
expect((staged_path / "Test App.pkg").read).to eq("test content")
expect(staged_path / "Test App v1.2.3.pkg").not_to exist
expect(staged_path / "Test App v2.0.0.pkg").to exist
end
end
context "when using exact filenames" do
let(:from) { "Exact File.dmg" }
let(:to) { "New Name.dmg" }
before do
(staged_path / "Exact File.dmg").write("dmg content")
end
it "renames the exact file" do
rename.perform_rename(staged_path)
expect(staged_path / "New Name.dmg").to exist
expect((staged_path / "New Name.dmg").read).to eq("dmg content")
expect(staged_path / "Exact File.dmg").not_to exist
end
end
context "when target is in a subdirectory" do
let(:from) { "source.txt" }
let(:to) { "subdir/target.txt" }
before do
(staged_path / "source.txt").write("content")
end
it "creates the subdirectory and renames the file" do
rename.perform_rename(staged_path)
expect(staged_path / "subdir" / "target.txt").to exist
expect((staged_path / "subdir" / "target.txt").read).to eq("content")
expect(staged_path / "source.txt").not_to exist
end
end
context "when no files match the pattern" do
let(:from) { "nonexistent*.pkg" }
let(:to) { "target.pkg" }
it "does nothing" do
rename.perform_rename(staged_path)
expect(staged_path / "target.pkg").not_to exist
end
end
context "when source file doesn't exist after glob" do
let(:from) { "missing.txt" }
let(:to) { "target.txt" }
it "does nothing" do
expect { rename.perform_rename(staged_path) }.not_to raise_error
expect(staged_path / "target.txt").not_to exist
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/cask/dsl/preflight_spec.rb | Library/Homebrew/test/cask/dsl/preflight_spec.rb | # frozen_string_literal: true
require "test/cask/dsl/shared_examples/base"
require "test/cask/dsl/shared_examples/staged"
RSpec.describe Cask::DSL::Preflight, :cask do
let(:cask) { Cask::CaskLoader.load(cask_path("basic-cask")) }
let(:fake_system_command) { class_double(SystemCommand) }
let(:dsl) { described_class.new(cask, fake_system_command) }
it_behaves_like Cask::DSL::Base
it_behaves_like Cask::Staged do
let(:staged) { dsl }
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/cask/dsl/container_spec.rb | Library/Homebrew/test/cask/dsl/container_spec.rb | # frozen_string_literal: true
require "test/cask/dsl/shared_examples/base"
RSpec.describe Cask::DSL::Container do
subject(:container) { described_class.new(**params) }
describe "#pairs" do
let(:params) { { nested: "NestedApp.dmg" } }
it "returns the attributes as a hash" do
expect(container.pairs).to eq(nested: "NestedApp.dmg")
end
end
describe "#to_s" do
let(:params) { { nested: "NestedApp.dmg", type: :naked } }
it "returns the stringified attributes" do
expect(container.to_s).to eq(params.inspect)
end
end
describe "#to_yaml" do
let(:params) { { nested: "NestedApp.dmg", type: :naked } }
it "returns the attributes in YAML format" do
expect(container.to_yaml).to eq(<<~YAML)
---
:nested: NestedApp.dmg
:type: :naked
YAML
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/cask/dsl/shared_examples/staged.rb | Library/Homebrew/test/cask/dsl/shared_examples/staged.rb | # frozen_string_literal: true
require "cask/staged"
RSpec.shared_examples Cask::Staged do
let(:existing_path) { Pathname("/path/to/file/that/exists") }
let(:non_existent_path) { Pathname("/path/to/file/that/does/not/exist") }
before do
allow(existing_path).to receive_messages(exist?: true, expand_path: existing_path)
allow(non_existent_path).to receive_messages(exist?: false, expand_path: non_existent_path)
end
it "can run system commands with list-form arguments" do
expect(fake_system_command).to receive(:run!)
.with("echo", args: ["homebrew-cask", "rocks!"])
staged.system_command("echo", args: ["homebrew-cask", "rocks!"])
end
it "can set the permissions of a file" do
fake_pathname = existing_path
allow(staged).to receive(:Pathname).and_return(fake_pathname)
expect(fake_system_command).to receive(:run!)
.with("chmod", args: ["-R", "--", "777", fake_pathname], sudo: false)
staged.set_permissions(fake_pathname.to_s, "777")
end
it "can set the permissions of multiple files" do
fake_pathname = existing_path
allow(staged).to receive(:Pathname).and_return(fake_pathname)
expect(fake_system_command).to receive(:run!)
.with("chmod", args: ["-R", "--", "777", fake_pathname, fake_pathname], sudo: false)
staged.set_permissions([fake_pathname.to_s, fake_pathname.to_s], "777")
end
it "cannot set the permissions of a file that does not exist" do
fake_pathname = non_existent_path
allow(staged).to receive(:Pathname).and_return(fake_pathname)
expect(fake_system_command).not_to receive(:run!)
staged.set_permissions(fake_pathname.to_s, "777")
end
it "can set the ownership of a file" do
fake_pathname = existing_path
allow(User).to receive(:current).and_return(User.new("fake_user"))
allow(staged).to receive(:Pathname).and_return(fake_pathname)
expect(fake_system_command).to receive(:run!)
.with("chown", args: ["-R", "--", "fake_user:staff", fake_pathname], sudo: true)
staged.set_ownership(fake_pathname.to_s)
end
it "can set the ownership of multiple files" do
fake_pathname = existing_path
allow(User).to receive(:current).and_return(User.new("fake_user"))
allow(staged).to receive(:Pathname).and_return(fake_pathname)
expect(fake_system_command).to receive(:run!)
.with(
"chown",
args: ["-R", "--", "fake_user:staff", fake_pathname, fake_pathname],
sudo: true,
)
staged.set_ownership([fake_pathname.to_s, fake_pathname.to_s])
end
it "can set the ownership of a file with a different user and group" do
fake_pathname = existing_path
allow(staged).to receive(:Pathname).and_return(fake_pathname)
expect(fake_system_command).to receive(:run!)
.with(
"chown",
args: ["-R", "--", "other_user:other_group", fake_pathname],
sudo: true,
)
staged.set_ownership(fake_pathname.to_s, user: "other_user", group: "other_group")
end
it "cannot set the ownership of a file that does not exist" do
allow(User).to receive(:current).and_return(User.new("fake_user"))
fake_pathname = non_existent_path
allow(staged).to receive(:Pathname).and_return(fake_pathname)
expect(fake_system_command).not_to receive(:run!)
staged.set_ownership(fake_pathname.to_s)
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/cask/dsl/shared_examples/base.rb | Library/Homebrew/test/cask/dsl/shared_examples/base.rb | # frozen_string_literal: true
require "cask/dsl/base"
RSpec.shared_examples Cask::DSL::Base do
it "supports the token method" do
expect(dsl.token).to eq(cask.token)
end
it "supports the version method" do
expect(dsl.version).to eq(cask.version)
end
it "supports the caskroom_path method" do
expect(dsl.caskroom_path).to eq(cask.caskroom_path)
end
it "supports the staged_path method" do
expect(dsl.staged_path).to eq(cask.staged_path)
end
it "supports the appdir method" do
expect(dsl.appdir).to eq(cask.appdir)
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/cask/artifact/zap_spec.rb | Library/Homebrew/test/cask/artifact/zap_spec.rb | # frozen_string_literal: true
require_relative "shared_examples/uninstall_zap"
RSpec.describe Cask::Artifact::Zap, :cask do
describe "#zap_phase" do
include_examples "#uninstall_phase or #zap_phase"
context "when using :rmdir" do
subject(:artifact) { cask.artifacts.find { |a| a.is_a?(described_class) } }
let(:fake_system_command) { NeverSudoSystemCommand }
let(:cask) { Cask::CaskLoader.load(cask_path("with-zap-rmdir")) }
let(:empty_directory) { Pathname.new("#{TEST_TMPDIR}/empty_directory_path") }
let(:empty_directory_tree) { empty_directory.join("nested", "empty_directory_path") }
let(:ds_store) { empty_directory.join(".DS_Store") }
before do
empty_directory_tree.mkpath
FileUtils.touch ds_store
end
after do
FileUtils.rm_rf empty_directory
end
it "is supported" do
expect(empty_directory_tree).to exist
expect(ds_store).to exist
artifact.zap_phase(command: fake_system_command)
expect(ds_store).not_to exist
expect(empty_directory).not_to exist
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/cask/artifact/bashcompletion_spec.rb | Library/Homebrew/test/cask/artifact/bashcompletion_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Artifact::BashCompletion, :cask do
let(:cask) { Cask::CaskLoader.load(cask_token) }
context "with install" do
let(:install_phase) do
lambda do
cask.artifacts.select { |a| a.is_a?(described_class) }.each do |artifact|
artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end
end
end
let(:source_path) { cask.staged_path.join("test.bash") }
let(:target_path) { cask.config.bash_completion.join("test") }
let(:full_source_path) { cask.staged_path.join("test.bash-completion") }
let(:full_target_path) { cask.config.bash_completion.join("test") }
before do
InstallHelper.install_without_artifacts(cask)
end
context "with completion" do
let(:cask_token) { "with-shellcompletion" }
it "links the completion to the proper directory" do
install_phase.call
expect(File).to be_identical target_path, source_path
end
end
context "with long completion" do
let(:cask_token) { "with-shellcompletion-long" }
it "links the completion to the proper directory" do
install_phase.call
expect(File).to be_identical full_target_path, full_source_path
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/cask/artifact/two_apps_correct_spec.rb | Library/Homebrew/test/cask/artifact/two_apps_correct_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Artifact::App, :cask do
describe "multiple apps" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-two-apps-correct")) }
let(:install_phase) do
cask.artifacts.select { |a| a.is_a?(described_class) }.each do |artifact|
artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end
end
let(:source_path_mini) { cask.staged_path.join("Caffeine Mini.app") }
let(:target_path_mini) { cask.config.appdir.join("Caffeine Mini.app") }
let(:source_path_pro) { cask.staged_path.join("Caffeine Pro.app") }
let(:target_path_pro) { cask.config.appdir.join("Caffeine Pro.app") }
before do
InstallHelper.install_without_artifacts(cask)
end
it "installs both apps using the proper target directory" do
install_phase
expect(target_path_mini).to be_a_directory
expect(source_path_mini).to be_a_symlink
expect(target_path_pro).to be_a_directory
expect(source_path_pro).to be_a_symlink
end
describe "when apps are in a subdirectory" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-two-apps-subdir")) }
let(:source_path_mini) { cask.staged_path.join("Caffeines", "Caffeine Mini.app") }
let(:source_path_pro) { cask.staged_path.join("Caffeines", "Caffeine Pro.app") }
it "installs both apps using the proper target directory" do
install_phase
expect(target_path_mini).to be_a_directory
expect(source_path_mini).to be_a_symlink
expect(target_path_pro).to be_a_directory
expect(source_path_pro).to be_a_symlink
end
end
it "only uses apps when they are specified" do
FileUtils.cp_r source_path_mini, source_path_mini.sub("Caffeine Mini.app", "Caffeine Deluxe.app")
install_phase
expect(target_path_mini).to be_a_directory
expect(source_path_mini).to be_a_symlink
expect(cask.config.appdir.join("Caffeine Deluxe.app")).not_to exist
expect(cask.staged_path.join("Caffeine Deluxe.app")).to exist
end
describe "avoids clobbering an existing app" do
it "when the first app of two already exists" do
target_path_mini.mkpath
expect do
expect { install_phase }.to output(<<~EOS).to_stdout
==> Moving App 'Caffeine Pro.app' to '#{target_path_pro}'
EOS
end.to raise_error(Cask::CaskError, "It seems there is already an App at '#{target_path_mini}'.")
expect(source_path_mini).to be_a_directory
expect(target_path_mini).to be_a_directory
expect(File.identical?(source_path_mini, target_path_mini)).to be false
end
it "when the second app of two already exists" do
target_path_pro.mkpath
expect do
expect { install_phase }.to output(<<~EOS).to_stdout
==> Moving App 'Caffeine Mini.app' to '#{target_path_mini}'
EOS
end.to raise_error(Cask::CaskError, "It seems there is already an App at '#{target_path_pro}'.")
expect(source_path_pro).to be_a_directory
expect(target_path_pro).to be_a_directory
expect(File.identical?(source_path_pro, target_path_pro)).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/cask/artifact/uninstall_no_zap_spec.rb | Library/Homebrew/test/cask/artifact/uninstall_no_zap_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Artifact::Zap, :cask do
let(:cask) { Cask::CaskLoader.load(cask_path("with-installable")) }
let(:zap_artifact) do
cask.artifacts.find { |a| a.is_a?(described_class) }
end
before do
InstallHelper.install_without_artifacts(cask)
end
describe "#uninstall_phase" do
subject { zap_artifact }
it { is_expected.not_to respond_to(:uninstall_phase) }
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/cask/artifact/symlinked_spec.rb | Library/Homebrew/test/cask/artifact/symlinked_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Artifact::Symlinked, :cask do
# Test the formula conflict detection functionality that applies to all symlinked artifacts
describe "#conflicting_formula" do
let(:cask) do
Cask::CaskLoader.load(cask_path("with-binary")).tap do |cask|
InstallHelper.install_without_artifacts(cask)
end
end
let(:binary_artifact) { cask.artifacts.find { |a| a.is_a?(Cask::Artifact::Binary) } }
let(:binarydir) { cask.config.binarydir }
let(:target_path) { binarydir.join("binary") }
around do |example|
binarydir.mkpath
example.run
ensure
FileUtils.rm_f target_path
FileUtils.rmdir binarydir
# Clean up the fake formula directory
FileUtils.rm_rf(HOMEBREW_CELLAR/"with-binary") if (HOMEBREW_CELLAR/"with-binary").exist?
end
context "when target is already linked from a formula" do
it "detects the conflict and skips linking with warning" do
# Create a fake formula directory structure
formula_cellar_path = HOMEBREW_CELLAR/"with-binary/1.0.0/bin"
formula_cellar_path.mkpath
formula_binary_path = formula_cellar_path/"binary"
FileUtils.touch formula_binary_path
# Create symlink from the expected location to the formula binary
target_path.make_symlink(formula_binary_path)
stderr = <<~EOS
Warning: It seems there is already a Binary at '#{target_path}' from formula with-binary; skipping link.
EOS
expect do
binary_artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end.to output(stderr).to_stderr
expect(target_path).to be_a_symlink
expect(target_path.readlink).to eq(formula_binary_path)
end
end
context "when target doesn't exist" do
it "proceeds with normal installation" do
expect do
binary_artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end.not_to raise_error
expect(target_path).to be_a_symlink
expect(target_path.readlink).to exist
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/cask/artifact/generic_artifact_spec.rb | Library/Homebrew/test/cask/artifact/generic_artifact_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Artifact::Artifact, :cask do
let(:cask) { Cask::CaskLoader.load(cask_path("with-generic-artifact")) }
let(:install_phase) do
lambda do
cask.artifacts.select { |a| a.is_a?(described_class) }.each do |artifact|
artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end
end
end
let(:source_path) { cask.staged_path.join("Caffeine.app") }
let(:target_path) { cask.config.appdir.join("Caffeine.app") }
before do
InstallHelper.install_without_artifacts(cask)
end
context "without target" do
it "fails to load", :no_api do
expect do
Cask::CaskLoader.load("invalid-generic-artifact-no-target")
end.to raise_error(Cask::CaskInvalidError, /Generic Artifact.*requires.*target/)
end
end
context "with relative target" do
it "does not fail to load" do
expect do
Cask::CaskLoader.load("generic-artifact-relative-target")
end.not_to raise_error
end
end
context "with user-relative target" do
it "does not fail to load" do
expect do
Cask::CaskLoader.load("generic-artifact-user-relative-target")
end.not_to raise_error
end
end
it "moves the artifact to the proper directory" do
install_phase.call
expect(target_path).to be_a_directory
expect(source_path).to be_a_symlink
end
it "avoids clobbering an existing artifact" do
target_path.mkpath
expect do
install_phase.call
end.to raise_error(Cask::CaskError)
expect(source_path).to be_a_directory
expect(target_path).to be_a_directory
expect(File.identical?(source_path, target_path)).to be false
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/cask/artifact/preflight_block_spec.rb | Library/Homebrew/test/cask/artifact/preflight_block_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Artifact::PreflightBlock, :cask do
describe "install_phase" do
it "calls the specified block before installing, passing a Cask mini-dsl" do
called = false
yielded_arg = nil
cask = Cask::Cask.new("with-preflight") do
preflight do |c|
called = true
yielded_arg = c
end
end
cask.artifacts.select { |a| a.is_a?(described_class) }.each do |artifact|
artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end
expect(called).to be true
expect(yielded_arg).to be_a Cask::DSL::Preflight
end
end
describe "uninstall_phase" do
it "calls the specified block before uninstalling, passing a Cask mini-dsl" do
called = false
yielded_arg = nil
cask = Cask::Cask.new("with-uninstall-preflight") do
uninstall_preflight do |c|
called = true
yielded_arg = c
end
end
cask.artifacts.select { |a| a.is_a?(described_class) }.each do |artifact|
artifact.uninstall_phase(command: NeverSudoSystemCommand, force: false)
end
expect(called).to be true
expect(yielded_arg).to be_a Cask::DSL::UninstallPreflight
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/cask/artifact/fishlcompletion_spec.rb | Library/Homebrew/test/cask/artifact/fishlcompletion_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Artifact::FishCompletion, :cask do
let(:cask) { Cask::CaskLoader.load(cask_token) }
context "with install" do
let(:install_phase) do
lambda do
cask.artifacts.select { |a| a.is_a?(described_class) }.each do |artifact|
artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end
end
end
let(:source_path) { cask.staged_path.join("test.fish") }
let(:target_path) { cask.config.fish_completion.join("test.fish") }
let(:full_source_path) { cask.staged_path.join("test.fish-completion") }
let(:full_target_path) { cask.config.fish_completion.join("test.fish") }
before do
InstallHelper.install_without_artifacts(cask)
end
context "with completion" do
let(:cask_token) { "with-shellcompletion" }
it "links the completion to the proper directory" do
install_phase.call
expect(File).to be_identical target_path, source_path
end
end
context "with long completion" do
let(:cask_token) { "with-shellcompletion-long" }
it "links the completion to the proper directory" do
install_phase.call
expect(File).to be_identical full_target_path, full_source_path
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/cask/artifact/postflight_block_spec.rb | Library/Homebrew/test/cask/artifact/postflight_block_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Artifact::PostflightBlock, :cask do
describe "install_phase" do
it "calls the specified block after installing, passing a Cask mini-dsl" do
called = false
yielded_arg = nil
cask = Cask::Cask.new("with-postflight") do
postflight do |c|
called = true
yielded_arg = c
end
end
cask.artifacts.select { |a| a.is_a?(described_class) }.each do |artifact|
artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end
expect(called).to be true
expect(yielded_arg).to be_a(Cask::DSL::Postflight)
end
end
describe "uninstall_phase" do
it "calls the specified block after uninstalling, passing a Cask mini-dsl" do
called = false
yielded_arg = nil
cask = Cask::Cask.new("with-uninstall-postflight") do
uninstall_postflight do |c|
called = true
yielded_arg = c
end
end
cask.artifacts.select { |a| a.is_a?(described_class) }.each do |artifact|
artifact.uninstall_phase(command: NeverSudoSystemCommand, force: false)
end
expect(called).to be true
expect(yielded_arg).to be_a(Cask::DSL::UninstallPostflight)
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/cask/artifact/binary_spec.rb | Library/Homebrew/test/cask/artifact/binary_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Artifact::Binary, :cask do
let(:cask) do
Cask::CaskLoader.load(cask_path("with-binary")).tap do |cask|
InstallHelper.install_without_artifacts(cask)
end
end
let(:artifacts) { cask.artifacts.select { |a| a.is_a?(described_class) } }
let(:binarydir) { cask.config.binarydir }
let(:expected_path) { binarydir.join("binary") }
around do |example|
binarydir.mkpath
example.run
ensure
FileUtils.rm_f expected_path
FileUtils.rmdir binarydir
end
context "when --no-binaries is specified" do
let(:cask) do
Cask::CaskLoader.load(cask_path("with-binary"))
end
it "doesn't link the binary when --no-binaries is specified" do
Cask::Installer.new(cask, binaries: false).install
expect(expected_path).not_to exist
end
end
it "links the binary to the proper directory" do
artifacts.each do |artifact|
artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end
expect(expected_path).to be_a_symlink
expect(expected_path.readlink).to exist
end
context "when the binary is not executable" do
let(:cask) do
Cask::CaskLoader.load(cask_path("with-non-executable-binary")).tap do |cask|
InstallHelper.install_without_artifacts(cask)
end
end
let(:expected_path) { cask.config.binarydir.join("naked_non_executable") }
it "makes the binary executable" do
expect(FileUtils).to receive(:chmod)
.with("+x", cask.staged_path.join("naked_non_executable")).and_call_original
artifacts.each do |artifact|
artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end
expect(expected_path).to be_a_symlink
expect(expected_path.readlink).to be_executable
end
end
it "avoids clobbering an existing binary by linking over it" do
FileUtils.touch expected_path
expect do
artifacts.each do |artifact|
artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end
end.to raise_error(Cask::CaskError)
expect(expected_path).not_to be :symlink?
end
it "avoids clobbering an existing symlink" do
expected_path.make_symlink("/tmp")
expect do
artifacts.each do |artifact|
artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end
end.to raise_error(Cask::CaskError)
expect(File.readlink(expected_path)).to eq("/tmp")
end
it "creates parent directory if it doesn't exist" do
FileUtils.rmdir binarydir
artifacts.each do |artifact|
artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end
expect(expected_path.exist?).to be true
end
context "when the binary is inside an app package" do
let(:cask) do
Cask::CaskLoader.load(cask_path("with-embedded-binary")).tap do |cask|
InstallHelper.install_without_artifacts(cask)
end
end
it "links the binary to the proper directory" do
cask.artifacts.select { |a| a.is_a?(Cask::Artifact::App) }.each do |artifact|
artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end
artifacts.each do |artifact|
artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end
expect(expected_path).to be_a_symlink
expect(expected_path.readlink).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/cask/artifact/relocated_spec.rb | Library/Homebrew/test/cask/artifact/relocated_spec.rb | # frozen_string_literal: true
require "cask/artifact/relocated"
RSpec.describe Cask::Artifact::Relocated, :cask do
let(:cask) do
Cask::Cask.new("test-cask") do
url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip"
homepage "https://brew.sh/"
version "1.0"
sha256 "67cdb8a02803ef37fdbf7e0be205863172e41a561ca446cd84f0d7ab35a99d94"
end
end
let(:command) { NeverSudoSystemCommand }
let(:artifact) { described_class.new(cask, "test_file.txt") }
describe "#add_altname_metadata" do
let(:file) { Pathname("/tmp/test_file.txt") }
let(:altname) { Pathname("alternate_name.txt") }
before do
allow(file).to receive_messages(basename: Pathname("test_file.txt"), writable?: true, realpath: file)
end
context "when running on Linux", :needs_linux do
it "is a no-op and does not call xattr commands" do
expect(command).not_to receive(:run)
expect(command).not_to receive(:run!)
artifact.send(:add_altname_metadata, file, altname, command: command)
end
end
context "when running on macOS", :needs_macos do
before do
stdout_double = instance_double(SystemCommand::Result, stdout: "")
allow(command).to receive(:run).and_return(stdout_double)
allow(command).to receive(:run!)
end
it "calls xattr commands to set metadata" do
expect(command).to receive(:run).with("/usr/bin/xattr",
args: ["-p", "com.apple.metadata:kMDItemAlternateNames", file],
print_stderr: false)
expect(command).to receive(:run!).twice
artifact.send(:add_altname_metadata, file, altname, command: command)
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/cask/artifact/pkg_spec.rb | Library/Homebrew/test/cask/artifact/pkg_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Artifact::Pkg, :cask do
let(:cask) { Cask::CaskLoader.load(cask_path("with-installable")) }
let(:fake_system_command) { class_double(SystemCommand) }
before do
InstallHelper.install_without_artifacts(cask)
end
describe "install_phase" do
it "runs the system installer on the specified pkgs" do
pkg = cask.artifacts.find { |a| a.is_a?(described_class) }
expect(fake_system_command).to receive(:run!).with(
"/usr/sbin/installer",
args: ["-pkg", cask.staged_path.join("MyFancyPkg", "Fancy.pkg"), "-target", "/"],
sudo: true,
sudo_as_root: true,
print_stdout: true,
env: {
"LOGNAME" => ENV.fetch("USER"),
"USER" => ENV.fetch("USER"),
"USERNAME" => ENV.fetch("USER"),
},
)
pkg.install_phase(command: fake_system_command)
end
end
describe "choices" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-choices")) }
it "passes the choice changes xml to the system installer" do
pkg = cask.artifacts.find { |a| a.is_a?(described_class) }
file = instance_double(Tempfile, path: Pathname.new("/tmp/choices.xml"))
expect(file).to receive(:write).with <<~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">
<array>
\t<dict>
\t\t<key>attributeSetting</key>
\t\t<integer>1</integer>
\t\t<key>choiceAttribute</key>
\t\t<string>selected</string>
\t\t<key>choiceIdentifier</key>
\t\t<string>choice1</string>
\t</dict>
</array>
</plist>
XML
expect(file).to receive(:close)
expect(file).to receive(:unlink)
expect(Tempfile).to receive(:open).and_yield(file)
expect(fake_system_command).to receive(:run!).with(
"/usr/sbin/installer",
args: [
"-pkg", cask.staged_path.join("MyFancyPkg", "Fancy.pkg"),
"-target", "/", "-applyChoiceChangesXML",
cask.staged_path.join("/tmp/choices.xml")
],
sudo: true,
sudo_as_root: true,
print_stdout: true,
env: {
"LOGNAME" => ENV.fetch("USER"),
"USER" => ENV.fetch("USER"),
"USERNAME" => ENV.fetch("USER"),
},
)
pkg.install_phase(command: fake_system_command)
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/cask/artifact/suite_spec.rb | Library/Homebrew/test/cask/artifact/suite_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Artifact::Suite, :cask do
let(:cask) { Cask::CaskLoader.load(cask_path("with-suite")) }
let(:install_phase) do
lambda do
cask.artifacts.select { |a| a.is_a?(described_class) }.each do |artifact|
artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end
end
end
let(:target_path) { cask.config.appdir.join("Caffeine") }
let(:source_path) { cask.staged_path.join("Caffeine") }
before do
InstallHelper.install_without_artifacts(cask)
end
it "creates a suite containing the expected app" do
install_phase.call
expect(target_path.join("Caffeine.app")).to exist
end
it "avoids clobbering an existing suite by moving over it" do
target_path.mkpath
expect do
install_phase.call
end.to raise_error(Cask::CaskError)
expect(source_path).to be_a_directory
expect(target_path).to be_a_directory
expect(File.identical?(source_path, target_path)).to be false
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/cask/artifact/abstract_artifact_spec.rb | Library/Homebrew/test/cask/artifact/abstract_artifact_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Artifact::AbstractArtifact, :cask do
describe ".read_script_arguments" do
let(:stanza) { :installer }
it "accepts a string and uses it as the executable" do
arguments = "something"
expect(described_class.read_script_arguments(arguments, stanza)).to eq(["something", {}])
end
it "accepts a hash with an executable" do
arguments = { executable: "something" }
expect(described_class.read_script_arguments(arguments, stanza)).to eq(["something", {}])
end
it "does not mutate the original arguments in place" do
arguments = { executable: "something" }
clone = arguments.dup
described_class.read_script_arguments(arguments, stanza)
expect(arguments).to eq(clone)
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/cask/artifact/app_spec.rb | Library/Homebrew/test/cask/artifact/app_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Artifact::App, :cask do
let(:cask) { Cask::CaskLoader.load(cask_path("local-caffeine")) }
let(:command) { NeverSudoSystemCommand }
let(:adopt) { false }
let(:force) { false }
let(:auto_updates) { false }
let(:app) { cask.artifacts.find { |a| a.is_a?(described_class) } }
let(:source_path) { cask.staged_path.join("Caffeine.app") }
let(:target_path) { cask.config.appdir.join("Caffeine.app") }
let(:install_phase) { app.install_phase(command:, adopt:, force:, auto_updates:) }
let(:uninstall_phase) { app.uninstall_phase(command:, force:) }
before do
InstallHelper.install_without_artifacts(cask)
end
describe "install_phase" do
it "installs the given app using the proper target directory" do
install_phase
expect(target_path).to be_a_directory
expect(source_path).to be_a_symlink
end
describe "when app is in a subdirectory" do
let(:cask) do
Cask::Cask.new("subdir") do
url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip"
homepage "https://brew.sh/local-caffeine"
version "1.2.3"
sha256 "67cdb8a02803ef37fdbf7e0be205863172e41a561ca446cd84f0d7ab35a99d94"
app "subdir/Caffeine.app"
end
end
it "installs the given app using the proper target directory" do
appsubdir = cask.staged_path.join("subdir").tap(&:mkpath)
FileUtils.mv(source_path, appsubdir)
install_phase
expect(target_path).to be_a_directory
expect(appsubdir.join("Caffeine.app")).to be_a_symlink
end
end
it "only uses apps when they are specified" do
staged_app_copy = source_path.sub("Caffeine.app", "Caffeine Deluxe.app")
FileUtils.cp_r source_path, staged_app_copy
install_phase
expect(target_path).to be_a_directory
expect(source_path).to be_a_symlink
expect(cask.config.appdir.join("Caffeine Deluxe.app")).not_to exist
expect(cask.staged_path.join("Caffeine Deluxe.app")).to exist
end
describe "when the target already exists" do
before do
target_path.mkpath
end
it "avoids clobbering an existing app" do
expect { install_phase }.to raise_error(
Cask::CaskError,
"It seems there is already an App at '#{target_path}'.",
)
expect(source_path).to be_a_directory
expect(target_path).to be_a_directory
expect(File.identical?(source_path, target_path)).to be false
contents_path = target_path.join("Contents/Info.plist")
expect(contents_path).not_to exist
end
describe "given the adopt option" do
let(:adopt) { true }
describe "when the target compares different from the source" do
describe "when the cask does not auto_updates" do
it "avoids clobbering the existing app if brew manages updates" do
stdout = <<~EOS
==> Adopting existing App at '#{target_path}'
EOS
expect { install_phase }
.to output(stdout).to_stdout
.and raise_error(
Cask::CaskError,
"It seems the existing App is different from the one being installed.",
)
expect(source_path).to be_a_directory
expect(target_path).to be_a_directory
expect(File.identical?(source_path, target_path)).to be false
contents_path = target_path.join("Contents/Info.plist")
expect(contents_path).not_to exist
end
end
describe "when the cask auto_updates" do
before do
target_path.delete
FileUtils.cp_r source_path, target_path
File.write(target_path.join("Contents/Info.plist"), "different")
end
let(:auto_updates) { true }
it "adopts the existing app" do
stdout = <<~EOS
==> Adopting existing App at '#{target_path}'
EOS
stderr = ""
expect { install_phase }
.to output(stdout).to_stdout
.and output(stderr).to_stderr
expect(source_path).to be_a_symlink
expect(target_path).to be_a_directory
contents_path = target_path.join("Contents/Info.plist")
expect(contents_path).to exist
expect(File.read(contents_path)).to eq("different")
end
end
end
describe "when the target compares the same as the source" do
before do
target_path.delete
FileUtils.cp_r source_path, target_path
end
it "adopts the existing app" do
stdout = <<~EOS
==> Adopting existing App at '#{target_path}'
EOS
stderr = ""
expect { install_phase }
.to output(stdout).to_stdout
.and output(stderr).to_stderr
expect(source_path).to be_a_symlink
expect(target_path).to be_a_directory
contents_path = target_path.join("Contents/Info.plist")
expect(contents_path).to exist
end
end
end
describe "given the force option" do
let(:force) { true }
before do
allow(User).to receive(:current).and_return(User.new("fake_user"))
end
describe "target is both writable and user-owned" do
it "overwrites the existing app" do
stdout = <<~EOS
==> Removing App '#{target_path}'
==> Moving App 'Caffeine.app' to '#{target_path}'
EOS
stderr = <<~EOS
Warning: It seems there is already an App at '#{target_path}'; overwriting.
EOS
expect { install_phase }
.to output(stdout).to_stdout
.and output(stderr).to_stderr
expect(source_path).to be_a_symlink
expect(target_path).to be_a_directory
contents_path = target_path.join("Contents/Info.plist")
expect(contents_path).to exist
end
end
describe "target is user-owned but contains read-only files" do
before do
FileUtils.touch "#{target_path}/foo"
FileUtils.chmod 0555, target_path
end
after do
FileUtils.chmod 0755, target_path
end
it "overwrites the existing app" do
expect(command).to receive(:run).and_call_original.at_least(:once)
stdout = <<~EOS
==> Removing App '#{target_path}'
==> Moving App 'Caffeine.app' to '#{target_path}'
EOS
stderr = <<~EOS
Warning: It seems there is already an App at '#{target_path}'; overwriting.
EOS
expect { install_phase }
.to output(stdout).to_stdout
.and output(stderr).to_stderr
expect(source_path).to be_a_symlink
expect(target_path).to be_a_directory
contents_path = target_path.join("Contents/Info.plist")
expect(contents_path).to exist
end
end
end
end
describe "when the target is a broken symlink" do
let(:deleted_path) { cask.staged_path.join("Deleted.app") }
before do
deleted_path.mkdir
File.symlink(deleted_path, target_path)
deleted_path.rmdir
end
it "leaves the target alone" do
expect { install_phase }.to raise_error(
Cask::CaskError, "It seems there is already an App at '#{target_path}'."
)
expect(target_path).to be_a_symlink
end
describe "given the force option" do
let(:force) { true }
it "overwrites the existing app" do
stdout = <<~EOS
==> Removing App '#{target_path}'
==> Moving App 'Caffeine.app' to '#{target_path}'
EOS
stderr = <<~EOS
Warning: It seems there is already an App at '#{target_path}'; overwriting.
EOS
expect { install_phase }
.to output(stdout).to_stdout
.and output(stderr).to_stderr
expect(source_path).to be_a_symlink
expect(target_path).to be_a_directory
contents_path = target_path.join("Contents/Info.plist")
expect(contents_path).to exist
end
end
end
it "gives a warning if the source doesn't exist" do
FileUtils.rm_r(source_path)
message = "It seems the App source '#{source_path}' is not there."
expect { install_phase }.to raise_error(Cask::CaskError, message)
end
end
describe "uninstall_phase" do
after do
FileUtils.chmod 0755, target_path if target_path.exist?
FileUtils.chmod 0755, source_path if source_path.exist?
end
it "deletes managed apps" do
install_phase
expect(target_path).to exist
uninstall_phase
expect(target_path).not_to exist
end
it "backs up read-only managed apps" do
install_phase
FileUtils.chmod 0544, target_path
uninstall_phase
expect(source_path).to be_a_directory
end
end
describe "summary" do
let(:description) { app.class.english_description }
let(:contents) { app.summarize_installed }
it "returns the correct english_description" do
expect(description).to eq("Apps")
end
describe "app is correctly installed" do
it "returns the path to the app" do
install_phase
expect(contents).to eq("#{target_path} (#{target_path.abv})")
end
end
describe "app is missing" do
it "returns a warning and the supposed path to the app" do
expect(contents).to match(/.*Missing App.*: #{target_path}/)
end
end
end
describe "upgrade" do
before do
install_phase
end
# Fix for https://github.com/Homebrew/homebrew-cask/issues/102721
it "reuses the same directory" do
contents_path = target_path.join("Contents/Info.plist")
expect(target_path).to exist
inode = target_path.stat.ino
expect(contents_path).to exist
app.uninstall_phase(command:, force:, successor: cask)
expect(target_path).to exist
expect(target_path.children).to be_empty
expect(contents_path).not_to exist
app.install_phase(command:, adopt:, force:, predecessor: cask)
expect(target_path).to exist
expect(target_path.stat.ino).to eq(inode)
expect(contents_path).to exist
end
describe "when the system blocks modifying apps" do
it "uninstalls and reinstalls the app" do
target_contents_path = target_path.join("Contents")
expect(File).to receive(:write).with(target_path / ".homebrew-write-test",
instance_of(String)).and_raise(Errno::EACCES)
app.uninstall_phase(command:, force:, successor: cask)
expect(target_path).not_to exist
app.install_phase(command:, adopt:, force:, predecessor: cask)
expect(target_contents_path).to exist
end
end
describe "when the directory is owned by root" do
before do
allow(app.target).to receive_messages(writable?: false, owned?: false)
end
it "reuses the same directory" do
source_contents_path = source_path.join("Contents")
target_contents_path = target_path.join("Contents")
allow(command).to receive(:run!).with(any_args).and_call_original
expect(command).to receive(:run!)
.with("/bin/cp", args: ["-pR", source_contents_path, target_path],
sudo: true)
.and_call_original
expect(FileUtils).not_to receive(:move).with(source_contents_path, an_instance_of(Pathname))
app.uninstall_phase(command:, force:, successor: cask)
expect(target_contents_path).not_to exist
expect(target_path).to exist
expect(source_contents_path).to exist
app.install_phase(command:, adopt:, force:, predecessor: cask)
expect(target_contents_path).to exist
end
describe "when the system blocks modifying apps" do
it "uninstalls and reinstalls the app" do
target_contents_path = target_path.join("Contents")
allow(command).to receive(:run!).with(any_args).and_call_original
expect(command).to receive(:run!)
.with("touch", args: [target_path / ".homebrew-write-test"],
print_stderr: false,
sudo: true)
.and_raise(ErrorDuringExecution.new([], status: 1,
output: [[:stderr, "touch: #{target_path}/.homebrew-write-test: Operation not permitted\n"]], secrets: []))
app.uninstall_phase(command:, force:, successor: cask)
expect(target_path).not_to exist
app.install_phase(command:, adopt:, force:, predecessor: cask)
expect(target_contents_path).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/cask/artifact/manpage_spec.rb | Library/Homebrew/test/cask/artifact/manpage_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Artifact::Manpage, :cask do
let(:cask) { Cask::CaskLoader.load(cask_token) }
context "without section" do
let(:cask_token) { "invalid-manpage-no-section" }
it "fails to load a cask without section", :no_api do
expect { cask }.to raise_error(Cask::CaskInvalidError, /is not a valid man page name/)
end
end
context "with install" do
let(:install_phase) do
lambda do
cask.artifacts.select { |a| a.is_a?(described_class) }.each do |artifact|
artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end
end
end
let(:source_path) { cask.staged_path.join("manpage.1") }
let(:target_path) { cask.config.manpagedir.join("man1/manpage.1") }
let(:gz_source_path) { cask.staged_path.join("gzpage.1.gz") }
let(:gz_target_path) { cask.config.manpagedir.join("man1/gzpage.1.gz") }
before do
InstallHelper.install_without_artifacts(cask)
end
context "with autodetected section" do
let(:cask_token) { "with-autodetected-manpage-section" }
it "links the manpage to the proper directory" do
install_phase.call
expect(File).to be_identical target_path, source_path
expect(File).to be_identical gz_target_path, gz_source_path
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/cask/artifact/alt_target_spec.rb | Library/Homebrew/test/cask/artifact/alt_target_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Artifact::App, :cask do
describe "activate to alternate target" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-alt-target")) }
let(:install_phase) do
cask.artifacts.select { |a| a.is_a?(described_class) }.each do |artifact|
artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end
end
let(:source_path) { cask.staged_path.join("Caffeine.app") }
let(:target_path) { cask.config.appdir.join("AnotherName.app") }
before do
InstallHelper.install_without_artifacts(cask)
end
it "installs the given apps using the proper target directory" do
expect(source_path).to be_a_directory
expect(target_path).not_to exist
install_phase
expect(target_path).to be_a_directory
expect(source_path).to be_a_symlink
end
describe "when app is in a subdirectory" do
let(:cask) do
Cask::Cask.new("subdir") do
url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip"
homepage "https://brew.sh/local-caffeine"
version "1.2.3"
sha256 "67cdb8a02803ef37fdbf7e0be205863172e41a561ca446cd84f0d7ab35a99d94"
app "subdir/Caffeine.app", target: "AnotherName.app"
end
end
it "installs the given apps using the proper target directory" do
appsubdir = cask.staged_path.join("subdir").tap(&:mkpath)
FileUtils.mv(source_path, appsubdir)
install_phase
expect(target_path).to be_a_directory
expect(appsubdir.join("Caffeine.app")).to be_a_symlink
end
end
it "only uses apps when they are specified" do
staged_app_copy = source_path.sub("Caffeine.app", "Caffeine Deluxe.app")
FileUtils.cp_r source_path, staged_app_copy
install_phase
expect(target_path).to be_a_directory
expect(source_path).to be_a_symlink
expect(cask.config.appdir.join("Caffeine Deluxe.app")).not_to exist
expect(cask.staged_path.join("Caffeine Deluxe.app")).to be_a_directory
end
it "avoids clobbering an existing app by moving over it" do
target_path.mkpath
expect { install_phase }
.to raise_error(Cask::CaskError, "It seems there is already an App at '#{target_path}'.")
expect(source_path).to be_a_directory
expect(target_path).to be_a_directory
expect(File.identical?(source_path, target_path)).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/cask/artifact/zshcompletion_spec.rb | Library/Homebrew/test/cask/artifact/zshcompletion_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Artifact::ZshCompletion, :cask do
let(:cask) { Cask::CaskLoader.load(cask_token) }
context "with install" do
let(:install_phase) do
lambda do
cask.artifacts.select { |a| a.is_a?(described_class) }.each do |artifact|
artifact.install_phase(command: NeverSudoSystemCommand, force: false)
end
end
end
let(:source_path) { cask.staged_path.join("_test") }
let(:target_path) { cask.config.zsh_completion.join("_test") }
let(:full_source_path) { cask.staged_path.join("test.zsh-completion") }
let(:full_target_path) { cask.config.zsh_completion.join("_test") }
before do
InstallHelper.install_without_artifacts(cask)
end
context "with completion" do
let(:cask_token) { "with-shellcompletion" }
it "links the completion to the proper directory" do
install_phase.call
expect(File).to be_identical target_path, source_path
end
end
context "with long completion" do
let(:cask_token) { "with-shellcompletion-long" }
it "links the completion to the proper directory" do
install_phase.call
expect(File).to be_identical full_target_path, full_source_path
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/cask/artifact/uninstall_spec.rb | Library/Homebrew/test/cask/artifact/uninstall_spec.rb | # frozen_string_literal: true
require_relative "shared_examples/uninstall_zap"
RSpec.describe Cask::Artifact::Uninstall, :cask do
describe "#uninstall_phase" do
let(:fake_system_command) { NeverSudoSystemCommand }
include_examples "#uninstall_phase or #zap_phase"
describe "upgrade/reinstall opt-in uninstall directives" do
context "with-uninstall-quit" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-uninstall-quit")) }
let(:artifact) { cask.artifacts.find { |a| a.is_a?(described_class) } }
it "skips :quit by default during upgrade" do
quit_called = false
allow(artifact).to receive(:dispatch_uninstall_directive) do |directive, **options|
quit_called ||= directive == :quit && options[:command] == fake_system_command
end
artifact.uninstall_phase(upgrade: true, command: fake_system_command)
expect(quit_called).to be false
end
it "skips :quit by default during reinstall" do
quit_called = false
allow(artifact).to receive(:dispatch_uninstall_directive) do |directive, **options|
quit_called ||= directive == :quit && options[:command] == fake_system_command
end
artifact.uninstall_phase(reinstall: true, command: fake_system_command)
expect(quit_called).to be false
end
end
context "with-uninstall-quit-on-upgrade" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-uninstall-quit-on-upgrade")) }
let(:artifact) { cask.artifacts.find { |a| a.is_a?(described_class) } }
it "invokes :quit during upgrade" do
quit_called = false
allow(artifact).to receive(:dispatch_uninstall_directive) do |directive, **options|
quit_called ||= directive == :quit && options[:command] == fake_system_command
end
artifact.uninstall_phase(upgrade: true, command: fake_system_command)
expect(quit_called).to be true
end
it "invokes :quit during reinstall" do
quit_called = false
allow(artifact).to receive(:dispatch_uninstall_directive) do |directive, **options|
quit_called ||= directive == :quit && options[:command] == fake_system_command
end
artifact.uninstall_phase(reinstall: true, command: fake_system_command)
expect(quit_called).to be true
end
end
context "with-uninstall-signal" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-uninstall-signal")) }
let(:artifact) { cask.artifacts.find { |a| a.is_a?(described_class) } }
it "skips :signal by default during upgrade" do
signal_called = false
allow(artifact).to receive(:dispatch_uninstall_directive) do |directive, **options|
signal_called ||= directive == :signal && options[:command] == fake_system_command
end
artifact.uninstall_phase(upgrade: true, command: fake_system_command)
expect(signal_called).to be false
end
it "skips :signal by default during reinstall" do
signal_called = false
allow(artifact).to receive(:dispatch_uninstall_directive) do |directive, **options|
signal_called ||= directive == :signal && options[:command] == fake_system_command
end
artifact.uninstall_phase(reinstall: true, command: fake_system_command)
expect(signal_called).to be false
end
end
context "with-uninstall-signal-on-upgrade" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-uninstall-signal-on-upgrade")) }
let(:artifact) { cask.artifacts.find { |a| a.is_a?(described_class) } }
it "invokes :signal during upgrade" do
signal_called = false
allow(artifact).to receive(:dispatch_uninstall_directive) do |directive, **options|
signal_called ||= directive == :signal && options[:command] == fake_system_command
end
artifact.uninstall_phase(upgrade: true, command: fake_system_command)
expect(signal_called).to be true
end
it "invokes :signal during reinstall" do
signal_called = false
allow(artifact).to receive(:dispatch_uninstall_directive) do |directive, **options|
signal_called ||= directive == :signal && options[:command] == fake_system_command
end
artifact.uninstall_phase(reinstall: true, command: fake_system_command)
expect(signal_called).to be true
end
end
end
context "with-uninstall-both-on-upgrade" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-uninstall-both-on-upgrade")) }
let(:artifact) { cask.artifacts.find { |a| a.is_a?(described_class) } }
it "invokes both quit and signal during upgrade" do
quit_called = false
signal_called = false
allow(artifact).to receive(:dispatch_uninstall_directive) do |directive, **options|
quit_called ||= directive == :quit && options[:command] == fake_system_command
signal_called ||= directive == :signal && options[:command] == fake_system_command
end
artifact.uninstall_phase(upgrade: true, command: fake_system_command)
expect(quit_called).to be true
expect(signal_called).to be true
end
end
context "with-uninstall-quit-only-on-upgrade" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-uninstall-quit-only-on-upgrade")) }
let(:artifact) { cask.artifacts.find { |a| a.is_a?(described_class) } }
it "invokes only quit during upgrade when on_upgrade: [:quit]" do
quit_called = false
signal_called = false
allow(artifact).to receive(:dispatch_uninstall_directive) do |directive, **options|
quit_called ||= directive == :quit && options[:command] == fake_system_command
signal_called ||= directive == :signal && options[:command] == fake_system_command
end
artifact.uninstall_phase(upgrade: true, command: fake_system_command)
expect(quit_called).to be true
expect(signal_called).to be false
end
end
end
describe "#post_uninstall_phase" do
subject(:artifact) { cask.artifacts.find { |a| a.is_a?(described_class) } }
context "when using :rmdir" do
let(:fake_system_command) { NeverSudoSystemCommand }
let(:cask) { Cask::CaskLoader.load(cask_path("with-uninstall-rmdir")) }
let(:empty_directory) { Pathname.new("#{TEST_TMPDIR}/empty_directory_path") }
let(:empty_directory_tree) { empty_directory.join("nested", "empty_directory_path") }
let(:ds_store) { empty_directory.join(".DS_Store") }
before do
empty_directory_tree.mkpath
FileUtils.touch ds_store
end
after do
FileUtils.rm_rf empty_directory
end
it "is supported" do
expect(empty_directory_tree).to exist
expect(ds_store).to exist
artifact.post_uninstall_phase(command: fake_system_command)
expect(ds_store).not_to exist
expect(empty_directory).not_to exist
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/cask/artifact/installer_spec.rb | Library/Homebrew/test/cask/artifact/installer_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::Artifact::Installer, :cask do
subject(:installer) { described_class.new(cask, **args) }
let(:staged_path) { mktmpdir }
let(:cask) { instance_double(Cask::Cask, staged_path:) }
let(:command) { SystemCommand }
let(:args) { {} }
describe "#install_phase" do
context "when given a manual installer" do
let(:args) { { manual: "installer" } }
it "shows a message prompting to run the installer manually" do
expect do
installer.install_phase(command:)
end.to output(%r{open #{staged_path}/installer}).to_stdout
end
end
context "when given a script installer" do
let(:executable) { staged_path/"executable" }
let(:args) { { script: { executable: "executable" } } }
before do
FileUtils.touch executable
end
it "looks for the executable in HOMEBREW_PREFIX" do
expect(command).to receive(:run!).with(
executable,
a_hash_including(
env: { "PATH" => PATH.new("#{HOMEBREW_PREFIX}/bin", "#{HOMEBREW_PREFIX}/sbin", ENV.fetch("PATH")) },
),
)
installer.install_phase(command:)
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/cask/artifact/shared_examples/uninstall_zap.rb | Library/Homebrew/test/cask/artifact/shared_examples/uninstall_zap.rb | # frozen_string_literal: true
require "benchmark"
RSpec.shared_examples "#uninstall_phase or #zap_phase" do
subject { artifact }
let(:artifact_dsl_key) { described_class.dsl_key }
let(:artifact) { cask.artifacts.find { |a| a.is_a?(described_class) } }
let(:fake_system_command) { class_double(SystemCommand) }
context "when using :launchctl" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-#{artifact_dsl_key}-launchctl")) }
let(:launchctl_list_cmd) { %w[/bin/launchctl list my.fancy.package.service] }
let(:launchctl_remove_cmd) { %w[/bin/launchctl remove my.fancy.package.service] }
let(:unknown_response) { "launchctl list returned unknown response\n" }
let(:service_info) do
<<~EOS
{
"LimitLoadToSessionType" = "Aqua";
"Label" = "my.fancy.package.service";
"TimeOut" = 30;
"OnDemand" = true;
"LastExitStatus" = 0;
"ProgramArguments" = (
"argument";
);
};
EOS
end
it "works when job is owned by user" do
allow(fake_system_command).to receive(:run)
.with(
"/bin/launchctl",
args: ["list", "my.fancy.package.service"],
print_stderr: false,
sudo: false,
sudo_as_root: false,
)
.and_return(instance_double(SystemCommand::Result, stdout: service_info))
allow(fake_system_command).to receive(:run)
.with(
"/bin/launchctl",
args: ["list", "my.fancy.package.service"],
print_stderr: false,
sudo: true,
sudo_as_root: true,
)
.and_return(instance_double(SystemCommand::Result, stdout: unknown_response))
expect(fake_system_command).to receive(:run)
.with("/bin/launchctl", args: ["remove", "my.fancy.package.service"],
must_succeed: false, sudo: false, sudo_as_root: false)
.and_return(instance_double(SystemCommand::Result, success?: true))
subject.public_send(:"#{artifact_dsl_key}_phase", command: fake_system_command)
end
it "works when job is owned by system" do
allow(fake_system_command).to receive(:run)
.with(
"/bin/launchctl",
args: ["list", "my.fancy.package.service"],
print_stderr: false,
sudo: false,
sudo_as_root: false,
)
.and_return(instance_double(SystemCommand::Result, stdout: unknown_response))
allow(fake_system_command).to receive(:run)
.with(
"/bin/launchctl",
args: ["list", "my.fancy.package.service"],
print_stderr: false,
sudo: true,
sudo_as_root: true,
)
.and_return(instance_double(SystemCommand::Result, stdout: service_info))
expect(fake_system_command).to receive(:run)
.with("/bin/launchctl", args: ["remove", "my.fancy.package.service"],
must_succeed: false, sudo: true, sudo_as_root: true)
.and_return(instance_double(SystemCommand::Result, success?: true))
subject.public_send(:"#{artifact_dsl_key}_phase", command: fake_system_command)
end
it "does not fail when sudo removal fails" do
allow(fake_system_command).to receive(:run)
.with(
"/bin/launchctl",
args: ["list", "my.fancy.package.service"],
print_stderr: false,
sudo: false,
sudo_as_root: false,
)
.and_return(instance_double(SystemCommand::Result, stdout: unknown_response))
allow(fake_system_command).to receive(:run)
.with(
"/bin/launchctl",
args: ["list", "my.fancy.package.service"],
print_stderr: false,
sudo: true,
sudo_as_root: true,
)
.and_return(instance_double(SystemCommand::Result, stdout: service_info))
expect(fake_system_command).to receive(:run)
.with("/bin/launchctl", args: ["remove", "my.fancy.package.service"],
must_succeed: false, sudo: true, sudo_as_root: true)
.and_return(instance_double(SystemCommand::Result, success?: false))
expect do
subject.public_send(:"#{artifact_dsl_key}_phase", command: fake_system_command)
end.not_to raise_error
end
end
context "when using :launchctl with regex wildcard" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-#{artifact_dsl_key}-launchctl-wildcard")) }
let(:launchctl_regex) { "my.fancy.package.service.*" }
let(:unknown_response) { "launchctl list returned unknown response\n" }
let(:service_info) do
<<~EOS
{
"LimitLoadToSessionType" = "Aqua";
"Label" = "my.fancy.package.service.12345";
"TimeOut" = 30;
"OnDemand" = true;
"LastExitStatus" = 0;
"ProgramArguments" = (
"argument";
);
};
EOS
end
let(:launchctl_list) do
<<~EOS
PID Status Label
1111 0 my.fancy.package.service.12345
- 0 com.apple.SafariHistoryServiceAgent
- 0 com.apple.progressd
555 0 my.fancy.package.service.test
EOS
end
it "searches installed launchctl items" do
expect(subject).to receive(:find_launchctl_with_wildcard)
.with(launchctl_regex)
.and_return(["my.fancy.package.service.12345"])
allow(fake_system_command).to receive(:run)
.with(
"/bin/launchctl",
args: ["list", "my.fancy.package.service.12345"],
print_stderr: false,
sudo: false,
sudo_as_root: false,
)
.and_return(instance_double(SystemCommand::Result, stdout: unknown_response))
allow(fake_system_command).to receive(:run)
.with(
"/bin/launchctl",
args: ["list", "my.fancy.package.service.12345"],
print_stderr: false,
sudo: true,
sudo_as_root: true,
)
.and_return(instance_double(SystemCommand::Result, stdout: service_info))
expect(fake_system_command).to receive(:run)
.with("/bin/launchctl", args: ["remove", "my.fancy.package.service.12345"],
must_succeed: false, sudo: true, sudo_as_root: true)
.and_return(instance_double(SystemCommand::Result, success?: true))
subject.public_send(:"#{artifact_dsl_key}_phase", command: fake_system_command)
end
it "returns the matching launchctl services" do
expect(subject).to receive(:system_command!)
.with("/bin/launchctl", args: ["list"])
.and_return(instance_double(SystemCommand::Result, stdout: launchctl_list))
expect(subject.send(:find_launchctl_with_wildcard,
"my.fancy.package.service.*")).to eq(["my.fancy.package.service.12345",
"my.fancy.package.service.test"])
end
end
context "when using :pkgutil" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-#{artifact_dsl_key}-pkgutil")) }
let(:main_pkg_id) { "my.fancy.package.main" }
let(:agent_pkg_id) { "my.fancy.package.agent" }
it "is supported" do
main_pkg = Cask::Pkg.new(main_pkg_id, fake_system_command)
agent_pkg = Cask::Pkg.new(agent_pkg_id, fake_system_command)
expect(Cask::Pkg).to receive(:all_matching).and_return(
[
main_pkg,
agent_pkg,
],
)
expect(main_pkg).to receive(:uninstall)
expect(agent_pkg).to receive(:uninstall)
subject.public_send(:"#{artifact_dsl_key}_phase", command: fake_system_command)
end
end
context "when using :kext" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-#{artifact_dsl_key}-kext")) }
let(:kext_id) { "my.fancy.package.kernelextension" }
it "is supported" do
allow(subject).to receive(:system_command!)
.with("/usr/sbin/kextstat", args: ["-l", "-b", kext_id], sudo: true, sudo_as_root: true)
.and_return(instance_double(SystemCommand::Result, stdout: "loaded"))
expect(subject).to receive(:system_command!)
.with("/sbin/kextunload", args: ["-b", kext_id], sudo: true, sudo_as_root: true)
.and_return(instance_double(SystemCommand::Result))
expect(subject).to receive(:system_command!)
.with("/usr/sbin/kextfind", args: ["-b", kext_id], sudo: true, sudo_as_root: true)
.and_return(instance_double(SystemCommand::Result, stdout: "/Library/Extensions/FancyPackage.kext\n"))
expect(subject).to receive(:system_command!)
.with("/bin/rm", args: ["-rf", "/Library/Extensions/FancyPackage.kext"], sudo: true, sudo_as_root: true)
subject.public_send(:"#{artifact_dsl_key}_phase", command: fake_system_command)
end
end
context "when using :quit" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-#{artifact_dsl_key}-quit")) }
let(:bundle_id) { "my.fancy.package.app" }
it "is skipped when the user is not a GUI user" do
allow(User.current).to receive(:gui?).and_return false
allow(subject).to receive(:running?).with(bundle_id).and_return(true)
expect do
subject.public_send(:"#{artifact_dsl_key}_phase", command: fake_system_command)
end.to output(/Not logged into a GUI; skipping quitting application ID 'my.fancy.package.app'\./).to_stderr
end
it "quits a running application" do
allow(User.current).to receive(:gui?).and_return true
expect(subject).to receive(:running?).with(bundle_id).ordered.and_return(true)
expect(subject).to receive(:quit).with(bundle_id)
.and_return(instance_double(SystemCommand::Result, success?: true))
expect(subject).to receive(:running?).with(bundle_id).ordered.and_return(false)
expect do
subject.public_send(:"#{artifact_dsl_key}_phase", command: fake_system_command)
end.to output(/Application 'my.fancy.package.app' quit successfully\./).to_stdout
end
it "does not attempt to quit when upgrading or reinstalling" do
next if artifact_dsl_key == :zap
allow(User.current).to receive(:gui?).and_return true
expect(subject).not_to receive(:running?)
expect(subject).not_to receive(:quit)
subject.public_send(:"#{artifact_dsl_key}_phase", upgrade: true, command: fake_system_command)
subject.public_send(:"#{artifact_dsl_key}_phase", reinstall: true, command: fake_system_command)
end
it "tries to quit the application for 10 seconds" do
allow(User.current).to receive(:gui?).and_return true
allow(subject).to receive(:running?).with(bundle_id).and_return(true)
allow(subject).to receive(:quit).with(bundle_id)
.and_return(instance_double(SystemCommand::Result, success?: false))
time = Benchmark.measure do
expect do
subject.public_send(:"#{artifact_dsl_key}_phase", command: fake_system_command)
end.to output(/Application 'my.fancy.package.app' did not quit\./).to_stderr
end
expect(time.real).to be_within(3).of(10)
end
end
context "when using :signal" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-#{artifact_dsl_key}-signal")) }
let(:bundle_id) { "my.fancy.package.app" }
let(:signals) { %w[TERM KILL] }
let(:unix_pids) { [12_345, 67_890] }
it "is supported" do
allow(subject).to receive(:running_processes).with(bundle_id)
.and_return(unix_pids.map { |pid| [pid, 0, bundle_id] })
signals.each do |signal|
expect(Process).to receive(:kill).with(signal, *unix_pids).and_return(1)
end
subject.public_send(:"#{artifact_dsl_key}_phase", command: fake_system_command)
end
it "does not send signal when upgrading or reinstalling" do
next if artifact_dsl_key == :zap
allow(subject).to receive(:running_processes).with(bundle_id)
.and_return(unix_pids.map { |pid| [pid, 0, bundle_id] })
signals.each do |_signal|
expect(Process).not_to receive(:kill)
end
subject.public_send(:"#{artifact_dsl_key}_phase", upgrade: true, command: fake_system_command)
subject.public_send(:"#{artifact_dsl_key}_phase", reinstall: true, command: fake_system_command)
end
end
[:delete, :trash].each do |directive|
next if directive == :trash && ENV["HOMEBREW_TESTS_COVERAGE"].nil?
context "when using :#{directive}" do
let(:dir) { TEST_TMPDIR }
let(:absolute_path) { Pathname.new("#{dir}/absolute_path") }
let(:path_with_tilde) { Pathname.new("#{dir}/path_with_tilde") }
let(:glob_path) { Pathname.new("#{dir}/glob_path") }
let(:glob_path_alt) { Pathname.new("#{dir}/glob_path_alt") }
let(:paths) { [absolute_path, path_with_tilde, glob_path, glob_path_alt] }
let(:fake_system_command) { NeverSudoSystemCommand }
let(:cask) { Cask::CaskLoader.load(cask_path("with-#{artifact_dsl_key}-#{directive}")) }
around do |example|
ENV["HOME"] = dir
FileUtils.touch paths
example.run
ensure
FileUtils.rm_f paths
end
before do
allow_any_instance_of(Cask::Artifact::AbstractUninstall).to receive(:trash_paths)
.and_wrap_original do |method, *args, **kwargs|
method.call(*args, **kwargs).tap do |trashed, _|
FileUtils.rm_r trashed
end
end
end
it "is supported" do
expect(paths).to all(exist)
subject.public_send(:"#{artifact_dsl_key}_phase", command: fake_system_command)
paths.each do |path|
expect(path).not_to exist
end
end
end
end
[:script, :early_script].each do |script_type|
context "when using #{script_type.inspect}" do
let(:fake_system_command) { NeverSudoSystemCommand }
let(:token) { "with-#{artifact_dsl_key}-#{script_type}".tr("_", "-") }
let(:cask) { Cask::CaskLoader.load(cask_path(token.to_s)) }
let(:script_pathname) { cask.staged_path.join("MyFancyPkg", "FancyUninstaller.tool") }
it "is supported" do
allow(fake_system_command).to receive(:run).with(any_args).and_call_original
expect(fake_system_command).to receive(:run)
.with(
cask.staged_path.join("MyFancyPkg", "FancyUninstaller.tool"),
args: ["--please"],
must_succeed: true,
print_stdout: true,
sudo: false,
)
InstallHelper.install_without_artifacts(cask)
subject.public_send(:"#{artifact_dsl_key}_phase", command: fake_system_command)
end
end
end
context "when using :login_item" do
let(:cask) { Cask::CaskLoader.load(cask_path("with-#{artifact_dsl_key}-login-item")) }
it "is supported" do
expect(subject).to receive(:system_command)
.with(
"osascript",
args: ["-e", 'tell application "System Events" to delete every login item whose name is "Fancy"'],
)
.and_return(instance_double(SystemCommand::Result, success?: true))
subject.public_send(:"#{artifact_dsl_key}_phase", command: fake_system_command)
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/cask/cask_loader/from_content_loader_spec.rb | Library/Homebrew/test/cask/cask_loader/from_content_loader_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::CaskLoader::FromContentLoader do
describe "::try_new" do
it "returns a loader for Casks specified with `cask \"token\" do … end`" do
expect(described_class.try_new(<<~RUBY)).not_to be_nil
cask "token" do
end
RUBY
end
it "returns a loader for Casks specified with `cask \"token\" do; end`" do
expect(described_class.try_new(<<~RUBY)).not_to be_nil
cask "token" do; end
RUBY
end
it "returns a loader for Casks specified with `cask 'token' do … end`" do
expect(described_class.try_new(<<~RUBY)).not_to be_nil
cask 'token' do
end
RUBY
end
it "returns a loader for Casks specified with `cask 'token' do; end`" do
expect(described_class.try_new(<<~RUBY)).not_to be_nil
cask 'token' do; end
RUBY
end
it "returns a loader for Casks specified with `cask(\"token\") { … }`" do
expect(described_class.try_new(<<~RUBY)).not_to be_nil
cask("token") {
}
RUBY
end
it "returns a loader for Casks specified with `cask(\"token\") {}`" do
expect(described_class.try_new(<<~RUBY)).not_to be_nil
cask("token") {}
RUBY
end
it "returns a loader for Casks specified with `cask('token') { … }`" do
expect(described_class.try_new(<<~RUBY)).not_to be_nil
cask('token') {
}
RUBY
end
it "returns a loader for Casks specified with `cask('token') {}`" do
expect(described_class.try_new(<<~RUBY)).not_to be_nil
cask('token') {}
RUBY
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/cask/cask_loader/from_api_loader_spec.rb | Library/Homebrew/test/cask/cask_loader/from_api_loader_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::CaskLoader::FromAPILoader, :cask do
shared_context "with API setup" do |local_token|
let(:api_token) { "#{local_token}-api" }
let(:cask_from_source) { Cask::CaskLoader.load(local_token) }
let(:cask_json) do
hash = cask_from_source.to_hash_with_variations
# This value will always be present in the json API, but is skipped in tests
hash["tap_git_head"] = "abcdef1234567890abcdef1234567890abcdef12"
json = JSON.pretty_generate(hash)
JSON.parse(json)
end
let(:casks_from_api_hash) { { api_token => cask_json.except("token") } }
let(:api_loader) { described_class.new(api_token, from_json: cask_json) }
before do
allow(Homebrew::API::Cask)
.to receive_messages(all_casks: casks_from_api_hash, all_renames: {})
# The call to `Cask::CaskLoader.load` above sets the Tap cache prematurely.
Tap.clear_cache
end
end
describe ".try_new" do
include_context "with API setup", "test-opera"
context "when not using the API", :no_api do
it "returns false" do
expect(described_class.try_new(api_token)).to be_nil
end
end
context "when using the API" do
it "returns a loader for valid token" do
expect(described_class.try_new(api_token))
.to be_a(described_class)
.and have_attributes(token: api_token)
end
it "returns a loader for valid full name" do
expect(described_class.try_new("homebrew/cask/#{api_token}"))
.to be_a(described_class)
.and have_attributes(token: api_token)
end
it "returns nil for full name with invalid tap" do
expect(described_class.try_new("homebrew/foo/#{api_token}")).to be_nil
end
context "with core tap migration renames" do
let(:foo_tap) { Tap.fetch("homebrew", "foo") }
before do
foo_tap.path.mkpath
end
after do
FileUtils.rm_rf foo_tap.path
end
it "returns the tap migration rename by old token" do
old_token = "#{api_token}-old"
(foo_tap.path/"tap_migrations.json").write <<~JSON
{ "#{old_token}": "homebrew/cask/#{api_token}" }
JSON
loader = Cask::CaskLoader::FromNameLoader.try_new(old_token)
expect(loader).to be_a(described_class)
expect(loader.token).to eq api_token
expect(loader.path).not_to exist
end
it "returns the tap migration rename by old full name" do
old_token = "#{api_token}-old"
(foo_tap.path/"tap_migrations.json").write <<~JSON
{ "#{old_token}": "homebrew/cask/#{api_token}" }
JSON
loader = Cask::CaskLoader::FromTapLoader.try_new("#{foo_tap}/#{old_token}")
expect(loader).to be_a(described_class)
expect(loader.token).to eq api_token
expect(loader.path).not_to exist
end
end
end
end
describe "#load" do
shared_examples "loads from API" do |cask_token, caskfile_only:|
include_context "with API setup", cask_token
let(:cask_from_api) { api_loader.load(config: nil) }
it "loads from JSON API" do
expect(cask_from_api).to be_a(Cask::Cask)
expect(cask_from_api.token).to eq(api_token)
expect(cask_from_api.loaded_from_api?).to be(true)
expect(cask_from_api.caskfile_only?).to be(caskfile_only)
expect(cask_from_api.sourcefile_path).to eq(Homebrew::API::Cask.cached_json_file_path)
end
end
context "with a binary stanza" do
include_examples "loads from API", "with-binary", caskfile_only: false
end
context "with cask dependencies" do
include_examples "loads from API", "with-depends-on-cask-multiple", caskfile_only: false
end
context "with formula dependencies" do
include_examples "loads from API", "with-depends-on-formula-multiple", caskfile_only: false
end
context "with macos dependencies" do
include_examples "loads from API", "with-depends-on-macos-array", caskfile_only: false
end
context "with an installer stanza" do
include_examples "loads from API", "with-installer-script", caskfile_only: false
end
context "with uninstall stanzas" do
include_examples "loads from API", "with-uninstall-multi", caskfile_only: false
end
context "with a zap stanza" do
include_examples "loads from API", "with-zap", caskfile_only: false
end
context "with a preflight stanza" do
include_examples "loads from API", "with-preflight", caskfile_only: true
end
context "with an uninstall-preflight stanza" do
include_examples "loads from API", "with-uninstall-preflight", caskfile_only: true
end
context "with a postflight stanza" do
include_examples "loads from API", "with-postflight", caskfile_only: true
end
context "with an uninstall-postflight stanza" do
include_examples "loads from API", "with-uninstall-postflight", caskfile_only: true
end
context "with a language stanza" do
include_examples "loads from API", "with-languages", caskfile_only: 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/cask/cask_loader/from_tap_loader_spec.rb | Library/Homebrew/test/cask/cask_loader/from_tap_loader_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::CaskLoader::FromTapLoader do
let(:tap) { CoreCaskTap.instance }
let(:cask_name) { "testball" }
let(:cask_full_name) { "homebrew/cask/#{cask_name}" }
let(:cask_path) { tap.cask_dir/"#{cask_name}.rb" }
describe "#load" do
before do
cask_path.parent.mkpath
cask_path.write <<~RUBY
cask '#{cask_name}' do
url 'https://brew.sh/'
end
RUBY
end
it "returns a Cask" do
expect(described_class.new(cask_full_name).load(config: nil)).to be_a(Cask::Cask)
end
it "raises an error if the Cask cannot be found" do
expect { described_class.new("foo/bar/baz").load(config: nil) }.to raise_error(Cask::CaskUnavailableError)
end
context "with sharded Cask directory", :no_api do
let(:cask_path) { tap.cask_dir/cask_name[0]/"#{cask_name}.rb" }
it "returns a Cask" do
expect(described_class.new(cask_full_name).load(config: nil)).to be_a(Cask::Cask)
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/cask/cask_loader/from_path_loader_spec.rb | Library/Homebrew/test/cask/cask_loader/from_path_loader_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::CaskLoader::FromPathLoader do
describe "#load" do
context "when the file does not contain a cask" do
let(:path) do
(mktmpdir/"cask.rb").tap do |path|
path.write <<~RUBY
true
RUBY
end
end
it "raises an error" do
expect do
described_class.new(path).load(config: nil)
end.to raise_error(Cask::CaskUnreadableError, /does not contain a cask/)
end
end
context "when the file calls a non-existent method" do
let(:path) do
(mktmpdir/"cask.rb").tap do |path|
path.write <<~RUBY
this_method_does_not_exist
RUBY
end
end
it "raises an error" do
expect do
described_class.new(path).load(config: nil)
end.to raise_error(Cask::CaskUnreadableError, /undefined local variable or method/)
end
end
context "when the file contains an outdated cask" do
it "raises an error" do
expect do
described_class.new(cask_path("invalid/invalid-depends-on-macos-bad-release")).load(config: nil)
end.to raise_error(Cask::CaskInvalidError,
/invalid 'depends_on macos' value: unknown or unsupported macOS version:/)
end
end
context "with a JSON cask file" do
let(:sourcefile_path) { TEST_FIXTURE_DIR/"cask/everything.json" }
it "loads a cask with a source file path" do
cask = described_class.new(sourcefile_path).load(config: nil)
expect(cask.sourcefile_path).to eq sourcefile_path
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/cask/cask_loader/from_uri_loader_spec.rb | Library/Homebrew/test/cask/cask_loader/from_uri_loader_spec.rb | # frozen_string_literal: true
RSpec.describe Cask::CaskLoader::FromURILoader do
describe "::try_new" do
it "returns a loader when given an URI" do
expect(described_class.try_new(URI("https://brew.sh/"))).not_to be_nil
end
it "returns a loader when given a string which can be parsed to a URI" do
expect(described_class.try_new("https://brew.sh/")).not_to be_nil
end
it "returns nil when path loading is disabled" do
ENV["HOMEBREW_FORBID_PACKAGES_FROM_PATHS"] = "1"
expect(described_class.try_new(URI("file://#{TEST_FIXTURE_DIR}/cask/Casks/local-caffeine.rb"))).to be_nil
end
it "returns nil when given a string with Cask contents containing a URL" do
expect(described_class.try_new(<<~RUBY)).to be_nil
cask 'token' do
url 'https://brew.sh/'
end
RUBY
end
end
describe "::load" do
it "raises an error when given an https URL" do
loader = described_class.new("https://brew.sh/foo.rb")
expect do
loader.load(config: nil)
end.to raise_error(UnsupportedInstallationMethod)
end
it "raises an error when given an ftp URL" do
loader = described_class.new("ftp://brew.sh/foo.rb")
expect do
loader.load(config: nil)
end.to raise_error(UnsupportedInstallationMethod)
end
it "raises an error when given an sftp URL" do
loader = described_class.new("sftp://brew.sh/foo.rb")
expect do
loader.load(config: nil)
end.to raise_error(UnsupportedInstallationMethod)
end
it "does not raise an error when given a file URL", :needs_utils_curl do
loader = described_class.new("file://#{TEST_FIXTURE_DIR}/cask/Casks/local-caffeine.rb")
expect do
loader.load(config: nil)
end.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/utils/path_spec.rb | Library/Homebrew/test/utils/path_spec.rb | # frozen_string_literal: true
require "utils/path"
RSpec.describe Utils::Path do
describe "::child_of?" do
it "recognizes a path as its own child" do
expect(described_class.child_of?("/foo/bar", "/foo/bar")).to be(true)
end
it "recognizes a path that is a child of the parent" do
expect(described_class.child_of?("/foo", "/foo/bar")).to be(true)
end
it "recognizes a path that is a grandchild of the parent" do
expect(described_class.child_of?("/foo", "/foo/bar/baz")).to be(true)
end
it "does not recognize a path that is not a child" do
expect(described_class.child_of?("/foo", "/bar/baz")).to be(false)
end
it "handles . and .. in paths correctly" do
expect(described_class.child_of?("/foo", "/foo/./bar")).to be(true)
expect(described_class.child_of?("/foo/bar", "/foo/../foo/bar/baz")).to be(true)
end
it "handles relative paths correctly" do
expect(described_class.child_of?("foo", "./bar/baz")).to be(false)
expect(described_class.child_of?("../foo", "./bar/baz/../../../foo/bar/baz")).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/utils/shared_audits_spec.rb | Library/Homebrew/test/utils/shared_audits_spec.rb | # frozen_string_literal: true
require "utils/shared_audits"
require "utils/curl"
RSpec.describe SharedAudits do
let(:eol_json_text) do
<<~JSON
{
"schema_version" : "1.0.0",
"generated_at": "2025-01-02T01:23:45+00:00",
"result": {
"name": "1.2",
"codename": null,
"label": "1.2",
"releaseDate": "2024-01-01",
"isLts": false,
"ltsFrom": null,
"isEol": true,
"eolFrom": "2025-01-01",
"isMaintained": false,
"latest": {
"name": "1.0.0",
"date": "2024-01-01",
"link": "https://example.com/1.0.0"
}
}
}
JSON
end
def mock_curl_output(stdout: "", success: true)
status = instance_double(Process::Status, success?: success)
curl_output = instance_double(SystemCommand::Result, stdout:, status:)
allow(Utils::Curl).to receive(:curl_output).and_return curl_output
end
describe "::eol_data" do
it "returns a parsed JSON object if the product is found" do
mock_curl_output stdout: eol_json_text
expect(described_class.eol_data("product", "cycle")&.dig("result", "isEol")).to be(true)
expect(described_class.eol_data("product", "cycle")&.dig("result", "eolFrom")).to eq("2025-01-01")
end
it "returns nil if the product is not found" do
mock_curl_output stdout: "<html></html>"
expect(described_class.eol_data("none", "cycle")).to be_nil
end
it "returns nil if api call fails" do
mock_curl_output success: false
expect(described_class.eol_data("", "")).to be_nil
end
end
describe "::github_tag_from_url" do
it "finds tags in archive urls" do
url = "https://github.com/a/b/archive/refs/tags/v1.2.3.tar.gz"
expect(described_class.github_tag_from_url(url)).to eq("v1.2.3")
end
it "finds tags in release urls" do
url = "https://github.com/a/b/releases/download/1.2.3/b-1.2.3.tar.bz2"
expect(described_class.github_tag_from_url(url)).to eq("1.2.3")
end
it "finds tags with slashes" do
url = "https://github.com/a/b/archive/refs/tags/c/d/e/f/g-v1.2.3.tar.gz"
expect(described_class.github_tag_from_url(url)).to eq("c/d/e/f/g-v1.2.3")
end
it "finds tags in orgs/repos with special characters" do
url = "https://github.com/a-b/c-d_e.f/archive/refs/tags/2.5.tar.gz"
expect(described_class.github_tag_from_url(url)).to eq("2.5")
end
end
describe "::gitlab_tag_from_url" do
it "doesn't find tags in invalid urls" do
url = "https://gitlab.com/a/-/archive/v1.2.3/a-v1.2.3.tar.gz"
expect(described_class.gitlab_tag_from_url(url)).to be_nil
end
it "finds tags in basic urls" do
url = "https://gitlab.com/a/b/-/archive/v1.2.3/b-1.2.3.tar.gz"
expect(described_class.gitlab_tag_from_url(url)).to eq("v1.2.3")
end
it "finds tags in urls with subgroups" do
url = "https://gitlab.com/a/b/c/d/e/f/g/-/archive/2.5/g-2.5.tar.gz"
expect(described_class.gitlab_tag_from_url(url)).to eq("2.5")
end
it "finds tags in urls with special characters" do
url = "https://gitlab.com/a.b/c-d_e/-/archive/2.5/c-d_e-2.5.tar.gz"
expect(described_class.gitlab_tag_from_url(url)).to eq("2.5")
end
end
describe "::forgejo_tag_from_url" do
it "finds tags in basic urls" do
url = "https://codeberg.org/Aviac/codeberg-cli/archive/v0.4.11.tar.gz"
expect(described_class.forgejo_tag_from_url(url)).to eq("v0.4.11")
end
it "finds tags in urls with subgroups" do
url = "https://codeberg.org/Aviac/codeberg-cli/archive/some/test/1.2.3.tar.gz"
expect(described_class.forgejo_tag_from_url(url)).to eq("some/test/1.2.3")
end
it "finds tags in orgs/repos with special characters" do
url = "https://codeberg.org/Aviaca-b_cv/codeberg-cli/archive/v0.4.11.tar.gz"
expect(described_class.forgejo_tag_from_url(url)).to eq("v0.4.11")
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/utils/inreplace_spec.rb | Library/Homebrew/test/utils/inreplace_spec.rb | # frozen_string_literal: true
require "tempfile"
require "utils/inreplace"
RSpec.describe Utils::Inreplace do
let(:file) { Tempfile.new("test") }
before do
File.binwrite(file, <<~EOS)
a
b
c
aa
EOS
end
after { file.unlink }
describe ".inreplace" do
it "raises error if there are no files given to replace" do
expect do
described_class.inreplace [], "d", "f"
end.to raise_error(Utils::Inreplace::Error)
end
it "raises error if there is nothing to replace" do
expect do
described_class.inreplace file.path, "d", "f"
end.to raise_error(Utils::Inreplace::Error)
end
it "raises error if there is nothing to replace in block form" do
expect do
described_class.inreplace(file.path) do |s|
# Using `gsub!` here is what we want, and it's only a test.
s.gsub!("d", "f") # rubocop:disable Performance/StringReplacement
end
end.to raise_error(Utils::Inreplace::Error)
end
it "raises error if there is no make variables to replace" do
expect do
described_class.inreplace(file.path) do |s|
s.change_make_var! "VAR", "value"
s.remove_make_var! "VAR2"
end
end.to raise_error(Utils::Inreplace::Error)
end
it "substitutes pathname within file" do
# For a specific instance of this, see https://github.com/Homebrew/homebrew-core/blob/a8b0b10/Formula/loki.rb#L48
described_class.inreplace(file.path) do |s|
s.gsub!(Pathname("b"), Pathname("f"))
end
expect(File.binread(file)).to eq <<~EOS
a
f
c
aa
EOS
end
it "substitutes all occurrences within file when `global: true`" do
described_class.inreplace(file.path, "a", "foo")
expect(File.binread(file)).to eq <<~EOS
foo
b
c
foofoo
EOS
end
it "substitutes only the first occurrence when `global: false`" do
described_class.inreplace(file.path, "a", "foo", global: false)
expect(File.binread(file)).to eq <<~EOS
foo
b
c
aa
EOS
end
end
describe ".inreplace_pairs" do
it "raises error if there is no old value" do
expect do
described_class.inreplace_pairs(file.path, [[nil, "f"]])
end.to raise_error(TypeError)
end
it "substitutes returned string but not file when `read_only_run: true`" do
expect(described_class.inreplace_pairs(file.path, [["a", "foo"]], read_only_run: true)).to eq <<~EOS
foo
b
c
foofoo
EOS
expect(File.binread(file)).to eq <<~EOS
a
b
c
aa
EOS
end
it "substitutes both returned string and file when `read_only_run: false`" do
replace_result = <<~TEXT
foo
b
c
foofoo
TEXT
expect(described_class.inreplace_pairs(file.path, [["a", "foo"]])).to eq replace_result
expect(File.binread(file)).to eq replace_result
end
it "substitutes multiple pairs in order" do
pairs = [["a", "b"], ["bb", "test"], ["b", "z"]]
replace_result = <<~TEXT
z
z
c
test
TEXT
expect(described_class.inreplace_pairs(file.path, pairs)).to eq replace_result
expect(File.binread(file)).to eq replace_result
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/utils/output_spec.rb | Library/Homebrew/test/utils/output_spec.rb | # frozen_string_literal: true
require "utils/output"
RSpec.describe Utils::Output do
def esc(code)
/(\e\[\d+m)*\e\[#{code}m/
end
describe "#pretty_installed" do
subject(:pretty_installed_output) { described_class.pretty_installed("foo") }
context "when $stdout is a TTY" do
before { allow($stdout).to receive(:tty?).and_return(true) }
context "with HOMEBREW_NO_EMOJI unset" do
it "returns a string with a colored checkmark" do
expect(pretty_installed_output)
.to match(/#{esc 1}foo #{esc 32}✔#{esc 0}/)
end
end
context "with HOMEBREW_NO_EMOJI set" do
before { ENV["HOMEBREW_NO_EMOJI"] = "1" }
it "returns a string with colored info" do
expect(pretty_installed_output)
.to match(/#{esc 1}foo \(installed\)#{esc 0}/)
end
end
end
context "when $stdout is not a TTY" do
before { allow($stdout).to receive(:tty?).and_return(false) }
it "returns plain text" do
expect(pretty_installed_output).to eq("foo")
end
end
end
describe "#pretty_uninstalled" do
subject(:pretty_uninstalled_output) { described_class.pretty_uninstalled("foo") }
context "when $stdout is a TTY" do
before { allow($stdout).to receive(:tty?).and_return(true) }
context "with HOMEBREW_NO_EMOJI unset" do
it "returns a string with a colored checkmark" do
expect(pretty_uninstalled_output)
.to match(/#{esc 1}foo #{esc 31}✘#{esc 0}/)
end
end
context "with HOMEBREW_NO_EMOJI set" do
before { ENV["HOMEBREW_NO_EMOJI"] = "1" }
it "returns a string with colored info" do
expect(pretty_uninstalled_output)
.to match(/#{esc 1}foo \(uninstalled\)#{esc 0}/)
end
end
end
context "when $stdout is not a TTY" do
before { allow($stdout).to receive(:tty?).and_return(false) }
it "returns plain text" do
expect(pretty_uninstalled_output).to eq("foo")
end
end
end
describe "#pretty_duration" do
it "converts seconds to a human-readable string" do
expect(described_class.pretty_duration(1)).to eq("1 second")
expect(described_class.pretty_duration(2.5)).to eq("2 seconds")
expect(described_class.pretty_duration(42)).to eq("42 seconds")
expect(described_class.pretty_duration(240)).to eq("4 minutes")
expect(described_class.pretty_duration(252.45)).to eq("4 minutes 12 seconds")
end
end
describe "#ofail" do
it "sets Homebrew.failed to true" do
expect do
described_class.ofail "foo"
end.to output("Error: foo\n").to_stderr
expect(Homebrew).to have_failed
end
end
describe "#odie" do
it "exits with 1" do
expect do
described_class.odie "foo"
end.to output("Error: foo\n").to_stderr.and raise_error SystemExit
end
end
describe "#odeprecated" do
it "raises a MethodDeprecatedError when `disable` is true" do
ENV.delete("HOMEBREW_DEVELOPER")
expect do
described_class.odeprecated(
"method", "replacement",
caller: ["#{HOMEBREW_LIBRARY}/Taps/playbrew/homebrew-play/"],
disable: true
)
end.to raise_error(
MethodDeprecatedError,
%r{method.*replacement.*playbrew/homebrew-play.*/Taps/playbrew/homebrew-play/}m,
)
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/utils/linkage_spec.rb | Library/Homebrew/test/utils/linkage_spec.rb | # frozen_string_literal: true
require "utils/linkage"
RSpec.describe Utils do
[:needs_macos, :needs_linux].each do |needs_os|
describe "::binary_linked_to_library?", needs_os do
let(:suffix) { OS.mac? ? ".dylib" : ".so" }
before do
mktmpdir do |dir|
(dir/"foo.h").write "void foo();"
(dir/"foo.c").write <<~C
#include <stdio.h>
#include "foo.h"
void foo() { printf("foo\\\\n"); }
C
(dir/"bar.c").write <<~C
#include <stdio.h>
void bar() { printf("bar\\\\n"); }
C
(dir/"test.c").write <<~C
#include "foo.h"
int main() { foo(); return 0; }
C
system "cc", "-c", "-fpic", dir/"foo.c", "-o", dir/"foo.o"
system "cc", "-c", "-fpic", dir/"bar.c", "-o", dir/"bar.o"
dll_flag = OS.mac? ? "-dynamiclib" : "-shared"
(HOMEBREW_PREFIX/"lib").mkdir
system "cc", dll_flag, "-o", HOMEBREW_PREFIX/"lib/libbrewfoo#{suffix}", dir/"foo.o"
system "cc", dll_flag, "-o", HOMEBREW_PREFIX/"lib/libbrewbar#{suffix}", dir/"bar.o"
rpath_flag = "-Wl,-rpath,#{HOMEBREW_PREFIX}/lib" if OS.linux?
system "cc", "-o", dir/"brewtest", dir/"test.c", *rpath_flag, "-L#{HOMEBREW_PREFIX/"lib"}", "-lbrewfoo"
(HOMEBREW_PREFIX/"bin").install dir/"brewtest"
end
end
it "returns true if the binary is linked to the library" do
result = described_class.binary_linked_to_library?(HOMEBREW_PREFIX/"bin/brewtest",
HOMEBREW_PREFIX/"lib/libbrewfoo#{suffix}")
expect(result).to be true
end
it "returns false if the binary is not linked to the library" do
result = described_class.binary_linked_to_library?(HOMEBREW_PREFIX/"bin/brewtest",
HOMEBREW_PREFIX/"lib/libbrewbar#{suffix}")
expect(result).to be false
end
it "can check if the binary is linked to a non-brew library" do
non_brew_library = "/usr/lib/libtest#{suffix}"
shim = OS.mac? ? MachOShim : ELFShim
allow_any_instance_of(shim).to receive(:dynamically_linked_libraries).and_return([non_brew_library])
result = described_class.binary_linked_to_library?(HOMEBREW_PREFIX/"bin/brewtest", non_brew_library)
expect(result).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/utils/repology_spec.rb | Library/Homebrew/test/utils/repology_spec.rb | # typed: strict
# frozen_string_literal: true
require "utils/repology"
| 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/analytics_spec.rb | Library/Homebrew/test/utils/analytics_spec.rb | # frozen_string_literal: true
require "utils/analytics"
require "formula_installer"
RSpec.describe Utils::Analytics do
describe "::default_package_tags" do
let(:ci) { ", CI" if ENV["CI"] }
it "returns OS_VERSION and prefix when HOMEBREW_PREFIX is a custom prefix on intel" do
expect(Homebrew).to receive(:default_prefix?).and_return(false).at_least(:once)
expect(described_class.default_package_tags).to have_key(:prefix)
expect(described_class.default_package_tags[:prefix]).to eq "custom-prefix"
end
it "returns OS_VERSION, ARM and prefix when HOMEBREW_PREFIX is a custom prefix on arm" do
expect(Homebrew).to receive(:default_prefix?).and_return(false).at_least(:once)
expect(described_class.default_package_tags).to have_key(:arch)
expect(described_class.default_package_tags[:arch]).to eq HOMEBREW_PHYSICAL_PROCESSOR
expect(described_class.default_package_tags).to have_key(:prefix)
expect(described_class.default_package_tags[:prefix]).to eq "custom-prefix"
end
it "returns OS_VERSION, Rosetta and prefix when HOMEBREW_PREFIX is a custom prefix on Rosetta", :needs_macos do
expect(Homebrew).to receive(:default_prefix?).and_return(false).at_least(:once)
expect(described_class.default_package_tags).to have_key(:prefix)
expect(described_class.default_package_tags[:prefix]).to eq "custom-prefix"
end
it "does not include prefix when HOMEBREW_PREFIX is the default prefix" do
expect(Homebrew).to receive(:default_prefix?).and_return(true).at_least(:once)
expect(described_class.default_package_tags).to have_key(:prefix)
expect(described_class.default_package_tags[:prefix]).to eq HOMEBREW_PREFIX.to_s
end
it "includes CI when ENV['CI'] is set" do
ENV["CI"] = "1"
expect(described_class.default_package_tags).to have_key(:ci)
end
it "includes developer when ENV['HOMEBREW_DEVELOPER'] is set" do
expect(Homebrew::EnvConfig).to receive(:developer?).and_return(true)
expect(described_class.default_package_tags).to have_key(:developer)
end
end
describe "::report_package_event" do
let(:f) { formula { url "foo-1.0" } }
let(:package_name) { f.name }
let(:tap_name) { f.tap.name }
let(:on_request) { false }
let(:options) { "--HEAD" }
context "when ENV vars is set" do
it "returns nil when HOMEBREW_NO_ANALYTICS is true" do
ENV["HOMEBREW_NO_ANALYTICS"] = "true"
expect(described_class).not_to receive(:report_influx)
described_class.report_package_event(:install, package_name:, tap_name:,
on_request:, options:)
end
it "returns nil when HOMEBREW_NO_ANALYTICS_THIS_RUN is true" do
ENV["HOMEBREW_NO_ANALYTICS_THIS_RUN"] = "true"
expect(described_class).not_to receive(:report_influx)
described_class.report_package_event(:install, package_name:, tap_name:,
on_request:, options:)
end
it "returns nil when HOMEBREW_ANALYTICS_DEBUG is true" do
ENV.delete("HOMEBREW_NO_ANALYTICS_THIS_RUN")
ENV.delete("HOMEBREW_NO_ANALYTICS")
ENV["HOMEBREW_ANALYTICS_DEBUG"] = "true"
expect(described_class).to receive(:report_influx)
described_class.report_package_event(:install, package_name:, tap_name:,
on_request:, options:)
end
end
it "passes to the influxdb method" do
ENV.delete("HOMEBREW_NO_ANALYTICS_THIS_RUN")
ENV.delete("HOMEBREW_NO_ANALYTICS")
ENV["HOMEBREW_ANALYTICS_DEBUG"] = "true"
expect(described_class).to receive(:report_influx).with(:install, hash_including(on_request:),
hash_including(package: package_name)).once
described_class.report_package_event(:install, package_name:, tap_name:,
on_request:, options:)
end
end
describe "::report_influx" do
let(:f) { formula { url "foo-1.0" } }
let(:package) { f.name }
let(:tap_name) { f.tap.name }
let(:on_request) { false }
let(:options) { "--HEAD" }
it "outputs in debug mode" do
ENV.delete("HOMEBREW_NO_ANALYTICS_THIS_RUN")
ENV.delete("HOMEBREW_NO_ANALYTICS")
ENV["HOMEBREW_ANALYTICS_DEBUG"] = "true"
expect(described_class).to receive(:deferred_curl).once
described_class.report_influx(:install, { on_request: }, { package:, tap_name: })
end
end
describe "::report_build_error" do
context "when tap is installed" do
let(:err) { BuildError.new(f, "badprg", %w[arg1 arg2], {}) }
let(:f) { formula { url "foo-1.0" } }
it "reports event if BuildError raised for a formula with a public remote repository" do
allow_any_instance_of(Tap).to receive(:custom_remote?).and_return(false)
expect(described_class).to respond_to(:report_package_event)
described_class.report_build_error(err)
end
it "does not report event if BuildError raised for a formula with a private remote repository" do
allow_any_instance_of(Tap).to receive(:private?).and_return(true)
expect(described_class).not_to receive(:report_package_event)
described_class.report_build_error(err)
end
end
context "when formula does not have a tap" do
let(:err) { BuildError.new(f, "badprg", %w[arg1 arg2], {}) }
let(:f) { instance_double(Formula, name: "foo", path: "blah", tap: nil) }
it "does not report event if BuildError is raised" do
expect(described_class).not_to receive(:report_package_event)
described_class.report_build_error(err)
end
end
context "when tap for a formula is not installed" do
let(:err) { BuildError.new(f, "badprg", %w[arg1 arg2], {}) }
let(:f) { instance_double(Formula, name: "foo", path: "blah", tap: CoreTap.instance) }
it "does not report event if BuildError is raised" do
allow_any_instance_of(Pathname).to receive(:directory?).and_return(false)
expect(described_class).not_to receive(:report_package_event)
described_class.report_build_error(err)
end
end
end
describe "::report_command_run" do
let(:command) { "audit" }
let(:options) { "--tap=" }
let(:command_instance) do
require "dev-cmd/audit"
Homebrew::DevCmd::Audit.new(["--tap=homebrew/core"])
end
it "passes to the influxdb method" do
ENV.delete("HOMEBREW_NO_ANALYTICS_THIS_RUN")
ENV.delete("HOMEBREW_NO_ANALYTICS")
ENV["HOMEBREW_ANALYTICS_DEBUG"] = "true"
expect(described_class).to receive(:report_influx).with(
:command_run,
hash_including(command:),
hash_including(options:),
).once
described_class.report_command_run(command_instance)
end
end
describe "::report_test_bot_test" do
let(:command) { "install wget" }
let(:passed) { true }
it "passes to the influxdb method" do
ENV.delete("HOMEBREW_NO_ANALYTICS_THIS_RUN")
ENV.delete("HOMEBREW_NO_ANALYTICS")
ENV["HOMEBREW_ANALYTICS_DEBUG"] = "true"
ENV["HOMEBREW_TEST_BOT_ANALYTICS"] = "true"
expect(described_class).to receive(:report_influx).with(
:test_bot_test,
hash_including(passed:),
hash_including(command:),
).once
described_class.report_test_bot_test(command, passed)
end
end
specify "::table_output" do
results = { "ack" => 10, "wget" => 100 }
expect { described_class.table_output("install", "30", results) }
.to output(/110 | 100.00%/).to_stdout
.and not_to_output.to_stderr
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/utils/autoremove_spec.rb | Library/Homebrew/test/utils/autoremove_spec.rb | # frozen_string_literal: true
require "utils/autoremove"
RSpec.describe Utils::Autoremove do
shared_context "with formulae for dependency testing" do
let(:formula_with_deps) do
formula "zero" do
url "zero-1.0"
depends_on "three" => :build
end
end
let(:first_formula_dep) do
formula "one" do
url "one-1.1"
end
end
let(:second_formula_dep) do
formula "two" do
url "two-1.1"
end
end
let(:formula_is_build_dep) do
formula "three" do
url "three-1.1"
end
end
let(:formulae) do
[
formula_with_deps,
first_formula_dep,
second_formula_dep,
formula_is_build_dep,
]
end
let(:tab_from_keg) { instance_double(Tab) }
before do
allow(formula_with_deps).to receive_messages(
installed_runtime_formula_dependencies: [first_formula_dep, second_formula_dep],
any_installed_keg: instance_double(Keg, tab: tab_from_keg),
)
allow(first_formula_dep).to receive_messages(
installed_runtime_formula_dependencies: [second_formula_dep],
any_installed_keg: instance_double(Keg, tab: tab_from_keg),
)
allow(second_formula_dep).to receive_messages(
installed_runtime_formula_dependencies: [],
any_installed_keg: instance_double(Keg, tab: tab_from_keg),
)
allow(formula_is_build_dep).to receive_messages(
installed_runtime_formula_dependencies: [],
any_installed_keg: instance_double(Keg, tab: tab_from_keg),
)
end
end
describe "::bottled_formulae_with_no_formula_dependents" do
include_context "with formulae for dependency testing"
before do
allow(Formulary).to receive(:factory).with("three", { warn: false })
.and_return(formula_is_build_dep)
end
context "when formulae are bottles" do
it "filters out runtime dependencies" do
allow(tab_from_keg).to receive(:poured_from_bottle).and_return(true)
expect(described_class.send(:bottled_formulae_with_no_formula_dependents, formulae))
.to eq([formula_with_deps, formula_is_build_dep])
end
end
context "when formulae are built from source" do
it "filters out formulae" do
allow(tab_from_keg).to receive(:poured_from_bottle).and_return(false)
expect(described_class.send(:bottled_formulae_with_no_formula_dependents, formulae))
.to eq([])
end
end
end
describe "::unused_formulae_with_no_formula_dependents" do
include_context "with formulae for dependency testing"
before do
allow(tab_from_keg).to receive(:poured_from_bottle).and_return(true)
end
specify "installed on request" do
allow(tab_from_keg).to receive_messages(installed_on_request: true, installed_on_request_present?: true)
expect(described_class.send(:unused_formulae_with_no_formula_dependents, formulae))
.to eq([])
end
specify "not installed on request" do
allow(tab_from_keg).to receive_messages(installed_on_request: false, installed_on_request_present?: true)
expect(described_class.send(:unused_formulae_with_no_formula_dependents, formulae))
.to match_array(formulae)
end
specify "installed on request is null" do
allow(tab_from_keg).to receive_messages(installed_on_request: false, installed_on_request_present?: false)
expect(described_class.send(:unused_formulae_with_no_formula_dependents, formulae))
.to eq([])
end
end
shared_context "with formulae and casks for dependency testing" do
include_context "with formulae for dependency testing"
require "cask/cask_loader"
let(:cask_one_dep) do
Cask::CaskLoader.load(+<<-RUBY)
cask "red" do
depends_on formula: "two"
end
RUBY
end
let(:cask_multiple_deps) do
Cask::CaskLoader.load(+<<-RUBY)
cask "blue" do
depends_on formula: "zero"
end
RUBY
end
let(:first_cask_no_deps) do
Cask::CaskLoader.load(+<<-RUBY)
cask "green" do
end
RUBY
end
let(:second_cask_no_deps) do
Cask::CaskLoader.load(+<<-RUBY)
cask "purple" do
end
RUBY
end
let(:casks_no_deps) { [first_cask_no_deps, second_cask_no_deps] }
let(:casks_one_dep) { [first_cask_no_deps, second_cask_no_deps, cask_one_dep] }
let(:casks_multiple_deps) { [first_cask_no_deps, second_cask_no_deps, cask_multiple_deps] }
before do
allow(Formulary).to receive(:resolve).with("zero").and_return(formula_with_deps)
allow(Formulary).to receive(:resolve).with("one").and_return(first_formula_dep)
allow(Formulary).to receive(:resolve).with("two").and_return(second_formula_dep)
end
end
describe "::formulae_with_cask_dependents" do
include_context "with formulae and casks for dependency testing"
specify "no dependents" do
expect(described_class.send(:formulae_with_cask_dependents, casks_no_deps))
.to eq([])
end
specify "one dependent" do
expect(described_class.send(:formulae_with_cask_dependents, casks_one_dep))
.to eq([second_formula_dep])
end
specify "multiple dependents" do
expect(described_class.send(:formulae_with_cask_dependents, casks_multiple_deps))
.to contain_exactly(formula_with_deps, first_formula_dep, second_formula_dep)
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/utils/pypi_spec.rb | Library/Homebrew/test/utils/pypi_spec.rb | # frozen_string_literal: true
require "utils/pypi"
RSpec.describe PyPI do
let(:pypi_package_url) do
"https://files.pythonhosted.org/packages/b0/3f/2e1dad67eb172b6443b5eb37eb885a054a55cfd733393071499514140282/" \
"snakemake-5.29.0.tar.gz"
end
let(:old_pypi_package_url) do
"https://files.pythonhosted.org/packages/6f/c4/da52bfdd6168ea46a0fe2b7c983b6c34c377a8733ec177cc00b197a96a9f/" \
"snakemake-5.28.0.tar.gz"
end
let(:non_pypi_package_url) do
"https://github.com/pypa/pip-audit/releases/download/v2.5.6/v2.5.6.tar.gz"
end
describe PyPI::Package do
let(:package_checksum) { "47417307d08ecb0707b3b29effc933bd63d8c8e3ab15509c62b685b7614c6568" }
let(:old_package_checksum) { "2367ce91baf7f8fa7738d33aff9670ffdf5410bbac49aeb209f73b45a3425046" }
let(:package) { described_class.new("snakemake") }
let(:package_with_version) { described_class.new("snakemake==5.28.0") }
let(:package_with_different_version) { described_class.new("snakemake==5.29.0") }
let(:package_with_extra) { described_class.new("snakemake[foo]") }
let(:package_with_extra_and_version) { described_class.new("snakemake[foo]==5.28.0") }
let(:package_with_different_capitalization) { described_class.new("SNAKEMAKE") }
let(:package_from_pypi_url) { described_class.new(pypi_package_url, is_url: true) }
let(:package_from_non_pypi_url) { described_class.new(non_pypi_package_url, is_url: true) }
let(:other_package) { described_class.new("virtualenv==20.2.0") }
describe "initialize" do
it "initializes name" do
expect(described_class.new("foo").name).to eq "foo"
end
it "initializes name with extra" do # rubocop:todo RSpec/AggregateExamples
expect(described_class.new("foo[bar]").name).to eq "foo"
end
it "initializes extra" do # rubocop:todo RSpec/AggregateExamples
expect(described_class.new("foo[bar]").extras).to eq ["bar"]
end
it "initializes multiple extras" do # rubocop:todo RSpec/AggregateExamples
expect(described_class.new("foo[bar,baz]").extras).to eq ["bar", "baz"]
end
it "initializes name with version" do # rubocop:todo RSpec/AggregateExamples
expect(described_class.new("foo==1.2.3").name).to eq "foo"
end
it "initializes version" do # rubocop:todo RSpec/AggregateExamples
expect(described_class.new("foo==1.2.3").version).to eq "1.2.3"
end
it "initializes extra with version" do # rubocop:todo RSpec/AggregateExamples
expect(described_class.new("foo[bar]==1.2.3").extras).to eq ["bar"]
end
it "initializes multiple extras with version" do # rubocop:todo RSpec/AggregateExamples
expect(described_class.new("foo[bar,baz]==1.2.3").extras).to eq ["bar", "baz"]
end
it "initializes version with extra" do # rubocop:todo RSpec/AggregateExamples
expect(described_class.new("foo[bar]==1.2.3").version).to eq "1.2.3"
end
it "initializes version with multiple extras" do # rubocop:todo RSpec/AggregateExamples
expect(described_class.new("foo[bar,baz]==1.2.3").version).to eq "1.2.3"
end
it "initializes name from PyPI url" do # rubocop:todo RSpec/AggregateExamples
expect(described_class.new(pypi_package_url, is_url: true).name).to eq "snakemake"
end
it "initializes version from PyPI url" do # rubocop:todo RSpec/AggregateExamples
expect(described_class.new(pypi_package_url, is_url: true).version).to eq "5.29.0"
end
end
describe ".version=" do
it "sets for package names" do
package = described_class.new("snakemake==5.28.0")
expect(package.version).to eq "5.28.0"
package.version = "5.29.0"
expect(package.version).to eq "5.29.0"
end
it "sets for PyPI package URLs" do
package = described_class.new(old_pypi_package_url, is_url: true)
expect(package.version).to eq "5.28.0"
package.version = "5.29.0"
expect(package.version).to eq "5.29.0"
end
it "fails for non-PYPI package URLs" do
package = described_class.new(non_pypi_package_url, is_url: true)
expect { package.version = "1.2.3" }.to raise_error(ArgumentError)
end
end
describe ".valid_pypi_package?" do
it "is true for package names" do
expect(package.valid_pypi_package?).to be true
end
it "is true for PyPI URLs" do # rubocop:todo RSpec/AggregateExamples
expect(package_from_pypi_url.valid_pypi_package?).to be true
end
it "is false for non-PyPI URLs" do # rubocop:todo RSpec/AggregateExamples
expect(package_from_non_pypi_url.valid_pypi_package?).to be false
end
end
describe ".pypi_info", :needs_network do
it "gets pypi info from a package name" do
expect(package.pypi_info.first).to eq "snakemake"
end
it "gets pypi info from a package name and specified version" do
expect(package.pypi_info(new_version: "5.29.0")).to eq ["snakemake", pypi_package_url, package_checksum,
"5.29.0"]
end
it "gets pypi info from a package name with extra" do # rubocop:todo RSpec/AggregateExamples
expect(package_with_extra.pypi_info.first).to eq "snakemake"
end
it "gets pypi info from a package name and version" do # rubocop:todo RSpec/AggregateExamples
expect(package_with_version.pypi_info).to eq ["snakemake", old_pypi_package_url, old_package_checksum,
"5.28.0"]
end
it "gets pypi info from a package name with overridden version" do
expected_result = ["snakemake", pypi_package_url, package_checksum, "5.29.0"]
expect(package_with_version.pypi_info(new_version: "5.29.0")).to eq expected_result
end
it "gets pypi info from a package name, extras and version" do
expected_result = ["snakemake", old_pypi_package_url, old_package_checksum, "5.28.0"]
expect(package_with_extra_and_version.pypi_info).to eq expected_result
end
it "gets pypi info from a url" do # rubocop:todo RSpec/AggregateExamples
expect(package_from_pypi_url.pypi_info).to eq ["snakemake", pypi_package_url, package_checksum, "5.29.0"]
end
it "gets pypi info from a url with overridden version" do
expected_result = ["snakemake", old_pypi_package_url, old_package_checksum, "5.28.0"]
expect(package_from_pypi_url.pypi_info(new_version: "5.28.0")).to eq expected_result
end
end
describe ".to_s" do
it "returns string representation of package name" do
expect(package.to_s).to eq "snakemake"
end
it "returns string representation of package with version" do # rubocop:todo RSpec/AggregateExamples
expect(package_with_version.to_s).to eq "snakemake==5.28.0"
end
it "returns string representation of package with extra" do # rubocop:todo RSpec/AggregateExamples
expect(package_with_extra.to_s).to eq "snakemake[foo]"
end
it "returns string representation of package with extra and version" do # rubocop:todo RSpec/AggregateExamples
expect(package_with_extra_and_version.to_s).to eq "snakemake[foo]==5.28.0"
end
it "returns string representation of package from url" do # rubocop:todo RSpec/AggregateExamples
expect(package_from_pypi_url.to_s).to eq "snakemake==5.29.0"
end
end
describe ".same_package?" do
it "returns false for different packages" do
expect(package.same_package?(other_package)).to be false
end
it "returns true for the same package" do
expect(package.same_package?(package_with_version)).to be true
end
it "returns true for the same package with different versions" do
expect(package_with_version.same_package?(package_with_different_version)).to be true
end
it "returns true for the same package with different capitalization" do
expect(package.same_package?(package_with_different_capitalization)).to be true
end
end
describe "<=>" do
it "returns -1" do
expect(package <=> other_package).to eq(-1)
end
it "returns 0" do
expect(package <=> package_with_version).to eq 0
end
it "returns 1" do
expect(other_package <=> package_with_extra_and_version).to eq 1
end
end
end
describe "update_pypi_url", :needs_network do
it "updates url to new version" do
expect(described_class.update_pypi_url(old_pypi_package_url, "5.29.0")).to eq pypi_package_url
end
it "returns nil for invalid versions" do
expect(described_class.update_pypi_url(old_pypi_package_url, "0.0.0")).to be_nil
end
it "returns nil for non-pypi urls" do
expect(described_class.update_pypi_url(non_pypi_package_url, "1.1")).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/utils/ruby_check_version_script_spec.rb | Library/Homebrew/test/utils/ruby_check_version_script_spec.rb | # frozen_string_literal: true
RSpec.describe Utils do
describe "ruby_check_version_script" do
subject do
homebrew_env = ENV.select { |key, _| key.start_with?("HOMEBREW_") }
Bundler.with_unbundled_env do
ENV.delete_if { |key,| key.start_with?("HOMEBREW_") }
ENV.update(homebrew_env)
# We intentionally don't use the shebang in this script as portable Ruby
# is usually not in PATH. This aligns with how we run the script in brew.
quiet_system RUBY_PATH, "#{HOMEBREW_LIBRARY_PATH}/utils/ruby_check_version_script.rb", required_ruby_version
end
end
before do
ENV.delete("HOMEBREW_DEVELOPER")
ENV.delete("HOMEBREW_USE_RUBY_FROM_PATH")
end
describe "succeeds on the running Ruby version" do
let(:required_ruby_version) { RUBY_VERSION }
it { is_expected.to be true }
end
describe "succeeds on newer mismatched major/minor required Ruby version and configured environment" do
let(:required_ruby_version) { "2.0.0" }
before do
ENV["HOMEBREW_DEVELOPER"] = "1"
ENV["HOMEBREW_USE_RUBY_FROM_PATH"] = "1"
end
it { is_expected.to be true }
end
describe "fails on on mismatched major/minor required Ruby version" do
let(:required_ruby_version) { "1.2.3" }
it { is_expected.to be false }
end
describe "fails on invalid required Ruby version" do
let(:required_ruby_version) { "fish" }
it { is_expected.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/utils/git_spec.rb | Library/Homebrew/test/utils/git_spec.rb | # frozen_string_literal: true
require "utils/git"
RSpec.describe Utils::Git do
around do |example|
described_class.clear_available_cache
example.run
ensure
described_class.clear_available_cache
end
before do
git = HOMEBREW_SHIMS_PATH/"shared/git"
HOMEBREW_CACHE.cd do
system git, "init"
File.write("README.md", "README")
system git, "add", HOMEBREW_CACHE/"README.md"
system git, "commit", "-m", "File added"
@h1 = `git rev-parse HEAD`
File.write("README.md", "# README")
system git, "add", HOMEBREW_CACHE/"README.md"
system git, "commit", "-m", "written to File"
@h2 = `git rev-parse HEAD`
File.write("LICENSE.txt", "LICENCE")
system git, "add", HOMEBREW_CACHE/"LICENSE.txt"
system git, "commit", "-m", "File added"
@h3 = `git rev-parse HEAD`
File.write("LICENSE.txt", "LICENSE")
system git, "add", HOMEBREW_CACHE/"LICENSE.txt"
system git, "commit", "-m", "written to File"
File.write("LICENSE.txt", "test")
system git, "add", HOMEBREW_CACHE/"LICENSE.txt"
system git, "commit", "-m", "written to File"
@cherry_pick_commit = `git rev-parse HEAD`
system git, "reset", "--hard", "HEAD^"
end
end
let(:file) { "README.md" }
# Allow instance variables here for a simpler `before do` block.
# rubocop:disable RSpec/InstanceVariable
let(:file_hash_one) { @h1[0..6] }
let(:file_hash_two) { @h2[0..6] }
let(:files) { ["README.md", "LICENSE.txt"] }
let(:files_hash_one) { [@h3[0..6], ["LICENSE.txt"]] }
let(:files_hash_two) { [@h2[0..6], ["README.md"]] }
let(:cherry_pick_commit) { @cherry_pick_commit[0..6] }
# rubocop:enable RSpec/InstanceVariable
describe "#cherry_pick!" do
it "can cherry pick a commit" do
expect(described_class.cherry_pick!(HOMEBREW_CACHE, cherry_pick_commit)).to be_truthy
end
it "aborts when cherry picking an existing hash" do
ENV["GIT_MERGE_VERBOSITY"] = "5" # Consistent output across git versions
expect do
described_class.cherry_pick!(HOMEBREW_CACHE, file_hash_one)
end.to raise_error(ErrorDuringExecution, /Merge conflict in README.md/)
end
end
describe "#last_revision_commit_of_file" do
it "gives last revision commit when before_commit is nil" do
expect(
described_class.last_revision_commit_of_file(HOMEBREW_CACHE, file),
).to eq(file_hash_one)
end
it "gives revision commit based on before_commit when it is not nil" do
expect(
described_class.last_revision_commit_of_file(HOMEBREW_CACHE,
file,
before_commit: file_hash_two),
).to eq(file_hash_two)
end
end
describe "#file_at_commit" do
it "returns file contents when file exists" do
expect(described_class.file_at_commit(HOMEBREW_CACHE, file, file_hash_one)).to eq("README")
end
it "returns empty when file doesn't exist" do
expect(described_class.file_at_commit(HOMEBREW_CACHE, "foo.txt", file_hash_one)).to eq("")
expect(described_class.file_at_commit(HOMEBREW_CACHE, "LICENSE.txt", file_hash_one)).to eq("")
end
end
describe "#last_revision_commit_of_files" do
context "when before_commit is nil" do
it "gives last revision commit" do
expect(
described_class.last_revision_commit_of_files(HOMEBREW_CACHE, files),
).to eq(files_hash_one)
end
end
context "when before_commit is not nil" do
it "gives last revision commit" do
expect(
described_class.last_revision_commit_of_files(HOMEBREW_CACHE,
files,
before_commit: file_hash_two),
).to eq(files_hash_two)
end
end
end
describe "#last_revision_of_file" do
it "returns last revision of file" do
expect(
described_class.last_revision_of_file(HOMEBREW_CACHE,
HOMEBREW_CACHE/file),
).to eq("README")
end
it "returns last revision of file based on before_commit" do
expect(
described_class.last_revision_of_file(HOMEBREW_CACHE, HOMEBREW_CACHE/file,
before_commit: "0..3"),
).to eq("# README")
end
end
describe "::available?" do
it "returns true if git --version command succeeds" do
expect(described_class).to be_available
end
it "returns false if git --version command does not succeed" do
stub_const("HOMEBREW_SHIMS_PATH", HOMEBREW_PREFIX/"bin/shim")
expect(described_class).not_to be_available
end
end
describe "::path" do
it "returns nil when git is not available" do
stub_const("HOMEBREW_SHIMS_PATH", HOMEBREW_PREFIX/"bin/shim")
expect(described_class.path).to be_nil
end
it "returns path of git when git is available" do
expect(described_class.path).to end_with("git")
end
end
describe "::version" do
it "returns null when git is not available" do
stub_const("HOMEBREW_SHIMS_PATH", HOMEBREW_PREFIX/"bin/shim")
expect(described_class.version).to be Version::NULL
end
it "returns version of git when git is available" do
expect(described_class.version).to be > Version::NULL
end
end
describe "::ensure_installed!" do
it "doesn't fail if git already available" do
expect { described_class.ensure_installed! }.not_to raise_error
end
context "when git is not already available" do
before do
stub_const("HOMEBREW_SHIMS_PATH", HOMEBREW_PREFIX/"bin/shim")
end
it "can't install brewed git if homebrew/core is unavailable" do
allow_any_instance_of(Pathname).to receive(:directory?).and_return(false)
expect { described_class.ensure_installed! }.to raise_error("Git is unavailable")
end
it "raises error if can't install git" do
stub_const("HOMEBREW_BREW_FILE", HOMEBREW_PREFIX/"bin/brew")
expect { described_class.ensure_installed! }.to raise_error("Git is unavailable")
end
unless ENV["HOMEBREW_TEST_GENERIC_OS"]
it "installs git" do
expect(described_class).to receive(:available?).and_return(false)
allow(CoreTap.instance).to receive(:installed?).and_return(true)
formula_double = instance_double(Formula)
allow(Formula).to receive(:[]).with("git").and_return(formula_double)
allow(formula_double).to receive(:ensure_installed!).and_return(formula_double)
expect(described_class).to receive(:available?).and_return(true)
described_class.ensure_installed!
end
end
end
end
describe "::remote_exists?" do
it "returns true when git is not available" do
stub_const("HOMEBREW_SHIMS_PATH", HOMEBREW_PREFIX/"bin/shim")
expect(described_class).to be_remote_exists("blah")
end
context "when git is available" do
it "returns true when git remote exists", :needs_network do
git = HOMEBREW_SHIMS_PATH/"shared/git"
url = "https://github.com/Homebrew/homebrew.github.io"
repo = HOMEBREW_CACHE/"hey"
repo.mkpath
repo.cd do
system git, "init"
system git, "remote", "add", "origin", url
end
expect(described_class).to be_remote_exists(url)
end
it "returns false when git remote does not exist" do
expect(described_class).not_to be_remote_exists("blah")
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/utils/backtrace_spec.rb | Library/Homebrew/test/utils/backtrace_spec.rb | # frozen_string_literal: true
require "utils/backtrace"
RSpec.describe Utils::Backtrace do
let(:backtrace_no_sorbet_paths) do
[
"/Library/Homebrew/downloadable.rb:75:in",
"/Library/Homebrew/downloadable.rb:50:in",
"/Library/Homebrew/cmd/fetch.rb:236:in",
"/Library/Homebrew/cmd/fetch.rb:201:in",
"/Library/Homebrew/cmd/fetch.rb:178:in",
"/Library/Homebrew/simulate_system.rb:29:in",
"/Library/Homebrew/cmd/fetch.rb:166:in",
"/Library/Homebrew/cmd/fetch.rb:163:in",
"/Library/Homebrew/cmd/fetch.rb:163:in",
"/Library/Homebrew/cmd/fetch.rb:94:in",
"/Library/Homebrew/cmd/fetch.rb:94:in",
"/Library/Homebrew/brew.rb:94:in",
]
end
let(:backtrace_with_sorbet_paths) do
[
"/Library/Homebrew/downloadable.rb:75:in",
"/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/sorbet-runtime-0.5.10461/lib/call_validation.rb:157:in",
"/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/sorbet-runtime-0.5.10461/lib/call_validation.rb:157:in",
"/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/sorbet-runtime-0.5.10461/lib/_methods.rb:270:in",
"/Library/Homebrew/downloadable.rb:50:in",
"/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/sorbet-runtime-0.5.10461/lib/call_validation.rb:157:in",
"/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/sorbet-runtime-0.5.10461/lib/call_validation.rb:157:in",
"/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/sorbet-runtime-0.5.10461/lib/_methods.rb:270:in",
"/Library/Homebrew/cmd/fetch.rb:236:in",
"/Library/Homebrew/cmd/fetch.rb:201:in",
"/Library/Homebrew/cmd/fetch.rb:178:in",
"/Library/Homebrew/simulate_system.rb:29:in",
"/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/sorbet-runtime-0.5.10461/lib/call_validation.rb:157:in",
"/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/sorbet-runtime-0.5.10461/lib/call_validation.rb:157:in",
"/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/sorbet-runtime-0.5.10461/lib/_methods.rb:270:in",
"/Library/Homebrew/cmd/fetch.rb:166:in",
"/Library/Homebrew/cmd/fetch.rb:163:in",
"/Library/Homebrew/cmd/fetch.rb:163:in",
"/Library/Homebrew/cmd/fetch.rb:94:in",
"/Library/Homebrew/cmd/fetch.rb:94:in",
"/Library/Homebrew/brew.rb:94:in",
]
end
let(:backtrace_with_sorbet_error) do
backtrace_with_sorbet_paths.drop(1)
end
def exception_with(backtrace:)
exception = StandardError.new
exception.set_backtrace(backtrace) if backtrace
exception
end
before do
allow(described_class).to receive(:sorbet_runtime_path)
.and_return("/Library/Homebrew/vendor/bundle/ruby/2.6.0/gems/sorbet-runtime")
allow(Context).to receive(:current).and_return(Context::ContextStruct.new(verbose: false))
end
it "handles nil backtrace" do
exception = exception_with backtrace: nil
expect(described_class.clean(exception)).to be_nil
end
it "handles empty array backtrace" do
exception = exception_with backtrace: []
expect(described_class.clean(exception)).to eq []
end
it "removes sorbet paths when top error is not from sorbet" do
exception = exception_with backtrace: backtrace_with_sorbet_paths
expect(described_class.clean(exception)).to eq backtrace_no_sorbet_paths
end
it "includes sorbet paths when top error is not from sorbet and verbose is set" do
allow(Context).to receive(:current).and_return(Context::ContextStruct.new(verbose: true))
exception = exception_with backtrace: backtrace_with_sorbet_paths
expect(described_class.clean(exception)).to eq backtrace_with_sorbet_paths
end
it "doesn't change backtrace when error is from sorbet" do
exception = exception_with backtrace: backtrace_with_sorbet_error
expect(described_class.clean(exception)).to eq backtrace_with_sorbet_error
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/utils/git_repository_spec.rb | Library/Homebrew/test/utils/git_repository_spec.rb | # frozen_string_literal: true
require "utils/git_repository"
RSpec.describe Utils do
shared_examples "git_repository helper function" do |method_name|
context "when directory is not a Git repository" do
it "returns nil if `safe` parameter is `false`" do
expect(described_class.public_send(method_name, TEST_TMPDIR, safe: false)).to be_nil
end
it "raises an error if `safe` parameter is `true`" do
expect { described_class.public_send(method_name, TEST_TMPDIR, safe: true) }
.to raise_error("Not a Git repository: #{TEST_TMPDIR}")
end
end
context "when Git is unavailable" do
before do
allow(Utils::Git).to receive(:available?).and_return(false)
end
it "returns nil if `safe` parameter is `false`" do
expect(described_class.public_send(method_name, HOMEBREW_CACHE, safe: false)).to be_nil
end
it "raises an error if `safe` parameter is `true`" do
expect { described_class.public_send(method_name, HOMEBREW_CACHE, safe: true) }
.to raise_error("Git is unavailable")
end
end
end
before do
HOMEBREW_CACHE.cd do
system "git", "init"
Pathname("README.md").write("README")
system "git", "add", "README.md"
system "git", "commit", "-m", commit_message
system "git", "checkout", "-b", branch_name
end
end
let(:commit_message) { "File added" }
let(:branch_name) { "test-branch" }
let(:head_revision) { HOMEBREW_CACHE.cd { `git rev-parse HEAD`.chomp } }
let(:short_head_revision) { HOMEBREW_CACHE.cd { `git rev-parse --short HEAD`.chomp } }
describe "::git_head" do
it "returns the revision at HEAD" do
expect(described_class.git_head(HOMEBREW_CACHE)).to eq(head_revision)
expect(described_class.git_head(HOMEBREW_CACHE, length: 5)).to eq(head_revision[0...5])
HOMEBREW_CACHE.cd do
expect(described_class.git_head).to eq(head_revision)
expect(described_class.git_head(length: 5)).to eq(head_revision[0...5])
end
end
include_examples "git_repository helper function", :git_head
end
describe "::git_short_head" do
it "returns the short revision at HEAD" do
expect(described_class.git_short_head(HOMEBREW_CACHE)).to eq(short_head_revision)
expect(described_class.git_short_head(HOMEBREW_CACHE, length: 5)).to eq(head_revision[0...5])
HOMEBREW_CACHE.cd do
expect(described_class.git_short_head).to eq(short_head_revision)
expect(described_class.git_short_head(length: 5)).to eq(head_revision[0...5])
end
end
include_examples "git_repository helper function", :git_short_head
end
describe "::git_branch" do
include_examples "git_repository helper function", :git_branch
it "returns the current Git branch" do
expect(described_class.git_branch(HOMEBREW_CACHE)).to eq(branch_name)
HOMEBREW_CACHE.cd do
expect(described_class.git_branch).to eq(branch_name)
end
end
end
describe "::git_commit_message" do
include_examples "git_repository helper function", :git_commit_message
it "returns the commit message of HEAD" do
expect(described_class.git_commit_message(HOMEBREW_CACHE)).to eq(commit_message)
expect(described_class.git_commit_message(HOMEBREW_CACHE, commit: head_revision)).to eq(commit_message)
HOMEBREW_CACHE.cd do
expect(described_class.git_commit_message).to eq(commit_message)
expect(described_class.git_commit_message(commit: head_revision)).to eq(commit_message)
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/utils/curl_spec.rb | Library/Homebrew/test/utils/curl_spec.rb | # frozen_string_literal: true
require "utils/curl"
RSpec.describe "Utils::Curl" do
include Utils::Curl
let(:details) do
details = {
normal: {},
cloudflare: {},
incapsula: {},
}
details[:normal][:no_cookie] = {
url: "https://www.example.com/",
final_url: nil,
status_code: "403",
headers: {
"age" => "123456",
"cache-control" => "max-age=604800",
"content-type" => "text/html; charset=UTF-8",
"date" => "Wed, 1 Jan 2020 01:23:45 GMT",
"etag" => "\"3147526947+ident\"",
"expires" => "Wed, 31 Jan 2020 01:23:45 GMT",
"last-modified" => "Wed, 1 Jan 2020 00:00:00 GMT",
"server" => "ECS (dcb/7EA2)",
"vary" => "Accept-Encoding",
"x-cache" => "HIT",
"content-length" => "3",
},
etag: "3147526947+ident",
content_length: "3",
file: "...",
file_hash: nil,
}
details[:normal][:ok] = details[:normal][:no_cookie].deep_dup
details[:normal][:ok][:status_code] = "200"
details[:normal][:single_cookie] = details[:normal][:no_cookie].deep_dup
details[:normal][:single_cookie][:headers]["set-cookie"] = "a_cookie=for_testing"
details[:normal][:multiple_cookies] = details[:normal][:no_cookie].deep_dup
details[:normal][:multiple_cookies][:headers]["set-cookie"] = [
"first_cookie=for_testing",
"last_cookie=also_for_testing",
]
details[:normal][:blank_headers] = details[:normal][:no_cookie].deep_dup
details[:normal][:blank_headers][:headers] = {}
details[:cloudflare][:single_cookie] = {
url: "https://www.example.com/",
final_url: nil,
status_code: "403",
headers: {
"date" => "Wed, 1 Jan 2020 01:23:45 GMT",
"content-type" => "text/plain; charset=UTF-8",
"content-length" => "16",
"x-frame-options" => "SAMEORIGIN",
"referrer-policy" => "same-origin",
"cache-control" => "private, max-age=0, no-store, no-cache, must-revalidate, post-check=0, pre-check=0",
"expires" => "Thu, 01 Jan 1970 00:00:01 GMT",
"expect-ct" => "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\"",
"set-cookie" => "__cf_bm=0123456789abcdef; path=/; expires=Wed, 31-Jan-20 01:23:45 GMT; " \
"domain=www.example.com; HttpOnly; Secure; SameSite=None",
"server" => "cloudflare",
"cf-ray" => "0123456789abcdef-IAD",
"alt-svc" => "h3=\":443\"; ma=86400, h3-29=\":443\"; ma=86400",
},
etag: nil,
content_length: "16",
file: "error code: 1020",
file_hash: nil,
}
details[:cloudflare][:multiple_cookies] = details[:cloudflare][:single_cookie].deep_dup
details[:cloudflare][:multiple_cookies][:headers]["set-cookie"] = [
"first_cookie=for_testing",
"__cf_bm=abcdef0123456789; path=/; expires=Thu, 28-Apr-22 18:38:40 GMT; domain=www.example.com; HttpOnly; " \
"Secure; SameSite=None",
"last_cookie=also_for_testing",
]
details[:cloudflare][:no_server] = details[:cloudflare][:single_cookie].deep_dup
details[:cloudflare][:no_server][:headers].delete("server")
details[:cloudflare][:wrong_server] = details[:cloudflare][:single_cookie].deep_dup
details[:cloudflare][:wrong_server][:headers]["server"] = "nginx 1.2.3"
# TODO: Make the Incapsula test data more realistic once we can find an
# example website to reference.
details[:incapsula][:single_cookie_visid_incap] = details[:normal][:no_cookie].deep_dup
details[:incapsula][:single_cookie_visid_incap][:headers]["set-cookie"] = "visid_incap_something=something"
details[:incapsula][:single_cookie_incap_ses] = details[:normal][:no_cookie].deep_dup
details[:incapsula][:single_cookie_incap_ses][:headers]["set-cookie"] = "incap_ses_something=something"
details[:incapsula][:multiple_cookies_visid_incap] = details[:normal][:no_cookie].deep_dup
details[:incapsula][:multiple_cookies_visid_incap][:headers]["set-cookie"] = [
"first_cookie=for_testing",
"visid_incap_something=something",
"last_cookie=also_for_testing",
]
details[:incapsula][:multiple_cookies_incap_ses] = details[:normal][:no_cookie].deep_dup
details[:incapsula][:multiple_cookies_incap_ses][:headers]["set-cookie"] = [
"first_cookie=for_testing",
"incap_ses_something=something",
"last_cookie=also_for_testing",
]
details
end
let(:location_urls) do
%w[
https://example.com/example/
https://example.com/example1/
https://example.com/example2/
]
end
let(:response_hash) do
response_hash = {}
response_hash[:ok] = {
status_code: "200",
status_text: "OK",
headers: {
"cache-control" => "max-age=604800",
"content-type" => "text/html; charset=UTF-8",
"date" => "Wed, 1 Jan 2020 01:23:45 GMT",
"expires" => "Wed, 31 Jan 2020 01:23:45 GMT",
"last-modified" => "Thu, 1 Jan 2019 01:23:45 GMT",
"content-length" => "123",
},
}
response_hash[:ok_no_status_text] = response_hash[:ok].deep_dup
response_hash[:ok_no_status_text].delete(:status_text)
response_hash[:ok_blank_header_value] = response_hash[:ok].deep_dup
response_hash[:ok_blank_header_value][:headers]["range"] = ""
response_hash[:redirection] = {
status_code: "301",
status_text: "Moved Permanently",
headers: {
"cache-control" => "max-age=604800",
"content-type" => "text/html; charset=UTF-8",
"date" => "Wed, 1 Jan 2020 01:23:45 GMT",
"expires" => "Wed, 31 Jan 2020 01:23:45 GMT",
"last-modified" => "Thu, 1 Jan 2019 01:23:45 GMT",
"content-length" => "123",
"location" => location_urls[0],
},
}
response_hash[:redirection1] = {
status_code: "301",
status_text: "Moved Permanently",
headers: {
"cache-control" => "max-age=604800",
"content-type" => "text/html; charset=UTF-8",
"date" => "Wed, 1 Jan 2020 01:23:45 GMT",
"expires" => "Wed, 31 Jan 2020 01:23:45 GMT",
"last-modified" => "Thu, 1 Jan 2019 01:23:45 GMT",
"content-length" => "123",
"location" => location_urls[1],
},
}
response_hash[:redirection2] = {
status_code: "301",
status_text: "Moved Permanently",
headers: {
"cache-control" => "max-age=604800",
"content-type" => "text/html; charset=UTF-8",
"date" => "Wed, 1 Jan 2020 01:23:45 GMT",
"expires" => "Wed, 31 Jan 2020 01:23:45 GMT",
"last-modified" => "Thu, 1 Jan 2019 01:23:45 GMT",
"content-length" => "123",
"location" => location_urls[2],
},
}
response_hash[:redirection_no_scheme] = {
status_code: "301",
status_text: "Moved Permanently",
headers: {
"cache-control" => "max-age=604800",
"content-type" => "text/html; charset=UTF-8",
"date" => "Wed, 1 Jan 2020 01:23:45 GMT",
"expires" => "Wed, 31 Jan 2020 01:23:45 GMT",
"last-modified" => "Thu, 1 Jan 2019 01:23:45 GMT",
"content-length" => "123",
"location" => "//www.example.com/example/",
},
}
response_hash[:redirection_root_relative] = {
status_code: "301",
status_text: "Moved Permanently",
headers: {
"cache-control" => "max-age=604800",
"content-type" => "text/html; charset=UTF-8",
"date" => "Wed, 1 Jan 2020 01:23:45 GMT",
"expires" => "Wed, 31 Jan 2020 01:23:45 GMT",
"last-modified" => "Thu, 1 Jan 2019 01:23:45 GMT",
"content-length" => "123",
"location" => "/example/",
},
}
response_hash[:redirection_parent_relative] = {
status_code: "301",
status_text: "Moved Permanently",
headers: {
"cache-control" => "max-age=604800",
"content-type" => "text/html; charset=UTF-8",
"date" => "Wed, 1 Jan 2020 01:23:45 GMT",
"expires" => "Wed, 31 Jan 2020 01:23:45 GMT",
"last-modified" => "Thu, 1 Jan 2019 01:23:45 GMT",
"content-length" => "123",
"location" => "./example/",
},
}
response_hash[:duplicate_header] = {
status_code: "200",
status_text: "OK",
headers: {
"cache-control" => "max-age=604800",
"content-type" => "text/html; charset=UTF-8",
"date" => "Wed, 1 Jan 2020 01:23:45 GMT",
"expires" => "Wed, 31 Jan 2020 01:23:45 GMT",
"last-modified" => "Thu, 1 Jan 2019 01:23:45 GMT",
"content-length" => "123",
"set-cookie" => [
"example1=first",
"example2=second; Expires Wed, 31 Jan 2020 01:23:45 GMT",
"example3=third",
],
},
}
response_hash
end
let(:response_text) do
response_text = {}
response_text[:ok] = <<~EOS
HTTP/1.1 #{response_hash[:ok][:status_code]} #{response_hash[:ok][:status_text]}\r
Cache-Control: #{response_hash[:ok][:headers]["cache-control"]}\r
Content-Type: #{response_hash[:ok][:headers]["content-type"]}\r
Date: #{response_hash[:ok][:headers]["date"]}\r
Expires: #{response_hash[:ok][:headers]["expires"]}\r
Last-Modified: #{response_hash[:ok][:headers]["last-modified"]}\r
Content-Length: #{response_hash[:ok][:headers]["content-length"]}\r
\r
EOS
response_text[:ok_no_status_text] = response_text[:ok].sub(" #{response_hash[:ok][:status_text]}", "")
response_text[:ok_blank_header_name] = response_text[:ok].sub(
"#{response_hash[:ok][:headers]["date"]}\r\n",
"#{response_hash[:ok][:headers]["date"]}\r\n: Test\r\n",
)
response_text[:ok_blank_header_value] = response_text[:ok].sub(
"#{response_hash[:ok][:headers]["date"]}\r\n",
"#{response_hash[:ok][:headers]["date"]}\r\nRange:\r\n",
)
response_text[:redirection] = response_text[:ok].sub(
"HTTP/1.1 #{response_hash[:ok][:status_code]} #{response_hash[:ok][:status_text]}\r",
"HTTP/1.1 #{response_hash[:redirection][:status_code]} #{response_hash[:redirection][:status_text]}\r\n" \
"Location: #{response_hash[:redirection][:headers]["location"]}\r",
)
response_text[:redirection_to_ok] = "#{response_text[:redirection]}#{response_text[:ok]}"
response_text[:redirections_to_ok] = <<~EOS
#{response_text[:redirection].sub(location_urls[0], location_urls[2])}
#{response_text[:redirection].sub(location_urls[0], location_urls[1])}
#{response_text[:redirection]}
#{response_text[:ok]}
EOS
response_text[:duplicate_header] = response_text[:ok].sub(
/\r\n\Z/,
"Set-Cookie: #{response_hash[:duplicate_header][:headers]["set-cookie"][0]}\r\n" \
"Set-Cookie: #{response_hash[:duplicate_header][:headers]["set-cookie"][1]}\r\n" \
"Set-Cookie: #{response_hash[:duplicate_header][:headers]["set-cookie"][2]}\r\n\r\n",
)
response_text
end
let(:body) do
body = {}
body[:default] = <<~EOS
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<h1>Example</h1>
<p>Hello, world!</p>
</body>
</html>
EOS
body[:with_carriage_returns] = body[:default].sub("<html>\n", "<html>\r\n\r\n")
body[:with_http_status_line] = body[:default].sub("<html>", "HTTP/1.1 200\r\n<html>")
body
end
describe "::curl_executable" do
it "returns HOMEBREW_BREWED_CURL_PATH when `use_homebrew_curl` is `true`" do
expect(curl_executable(use_homebrew_curl: true)).to eq(HOMEBREW_BREWED_CURL_PATH)
end
it "returns curl shim path when `use_homebrew_curl` is `false` or omitted" do
curl_shim_path = HOMEBREW_SHIMS_PATH/"shared/curl"
expect(curl_executable(use_homebrew_curl: false)).to eq(curl_shim_path)
expect(curl_executable).to eq(curl_shim_path)
end
end
describe "::curl_path" do
it "returns a curl path string" do
expect(curl_path).to match(%r{[^/]+(?:/[^/]+)*})
end
end
describe "::curl_args" do
include Context
let(:args) { ["foo"] }
let(:user_agent_string) { "Lorem ipsum dolor sit amet" }
it "returns `--disable` as the first argument when HOMEBREW_CURLRC is not set" do
# --disable must be the first argument according to "man curl"
expect(curl_args(*args).first).to eq("--disable")
end
it "doesn't return `--disable` as the first argument when HOMEBREW_CURLRC is set but not a path" do
ENV["HOMEBREW_CURLRC"] = "1"
expect(curl_args(*args).first).not_to eq("--disable")
end
it "doesn't return `--config` when HOMEBREW_CURLRC is unset" do
expect(curl_args(*args)).not_to include(a_string_starting_with("--config"))
end
it "returns `--config` when HOMEBREW_CURLRC is a valid path" do
Tempfile.create do |tmpfile|
path = tmpfile.path
ENV["HOMEBREW_CURLRC"] = path
# We still expect --disable
expect(curl_args(*args).first).to eq("--disable")
expect(curl_args(*args).join(" ")).to include("--config #{path}")
end
ensure
ENV["HOMEBREW_CURLRC"] = nil
end
it "uses `--connect-timeout` when `:connect_timeout` is Numeric" do
expect(curl_args(*args, connect_timeout: 123).join(" ")).to include("--connect-timeout 123")
expect(curl_args(*args, connect_timeout: 123.4).join(" ")).to include("--connect-timeout 123.4")
expect(curl_args(*args, connect_timeout: 123.4567).join(" ")).to include("--connect-timeout 123.457")
end
it "errors when `:connect_timeout` is not Numeric" do
expect { curl_args(*args, connect_timeout: "test") }.to raise_error(TypeError)
end
it "uses `--max-time` when `:max_time` is Numeric" do
expect(curl_args(*args, max_time: 123).join(" ")).to include("--max-time 123")
expect(curl_args(*args, max_time: 123.4).join(" ")).to include("--max-time 123.4")
expect(curl_args(*args, max_time: 123.4567).join(" ")).to include("--max-time 123.457")
end
it "errors when `:max_time` is not Numeric" do
expect { curl_args(*args, max_time: "test") }.to raise_error(TypeError)
end
it "uses `--retry 3` when HOMEBREW_CURL_RETRIES is unset" do
expect(curl_args(*args).join(" ")).to include("--retry 3")
end
it "uses the given value for `--retry` when HOMEBREW_CURL_RETRIES is set" do
ENV["HOMEBREW_CURL_RETRIES"] = "10"
expect(curl_args(*args).join(" ")).to include("--retry 10")
end
it "uses `--retry` when `:retries` is a positive Integer" do
expect(curl_args(*args, retries: 5).join(" ")).to include("--retry 5")
end
it "doesn't use `--retry` when `:retries` is nil or a non-positive Integer" do
expect(curl_args(*args, retries: nil).join(" ")).not_to include("--retry")
expect(curl_args(*args, retries: 0).join(" ")).not_to include("--retry")
expect(curl_args(*args, retries: -1).join(" ")).not_to include("--retry")
end
it "errors when `:retries` is not Numeric" do
expect { curl_args(*args, retries: "test") }.to raise_error(TypeError)
end
it "uses `--retry-max-time` when `:retry_max_time` is Numeric" do
expect(curl_args(*args, retry_max_time: 123).join(" ")).to include("--retry-max-time 123")
expect(curl_args(*args, retry_max_time: 123.4).join(" ")).to include("--retry-max-time 123")
end
it "errors when `:retry_max_time` is not Numeric" do
expect { curl_args(*args, retry_max_time: "test") }.to raise_error(TypeError)
end
it "uses `--show-error` when :show_error is `true`" do
expect(curl_args(*args, show_error: true)).to include("--show-error")
expect(curl_args(*args, show_error: false)).not_to include("--show-error")
end
it "uses `--cookie` with argument when :cookies is present" do
cookies = { "cookie_key" => "cookie_value" }
expect(curl_args(*args, cookies:).join(" "))
.not_to include("--cookie #{File::NULL}")
expect(curl_args(*args, cookies:).join(" "))
.to include("--cookie cookie_key=cookie_value")
end
it "uses `--header` with argument when :header is present" do
expect(curl_args(*args, header: "Accept: */*").join(" "))
.to include("--header Accept: */*")
expect(curl_args(*args, header: ["Accept: */*", "X-Requested-With: XMLHttpRequest"]).join(" "))
.to include("--header Accept: */* --header X-Requested-With: XMLHttpRequest")
end
it "uses `--referer` when :referer is present" do
expect(curl_args(*args, referer: "https://brew.sh").join(" ")).to include("--referer https://brew.sh")
end
it "doesn't use `--referer` when :referer is nil" do
expect(curl_args(*args, referer: nil).join(" ")).not_to include("--referer")
end
it "omits `--user-agent` when `:user_agent` is `:curl`" do
expect(curl_args(*args, user_agent: :curl).join(" ")).not_to include("--user-agent")
end
it "uses HOMEBREW_USER_AGENT_FAKE_SAFARI when `:user_agent` is `:browser` or `:fake`" do
expect(curl_args(*args, user_agent: :browser).join(" "))
.to include("--user-agent #{HOMEBREW_USER_AGENT_FAKE_SAFARI}")
expect(curl_args(*args, user_agent: :fake).join(" "))
.to include("--user-agent #{HOMEBREW_USER_AGENT_FAKE_SAFARI}")
end
it "uses HOMEBREW_USER_AGENT_CURL when `:user_agent` is `:default` or omitted" do
expect(curl_args(*args, user_agent: :default).join(" ")).to include("--user-agent #{HOMEBREW_USER_AGENT_CURL}")
expect(curl_args(*args, user_agent: nil).join(" ")).to include("--user-agent #{HOMEBREW_USER_AGENT_CURL}")
expect(curl_args(*args).join(" ")).to include("--user-agent #{HOMEBREW_USER_AGENT_CURL}")
end
it "uses provided user agent string when `:user_agent` is a `String`" do
expect(curl_args(*args, user_agent: user_agent_string).join(" "))
.to include("--user-agent #{user_agent_string}")
end
it "errors when `:user_agent` is not a String or supported Symbol" do
expect { curl_args(*args, user_agent: :an_unsupported_symbol) }
.to raise_error(TypeError, ":user_agent must be :browser/:fake, :default, :curl, or a String")
expect { curl_args(*args, user_agent: 123) }.to raise_error(TypeError)
end
it "uses `--fail` unless `:show_output` is `true`" do
expect(curl_args(*args, show_output: false).join(" ")).to include("--fail")
expect(curl_args(*args, show_output: nil).join(" ")).to include("--fail")
expect(curl_args(*args).join(" ")).to include("--fail")
expect(curl_args(*args, show_output: true).join(" ")).not_to include("--fail")
end
it "uses `--progress-bar` outside of a `--verbose` context" do
expect(curl_args(*args).join(" ")).to include("--progress-bar")
with_context verbose: true do
expect(curl_args(*args).join(" ")).not_to include("--progress-bar")
end
end
context "when `EnvConfig.curl_verbose?` is `true`" do
before do
allow(Homebrew::EnvConfig).to receive(:curl_verbose?).and_return(true)
end
it "uses `--verbose`" do
expect(curl_args(*args).join(" ")).to include("--verbose")
end
end
context "when `EnvConfig.curl_verbose?` is `false`" do
before do
allow(Homebrew::EnvConfig).to receive(:curl_verbose?).and_return(false)
end
it "doesn't use `--verbose`" do
expect(curl_args(*args).join(" ")).not_to include("--verbose")
end
end
context "when `$stdout.tty?` is `false`" do
before do
allow($stdout).to receive(:tty?).and_return(false)
end
it "uses `--silent`" do
expect(curl_args(*args).join(" ")).to include("--silent")
end
end
context "when `$stdout.tty?` is `true`" do
before do
allow($stdout).to receive(:tty?).and_return(true)
end
it "doesn't use `--silent` outside of a `--quiet` context" do
with_context quiet: false do
expect(curl_args(*args).join(" ")).not_to include("--silent")
end
with_context quiet: true do
expect(curl_args(*args).join(" ")).to include("--silent")
end
end
end
end
describe "::url_protected_by_cloudflare?" do
it "returns `true` when a URL is protected by Cloudflare" do
expect(url_protected_by_cloudflare?(details[:cloudflare][:single_cookie])).to be(true)
expect(url_protected_by_cloudflare?(details[:cloudflare][:multiple_cookies])).to be(true)
end
it "returns `false` when a URL is not protected by Cloudflare" do
expect(url_protected_by_cloudflare?(details[:cloudflare][:no_server])).to be(false)
expect(url_protected_by_cloudflare?(details[:cloudflare][:wrong_server])).to be(false)
expect(url_protected_by_cloudflare?(details[:normal][:no_cookie])).to be(false)
expect(url_protected_by_cloudflare?(details[:normal][:ok])).to be(false)
expect(url_protected_by_cloudflare?(details[:normal][:single_cookie])).to be(false)
expect(url_protected_by_cloudflare?(details[:normal][:multiple_cookies])).to be(false)
end
it "returns `false` when response headers are blank" do
expect(url_protected_by_cloudflare?(details[:normal][:blank_headers])).to be(false)
end
end
describe "::url_protected_by_incapsula?" do
it "returns `true` when a URL is protected by Cloudflare" do
expect(url_protected_by_incapsula?(details[:incapsula][:single_cookie_visid_incap])).to be(true)
expect(url_protected_by_incapsula?(details[:incapsula][:single_cookie_incap_ses])).to be(true)
expect(url_protected_by_incapsula?(details[:incapsula][:multiple_cookies_visid_incap])).to be(true)
expect(url_protected_by_incapsula?(details[:incapsula][:multiple_cookies_incap_ses])).to be(true)
end
it "returns `false` when a URL is not protected by Incapsula" do
expect(url_protected_by_incapsula?(details[:normal][:no_cookie])).to be(false)
expect(url_protected_by_incapsula?(details[:normal][:ok])).to be(false)
expect(url_protected_by_incapsula?(details[:normal][:single_cookie])).to be(false)
expect(url_protected_by_incapsula?(details[:normal][:multiple_cookies])).to be(false)
end
it "returns `false` when response headers are blank" do
expect(url_protected_by_incapsula?(details[:normal][:blank_headers])).to be(false)
end
end
describe "::curl_version" do
it "returns a curl version string" do
expect(curl_version).to match(/^v?(\d+(?:\.\d+)+)$/)
end
end
describe "::curl_supports_fail_with_body?" do
it "returns `true` if curl version is 7.76.0 or higher" do
allow_any_instance_of(Utils::Curl).to receive(:curl_version).and_return(Version.new("7.76.0"))
expect(curl_supports_fail_with_body?).to be(true)
allow_any_instance_of(Utils::Curl).to receive(:curl_version).and_return(Version.new("7.76.1"))
expect(curl_supports_fail_with_body?).to be(true)
end
it "returns `false` if curl version is lower than 7.76.0" do
allow_any_instance_of(Utils::Curl).to receive(:curl_version).and_return(Version.new("7.75.0"))
expect(curl_supports_fail_with_body?).to be(false)
end
end
describe "::curl_supports_tls13?" do
it "returns `true` if curl command is successful" do
allow_any_instance_of(Kernel).to receive(:quiet_system).and_return(true)
expect(curl_supports_tls13?).to be(true)
end
it "returns `false` if curl command is not successful" do
allow_any_instance_of(Kernel).to receive(:quiet_system).and_return(false)
expect(curl_supports_tls13?).to be(false)
end
end
describe "::http_status_ok?" do
it "returns `true` when `status` is 1xx or 2xx" do
expect(http_status_ok?("200")).to be(true)
end
it "returns `false` when `status` is not 1xx or 2xx" do
expect(http_status_ok?("301")).to be(false)
end
it "returns `false` when `status` is `nil`" do
expect(http_status_ok?(nil)).to be(false)
end
end
describe "::parse_curl_output" do
it "returns a correct hash when curl output contains response(s) and body" do
expect(parse_curl_output("#{response_text[:ok]}#{body[:default]}"))
.to eq({ responses: [response_hash[:ok]], body: body[:default] })
expect(parse_curl_output("#{response_text[:ok]}#{body[:with_carriage_returns]}"))
.to eq({ responses: [response_hash[:ok]], body: body[:with_carriage_returns] })
expect(parse_curl_output("#{response_text[:ok]}#{body[:with_http_status_line]}"))
.to eq({ responses: [response_hash[:ok]], body: body[:with_http_status_line] })
expect(parse_curl_output("#{response_text[:redirection_to_ok]}#{body[:default]}"))
.to eq({ responses: [response_hash[:redirection], response_hash[:ok]], body: body[:default] })
expect(parse_curl_output("#{response_text[:redirections_to_ok]}#{body[:default]}"))
.to eq({
responses: [
response_hash[:redirection2],
response_hash[:redirection1],
response_hash[:redirection],
response_hash[:ok],
],
body: body[:default],
})
end
it "returns a correct hash when curl output contains HTTP response text and no body" do
expect(parse_curl_output(response_text[:ok])).to eq({ responses: [response_hash[:ok]], body: "" })
end
it "returns a correct hash when curl output contains body and no HTTP response text" do
expect(parse_curl_output(body[:default])).to eq({ responses: [], body: body[:default] })
expect(parse_curl_output(body[:with_carriage_returns]))
.to eq({ responses: [], body: body[:with_carriage_returns] })
expect(parse_curl_output(body[:with_http_status_line]))
.to eq({ responses: [], body: body[:with_http_status_line] })
end
it "returns correct hash when curl output is blank" do
expect(parse_curl_output("")).to eq({ responses: [], body: "" })
end
it "errors if response count exceeds `max_iterations`" do
expect do
parse_curl_output(response_text[:redirections_to_ok], max_iterations: 1)
end.to raise_error("Too many redirects (max = 1)")
end
end
describe "::parse_curl_response" do
it "returns a correct hash when given HTTP response text" do
expect(parse_curl_response(response_text[:ok])).to eq(response_hash[:ok])
expect(parse_curl_response(response_text[:ok_no_status_text])).to eq(response_hash[:ok_no_status_text])
expect(parse_curl_response(response_text[:ok_blank_header_value])).to eq(response_hash[:ok_blank_header_value])
expect(parse_curl_response(response_text[:redirection])).to eq(response_hash[:redirection])
expect(parse_curl_response(response_text[:duplicate_header])).to eq(response_hash[:duplicate_header])
end
it "skips over response header lines with blank header name" do
expect(parse_curl_response(response_text[:ok_blank_header_name])).to eq(response_hash[:ok])
end
it "returns an empty hash when given an empty string" do
expect(parse_curl_response("")).to eq({})
end
end
describe "::curl_response_last_location" do
it "returns the last location header when given an array of HTTP response hashes" do
expect(curl_response_last_location([
response_hash[:redirection],
response_hash[:ok],
])).to eq(response_hash[:redirection][:headers]["location"])
expect(curl_response_last_location([
response_hash[:redirection2],
response_hash[:redirection1],
response_hash[:redirection],
response_hash[:ok],
])).to eq(response_hash[:redirection][:headers]["location"])
end
it "returns the location as given, by default or when absolutize is false" do
expect(curl_response_last_location([
response_hash[:redirection_no_scheme],
response_hash[:ok],
])).to eq(response_hash[:redirection_no_scheme][:headers]["location"])
expect(curl_response_last_location([
response_hash[:redirection_root_relative],
response_hash[:ok],
])).to eq(response_hash[:redirection_root_relative][:headers]["location"])
expect(curl_response_last_location([
response_hash[:redirection_parent_relative],
response_hash[:ok],
])).to eq(response_hash[:redirection_parent_relative][:headers]["location"])
end
it "returns an absolute URL when absolutize is true and a base URL is provided" do
expect(
curl_response_last_location(
[response_hash[:redirection_no_scheme], response_hash[:ok]],
absolutize: true,
base_url: "https://brew.sh/test",
),
).to eq("https:#{response_hash[:redirection_no_scheme][:headers]["location"]}")
expect(
curl_response_last_location(
[response_hash[:redirection_root_relative], response_hash[:ok]],
absolutize: true,
base_url: "https://brew.sh/test",
),
).to eq("https://brew.sh#{response_hash[:redirection_root_relative][:headers]["location"]}")
expect(
curl_response_last_location(
[response_hash[:redirection_parent_relative], response_hash[:ok]],
absolutize: true,
base_url: "https://brew.sh/test1/test2",
),
).to eq(response_hash[:redirection_parent_relative][:headers]["location"].sub(/^\./, "https://brew.sh/test1"))
end
it "skips response hashes without a `:headers` value" do
expect(curl_response_last_location([
response_hash[:redirection],
{ status_code: "404", status_text: "Not Found" },
response_hash[:ok],
])).to eq(response_hash[:redirection][:headers]["location"])
end
it "returns nil when the response hash doesn't contain a location header" do
expect(curl_response_last_location([response_hash[:ok]])).to be_nil
end
end
describe "::curl_response_follow_redirections" do
it "returns the original URL when there are no location headers" do
expect(
curl_response_follow_redirections(
[response_hash[:ok]],
"https://brew.sh/test1/test2",
),
).to eq("https://brew.sh/test1/test2")
end
it "returns the URL relative to base when locations are relative" do
expect(
curl_response_follow_redirections(
[response_hash[:redirection_root_relative], response_hash[:ok]],
"https://brew.sh/test1/test2",
),
).to eq("https://brew.sh/example/")
expect(
curl_response_follow_redirections(
[response_hash[:redirection_parent_relative], response_hash[:ok]],
"https://brew.sh/test1/test2",
),
).to eq("https://brew.sh/test1/example/")
expect(
curl_response_follow_redirections(
[
response_hash[:redirection_parent_relative],
response_hash[:redirection_parent_relative],
response_hash[:ok],
],
"https://brew.sh/test1/test2",
),
).to eq("https://brew.sh/test1/example/example/")
end
it "returns new base when there are absolute location(s)" do
expect(
curl_response_follow_redirections(
[response_hash[:redirection], response_hash[:ok]],
"https://brew.sh/test1/test2",
),
).to eq(location_urls[0])
expect(
curl_response_follow_redirections(
[response_hash[:redirection], response_hash[:redirection_parent_relative], response_hash[:ok]],
"https://brew.sh/test1/test2",
),
).to eq("#{location_urls[0]}example/")
end
it "skips response hashes without a `:headers` value" do
expect(
curl_response_follow_redirections(
[
response_hash[:redirection_root_relative],
{ status_code: "404", status_text: "Not Found" },
response_hash[:ok],
],
"https://brew.sh/test1/test2",
),
).to eq("https://brew.sh/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/utils/topological_hash_spec.rb | Library/Homebrew/test/utils/topological_hash_spec.rb | # frozen_string_literal: true
require "utils/topological_hash"
RSpec.describe Utils::TopologicalHash do
describe "#tsort" do
it "returns a topologically sorted array" do
hash = described_class.new
hash[1] = [2, 3]
hash[2] = [3]
hash[3] = []
hash[4] = []
expect(hash.tsort).to eq [3, 2, 1, 4]
end
end
describe "#strongly_connected_components" do
it "returns an array of arrays" do
hash = described_class.new
hash[1] = [2]
hash[2] = [3, 4]
hash[3] = [2]
hash[4] = []
expect(hash.strongly_connected_components).to eq [[4], [2, 3], [1]]
end
end
describe "::graph_package_dependencies" do
it "returns a topological hash" do
formula1 = formula "homebrew-test-formula1" do
url "foo"
version "0.5"
end
formula2 = formula "homebrew-test-formula2" do
url "foo"
version "0.5"
depends_on "homebrew-test-formula1"
end
formula3 = formula "homebrew-test-formula3" do
url "foo"
version "0.5"
depends_on "homebrew-test-formula4"
end
formula4 = formula "homebrew-test-formula4" do
url "foo"
version "0.5"
depends_on "homebrew-test-formula3"
end
cask1 = Cask::Cask.new("homebrew-test-cask1") do
url "foo"
version "1.2.3"
end
cask2 = Cask::Cask.new("homebrew-test-cask2") do
url "foo"
version "1.2.3"
depends_on cask: "homebrew-test-cask1"
depends_on formula: "homebrew-test-formula1"
end
cask3 = Cask::Cask.new("homebrew-test-cask3") do
url "foo"
version "1.2.3"
depends_on cask: "homebrew-test-cask2"
end
stub_formula_loader formula1
stub_formula_loader formula2
stub_formula_loader formula3
stub_formula_loader formula4
stub_cask_loader cask1
stub_cask_loader cask2
stub_cask_loader cask3
packages = [formula1, formula2, formula3, formula4, cask1, cask2, cask3]
expect(described_class.graph_package_dependencies(packages)).to eq({
formula1 => [],
formula2 => [formula1],
formula3 => [formula4],
formula4 => [formula3],
cask1 => [],
cask2 => [formula1, cask1],
cask3 => [cask2],
})
sorted = [formula1, cask1, cask2, cask3, formula2]
expect(described_class.graph_package_dependencies([cask3, cask2, cask1, formula2, formula1]).tsort).to eq sorted
expect(described_class.graph_package_dependencies([cask3, formula2]).tsort).to eq sorted
expect { described_class.graph_package_dependencies([formula3, formula4]).tsort }.to raise_error TSort::Cyclic
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/utils/service_spec.rb | Library/Homebrew/test/utils/service_spec.rb | # frozen_string_literal: true
require "utils/service"
RSpec.describe Utils::Service do
describe "::systemd_quote" do
it "quotes empty strings correctly" do
expect(described_class.systemd_quote("")).to eq '""'
end
it "quotes strings with special characters escaped correctly" do
expect(described_class.systemd_quote("\a\b\f\n\r\t\v\\"))
.to eq '"\\a\\b\\f\\n\\r\\t\\v\\\\"'
expect(described_class.systemd_quote("\"' ")).to eq "\"\\\"' \""
end
it "does not escape characters that do not need escaping" do
expect(described_class.systemd_quote("daemon off;")).to eq '"daemon off;"'
expect(described_class.systemd_quote("--timeout=3")).to eq '"--timeout=3"'
expect(described_class.systemd_quote("--answer=foo bar"))
.to eq '"--answer=foo bar"'
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/utils/cpan_spec.rb | Library/Homebrew/test/utils/cpan_spec.rb | # frozen_string_literal: true
require "utils/cpan"
RSpec.describe CPAN do
let(:cpan_package_url) do
"https://cpan.metacpan.org/authors/id/P/PE/PEVANS/Scalar-List-Utils-1.68.tar.gz"
end
let(:cpan_tgz_url) do
"https://cpan.metacpan.org/authors/id/S/ST/STBEY/Example-Module-1.23.tgz"
end
let(:non_cpan_package_url) do
"https://github.com/example/package/archive/v1.0.0.tar.gz"
end
describe CPAN::Package do
let(:package_from_cpan_url) { described_class.new("Scalar::Util", cpan_package_url) }
let(:package_from_tgz_url) { described_class.new("Example::Module", cpan_tgz_url) }
let(:package_from_non_cpan_url) { described_class.new("SomePackage", non_cpan_package_url) }
describe "initialize" do
it "initializes resource name" do
expect(package_from_cpan_url.name).to eq "Scalar::Util"
end
it "extracts version from CPAN url" do # rubocop:todo RSpec/AggregateExamples
expect(package_from_cpan_url.current_version).to eq "1.68"
end
it "handles .tgz extensions" do # rubocop:todo RSpec/AggregateExamples
expect(package_from_tgz_url.current_version).to eq "1.23"
end
end
describe ".valid_cpan_package?" do
it "is true for CPAN URLs" do
expect(package_from_cpan_url.valid_cpan_package?).to be true
end
it "is false for non-CPAN URLs" do # rubocop:todo RSpec/AggregateExamples
expect(package_from_non_cpan_url.valid_cpan_package?).to be false
end
end
describe ".to_s" do
it "returns resource name" do
expect(package_from_cpan_url.to_s).to eq "Scalar::Util"
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/utils/svn_spec.rb | Library/Homebrew/test/utils/svn_spec.rb | # frozen_string_literal: true
require "utils/svn"
RSpec.describe Utils::Svn do
before do
described_class.clear_version_cache
end
describe "::available?" do
it "returns svn version if svn available" do
if quiet_system "#{HOMEBREW_SHIMS_PATH}/shared/svn", "--version"
expect(described_class).to be_available
else
expect(described_class).not_to be_available
end
end
end
describe "::version" do
it "returns svn version if svn available" do
if quiet_system "#{HOMEBREW_SHIMS_PATH}/shared/svn", "--version"
expect(described_class.version).to match(/^\d+\.\d+\.\d+$/)
else
expect(described_class.version).to be_nil
end
end
it "returns version of svn when svn is available", :needs_svn do
expect(described_class.version).not_to be_nil
end
end
describe "::remote_exists?" do
it "returns true when svn is not available" do
allow(described_class).to receive(:available?).and_return(false)
expect(described_class).to be_remote_exists("blah")
end
context "when svn is available" do
before do
allow(described_class).to receive(:available?).and_return(true)
end
it "returns false when remote does not exist" do
expect(described_class).not_to be_remote_exists("blah")
end
it "returns true when remote exists", :needs_network, :needs_svn do
expect(described_class).to be_remote_exists("https://svn.apache.org/repos/asf/openoffice/trunk")
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/utils/string_inreplace_extension_spec.rb | Library/Homebrew/test/utils/string_inreplace_extension_spec.rb | # frozen_string_literal: true
require "utils/string_inreplace_extension"
RSpec.describe StringInreplaceExtension do
subject(:string_extension) { described_class.new(string.dup) }
describe "#change_make_var!" do
context "with a flag" do
context "with spaces" do
let(:string) do
<<~EOS
OTHER=def
FLAG = abc
FLAG2=abc
EOS
end
it "is successfully replaced" do
string_extension.change_make_var! "FLAG", "def"
expect(string_extension.inreplace_string).to eq <<~EOS
OTHER=def
FLAG=def
FLAG2=abc
EOS
end
it "is successfully appended" do
string_extension.change_make_var! "FLAG", "\\1 def"
expect(string_extension.inreplace_string).to eq <<~EOS
OTHER=def
FLAG=abc def
FLAG2=abc
EOS
end
end
context "with tabs" do
let(:string) do
<<~EOS
CFLAGS\t=\t-Wall -O2
LDFLAGS\t=\t-lcrypto -lssl
EOS
end
it "is successfully replaced" do
string_extension.change_make_var! "CFLAGS", "-O3"
expect(string_extension.inreplace_string).to eq <<~EOS
CFLAGS=-O3
LDFLAGS\t=\t-lcrypto -lssl
EOS
end
end
context "with newlines" do
let(:string) do
<<~'EOS'
CFLAGS = -Wall -O2 \
-DSOME_VAR=1
LDFLAGS = -lcrypto -lssl
EOS
end
it "is successfully replaced" do
string_extension.change_make_var! "CFLAGS", "-O3"
expect(string_extension.inreplace_string).to eq <<~EOS
CFLAGS=-O3
LDFLAGS = -lcrypto -lssl
EOS
end
end
end
context "with an empty flag between other flags" do
let(:string) do
<<~EOS
OTHER=def
FLAG =
FLAG2=abc
EOS
end
it "is successfully replaced" do
string_extension.change_make_var! "FLAG", "def"
expect(string_extension.inreplace_string).to eq <<~EOS
OTHER=def
FLAG=def
FLAG2=abc
EOS
end
end
context "with an empty flag" do
let(:string) do
<<~EOS
FLAG =
mv file_a file_b
EOS
end
it "is successfully replaced" do
string_extension.change_make_var! "FLAG", "def"
expect(string_extension.inreplace_string).to eq <<~EOS
FLAG=def
mv file_a file_b
EOS
end
end
context "with shell-style variable" do
let(:string) do
<<~EOS
OTHER=def
FLAG=abc
FLAG2=abc
EOS
end
it "is successfully replaced" do
string_extension.change_make_var! "FLAG", "def"
expect(string_extension.inreplace_string).to eq <<~EOS
OTHER=def
FLAG=def
FLAG2=abc
EOS
end
end
end
describe "#remove_make_var!" do
context "with a flag" do
context "with spaces" do
let(:string) do
<<~EOS
OTHER=def
FLAG = abc
FLAG2 = def
EOS
end
it "is successfully removed" do
string_extension.remove_make_var! "FLAG"
expect(string_extension.inreplace_string).to eq <<~EOS
OTHER=def
FLAG2 = def
EOS
end
end
context "with tabs" do
let(:string) do
<<~EOS
CFLAGS\t=\t-Wall -O2
LDFLAGS\t=\t-lcrypto -lssl
EOS
end
it "is successfully removed" do
string_extension.remove_make_var! "LDFLAGS"
expect(string_extension.inreplace_string).to eq <<~EOS
CFLAGS\t=\t-Wall -O2
EOS
end
end
context "with newlines" do
let(:string) do
<<~'EOS'
CFLAGS = -Wall -O2 \
-DSOME_VAR=1
LDFLAGS = -lcrypto -lssl
EOS
end
it "is successfully removed" do
string_extension.remove_make_var! "CFLAGS"
expect(string_extension.inreplace_string).to eq <<~EOS
LDFLAGS = -lcrypto -lssl
EOS
end
end
end
context "with multiple flags" do
let(:string) do
<<~EOS
OTHER=def
FLAG = abc
FLAG2 = def
OTHER2=def
EOS
end
specify "are be successfully removed" do
string_extension.remove_make_var! ["FLAG", "FLAG2"]
expect(string_extension.inreplace_string).to eq <<~EOS
OTHER=def
OTHER2=def
EOS
end
end
end
describe "#get_make_var" do
context "with spaces" do
let(:string) do
<<~EOS
CFLAGS = -Wall -O2
LDFLAGS = -lcrypto -lssl
EOS
end
it "extracts the value for a given variable" do
expect(string_extension.get_make_var("CFLAGS")).to eq("-Wall -O2")
end
end
context "with tabs" do
let(:string) do
<<~EOS
CFLAGS\t=\t-Wall -O2
LDFLAGS\t=\t-lcrypto -lssl
EOS
end
it "extracts the value for a given variable" do
expect(string_extension.get_make_var("CFLAGS")).to eq("-Wall -O2")
end
end
context "with newlines" do
let(:string) do
<<~'EOS'
CFLAGS = -Wall -O2 \
-DSOME_VAR=1
LDFLAGS = -lcrypto -lssl
EOS
end
it "extracts the value for a given variable" do
expect(string_extension.get_make_var("CFLAGS")).to match(/^-Wall -O2 \\\n +-DSOME_VAR=1$/)
end
end
end
describe "#sub!" do
let(:string) { "foo" }
it "replaces the first occurrence" do
string_extension.sub!("o", "e")
expect(string_extension.inreplace_string).to eq("feo")
expect(string_extension.errors).to be_empty
end
it "adds an error to #errors when no replacement was made" do
string_extension.sub! "not here", "test"
expect(string_extension.inreplace_string).to eq(string)
expect(string_extension.errors).to eq(['expected replacement of "not here" with "test"'])
end
it "doesn't add an error to #errors when no replace was made and `audit_result: false`" do
string_extension.sub! "not here", "test", audit_result: false
expect(string_extension.inreplace_string).to eq(string)
expect(string_extension.errors).to be_empty
end
end
describe "#gsub!" do
let(:string) { "foo" }
it "replaces all occurrences" do
# Using `gsub!` here is what we want, and it's only a test.
string_extension.gsub!("o", "e") # rubocop:disable Performance/StringReplacement
expect(string_extension.inreplace_string).to eq("fee")
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/utils/github_spec.rb | Library/Homebrew/test/utils/github_spec.rb | # frozen_string_literal: true
require "utils/github"
RSpec.describe GitHub do
describe "::search_query_string" do
it "builds a query with the given hash parameters formatted as key:value" do
query = described_class.search_query_string(user: "Homebrew", repo: "brew")
expect(query).to eq("q=user%3AHomebrew+repo%3Abrew&per_page=100")
end
it "adds a variable number of top-level string parameters to the query when provided" do
query = described_class.search_query_string("value1", "value2", user: "Homebrew")
expect(query).to eq("q=value1+value2+user%3AHomebrew&per_page=100")
end
it "turns array values into multiple key:value parameters" do
query = described_class.search_query_string(user: ["Homebrew", "caskroom"])
expect(query).to eq("q=user%3AHomebrew+user%3Acaskroom&per_page=100")
end
end
describe "::search_issues", :needs_network do
it "queries GitHub issues with the passed parameters" do
results = described_class.search_issues("brew search",
repo: "Homebrew/legacy-homebrew",
author: "MikeMcQuaid",
is: "issue",
no: "milestone")
expect(results).not_to be_empty
expect(results.first["title"]).to eq("Shall we move more things to taps?")
end
end
describe "::repository_approved_reviews", :needs_network do
it "can get reviews for a pull request" do
reviews = described_class.repository_approved_reviews("Homebrew", "homebrew-core", 1, commit: "deadbeef")
expect(reviews).to eq([])
end
end
describe "::public_member_usernames", :needs_network do
it "gets the usernames of all publicly visible members of the organisation" do
response = described_class.public_member_usernames("Homebrew")
expect(response).to be_a(Array)
end
end
describe "::get_artifact_urls", :needs_network do
it "fails to find a nonexistent workflow" do
expect do
described_class.get_artifact_urls(
described_class.get_workflow_run("Homebrew", "homebrew-core", "1"),
)
end.to raise_error(/No matching check suite found/)
end
it "fails to find artifacts that don't exist" do
expect do
described_class.get_artifact_urls(
described_class.get_workflow_run("Homebrew", "homebrew-core", "252626",
workflow_id: "triage.yml", artifact_pattern: "false_artifact"),
)
end.to raise_error(/No artifacts with the pattern .+ were found/)
end
it "gets artifact URLs" do
urls = described_class.get_artifact_urls(
described_class.get_workflow_run("Homebrew", "homebrew-core", "252626",
workflow_id: "triage.yml", artifact_pattern: "event_payload"),
)
expect(urls).to eq(["https://api.github.com/repos/Homebrew/homebrew-core/actions/artifacts/4457761305/zip"])
end
end
describe "::pull_request_commits", :needs_network do
let(:hashes) do
%w[
188606a4a9587365d930b02c98ad6857b1d00150
25a71fe1ea1558415d6496d23834dc70778ddee5
]
end
it "gets commit hashes for a pull request" do
expect(described_class.pull_request_commits("Homebrew", "legacy-homebrew", 50678)).to eq(hashes)
end
it "gets commit hashes for a paginated pull request API response" do
expect(described_class.pull_request_commits("Homebrew", "legacy-homebrew", 50678, per_page: 1)).to eq(hashes)
end
end
describe "::count_repo_commits" do
let(:five_shas) { %w[abcdef ghjkl mnop qrst uvwxyz] }
let(:ten_shas) { %w[abcdef ghjkl mnop qrst uvwxyz fedcba lkjhg ponm tsrq zyxwvu] }
let(:max) { 1000 }
let(:verbose) { false }
let(:from) { nil }
let(:to) { nil }
it "counts commits authored by a user" do
allow(described_class).to receive(:repo_commits_for_user)
.with("homebrew/cask", "user1", "author", nil, nil, max, verbose).and_return(five_shas)
allow(described_class).to receive(:repo_commits_for_user)
.with("homebrew/cask", "user1", "committer", nil, nil, max, verbose).and_return([])
expect(described_class.count_repository_commits("homebrew/cask", "user1", max:, verbose:, from:,
to:)).to eq(5)
end
it "counts commits committed by a user" do
allow(described_class).to receive(:repo_commits_for_user)
.with("homebrew/core", "user1", "author", nil, nil, max, verbose).and_return([])
allow(described_class).to receive(:repo_commits_for_user)
.with("homebrew/core", "user1", "committer", nil, nil, max, verbose).and_return(five_shas)
expect(described_class.count_repository_commits("homebrew/core", "user1", max:, verbose:, from:,
to:)).to eq(5)
end
it "calculates correctly when authored > committed with different shas" do
allow(described_class).to receive(:repo_commits_for_user)
.with("homebrew/cask", "user1", "author", nil, nil, max, verbose).and_return(ten_shas)
allow(described_class).to receive(:repo_commits_for_user)
.with("homebrew/cask", "user1", "committer", nil, nil, max, verbose).and_return(%w[1 2 3 4 5])
expect(described_class.count_repository_commits("homebrew/cask", "user1", max:, verbose:, from:,
to:)).to eq(15)
end
it "calculates correctly when committed > authored" do
allow(described_class).to receive(:repo_commits_for_user)
.with("homebrew/cask", "user1", "author", nil, nil, max, verbose).and_return(five_shas)
allow(described_class).to receive(:repo_commits_for_user)
.with("homebrew/cask", "user1", "committer", nil, nil, max, verbose).and_return(ten_shas)
expect(described_class.count_repository_commits("homebrew/cask", "user1", max:, verbose:, from:,
to:)).to eq(10)
end
it "deduplicates commits authored and committed by the same user" do
allow(described_class).to receive(:repo_commits_for_user)
.with("homebrew/core", "user1", "author", nil, nil, max, verbose).and_return(five_shas)
allow(described_class).to receive(:repo_commits_for_user)
.with("homebrew/core", "user1", "committer", nil, nil, max, verbose).and_return(five_shas)
# Because user1 authored and committed the same 5 commits.
expect(described_class.count_repository_commits("homebrew/core", "user1", max:, verbose:, from:,
to:)).to eq(5)
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/utils/fork_spec.rb | Library/Homebrew/test/utils/fork_spec.rb | # frozen_string_literal: true
require "utils/fork"
RSpec.describe Utils do
describe "#safe_fork" do
it "raises a RuntimeError on an error that isn't ErrorDuringExecution" do
expect do
described_class.safe_fork do
raise "this is an exception in the child"
end
end.to raise_error(RuntimeError)
end
it "raises an ErrorDuringExecution on one in the child" do
expect do
described_class.safe_fork do
safe_system "/usr/bin/false"
end
end.to raise_error(ErrorDuringExecution)
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/utils/tar_spec.rb | Library/Homebrew/test/utils/tar_spec.rb | # frozen_string_literal: true
require "utils/tar"
RSpec.describe Utils::Tar do
before do
described_class.clear_executable_cache
end
describe ".available?" do
it "returns true if tar or gnu-tar is available" do
if described_class.executable.present?
expect(described_class).to be_available
else
expect(described_class).not_to be_available
end
end
end
describe ".validate_file" do
it "does not raise an error when tar and gnu-tar are unavailable" do
allow(described_class).to receive(:available?).and_return false
expect { described_class.validate_file "blah" }.not_to raise_error
end
context "when tar or gnu-tar is available" do
let(:testball_resource) { "#{TEST_FIXTURE_DIR}/tarballs/testball-0.1.tbz" }
let(:invalid_resource) { "#{TEST_TMPDIR}/invalid.tgz" }
before do
allow(described_class).to receive(:available?).and_return true
end
it "does not raise an error if file is not a tar file" do
expect { described_class.validate_file "blah" }.not_to raise_error
end
it "does not raise an error if file is valid tar file" do
expect { described_class.validate_file testball_resource }.not_to raise_error
end
it "raises an error if file is an invalid tar file" do
FileUtils.touch invalid_resource
expect { described_class.validate_file invalid_resource }.to raise_error SystemExit
FileUtils.rm_f invalid_resource
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/utils/gzip_spec.rb | Library/Homebrew/test/utils/gzip_spec.rb | # frozen_string_literal: true
require "utils/gzip"
RSpec.describe Utils::Gzip do
include FileUtils
describe "compress_with_options" do
it "uses the explicitly specified mtime, orig_name and output path when passed" do
mktmpdir do |path|
mtime = Time.at(12345).utc
orig_name = "someotherfile"
output = path/"subdir/anotherfile.gz"
file_content = "Hello world"
expected_checksum = "df509051b519faa8a1143157d2750d1694dc5fe6373e493c0d5c360be3e61516"
somefile = path/"somefile"
File.write(somefile, file_content)
mkdir path/"subdir"
expect(described_class.compress_with_options(somefile, mtime:, orig_name:,
output:)).to eq(output)
expect(Digest::SHA256.hexdigest(File.read(output))).to eq(expected_checksum)
end
end
it "uses SOURCE_DATE_EPOCH as mtime when not explicitly specified" do
mktmpdir do |path|
ENV["SOURCE_DATE_EPOCH"] = "23456"
file_content = "Hello world"
expected_checksum = "a579be88ec8073391a5753b1df4d87fbf008aaec6b5a03f8f16412e2e01f119a"
somefile = path/"somefile"
File.write(somefile, file_content)
expect(described_class.compress_with_options(somefile).to_s).to eq("#{somefile}.gz")
expect(Digest::SHA256.hexdigest(File.read("#{somefile}.gz"))).to eq(expected_checksum)
end
end
end
describe "compress" do
it "creates non-reproducible gz files from input files" do
mktmpdir do |path|
files = (0..2).map { |n| path/"somefile#{n}" }
FileUtils.touch files
results = described_class.compress(*files, reproducible: false)
3.times do |n|
expect(results[n].to_s).to eq("#{files[n]}.gz")
expect(Pathname.new("#{files[n]}.gz")).to exist
end
end
end
it "creates reproducible gz files from input files with explicit mtime" do
mtime = Time.at(12345).utc
expected_checksums = %w[
5b45cabc7f0192854365aeccd82036e482e35131ba39fbbc6d0684266eb2e88a
d422bf4cbede17ae242135d7f32ba5379fbffb288c29cd38b7e5e1a5f89073f8
1d93a3808e2bd5d8c6371ea1c9b8b538774d6486af260719400fc3a5b7ac8d6f
]
mktmpdir do |path|
files = (0..2).map { |n| path/"somefile#{n}" }
files.each { |f| File.write(f, "Hello world") }
results = described_class.compress(*files, mtime:)
3.times do |n|
expect(results[n].to_s).to eq("#{files[n]}.gz")
expect(Digest::SHA256.hexdigest(File.read(results[n]))).to eq(expected_checksums[n])
end
end
end
it "creates reproducible gz files from input files with SOURCE_DATE_EPOCH as mtime" do
ENV["SOURCE_DATE_EPOCH"] = "23456"
expected_checksums = %w[
d5e0cc3259b1eb61d93ee5a30d41aef4a382c1cf2b759719c289f625e27b915c
068657725bca5f9c2bc62bc6bf679eb63786e92d16cae575dee2fd9787a338f3
e566e9fdaf9aa2a7c9501f9845fed1b70669bfa679b0de609e3b63f99988784d
]
mktmpdir do |path|
files = (0..2).map { |n| path/"somefile#{n}" }
files.each { |f| File.write(f, "Hello world") }
results = described_class.compress(*files)
3.times do |n|
expect(results[n].to_s).to eq("#{files[n]}.gz")
expect(Digest::SHA256.hexdigest(File.read(results[n]))).to eq(expected_checksums[n])
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/utils/shell_spec.rb | Library/Homebrew/test/utils/shell_spec.rb | # frozen_string_literal: true
require "utils/shell"
RSpec.describe Utils::Shell do
describe "::profile" do
it "returns ~/.profile by default" do
ENV["SHELL"] = "/bin/another_shell"
expect(described_class.profile).to eq("~/.profile")
end
it "returns ~/.profile for sh" do
ENV["SHELL"] = "/bin/sh"
expect(described_class.profile).to eq("~/.profile")
end
it "returns ~/.profile for Bash" do
ENV["SHELL"] = "/bin/bash"
expect(described_class.profile).to eq("~/.profile")
end
it "returns /tmp/.zshrc for Zsh if ZDOTDIR is /tmp" do
ENV["SHELL"] = "/bin/zsh"
ENV["HOMEBREW_ZDOTDIR"] = "/tmp"
expect(described_class.profile).to eq("/tmp/.zshrc")
end
it "returns ~/.zshrc for Zsh" do
ENV["SHELL"] = "/bin/zsh"
ENV["HOMEBREW_ZDOTDIR"] = nil
expect(described_class.profile).to eq("~/.zshrc")
end
it "returns ~/.kshrc for Ksh" do
ENV["SHELL"] = "/bin/ksh"
expect(described_class.profile).to eq("~/.kshrc")
end
it "returns ~/.config/powershell/Microsoft.PowerShell_profile.ps1 for PowerShell" do
ENV["SHELL"] = "/usr/bin/pwsh"
expect(described_class.profile).to eq("~/.config/powershell/Microsoft.PowerShell_profile.ps1")
end
end
describe "::from_path" do
it "supports a raw command name" do
expect(described_class.from_path("bash")).to eq(:bash)
end
it "supports full paths" do
expect(described_class.from_path("/bin/bash")).to eq(:bash)
end
it "supports versions" do
expect(described_class.from_path("zsh-5.2")).to eq(:zsh)
end
it "strips newlines" do
expect(described_class.from_path("zsh-5.2\n")).to eq(:zsh)
end
it "returns nil when input is invalid" do
expect(described_class.from_path("")).to be_nil
expect(described_class.from_path("@@@@@@")).to be_nil
expect(described_class.from_path("invalid_shell-4.2")).to be_nil
end
end
specify "::sh_quote" do
expect(described_class.send(:sh_quote, "")).to eq("''")
expect(described_class.send(:sh_quote, "\\")).to eq("\\\\")
expect(described_class.send(:sh_quote, "\n")).to eq("'\n'")
expect(described_class.send(:sh_quote, "$")).to eq("\\$")
expect(described_class.send(:sh_quote, "word")).to eq("word")
end
specify "::csh_quote" do
expect(described_class.send(:csh_quote, "")).to eq("''")
expect(described_class.send(:csh_quote, "\\")).to eq("\\\\")
# NOTE: This test is different than for `sh`.
expect(described_class.send(:csh_quote, "\n")).to eq("'\\\n'")
expect(described_class.send(:csh_quote, "$")).to eq("\\$")
expect(described_class.send(:csh_quote, "word")).to eq("word")
end
describe "::prepend_path_in_profile" do
let(:path) { "/my/path" }
it "supports tcsh" do
ENV["SHELL"] = "/bin/tcsh"
expect(described_class.prepend_path_in_profile(path))
.to eq("echo 'setenv PATH #{path}:$PATH' >> #{described_class.profile}")
end
it "supports Bash" do
ENV["SHELL"] = "/bin/bash"
expect(described_class.prepend_path_in_profile(path))
.to eq("echo 'export PATH=\"#{path}:$PATH\"' >> #{described_class.profile}")
end
it "supports fish" do
ENV["SHELL"] = "/usr/local/bin/fish"
ENV["fish_user_paths"] = "/some/path"
expect(described_class.prepend_path_in_profile(path))
.to eq("fish_add_path #{path}")
end
end
describe "::shell_with_prompt" do
let(:home) { HOMEBREW_TEMP }
let(:notice) { "" }
let(:prompt) { "test" }
let(:path) { "/some/path" }
it "returns zsh-specific prompt configuration" do
preferred_path = "/bin/zsh"
ENV["SHELL"] = preferred_path
ENV["PATH"] = path
zdotdir = "#{HOMEBREW_TEMP}/brew-zsh-prompt-#{Process.euid}"
expect(described_class.shell_with_prompt(prompt, preferred_path:, notice:, home:)).to eq \
"BREW_PROMPT_PATH=\"#{path}\" BREW_PROMPT_TYPE=\"#{prompt}\" ZDOTDIR=\"#{zdotdir}\" #{preferred_path}"
end
it "returns bash-specific prompt configuration" do
preferred_path = "/bin/bash"
ENV["SHELL"] = "/bin/bash"
ENV["PATH"] = path
rcfile = "#{HOMEBREW_LIBRARY_PATH}/utils/bash/brew-sh-prompt-bashrc.bash"
expect(described_class.shell_with_prompt(prompt, preferred_path:, notice:, home:)).to eq \
"BREW_PROMPT_PATH=\"#{path}\" BREW_PROMPT_TYPE=\"#{prompt}\" #{preferred_path} --rcfile \"#{rcfile}\""
end
it "returns generic shell prompt configuration" do
preferred_path = "/bin/dash"
ENV["SHELL"] = preferred_path
expect(described_class.shell_with_prompt(prompt, preferred_path:, notice:, home:)).to eq \
"PS1=\"\\[\\033[1;32m\\]#{prompt} \\[\\033[1;31m\\]\\w \\[\\033[1;34m\\]$\\[\\033[0m\\] \" #{preferred_path}"
end
it "outputs notice when provided" do
notice = "Test Notice"
expect { described_class.shell_with_prompt("test", preferred_path: "/bin/bash", notice: notice) }
.to output("#{notice}\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/utils/timer_spec.rb | Library/Homebrew/test/utils/timer_spec.rb | # frozen_string_literal: true
require "utils/timer"
RSpec.describe Utils::Timer do
describe "#remaining" do
it "returns nil when nil" do
expect(described_class.remaining(nil)).to be_nil
end
it "returns time remaining when there is time remaining" do
expect(described_class.remaining(Time.now + 10)).to be > 1
end
it "returns 0 when there is no time remaining" do
expect(described_class.remaining(Time.now - 10)).to be 0
end
end
describe "#remaining!" do
it "returns nil when nil" do
expect(described_class.remaining!(nil)).to be_nil
end
it "returns time remaining when there is time remaining" do
expect(described_class.remaining!(Time.now + 10)).to be > 1
end
it "returns 0 when there is no time remaining" do
expect { described_class.remaining!(Time.now - 10) }.to raise_error(Timeout::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/utils/tty_spec.rb | Library/Homebrew/test/utils/tty_spec.rb | # frozen_string_literal: true
RSpec.describe Tty do
describe "::strip_ansi" do
it "removes ANSI escape codes from a string" do
expect(described_class.strip_ansi("\033[36;7mhello\033[0m")).to eq("hello")
end
end
describe "::width" do
it "returns an Integer" do
expect(described_class.width).to be_a(Integer)
end
it "cannot be negative" do # rubocop:todo RSpec/AggregateExamples
expect(described_class.width).to be >= 0
end
end
describe "::truncate" do
it "truncates the text to the terminal width, minus 4, to account for '==> '" do
allow(described_class).to receive(:width).and_return(15)
expect(described_class.truncate("foobar something very long")).to eq("foobar some")
expect(described_class.truncate("truncate")).to eq("truncate")
end
it "doesn't truncate the text if the terminal is unsupported, i.e. the width is 0" do
allow(described_class).to receive(:width).and_return(0)
expect(described_class.truncate("foobar something very long")).to eq("foobar something very long")
end
end
context "when $stdout is not a TTY" do
before do
allow($stdout).to receive(:tty?).and_return(false)
end
it "returns an empty string for all colors" do
expect(described_class.to_s).to eq("")
expect(described_class.red.to_s).to eq("")
expect(described_class.green.to_s).to eq("")
expect(described_class.yellow.to_s).to eq("")
expect(described_class.blue.to_s).to eq("")
expect(described_class.magenta.to_s).to eq("")
expect(described_class.cyan.to_s).to eq("")
expect(described_class.default.to_s).to eq("")
end
end
context "when $stdout is a TTY" do
before do
allow($stdout).to receive(:tty?).and_return(true)
end
it "returns ANSI escape codes for colors" do
expect(described_class.to_s).to eq("")
expect(described_class.red.to_s).to eq("\033[31m")
expect(described_class.green.to_s).to eq("\033[32m")
expect(described_class.yellow.to_s).to eq("\033[33m")
expect(described_class.blue.to_s).to eq("\033[34m")
expect(described_class.magenta.to_s).to eq("\033[35m")
expect(described_class.cyan.to_s).to eq("\033[36m")
expect(described_class.default.to_s).to eq("\033[39m")
end
it "returns an empty string for all colors when HOMEBREW_NO_COLOR is set" do
ENV["HOMEBREW_NO_COLOR"] = "1"
expect(described_class.to_s).to eq("")
expect(described_class.red.to_s).to eq("")
expect(described_class.green.to_s).to eq("")
expect(described_class.yellow.to_s).to eq("")
expect(described_class.blue.to_s).to eq("")
expect(described_class.magenta.to_s).to eq("")
expect(described_class.cyan.to_s).to eq("")
expect(described_class.default.to_s).to eq("")
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/utils/popen_spec.rb | Library/Homebrew/test/utils/popen_spec.rb | # frozen_string_literal: true
require "utils/popen"
RSpec.describe Utils do
describe "::popen_read" do
it "reads the standard output of a given command" do
expect(described_class.popen_read("sh", "-c", "echo success").chomp).to eq("success")
expect($CHILD_STATUS).to be_a_success
end
it "can be given a block to manually read from the pipe" do
expect(
described_class.popen_read("sh", "-c", "echo success") do |pipe|
pipe.read.chomp
end,
).to eq("success")
expect($CHILD_STATUS).to be_a_success
end
it "fails when the command does not exist" do
expect(described_class.popen_read("./nonexistent", err: :out))
.to eq("brew: command not found: ./nonexistent\n")
expect($CHILD_STATUS).to be_a_failure
end
end
describe "::popen_write" do
let(:foo) { mktmpdir/"foo" }
before { foo.write "Foo\n" }
it "supports writing to a command's standard input" do
described_class.popen_write("grep", "-q", "success") do |pipe|
pipe.write "success\n"
end
expect($CHILD_STATUS).to be_a_success
end
it "returns the command's standard output before writing" do
child_stdout = described_class.popen_write("cat", foo, "-") do |pipe|
pipe.write "Bar\n"
end
expect($CHILD_STATUS).to be_a_success
expect(child_stdout).to eq <<~EOS
Foo
Bar
EOS
end
it "returns the command's standard output after writing" do
child_stdout = described_class.popen_write("cat", "-", foo) do |pipe|
pipe.write "Bar\n"
end
expect($CHILD_STATUS).to be_a_success
expect(child_stdout).to eq <<~EOS
Bar
Foo
EOS
end
it "supports interleaved writing between two reads" do
child_stdout = described_class.popen_write("cat", foo, "-", foo) do |pipe|
pipe.write "Bar\n"
end
expect($CHILD_STATUS).to be_a_success
expect(child_stdout).to eq <<~EOS
Foo
Bar
Foo
EOS
end
end
describe "::safe_popen_read" do
it "does not raise an error if the command succeeds" do
expect(described_class.safe_popen_read("sh", "-c", "true")).to eq("")
expect($CHILD_STATUS).to be_a_success
end
it "raises an error if the command fails" do
expect { described_class.safe_popen_read("sh", "-c", "false") }.to raise_error(ErrorDuringExecution)
expect($CHILD_STATUS).to be_a_failure
end
end
describe "::safe_popen_write" do
it "does not raise an error if the command succeeds" do
expect(
described_class.safe_popen_write("grep", "success") { |pipe| pipe.write "success\n" }.chomp,
).to eq("success")
expect($CHILD_STATUS).to be_a_success
end
it "raises an error if the command fails" do
expect do
described_class.safe_popen_write("grep", "success") { |pipe| pipe.write "failure\n" }
end.to raise_error(ErrorDuringExecution)
expect($CHILD_STATUS).to be_a_failure
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/utils/user_spec.rb | Library/Homebrew/test/utils/user_spec.rb | # frozen_string_literal: true
require "utils/user"
RSpec.describe User do
subject(:user) { described_class.current }
it { is_expected.to eq ENV.fetch("USER") }
describe "#gui?" do
before do
allow(SystemCommand).to receive(:run)
.with("who", any_args)
.and_return(instance_double(SystemCommand::Result,
to_a: [who_output, "", instance_double(Process::Status, success?: true)]))
end
context "when the current user is in a console session" do
let(:who_output) do
<<~EOS
#{ENV.fetch("USER")} console Oct 1 11:23
#{ENV.fetch("USER")} ttys001 Oct 1 11:25
EOS
end
it(:gui?) { expect(user.gui?).to be true }
end
context "when the current user is not in a console session" do
let(:who_output) do
<<~EOS
#{ENV.fetch("USER")} ttys001 Oct 1 11:25
fake_user ttys002 Oct 1 11:27
EOS
end
it(:gui?) { expect(user.gui?).to be false }
end
end
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.