From 6fc99d956958d7e3dfad1d53a33b91e38a56f25e Mon Sep 17 00:00:00 2001 From: Douglas Eichelberger Date: Wed, 6 Mar 2024 21:12:17 -0800 Subject: [PATCH] Add tests --- Library/Homebrew/abstract_command.rb | 6 +- .../Homebrew/test/abstract_command_spec.rb | 56 +++++++++++++++++++ .../Homebrew/test/abstract_command_spec.rbi | 4 ++ 3 files changed, 63 insertions(+), 3 deletions(-) create mode 100644 Library/Homebrew/test/abstract_command_spec.rb create mode 100644 Library/Homebrew/test/abstract_command_spec.rbi diff --git a/Library/Homebrew/abstract_command.rb b/Library/Homebrew/abstract_command.rb index e6932ccc96..3d633058c4 100644 --- a/Library/Homebrew/abstract_command.rb +++ b/Library/Homebrew/abstract_command.rb @@ -37,9 +37,9 @@ module Homebrew sig { returns(CLI::Args) } attr_reader :args - sig { void } - def initialize - @args = T.let(CLI::Parser.new(&self.class.parser_block).parse, CLI::Args) + sig { params(argv: T::Array[String]).void } + def initialize(argv = ARGV.freeze) + @args = T.let(CLI::Parser.new(&self.class.parser_block).parse(argv), CLI::Args) end sig { abstract.void } diff --git a/Library/Homebrew/test/abstract_command_spec.rb b/Library/Homebrew/test/abstract_command_spec.rb new file mode 100644 index 0000000000..0b3b5e05a4 --- /dev/null +++ b/Library/Homebrew/test/abstract_command_spec.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +require "abstract_command" + +RSpec.describe Homebrew::AbstractCommand do + describe "subclasses" do + before do + cat = Class.new(described_class) do + cmd_args do + switch "--foo" + flag "--bar=" + end + def run; end + end + stub_const("Cat", cat) + end + + describe "parsing args" do + it "parses valid args" do + expect { Cat.new(["--foo"]).run }.not_to raise_error + end + + it "allows access to args" do + expect(Cat.new(["--bar", "baz"]).args[:bar]).to eq("baz") + end + + it "raises on invalid args" do + expect { Cat.new(["--bat"]) }.to raise_error(OptionParser::InvalidOption) + end + end + + describe "command names" do + it "has a default command name" do + expect(Cat.command_name).to eq("cat") + end + + it "can lookup command" do + expect(described_class.command("cat")).to be(Cat) + end + + describe "when command name is overridden" do + before do + tac = Class.new(described_class) do + def self.command_name = "t-a-c" + def run; end + end + stub_const("Tac", tac) + end + + it "can be looked up by command name" do + expect(described_class.command("t-a-c")).to be(Tac) + end + end + end + end +end diff --git a/Library/Homebrew/test/abstract_command_spec.rbi b/Library/Homebrew/test/abstract_command_spec.rbi new file mode 100644 index 0000000000..f282e9a02f --- /dev/null +++ b/Library/Homebrew/test/abstract_command_spec.rbi @@ -0,0 +1,4 @@ +# typed: strict + +class Cat < Homebrew::AbstractCommand; end +class Tac < Homebrew::AbstractCommand; end