net_observer 0.2.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,21 @@
1
+ Copyright (c) 2004-2010 David Heinemeier Hansson
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining
4
+ a copy of this software and associated documentation files (the
5
+ "Software"), to deal in the Software without restriction, including
6
+ without limitation the rights to use, copy, modify, merge, publish,
7
+ distribute, sublicense, and/or sell copies of the Software, and to
8
+ permit persons to whom the Software is furnished to do so, subject to
9
+ the following conditions:
10
+
11
+ The above copyright notice and this permission notice shall be
12
+ included in all copies or substantial portions of the Software.
13
+
14
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21
+
@@ -0,0 +1,37 @@
1
+ Description
2
+ -----------
3
+
4
+ Net Observer lets you observe outgoing Net::HTTP requests that your
5
+ Ruby application makes. This can be useful when it fails at the remote
6
+ end and you want to report the exact request that caused the problem.
7
+
8
+ Documentation
9
+ -------------
10
+
11
+ Create a `NetObserver::Logger` instance to log the requests and
12
+ reponse. Use the `NetObserver::Base` class to observe the requests in
13
+ another way.
14
+
15
+ Examples
16
+ --------
17
+
18
+ This:
19
+
20
+ require "net_observer"
21
+ require "logger"
22
+
23
+ log = Logger.new(STDOUT)
24
+ net_logger = NetObserver::Logger.new log
25
+ Net::HTTP.get URI.parse("http://google.com/search?q=wikipedia")
26
+
27
+ produces:
28
+
29
+ I, [2010-12-14T12:42:50.570907 #23968] INFO -- : get request for url http://google.com:80/search?q=wikipedia with method: GET with body
30
+ W, [2010-12-14T12:42:50.579045 #23968] WARN -- : get response: #<Net::HTTPForbidden 403 Forbidden readbody=true> with body <html><head>[...]
31
+
32
+ Development
33
+ -----------
34
+
35
+ NetObserver was conceived by [Josef Reidinger](mailto:jreidinger@suse.cz).
36
+
37
+ The repository is at GitHub: <https://github.com/mvidner/net-observer>.
@@ -0,0 +1,71 @@
1
+ require 'rake' # emacs: -*- ruby -*-
2
+ require 'rake/rdoctask'
3
+ require 'rake/testtask'
4
+
5
+
6
+ task :default => "test"
7
+
8
+ namespace :test do
9
+ desc "Test all classes"
10
+ Rake::TestTask.new(:all) do |t|
11
+ t.libs << "test"
12
+ t.pattern = 'test/*_test.rb'
13
+ t.verbose = true
14
+ end
15
+ end
16
+
17
+ desc "Run all the unit tests"
18
+ task :test do
19
+ Rake::Task["test:all"].invoke
20
+ end
21
+
22
+ desc 'Generate documentation.'
23
+ Rake::RDocTask.new(:rdoc) do |rdoc|
24
+ rdoc.rdoc_dir = 'rdoc'
25
+ rdoc.title = 'net-observer'
26
+ rdoc.options << '--line-numbers' << "--main" << "README.rdoc"
27
+ rdoc.rdoc_files.include('README.rdoc')
28
+ rdoc.rdoc_files.include('lib/**/*.rb')
29
+ end
30
+
31
+ begin
32
+ require 'jeweler'
33
+ Jeweler::Tasks.new do |gem|
34
+ gem.name = %q{net_observer}
35
+ gem.summary = %q{Gem allow easy observation of network communication in ruby via ruby network library}
36
+ gem.description = %q{Gem allow easy observation of network communication in ruby via ruby network library. It is useful to log low level information for abstract layers like ActiveResource. It contain predefined observers for logging and to remember last request.}
37
+
38
+ gem.files = FileList['[A-Z]*', 'lib/**/*.rb', 'test/**/*.rb']
39
+ gem.require_path = 'lib'
40
+ gem.test_files = Dir[*['test/**/*_test.rb']]
41
+
42
+ gem.has_rdoc = true
43
+ gem.extra_rdoc_files = ["README.md"]
44
+ gem.rdoc_options = ['--line-numbers', "--main", "README.md"]
45
+
46
+ gem.authors = ["Flavio Castelli", "Josef Reidinger", "Martin Vidner"]
47
+ gem.email = %w(flavio@castelli.name jreidinger@suse.cz mvidner@suse.cz)
48
+ gem.homepage = "http://github.com/mvidner/net-observer"
49
+
50
+ gem.add_development_dependency "fakeweb"
51
+ gem.add_development_dependency "yard"
52
+
53
+ gem.platform = Gem::Platform::RUBY
54
+ end
55
+ Jeweler::GemcutterTasks.new
56
+ rescue LoadError
57
+ puts "Jeweler not available. Install it with: gem install jeweler"
58
+ end
59
+
60
+ desc "Clean files generated by rake tasks"
61
+ task :clobber => [:clobber_rdoc]
62
+
63
+ begin
64
+ require "yard"
65
+ YARD::Rake::YardocTask.new do |t|
66
+ t.files = ['lib/**/*.rb'] # optional
67
+ t.options = [] # optional
68
+ end
69
+ rescue LoadError
70
+ puts "YARD not available. Install it with: gem install yard"
71
+ end
data/VERSION ADDED
@@ -0,0 +1 @@
1
+ 0.2.0
@@ -0,0 +1,17 @@
1
+ require 'net_observer/base'
2
+ require 'net/http'
3
+
4
+ module Net
5
+ class HTTP
6
+ alias_method :orig_request, :request
7
+
8
+ # hook into net code to get request and response for it
9
+ def request(req, body = nil, &block) # :yield: +response+
10
+ return orig_request req, body, &block unless started? #if not started don't log twice
11
+ NetObserver::Base.instance.request_data(self, req, body)
12
+ res = orig_request req, body, &block
13
+ NetObserver::Base.instance.response_data(self, res)
14
+ res
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,2 @@
1
+ require 'net_observer/logger'
2
+ require 'net_observer/last_request'
@@ -0,0 +1,41 @@
1
+ require "observer"
2
+ require "singleton"
3
+ require "core-ext/net/http"
4
+
5
+ module NetObserver
6
+ # == Base Class ==
7
+ #
8
+ # Basic object for observing network communication. It is singleton, as it doesn't make sense to have more then one
9
+ # object which observe network. Object is observable, so anyone could attach own object which contain update method
10
+ # for all network objects.
11
+ #
12
+ # Parameters for update command in observers:
13
+ #
14
+ # @param(Symbol) type of request, can be :request or :response
15
+ #
16
+ # @param(Net::HttpRequest) request send or received from network
17
+ #
18
+ # @param(String) body body used/received in request
19
+ #
20
+ # @param(Net::HTTP,Net::HTTPS) connection connection on which is called method
21
+ #
22
+ # @see NetObserver::Logger for example usage
23
+ class Base
24
+ include Observable
25
+ include Singleton
26
+
27
+ # @private
28
+ # internal method for network hook
29
+ def request_data(connection, request,body)
30
+ changed
31
+ notify_observers(:request,request,body, connection)
32
+ end
33
+ # @private
34
+ # internal method for network hook
35
+ def response_data(connection, response)
36
+ changed
37
+ body = response.respond_to?(:body) ? response.body : ""
38
+ notify_observers(:response,response,body, connection)
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,36 @@
1
+ require "net_observer/base"
2
+ require "singleton"
3
+
4
+ module NetObserver
5
+ # == Logger class
6
+ # It can be used to pass network communication into logger.
7
+ # It report requests and success response as info and failed one as
8
+ # warn message.
9
+ # @example Set simple logging to console
10
+ # NetObserver::Logger.new Logger.new STDOUT
11
+ class LastRequest
12
+ include Singleton
13
+ attr_reader :last_request
14
+ # register logger to receiving infos about network communication
15
+ # @param(Logger) logger which recieve informations about communication
16
+ def enable
17
+ @last_request = nil
18
+ Base.instance.add_observer(self)
19
+ end
20
+
21
+ def disable
22
+ @last_request = nil
23
+ Base.instance.delete_observer(self)
24
+ end
25
+ # methods to receive information about connection. Needed to allow itself to register agains Base
26
+ # @see NetObserver::Base for parameters details
27
+ def update(type, request, body, connection)
28
+ case type
29
+ when :response
30
+ return #don't care
31
+ when :request
32
+ @last_request = { :connection => connection, :request => request, :body => (request.body || body)}
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,33 @@
1
+ require "net_observer/base"
2
+
3
+ module NetObserver
4
+ # == Logger class
5
+ # It can be used to pass network communication into logger.
6
+ # It report requests and success response as info and failed one as
7
+ # warn message.
8
+ # @example Set simple logging to console
9
+ # NetObserver::Logger.new Logger.new STDOUT
10
+ class Logger
11
+ # register logger to receiving infos about network communication
12
+ # @param(Logger) logger which recieve informations about communication
13
+ def initialize(logger)
14
+ @logger = logger
15
+ Base.instance.add_observer(self)
16
+ end
17
+
18
+ # methods to receive information about connection. Needed to allow itself to register agains Base
19
+ # @see NetObserver::Base for parameters details
20
+ def update(type, request, body, connection)
21
+ case type
22
+ when :response
23
+ method = request.kind_of?(Net::HTTPSuccess) ? :info : :warn
24
+ @logger.send method, "get response: #{request.inspect} with body #{body}"
25
+ when :request
26
+ port = ""
27
+ port = ":#{connection.port}" if (connection.port.to_i != (connection.use_ssl? ? 443 : 80))
28
+ url = "#{connection.use_ssl? ? "https" : "http"}://#{connection.address}#{port}"
29
+ @logger.info "get request for url #{url}#{request.path} with method: #{request.method} with body #{request.body || body}"
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,33 @@
1
+ #!/usr/bin/env ruby
2
+ require 'rubygems'
3
+ require 'mocha'
4
+ require File.join File.dirname(__FILE__),'test_helper'
5
+ require "logger"
6
+ require "net_observer"
7
+
8
+ class BasicTest < Test::Unit::TestCase
9
+ def setup
10
+ FakeWeb.allow_net_connect = false
11
+ end
12
+
13
+ def test_simple_request
14
+ assert_nothing_raised do
15
+ url = "http://google.com/search?q=wikipedia"
16
+ log = Logger.new(STDOUT)
17
+ net_logger = NetObserver::Logger.new log
18
+
19
+ reply = File.read(File.join( File.dirname(__FILE__), "mocked_responses", "wikipedia"))
20
+ html_body = reply[reply.index("<html>")..reply.size]
21
+ log.expects(:info).with("get request for url #{url} with method: GET with body ").once
22
+
23
+ # make sure response contents are printed too
24
+ log.expects(:warn).with() do |value|
25
+ value.include?(html_body)
26
+ end
27
+
28
+ register_fake_response :get, url , "wikipedia"
29
+
30
+ Net::HTTP.get URI.parse(url)
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,47 @@
1
+ #!/usr/bin/env ruby
2
+ require 'rubygems'
3
+ require 'mocha'
4
+ require File.join File.dirname(__FILE__),'test_helper'
5
+ require "net_observer"
6
+
7
+ class LastRequestTest < Test::Unit::TestCase
8
+ def setup
9
+ FakeWeb.allow_net_connect = false
10
+ end
11
+
12
+ def test_request_url
13
+ assert_nothing_raised do
14
+ url = "http://google.com/search?q=wikipedia"
15
+ NetObserver::LastRequest.instance.enable
16
+
17
+ register_fake_response :get, url , "wikipedia"
18
+
19
+ Net::HTTP.get URI.parse(url)
20
+
21
+ last_request = NetObserver::LastRequest.instance.last_request
22
+ site = "#{last_request[:connection].use_ssl? ? "https" : "http"}://#{last_request[:connection].address}"
23
+ assert_equal url, site+last_request[:request].path
24
+ end
25
+ end
26
+
27
+ def test_stop_catching_request
28
+ assert_nothing_raised do
29
+ url = "http://google.com/search?q=wikipedia"
30
+ NetObserver::LastRequest.instance.enable
31
+
32
+ register_fake_response :get, url , "wikipedia"
33
+
34
+ Net::HTTP.get URI.parse(url)
35
+
36
+ last_request = NetObserver::LastRequest.instance.last_request
37
+ assert_not_nil last_request
38
+
39
+ NetObserver::LastRequest.instance.disable
40
+ Net::HTTP.get URI.parse(url)
41
+ last_request = NetObserver::LastRequest.instance.last_request
42
+ assert_nil last_request
43
+
44
+ end
45
+ end
46
+
47
+ end
@@ -0,0 +1,13 @@
1
+ $LOAD_PATH << (File.join(File.dirname(__FILE__), '..', 'lib'))
2
+ require 'rubygems'
3
+ require "test/unit"
4
+ require 'fakeweb'
5
+
6
+ class Test::Unit::TestCase
7
+ def register_fake_response type, url, response_file=nil
8
+ response_file = url if response_file.nil?
9
+ response = File.read(File.join( File.dirname(__FILE__),
10
+ "mocked_responses", response_file))
11
+ FakeWeb.register_uri(type, url, :response => response)
12
+ end
13
+ end
metadata ADDED
@@ -0,0 +1,113 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: net_observer
3
+ version: !ruby/object:Gem::Version
4
+ hash: 23
5
+ prerelease: false
6
+ segments:
7
+ - 0
8
+ - 2
9
+ - 0
10
+ version: 0.2.0
11
+ platform: ruby
12
+ authors:
13
+ - Flavio Castelli
14
+ - Josef Reidinger
15
+ - Martin Vidner
16
+ autorequire:
17
+ bindir: bin
18
+ cert_chain: []
19
+
20
+ date: 2010-12-21 00:00:00 +01:00
21
+ default_executable:
22
+ dependencies:
23
+ - !ruby/object:Gem::Dependency
24
+ name: fakeweb
25
+ prerelease: false
26
+ requirement: &id001 !ruby/object:Gem::Requirement
27
+ none: false
28
+ requirements:
29
+ - - ">="
30
+ - !ruby/object:Gem::Version
31
+ hash: 3
32
+ segments:
33
+ - 0
34
+ version: "0"
35
+ type: :development
36
+ version_requirements: *id001
37
+ - !ruby/object:Gem::Dependency
38
+ name: yard
39
+ prerelease: false
40
+ requirement: &id002 !ruby/object:Gem::Requirement
41
+ none: false
42
+ requirements:
43
+ - - ">="
44
+ - !ruby/object:Gem::Version
45
+ hash: 3
46
+ segments:
47
+ - 0
48
+ version: "0"
49
+ type: :development
50
+ version_requirements: *id002
51
+ description: Gem allow easy observation of network communication in ruby via ruby network library. It is useful to log low level information for abstract layers like ActiveResource. It contain predefined observers for logging and to remember last request.
52
+ email:
53
+ - flavio@castelli.name
54
+ - jreidinger@suse.cz
55
+ - mvidner@suse.cz
56
+ executables: []
57
+
58
+ extensions: []
59
+
60
+ extra_rdoc_files:
61
+ - README.md
62
+ files:
63
+ - MIT-LICENSE
64
+ - README.md
65
+ - Rakefile
66
+ - VERSION
67
+ - lib/core-ext/net/http.rb
68
+ - lib/net_observer.rb
69
+ - lib/net_observer/base.rb
70
+ - lib/net_observer/last_request.rb
71
+ - lib/net_observer/logger.rb
72
+ - test/basic_test.rb
73
+ - test/last_request_test.rb
74
+ - test/test_helper.rb
75
+ has_rdoc: true
76
+ homepage: http://github.com/mvidner/net-observer
77
+ licenses: []
78
+
79
+ post_install_message:
80
+ rdoc_options:
81
+ - --line-numbers
82
+ - --main
83
+ - README.md
84
+ require_paths:
85
+ - lib
86
+ required_ruby_version: !ruby/object:Gem::Requirement
87
+ none: false
88
+ requirements:
89
+ - - ">="
90
+ - !ruby/object:Gem::Version
91
+ hash: 3
92
+ segments:
93
+ - 0
94
+ version: "0"
95
+ required_rubygems_version: !ruby/object:Gem::Requirement
96
+ none: false
97
+ requirements:
98
+ - - ">="
99
+ - !ruby/object:Gem::Version
100
+ hash: 3
101
+ segments:
102
+ - 0
103
+ version: "0"
104
+ requirements: []
105
+
106
+ rubyforge_project:
107
+ rubygems_version: 1.3.7
108
+ signing_key:
109
+ specification_version: 3
110
+ summary: Gem allow easy observation of network communication in ruby via ruby network library
111
+ test_files:
112
+ - test/basic_test.rb
113
+ - test/last_request_test.rb