Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 330 lines (275 sloc) 11.439 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
require File.dirname(__FILE__) + '/helper'

class ActionControllerCatcherTest < Test::Unit::TestCase

  include DefinesConstants

  def setup
    super
    reset_config
    HoptoadNotifier.sender = CollectingSender.new
    define_constant('RAILS_ROOT', '/path/to/rails/root')
  end

  def ignore(exception_class)
    HoptoadNotifier.configuration.ignore << exception_class
  end

  def build_controller_class(&definition)
    returning Class.new(ActionController::Base) do |klass|
      klass.__send__(:include, HoptoadNotifier::Rails::ActionControllerCatcher)
      klass.class_eval(&definition) if definition
      define_constant('HoptoadTestController', klass)
    end
  end

  def assert_sent_hash(hash, xpath)
    hash.each do |key, value|
      element_xpath = "#{xpath}/var[@key = '#{key}']"
      if value.respond_to?(:to_hash)
        assert_sent_hash value.to_hash, element_xpath
      else
        assert_sent_element value, element_xpath
      end
    end
  end

  def assert_sent_element(value, xpath)
    assert_valid_node last_sent_notice_document, xpath, stringify_array_elements(value).to_s
  end

  def stringify_array_elements(data)
    if data.respond_to?(:to_ary)
      data.collect do |value|
        stringify_array_elements(value)
      end
    else
      data.to_s
    end
  end

  def assert_sent_request_info_for(request)
    params = request.parameters.to_hash
    assert_sent_hash params, '/notice/request/params'
    assert_sent_element params['controller'], '/notice/request/component'
    assert_sent_element params['action'], '/notice/request/action'
    assert_sent_element url_from_request(request), '/notice/request/url'
    assert_sent_hash request.env, '/notice/request/cgi-data'
  end

  def url_from_request(request)
    url = "#{request.protocol}#{request.host}"

    unless [80, 443].include?(request.port)
      url << ":#{request.port}"
    end

    url << request.request_uri
    url
  end

  def sender
    HoptoadNotifier.sender
  end

  def last_sent_notice_xml
    sender.collected.last
  end

  def last_sent_notice_document
    assert_not_nil xml = last_sent_notice_xml, "No xml was sent"
    Nokogiri::XML.parse(xml)
  end

  def process_action(opts = {}, &action)
    opts[:request] ||= ActionController::TestRequest.new
    opts[:response] ||= ActionController::TestResponse.new
    klass = build_controller_class do
      cattr_accessor :local
      define_method(:index, &action)
      def local_request?
        local
      end
    end
    if opts[:filters]
      klass.filter_parameter_logging *opts[:filters]
    end
    if opts[:user_agent]
      if opts[:request].respond_to?(:user_agent=)
        opts[:request].user_agent = opts[:user_agent]
      else
        opts[:request].env["HTTP_USER_AGENT"] = opts[:user_agent]
      end
    end
    if opts[:port]
      opts[:request].port = opts[:port]
    end
    klass.consider_all_requests_local = opts[:all_local]
    klass.local = opts[:local]
    controller = klass.new
    controller.stubs(:rescue_action_in_public_without_hoptoad)
    opts[:request].query_parameters = opts[:request].query_parameters.merge(opts[:params] || {})
    opts[:request].session = ActionController::TestSession.new(opts[:session] || {})
    controller.process(opts[:request], opts[:response])
    controller
  end

  def process_action_with_manual_notification(args = {})
    process_action(args) do
      notify_hoptoad(:error_message => 'fail')
      # Rails will raise a template error if we don't render something
      render :nothing => true
    end
  end

  def process_action_with_automatic_notification(args = {})
    process_action(args) { raise "Hello" }
  end

  should "deliver notices from exceptions raised in public requests" do
    process_action_with_automatic_notification
    assert_caught_and_sent
  end

  should "not deliver notices from exceptions in local requests" do
    process_action_with_automatic_notification(:local => true)
    assert_caught_and_not_sent
  end

  should "not deliver notices from exceptions when all requests are local" do
    process_action_with_automatic_notification(:all_local => true)
    assert_caught_and_not_sent
  end

  should "not deliver notices from actions that don't raise" do
    controller = process_action { render :text => 'Hello' }
    assert_caught_and_not_sent
    assert_equal 'Hello', controller.response.body
  end

  should "not deliver ignored exceptions raised by actions" do
    ignore(RuntimeError)
    process_action_with_automatic_notification
    assert_caught_and_not_sent
  end

  should "deliver ignored exception raised manually" do
    ignore(RuntimeError)
    process_action_with_manual_notification
    assert_caught_and_sent
  end

  should "deliver manually sent notices in public requests" do
    process_action_with_manual_notification
    assert_caught_and_sent
  end

  should "not deliver manually sent notices in local requests" do
    process_action_with_manual_notification(:local => true)
    assert_caught_and_not_sent
  end

  should "not deliver manually sent notices when all requests are local" do
    process_action_with_manual_notification(:all_local => true)
    assert_caught_and_not_sent
  end

  should "continue with default behavior after delivering an exception" do
    controller = process_action_with_automatic_notification(:public => true)
    # TODO: can we test this without stubbing?
    assert_received(controller, :rescue_action_in_public_without_hoptoad)
  end

  should "not create actions from Hoptoad methods" do
    controller = build_controller_class.new
    assert_equal [], HoptoadNotifier::Rails::ActionControllerCatcher.instance_methods
  end

  should "ignore exceptions when user agent is being ignored by regular expression" do
    HoptoadNotifier.configuration.ignore_user_agent_only = [/Ignored/]
    process_action_with_automatic_notification(:user_agent => 'ShouldBeIgnored')
    assert_caught_and_not_sent
  end

  should "ignore exceptions when user agent is being ignored by string" do
    HoptoadNotifier.configuration.ignore_user_agent_only = ['IgnoredUserAgent']
    process_action_with_automatic_notification(:user_agent => 'IgnoredUserAgent')
    assert_caught_and_not_sent
  end

  should "not ignore exceptions when user agent is not being ignored" do
    HoptoadNotifier.configuration.ignore_user_agent_only = ['IgnoredUserAgent']
    process_action_with_automatic_notification(:user_agent => 'NonIgnoredAgent')
    assert_caught_and_sent
  end

  should "send session data for manual notifications" do
    data = { 'one' => 'two' }
    process_action_with_manual_notification(:session => data)
    assert_sent_hash data, "/notice/request/session"
  end

  should "send session data for automatic notification" do
    data = { 'one' => 'two' }
    process_action_with_automatic_notification(:session => data)
    assert_sent_hash data, "/notice/request/session"
  end

  should "send request data for manual notification" do
    params = { 'controller' => "hoptoad_test", 'action' => "index" }
    controller = process_action_with_manual_notification(:params => params)
    assert_sent_request_info_for controller.request
  end

  should "send request data for manual notification with non-standard port" do
    params = { 'controller' => "hoptoad_test", 'action' => "index" }
    controller = process_action_with_manual_notification(:params => params, :port => 81)
    assert_sent_request_info_for controller.request
  end

  should "send request data for automatic notification" do
    params = { 'controller' => "hoptoad_test", 'action' => "index" }
    controller = process_action_with_automatic_notification(:params => params)
    assert_sent_request_info_for controller.request
  end

  should "send request data for automatic notification with non-standard port" do
    params = { 'controller' => "hoptoad_test", 'action' => "index" }
    controller = process_action_with_automatic_notification(:params => params, :port => 81)
    assert_sent_request_info_for controller.request
  end

  should "use standard rails logging filters on params and session and env" do
    filtered_params = { "abc" => "123",
                        "def" => "456",
                        "ghi" => "[FILTERED]" }
    filtered_session = { "abc" => "123",
                         "ghi" => "[FILTERED]" }
    ENV['ghi'] = 'abc'
    filtered_env = { 'ghi' => '[FILTERED]' }
    filtered_cgi = { 'REQUEST_METHOD' => '[FILTERED]' }

    process_action_with_automatic_notification(:filters => [:ghi, :request_method],
                                               :params => { "abc" => "123",
                                                            "def" => "456",
                                                            "ghi" => "789" },
                                               :session => { "abc" => "123",
                                                             "ghi" => "789" })
    assert_sent_hash filtered_params, '/notice/request/params'
    assert_sent_hash filtered_cgi, '/notice/request/cgi-data'
    assert_sent_hash filtered_session, '/notice/request/session'
  end

  context "for a local error with development lookup enabled" do
    setup do
      HoptoadNotifier.configuration.development_lookup = true
      HoptoadNotifier.stubs(:build_lookup_hash_for).returns({ :awesome => 2 })

      @controller = process_action_with_automatic_notification(:local => true)
      @response = @controller.response
    end

    should "append custom CSS and JS to response body for a local error" do
      assert_match /text\/css/, @response.body
      assert_match /text\/javascript/, @response.body
    end

    should "contain host, API key and notice JSON" do
      assert_match HoptoadNotifier.configuration.host.to_json, @response.body
      assert_match HoptoadNotifier.configuration.api_key.to_json, @response.body
      assert_match ({ :awesome => 2 }).to_json, @response.body
    end
  end

  context "for a local error with development lookup disabled" do
    setup do
      HoptoadNotifier.configuration.development_lookup = false

      @controller = process_action_with_automatic_notification(:local => true)
      @response = @controller.response
    end

    should "not append custom CSS and JS to response for a local error" do
      assert_no_match /text\/css/, @response.body
      assert_no_match /text\/javascript/, @response.body
    end
  end

  should "call session.to_hash if available" do
    hash_data = {:key => :value}

    session = ActionController::TestSession.new
    ActionController::TestSession.stubs(:new).returns(session)
    session.stubs(:to_hash).returns(hash_data)

    process_action_with_automatic_notification
    assert_received(session, :to_hash)
    assert_received(session, :data) { |expect| expect.never }
    assert_caught_and_sent
  end

  should "call session.data if session.to_hash is undefined" do
    hash_data = {:key => :value}

    session = ActionController::TestSession.new
    ActionController::TestSession.stubs(:new).returns(session)
    session.stubs(:data).returns(hash_data)
    if session.respond_to?(:to_hash)
      class << session
        undef to_hash
      end
    end

    process_action_with_automatic_notification
    assert_received(session, :to_hash) { |expect| expect.never }
    assert_received(session, :data) { |expect| expect.at_least_once }
    assert_caught_and_sent
  end

end
Something went wrong with that request. Please try again.