Skip to content

Commit

Permalink
Merge pull request #14 from DataDog/tonycthsu/test-callback
Browse files Browse the repository at this point in the history
Test for callback
  • Loading branch information
TonyCTHsu authored May 14, 2024
2 parents a2e55ea + 8ca0b4e commit d09a863
Show file tree
Hide file tree
Showing 2 changed files with 95 additions and 7 deletions.
15 changes: 8 additions & 7 deletions lib/graft/callback.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,37 +4,38 @@ module Graft
class Callback
attr_reader :name

# NOTE: opts is not used in the current implementation
def initialize(name = nil, opts = {}, &block)
@name = name
@opts = opts
@block = block
@disabled = false
@enabled = true
end

if RUBY_VERSION < "3.0"
def call(*args, &block)
return if @disabled
return unless enabled?

@block.call(*args, &block)
end
else
def call(*args, **kwargs, &block)
return if @disabled
return unless enabled?

@block.call(*args, **kwargs, &block)
end
end

def disable
@disabled = true
@enabled = false
end

def enable
@disabled = false
@enabled = true
end

def disabled?
@disabled
def enabled?
@enabled
end
end
end
87 changes: 87 additions & 0 deletions test/graft/callback_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
require "minitest/spec"
require "minitest/autorun"

require "graft/callback"

describe Graft::Callback do
describe "initialize" do
it do
callback = Graft::Callback.new

_(callback.name).must_be_nil
end

it do
name = "Tony Stark"

callback = Graft::Callback.new(name)

_(callback.name).must_be :==, name
end

describe "enabled?" do
it do
callback = Graft::Callback.new

_(callback).must_be :enabled?

callback.disable

_(callback).wont_be :enabled?

callback.enable

_(callback).must_be :enabled?
end
end

describe "#call" do
invocations = [
->(c) { c.call }, # with no args
->(c) { c.call(:foo) }, # with positional arg
->(c) { c.call(:foo, :bar) }, # with 2 positional args
->(c) { c.call({foo: :bar}) }, # with positional arg(hash)
->(c) { c.call(foo: :bar) }, # with kwargs
->(c) { c.call { :baz } }, # with block
->(c) { c.call(:foo) { :baz } }, # with positional arg + block
->(c) { c.call(:foo, :bar) { :baz } }, # with 2 positional arg + block
->(c) { c.call({foo: :bar}) { :baz } }, # with positional arg(hash) + block
->(c) { c.call(foo: :bar) { :baz } } # with kwargs + block
# Add more invocations here...
]

it do
callback = Graft::Callback.new("name", {})

callback.enable

invocations.each do |i|
_ { i.call(callback) }.must_raise NoMethodError
end

callback.disable

invocations.each do |i|
_(i.call(callback)).must_be_nil
end
end

it do
callback = Graft::Callback.new("name", {}) { :wuff }
# NOTE: What is missing?

callback.enable

invocations.each do |i, v|
_(i.call(callback)).must_be :==, :wuff
end

callback.disable

invocations.each do |i|
_(i.call(callback)).must_be_nil
end
end
end
end
end

0 comments on commit d09a863

Please sign in to comment.