module BigBench # A fragment represents a single http request inside a benchmark. It is executed by the benchmark and resides inside the benchmark block in the test # reciepts: # # benchmark "index page" => "http://localhost:3000" do # # Fragments # end # # Possible fragment types are the HTTP verbs, like GET, POST, PUT and DELETE. They look like this: # # get "/" # post "/login/new", { :name => "a name", :password => "secret" } # put "/books", { :name => "A Book title", :rating => 30.4 } # delete "/books/5" # module Fragment @fragments = [] @benchmark = nil class Fragment attr_accessor :benchmark attr_accessor :path attr_accessor :method attr_accessor :params attr_accessor :uri def initialize benchmark, path, method, params = {} @benchmark, @path, @method, @params = benchmark, path, method, params @uri = URI(@benchmark.uri.to_s + @path) end # Initiates the request in the context of a Net::HTTP.start block def run!(http) request = case @method when :get then Net::HTTP::Get.new(@uri.request_uri) when :post then Net::HTTP::Post.new(@uri.request_uri) when :put then Net::HTTP::Put.new(@uri.request_uri) when :delete then Net::HTTP::Delete.new(@uri.request_uri) else nil end start = Time.now response = http.request(request) stop = Time.now track!(start, stop, response) response end # Adds the current tracking result as a hash to the benchmark's tracker def track!(start, stop, response) @benchmark.tracker.track( { :elapsed => (stop - benchmark.start).to_f, :start => start.to_f, :stop => stop.to_f, :duration => (stop - start).to_milliseconds, :benchmark => @benchmark.name, :url => @uri.to_s, :path => @uri.request_uri, :method => @method, :status => response.code } ) end end # Performs a GET request to the given url, e.g. # # get "/some/page" # def self.get(path) @fragments << Fragment.new(@benchmark, path, :get, {}) end # Performs a POST request to the given url, e.g. # # post "/login", { :user => "some@sample.com", :password => "secret" } # def self.post(path, params = {}) @fragments << Fragment.new(@benchmark, path, :post, params) end # Performs a PUT request to the given url, e.g. # # put "/books", { :book => "Some book content" } # def self.put(path, params = {}) @fragments << Fragment.new(@benchmark, path, :put, params) end # Performs a DELETE request to the given url, e.g. # # delete "/books/5", { :user => "some@sample.com", :password => "secret" } # def self.delete(path, params = {}) @fragments << Fragment.new(@benchmark, path, :delete, params) end # Evaluates a benchmark block full of puts and gets and returns an array of fully configured fragments for it def self.parse(benchmark, &block) reset! return [] if block.nil? @benchmark = benchmark module_exec(&block) @fragments end # Reset all fragments def self.reset! @benchmark = nil @fragments = [] end end end