From 3ccdaf91824cd788d6383adb5fbdc60b994e1570 Mon Sep 17 00:00:00 2001 From: John Bender Date: Mon, 8 Feb 2010 22:38:32 -0800 Subject: [PATCH] Hobo.busy added, and tested --- lib/hobo.rb | 1 + lib/hobo/busy.rb | 32 ++++++++++++++++++++++++++++++++ test/hobo/busy_test.rb | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 70 insertions(+) create mode 100644 lib/hobo/busy.rb create mode 100644 test/hobo/busy_test.rb diff --git a/lib/hobo.rb b/lib/hobo.rb index b0b6cde08..d2bcec9e8 100644 --- a/lib/hobo.rb +++ b/lib/hobo.rb @@ -8,6 +8,7 @@ require 'logger' require 'virtualbox' require 'net/ssh' require 'ping' +require 'hobo/busy' require 'hobo/util' require 'hobo/config' require 'hobo/env' diff --git a/lib/hobo/busy.rb b/lib/hobo/busy.rb new file mode 100644 index 000000000..c36fb7478 --- /dev/null +++ b/lib/hobo/busy.rb @@ -0,0 +1,32 @@ +module Hobo + def self.busy? + Busy.busy? + end + + def self.busy(&block) + Mutex.new.synchronize do + Busy.busy = true + yield + Busy.busy = false + end + + # In the case were an exception is thrown by the wrapped code + # make sure to set busy to sane state and reraise the error + rescue Exception => e + Busy.busy = false + raise + end + + class Busy + @@busy = false + class << self + def busy? + @@busy + end + + def busy=(val) + @@busy = val + end + end + end +end diff --git a/test/hobo/busy_test.rb b/test/hobo/busy_test.rb new file mode 100644 index 000000000..25be668a0 --- /dev/null +++ b/test/hobo/busy_test.rb @@ -0,0 +1,37 @@ +require File.join(File.dirname(__FILE__), '..', 'test_helper') + +class BusyTest < Test::Unit::TestCase + context "during an action in a busy block" do + should "hobo should report as busy" do + Hobo.busy do + # Inside the block Hobo.busy? should be true + assert Hobo.busy? + end + + #After the block finishes Hobo.busy? should be false + assert !Hobo.busy? + end + + should "set busy to false upon exception and reraise the error" do + assert_raise Exception do + Hobo.busy do + assert Hobo.busy? + raise Exception + end + end + + assert !Hobo.busy? + end + + should "report busy to the outside world regardless of thread" do + Thread.new do + Hobo.busy do + sleep(10) + end + end + + # While the above thread is executing hobo should be busy + assert Hobo.busy? + end + end +end