diff --git a/lib/statsd.rb b/lib/statsd.rb index 5af9196..f8a53aa 100644 --- a/lib/statsd.rb +++ b/lib/statsd.rb @@ -13,6 +13,8 @@ # statsd = Statsd.new('localhost').tap{|sd| sd.namespace = 'account'} # statsd.increment 'activate' class Statsd + class ConfigError < StandardError; end; + # A namespace to prepend to all statsd calls. attr_accessor :namespace @@ -109,4 +111,22 @@ def send_to_socket(message) end def socket; @socket ||= UDPSocket.new end + + def self.setup(options={}) + params = [ + options[:host] || "localhost", + options[:port] + ].compact + @instance = self.new(*params) + end + + def self.clear_setup + @instance = nil + end + + def self.method_missing(m, *args, &block) + raise ConfigError.new("I'm not setup()") unless @instance + @instance.__send__(m, *args, &block) + end end + diff --git a/spec/statsd_spec.rb b/spec/statsd_spec.rb index 6c6523c..7e69c7b 100644 --- a/spec/statsd_spec.rb +++ b/spec/statsd_spec.rb @@ -160,7 +160,6 @@ def socket; @socket ||= FakeUDPSocket.new end end describe "stat names" do - it "should accept anything as stat" do @statsd.increment(Object, 1) end @@ -176,7 +175,56 @@ class Statsd::SomeClass; end @statsd.increment('ray@hostname.blah|blah.blah:blah', 1) @statsd.socket.recv.must_equal ['ray_hostname.blah_blah.blah_blah:1|c'] end + end + describe "should support direct calls" do + before do + Statsd.clear_setup + Statsd.setup(:host => "localhost", :port => 1234) + @instance = Statsd.instance_variable_get('@instance') + class << @instance + public :sampled # we need to test this + attr_reader :host, :port # we also need to test this + def socket; @socket ||= FakeUDPSocket.new end + end + end + + it 'should complain if setup has not been called' do + Statsd.clear_setup + assert_raises(Statsd::ConfigError) do + Statsd.timing("dummy", rand) + end + end + + it 'should setup instance correctly' do + @instance.host.must_equal 'localhost' + @instance.port.must_equal 1234 + end + + it "should support increment" do + Statsd.increment('foobar') + @instance.socket.recv.must_equal ['foobar:1|c'] + end + + it "should support decrement" do + Statsd.decrement('foobar') + @instance.socket.recv.must_equal ['foobar:-1|c'] + end + + it "should support timing" do + t = 100 + Statsd.timing('foobar', t) + @instance.socket.recv.must_equal ["foobar:#{t}|ms"] + end + + it "should support time" do + Statsd.time('foobar') { sleep(0.001); 'test' } + @instance.socket.recv.must_equal ['foobar:1|ms'] + end + + it "should support sampled" do + Statsd.sampled(1) { :yielded }.must_equal :yielded + end end end