Skip to content

Commit

Permalink
Print a warning when FakeWeb is loaded after Samuel
Browse files Browse the repository at this point in the history
FakeWeb stops Samuel (and other "around advice" Net::HTTP patchers) from working when required after them, since the whole point of FakeWeb is to stop faked requests from propagating through to Net::HTTP. Everything works fine when you require FakeWeb first, though, since in that case Samuel is wrapping FakeWeb instead of the other way around.
  • Loading branch information
chrisk committed Oct 5, 2009
1 parent e366ca3 commit 22533e2
Show file tree
Hide file tree
Showing 18 changed files with 765 additions and 2 deletions.
4 changes: 2 additions & 2 deletions Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ end

require 'rake/testtask'
Rake::TestTask.new(:test) do |test|
test.test_files = FileList["test/**/*.rb"].exclude("test/test_helper.rb")
test.test_files = FileList["test/**/*.rb"].exclude("test/test_helper.rb", "test/vendor")
test.verbose = false
test.warning = true
end
Expand All @@ -38,7 +38,7 @@ task :default => :test
begin
require 'rcov/rcovtask'
Rcov::RcovTask.new do |t|
t.test_files = FileList["test/**/*.rb"].exclude("test/test_helper.rb")
t.test_files = FileList["test/**/*.rb"].exclude("test/test_helper.rb", "test/vendor")
t.rcov_opts << "--sort coverage"
t.rcov_opts << "--exclude gems"
t.warning = true
Expand Down
2 changes: 2 additions & 0 deletions lib/fake_web.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
require 'fake_web/stub_socket'
require 'fake_web/utility'

FakeWeb::Utility.puts_warning_for_net_http_around_advice_libs_if_needed

module FakeWeb

# Returns the version string for the copy of FakeWeb you have loaded.
Expand Down
13 changes: 13 additions & 0 deletions lib/fake_web/utility.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,18 @@ def self.simple_array_permutation(array, &block)
array
end

def self.puts_warning_for_net_http_around_advice_libs_if_needed
libs = {"Samuel" => defined?(Samuel)}
warnings = libs.select { |_, loaded| loaded }.map do |name, _|
<<-TEXT.gsub(/ {10}/, '')
\e[1mWarning: FakeWeb was loaded after #{name}\e[0m
* #{name}'s code is being ignored when a request is handled by FakeWeb,
because both libraries work by patching Net::HTTP.
* To fix this, just reorder your requires so that FakeWeb is before #{name}.
TEXT
end
$stderr.puts "\n" + warnings.join("\n") + "\n" if warnings.any?
end

end
end
25 changes: 25 additions & 0 deletions test/test_other_net_http_libraries.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
require File.join(File.dirname(__FILE__), "test_helper")

class TestOtherNetHttpLibraries < Test::Unit::TestCase

def capture_output_from_requiring(*libs)
requires = libs.map { |lib| "require '#{lib}'" }.join("; ")
fakeweb_dir = "#{File.dirname(__FILE__)}/../lib"
vendor_dirs = Dir["#{File.dirname(__FILE__)}/vendor/*/lib"]
load_path_opts = vendor_dirs.unshift(fakeweb_dir).map { |dir| "-I#{dir}" }.join(" ")

# TODO: use the same Ruby executable that this test was invoked with
`ruby #{load_path_opts} -e "#{requires}" 2>&1`
end

def test_requiring_samuel_before_fakeweb_prints_warning
output = capture_output_from_requiring "samuel", "fakeweb"
assert_match %r(Warning: FakeWeb was loaded after Samuel), output
end

def test_requiring_samuel_after_fakeweb_does_not_print_warning
output = capture_output_from_requiring "fakeweb", "samuel"
assert output.empty?
end

end
5 changes: 5 additions & 0 deletions test/vendor/samuel-0.2.1/.document
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
README.rdoc
lib/**/*.rb
bin/*
features/**/*.feature
LICENSE
5 changes: 5 additions & 0 deletions test/vendor/samuel-0.2.1/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.DS_Store
.yardoc
/coverage
/doc
/pkg
20 changes: 20 additions & 0 deletions test/vendor/samuel-0.2.1/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Copyright 2009 Chris Kampmeier

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
70 changes: 70 additions & 0 deletions test/vendor/samuel-0.2.1/README.rdoc
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
= Samuel

Samuel is a gem for automatic logging of your Net::HTTP requests. It's named for
the serial diarist Mr. Pepys, who was known to reliably record events both
quotidian and remarkable.

Should a Great Plague, Fire, or Whale befall an important external web service
you use, you'll be sure to have a tidy record of it.

== Usage:

When Rails is loaded, Samuel configures a few things automatically. So all you
need to do is this:

# config/environment.rb
config.gem "samuel"

And Samuel will automatically use Rails's logger and an ActiveRecord-like format.

For non-Rails projects, you'll have to manually configure logging, like this:

require 'samuel'
Samuel.logger = Logger.new('http_requests.log')

If you don't assign a logger, Samuel will configure a default logger on +STDOUT+.

== Configuration

There are two ways to specify configuration options for Samuel: global and
inline. Global configs look like this:

Samuel.config[:labels] = {"example.com" => "Example API"}
Samuel.config[:filtered_params] = :password

You should put global configuration somewhere early-on in your program. If
you're using Rails, <tt>config/initializers/samuel.rb</tt> will do the trick.

Alternatively, an inline configuration block temporarily overrides any global
configuration for a set of HTTP requests:

Samuel.with_config :label => "Twitter API" do
Net::HTTP.start("twitter.com") { |http| http.get("/help/test") }
end

Right now, there are three configuration changes you can make in either style:

* +:labels+ - This is a hash with domain substrings as keys and log labels as
values. If a request domain includes one of the domain substrings, the
corresponding label will be used for the first part of that log entry. By
default this is set to <tt>\{"" => "HTTP"}</tt>, so that all requests are
labeled with <tt>"HTTP Request"</tt>.
* +:label+ - As an alternative to the +:labels+ hash, this is simply a string.
If set, it takes precedence over any +:labels+ (by default, it's not set). It
gets <tt>"Request"</tt> appended to it as well -- so if you want your log to
always say +Twitter API Request+ instead of the default +HTTP Request+, you
can set this to <tt>"Twitter API"</tt>. I'd recommend using this setting
globally if you're only making requests to one service, or inline if you just
need to temporarily override the global +:labels+.
* +:filtered_params+ - This works just like Rails's +filter_parameter_logging+
method. Set it to a symbol, string, or array of them, and Samuel will filter
the value of query parameters that have any of these patterns as a substring
by replacing the value with <tt>[FILTERED]</tt> in your logs. By default, no
filtering is enabled.

Samuel logs successful HTTP requests at the +INFO+ level; Failed requests log at
the +WARN+ level. This isn't currently configurable, but it's on the list.

== License

Copyright 2009 Chris Kampmeier. See +LICENSE+ for details.
62 changes: 62 additions & 0 deletions test/vendor/samuel-0.2.1/Rakefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
require 'rubygems'
require 'rake'

begin
require 'jeweler'
Jeweler::Tasks.new do |gem|
gem.name = "samuel"
gem.summary = %Q{An automatic logger for HTTP requests in Ruby}
gem.description = %Q{An automatic logger for HTTP requests in Ruby. Adds Net::HTTP request logging to your Rails logs, and more.}
gem.email = "chris@kampers.net"
gem.homepage = "http://github.com/chrisk/samuel"
gem.authors = ["Chris Kampmeier"]
gem.rubyforge_project = "samuel"
gem.add_development_dependency "thoughtbot-shoulda"
gem.add_development_dependency "yard"
gem.add_development_dependency "mocha"
gem.add_development_dependency "fakeweb"
end
Jeweler::GemcutterTasks.new
Jeweler::RubyforgeTasks.new do |rubyforge|
rubyforge.doc_task = "yardoc"
end
rescue LoadError
puts "Jeweler (or a dependency) not available. Install it with: sudo gem install jeweler"
end

require 'rake/testtask'
Rake::TestTask.new(:test) do |test|
test.libs << 'lib' << 'test'
test.pattern = 'test/**/*_test.rb'
test.verbose = false
test.warning = true
end

begin
require 'rcov/rcovtask'
Rcov::RcovTask.new do |test|
test.libs << 'test'
test.pattern = 'test/**/*_test.rb'
test.rcov_opts << "--sort coverage"
test.rcov_opts << "--exclude gems"
test.verbose = false
test.warning = true
end
rescue LoadError
task :rcov do
abort "RCov is not available. In order to run rcov, you must: sudo gem install spicycode-rcov"
end
end

task :test => :check_dependencies

task :default => :test

begin
require 'yard'
YARD::Rake::YardocTask.new
rescue LoadError
task :yardoc do
abort "YARD is not available. In order to run yardoc, you must: sudo gem install yard"
end
end
1 change: 1 addition & 0 deletions test/vendor/samuel-0.2.1/VERSION
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
0.2.1
52 changes: 52 additions & 0 deletions test/vendor/samuel-0.2.1/lib/samuel.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
require "logger"
require "net/http"
require "net/https"
require "benchmark"

require "samuel/net_http"
require "samuel/request"


module Samuel
extend self

attr_writer :config, :logger

def logger
@logger = nil if !defined?(@logger)
return @logger if !@logger.nil?

if defined?(RAILS_DEFAULT_LOGGER)
@logger = RAILS_DEFAULT_LOGGER
else
@logger = Logger.new(STDOUT)
end
end

def config
Thread.current[:__samuel_config] ? Thread.current[:__samuel_config] : @config
end

def log_request(http, request, &block)
request = Request.new(http, request, block)
request.perform_and_log!
request.response
end

def with_config(options = {})
original_config = config.dup
nested = !Thread.current[:__samuel_config].nil?

Thread.current[:__samuel_config] = original_config.merge(options)
yield
Thread.current[:__samuel_config] = nested ? original_config : nil
end

def reset_config
Thread.current[:__samuel_config] = nil
@config = {:label => nil, :labels => {"" => "HTTP"}, :filtered_params => []}
end

end

Samuel.reset_config
10 changes: 10 additions & 0 deletions test/vendor/samuel-0.2.1/lib/samuel/net_http.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
class Net::HTTP

alias request_without_samuel request
def request(req, body = nil, &block)
Samuel.log_request(self, req) do
request_without_samuel(req, body, &block)
end
end

end
Loading

0 comments on commit 22533e2

Please sign in to comment.