Project

General

Profile

Bug #12614 ยป small_test_newrelic_rpm.patch

wanabe (_ wanabe), 08/14/2016 06:01 AM

View differences:

newrelic_rpm.gemspec
47 47
  s.add_development_dependency 'yard'
48 48
  s.add_development_dependency 'rails', '~> 3.2.13'
49 49
  s.add_development_dependency 'pry', '~> 0.9.12'
50
  s.add_development_dependency 'pry-stack_explorer'
51
  s.add_development_dependency 'pry-byebug'
50 52
  s.add_development_dependency 'hometown', '~> 0.2.5'
51 53

  
52 54
  # Only let Guard run on newer Rubies
test/multiverse/suites/rails/action_cable_test.rb
1
# encoding: utf-8
2
# This file is distributed under New Relic's license terms.
3
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
4

  
5
begin
6
  require 'action_cable'
7
rescue LoadError
8
end
9

  
10
if defined?(ActionCable::Channel)
11

  
12
require 'stringio'
13
require 'logger'
14
require 'json'
15

  
16
class ActionCableTest < Minitest::Test
17
include MultiverseHelpers
18

  
19
  class TestConnection
20
    attr_reader :transmissions, :identifiers, :logger
21

  
22
    def initialize
23
      @transmissions = []
24
      @identifiers = []
25
      @logger = Logger.new StringIO.new
26
    end
27

  
28
    def transmit data
29
      @transmissions << data
30
    end
31

  
32
    def last_transmission
33
      JSON.parse @transmissions.last
34
    end
35
  end
36

  
37
  class TestChannel < ActionCable::Channel::Base
38
    def test_action data
39
      transmit data['content']
40
    end
41

  
42
    def boom data
43
      raise StandardError.new("Boom!")
44
    end
45
  end
46

  
47
  setup_and_teardown_agent do
48
    @connection = TestConnection.new
49
    @channel = TestChannel.new @connection, "{id: 1}"
50
  end
51

  
52
  def test_creates_trace
53
    @channel.perform_action({ 'action' => :test_action, 'content' => 'hello' })
54

  
55
    last_sample = NewRelic::Agent.instance.transaction_sampler.last_sample
56
    assert_equal('Controller/ActionCable/ActionCableTest::TestChannel/test_action', last_sample.transaction_name)
57
  end
58

  
59
  def test_creates_web_transaction
60
    @channel.perform_action({ 'action'=> :test_action, 'content' => 'hello' })
61

  
62
    expected_metrics = {
63
      'HttpDispatcher' => { :call_count => 1 },
64
      'Controller/ActionCable/ActionCableTest::TestChannel/test_action' => { :call_count => 1}
65
    }
66

  
67
    assert_metrics_recorded expected_metrics
68
  end
69

  
70
  def test_action_with_error_is_noticed_by_agent
71
    @channel.perform_action({ 'action'=> :boom }) rescue nil
72

  
73
    error_trace = last_traced_error
74

  
75
    assert_equal "StandardError", error_trace.exception_class_name
76
    assert_equal "Boom!", error_trace.message
77
    assert_equal "Controller/ActionCable/ActionCableTest::TestChannel/boom", error_trace.path
78
  end
79
end
80

  
81
end
test/multiverse/suites/rails/action_controller_live_rum_test.rb
1
# encoding: utf-8
2
# This file is distributed under New Relic's license terms.
3
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
4

  
5
require './app'
6

  
7
if defined?(ActionController::Live)
8

  
9
class UndeadController < ApplicationController
10
  RESPONSE_BODY = "<html><head></head><body>Brains!</body></html>"
11

  
12
  def brains
13
    render :inline => RESPONSE_BODY
14
  end
15
end
16

  
17
class LiveController < UndeadController
18
  include ActionController::Live
19
end
20

  
21
class ActionControllerLiveRumTest < RailsMultiverseTest
22
  include MultiverseHelpers
23

  
24
  JS_LOADER = "JS LOADER IN DA HOUSE"
25

  
26
  setup_and_teardown_agent(:js_agent_loader => JS_LOADER, :beacon => "beacon", :browser_key => "key")
27

  
28
  def test_rum_instrumentation_when_not_streaming
29
    get '/undead/brains'
30
    assert_includes(response.body, JS_LOADER)
31
  end
32

  
33
  def test_excludes_rum_instrumentation_when_streaming_with_action_controller_live
34
    get '/live/brains'
35
    assert_equal(LiveController::RESPONSE_BODY, response.body)
36
  end
37
end
38

  
39
end
test/multiverse/suites/rails/activejob_test.rb
1
# encoding: utf-8
2
# This file is distributed under New Relic's license terms.
3
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
4

  
5
require File.expand_path(File.join(__FILE__, '..', 'app'))
6

  
7
require 'logger'
8
require 'stringio'
9

  
10
# ActiveJob is in Rails 4.2+, so make sure we're on an allowed version before
11
# we try to load. Previously just tried to require it, but that had load issues
12
# on Rubinius.
13
if Rails::VERSION::STRING >= "4.2.0"
14

  
15
require 'active_job'
16

  
17
ActiveJob::Base.queue_adapter = :inline
18

  
19
class MyJob < ActiveJob::Base
20
  def perform
21
    # Nothing needed!
22
  end
23
end
24

  
25
class MyJobWithAlternateQueue < ActiveJob::Base
26
  queue_as :my_jobs
27

  
28
  def perform
29
  end
30
end
31

  
32
class MyJobWithParams < ActiveJob::Base
33
  def self.last_params
34
    @@last_params
35
  end
36

  
37
  def perform(first, last)
38
    @@last_params = [first, last]
39
  end
40
end
41

  
42
class MyFailure < ActiveJob::Base
43

  
44
  def perform
45
    raise ArgumentError.new("No it isn't!")
46
  end
47
end
48

  
49
class ActiveJobTest < Minitest::Test
50

  
51
  include MultiverseHelpers
52

  
53
  setup_and_teardown_agent do
54
    @log = StringIO.new
55
    ActiveJob::Base.logger = ::Logger.new(@log)
56
  end
57

  
58
  def after_teardown
59
    unless passed?
60
      puts "\nEmitting log from failure: #{self.name}"
61
      @log.rewind
62
      puts @log.read
63
    end
64
  end
65

  
66
  ENQUEUE_PREFIX = "MessageBroker/ActiveJob::Inline/Queue/Produce/Named"
67
  PERFORM_PREFIX = "MessageBroker/ActiveJob::Inline/Queue/Consume/Named"
68

  
69
  PERFORM_TRANSACTION_NAME   = 'OtherTransaction/ActiveJob::Inline/MyJob/execute'
70
  PERFORM_TRANSACTION_ROLLUP = 'OtherTransaction/ActiveJob::Inline/all'
71

  
72
  def test_record_enqueue_metrics
73
    in_web_transaction do
74
      MyJob.perform_later
75
    end
76

  
77
    assert_metrics_recorded("#{ENQUEUE_PREFIX}/default")
78
  end
79

  
80
  def test_record_enqueue_metrics_with_alternate_queue
81
    in_web_transaction do
82
      MyJobWithAlternateQueue.perform_later
83
    end
84

  
85
    assert_metrics_recorded("#{ENQUEUE_PREFIX}/my_jobs")
86
  end
87

  
88
  def test_record_perform_metrics_in_web
89
    in_web_transaction do
90
      MyJob.perform_later
91
    end
92

  
93
    assert_metrics_recorded("#{PERFORM_PREFIX}/default")
94
  end
95

  
96
  def test_record_perform_metrics_with_alternate_queue_in_web
97
    in_web_transaction do
98
      MyJobWithAlternateQueue.perform_later
99
    end
100

  
101
    assert_metrics_recorded("#{PERFORM_PREFIX}/my_jobs")
102
  end
103

  
104
  def test_doesnt_record_perform_metrics_from_background
105
    in_background_transaction do
106
      MyJob.perform_later
107
    end
108

  
109
    assert_metrics_not_recorded("#{PERFORM_PREFIX}/default")
110
  end
111

  
112
  def test_starts_transaction_if_there_isnt_one
113
    MyJob.perform_later
114
    assert_metrics_recorded([PERFORM_TRANSACTION_ROLLUP,
115
                             PERFORM_TRANSACTION_NAME])
116
  end
117

  
118
  def test_nests_other_transaction_if_already_running
119
    in_background_transaction do
120
      MyJob.perform_later
121
    end
122

  
123
    assert_metrics_recorded([PERFORM_TRANSACTION_ROLLUP,
124
                             PERFORM_TRANSACTION_NAME])
125
  end
126

  
127
  # If running tasks inline, either in a dev environment or from
128
  # misconfiguration we shouldn't accidentally rename our web transaction
129
  def test_doesnt_nest_transactions_if_in_web
130
    in_web_transaction do
131
      MyJob.perform_later
132
    end
133

  
134
    assert_metrics_not_recorded([PERFORM_TRANSACTION_ROLLUP,
135
                                 PERFORM_TRANSACTION_NAME])
136
  end
137

  
138
  def test_doesnt_interfere_with_params_on_job
139
    MyJobWithParams.perform_later("1", "2")
140
    assert_equal(["1", "2"], MyJobWithParams.last_params)
141
  end
142

  
143
  def test_captures_errors
144
    # Because we're processing inline, we get the error raised here
145
    assert_raises ArgumentError do
146
      MyFailure.perform_later
147
    end
148
    assert_metrics_recorded(["Errors/all"])
149
  end
150
end
151

  
152
end
test/multiverse/suites/rails/bad_instrumentation_test.rb
1
# encoding: utf-8
2
# This file is distributed under New Relic's license terms.
3
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
4

  
5
require './app'
6

  
7
class BadInstrumentationController < ApplicationController
8
  # This action is intended to simulate a chunk of instrumentation that pushes
9
  # a traced method frame, but then never pops it. Such a situation will break
10
  # instrumentation of that request, but should not actually cause the request
11
  # to fail.
12
  # https://newrelic.atlassian.net/browse/RUBY-1158
13
  def failwhale
14
    state = NewRelic::Agent::TransactionState.tl_get
15
    stack = state.traced_method_stack
16
    stack.push_frame(state, 'failwhale')
17
    render :text => 'everything went great'
18
  end
19
end
20

  
21
class BadInstrumentationTest < RailsMultiverseTest
22
  include MultiverseHelpers
23
  setup_and_teardown_agent
24

  
25
  def test_unbalanced_tt_stack_should_not_cause_request_to_fail
26
    rsp = get '/bad_instrumentation/failwhale'
27
    assert_equal(200, rsp.to_i)
28
  end
29
end
test/multiverse/suites/rails/error_tracing_test.rb
1 1
# encoding: utf-8
2 2
# This file is distributed under New Relic's license terms.
3 3
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
4
require 'action_controller/railtie'
5
require 'active_model'
6
require 'rails/test_help'
4 7

  
5
# https://newrelic.atlassian.net/browse/RUBY-747
6
require './app'
7
require 'fake_collector'
8
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..', 'helpers', 'exceptions'))
9

  
10
class ErrorController < ApplicationController
11
  include NewRelic::TestHelpers::Exceptions
12

  
13
  newrelic_ignore :only => :ignored_action
14

  
15
  def controller_error
16
    raise 'this is an uncaught controller error'
17
  end
18

  
19
  def exception_error
20
    raise Exception.new('wobble')
21
  end
22

  
23
  def view_error
24
    render :inline => "<% raise 'this is an uncaught view error' %>"
25
  end
26

  
27
  def model_error
28
    Foo.new.raise_error
29
  end
30

  
31
  def ignored_action
32
    raise 'this error should not be noticed'
33
  end
34

  
35
  def ignored_error
36
    raise NewRelic::TestHelpers::Exceptions::IgnoredError.new('this error should not be noticed')
37
  end
38

  
39
  def server_ignored_error
40
    raise NewRelic::TestHelpers::Exceptions::ServerIgnoredError.new('this is a server ignored error')
41
  end
42

  
43
  def frozen_error
44
    e = RuntimeError.new("frozen errors make a refreshing treat on a hot summer day")
45
    e.freeze
46
    raise e
47
  end
48

  
49
  def string_noticed_error
50
    NewRelic::Agent.notice_error("trilobites died out millions of years ago")
51
    render :text => 'trilobites'
52
  end
53

  
54
  def noticed_error
55
    NewRelic::Agent.notice_error(RuntimeError.new('this error should be noticed'))
56
    render :text => "Shoulda noticed an error"
57
  end
58

  
59
  def deprecated_noticed_error
60
    newrelic_notice_error(RuntimeError.new('this error should be noticed'))
61
    render :text => "Shoulda noticed an error"
62
  end
63

  
64
  def middleware_error
65
    render :text => 'everything went great'
66
  end
67

  
68
  def error_with_custom_params
69
    NewRelic::Agent.add_custom_attributes(:texture => 'chunky')
70
    raise 'bad things'
71
  end
72

  
73
  if Rails::VERSION::MAJOR == 2
74
    filter_parameter_logging(:secret)
75
  end
76
end
77

  
78
class ErrorsWithoutSSCTest < RailsMultiverseTest
79
  extend Multiverse::Color
80

  
81
  include MultiverseHelpers
82

  
83
  setup_and_teardown_agent do |collector|
84
    setup_collector_mocks
85
    @error_collector = agent.error_collector
86
  end
87

  
88
  # Let base class override this without moving where we start the agent
89
  def setup_collector_mocks
90
    $collector.stub('connect', {"agent_run_id" => 666 }, 200)
91
  end
92

  
93
  def last_error
94
    errors.last
95
  end
96

  
97
  if Rails::VERSION::MAJOR >= 3
98
    def test_error_collector_should_be_enabled
99
      assert NewRelic::Agent.config[:agent_enabled]
100
      assert NewRelic::Agent.config[:'error_collector.enabled']
101
      assert @error_collector.enabled?
102
    end
103

  
104
    def test_should_capture_routing_error
105
      get '/bad_route'
106
      assert_error_reported_once('this is an uncaught routing error', nil, nil)
107
    end
108

  
109
    def test_should_capture_errors_raised_in_middleware_before_call
110
      get '/error/middleware_error/before'
111
      assert_error_reported_once('middleware error', nil, nil)
112
    end
113

  
114
    def test_should_capture_errors_raised_in_middleware_after_call
115
      get '/error/middleware_error/after'
116
      assert_error_reported_once('middleware error', nil, nil)
117
    end
118

  
119
    def test_should_capture_request_uri_and_params
120
      get '/error/controller_error?eat=static'
121
      assert_equal('/error/controller_error', attributes_for_single_error_posted("request_uri"))
122

  
123
      expected_params = {
124
        'request.parameters.eat' => 'static',
125
        'httpResponseCode' => '500'
126
      }
127

  
128
      attributes = agent_attributes_for_single_error_posted
129
      expected_params.each do |key, value|
130
        assert_equal value, attributes[key]
131
      end
132
    end
133
  end
134

  
135
  def test_should_capture_error_raised_in_view
136
    get '/error/view_error'
137
    assert_error_reported_once('this is an uncaught view error',
138
                               'Controller/error/view_error')
139
  end
140

  
141
  def test_should_capture_error_raised_in_controller
142
    get '/error/controller_error'
143
    assert_error_reported_once('this is an uncaught controller error',
144
                               'Controller/error/controller_error')
145
  end
146

  
147
  def test_should_capture_error_raised_in_model
148
    get '/error/model_error'
149
    assert_error_reported_once('this is an uncaught model error',
150
                               'Controller/error/model_error')
151
  end
152

  
153
  if Rails::VERSION::MAJOR < 5
154
    def test_should_capture_deprecated_noticed_error_in_controller
155
      get '/error/deprecated_noticed_error'
156
      assert_error_reported_once('this error should be noticed',
157
                                 'Controller/error/deprecated_noticed_error')
158
    end
159
  end
160

  
161
  def test_should_capture_noticed_error_in_controller
162
    get '/error/noticed_error'
163
    assert_error_reported_once('this error should be noticed',
164
                               'Controller/error/noticed_error')
165
  end
166

  
167
  def test_should_capture_frozen_errors
168
    get '/error/frozen_error'
169
    assert_error_reported_once("frozen errors make a refreshing treat on a hot summer day",
170
                               "Controller/error/frozen_error")
171
  end
172

  
173
  def test_should_capture_string_noticed_errors
174
    get '/error/string_noticed_error'
175
    assert_error_reported_once("trilobites died out millions of years ago",
176
                               "Controller/error/string_noticed_error")
177
  end
178

  
179
  # Important choice of controllor_error, since this goes through both the
180
  # transaction and the rack error collector, so risks multiple counting!
181
  def test_should_capture_multiple_errors
182
    40.times do
183
      get '/error/controller_error'
8
if !defined?(MyApp)
9
  class MyApp < Rails::Application
10
    initialize!
11
    routes.draw do
12
      get '/:controller(/:action(/:id))'
184 13
    end
185

  
186
    assert_errors_reported('this is an uncaught controller error',
187
                           NewRelic::Agent::ErrorCollector::MAX_ERROR_QUEUE_LENGTH,
188
                           40, nil, 40)
189
  end
190

  
191
  def test_should_capture_manually_noticed_error
192
    NewRelic::Agent.notice_error(RuntimeError.new('this is a noticed error'))
193
    assert_error_reported_once('this is a noticed error', nil, nil)
194
  end
195

  
196
  def test_should_apply_parameter_filtering
197
    get '/error/controller_error?secret=shouldnotbecaptured&other=whatever'
198
    attributes = agent_attributes_for_single_error_posted
199
    assert_equal('[FILTERED]', attributes['request.parameters.secret'])
200
    assert_equal('whatever', attributes['request.parameters.other'])
201
  end
202

  
203
  def test_should_apply_parameter_filtering_for_non_standard_errors
204
    get '/error/exception_error?secret=shouldnotbecaptured&other=whatever'
205
    attributes = agent_attributes_for_single_error_posted
206
    assert_equal('[FILTERED]', attributes['request.parameters.secret'])
207
    assert_equal('whatever', attributes['request.parameters.other'])
208 14
  end
209 15

  
210
  def test_should_not_notice_errors_from_ignored_action
211
    get '/error/ignored_action'
212
    assert(errors.empty?,
213
           'Noticed an error that should have been ignored')
214
  end
215

  
216
  def test_should_not_notice_ignored_error_classes
217
    get '/error/ignored_error'
218
    assert(errors.empty?,
219
           'Noticed an error that should have been ignored')
220
  end
16
  class ApplicationController < ActionController::Base; end
17
end
221 18

  
222
  def test_should_not_fail_apdex_for_ignored_error_class_noticed
223
    get '/error/ignored_error'
224
    assert_metrics_recorded({
225
      'Apdex'                     => { :apdex_f => 0 },
226
      'Apdex/error/ignored_error' => { :apdex_f => 0 }
227
    })
19
class ErrorController < ApplicationController
20
  def controller_error
21
    raise
228 22
  end
23
end
229 24

  
230
  def test_should_not_notice_filtered_errors
231
    filter = Proc.new do |error|
232
      !error.kind_of?(RuntimeError)
233
    end
234

  
235
    with_ignore_error_filter(filter) do
25
class ErrorsWithoutSSCTest < ActionDispatch::IntegrationTest
26
  def test_1
27
    100.times do
236 28
      get '/error/controller_error'
237 29
    end
238

  
239
    assert(errors.empty?,
240
           'Noticed an error that should have been ignored')
241
  end
242

  
243
  def test_should_notice_server_ignored_error_if_no_server_side_config
244
    get '/error/server_ignored_error'
245
    assert_error_reported_once('this is a server ignored error')
246
  end
247

  
248
  def test_captured_errors_should_include_custom_params
249
    with_config(:'error_collector.attributes.enabled' => true) do
250
      get '/error/error_with_custom_params'
251
      assert_error_reported_once('bad things')
252

  
253
      attributes = user_attributes_for_single_error_posted
254
      assert_equal({'texture' => 'chunky'}, attributes)
255
    end
256
  end
257

  
258
  def test_captured_errors_should_include_custom_params_with_legacy_setting
259
    with_config(:'error_collector.capture_attributes' => true) do
260
      get '/error/error_with_custom_params'
261
      assert_error_reported_once('bad things')
262

  
263
      attributes = user_attributes_for_single_error_posted
264
      assert_equal({'texture' => 'chunky'}, attributes)
265
    end
266
  end
267

  
268
  def test_captured_errors_should_not_include_custom_params_if_config_says_no
269
    with_config(:'error_collector.attributes.enabled' => false) do
270
      get '/error/error_with_custom_params'
271
      assert_error_reported_once('bad things')
272

  
273
      attributes = user_attributes_for_single_error_posted
274
      assert_empty attributes
275
    end
276
  end
277

  
278
  def test_captured_errors_should_not_include_custom_params_if_legacy_setting_says_no
279
    with_config(:'error_collector.capture_attributes' => false) do
280
      get '/error/error_with_custom_params'
281
      assert_error_reported_once('bad things')
282

  
283
      attributes = user_attributes_for_single_error_posted
284
      assert_empty attributes
285
    end
286
  end
287

  
288
  protected
289

  
290
  def errors
291
    @error_collector.error_trace_aggregator.instance_variable_get :@errors
292 30
  end
293 31

  
294
  def errors_with_message(message)
295
    errors.select{|error| error.message == message}
296
  end
297

  
298
  def assert_errors_reported(message, queued_count, total_count=queued_count, txn_name=nil, apdex_f=1)
299
    expected = { :call_count => total_count }
300
    assert_metrics_recorded("Errors/all" => expected)
301
    assert_metrics_recorded("Errors/#{txn_name}" => expected) if txn_name
302

  
303
    unless apdex_f.nil?
304
      assert_metrics_recorded("Apdex" => { :apdex_f => apdex_f })
305
    end
306

  
307
    assert_equal(queued_count,
308
      errors_with_message(message).size,
309
      "Wrong number of errors with message #{message.inspect} found")
310
  end
311

  
312
  def assert_error_reported_once(message, txn_name=nil, apdex_f=1)
313
    assert_errors_reported(message, 1, 1, txn_name, apdex_f)
314
  end
32
  alias test_2 test_1
315 33
end
316 34

  
317 35
class ErrorsWithSSCTest < ErrorsWithoutSSCTest
318
  def setup_collector_mocks
319
    $collector.stub('connect', {
320
      "agent_run_id" => 1,
321
      "agent_config" => {
322
        "error_collector.ignore_errors" => 'NewRelic::TestHelpers::Exceptions::IgnoredError,NewRelic::TestHelpers::Exceptions::ServerIgnoredError',
323
        "error_collector.enabled" => true,
324
      },
325
      "collect_errors" => true
326
    }, 200)
327
  end
328

  
329
  def test_should_notice_server_ignored_error_if_no_server_side_config
330
    # Overrides test in base class, since doesn't apply
331
  end
332

  
333
  def test_should_ignore_server_ignored_errors
334
    get '/error/server_ignored_error'
335

  
336
    assert(errors.empty?,
337
           'Noticed an error that should have been ignored' + errors.join(', '))
338
  end
339

  
340 36
end
37
GC.disable
38
GC.enable
test/multiverse/suites/rails/gc_instrumentation_test.rb
1
# encoding: utf-8
2
# This file is distributed under New Relic's license terms.
3
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
4

  
5
require './app'
6

  
7
# These tests only return consistent results for REE or MRI >= 1.9.2
8
if NewRelic::LanguageSupport.ree? ||
9
    (RUBY_VERSION >= '1.9.2' &&
10
     !NewRelic::LanguageSupport.jruby? &&
11
     !NewRelic::LanguageSupport.rubinius?)
12

  
13
class GcController < ApplicationController
14
  def gc_action
15
    begin
16
      NewRelic::Agent::StatsEngine::GCProfiler.init
17
      initial_gc_count = current_gc_count
18

  
19
      Timeout.timeout(5) do
20
        until current_gc_count > initial_gc_count
21
          long_string = "01234567" * 100_000
22
          long_string = nil
23
          another_long_string = "01234567" * 100_000
24
          another_long_string = nil
25
        end
26
      end
27
    rescue Timeout::Error
28
      puts "Timed out waiting for GC..."
29
    end
30

  
31
    render :text => 'ha'
32
  end
33

  
34
  def current_gc_count
35
    if NewRelic::LanguageSupport.ree?
36
      ::GC.collections
37
    elsif RUBY_VERSION >= '1.9.2'
38
      ::GC.count
39
    end
40
  end
41
end
42

  
43
class GCRailsInstrumentationTest < ActionController::TestCase
44
  tests GcController
45

  
46
  include MultiverseHelpers
47

  
48
  setup_and_teardown_agent do
49
    NewRelic::Agent.drop_buffered_data
50
    NewRelic::Agent::StatsEngine::GCProfiler.reset
51
    enable_gc_stats
52
    @controller = GcController.new
53
  end
54

  
55
  def test_records_accurate_time_for_gc_activity
56
    start = Time.now
57
    get :gc_action
58
    elapsed = Time.now.to_f - start.to_f
59

  
60
    assert_in_range(elapsed, get_call_time('GC/Transaction/allWeb'))
61
    assert_in_range(elapsed, get_call_time('GC/Transaction/allWeb', 'Controller/gc/gc_action'))
62
  end
63

  
64
  def test_records_transaction_param_for_gc_activity
65
    start = Time.now.to_f
66
    get :gc_action
67
    elapsed = Time.now.to_f - start
68

  
69
    trace = NewRelic::Agent.instance.transaction_sampler.last_sample
70
    assert_in_range(elapsed, attributes_for(trace, :intrinsic)[:gc_time])
71
  end
72

  
73
  def assert_in_range(duration, gc_time)
74
    assert gc_time > 0.0, "GC Time wasn't recorded!"
75
    assert gc_time < duration, "GC Time #{gc_time} can't be more than elapsed #{duration}!"
76
  end
77

  
78
  def get_call_time(name, scope=nil)
79
    NewRelic::Agent.agent.stats_engine.
80
      get_stats(name, true, false, scope).
81
      total_call_time
82
  end
83

  
84
  def enable_gc_stats
85
    if NewRelic::LanguageSupport.ree?
86
      GC.enable_stats
87
    elsif RUBY_VERSION >= '1.9.2'
88
      GC::Profiler.enable
89
    end
90
  end
91
end
92

  
93
end
test/multiverse/suites/rails/ignore_test.rb
1
# encoding: utf-8
2
# This file is distributed under New Relic's license terms.
3
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
4

  
5
# https://newrelic.atlassian.net/browse/RUBY-927
6

  
7
require './app'
8

  
9
class IgnoredController < ApplicationController
10
  newrelic_ignore :only => :action_to_ignore
11
  newrelic_ignore_apdex :only => :action_to_ignore_apdex
12

  
13
  def action_to_ignore
14
    render :text => "Ignore this"
15
  end
16

  
17
  def action_to_ignore_apdex
18
    render :text => "This too"
19
  end
20
end
21

  
22
class ParentController < ApplicationController
23
  newrelic_ignore_apdex
24

  
25
  def foo(*args); end
26

  
27
  add_transaction_tracer :foo
28
end
29

  
30
class ChildController < ParentController
31
  def bar(*args); end
32

  
33
  add_transaction_tracer :bar
34
end
35

  
36

  
37
class IgnoredActionsTest < RailsMultiverseTest
38
  include MultiverseHelpers
39

  
40
  setup_and_teardown_agent(:cross_process_id => "boo",
41
                           :encoding_key => "\0",
42
                           :trusted_account_ids => [1])
43

  
44
  def after_setup
45
    # Make sure we've got a blank slate for doing easier metric comparisons
46
    NewRelic::Agent.instance.drop_buffered_data
47
  end
48

  
49
  def test_metric__ignore
50
    get '/ignored/action_to_ignore'
51
    assert_metrics_recorded_exclusive([])
52
  end
53

  
54
  def test_metric__ignore_apdex
55
    get '/ignored/action_to_ignore_apdex'
56
    assert_metrics_recorded(["Controller/ignored/action_to_ignore_apdex"])
57
    assert_metrics_not_recorded(["Apdex"])
58
  end
59

  
60
  def test_ignored_transaction_traces_dont_leak
61
    get '/ignored/action_to_ignore'
62
    get '/request_stats/stats_action'
63

  
64
    trace = NewRelic::Agent.instance.transaction_sampler.last_sample
65
    assert_equal 1, trace.root_node.called_nodes.count
66
  end
67

  
68
  def test_should_not_write_cat_response_headers_for_ignored_transactions
69
    get '/ignored/action_to_ignore', nil, {'X-NewRelic-ID' => Base64.encode64('1#234')}
70
    assert_nil @response.headers["X-NewRelic-App-Data"]
71
  end
72

  
73
  def test_apdex_ignored_if_ignored_in_parent_class
74
    get '/child/foo'
75
    get '/child/bar'
76

  
77
    assert_metrics_not_recorded("Apdex")
78
  end
79
end
test/multiverse/suites/rails/middleware_instrumentation_test.rb
1
# encoding: utf-8
2
# This file is distributed under New Relic's license terms.
3
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
4

  
5
# https://newrelic.atlassian.net/browse/RUBY-927
6

  
7
require './app'
8

  
9
if Rails::VERSION::MAJOR.to_i >= 3
10

  
11
class MiddlewareInstrumentationTest < RailsMultiverseTest
12
  def test_rails_middleware_records_metrics
13
    get('/')
14
    assert_metrics_recorded(
15
      ['Middleware/all', 'Middleware/Rack/Rails::Rack::Logger/call']
16
    )
17
  end
18

  
19
  def test_rails_routeset_is_instrumented
20
    get('/')
21
    assert_metrics_recorded(
22
      'Middleware/Rack/ActionDispatch::Routing::RouteSet/call'
23
    )
24
  end
25

  
26
  if Rails::VERSION::MAJOR >= 4
27
    def test_rails_middlewares_constructed_by_name
28
      get('/')
29
      assert response.headers['NamedMiddleware'], "NamedMiddleware should have been called, but wasn't"
30
      assert_metrics_recorded('Middleware/Rack/NamedMiddleware/call')
31
    end
32

  
33
    def test_rails_middlewares_passed_as_instances
34
      get('/')
35
      assert response.headers['InstanceMiddleware'], "InstanceMiddleware should have been called, but wasn't"
36
      assert_metrics_recorded('Middleware/Rack/InstanceMiddleware/call')
37
    end
38
  end
39
end
40

  
41
end
test/multiverse/suites/rails/parameter_capture_test.rb
1
# encoding: utf-8
2
# This file is distributed under New Relic's license terms.
3
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
4

  
5
require './app'
6

  
7
class ParameterCaptureController < ApplicationController
8
  def transaction
9
    render :text => 'hi!'
10
  end
11

  
12
  def create
13
    raise 'problem' if params[:raise]
14
    render :text => 'created'
15
  end
16

  
17
  def sql
18
    NewRelic::Agent.agent.sql_sampler.notice_sql(
19
      'SELECT * FROM table',
20
      'ActiveRecord/foos/find',
21
      {},
22
      100.0
23
    )
24
  end
25

  
26
  def error
27
    raise 'wut'
28
  end
29

  
30
  # For Rails 3+, this is configured globally in the config block for the app
31
  if Rails::VERSION::MAJOR == 2
32
    filter_parameter_logging(:secret)
33
  end
34
end
35

  
36
class ParameterCaptureTest < RailsMultiverseTest
37
  include MultiverseHelpers
38
  setup_and_teardown_agent
39

  
40
  def test_no_params_captured_on_errors_when_disabled
41
    with_config(:capture_params => false) do
42
      get '/parameter_capture/error?other=1234&secret=4567'
43
      refute_contains_request_params(agent_attributes_for_single_error_posted)
44
    end
45
  end
46

  
47
  def test_no_params_captured_on_tts_when_disabled
48
    with_config(:capture_params => false) do
49
      get '/parameter_capture/transaction?other=1234&secret=4567'
50
    end
51
    assert_equal({}, last_transaction_trace_request_params)
52
  end
53

  
54
  def test_uri_on_traced_errors_never_contains_query_string_without_capture_params
55
    with_config(:capture_params => false) do
56
      get '/parameter_capture/error?other=1234&secret=4567'
57
      assert_equal('/parameter_capture/error', attributes_for_single_error_posted("request_uri"))
58
    end
59
  end
60

  
61
  def test_uri_on_traced_errors_never_contains_query_string_with_capture_params
62
    with_config(:capture_params => true) do
63
      get '/parameter_capture/error?other=1234&secret=4567'
64
      assert_equal('/parameter_capture/error', attributes_for_single_error_posted("request_uri"))
65
    end
66
  end
67

  
68
  def test_referrer_on_traced_errors_never_contains_query_string_without_capture_params
69
    with_config(:capture_params => false) do
70
      get '/parameter_capture/error?other=1234&secret=4567', {}, { 'HTTP_REFERER' => '/foo/bar?other=123&secret=456' }
71
      attributes = agent_attributes_for_single_error_posted
72
      assert_equal('/foo/bar', attributes["request.headers.referer"])
73
    end
74
  end
75

  
76
  def test_referrer_on_traced_errors_never_contains_query_string_even_with_capture_params
77
    with_config(:capture_params => true) do
78
      get '/parameter_capture/error?other=1234&secret=4567', {}, { 'HTTP_REFERER' => '/foo/bar?other=123&secret=456' }
79
      attributes = agent_attributes_for_single_error_posted
80
      assert_equal('/foo/bar', attributes["request.headers.referer"])
81
    end
82
  end
83

  
84
  def test_controller_and_action_excluded_from_error_parameters
85
    with_config(:capture_params => true) do
86
      get '/parameter_capture/error'
87
      run_harvest
88

  
89
      refute_error_has_agent_attribute('request.parameters.controller')
90
      refute_error_has_agent_attribute('request.parameters.action')
91
    end
92
  end
93

  
94
  def test_controller_and_action_excluded_from_transaction_trace_parameters
95
    with_config(:capture_params => true, :'transaction_tracer.transaction_threshold' => -10) do
96
      get '/parameter_capture/transaction'
97
      run_harvest
98

  
99
      refute_transaction_trace_has_agent_attribute('request.parameters.controller')
100
      refute_transaction_trace_has_agent_attribute('request.parameters.action')
101
    end
102
  end
103

  
104
  def test_uri_on_tts_never_contains_query_string
105
    with_config(:capture_params => false) do
106
      get '/parameter_capture/transaction?other=1234&secret=4567'
107
    end
108
    assert_equal('/parameter_capture/transaction', last_transaction_trace.uri)
109

  
110
    with_config(:capture_params => true) do
111
      get '/parameter_capture/transaction?other=1234&secret=4567'
112
    end
113
    assert_equal('/parameter_capture/transaction', last_transaction_trace.uri)
114
  end
115

  
116
  def test_filters_parameters_on_traced_errors
117
    with_config(:capture_params => true) do
118
      get '/parameter_capture/error?other=1234&secret=4567'
119

  
120
      captured_params = agent_attributes_for_single_error_posted
121
      assert_equal('[FILTERED]', captured_params['request.parameters.secret'])
122
      assert_equal('1234',       captured_params['request.parameters.other'])
123
    end
124
  end
125

  
126
  def test_filters_parameters_on_transaction_traces
127
    with_config(:capture_params => true) do
128
      get '/parameter_capture/transaction?other=1234&secret=4567'
129
    end
130

  
131
    captured_params = last_transaction_trace_request_params
132
    assert_equal('[FILTERED]', captured_params['request.parameters.secret'])
133
    assert_equal('1234',       captured_params['request.parameters.other'])
134
  end
135

  
136
  def test_no_traced_error_params_captured_when_bails_before_rails
137
    with_config(:capture_params => false) do
138
      get '/middleware_error/before?other=1234&secret=4567'
139
      refute_contains_request_params(agent_attributes_for_single_error_posted)
140
    end
141
  end
142

  
143
  def test_no_transaction_trace_params_captured_when_bails_before_rails
144
    with_config(:capture_params => false) do
145
      get '/middleware_error/before?other=1234&secret=4567'
146
    end
147

  
148
    assert_equal({}, last_transaction_trace_request_params)
149
  end
150

  
151
  def test_no_params_captured_on_error_when_bails_before_rails_even_when_enabled
152
    with_config(:capture_params => true) do
153
      get '/middleware_error/before?other=1234&secret=4567'
154
      refute_contains_request_params(agent_attributes_for_single_error_posted)
155
    end
156
  end
157

  
158
  def test_no_params_captured_on_tt_when_bails_before_rails_even_when_enabled
159
    with_config(:capture_params => true) do
160
      get '/middleware_error/before?other=1234&secret=4567'
161
    end
162
    assert_equal({}, last_transaction_trace_request_params)
163
  end
164

  
165
  def test_uri_on_tt_should_not_contain_query_string_with_capture_params_off
166
    with_config(:capture_params => false) do
167
      get '/parameter_capture/transaction?param1=value1&param2=value2'
168
    end
169
    assert_equal('/parameter_capture/transaction', last_transaction_trace.uri)
170
  end
171

  
172
  def test_uri_on_tt_should_not_contain_query_string_with_capture_params_on
173
    with_config(:capture_params => true) do
174
      get '/parameter_capture/transaction?param1=value1&param2=value2'
175
    end
176
    assert_equal('/parameter_capture/transaction', last_transaction_trace.uri)
177
  end
178

  
179
  def test_uri_on_traced_error_should_not_contain_query_string_with_capture_params_off
180
    with_config(:capture_params => false) do
181
      get '/parameter_capture/error?param1=value1&param2=value2'
182
      assert_equal('/parameter_capture/error', attributes_for_single_error_posted("request_uri"))
183
    end
184
  end
185

  
186
  def test_uri_on_traced_error_should_not_contain_query_string_with_capture_params_on
187
    with_config(:capture_params => true) do
188
      get '/parameter_capture/error?param1=value1&param2=value2'
189
      assert_equal('/parameter_capture/error', attributes_for_single_error_posted("request_uri"))
190
    end
191
  end
192

  
193
  def test_uri_on_sql_trace_should_not_contain_query_string_with_capture_params_off
194
    with_config(:capture_params => false) do
195
      get '/parameter_capture/sql?param1=value1&param2=value2'
196
    end
197
    assert_equal('/parameter_capture/sql', last_sql_trace.url)
198
  end
199

  
200
  def test_uri_on_sql_trace_should_not_contain_query_string_with_capture_params_on
201
    with_config(:capture_params => true) do
202
      get '/parameter_capture/sql?param1=value1&param2=value2'
203
    end
204
    assert_equal('/parameter_capture/sql', last_sql_trace.url)
205
  end
206

  
207
  def test_parameters_attached_to_transaction_events_if_enabled
208
    with_config(:'attributes.include' => 'request.parameters.*',
209
                :'attributes.exclude' => ['request.*', 'response.*']) do
210
      get '/parameter_capture/transaction?param1=value1&param2=value2'
211
    end
212

  
213
    actual = agent_attributes_for_single_event_posted_without_ignored_attributes
214

  
215
    expected = {"request.parameters.param1" => "value1",
216
      "request.parameters.param2" => "value2"
217
    }
218

  
219
    assert_equal expected, actual
220
  end
221

  
222
  def test_request_and_response_attributes_recorded_as_agent_attributes
223
      get '/parameter_capture/transaction'
224

  
225
      expected = {
226
        "response.headers.contentType" => "#{response.content_type}; charset=#{response.charset}",
227
        "request.headers.contentLength" => request.content_length.to_i,
228
        "request.headers.contentType" => request.content_type,
229
        "request.headers.host" => request.host,
230
        "request.headers.accept" => request.accept
231
      }
232

  
233
      # ActionController::IntegrationTest sets this header whereas ActionDispatch::IntegrationTest
234
      # does not. Since we test using both we need to conditionally expect content_length to be set.
235

  
236
      unless defined?(ActionDispatch::IntegrationTest)
237
        expected["response.headers.contentLength"] = response.content_length
238
      end
239

  
240
      actual = agent_attributes_for_single_event_posted_without_ignored_attributes
241

  
242
      # request method may be a symbol or string based on Rails versions
243
      request_method = actual.delete("request.method")
244
      assert_equal request_method, request.request_method.to_s.upcase
245

  
246
      assert_equal(expected, actual)
247
  end
248

  
249

  
250
  if Rails::VERSION::MAJOR > 2
251
    def test_params_tts_should_be_filtered_when_serviced_by_rack_app
252
      params = {"secret" => "shhhhhhh", "name" => "name"}
253
      with_config(:capture_params => true) do
254
        post '/filtering_test/', params
255
      end
256

  
257
      expected = {
258
        "request.parameters.secret" => "[FILTERED]",
259
        "request.parameters.name" => "name"
260
      }
261
      assert_equal expected, last_transaction_trace_request_params
262
    end
263

  
264
    def test_params_on_errors_should_be_filtered_when_serviced_by_rack_app
265
      params = {"secret" => "shhhhhhh", "name" => "name"}
266
      with_config(:capture_params => true) do
267
        post '/filtering_test?raise=1', params
268

  
269
        expected = {
270
          "request.parameters.secret" => "[FILTERED]",
271
          "request.parameters.name" => "name",
272
          "request.parameters.raise" => "1"
273
        }
274

  
275
        attributes = agent_attributes_for_single_error_posted
276
        expected.each do |key, value|
277
          assert_equal value, attributes[key]
278
        end
279
      end
280
    end
281

  
282
    def test_parameter_filtering_should_not_mutate_argument
283
      input = { "foo" => "bar", "secret" => "baz" }
284
      env   = { "action_dispatch.parameter_filter" => ["secret"] }
285
      filtered = NewRelic::Agent::ParameterFiltering.apply_filters(env, input)
286

  
287
      assert_equal({ "foo" => "bar", "secret" => "[FILTERED]" }, filtered)
288
      assert_equal({ "foo" => "bar", "secret" => "baz" }, input)
289
    end
290
  end
291

  
292
  if Rails::VERSION::MAJOR > 2 && defined?(Sinatra)
293
    def test_params_tts_should_be_filtered_when_serviced_by_sinatra_app
294
      with_config(:capture_params => true) do
295
        get '/sinatra_app/', "secret" => "shhhhhhh", "name" => "name"
296
      end
297

  
298
      expected = {
299
        "request.parameters.secret" => "[FILTERED]",
300
        "request.parameters.name" => "name"
301
      }
302
      assert_equal expected, last_transaction_trace_request_params
303
    end
304

  
305
    def test_params_on_errors_should_be_filtered_when_serviced_by_sinatra_app
306
      with_config(:capture_params => true) do
307
        get '/sinatra_app?raise=1', "secret" => "shhhhhhh", "name" => "name"
308

  
309
        attributes = agent_attributes_for_single_error_posted
310
        assert_equal "[FILTERED]", attributes["request.parameters.secret"]
311
        assert_equal "name", attributes["request.parameters.name"]
312
        assert_equal "1", attributes["request.parameters.raise"]
313
      end
314
    end
315

  
316
    def test_file_upload_params_are_replaced_with_placeholder
317
      with_config(:capture_params => true, :'transaction_tracer.transaction_threshold' => -10) do
318
        post '/parameter_capture', :file => Rack::Test::UploadedFile.new(__FILE__, 'text/plain')
319

  
320
        run_harvest
321

  
322
        result = single_transaction_trace_posted
323
        assert_equal "#<ActionDispatch::Http::UploadedFile>", result.agent_attributes["request.parameters.file"]
324
      end
325
    end
326
  end
327

  
328
end
test/multiverse/suites/rails/queue_time_test.rb
1
# encoding: utf-8
2
# This file is distributed under New Relic's license terms.
3
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
4

  
5
# https://newrelic.atlassian.net/browse/RUBY-927
6

  
7
require './app'
8

  
9
class QueueController < ApplicationController
10
  def queued
11
    respond_to do |format|
12
      format.html { render :text => "<html><head></head><body>Queued</body></html>" }
13
    end
14
  end
15

  
16
  def nested
17
    nested_transaction
18
    render :text => 'whatever'
19
  end
20

  
21
  def nested_transaction; end
22

  
23
  add_transaction_tracer :nested_transaction
24
end
25

  
26
class QueueTimeTest < RailsMultiverseTest
27

  
28
  REQUEST_START_HEADER = 'HTTP_X_REQUEST_START'
29

  
30
  include MultiverseHelpers
31

  
32
  setup_and_teardown_agent(:beacon => "beacon", :browser_key => "key", :js_agent_loader => "loader")
33

  
34
  def test_should_track_queue_time_metric
35
    t0 = freeze_time
36
    t1 = advance_time(2)
37
    get_path('/queue/queued', t0)
38

  
39
    assert_metrics_recorded(
40
      'WebFrontend/QueueTime' => {
41
        :call_count      => 1,
42
        :total_call_time => (t1 - t0)
43
      }
44
    )
45
  end
46

  
47
  def test_should_see_queue_time_in_rum
48
    t0 = freeze_time
49
    t1 = advance_time(2)
50
    get_path('/queue/queued', t0)
51
    queue_time = extract_queue_time_from_response
52
    assert_equal((t1 - t0) * 1000, queue_time)
53
  end
54

  
55
  def test_should_not_track_queue_time_for_nested_transactions
56
    t0 = freeze_time
57
    t1 = advance_time(2)
58
    get_path('/queue/nested', t0)
59
    assert_metrics_recorded(
60
      'WebFrontend/QueueTime' => {
61
        :call_count      => 1,
62
        :total_call_time => (t1 - t0)
63
      }
64
    )
65
  end
66

  
67
  def get_path(path, queue_start_time)
68
    value = "t=#{(queue_start_time.to_f * 1_000_000).to_i}"
69
    get(path, nil, REQUEST_START_HEADER => value)
70
  end
71

  
72
  def extract_queue_time_from_response
73
    get_last_response_body =~ /\"queueTime\":(\d+.*)/
74
    refute_nil $1, "Should have found queue time in #{@response.body.inspect}"
75
    $1.to_i
76
  end
77

  
78
  def get_last_response_body
79
    if Rails::VERSION::MAJOR >= 3
80
      @response.body
81
    else
82
      # In Rails 2 integration tests, @response.body is always the response from
83
      # the controller itself, not the middleware stack. Since we want the
84
      # response from the middleware stack, we grab it off of the integration
85
      # session.
86
      @integration_session.body
87
    end
88
  end
89
end
test/multiverse/suites/rails/request_statistics_test.rb
1
# encoding: utf-8
2
# This file is distributed under New Relic's license terms.
3
# See https://github.com/newrelic/rpm/blob/master/LICENSE for complete details.
4

  
5
# https://newrelic.atlassian.net/browse/RUBY-1096
6

  
7
require './app'
8

  
9
class RequestStatsController < ApplicationController
10
  def stats_action
11
    sleep 0.01
12
    render :text => 'some stuff'
13
  end
14

  
15
  def cross_app_action
16
    NewRelic::Agent::TransactionState.tl_get.is_cross_app_caller = true
17
    render :text => 'some stuff'
18
  end
19

  
20
  def stats_action_with_custom_params
21
    ::NewRelic::Agent.add_custom_attributes('color' => 'blue', 1 => :bar, 'bad' => {})
22
    render :text => 'some stuff'
23
  end
24
end
25

  
26
class RequestStatsTest < RailsMultiverseTest
27
  extend Multiverse::Color
28

  
29
  include MultiverseHelpers
30
  setup_and_teardown_agent
31

  
32
  #
33
  # Tests
34
  #
35

  
36
  def test_doesnt_send_when_disabled
37
    with_config( :'analytics_events.enabled' => false ) do
38
      5.times { get '/request_stats/stats_action' }
39

  
40
      NewRelic::Agent.agent.send(:harvest_and_send_analytic_event_data)
41

  
42
      assert_equal 0, $collector.calls_for('analytic_event_data').length
43
    end
44
  end
45

  
46
  def test_request_times_should_be_reported_if_enabled
47
    with_config( :'analytics_events.enabled' => true ) do
48
      5.times { get '/request_stats/stats_action' }
49

  
50
      NewRelic::Agent.agent.send(:harvest_and_send_analytic_event_data)
51

  
52
      post = $collector.calls_for('analytic_event_data').first
53

  
54
      refute_nil( post )
55
      assert_kind_of Array, post.events
56
      assert_kind_of Array, post.events.first
57

  
58
      assert_equal 3, post.events.first.length
59

  
60
      post.events.first.each do |event_chunk|
61
        assert_kind_of Hash, event_chunk
62
      end
63

  
64
      sample = post.events.first.first
65
      assert_equal 'Controller/request_stats/stats_action', sample['name']
66
      assert_encoding 'utf-8', sample['name']
67
      assert_equal 'Transaction', sample['type']
68
      assert_kind_of Float, sample['duration']
69
      assert_kind_of Float, sample['timestamp']
70

  
71
      assert_nil sample['nr.guid']
72
      assert_nil sample['nr.referringTransactionGuid']
73
    end
74
  end
75

  
76
  def test_request_should_include_guid_if_cross_app
77
    with_config( :'analytics_events.enabled' => true ) do
78
      5.times { get '/request_stats/cross_app_action' }
79

  
80
      NewRelic::Agent.agent.send(:harvest_and_send_analytic_event_data)
81

  
82
      post = $collector.calls_for('analytic_event_data').first
83

  
84
      refute_nil( post )
85
      assert_kind_of Array, post.events
86
      assert_kind_of Array, post.events.first
87

  
88
      sample = post.events.first.first
89
      assert_kind_of Hash, sample
90

  
91
      assert_kind_of String, sample['nr.guid']
92
    end
93
  end
94

  
95
  def test_request_should_include_referring_guid_if_needed
96
    with_config(:'analytics_events.enabled' => true,
97
                :'cross_process_id' => 'boo',
98
                :'encoding_key' => "\0",
99
                :'trusted_account_ids' => [1]) do
100
      rack_env = {
101
        'HTTP_X_NEWRELIC_ID'          => Base64.encode64('1#234'),
102
        'HTTP_X_NEWRELIC_TRANSACTION' => Base64.encode64('["8badf00d",1]')
103
      }
104
      get '/request_stats/cross_app_action', {}, rack_env
105

  
106
      NewRelic::Agent.agent.send(:harvest_and_send_analytic_event_data)
107

  
108
      post = $collector.calls_for('analytic_event_data').first
109

  
110
      refute_nil( post )
111
      assert_kind_of Array, post.events
112
      assert_kind_of Array, post.events.first
113

  
114
      sample = post.events.first.first
115

  
116
      assert_kind_of Hash, sample
117
      assert_kind_of String, sample['nr.guid']
118
      assert_equal('8badf00d', sample['nr.referringTransactionGuid'])
119
    end
120
  end
121

  
122
  def test_custom_params_should_be_reported_with_events_and_coerced_to_safe_types
123
    with_config( :'analytics_events.enabled' => true ) do
124
      5.times { get '/request_stats/stats_action_with_custom_params' }
125

  
126
      NewRelic::Agent.agent.send(:harvest_and_send_analytic_event_data)
127

  
128
      post = $collector.calls_for('analytic_event_data').first
129

  
130
      refute_nil( post )
131
      assert_kind_of Array, post.events
132
      assert_kind_of Array, post.events.first
... This diff was truncated because it exceeds the maximum size that can be displayed.