diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4c1fe39918..102a7302f2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -206,7 +206,7 @@ jobs: name: Prepare mysql directory run: sudo chown -R $USER /usr/local - - if: matrix.ruby-version == '2.4.10' + - if: matrix.ruby-version == '2.4.10' name: Cache mysql55 id: mysql55-cache uses: actions/cache@v3.2.2 @@ -265,6 +265,16 @@ jobs: path: lib/coverage_*/.resultset.json retention-days: 2 + - name: Generate gem manifest + run: rake test:multiverse:gem_manifest + + - name: Save gem manifest + uses: actions/upload-artifact@v3 + with: + name: gem_manifest_${{ matrix.ruby-version }}.json + path: gem_manifest_${{ matrix.ruby-version }}.json + retention-days: 2 + infinite_tracing: needs: run_rubocop @@ -336,4 +346,4 @@ jobs: token: ${{ secrets.GITHUB_TOKEN }} resultPath: lib/coverage_results/.last_run.json failedThreshold: 93 - failedThresholdBranch: 84 + failedThresholdBranch: 85 diff --git a/.github/workflows/ci_cron.yml b/.github/workflows/ci_cron.yml index c124554c09..8f8d5f6aab 100644 --- a/.github/workflows/ci_cron.yml +++ b/.github/workflows/ci_cron.yml @@ -54,7 +54,6 @@ jobs: with: ruby-version: ${{ matrix.ruby-version }} - # ,railsedge goes in 2.7+ - name: Set up mini-envs for ruby version uses: kanga333/variable-mapper@master with: @@ -71,16 +70,16 @@ jobs: "rails": "norails,rails61,rails60,rails52,rails51,rails42" }, "2.7.7": { - "rails": "norails,rails61,rails60,rails70" + "rails": "norails,rails61,rails60,rails70,railsedge" }, "3.0.5": { - "rails": "norails,rails61,rails60,rails70" + "rails": "norails,rails61,rails60,rails70,railsedge" }, "3.1.3": { - "rails": "norails,rails61,rails70" + "rails": "norails,rails61,rails70,railsedge" }, "3.2.1": { - "rails": "norails,rails61,rails70" + "rails": "norails,rails61,rails70,railsedge" } } diff --git a/.github/workflows/ci_jruby.yml b/.github/workflows/ci_jruby.yml index 13a60f0c04..105246d7bf 100644 --- a/.github/workflows/ci_jruby.yml +++ b/.github/workflows/ci_jruby.yml @@ -23,16 +23,10 @@ jobs: run: 'git config --global init.defaultBranch main' - uses: actions/checkout@v3 - # - curl is needed for Curb - # - xslt is needed for older Nokogiris, RUBY_VERSION < 2.5 - # - sasl is needed for memcached - - name: Install OS packages - run: sudo apt-get update; sudo apt-get install -y --no-install-recommends libcurl4-nss-dev libsasl2-dev - - - name: Install Ruby jruby-9.3.9.0 + - name: Install Ruby jruby-9.4.2.0 uses: ruby/setup-ruby@v1 with: - ruby-version: jruby-9.3.9.0 + ruby-version: jruby-9.4.2.0 - name: Bundle run: bundle install @@ -122,12 +116,6 @@ jobs: matrix: multiverse: [agent, background, background_2, database, frameworks, httpclients, httpclients_2, rails, rest] steps: - - name: Set the default Java version - run: sudo update-alternatives --set java ${JAVA_HOME_8_X64}/bin/java && - sudo update-alternatives --set javac ${JAVA_HOME_8_X64}/bin/javac && - java -version && - javac -version - - name: Configure git run: 'git config --global init.defaultBranch main' @@ -137,14 +125,10 @@ jobs: - name: Install JRuby uses: ruby/setup-ruby@v1 with: - ruby-version: jruby-9.3.9.0 - env: - JAVA_HOME: /usr/lib/jvm/temurin-8-jdk-amd64 + ruby-version: jruby-9.4.2.0 - name: Bundle run: bundle install - env: - JAVA_HOME: /usr/lib/jvm/temurin-8-jdk-amd64 - name: Run Multiverse Tests run: ./.github/workflows/scripts/retry_command @@ -155,7 +139,6 @@ jobs: SERIALIZE: 1 DB_PORT: ${{ job.services.mysql.ports[3306] }} JRUBY_OPTS: --dev --debug - JAVA_HOME: /usr/lib/jvm/temurin-8-jdk-amd64 - name: Annotate errors if: ${{ failure() }} diff --git a/.github/workflows/scripts/generate_release_notes.rb b/.github/workflows/scripts/generate_release_notes.rb new file mode 100644 index 0000000000..777fc421ab --- /dev/null +++ b/.github/workflows/scripts/generate_release_notes.rb @@ -0,0 +1,67 @@ +#!/usr/bin/ruby +# This file is distributed under New Relic's license terms. +# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. +# frozen_string_literal: true + +require 'date' +require_relative '../../../lib/new_relic/version' + +class GenerateReleaseNotes + DIVIDER = '---' + SUPPORT_STATEMENT = <<~SUPPORT_STATEMENT + + We recommend updating to the latest agent version as soon as it's available. If you can't upgrade to the latest version, update your agents to a version at most 90 days old. Read more about [keeping agents up to date](/docs/new-relic-solutions/new-relic-one/install-configure/update-new-relic-agent/). + + See the New Relic Ruby agent [EOL policy](https://docs.newrelic.com/docs/apm/agents/ruby-agent/getting-started/ruby-agent-eol-policy/) for information about agent releases and support dates. + + SUPPORT_STATEMENT + + def build_metadata + changelog = File.read('CHANGELOG.md') + latest_entry = changelog.split('##')[1].prepend('##') + titles = latest_entry.scan(/^- \*{2}(.*?)\*{2}$/).flatten # Match strings between sets of '**' + metadata = Hash.new { |h, k| h[k] = [] } + + titles.each do |t| + category = t.split(':').first + case category + when 'Feature' + metadata[:features] << t.delete_prefix('Feature: ') + when 'Bugfix' + metadata[:bugs] << t.delete_prefix('Bugfix: ') + when 'Security' + metadata[:security] << t.delete_prefix('Security: ') + end + end + + return metadata, latest_entry + end + + def build_release_content + metadata, latest_entry = build_metadata + <<~FRONTMATTER + #{DIVIDER} + subject: Ruby agent + date: #{Date.today} + version: #{NewRelic::VERSION::STRING} + downloadLink: https://rubygems.org/downloads/newrelic_rpm-#{NewRelic::VERSION::STRING}.gem + features: #{metadata[:features]} + bugs: #{metadata[:bugs]} + security: #{metadata[:security]} + #{DIVIDER} + + #{SUPPORT_STATEMENT} + #{latest_entry} + FRONTMATTER + end + + def write_filename + "ruby-agent-#{NewRelic::VERSION::STRING.tr('.', '-')}.mdx" + end + + def write_output_file + File.write(write_filename, build_release_content) + end +end + +GenerateReleaseNotes.new.write_output_file diff --git a/.gitignore b/.gitignore index 4d7a7f20db..e9b456f626 100644 --- a/.gitignore +++ b/.gitignore @@ -40,3 +40,4 @@ vendor/ Brewfile.lock.json .github/actions/simplecov-report/lib/ test/minitest/minitest_time_report +gem_manifest_*.json diff --git a/.rubocop.yml b/.rubocop.yml index b477ec5c6c..f07ac203ad 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -66,7 +66,7 @@ Style/RedundantEach: # new in 1.38 Enabled: true Style/RedundantInitialize: # new in 1.27 Enabled: true -Style/RedundantStringEscape: # new in 1.37 +Style/RedundantStringEscape: # new in 1.37, 'pending' by default so enabled to make sure it's applied Enabled: true Style/YodaExpression: # new in 1.42 Enabled: true @@ -140,7 +140,8 @@ Performance/StringIdentifierArgument: # new in 1.13 Enabled: true Performance/StringInclude: # new in 1.7 Enabled: true - +Performance/Sum: # new in 1.8, pending so left enabled explicitly until 2.0 + Enabled: true # Old cops @@ -1255,9 +1256,6 @@ Style/DocumentationMethod: Style/DoubleCopDisableDirective: Enabled: false -Style/DoubleNegation: - Enabled: false - Style/EachForSimpleLoop: Enabled: true @@ -1318,6 +1316,9 @@ Style/ExplicitBlockArgument: Style/ExponentialNotation: Enabled: false +Style/FetchEnvVar: + Enabled: false + Style/FloatDivision: Enabled: false @@ -1781,17 +1782,6 @@ Style/StringConcatenation: Style/StringHashKeys: Enabled: false -# Disabling for now -Style/StringLiterals: - Enabled: false -# EnforcedStyle: double_quotes -# ConsistentQuotesInMultiline: false - -# Disabling for now -Style/StringLiteralsInInterpolation: - Enabled: false - # EnforcedStyle: double_quotes - Style/StringMethods: Enabled: false diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml index eae2743522..a2a3c22df6 100644 --- a/.rubocop_todo.yml +++ b/.rubocop_todo.yml @@ -9,10 +9,11 @@ # Offense count: 422 # Configuration parameters: AllowedMethods, AllowedPatterns, IgnoredMethods, CountRepeatedAttributes. Metrics/AbcSize: - Max: 54 + Max: 40 Exclude: - - test/**/* - infinite_tracing/test/**/* + - lib/new_relic/cli/commands/deployments.rb + - test/**/* # This cop supports safe autocorrection (--autocorrect). Minitest/AssertInDelta: @@ -36,6 +37,7 @@ Minitest/DuplicateTestRun: Minitest/EmptyLineBeforeAssertionMethods: Exclude: - 'test/new_relic/agent_test.rb' + - 'test/new_relic/cli/commands/deployments_test.rb' # Offense count: 269 Minitest/MultipleAssertions: @@ -57,44 +59,3 @@ Style/ConcatArrayLiterals: Minitest/RefuteRespondTo: Exclude: - 'test/new_relic/cli/commands/deployments_test.rb' - -Minitest/EmptyLineBeforeAssertionMethods: - Exclude: - - 'test/new_relic/agent_test.rb' - - 'test/new_relic/cli/commands/deployments_test.rb' - -# Offense count: 23 -# This cop supports safe autocorrection (--autocorrect). -Performance/RegexpMatch: - Enabled: false - -# Offense count: 1 -# This cop supports unsafe autocorrection (--autocorrect-all). -# Configuration parameters: OnlySumOrWithInitialValue. -Performance/Sum: - Exclude: - - 'lib/new_relic/agent/system_info.rb' - -# Offense count: 72 -# This cop supports unsafe autocorrection (--autocorrect-all). -Performance/UnfreezeString: - Enabled: false - -# Offense count: 21 -# This cop supports safe autocorrection (--autocorrect). -# Configuration parameters: AllowedVars. -Style/FetchEnvVar: - Enabled: false - -# Offense count: 1 -# This cop supports safe autocorrection (--autocorrect). -Style/RedundantStringEscape: - Exclude: - - 'test/new_relic/agent/logging_test.rb' - -# Offense count: 115 -# This cop supports unsafe autocorrection (--autocorrect-all). -# Configuration parameters: ConvertCodeThatCanStartToReturnNil, AllowedMethods, MaxChainLength. -# AllowedMethods: present?, blank?, presence, try, try! -Style/SafeNavigation: - Enabled: false diff --git a/.simplecov b/.simplecov index a8bb2cdb95..98eaabb7c0 100644 --- a/.simplecov +++ b/.simplecov @@ -10,6 +10,6 @@ end SimpleCov.start do enable_coverage(:branch) SimpleCov.root(File.join(File.dirname(__FILE__), '/lib')) - track_files("**/*.rb") + track_files('**/*.rb') formatter(SimpleCov::Formatter::SimpleFormatter) if ENV['CI'] end diff --git a/CHANGELOG.md b/CHANGELOG.md index 4950388ae5..9f18fb19b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,63 @@ # New Relic Ruby Agent Release Notes +## v9.1.0 + + Version 9.1.0 of the agent delivers support for two new [errors inbox](https://docs.newrelic.com/docs/errors-inbox/errors-inbox/) features: error fingerprinting and user tracking, identifies the Amazon Timestream data store, removes Distributed Tracing warnings from agent logs when using Sidekiq, fixes bugs, and is tested against the recently released JRuby 9.4.2.0. + +- **Feature: Error fingerprinting - supply your own errors inbox group names** + + Are your error occurrences grouped poorly? Set your own error fingerprint via a callback function. A new `set_error_group_callback` public API method has been added that will accept a user defined proc. The proc will be invoked for each noticed error and whenever it returns a string, that string will be used as the error group name for the error and will take precedence over any server-side grouping that takes place with the New Relic errors inbox. This gives users much greater control over the grouping of their errors. + + The customer defined proc will be expected to receive exactly one input argument, a hash. The hash contains the following: + + | Key | Value | + | ---------------------| ---------------------------------------------------------------------------- | + | `:error` | The Ruby error class instance. Offers `#class`, `#message`, and `#backtrace` | + | `:customAttributes` | Any customer defined custom attributes for the current transaction | + | `:'request.uri'` | The current request URI if available | + | `:'http.statusCode'` | The HTTP status code (200, 404, etc.) if available | + | `:'http.method'` | The HTTP method (GET, PUT, etc.) if available | + | `:'error.expected'` | Whether (true) or not (false) the error was expected | + | `:'options'` | The options hash passed to `NewRelic::Agent.notice_error` | + + The callback only needs to be set once per initialization of the New Relic agent. + + Example usage: + + ``` + proc = proc { |hash| "Access" if hash[:'http.statusCode'] == 401 } + NewRelic::Agent.set_error_group_callback(proc) + ``` + +- **Feature: User tracking - associate errors with a user id** + + You can now see the number of users impacted by an error group. Identify the end user with a new `set_user_id` public API method that will accept a string representation of a user id and associate that user id with the current transaction. Transactions and errors will then have a new `enduser.id` agent attribute associated with them. This will allow agent users to tag transactions and errors as belonging to given user ids in support of greater filtering and alerting capabilities. + +- **Identify Amazon Timestream when the amazon_timestream AR adapter is used** + + When the agent sees the [activerecord-amazon-timestream-adapter](https://rubygems.org/gems/activerecord-amazon-timestream-adapter) gem being used, it will now identify the data store as "Timestream". Thanks very much to [@wagner](https://github.com/wagner) for contributing this enhancement! [PR#1872](https://github.com/newrelic/newrelic-ruby-agent/pull/1872) + +- **Bugfix: Remove Distributed Tracing related warnings from agent logs when headers are not present in Sidekiq** + + Previously, the agent would log a warning to `newrelic_agent.log` every time it attempted to accept empty Distributed Tracing headers from Sidekiq jobs which could result in an excessive number of warnings. Now the agent will no longer create these warnings when using Sidekiq. [PR#1834](https://github.com/newrelic/newrelic-ruby-agent/pull/1834) + +- **Bugfix: Log request headers in debug-level logs instead of human-readable Objects** + + Previously, the agent sometimes received children of the `NewRelic::Agent::HTTPClients::AbstractRequest` class as an argument when `NewRelic::Agent::Transaction::DistributedTracers#log_request_headers` was called. This caused debug-level log messages that print the request headers to show human-readable Objects (ex. `#`) instead of the request headers. Now, the hash of the request headers should always be logged. [PR#1839](https://github.com/newrelic/newrelic-ruby-agent/pull/1839) + +- **Bugfix: Fix undefined method `controller_path` logged in Action Controller Instrumentation** + + Previously, the agent could log an error when trying to determine the metric name in the Action Controller instrumentation if the controller class did not respond to `controller_path`. This has been resolved and the agent will no longer call this method unless the class responds to it. Thank you to [@gsar](https://github.com/gsar) for letting us know about this issue. [PR#1844](https://github.com/newrelic/newrelic-ruby-agent/pull/1844) + +- **Bugfix: Fix Transaction#finish exception and decrease log level for related warning during async transactions** + + Previously, the agent would raise a non-fatal error when a segment without a parent was unfinished when the transaction completed. This error was raised while constructing a `warn`-level log message. Now that Thread instrumentation is on by default, this log message emits more frequently and is less concerning. In cases where we see a Thread, Fiber, or concurrent-ruby segment in a transaction, the message will be degraded to a `debug`-level. Thanks to [@NielsKSchjoedt](https://github.com/NielsKSchjoedt) for creating the issue and [@boomer196](https://github.com/boomer196) for testing solutions. [PR#1876](https://github.com/newrelic/newrelic-ruby-agent/pull/1876) + +- **CI: Target JRuby 9.4.2.0** + + The agent is now actively being tested against JRuby 9.4.2.0. NOTE that this release does not contain any non-CI related changes for JRuby. Old agent versions are still expected to work with newer JRubies and the newest agent version is still expected to work with older JRubies. + + ## v9.0.0 Version 9.0.0 of the agent removes several deprecated configuration options and API methods, enables Thread tracing by default, adds Fiber instrumentation, removes support for Ruby versions 2.2 and 2.3, removes instrumentation for several deprecated gems, changes how the API method `set_transaction_name` works, and updates `rails_defer_initialization` to be an environment variable only configuration option. @@ -92,8 +150,8 @@ - HttpClient: 2.2.0 - 2.8.0 - HttpRb: 0.9.9 - 2.2.1 - Typhoeus: 0.5.3 - 1.2.x - - Bunny: 2.0.x - 2.6.x - - ActiveMerchant: 1.25.0 - 1.64.x + - Bunny: 2.0.x - 2.6.x + - ActiveMerchant: 1.25.0 - 1.64.x - **Updated API method `set_transaction_name`** diff --git a/Gemfile b/Gemfile index 2a2ef94672..98632a9f23 100644 --- a/Gemfile +++ b/Gemfile @@ -3,4 +3,4 @@ # frozen_string_literal: true source 'https://rubygems.org' -gemspec name: "newrelic_rpm" +gemspec name: 'newrelic_rpm' diff --git a/Guardfile b/Guardfile index 6d592c0ffb..05f2d9e1fa 100644 --- a/Guardfile +++ b/Guardfile @@ -1,10 +1,10 @@ # frozen_string_literal: true require './test/multiverse/lib/multiverse/bundler_patch' -test_folders = Dir.glob("test/new_relic/*").select { |f| File.directory?(f) } -test_folders += Dir.glob("test/new_relic/**/*").select { |f| File.directory?(f) } +test_folders = Dir.glob('test/new_relic/*').select { |f| File.directory?(f) } +test_folders += Dir.glob('test/new_relic/**/*').select { |f| File.directory?(f) } -rake_lib_path = Bundler.with_unbundled_env { `bundle exec gem which rake`.chomp.gsub("lib/rake.rb", "lib") } +rake_lib_path = Bundler.with_unbundled_env { `bundle exec gem which rake`.chomp.gsub('lib/rake.rb', 'lib') } ruby_options = %(-w -I"#{rake_lib_path}" "#{rake_lib_path}/rake/rake_test_loader.rb") guard_options = { @@ -17,10 +17,10 @@ guard_options = { guard :minitest, guard_options do watch(%r{^lib/(.+)\.rb$}) { |m| "test/#{m[1]}_test.rb" } watch(%r{^test/.+_test\.rb$}) - watch(%r{^test/rum/.*}) { "test/new_relic/rack/browser_monitoring_test.rb" } + watch(%r{^test/rum/.*}) { 'test/new_relic/rack/browser_monitoring_test.rb' } watch(%r{^test/fixtures/cross_agent_tests/distributed_tracing/(.+).json}) { |m| "test/new_relic/agent/distributed_tracing/#{m[1]}_cross_agent_test.rb" } - watch('test/test_helper.rb') { "test/new_relic" } - watch('test/agent_helper.rb') { "test/new_relic" } - watch('lib/new_relic/agent/configuration/default_source.rb') { "test/new_relic/agent/configuration/orphan_configuration_test.rb" } + watch('test/test_helper.rb') { 'test/new_relic' } + watch('test/agent_helper.rb') { 'test/new_relic' } + watch('lib/new_relic/agent/configuration/default_source.rb') { 'test/new_relic/agent/configuration/orphan_configuration_test.rb' } watch(%r{^lib/new_relic/agent/transaction/(.+).rb}) { |m| "test/new_relic/agent/distributed_tracing/#{m[1]}_cross_agent_test.rb" } end diff --git a/README.md b/README.md index 1545d17090..a8d53ffba9 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,4 @@ -[![Community Plus header](https://github.com/newrelic/opensource-website/raw/main/src/images/categories/Community_Plus.png)](https://opensource.newrelic.com/oss-category/#community-plus) - +New Relic Open Source community plus project banner. # New Relic Ruby Agent diff --git a/Rakefile b/Rakefile index 3792702104..fe15cc68a7 100644 --- a/Rakefile +++ b/Rakefile @@ -15,11 +15,11 @@ task :default => :test task :test => ['test:newrelic'] namespace :test do - desc "Run all tests" + desc 'Run all tests' task :all => %w[newrelic multiverse all_compatible_envs] agent_home = File.expand_path(File.dirname(__FILE__)) - desc "Run agent performance tests" + desc 'Run agent performance tests' task :performance, [:suite, :name] => [] do |t, args| require File.expand_path(File.join(File.dirname(__FILE__), 'test', 'performance', 'lib', 'performance')) options = {} @@ -28,13 +28,13 @@ namespace :test do Performance::Runner.new(options).run_and_report end - desc "Run agent within existing mini environment(s): env[name1,name2,name3,etc.]" + desc 'Run agent within existing mini environment(s): env[name1,name2,name3,etc.]' task :env do |t, args| require File.expand_path(File.join(File.dirname(__FILE__), 'test', 'environments', 'lib', 'environments', 'runner')) Environments::Runner.new(args.to_a).run_and_report end - desc "Run all mini environment tests known to work with the current Ruby version" + desc 'Run all mini environment tests known to work with the current Ruby version' task :all_compatible_envs do |t, args| require File.expand_path(File.join(File.dirname(__FILE__), 'test', 'helpers', 'ruby_rails_mappings')) rails_versions = rails_versions_for_ruby_version(RUBY_VERSION) @@ -62,10 +62,10 @@ task :record_build, [:build_number, :stage] do |t, args| build_string = args.build_number build_string << ".#{args.stage}" unless args.stage.nil? || args.stage.empty? - gitsha = File.exist?(".git") ? `git rev-parse HEAD` : "Unknown" + gitsha = File.exist?('.git') ? `git rev-parse HEAD` : 'Unknown' gitsha.chomp! - File.open("lib/new_relic/build.rb", "w") do |f| + File.open('lib/new_relic/build.rb', 'w') do |f| f.write("# GITSHA: #{gitsha}\n") f.write("module NewRelic; module VERSION; BUILD='#{build_string}'; end; end\n") end @@ -93,14 +93,14 @@ task :update_ca_bundle do |t| bundle_last_update = `cd #{ca_bundle_path} && git show -s --format=%ci HEAD` puts "Source CA bundle last updated #{bundle_last_update}" - bundle_path = "cert/cacert.pem" + bundle_path = 'cert/cacert.pem' cert_paths = [] Dir.glob("#{ca_bundle_path}/*.pem").each { |p| cert_paths << p } cert_paths.sort! puts "Writing #{cert_paths.size} certs to bundle at #{bundle_path}..." - File.open(bundle_path, "w") do |f| + File.open(bundle_path, 'w') do |f| cert_paths.each do |cert_path| cert_name = File.basename(cert_path, '.pem') puts "Adding #{cert_name}" diff --git a/Thorfile b/Thorfile index b883c3c820..113ead294e 100644 --- a/Thorfile +++ b/Thorfile @@ -2,4 +2,4 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -Dir["./lib/tasks/**/*.thor"].sort.each { |f| load f } +Dir['./lib/tasks/**/*.thor'].sort.each { |f| load f } diff --git a/bin/nrdebug b/bin/nrdebug index 33460a9d53..d998c4e56d 100755 --- a/bin/nrdebug +++ b/bin/nrdebug @@ -96,7 +96,7 @@ class LinuxProcessDataProvider < ProcessDataProvider end def procline - File.read(proc_path('cmdline')).tr("\000", " ") + File.read(proc_path('cmdline')).tr("\000", ' ') end def environment @@ -189,7 +189,7 @@ class ProcessReport def open if @path - File.open(@path, "w") do |f| + File.open(@path, 'w') do |f| yield(f) end else @@ -216,16 +216,16 @@ class ProcessReport section(f) do c_backtraces, ruby_backtraces = @target.gather_backtraces - if c_backtraces =~ /could not attach/i - fail("Failed to attach to target process. Please try again with sudo.") + if /could not attach/i.match?(c_backtraces) + fail('Failed to attach to target process. Please try again with sudo.') end - section(f, "C Backtraces") { c_backtraces } - section(f, "Ruby Backtrace(s)") { ruby_backtraces } + section(f, 'C Backtraces') { c_backtraces } + section(f, 'Ruby Backtrace(s)') { ruby_backtraces } end - section(f, "Open files") { @target.open_files } - section(f, "Log") do + section(f, 'Open files') { @target.open_files } + section(f, 'Log') do commands = Logger.messages.map { |(_, msg)| msg } commands.join("\n") end @@ -235,14 +235,14 @@ class ProcessReport private def add_environment_sections(handle) - section(handle, "Time") { Time.now } - section(handle, "PID") { @target.pid } - section(handle, "Command") { @target.procline } - section(handle, "RSS") { @target.rss } - section(handle, "CPU") { @target.cpu } - section(handle, "Parent PID") { @target.ppid } - section(handle, "OS") { ShellWrapper.execute('uname -a') } - section(handle, "Environment") { @target.environment } + section(handle, 'Time') { Time.now } + section(handle, 'PID') { @target.pid } + section(handle, 'Command') { @target.procline } + section(handle, 'RSS') { @target.rss } + section(handle, 'CPU') { @target.cpu } + section(handle, 'Parent PID') { @target.ppid } + section(handle, 'OS') { ShellWrapper.execute('uname -a') } + section(handle, 'Environment') { @target.environment } end end @@ -270,10 +270,10 @@ def prompt_for_confirmation(target_pid, target_cmd) end target_pid = ARGV[0] -fail("Please provide a PID for the target process", :usage => true) unless target_pid +fail('Please provide a PID for the target process', :usage => true) unless target_pid gdb_path = `which gdb` -fail("Could not find gdb, please ensure it is installed and in your PATH") if gdb_path.empty? +fail('Could not find gdb, please ensure it is installed and in your PATH') if gdb_path.empty? target = RubyProcess.new(target_pid) if !target.attachable? @@ -298,5 +298,5 @@ report.generate puts "Generated '#{report_filename}'" puts '' -puts "Please examine the output file for potentially sensitive information and" -puts "remove it before sharing this file with anyone." +puts 'Please examine the output file for potentially sensitive information and' +puts 'remove it before sharing this file with anyone.' diff --git a/infinite_tracing/Gemfile b/infinite_tracing/Gemfile index 1522c3b61b..a0c78fdf10 100644 --- a/infinite_tracing/Gemfile +++ b/infinite_tracing/Gemfile @@ -4,7 +4,7 @@ source 'https://rubygems.org' -gemspec name: "newrelic-infinite_tracing" +gemspec name: 'newrelic-infinite_tracing' group :development do gem 'newrelic_rpm', path: '..' diff --git a/infinite_tracing/Rakefile b/infinite_tracing/Rakefile index 5568ed0d73..b1e2c9cc52 100644 --- a/infinite_tracing/Rakefile +++ b/infinite_tracing/Rakefile @@ -23,6 +23,6 @@ Rake::TestTask.new do |t| t.libs << "#{ROOT}/test" t.libs << "#{ROOT}/lib" - t.pattern = Array(file_pattern).join(",") - t.verbose = ENV["VERBOSE"] + t.pattern = Array(file_pattern).join(',') + t.verbose = ENV['VERBOSE'] end diff --git a/infinite_tracing/lib/infinite_tracing/agent_integrations.rb b/infinite_tracing/lib/infinite_tracing/agent_integrations.rb index f5f307eebc..3b00d5f1cc 100644 --- a/infinite_tracing/lib/infinite_tracing/agent_integrations.rb +++ b/infinite_tracing/lib/infinite_tracing/agent_integrations.rb @@ -5,7 +5,7 @@ module NewRelic::Agent module InfiniteTracing if Config.enabled? || Config.test_framework? - NewRelic::Agent.logger.debug("Integrating Infinite Tracer with Agent") + NewRelic::Agent.logger.debug('Integrating Infinite Tracer with Agent') require_relative 'agent_integrations/agent' require_relative 'agent_integrations/segment' @@ -13,7 +13,7 @@ module InfiniteTracing require_relative 'agent_integrations/external_request_segment' else - NewRelic::Agent.logger.debug("Skipped Integrating Infinite Tracer with Agent") + NewRelic::Agent.logger.debug('Skipped Integrating Infinite Tracer with Agent') end end end diff --git a/infinite_tracing/lib/infinite_tracing/agent_integrations/agent.rb b/infinite_tracing/lib/infinite_tracing/agent_integrations/agent.rb index e05e5d1954..5b1ff268c5 100644 --- a/infinite_tracing/lib/infinite_tracing/agent_integrations/agent.rb +++ b/infinite_tracing/lib/infinite_tracing/agent_integrations/agent.rb @@ -3,7 +3,7 @@ # frozen_string_literal: true module NewRelic::Agent - NewRelic::Agent.logger.debug("Installing Infinite Tracer in Agent") + NewRelic::Agent.logger.debug('Installing Infinite Tracer in Agent') Agent.class_eval do def new_infinite_tracer @@ -11,7 +11,7 @@ def new_infinite_tracer # entire start up process for the Agent. InfiniteTracing::Client.new.tap do |client| @infinite_tracer_thread = InfiniteTracing::Worker.new(:infinite_tracer) do - NewRelic::Agent.logger.debug("Opening Infinite Tracer Stream with gRPC server") + NewRelic::Agent.logger.debug('Opening Infinite Tracer Stream with gRPC server') client.start_streaming end end @@ -23,7 +23,7 @@ def new_infinite_tracer def handle_force_restart(error) ::NewRelic::Agent.logger.debug(error.message) drop_buffered_data - @service.force_restart if @service + @service&.force_restart @connect_state = :pending close_infinite_tracer sleep(30) @@ -31,7 +31,7 @@ def handle_force_restart(error) # Whenever we reconnect, close and restart def close_infinite_tracer - NewRelic::Agent.logger.debug("Closing infinite tracer threads") + NewRelic::Agent.logger.debug('Closing infinite tracer threads') return unless @infinite_tracer_thread @infinite_tracer_thread.join diff --git a/infinite_tracing/lib/infinite_tracing/client.rb b/infinite_tracing/lib/infinite_tracing/client.rb index 2a8585d55a..56614463ad 100644 --- a/infinite_tracing/lib/infinite_tracing/client.rb +++ b/infinite_tracing/lib/infinite_tracing/client.rb @@ -55,7 +55,7 @@ def flush # Turns camelcase base class name into upper snake case version of the name. def formatted_class_name(class_name) - class_name = class_name.split(":")[-1] + class_name = class_name.split(':')[-1] (class_name.gsub!(/(.)([A-Z])/, '\1_\2') || class_name).upcase end @@ -73,7 +73,7 @@ def record_error_metrics_and_log(error) else NewRelic::Agent.record_metric(GRPC_OTHER_ERROR_METRIC, 0.0) end - NewRelic::Agent.logger.warn("gRPC response error received.", error) + NewRelic::Agent.logger.warn('gRPC response error received.', error) end def handle_error(error) @@ -99,8 +99,8 @@ def suspended? # server and re-establish the gRPC bi-directional stream. Useful for the server # to initiate a load-balancing scheme. def handle_close - NewRelic::Agent.logger.debug("The gRPC Trace Observer closed the stream with OK response. " \ - "Restarting the stream.") + NewRelic::Agent.logger.debug('The gRPC Trace Observer closed the stream with OK response. ' \ + 'Restarting the stream.') start_streaming end @@ -113,8 +113,8 @@ def suspend @lock.synchronize do @suspended = true @buffer = new_streaming_buffer - NewRelic::Agent.logger.warn("The Trace Observer host signaled to suspend streaming span events. " \ - "No more span events will be sent during this session.") + NewRelic::Agent.logger.warn('The Trace Observer host signaled to suspend streaming span events. ' \ + 'No more span events will be sent during this session.') end end diff --git a/infinite_tracing/lib/infinite_tracing/config.rb b/infinite_tracing/lib/infinite_tracing/config.rb index 46300ec70e..97c9b03eae 100644 --- a/infinite_tracing/lib/infinite_tracing/config.rb +++ b/infinite_tracing/lib/infinite_tracing/config.rb @@ -10,7 +10,7 @@ module Config COMPRESSION_LEVEL_DISABLED = :none COMPRESSION_LEVEL_DEFAULT = :high COMPRESSION_LEVEL_LIST = %i[none low medium high].freeze - TRACE_OBSERVER_NOT_CONFIGURED_ERROR = "Trace Observer host not configured!" + TRACE_OBSERVER_NOT_CONFIGURED_ERROR = 'Trace Observer host not configured!' # We only want to load the infinite tracing gem's files when # a) we're inside test framework and running tests @@ -64,7 +64,7 @@ def trace_observer_host # is overridden by the presence of the port on the host entry. def port_from_host_entry port_str = NewRelic::Agent.config[:'infinite_tracing.trace_observer.host'].scan(%r{:(\d+)$}).flatten - if port = (port_str[0] and port_str[0].to_i) + if port = port_str[0]&.to_i NewRelic::Agent.logger.warn(":'infinite_tracing.trace_observer.port' is ignored if present because :'infinite_tracing.trace_observer.host' specifies the port") return port end diff --git a/infinite_tracing/lib/infinite_tracing/connection.rb b/infinite_tracing/lib/infinite_tracing/connection.rb index 95667639b6..30c783b5d3 100644 --- a/infinite_tracing/lib/infinite_tracing/connection.rb +++ b/infinite_tracing/lib/infinite_tracing/connection.rb @@ -31,7 +31,7 @@ class Connection Connection.instance.notify_agent_started rescue => error NewRelic::Agent.logger.error( \ - "Error during notify :server_source_configuration_added event", + 'Error during notify :server_source_configuration_added event', error ) end @@ -102,8 +102,8 @@ def metadata @lock.synchronize do @metadata = { - "license_key" => license_key, - "agent_run_token" => agent_id + 'license_key' => license_key, + 'agent_run_token' => agent_id } @metadata.merge!(request_headers_map) merge_gzip_metadata @@ -168,7 +168,7 @@ def with_reconnection_backoff(exponential_backoff = true, &block) yield rescue => exception retry_connection_period = retry_connection_period(exponential_backoff) - ::NewRelic::Agent.logger.error("Error establishing connection with infinite tracing service:", exception) + ::NewRelic::Agent.logger.error('Error establishing connection with infinite tracing service:', exception) ::NewRelic::Agent.logger.info("Will re-attempt infinite tracing connection in #{retry_connection_period} seconds") sleep(retry_connection_period) note_connect_failure diff --git a/infinite_tracing/lib/infinite_tracing/constants.rb b/infinite_tracing/lib/infinite_tracing/constants.rb index 6f9780e0c8..c76b8613a8 100644 --- a/infinite_tracing/lib/infinite_tracing/constants.rb +++ b/infinite_tracing/lib/infinite_tracing/constants.rb @@ -5,7 +5,7 @@ module NewRelic::Agent module InfiniteTracing module Constants - SUPPORTABILITY_PREFIX = "Supportability/InfiniteTracing/Span" + SUPPORTABILITY_PREFIX = 'Supportability/InfiniteTracing/Span' SPANS_SEEN_METRIC = "#{SUPPORTABILITY_PREFIX}/Seen" SPANS_SENT_METRIC = "#{SUPPORTABILITY_PREFIX}/Sent" @@ -13,7 +13,7 @@ module Constants RESPONSE_ERROR_METRIC = "#{SUPPORTABILITY_PREFIX}/Response/Error" GRPC_ERROR_NAME_METRIC = "#{SUPPORTABILITY_PREFIX}/gRPC/%s" - GRPC_OTHER_ERROR_METRIC = GRPC_ERROR_NAME_METRIC % "Other" + GRPC_OTHER_ERROR_METRIC = GRPC_ERROR_NAME_METRIC % 'Other' end end end diff --git a/infinite_tracing/lib/infinite_tracing/proto/infinite_tracing_pb.rb b/infinite_tracing/lib/infinite_tracing/proto/infinite_tracing_pb.rb index d1fcdc8848..b2b080edfe 100644 --- a/infinite_tracing/lib/infinite_tracing/proto/infinite_tracing_pb.rb +++ b/infinite_tracing/lib/infinite_tracing/proto/infinite_tracing_pb.rb @@ -6,16 +6,16 @@ # source: infinite_tracing.proto Google::Protobuf::DescriptorPool.generated_pool.build do - add_message "com.newrelic.trace.v1.SpanBatch" do - repeated :spans, :message, 1, "com.newrelic.trace.v1.Span" + add_message 'com.newrelic.trace.v1.SpanBatch' do + repeated :spans, :message, 1, 'com.newrelic.trace.v1.Span' end - add_message "com.newrelic.trace.v1.Span" do + add_message 'com.newrelic.trace.v1.Span' do optional :trace_id, :string, 1 - map :intrinsics, :string, :message, 2, "com.newrelic.trace.v1.AttributeValue" - map :user_attributes, :string, :message, 3, "com.newrelic.trace.v1.AttributeValue" - map :agent_attributes, :string, :message, 4, "com.newrelic.trace.v1.AttributeValue" + map :intrinsics, :string, :message, 2, 'com.newrelic.trace.v1.AttributeValue' + map :user_attributes, :string, :message, 3, 'com.newrelic.trace.v1.AttributeValue' + map :agent_attributes, :string, :message, 4, 'com.newrelic.trace.v1.AttributeValue' end - add_message "com.newrelic.trace.v1.AttributeValue" do + add_message 'com.newrelic.trace.v1.AttributeValue' do oneof :value do optional :string_value, :string, 1 optional :bool_value, :bool, 2 @@ -23,7 +23,7 @@ optional :double_value, :double, 4 end end - add_message "com.newrelic.trace.v1.RecordStatus" do + add_message 'com.newrelic.trace.v1.RecordStatus' do optional :messages_seen, :uint64, 1 end end @@ -32,10 +32,10 @@ module Com module Newrelic module Trace module V1 - SpanBatch = Google::Protobuf::DescriptorPool.generated_pool.lookup("com.newrelic.trace.v1.SpanBatch").msgclass - Span = Google::Protobuf::DescriptorPool.generated_pool.lookup("com.newrelic.trace.v1.Span").msgclass - AttributeValue = Google::Protobuf::DescriptorPool.generated_pool.lookup("com.newrelic.trace.v1.AttributeValue").msgclass - RecordStatus = Google::Protobuf::DescriptorPool.generated_pool.lookup("com.newrelic.trace.v1.RecordStatus").msgclass + SpanBatch = Google::Protobuf::DescriptorPool.generated_pool.lookup('com.newrelic.trace.v1.SpanBatch').msgclass + Span = Google::Protobuf::DescriptorPool.generated_pool.lookup('com.newrelic.trace.v1.Span').msgclass + AttributeValue = Google::Protobuf::DescriptorPool.generated_pool.lookup('com.newrelic.trace.v1.AttributeValue').msgclass + RecordStatus = Google::Protobuf::DescriptorPool.generated_pool.lookup('com.newrelic.trace.v1.RecordStatus').msgclass end end end diff --git a/infinite_tracing/lib/infinite_tracing/record_status_handler.rb b/infinite_tracing/lib/infinite_tracing/record_status_handler.rb index 0946509ee0..2775d814dd 100644 --- a/infinite_tracing/lib/infinite_tracing/record_status_handler.rb +++ b/infinite_tracing/lib/infinite_tracing/record_status_handler.rb @@ -21,7 +21,7 @@ def stop return if @worker.nil? @lock.synchronize do - NewRelic::Agent.logger.debug("gRPC Stopping Response Handler") + NewRelic::Agent.logger.debug('gRPC Stopping Response Handler') @worker.stop @worker = nil end @@ -43,13 +43,13 @@ def handle_response def start_handler Worker.new(self.class.name) do handle_response - NewRelic::Agent.logger.debug("gRPC Infinite Tracer Observer closed the stream") + NewRelic::Agent.logger.debug('gRPC Infinite Tracer Observer closed the stream') @client.handle_close rescue => error @client.handle_error(error) end rescue => error - NewRelic::Agent.logger.error("gRPC Worker Error", error) + NewRelic::Agent.logger.error('gRPC Worker Error', error) end end end diff --git a/infinite_tracing/lib/infinite_tracing/transformer.rb b/infinite_tracing/lib/infinite_tracing/transformer.rb index ba4a0ebc24..be6301fd99 100644 --- a/infinite_tracing/lib/infinite_tracing/transformer.rb +++ b/infinite_tracing/lib/infinite_tracing/transformer.rb @@ -10,10 +10,10 @@ module Transformer def transform(span_event) intrinsics, user_attributes, agent_attributes = span_event { - "trace_id" => intrinsics[NewRelic::Agent::SpanEventPrimitive::TRACE_ID_KEY], - "intrinsics" => hash_to_attributes(intrinsics), - "user_attributes" => hash_to_attributes(user_attributes), - "agent_attributes" => hash_to_attributes(agent_attributes) + 'trace_id' => intrinsics[NewRelic::Agent::SpanEventPrimitive::TRACE_ID_KEY], + 'intrinsics' => hash_to_attributes(intrinsics), + 'user_attributes' => hash_to_attributes(user_attributes), + 'agent_attributes' => hash_to_attributes(agent_attributes) } end diff --git a/infinite_tracing/lib/infinite_tracing/worker.rb b/infinite_tracing/lib/infinite_tracing/worker.rb index 34e45ec861..b460be1d3c 100644 --- a/infinite_tracing/lib/infinite_tracing/worker.rb +++ b/infinite_tracing/lib/infinite_tracing/worker.rb @@ -21,12 +21,12 @@ def initialize(name, &job) end def status - return "error" if error? + return 'error' if error? @lock.synchronize do - return "stopped" if @worker_thread.nil? + return 'stopped' if @worker_thread.nil? - @worker_thread.status || "idle" + @worker_thread.status || 'idle' end end @@ -55,7 +55,7 @@ def stop def start_thread NewRelic::Agent.logger.debug("starting worker #{@name} thread...") - @worker_thread = NewRelic::Agent::Threading::AgentThread.create("infinite_tracing_worker") do + @worker_thread = NewRelic::Agent::Threading::AgentThread.create('infinite_tracing_worker') do catch(:exit) do begin @job.call @@ -67,7 +67,7 @@ def start_thread end @worker_thread.abort_on_exception = true if @worker_thread.respond_to?(:report_on_exception) - @worker_thread.report_on_exception = NewRelic::Agent.config[:log_level] == "debug" + @worker_thread.report_on_exception = NewRelic::Agent.config[:log_level] == 'debug' end end end diff --git a/infinite_tracing/lib/newrelic/infinite_tracing.rb b/infinite_tracing/lib/newrelic/infinite_tracing.rb index b07d5c6f96..4f5bbf02ce 100644 --- a/infinite_tracing/lib/newrelic/infinite_tracing.rb +++ b/infinite_tracing/lib/newrelic/infinite_tracing.rb @@ -8,7 +8,7 @@ require 'newrelic_rpm' -NewRelic::Agent.logger.debug("Detected New Relic Infinite Tracing Gem") +NewRelic::Agent.logger.debug('Detected New Relic Infinite Tracing Gem') require 'infinite_tracing/version' require 'infinite_tracing/config' @@ -21,7 +21,7 @@ end executes do - NewRelic::Agent.logger.debug("Loading New Relic Infinite Tracing Library") + NewRelic::Agent.logger.debug('Loading New Relic Infinite Tracing Library') require 'infinite_tracing/proto' diff --git a/infinite_tracing/newrelic-infinite_tracing.gemspec b/infinite_tracing/newrelic-infinite_tracing.gemspec index 3a6c97f9ba..0f7bb2e6b2 100644 --- a/infinite_tracing/newrelic-infinite_tracing.gemspec +++ b/infinite_tracing/newrelic-infinite_tracing.gemspec @@ -22,17 +22,17 @@ Gem::Specification.new do |s| end shared_files = [ - "../LICENSE", - "../CONTRIBUTING.md" + '../LICENSE', + '../CONTRIBUTING.md' ] self.copy_files(shared_files) - s.name = "newrelic-infinite_tracing" + s.name = 'newrelic-infinite_tracing' s.version = NewRelic::VERSION::STRING s.required_ruby_version = '>= 2.5.0' - s.required_rubygems_version = Gem::Requirement.new("> 1.3.1") if s.respond_to?(:required_rubygems_version=) - s.authors = ["Tanna McClure", "Kayla Reopelle", "James Bunch", "Hannah Ramadan"] + s.required_rubygems_version = Gem::Requirement.new('> 1.3.1') if s.respond_to?(:required_rubygems_version=) + s.authors = ['Tanna McClure', 'Kayla Reopelle', 'James Bunch', 'Hannah Ramadan'] s.licenses = ['Apache-2.0'] s.description = <<~EOS The New Relic Ruby agent requires the gem newrelic_rpm, and it includes distributed @@ -49,11 +49,11 @@ Gem::Specification.new do |s| Gem or plugin, hosted on https://github.com/newrelic/newrelic-ruby-agent/ EOS - s.email = "support@newrelic.com" + s.email = 'support@newrelic.com' s.executables = [] s.extra_rdoc_files = [ - "CHANGELOG.md", - "LICENSE" + 'CHANGELOG.md', + 'LICENSE' ] s.metadata = { @@ -61,15 +61,15 @@ Gem::Specification.new do |s| 'changelog_uri' => 'https://github.com/newrelic/newrelic-ruby-agent/blob/main/infinite_tracing/CHANGELOG.md', 'documentation_uri' => 'https://docs.newrelic.com/docs/agents/ruby-agent', 'source_code_uri' => 'https://github.com/newrelic/newrelic-ruby-agent', - "homepage_uri" => "https://newrelic.com/products/edge-infinite-tracing" + 'homepage_uri' => 'https://newrelic.com/products/edge-infinite-tracing' } file_list = `git ls-files . -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/(?!agent_helper.rb)}) } s.files = file_list - s.homepage = "https://github.com/newrelic/newrelic-ruby-agent/tree/main/infinite_tracing" + s.homepage = 'https://github.com/newrelic/newrelic-ruby-agent/tree/main/infinite_tracing' s.require_paths = %w[lib infinite_tracing] - s.summary = "New Relic Infinite Tracing for the Ruby agent" + s.summary = 'New Relic Infinite Tracing for the Ruby agent' s.add_dependency 'newrelic_rpm', NewRelic::VERSION::STRING s.add_dependency 'grpc', '~> 1.34' @@ -87,5 +87,5 @@ Gem::Specification.new do |s| s.add_development_dependency 'bundler' s.add_development_dependency 'simplecov' - s.add_development_dependency 'grpc-tools', "~> 1.14" + s.add_development_dependency 'grpc-tools', '~> 1.14' end diff --git a/infinite_tracing/tasks/helpers/license.rb b/infinite_tracing/tasks/helpers/license.rb index 5c5892badc..191f57babb 100644 --- a/infinite_tracing/tasks/helpers/license.rb +++ b/infinite_tracing/tasks/helpers/license.rb @@ -6,14 +6,14 @@ module License def extract_license_terms(file_contents) text = [] text << file_contents.shift while !file_contents.empty? && file_contents[0] =~ /^#/ - text << "" + text << '' text end def add_license_preamble_and_remove_requires(output_path) gemspec_path = File.expand_path(File.join(output_path, '..', '..', '..', '..', '..')) - license_terms = extract_license_terms(File.readlines(File.join(gemspec_path, "Gemfile"))) - Dir.glob(File.join(output_path, "*.rb")) do |filename| + license_terms = extract_license_terms(File.readlines(File.join(gemspec_path, 'Gemfile'))) + Dir.glob(File.join(output_path, '*.rb')) do |filename| contents = File.readlines(filename) contents.reject! { |r| r =~ /^\s*require\s.*$/ } File.open(filename, 'w') do |output| diff --git a/infinite_tracing/tasks/proto.rake b/infinite_tracing/tasks/proto.rake index 27f3771546..4024ec35b0 100644 --- a/infinite_tracing/tasks/proto.rake +++ b/infinite_tracing/tasks/proto.rake @@ -6,25 +6,25 @@ require_relative 'helpers/license' include License namespace :proto do - desc "Generate proto files" + desc 'Generate proto files' task :generate do - gem_folder = File.expand_path(File.join(File.dirname(__FILE__), "..")) - proto_filename = File.join(gem_folder, "lib", "new_relic", "proto", "infinite_tracing.proto") - output_path = File.join(gem_folder, "lib", "new_relic", "infinite_tracing", "proto") + gem_folder = File.expand_path(File.join(File.dirname(__FILE__), '..')) + proto_filename = File.join(gem_folder, 'lib', 'new_relic', 'proto', 'infinite_tracing.proto') + output_path = File.join(gem_folder, 'lib', 'new_relic', 'infinite_tracing', 'proto') FileUtils.mkdir_p(output_path) cmd = [ - "grpc_tools_ruby_protoc", + 'grpc_tools_ruby_protoc', "-I#{gem_folder}/lib/new_relic/proto", "--ruby_out=#{output_path}", "--grpc_out=#{output_path} #{proto_filename}" - ].join(" ") + ].join(' ') if system(cmd) - puts "Proto file generated!" + puts 'Proto file generated!' add_license_preamble_and_remove_requires(output_path) else - puts "Failed to generate proto file." + puts 'Failed to generate proto file.' end end end diff --git a/infinite_tracing/test/infinite_tracing/agent_integrations/agent_test.rb b/infinite_tracing/test/infinite_tracing/agent_integrations/agent_test.rb index 8c97696c65..1acd0701fc 100644 --- a/infinite_tracing/test/infinite_tracing/agent_integrations/agent_test.rb +++ b/infinite_tracing/test/infinite_tracing/agent_integrations/agent_test.rb @@ -11,7 +11,7 @@ class AgentIntegrationTest < Minitest::Test include FakeTraceObserverHelpers def test_injects_infinite_tracer - assert ::NewRelic::Agent.instance, "expected to get an Agent instance" + assert ::NewRelic::Agent.instance, 'expected to get an Agent instance' assert ::NewRelic::Agent.instance.infinite_tracer end diff --git a/infinite_tracing/test/infinite_tracing/agent_integrations/datastore_segment_test.rb b/infinite_tracing/test/infinite_tracing/agent_integrations/datastore_segment_test.rb index 133ef979ba..a967142dcd 100644 --- a/infinite_tracing/test/infinite_tracing/agent_integrations/datastore_segment_test.rb +++ b/infinite_tracing/test/infinite_tracing/agent_integrations/datastore_segment_test.rb @@ -17,19 +17,19 @@ def test_sampled_segment_records_span_event sampled = nil priority = nil timestamp = nil - sql_statement = "select * from table" + sql_statement = 'select * from table' span_events = generate_and_stream_segments do in_web_transaction('wat') do |txn| txn.stubs(:sampled?).returns(true) segment = Tracer.start_datastore_segment( - product: "SQLite", - collection: "Blahg", - operation: "select", - host: "rachel.foo", + product: 'SQLite', + collection: 'Blahg', + operation: 'select', + host: 'rachel.foo', port_path_or_id: 1337807, - database_name: "calzone_zone" + database_name: 'calzone_zone' ) segment.notice_sql(sql_statement) @@ -83,8 +83,8 @@ def test_non_sampled_segment_does_record_span_event txn.stubs(:sampled?).returns(false) segment = Tracer.start_datastore_segment( - product: "SQLite", - operation: "select", + product: 'SQLite', + operation: 'select', port_path_or_id: 1337807 ) @@ -105,8 +105,8 @@ def test_ignored_transaction_does_not_record_span_event txn.stubs(:ignore?).returns(true) segment = Tracer.start_datastore_segment( - product: "SQLite", - operation: "select", + product: 'SQLite', + operation: 'select', port_path_or_id: 1337807 ) diff --git a/infinite_tracing/test/infinite_tracing/agent_integrations/external_request_segment_test.rb b/infinite_tracing/test/infinite_tracing/agent_integrations/external_request_segment_test.rb index 8e94b43869..548b0f062c 100644 --- a/infinite_tracing/test/infinite_tracing/agent_integrations/external_request_segment_test.rb +++ b/infinite_tracing/test/infinite_tracing/agent_integrations/external_request_segment_test.rb @@ -24,9 +24,9 @@ def test_sampled_external_records_span_event txn.stubs(:sampled?).returns(true) segment = Transaction::ExternalRequestSegment.new( \ - "Typhoeus", - "http://remotehost.com/blogs/index", - "GET" + 'Typhoeus', + 'http://remotehost.com/blogs/index', + 'GET' ) txn.add_segment(segment) @@ -75,9 +75,9 @@ def test_non_sampled_segment_does_record_span_event txn.stubs(:sampled?).returns(false) segment = Transaction::ExternalRequestSegment.new( \ - "Typhoeus", - "http://remotehost.com/blogs/index", - "GET" + 'Typhoeus', + 'http://remotehost.com/blogs/index', + 'GET' ) txn.add_segment(segment) @@ -98,9 +98,9 @@ def test_ignored_transaction_does_not_record_span_event txn.stubs(:ignore?).returns(true) segment = Transaction::ExternalRequestSegment.new( \ - "Typhoeus", - "http://remotehost.com/blogs/index", - "GET" + 'Typhoeus', + 'http://remotehost.com/blogs/index', + 'GET' ) txn.add_segment(segment) diff --git a/infinite_tracing/test/infinite_tracing/channel_test.rb b/infinite_tracing/test/infinite_tracing/channel_test.rb index 53baf20940..d717411a9a 100644 --- a/infinite_tracing/test/infinite_tracing/channel_test.rb +++ b/infinite_tracing/test/infinite_tracing/channel_test.rb @@ -12,7 +12,7 @@ def local_config { :'distributed_tracing.enabled' => true, :'span_events.enabled' => true, - :'infinite_tracing.trace_observer.host' => "localhost:80" + :'infinite_tracing.trace_observer.host' => 'localhost:80' } end @@ -20,7 +20,7 @@ def remote_config { :'distributed_tracing.enabled' => true, :'span_events.enabled' => true, - :'infinite_tracing.trace_observer.host' => "https://example.com" + :'infinite_tracing.trace_observer.host' => 'https://example.com' } end @@ -31,7 +31,7 @@ def test_channel_is_secure_for_remote_host channel = Channel.new credentials = channel.send(:credentials) - assert_equal "example.com:443", channel.send(:host_and_port) + assert_equal 'example.com:443', channel.send(:host_and_port) assert_kind_of GRPC::Core::ChannelCredentials, credentials end ensure @@ -42,14 +42,14 @@ def test_channel_is_really_secure_for_remote_host Config.stubs(:test_framework?).returns(false) # HTTP instead of HTTPS... insecure_remote_config = remote_config.merge({ - :'infinite_tracing.trace_observer.host' => "http://example.com" + :'infinite_tracing.trace_observer.host' => 'http://example.com' }) with_config(insecure_remote_config) do channel = Channel.new credentials = channel.send(:credentials) - assert_equal "example.com:443", channel.send(:host_and_port) + assert_equal 'example.com:443', channel.send(:host_and_port) assert_kind_of GRPC::Core::ChannelCredentials, credentials end ensure diff --git a/infinite_tracing/test/infinite_tracing/client_test.rb b/infinite_tracing/test/infinite_tracing/client_test.rb index 7c302d86ba..72a5de9b23 100644 --- a/infinite_tracing/test/infinite_tracing/client_test.rb +++ b/infinite_tracing/test/infinite_tracing/client_test.rb @@ -21,13 +21,13 @@ def test_streams_multiple_segments assert_equal total_spans, segments.size spans.each_with_index do |span, index| assert_kind_of NewRelic::Agent::InfiniteTracing::Span, span - assert_equal segments[index].transaction.trace_id, span["trace_id"] + assert_equal segments[index].transaction.trace_id, span['trace_id'] end - refute_metrics_recorded(["Supportability/InfiniteTracing/Span/AgentQueueDumped"]) + refute_metrics_recorded(['Supportability/InfiniteTracing/Span/AgentQueueDumped']) assert_metrics_recorded({ - "Supportability/InfiniteTracing/Span/Seen" => {:call_count => 5}, - "Supportability/InfiniteTracing/Span/Sent" => {:call_count => 5} + 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => 5}, + 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => 5} }) end end @@ -49,15 +49,15 @@ def test_streams_across_reconnects assert_equal total_spans, segments.size assert_equal total_spans, spans.size - span_ids = spans.map { |s| s["trace_id"] }.sort + span_ids = spans.map { |s| s['trace_id'] }.sort segment_ids = segments.map { |s| s.transaction.trace_id }.sort assert_equal segment_ids, span_ids - refute_metrics_recorded(["Supportability/InfiniteTracing/Span/AgentQueueDumped"]) + refute_metrics_recorded(['Supportability/InfiniteTracing/Span/AgentQueueDumped']) assert_metrics_recorded({ - "Supportability/InfiniteTracing/Span/Seen" => {:call_count => 5}, - "Supportability/InfiniteTracing/Span/Sent" => {:call_count => 5} + 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => 5}, + 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => 5} }) end end @@ -89,15 +89,15 @@ def test_handles_server_disconnects assert_equal total_spans, segments.size assert_equal total_spans, spans.size - span_ids = spans.map { |s| s["trace_id"] }.sort + span_ids = spans.map { |s| s['trace_id'] }.sort segment_ids = segments.map { |s| s.transaction.trace_id }.sort assert_equal segment_ids, span_ids - refute_metrics_recorded(["Supportability/InfiniteTracing/Span/AgentQueueDumped"]) + refute_metrics_recorded(['Supportability/InfiniteTracing/Span/AgentQueueDumped']) assert_metrics_recorded({ - "Supportability/InfiniteTracing/Span/Seen" => {:call_count => 5}, - "Supportability/InfiniteTracing/Span/Sent" => {:call_count => 5} + 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => 5}, + 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => 5} }) end end @@ -113,11 +113,11 @@ def test_handles_server_error_responses total_spans = 2 emulate_streaming_with_initial_error(total_spans) - assert_metrics_recorded "Supportability/InfiniteTracing/Span/Sent" - assert_metrics_recorded "Supportability/InfiniteTracing/Span/Response/Error" + assert_metrics_recorded 'Supportability/InfiniteTracing/Span/Sent' + assert_metrics_recorded 'Supportability/InfiniteTracing/Span/Response/Error' assert_metrics_recorded({ - "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans}, - "Supportability/InfiniteTracing/Span/gRPC/PERMISSION_DENIED" => {:call_count => 1} + 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => total_spans}, + 'Supportability/InfiniteTracing/Span/gRPC/PERMISSION_DENIED' => {:call_count => 1} }) end end @@ -133,19 +133,19 @@ def test_handles_suspended_state total_spans = 5 emulate_streaming_segments(total_spans) do |client, segments| if segments.size == 3 - simulate_server_response_shutdown(GRPC::Unimplemented.new("i dont exist")) + simulate_server_response_shutdown(GRPC::Unimplemented.new('i dont exist')) else simulate_server_response end end - assert_metrics_recorded "Supportability/InfiniteTracing/Span/gRPC/UNIMPLEMENTED" - assert_metrics_recorded "Supportability/InfiniteTracing/Span/Sent" - assert_metrics_recorded "Supportability/InfiniteTracing/Span/Response/Error" + assert_metrics_recorded 'Supportability/InfiniteTracing/Span/gRPC/UNIMPLEMENTED' + assert_metrics_recorded 'Supportability/InfiniteTracing/Span/Sent' + assert_metrics_recorded 'Supportability/InfiniteTracing/Span/Response/Error' assert_metrics_recorded({ - "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans}, - "Supportability/InfiniteTracing/Span/Sent" => {:call_count => 3}, - "Supportability/InfiniteTracing/Span/gRPC/UNIMPLEMENTED" => {:call_count => 1} + 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => total_spans}, + 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => 3}, + 'Supportability/InfiniteTracing/Span/gRPC/UNIMPLEMENTED' => {:call_count => 1} }) end end @@ -214,10 +214,10 @@ def test_streams_multiple_batches end end - refute_metrics_recorded(["Supportability/InfiniteTracing/Span/AgentQueueDumped"]) + refute_metrics_recorded(['Supportability/InfiniteTracing/Span/AgentQueueDumped']) assert_metrics_recorded({ - "Supportability/InfiniteTracing/Span/Seen" => {:call_count => 5}, - "Supportability/InfiniteTracing/Span/Sent" => {:call_count => 5} + 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => 5}, + 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => 5} }) end end diff --git a/infinite_tracing/test/infinite_tracing/config_test.rb b/infinite_tracing/test/infinite_tracing/config_test.rb index 8cdf8d4550..ee6b4409d4 100644 --- a/infinite_tracing/test/infinite_tracing/config_test.rb +++ b/infinite_tracing/test/infinite_tracing/config_test.rb @@ -35,7 +35,7 @@ def test_trace_observer_host_normalizes ] hostnames.each do |hostname| with_config(:'infinite_tracing.trace_observer.host' => hostname) do - assert_equal "example.com", Config.trace_observer_host + assert_equal 'example.com', Config.trace_observer_host end end end diff --git a/infinite_tracing/test/infinite_tracing/connection_test.rb b/infinite_tracing/test/infinite_tracing/connection_test.rb index 5986c61b9f..248abb16aa 100644 --- a/infinite_tracing/test/infinite_tracing/connection_test.rb +++ b/infinite_tracing/test/infinite_tracing/connection_test.rb @@ -20,8 +20,8 @@ def test_connection_initialized_before_connecting simulator.join # ensure our simulation happens! metadata = connection.send(:metadata) - assert_equal "swiss_cheese", metadata["license_key"] - assert_equal "fiddlesticks", metadata["agent_run_token"] + assert_equal 'swiss_cheese', metadata['license_key'] + assert_equal 'fiddlesticks', metadata['agent_run_token'] end end end @@ -37,8 +37,8 @@ def test_connection_initialized_after_connecting connection = Connection.instance # instantiate after simulated connection metadata = connection.send(:metadata) - assert_equal "swiss_cheese", metadata["license_key"] - assert_equal "fiddlesticks", metadata["agent_run_token"] + assert_equal 'swiss_cheese', metadata['license_key'] + assert_equal 'fiddlesticks', metadata['agent_run_token'] end end end @@ -54,8 +54,8 @@ def test_connection_initialized_after_connecting_and_waiting connection = Connection.instance metadata = connection.send(:metadata) - assert_equal "swiss_cheese", metadata["license_key"] - assert_equal "fiddlesticks", metadata["agent_run_token"] + assert_equal 'swiss_cheese', metadata['license_key'] + assert_equal 'fiddlesticks', metadata['agent_run_token'] end end end @@ -71,15 +71,15 @@ def test_connection_reconnects simulator.join metadata = connection.send(:metadata) - assert_equal "swiss_cheese", metadata["license_key"] - assert_equal "fiddlesticks", metadata["agent_run_token"] + assert_equal 'swiss_cheese', metadata['license_key'] + assert_equal 'fiddlesticks', metadata['agent_run_token'] simulate_reconnect_to_collector(reconnect_config) metadata = connection.send(:metadata) - assert_equal "swiss_cheese", metadata["license_key"] - assert_equal "shazbat", metadata["agent_run_token"] + assert_equal 'swiss_cheese', metadata['license_key'] + assert_equal 'shazbat', metadata['agent_run_token'] end end end @@ -106,17 +106,17 @@ def test_handling_unimplemented_server_response spans, segments, active_client = emulate_streaming_to_unimplemented(total_spans) assert_kind_of SuspendedStreamingBuffer, active_client.buffer - assert_predicate active_client, :suspended?, "expected client to be suspended." + assert_predicate active_client, :suspended?, 'expected client to be suspended.' assert_equal total_spans, segments.size assert_equal 0, spans.size - assert_metrics_recorded "Supportability/InfiniteTracing/Span/Sent" - assert_metrics_recorded "Supportability/InfiniteTracing/Span/Response/Error" + assert_metrics_recorded 'Supportability/InfiniteTracing/Span/Sent' + assert_metrics_recorded 'Supportability/InfiniteTracing/Span/Response/Error' assert_metrics_recorded({ - "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans}, - "Supportability/InfiniteTracing/Span/gRPC/UNIMPLEMENTED" => {:call_count => 1} + 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => total_spans}, + 'Supportability/InfiniteTracing/Span/gRPC/UNIMPLEMENTED' => {:call_count => 1} }) end end @@ -131,17 +131,17 @@ def test_handling_failed_precondition_server_response spans, segments, active_client = emulate_streaming_to_failed_precondition(total_spans) refute_kind_of SuspendedStreamingBuffer, active_client.buffer - refute active_client.suspended?, "expected client to not be suspended." + refute active_client.suspended?, 'expected client to not be suspended.' assert_equal total_spans, segments.size assert_equal 0, spans.size - assert_metrics_recorded "Supportability/InfiniteTracing/Span/Sent" - assert_metrics_recorded "Supportability/InfiniteTracing/Span/Response/Error" + assert_metrics_recorded 'Supportability/InfiniteTracing/Span/Sent' + assert_metrics_recorded 'Supportability/InfiniteTracing/Span/Response/Error' assert_metrics_recorded({ - "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans}, - "Supportability/InfiniteTracing/Span/gRPC/FAILED_PRECONDITION" => {:call_count => 5} + 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => total_spans}, + 'Supportability/InfiniteTracing/Span/gRPC/FAILED_PRECONDITION' => {:call_count => 5} }) end end @@ -151,16 +151,16 @@ def test_handling_ok_and_close_server_response with_config('infinite_tracing.batching': false) do with_detailed_trace do total_spans = 5 - expects_logging(:debug, all_of(includes("closed the stream"), includes("OK response.")), anything) + expects_logging(:debug, all_of(includes('closed the stream'), includes('OK response.')), anything) spans, segments = emulate_streaming_with_ok_close_response(total_spans) assert_equal total_spans, segments.size - assert_equal total_spans, spans.size, "spans got dropped/discarded?" + assert_equal total_spans, spans.size, 'spans got dropped/discarded?' - refute_metrics_recorded "Supportability/InfiniteTracing/Span/Response/Error" + refute_metrics_recorded 'Supportability/InfiniteTracing/Span/Response/Error' - assert_metrics_recorded("Supportability/InfiniteTracing/Span/Sent") + assert_metrics_recorded('Supportability/InfiniteTracing/Span/Sent') end end end @@ -188,14 +188,14 @@ def test_reconnection_backoff def test_metadata_includes_request_headers_map with_serial_lock do with_config(localhost_config) do - NewRelic::Agent.agent.service.instance_variable_set(:@request_headers_map, {"NR-UtilizationMetadata" => "test_metadata"}) + NewRelic::Agent.agent.service.instance_variable_set(:@request_headers_map, {'NR-UtilizationMetadata' => 'test_metadata'}) connection = Connection.instance # instantiate before simulation simulate_connect_to_collector(fiddlesticks_config, 0.01) do |simulator| simulator.join # ensure our simulation happens! metadata = connection.send(:metadata) - assert_equal "test_metadata", metadata["nr-utilizationmetadata"] + assert_equal 'test_metadata', metadata['nr-utilizationmetadata'] end end end diff --git a/infinite_tracing/test/infinite_tracing/record_status_handler_test.rb b/infinite_tracing/test/infinite_tracing/record_status_handler_test.rb index b1e1a6cd26..08479442c5 100644 --- a/infinite_tracing/test/infinite_tracing/record_status_handler_test.rb +++ b/infinite_tracing/test/infinite_tracing/record_status_handler_test.rb @@ -33,7 +33,7 @@ def test_processes_multiple_items_and_stops end def test_processes_error_on_queue - error_object = RuntimeError.new("oops") + error_object = RuntimeError.new('oops') queue = EnumeratorQueue.new.preload(error_object) handler = build_handler(queue) @@ -55,7 +55,7 @@ def test_processes_nil_on_queue class TestClient def handle_error(error) - NewRelic::Agent.record_metric("Supportability/InfiniteTracing/Span/Response/Error", 0.0) + NewRelic::Agent.record_metric('Supportability/InfiniteTracing/Span/Response/Error', 0.0) end end diff --git a/infinite_tracing/test/infinite_tracing/streaming_buffer_test.rb b/infinite_tracing/test/infinite_tracing/streaming_buffer_test.rb index 5aea73e226..1e263a3489 100644 --- a/infinite_tracing/test/infinite_tracing/streaming_buffer_test.rb +++ b/infinite_tracing/test/infinite_tracing/streaming_buffer_test.rb @@ -23,10 +23,10 @@ def test_streams_single_segment buffer, _segments = stream_segments(total_spans) consume_spans(buffer) - refute_metrics_recorded(["Supportability/InfiniteTracing/Span/AgentQueueDumped"]) + refute_metrics_recorded(['Supportability/InfiniteTracing/Span/AgentQueueDumped']) assert_metrics_recorded({ - "Supportability/InfiniteTracing/Span/Seen" => {:call_count => 1}, - "Supportability/InfiniteTracing/Span/Sent" => {:call_count => 1} + 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => 1}, + 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => 1} }) end end @@ -43,10 +43,10 @@ def test_streams_single_segment_in_threads buffer.flush_queue consumer.join - refute_metrics_recorded(["Supportability/InfiniteTracing/Span/AgentQueueDumped"]) + refute_metrics_recorded(['Supportability/InfiniteTracing/Span/AgentQueueDumped']) assert_metrics_recorded({ - "Supportability/InfiniteTracing/Span/Seen" => {:call_count => 1}, - "Supportability/InfiniteTracing/Span/Sent" => {:call_count => 1} + 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => 1}, + 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => 1} }) assert_watched_threads_finished buffer end @@ -62,13 +62,13 @@ def test_streams_multiple_segments assert_equal total_spans, spans.size spans.each_with_index do |span, index| assert_kind_of NewRelic::Agent::InfiniteTracing::Span, span - assert_equal segments[index].transaction.trace_id, span["trace_id"] + assert_equal segments[index].transaction.trace_id, span['trace_id'] end - refute_metrics_recorded(["Supportability/InfiniteTracing/Span/AgentQueueDumped"]) + refute_metrics_recorded(['Supportability/InfiniteTracing/Span/AgentQueueDumped']) assert_metrics_recorded({ - "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans}, - "Supportability/InfiniteTracing/Span/Sent" => {:call_count => total_spans} + 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => total_spans}, + 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => total_spans} }) assert_watched_threads_finished buffer end @@ -122,13 +122,13 @@ def test_streams_multiple_segments_in_threads assert_equal total_spans, spans.size spans.each_with_index do |span, index| assert_kind_of NewRelic::Agent::InfiniteTracing::Span, span - assert_equal segments[index].transaction.trace_id, span["trace_id"] + assert_equal segments[index].transaction.trace_id, span['trace_id'] end - refute_metrics_recorded(["Supportability/InfiniteTracing/Span/AgentQueueDumped"]) + refute_metrics_recorded(['Supportability/InfiniteTracing/Span/AgentQueueDumped']) assert_metrics_recorded({ - "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans}, - "Supportability/InfiniteTracing/Span/Sent" => {:call_count => total_spans} + 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => total_spans}, + 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => total_spans} }) assert_watched_threads_finished buffer end @@ -146,13 +146,13 @@ def test_drops_queue_when_max_reached spans = consume_spans(buffer) assert_equal 1, spans.size - assert_equal segments[-1].transaction.trace_id, spans[0]["trace_id"] - assert_equal segments[-1].transaction.trace_id, spans[0]["intrinsics"]["traceId"].string_value + assert_equal segments[-1].transaction.trace_id, spans[0]['trace_id'] + assert_equal segments[-1].transaction.trace_id, spans[0]['intrinsics']['traceId'].string_value assert_metrics_recorded({ - "Supportability/InfiniteTracing/Span/Seen" => {:call_count => 9}, - "Supportability/InfiniteTracing/Span/Sent" => {:call_count => 1}, - "Supportability/InfiniteTracing/Span/AgentQueueDumped" => {:call_count => 2} + 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => 9}, + 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => 1}, + 'Supportability/InfiniteTracing/Span/AgentQueueDumped' => {:call_count => 2} }) assert_watched_threads_finished buffer end @@ -184,14 +184,14 @@ def test_can_close_an_empty_buffer buffer.flush_queue consumer.join - assert emptied, "spans streamed reached total but buffer not empty!" - assert closed, "failed to close the buffer" + assert emptied, 'spans streamed reached total but buffer not empty!' + assert closed, 'failed to close the buffer' assert_equal total_spans, segments.size assert_equal total_spans, spans.size assert_metrics_recorded({ - "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans}, - "Supportability/InfiniteTracing/Span/Sent" => {:call_count => total_spans} + 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => total_spans}, + 'Supportability/InfiniteTracing/Span/Sent' => {:call_count => total_spans} }) assert_watched_threads_finished buffer end diff --git a/infinite_tracing/test/infinite_tracing/suspended_streaming_buffer_test.rb b/infinite_tracing/test/infinite_tracing/suspended_streaming_buffer_test.rb index 9329b397c7..c2dd20ec84 100644 --- a/infinite_tracing/test/infinite_tracing/suspended_streaming_buffer_test.rb +++ b/infinite_tracing/test/infinite_tracing/suspended_streaming_buffer_test.rb @@ -26,15 +26,15 @@ def test_streams_multiple_segments assert_equal 0, spans.size spans.each_with_index do |span, index| assert_kind_of NewRelic::Agent::InfiniteTracing::Span, span - assert_equal segments[index].transaction.trace_id, span["trace_id"] + assert_equal segments[index].transaction.trace_id, span['trace_id'] end refute_metrics_recorded([ - "Supportability/InfiniteTracing/Span/AgentQueueDumped", - "Supportability/InfiniteTracing/Span/Sent" + 'Supportability/InfiniteTracing/Span/AgentQueueDumped', + 'Supportability/InfiniteTracing/Span/Sent' ]) assert_metrics_recorded({ - "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans} + 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => total_spans} }) assert_watched_threads_finished buffer end @@ -66,17 +66,17 @@ def test_can_close_an_empty_buffer buffer.flush_queue consumer.join - assert emptied, "spans streamed reached total but buffer not empty!" - assert closed, "failed to close the buffer" + assert emptied, 'spans streamed reached total but buffer not empty!' + assert closed, 'failed to close the buffer' assert_equal total_spans, segments.size assert_equal 0, spans.size refute_metrics_recorded([ - "Supportability/InfiniteTracing/Span/AgentQueueDumped", - "Supportability/InfiniteTracing/Span/Sent" + 'Supportability/InfiniteTracing/Span/AgentQueueDumped', + 'Supportability/InfiniteTracing/Span/Sent' ]) assert_metrics_recorded({ - "Supportability/InfiniteTracing/Span/Seen" => {:call_count => total_spans} + 'Supportability/InfiniteTracing/Span/Seen' => {:call_count => total_spans} }) assert_watched_threads_finished buffer end diff --git a/infinite_tracing/test/infinite_tracing/transformer_test.rb b/infinite_tracing/test/infinite_tracing/transformer_test.rb index d9a4fa7f86..a7d449ca7b 100644 --- a/infinite_tracing/test/infinite_tracing/transformer_test.rb +++ b/infinite_tracing/test/infinite_tracing/transformer_test.rb @@ -12,36 +12,36 @@ def test_transforms_single_span_event span_event = Transformer.transform(span_event_fixture(:single)) assert_kind_of Hash, span_event - assert_equal "cb4925eee573c1f9c786fdb2b296459b", span_event["trace_id"] - span_event["intrinsics"].each do |key, value| + assert_equal 'cb4925eee573c1f9c786fdb2b296459b', span_event['trace_id'] + span_event['intrinsics'].each do |key, value| assert_kind_of String, key assert_kind_of AttributeValue, value end - assert_empty span_event["user_attributes"] - assert_empty span_event["agent_attributes"] + assert_empty span_event['user_attributes'] + assert_empty span_event['agent_attributes'] end def test_transforms_single_full_span_event span_event = Transformer.transform(span_event_fixture(:single_full_attributes)) assert_kind_of Hash, span_event - assert_equal "cb4925eee573c1f9c786fdb2b296459b", span_event["trace_id"] + assert_equal 'cb4925eee573c1f9c786fdb2b296459b', span_event['trace_id'] - span_event["intrinsics"].each do |key, value| + span_event['intrinsics'].each do |key, value| assert_kind_of String, key assert_kind_of AttributeValue, value end - refute_empty span_event["user_attributes"] - refute_empty span_event["agent_attributes"] + refute_empty span_event['user_attributes'] + refute_empty span_event['agent_attributes'] - span_event["user_attributes"].each do |key, value| + span_event['user_attributes'].each do |key, value| assert_kind_of String, key assert_kind_of AttributeValue, value end - span_event["agent_attributes"].each do |key, value| + span_event['agent_attributes'].each do |key, value| assert_kind_of String, key assert_kind_of AttributeValue, value end diff --git a/infinite_tracing/test/infinite_tracing/worker_test.rb b/infinite_tracing/test/infinite_tracing/worker_test.rb index 2167ab2b81..acd124383f 100644 --- a/infinite_tracing/test/infinite_tracing/worker_test.rb +++ b/infinite_tracing/test/infinite_tracing/worker_test.rb @@ -11,46 +11,46 @@ def teardown end def test_processes_simple_task - worker = Worker.new("simple") do - NewRelic::Agent.record_metric("Supportability/InfiniteTracing/Worker", 0.0) + worker = Worker.new('simple') do + NewRelic::Agent.record_metric('Supportability/InfiniteTracing/Worker', 0.0) end - assert_equal "run", worker.status + assert_equal 'run', worker.status worker.join - assert_equal "idle", worker.status + assert_equal 'idle', worker.status worker.stop - assert_equal "stopped", worker.status + assert_equal 'stopped', worker.status - assert_equal "simple", worker.name - assert_metrics_recorded "Supportability/InfiniteTracing/Worker" + assert_equal 'simple', worker.name + assert_metrics_recorded 'Supportability/InfiniteTracing/Worker' end def test_worker_uses_agentthread NewRelic::Agent::Threading::AgentThread.expects(:create).returns(Thread.new {}) - worker = Worker.new("simple") {} + worker = Worker.new('simple') {} worker.join end def test_worker_handles_errors - worker = Worker.new("error") do - NewRelic::Agent.record_metric("Supportability/InfiniteTracing/Worker", 0.0) - raise "Oops!" - NewRelic::Agent.record_metric("Supportability/InfiniteTracing/Error", 0.0) + worker = Worker.new('error') do + NewRelic::Agent.record_metric('Supportability/InfiniteTracing/Worker', 0.0) + raise 'Oops!' + NewRelic::Agent.record_metric('Supportability/InfiniteTracing/Error', 0.0) end begin worker.join rescue => err - assert_equal "Oops!", err.message + assert_equal 'Oops!', err.message assert worker.error end - assert_equal "error", worker.name - assert_equal "error", worker.status - assert_metrics_recorded "Supportability/InfiniteTracing/Worker" - refute_metrics_recorded "Supportability/InfiniteTracing/Error" + assert_equal 'error', worker.name + assert_equal 'error', worker.status + assert_metrics_recorded 'Supportability/InfiniteTracing/Worker' + refute_metrics_recorded 'Supportability/InfiniteTracing/Error' end end end diff --git a/infinite_tracing/test/support/fake_trace_observer_helpers.rb b/infinite_tracing/test/support/fake_trace_observer_helpers.rb index 791ad16c87..0aee1c9461 100644 --- a/infinite_tracing/test/support/fake_trace_observer_helpers.rb +++ b/infinite_tracing/test/support/fake_trace_observer_helpers.rb @@ -52,7 +52,7 @@ def assert_only_one_subscription_notifier end def teardown - @mock_thread.kill if @mock_thread + @mock_thread&.kill @mock_thread = nil @server_response_enum = nil reset_buffers_and_caches @@ -81,8 +81,8 @@ def localhost_config { :'distributed_tracing.enabled' => true, :'span_events.enabled' => true, - :'infinite_tracing.trace_observer.host' => "localhost:80", - :'license_key' => "swiss_cheese" + :'infinite_tracing.trace_observer.host' => 'localhost:80', + :'license_key' => 'swiss_cheese' } end @@ -90,9 +90,9 @@ def fake_server_config { :'distributed_tracing.enabled' => true, :'span_events.enabled' => true, - :'infinite_tracing.trace_observer.host' => "localhost", + :'infinite_tracing.trace_observer.host' => 'localhost', :'infinite_tracing.trace_observer.port' => FAKE_SERVER_PORT, - :'license_key' => "swiss_cheese" + :'license_key' => 'swiss_cheese' } end @@ -170,7 +170,7 @@ def emulate_streaming_with_tracer(tracer_class, count, max_buffer_size, &block) end end ensure - client.stop unless client.nil? + client&.stop end # when the server responds with an error that should stop the server @@ -215,7 +215,7 @@ def create_grpc_mock(simulate_broken_server: false, expect_mock: true, expect_ba end def join_grpc_mock - @mock_thread.join if @mock_thread + @mock_thread&.join end # Simulates a Messages seen response from the mock grpc server @@ -265,7 +265,7 @@ def emulate_streaming_with_initial_error(count, max_buffer_size = 100_000, &bloc segments = emulate_streaming_with_tracer(nil, count, max_buffer_size) do |client, current_segments| if first # raise error only first time - simulate_server_response_shutdown(GRPC::PermissionDenied.new(details = "denied")) + simulate_server_response_shutdown(GRPC::PermissionDenied.new(details = 'denied')) first = false else simulate_server_response diff --git a/infinite_tracing/test/support/fixtures.rb b/infinite_tracing/test/support/fixtures.rb index 472b4e43f4..16ff5cc882 100644 --- a/infinite_tracing/test/support/fixtures.rb +++ b/infinite_tracing/test/support/fixtures.rb @@ -9,7 +9,7 @@ def fixtures_path end def span_event_fixture(fixture_name) - fixture_filename = File.join(fixtures_path, "span_events", "#{fixture_name}.yml") + fixture_filename = File.join(fixtures_path, 'span_events', "#{fixture_name}.yml") assert_path_exists(fixture_filename, "Missing Span Event Fixture: #{fixture_name}. Looked for #{fixture_filename}") if YAML.respond_to?(:unsafe_load) diff --git a/init.rb b/init.rb index 2711b13570..9c5ac9f02a 100644 --- a/init.rb +++ b/init.rb @@ -26,5 +26,5 @@ NewRelic::Control.instance.init_plugin(:config => current_config) rescue => e - NewRelic::Agent.logger.error("Error initializing New Relic plugin. Agent is disabled.", e) + NewRelic::Agent.logger.error('Error initializing New Relic plugin. Agent is disabled.', e) end diff --git a/lib/new_relic/agent.rb b/lib/new_relic/agent.rb index a729889c6c..3449499dd1 100644 --- a/lib/new_relic/agent.rb +++ b/lib/new_relic/agent.rb @@ -105,7 +105,10 @@ class SerializationError < StandardError; end # placeholder name used when we cannot determine a transaction's name UNKNOWN_METRIC = '(unknown)'.freeze + attr_reader :error_group_callback + @agent = nil + @error_group_callback = nil @logger = nil @tracer_lock = Mutex.new @tracer_queue = [] @@ -210,6 +213,8 @@ def record_metric_once(metric_name, value = 0.0) record_metric(metric_name, value) end + SUPPORTABILITY_INCREMENT_METRIC = 'Supportability/API/increment_metric'.freeze + # Increment a simple counter metric. # # +metric_name+ should follow a slash separated path convention. Application @@ -218,9 +223,7 @@ def record_metric_once(metric_name, value = 0.0) # This method is safe to use from any thread. # # @api public - - SUPPORTABILITY_INCREMENT_METRIC = 'Supportability/API/increment_metric'.freeze - + # def increment_metric(metric_name, amount = 1) # THREAD_LOCAL_ACCESS return unless agent @@ -293,6 +296,47 @@ def notice_error(exception, options = {}) nil # don't return a noticed error data structure. it can only hurt. end + # Set a callback proc for determining an error's error group name + # + # @param [Proc] the callback proc + # + # Typically this method should be called only once to set a callback for + # use with all noticed errors. If it is called multiple times, each new + # callback given will replace the old one. + # + # The proc will be called with a single hash as its input argument and is + # expected to return a string representing the desired error group. + # + # see https://docs.newrelic.com/docs/errors-inbox/errors-inbox/#groups + # + # The hash passed to the customer defined callback proc has the following + # keys: + # + # :error => The Ruby error class instance, likely inheriting from + # StandardError. Call `#class`, `#message`, and `#backtrace` on + # the error object to retrieve the error's class, message, and + # backtrace. + # :customAttributes => Any customer defined custom attributes that have been + # associated with the current transaction. + # :'request.uri' => The current request URI if available + # :'http.statusCode' => The HTTP status code (200, 404, etc.) if available + # :'http.method' => The HTTP method (GET, PUT, etc.) if available + # :'error.expected' => Whether (true) or not (false) the error was expected + # :options => The options hash passed to `NewRelic::Agent.notice_error` + # + # @api public + # + def set_error_group_callback(callback_proc) + unless callback_proc.is_a?(Proc) + NewRelic::Agent.logger.error("#{self}.#{__method__}: expected an argument of type Proc, " \ + "got #{callback_proc.class}") + return + end + + record_api_supportability_metric(:set_error_group_callback) + @error_group_callback = callback_proc + end + # @!endgroup # @!group Recording custom Insights events @@ -353,7 +397,7 @@ def record_custom_event(event_type, event_attrs) # @api public # def manual_start(options = {}) - raise "Options must be a hash" unless Hash === options + raise 'Options must be a hash' unless Hash === options NewRelic::Control.instance.init_plugin({:agent_enabled => true, :sync_startup => true}.merge(options)) record_api_supportability_metric(:manual_start) @@ -386,7 +430,8 @@ def manual_start(options = {}) # def after_fork(options = {}) record_api_supportability_metric(:after_fork) - agent.after_fork(options) if agent + # the following line needs else branch coverage + agent.after_fork(options) if agent # rubocop:disable Style/SafeNavigation end # Shutdown the agent. Call this before exiting. Sends any queued data @@ -398,7 +443,7 @@ def after_fork(options = {}) # def shutdown(options = {}) record_api_supportability_metric(:shutdown) - agent.shutdown if agent + agent&.shutdown end # Clear out any data the agent has buffered but has not yet transmitted @@ -406,7 +451,8 @@ def shutdown(options = {}) # # @api public def drop_buffered_data - agent.drop_buffered_data if agent + # the following line needs else branch coverage + agent.drop_buffered_data if agent # rubocop:disable Style/SafeNavigation record_api_supportability_metric(:drop_buffered_data) end @@ -465,8 +511,7 @@ def set_sql_obfuscator(type = :replace, &block) # def ignore_transaction record_api_supportability_metric(:ignore_transaction) - txn = NewRelic::Agent::Transaction.tl_current - txn.ignore! if txn + NewRelic::Agent::Transaction.tl_current&.ignore! end # This method disables the recording of Apdex metrics in the current @@ -476,8 +521,7 @@ def ignore_transaction # def ignore_apdex record_api_supportability_metric(:ignore_apdex) - txn = NewRelic::Agent::Transaction.tl_current - txn.ignore_apdex! if txn + NewRelic::Agent::Transaction.tl_current&.ignore_apdex! end # This method disables browser monitoring javascript injection in the @@ -487,8 +531,7 @@ def ignore_apdex # def ignore_enduser record_api_supportability_metric(:ignore_enduser) - txn = NewRelic::Agent::Transaction.tl_current - txn.ignore_enduser! if txn + NewRelic::Agent::Transaction.tl_current&.ignore_enduser! end # Yield to the block without collecting any metrics or traces in @@ -564,8 +607,7 @@ def add_custom_attributes(params) # THREAD_LOCAL_ACCESS record_api_supportability_metric(:add_custom_attributes) if params.is_a?(Hash) - txn = Transaction.tl_current - txn.add_custom_attributes(params) if txn + Transaction.tl_current&.add_custom_attributes(params) segment = ::NewRelic::Agent::Tracer.current_segment if segment @@ -607,6 +649,26 @@ def add_custom_span_attributes(params) end end + # Set the user id for the current transaction. When present, this value will be included in the agent attributes for transaction and error events as 'enduser.id'. + # + # @param [String] user_id The user id to add to the current transaction attributes + # + # @api public + def set_user_id(user_id) + record_api_supportability_metric(:set_user_id) + + if user_id.nil? || user_id.empty? + ::NewRelic::Agent.logger.warn('NewRelic::Agent.set_user_id called with a nil or empty user id.') + return + end + + default_destinations = NewRelic::Agent::AttributeFilter::DST_TRANSACTION_TRACER | + NewRelic::Agent::AttributeFilter::DST_TRANSACTION_EVENTS | + NewRelic::Agent::AttributeFilter::DST_ERROR_COLLECTOR + + NewRelic::Agent::Transaction.add_agent_attribute(:'enduser.id', user_id, default_destinations) + end + # @!endgroup # @!group Transaction naming @@ -686,7 +748,7 @@ def subscribe(event_type, &handler) def notify(event_type, *args) agent.events.notify(event_type, *args) rescue - NewRelic::Agent.logger.debug("Ignoring exception during %p event notification" % [event_type]) + NewRelic::Agent.logger.debug('Ignoring exception during %p event notification' % [event_type]) end # @!group Trace and Entity metadata diff --git a/lib/new_relic/agent/agent.rb b/lib/new_relic/agent/agent.rb index a004ba147a..0e5b947666 100644 --- a/lib/new_relic/agent/agent.rb +++ b/lib/new_relic/agent/agent.rb @@ -142,20 +142,16 @@ module InstanceMethods # the transaction sampler that handles recording transactions attr_reader :transaction_sampler attr_reader :sql_sampler - # manages agent commands we receive from the collector, and the handlers - attr_reader :agent_command_router # error collector is a simple collection of recorded errors attr_reader :error_collector - attr_reader :harvest_samplers # whether we should record raw, obfuscated, or no sql attr_reader :record_sql # builder for JS agent scripts to inject attr_reader :javascript_instrumentor # cross application tracing ids and encoding attr_reader :cross_process_id - attr_reader :cross_app_encoding_bytes # service for communicating with collector - attr_accessor :service + attr_reader :service # Global events dispatcher. This will provides our primary mechanism # for agent-wide events, such as finishing configuration, error notification # and request before/after from Rack. @@ -168,8 +164,6 @@ module InstanceMethods # collector on connect. The former are applied during txns, # the latter during harvest. attr_accessor :transaction_rules - # Responsible for restarting the harvest thread - attr_reader :harvester # GC::Profiler.total_time is not monotonic so we wrap it. attr_reader :monotonic_gc_profiler attr_reader :custom_event_aggregator @@ -178,7 +172,6 @@ module InstanceMethods attr_reader :transaction_event_recorder attr_reader :attribute_filter attr_reader :adaptive_sampler - attr_reader :environment_report def transaction_event_aggregator @transaction_event_recorder.transaction_event_aggregator @@ -262,8 +255,8 @@ def trap_signals_for_litespeed # if litespeed, then ignore all future SIGUSR1 - it's # litespeed trying to shut us down if Agent.config[:dispatcher] == :litespeed - Signal.trap("SIGUSR1", "IGNORE") - Signal.trap("SIGTERM", "IGNORE") + Signal.trap('SIGUSR1', 'IGNORE') + Signal.trap('SIGTERM', 'IGNORE') end end @@ -355,12 +348,6 @@ def merge_data_for_endpoint(endpoint, data) end public :merge_data_for_endpoint - - # Delegates to the control class to determine the root - # directory of this project - def determine_home_directory - control.root - end end extend ClassMethods diff --git a/lib/new_relic/agent/agent_helpers/connect.rb b/lib/new_relic/agent/agent_helpers/connect.rb index e4380e0de9..fe0c8c18d1 100644 --- a/lib/new_relic/agent/agent_helpers/connect.rb +++ b/lib/new_relic/agent/agent_helpers/connect.rb @@ -64,7 +64,7 @@ def log_error(error) def handle_license_error(error) ::NewRelic::Agent.logger.error( \ error.message, \ - "Visit NewRelic.com to obtain a valid license key, or to upgrade your account." + 'Visit NewRelic.com to obtain a valid license key, or to upgrade your account.' ) disconnect end @@ -115,7 +115,7 @@ def log_connection(config_data) ::NewRelic::Agent.logger.debug("Connected to NewRelic Service at #{@service.collector.name}") ::NewRelic::Agent.logger.debug("Agent Run = #{@service.agent_id}.") ::NewRelic::Agent.logger.debug("Connection data = #{config_data.inspect}") - if config_data['messages'] && config_data['messages'].any? + if config_data['messages']&.any? log_collector_messages(config_data['messages']) end end @@ -126,11 +126,6 @@ def log_collector_messages(messages) end end - # apdex_f is always 4 times the apdex_t - def apdex_f - (Agent.config[:apdex_t] * 4).to_f - end - class WaitOnConnectTimeout < StandardError end @@ -149,7 +144,7 @@ def wait_on_connect(timeout) return if connected? @waited_on_connect = true - NewRelic::Agent.logger.debug("Waiting on connect to complete.") + NewRelic::Agent.logger.debug('Waiting on connect to complete.') @wait_on_connect_mutex.synchronize do @wait_on_connect_condition.wait(@wait_on_connect_mutex, timeout) @@ -203,7 +198,7 @@ def connect(options = {}) rescue StandardError, Timeout::Error, NewRelic::Agent::ServerConnectionException => e retry if retry_from_error?(e, opts) rescue Exception => e - ::NewRelic::Agent.logger.error("Exception of unexpected type during Agent#connect():", e) + ::NewRelic::Agent.logger.error('Exception of unexpected type during Agent#connect():', e) raise end diff --git a/lib/new_relic/agent/agent_helpers/harvest.rb b/lib/new_relic/agent/agent_helpers/harvest.rb index f760a2e4a2..af5596ad21 100644 --- a/lib/new_relic/agent/agent_helpers/harvest.rb +++ b/lib/new_relic/agent/agent_helpers/harvest.rb @@ -133,18 +133,18 @@ def check_for_and_handle_agent_commands rescue ForceRestartException, ForceDisconnectException raise rescue UnrecoverableServerException => e - NewRelic::Agent.logger.warn("get_agent_commands message was rejected by remote service, discarding. " \ - "Error: ", e) + NewRelic::Agent.logger.warn('get_agent_commands message was rejected by remote service, discarding. ' \ + 'Error: ', e) rescue ServerConnectionException => e log_remote_unavailable(:get_agent_commands, e) rescue => e - NewRelic::Agent.logger.info("Error during check_for_and_handle_agent_commands, will retry later: ", e) + NewRelic::Agent.logger.info('Error during check_for_and_handle_agent_commands, will retry later: ', e) end end def log_remote_unavailable(endpoint, e) NewRelic::Agent.logger.debug("Unable to send #{endpoint} data, will try again later. Error: ", e) - NewRelic::Agent.record_metric("Supportability/remote_unavailable", 0.0) + NewRelic::Agent.record_metric('Supportability/remote_unavailable', 0.0) NewRelic::Agent.record_metric("Supportability/remote_unavailable/#{endpoint.to_s}", 0.0) end end diff --git a/lib/new_relic/agent/agent_helpers/shutdown.rb b/lib/new_relic/agent/agent_helpers/shutdown.rb index 868e914177..e6f6017e13 100644 --- a/lib/new_relic/agent/agent_helpers/shutdown.rb +++ b/lib/new_relic/agent/agent_helpers/shutdown.rb @@ -11,7 +11,7 @@ module Shutdown def shutdown return unless started? - ::NewRelic::Agent.logger.info("Starting Agent shutdown") + ::NewRelic::Agent.logger.info('Starting Agent shutdown') stop_event_loop trap_signals_for_litespeed @@ -48,22 +48,22 @@ def graceful_disconnect transmit_data_types shutdown_service - ::NewRelic::Agent.logger.debug("Graceful disconnect complete") + ::NewRelic::Agent.logger.debug('Graceful disconnect complete') rescue Timeout::Error, StandardError => e ::NewRelic::Agent.logger.debug("Error when disconnecting #{e.class.name}: #{e.message}") end else - ::NewRelic::Agent.logger.debug("Bypassing graceful disconnect - agent not connected") + ::NewRelic::Agent.logger.debug('Bypassing graceful disconnect - agent not connected') end end def shutdown_service if @connected_pid == $$ && !@service.kind_of?(NewRelic::Agent::NewRelicService) - ::NewRelic::Agent.logger.debug("Sending New Relic service agent run shutdown message") + ::NewRelic::Agent.logger.debug('Sending New Relic service agent run shutdown message') @service.shutdown else ::NewRelic::Agent.logger.debug("This agent connected from parent process #{@connected_pid}--not sending " \ - "shutdown") + 'shutdown') end end end diff --git a/lib/new_relic/agent/agent_helpers/special_startup.rb b/lib/new_relic/agent/agent_helpers/special_startup.rb index 9fb2bb0160..08b5d4cf33 100644 --- a/lib/new_relic/agent/agent_helpers/special_startup.rb +++ b/lib/new_relic/agent/agent_helpers/special_startup.rb @@ -11,7 +11,7 @@ module SpecialStartup # before connecting, otherwise the parent process sends useless data def using_forking_dispatcher? if [:puma, :passenger, :unicorn].include?(Agent.config[:dispatcher]) - ::NewRelic::Agent.logger.info("Deferring startup of agent reporting thread because " \ + ::NewRelic::Agent.logger.info('Deferring startup of agent reporting thread because ' \ "#{Agent.config[:dispatcher]} may fork.") true else @@ -65,7 +65,7 @@ def should_install_exit_handler? def install_exit_handler return unless should_install_exit_handler? - NewRelic::Agent.logger.debug("Installing at_exit handler") + NewRelic::Agent.logger.debug('Installing at_exit handler') at_exit { shutdown } end end diff --git a/lib/new_relic/agent/agent_helpers/start_worker_thread.rb b/lib/new_relic/agent/agent_helpers/start_worker_thread.rb index 1d51923078..d59f0d3229 100644 --- a/lib/new_relic/agent/agent_helpers/start_worker_thread.rb +++ b/lib/new_relic/agent/agent_helpers/start_worker_thread.rb @@ -8,23 +8,23 @@ module AgentHelpers module StartWorkerThread LOG_ONCE_KEYS_RESET_PERIOD = 60.0 - TRANSACTION_EVENT_DATA = "transaction_event_data".freeze - CUSTOM_EVENT_DATA = "custom_event_data".freeze - ERROR_EVENT_DATA = "error_event_data".freeze - SPAN_EVENT_DATA = "span_event_data".freeze - LOG_EVENT_DATA = "log_event_data".freeze + TRANSACTION_EVENT_DATA = 'transaction_event_data'.freeze + CUSTOM_EVENT_DATA = 'custom_event_data'.freeze + ERROR_EVENT_DATA = 'error_event_data'.freeze + SPAN_EVENT_DATA = 'span_event_data'.freeze + LOG_EVENT_DATA = 'log_event_data'.freeze # Try to launch the worker thread and connect to the server. # # See #connect for a description of connection_options. def start_worker_thread(connection_options = {}) if disable = NewRelic::Agent.config[:disable_harvest_thread] - NewRelic::Agent.logger.info("Not starting Ruby Agent worker thread because :disable_harvest_thread is " \ + NewRelic::Agent.logger.info('Not starting Ruby Agent worker thread because :disable_harvest_thread is ' \ "#{disable}") return end - ::NewRelic::Agent.logger.debug("Creating Ruby Agent worker thread.") + ::NewRelic::Agent.logger.debug('Creating Ruby Agent worker thread.') @worker_thread = Threading::AgentThread.create('Worker Loop') do deferred_work!(connection_options) end @@ -42,11 +42,11 @@ def create_event_loop # The use-case where this typically arises is in cronjob scheduled rake tasks where there's # also some network stability/latency issues happening. def stop_event_loop - @event_loop.stop if @event_loop + @event_loop&.stop # Wait the end of the event loop thread. if @worker_thread unless @worker_thread.join(3) - ::NewRelic::Agent.logger.debug("Event loop thread did not stop within 3 seconds") + ::NewRelic::Agent.logger.debug('Event loop thread did not stop within 3 seconds') end end end @@ -60,36 +60,13 @@ def interval_for(event_type) end def create_and_run_event_loop - data_harvest = :"#{Agent.config[:data_report_period]}_second_harvest" - event_harvest = :"#{Agent.config[:event_report_period]}_second_harvest" - @event_loop = create_event_loop + data_harvest = :"#{Agent.config[:data_report_period]}_second_harvest" @event_loop.on(data_harvest) do transmit_data end - - @event_loop.on(interval_for(TRANSACTION_EVENT_DATA)) do - transmit_analytic_event_data - end - @event_loop.on(interval_for(CUSTOM_EVENT_DATA)) do - transmit_custom_event_data - end - @event_loop.on(interval_for(ERROR_EVENT_DATA)) do - transmit_error_event_data - end - @event_loop.on(interval_for(SPAN_EVENT_DATA)) do - transmit_span_event_data - end - @event_loop.on(interval_for(LOG_EVENT_DATA)) do - transmit_log_event_data - end - - @event_loop.on(:reset_log_once_keys) do - ::NewRelic::Agent.logger.clear_already_logged - end - @event_loop.fire_every(Agent.config[:data_report_period], data_harvest) - @event_loop.fire_every(Agent.config[:event_report_period], event_harvest) - @event_loop.fire_every(LOG_ONCE_KEYS_RESET_PERIOD, :reset_log_once_keys) + establish_interval_transmissions + establish_fire_everies(data_harvest) @event_loop.run end @@ -100,7 +77,7 @@ def create_and_run_event_loop def handle_force_restart(error) ::NewRelic::Agent.logger.debug(error.message) drop_buffered_data - @service.force_restart if @service + @service&.force_restart @connect_state = :pending sleep(30) end @@ -109,7 +86,7 @@ def handle_force_restart(error) # is the worker thread that gathers data and talks to the # server. def handle_force_disconnect(error) - ::NewRelic::Agent.logger.warn("Agent received a ForceDisconnectException from the server, disconnecting. " \ + ::NewRelic::Agent.logger.warn('Agent received a ForceDisconnectException from the server, disconnecting. ' \ "(#{error.message})") disconnect end @@ -118,7 +95,7 @@ def handle_force_disconnect(error) # it and disconnecting the agent, since we are now in an # unknown state. def handle_other_error(error) - ::NewRelic::Agent.logger.error("Unhandled error in worker thread, disconnecting.") + ::NewRelic::Agent.logger.error('Unhandled error in worker thread, disconnecting.') # These errors are fatal (that is, they will prevent the agent from # reporting entirely), so we really want backtraces when they happen ::NewRelic::Agent.logger.log_exception(:error, error) @@ -156,11 +133,42 @@ def deferred_work!(connection_options) # never reaches here unless there is a problem or # the agent is exiting else - ::NewRelic::Agent.logger.debug("No connection. Worker thread ending.") + ::NewRelic::Agent.logger.debug('No connection. Worker thread ending.') end end end end + + private + + def establish_interval_transmissions + @event_loop.on(interval_for(TRANSACTION_EVENT_DATA)) do + transmit_analytic_event_data + end + @event_loop.on(interval_for(CUSTOM_EVENT_DATA)) do + transmit_custom_event_data + end + @event_loop.on(interval_for(ERROR_EVENT_DATA)) do + transmit_error_event_data + end + @event_loop.on(interval_for(SPAN_EVENT_DATA)) do + transmit_span_event_data + end + @event_loop.on(interval_for(LOG_EVENT_DATA)) do + transmit_log_event_data + end + end + + def establish_fire_everies(data_harvest) + @event_loop.on(:reset_log_once_keys) do + ::NewRelic::Agent.logger.clear_already_logged + end + + event_harvest = :"#{Agent.config[:event_report_period]}_second_harvest" + @event_loop.fire_every(Agent.config[:data_report_period], data_harvest) + @event_loop.fire_every(Agent.config[:event_report_period], event_harvest) + @event_loop.fire_every(LOG_ONCE_KEYS_RESET_PERIOD, :reset_log_once_keys) + end end end end diff --git a/lib/new_relic/agent/agent_helpers/startup.rb b/lib/new_relic/agent/agent_helpers/startup.rb index b312e7d00f..c71719a95d 100644 --- a/lib/new_relic/agent/agent_helpers/startup.rb +++ b/lib/new_relic/agent/agent_helpers/startup.rb @@ -14,7 +14,7 @@ def started? # Check whether we have already started, which is an error condition def already_started? if started? - ::NewRelic::Agent.logger.error("Agent Started Already!") + ::NewRelic::Agent.logger.error('Agent Started Already!') true end end @@ -87,15 +87,15 @@ def log_dispatcher end def log_app_name - ::NewRelic::Agent.logger.info("Application: #{Agent.config[:app_name].join(", ")}") + ::NewRelic::Agent.logger.info("Application: #{Agent.config[:app_name].join(', ')}") end def log_ignore_url_regexes regexes = NewRelic::Agent.config[:'rules.ignore_url_regexes'] unless regexes.empty? - ::NewRelic::Agent.logger.info("Ignoring URLs that match the following regexes: " \ - "#{regexes.map(&:inspect).join(", ")}.") + ::NewRelic::Agent.logger.info('Ignoring URLs that match the following regexes: ' \ + "#{regexes.map(&:inspect).join(', ')}.") end end @@ -138,10 +138,10 @@ def has_license_key? if Agent.config[:license_key] && Agent.config[:license_key].length > 0 true else - ::NewRelic::Agent.logger.warn("No license key found. " + - "This often means your newrelic.yml file was not found, or it lacks a section for the running " \ + ::NewRelic::Agent.logger.warn('No license key found. ' + + 'This often means your newrelic.yml file was not found, or it lacks a section for the running ' \ "environment, '#{NewRelic::Control.instance.env}'. You may also want to try linting your newrelic.yml " \ - "to ensure it is valid YML.") + 'to ensure it is valid YML.') false end end @@ -169,21 +169,21 @@ def agent_should_start? return false if already_started? || disabled? if defer_for_delayed_job? - ::NewRelic::Agent.logger.debug("Deferring startup for DelayedJob") + ::NewRelic::Agent.logger.debug('Deferring startup for DelayedJob') return false end if defer_for_resque? - ::NewRelic::Agent.logger.debug("Deferring startup for Resque in case it daemonizes") + ::NewRelic::Agent.logger.debug('Deferring startup for Resque in case it daemonizes') return false end unless app_name_configured? - NewRelic::Agent.logger.error("No application name configured.", - "The Agent cannot start without at least one. Please check your ", - "newrelic.yml and ensure that it is valid and has at least one ", + NewRelic::Agent.logger.error('No application name configured.', + 'The Agent cannot start without at least one. Please check your ', + 'newrelic.yml and ensure that it is valid and has at least one ', "value set for app_name in the #{NewRelic::Control.instance.env} ", - "environment.") + 'environment.') return false end diff --git a/lib/new_relic/agent/agent_helpers/transmit.rb b/lib/new_relic/agent/agent_helpers/transmit.rb index 6741206c94..5ab441a0f6 100644 --- a/lib/new_relic/agent/agent_helpers/transmit.rb +++ b/lib/new_relic/agent/agent_helpers/transmit.rb @@ -6,27 +6,27 @@ module NewRelic module Agent module AgentHelpers module Transmit - TRANSACTION_EVENT = "TransactionEvent".freeze + TRANSACTION_EVENT = 'TransactionEvent'.freeze def transmit_analytic_event_data transmit_single_data_type(:harvest_and_send_analytic_event_data, TRANSACTION_EVENT) end - CUSTOM_EVENT = "CustomEvent".freeze + CUSTOM_EVENT = 'CustomEvent'.freeze def transmit_custom_event_data transmit_single_data_type(:harvest_and_send_custom_event_data, CUSTOM_EVENT) end - ERROR_EVENT = "ErrorEvent".freeze + ERROR_EVENT = 'ErrorEvent'.freeze def transmit_error_event_data transmit_single_data_type(:harvest_and_send_error_event_data, ERROR_EVENT) end - SPAN_EVENT = "SpanEvent".freeze + SPAN_EVENT = 'SpanEvent'.freeze def transmit_span_event_data transmit_single_data_type(:harvest_and_send_span_event_data, SPAN_EVENT) end - LOG_EVENT = "LogEvent".freeze + LOG_EVENT = 'LogEvent'.freeze def transmit_log_event_data transmit_single_data_type(:harvest_and_send_log_event_data, LOG_EVENT) end @@ -47,7 +47,7 @@ def transmit_single_data_type(harvest_method, supportability_name) def transmit_data now = Process.clock_gettime(Process::CLOCK_MONOTONIC) - ::NewRelic::Agent.logger.debug("Sending data to New Relic Service") + ::NewRelic::Agent.logger.debug('Sending data to New Relic Service') @events.notify(:before_harvest) @service.session do # use http keep-alive diff --git a/lib/new_relic/agent/agent_logger.rb b/lib/new_relic/agent/agent_logger.rb index f97e45550a..e5fe2fa1e9 100644 --- a/lib/new_relic/agent/agent_logger.rb +++ b/lib/new_relic/agent/agent_logger.rb @@ -13,7 +13,7 @@ module Agent class AgentLogger include LogOnce - def initialize(root = "", override_logger = nil) + def initialize(root = '', override_logger = nil) @already_logged_lock = Mutex.new clear_already_logged create_log(root, override_logger) @@ -53,13 +53,13 @@ def is_startup_logger? # default behavior of backtraces logged at debug, use one of the methods # above and pass an Exception as one of the args. def log_exception(level, e, backtrace_level = level) - @log.send(level, "%p: %s" % [e.class, e.message]) + @log.send(level, '%p: %s' % [e.class, e.message]) @log.send(backtrace_level) do backtrace = backtrace_from_exception(e) if backtrace "Debugging backtrace:\n" + backtrace.join("\n ") else - "No backtrace available." + 'No backtrace available.' end end end @@ -150,11 +150,11 @@ def set_log_level! end LOG_LEVELS = { - "debug" => ::Logger::DEBUG, - "info" => ::Logger::INFO, - "warn" => ::Logger::WARN, - "error" => ::Logger::ERROR, - "fatal" => ::Logger::FATAL + 'debug' => ::Logger::DEBUG, + 'info' => ::Logger::INFO, + 'warn' => ::Logger::WARN, + 'error' => ::Logger::ERROR, + 'fatal' => ::Logger::FATAL } def self.log_level_for(level) @@ -165,7 +165,7 @@ def set_log_format! @hostname = NewRelic::Agent::Hostname.get @prefix = wants_stdout? ? '** [NewRelic]' : '' @log.formatter = proc do |severity, timestamp, progname, msg| - "#{@prefix}[#{timestamp.strftime("%F %H:%M:%S %z")} #{@hostname} (#{$$})] #{severity} : #{msg}\n" + "#{@prefix}[#{timestamp.strftime('%F %H:%M:%S %z')} #{@hostname} (#{$$})] #{severity} : #{msg}\n" end end diff --git a/lib/new_relic/agent/attribute_filter.rb b/lib/new_relic/agent/attribute_filter.rb index 4a5dcc42d9..bc082daba8 100644 --- a/lib/new_relic/agent/attribute_filter.rb +++ b/lib/new_relic/agent/attribute_filter.rb @@ -273,8 +273,8 @@ class AttributeFilterRule attr_reader :attribute_name, :destinations, :is_include, :wildcard def initialize(attribute_name, destinations, is_include) - @attribute_name = attribute_name.sub(/\*$/, "") - @wildcard = attribute_name.end_with?("*") + @attribute_name = attribute_name.sub(/\*$/, '') + @wildcard = attribute_name.end_with?('*') @is_include = is_include @destinations = is_include ? destinations : ~destinations end diff --git a/lib/new_relic/agent/attribute_processing.rb b/lib/new_relic/agent/attribute_processing.rb index 6f7b033a33..e23a145c9a 100644 --- a/lib/new_relic/agent/attribute_processing.rb +++ b/lib/new_relic/agent/attribute_processing.rb @@ -7,8 +7,8 @@ module Agent module AttributeProcessing module_function - EMPTY_HASH_STRING_LITERAL = "{}".freeze - EMPTY_ARRAY_STRING_LITERAL = "[]".freeze + EMPTY_HASH_STRING_LITERAL = '{}'.freeze + EMPTY_ARRAY_STRING_LITERAL = '[]'.freeze def flatten_and_coerce(object, prefix = nil, result = {}, &blk) if object.is_a?(Hash) diff --git a/lib/new_relic/agent/audit_logger.rb b/lib/new_relic/agent/audit_logger.rb index 8290373830..0e63a5cc0b 100644 --- a/lib/new_relic/agent/audit_logger.rb +++ b/lib/new_relic/agent/audit_logger.rb @@ -32,9 +32,9 @@ def log_request_headers(uri, headers) @log.info("REQUEST HEADERS: #{headers}") rescue StandardError, SystemStackError, SystemCallError => e - ::NewRelic::Agent.logger.warn("Failed writing request headers to audit log", e) + ::NewRelic::Agent.logger.warn('Failed writing request headers to audit log', e) rescue Exception => e - ::NewRelic::Agent.logger.warn("Failed writing request headers to audit log with exception. Re-raising in case of interrupt.", e) + ::NewRelic::Agent.logger.warn('Failed writing request headers to audit log with exception. Re-raising in case of interrupt.', e) raise end @@ -50,9 +50,9 @@ def log_request(uri, data, marshaller) @log.info("REQUEST: #{uri}") @log.info("REQUEST BODY: #{request_body}") rescue StandardError, SystemStackError, SystemCallError => e - ::NewRelic::Agent.logger.warn("Failed writing to audit log", e) + ::NewRelic::Agent.logger.warn('Failed writing to audit log', e) rescue Exception => e - ::NewRelic::Agent.logger.warn("Failed writing to audit log with exception. Re-raising in case of interrupt.", e) + ::NewRelic::Agent.logger.warn('Failed writing to audit log with exception. Re-raising in case of interrupt.', e) raise end @@ -64,7 +64,7 @@ def setup_logger if wants_stdout? # Using $stdout global for easier reassignment in testing @log = ::Logger.new($stdout) - ::NewRelic::Agent.logger.info("Audit log enabled to STDOUT") + ::NewRelic::Agent.logger.info('Audit log enabled to STDOUT') elsif path = ensure_log_path @log = ::Logger.new(path) ::NewRelic::Agent.logger.info("Audit log enabled at '#{path}'") diff --git a/lib/new_relic/agent/autostart.rb b/lib/new_relic/agent/autostart.rb index 57307b42db..12a7ab1a6b 100644 --- a/lib/new_relic/agent/autostart.rb +++ b/lib/new_relic/agent/autostart.rb @@ -28,7 +28,7 @@ def agent_should_start? !in_denylisted_rake_task? end - COMMA = ",".freeze + COMMA = ','.freeze def denylisted_constants? denylisted?(NewRelic::Agent.config[:'autostart.denylisted_constants']) do |name| diff --git a/lib/new_relic/agent/commands/agent_command.rb b/lib/new_relic/agent/commands/agent_command.rb index e9c23538b3..9c1a0d0af5 100644 --- a/lib/new_relic/agent/commands/agent_command.rb +++ b/lib/new_relic/agent/commands/agent_command.rb @@ -10,8 +10,8 @@ class AgentCommand def initialize(raw_collector_command) @id = raw_collector_command[0] - @name = raw_collector_command[1]["name"] - @arguments = raw_collector_command[1]["arguments"] + @name = raw_collector_command[1]['name'] + @arguments = raw_collector_command[1]['arguments'] end end end diff --git a/lib/new_relic/agent/commands/agent_command_router.rb b/lib/new_relic/agent/commands/agent_command_router.rb index 083d9a7cda..cf8a0e3e81 100644 --- a/lib/new_relic/agent/commands/agent_command_router.rb +++ b/lib/new_relic/agent/commands/agent_command_router.rb @@ -29,7 +29,8 @@ def initialize(event_listener = nil) @handlers['start_profiler'] = proc { |cmd| thread_profiler_session.handle_start_command(cmd) } @handlers['stop_profiler'] = proc { |cmd| thread_profiler_session.handle_stop_command(cmd) } - if event_listener + # the following statement needs else branch coverage + if event_listener # rubocop:disable Style/SafeNavigation event_listener.subscribe(:before_shutdown, &method(:on_before_shutdown)) end end @@ -77,10 +78,10 @@ def harvest_from_thread_profiler_session def log_profiles(profiles) if profiles.empty? - ::NewRelic::Agent.logger.debug("No thread profiles with data found to send.") + ::NewRelic::Agent.logger.debug('No thread profiles with data found to send.') else profile_descriptions = profiles.map { |p| p.to_log_description } - ::NewRelic::Agent.logger.debug("Sending thread profiles [#{profile_descriptions.join(", ")}]") + ::NewRelic::Agent.logger.debug("Sending thread profiles [#{profile_descriptions.join(', ')}]") end end @@ -114,7 +115,7 @@ def invoke_command(agent_command) end SUCCESS_RESULT = NewRelic::EMPTY_HASH - ERROR_KEY = "error" + ERROR_KEY = 'error' def success SUCCESS_RESULT diff --git a/lib/new_relic/agent/commands/thread_profiler_session.rb b/lib/new_relic/agent/commands/thread_profiler_session.rb index 8f65372cc0..e9976e62d5 100644 --- a/lib/new_relic/agent/commands/thread_profiler_session.rb +++ b/lib/new_relic/agent/commands/thread_profiler_session.rb @@ -25,12 +25,12 @@ def handle_start_command(agent_command) end def handle_stop_command(agent_command) - report_data = agent_command.arguments.fetch("report_data", true) + report_data = agent_command.arguments.fetch('report_data', true) stop(report_data) end def start(agent_command) - NewRelic::Agent.logger.debug("Starting Thread Profiler.") + NewRelic::Agent.logger.debug('Starting Thread Profiler.') profile = @backtrace_service.subscribe( NewRelic::Agent::Threading::BacktraceService::ALL_TRANSACTIONS, agent_command.arguments @@ -43,7 +43,7 @@ def start(agent_command) def stop(report_data) return unless running? - NewRelic::Agent.logger.debug("Stopping Thread Profiler.") + NewRelic::Agent.logger.debug('Stopping Thread Profiler.') @finished_profile = @backtrace_service.harvest(NewRelic::Agent::Threading::BacktraceService::ALL_TRANSACTIONS) @backtrace_service.unsubscribe(NewRelic::Agent::Threading::BacktraceService::ALL_TRANSACTIONS) @finished_profile = nil if !report_data @@ -51,7 +51,7 @@ def stop(report_data) def harvest NewRelic::Agent.logger.debug( - "Harvesting from Thread Profiler #{@finished_profile.to_log_description unless @finished_profile.nil?}" + "Harvesting from Thread Profiler #{@finished_profile&.to_log_description}" ) profile = @finished_profile @backtrace_service.profile_agent_code = false @@ -102,7 +102,7 @@ def raise_thread_profiler_disabled end def raise_already_started_error - msg = "Profile already in progress. Ignoring agent command to start another." + msg = 'Profile already in progress. Ignoring agent command to start another.' raise_command_error(msg) end end diff --git a/lib/new_relic/agent/configuration/default_source.rb b/lib/new_relic/agent/configuration/default_source.rb index 1b0c6a5666..85a862f06a 100644 --- a/lib/new_relic/agent/configuration/default_source.rb +++ b/lib/new_relic/agent/configuration/default_source.rb @@ -29,11 +29,11 @@ def self.value_of(key) def self.instrumentation_value_of(disable_key, prepend_key = nil) proc do if NewRelic::Agent.config[disable_key] - "disabled" + 'disabled' elsif prepend_key && !NewRelic::Agent.config[prepend_key] - "chain" + 'chain' else - "auto" + 'auto' end end end @@ -47,7 +47,7 @@ def self.instrumentation_value_from_boolean(key) # Marks the config option as deprecated in the documentation once generated. # Does not appear in logs. def self.deprecated_description(new_setting, description) - link_ref = new_setting.to_s.tr(".", "-") + link_ref = new_setting.to_s.tr('.', '-') %{Please see: [#{new_setting}](docs/agents/ruby-agent/configuration/ruby-agent-configuration##{link_ref}). \n\n#{description}} end @@ -80,34 +80,35 @@ def self.transform_for(key) default_settings[:transform] if default_settings end - def self.config_search_paths + def self.config_search_paths # rubocop:disable Metrics/AbcSize proc { - paths = [ - File.join("config", "newrelic.yml"), - File.join("newrelic.yml"), - File.join("config", "newrelic.yml.erb"), - File.join("newrelic.yml.erb") - ] + yaml = 'newrelic.yml' + config_yaml = File.join('config', yaml) + erb = 'newrelic.yml.erb' + config_erb = File.join('config', erb) + + paths = [config_yaml, yaml, config_erb, erb] if NewRelic::Control.instance.root - paths << File.join(NewRelic::Control.instance.root, "config", "newrelic.yml") - paths << File.join(NewRelic::Control.instance.root, "newrelic.yml") - paths << File.join(NewRelic::Control.instance.root, "config", "newrelic.yml.erb") - paths << File.join(NewRelic::Control.instance.root, "newrelic.yml.erb") + paths << File.join(NewRelic::Control.instance.root, config_yaml) + paths << File.join(NewRelic::Control.instance.root, yaml) + paths << File.join(NewRelic::Control.instance.root, config_erb) + paths << File.join(NewRelic::Control.instance.root, erb) end if ENV['HOME'] - paths << File.join(ENV['HOME'], ".newrelic", "newrelic.yml") - paths << File.join(ENV['HOME'], "newrelic.yml") - paths << File.join(ENV['HOME'], ".newrelic", "newrelic.yml.erb") - paths << File.join(ENV['HOME'], "newrelic.yml.erb") + paths << File.join(ENV['HOME'], '.newrelic', yaml) + paths << File.join(ENV['HOME'], yaml) + paths << File.join(ENV['HOME'], '.newrelic', erb) + paths << File.join(ENV['HOME'], erb) end # If we're packaged for warbler, we can tell from GEM_HOME - if ENV["GEM_HOME"] && ENV["GEM_HOME"].end_with?(".jar!") - app_name = File.basename(ENV["GEM_HOME"], ".jar!") - paths << File.join(ENV["GEM_HOME"], app_name, "config", "newrelic.yml") - paths << File.join(ENV["GEM_HOME"], app_name, "config", "newrelic.yml.erb") + # the following line needs else branch coverage + if ENV['GEM_HOME'] && ENV['GEM_HOME'].end_with?('.jar!') # rubocop:disable Style/SafeNavigation + app_name = File.basename(ENV['GEM_HOME'], '.jar!') + paths << File.join(ENV['GEM_HOME'], app_name, config_yaml) + paths << File.join(ENV['GEM_HOME'], app_name, config_erb) end paths @@ -206,11 +207,11 @@ def self.api_host # only used for deployment task proc do api_version = if NewRelic::Agent.config[:api_key].nil? || NewRelic::Agent.config[:api_key].empty? - "rpm" + 'rpm' else - "api" + 'api' end - api_region = "eu." if String(NewRelic::Agent.config[:license_key]).start_with?('eu') + api_region = 'eu.' if String(NewRelic::Agent.config[:license_key]).start_with?('eu') "#{api_version}.#{api_region}newrelic.com" end @@ -432,7 +433,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :public => true, :type => Boolean, :allowed_from_server => true, - :description => "Allows newrelic distributed tracing headers to be suppressed on outbound requests." + :description => 'Allows newrelic distributed tracing headers to be suppressed on outbound requests.' }, :force_install_exit_handler => { :default => false, @@ -959,7 +960,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :description => 'If `true`, enables an audit log which logs communications with the New Relic [collector](/docs/using-new-relic/welcome-new-relic/get-started/glossary/#collector).' }, :'audit_log.endpoints' => { - :default => [".*"], + :default => ['.*'], :public => true, :type => Array, :allowed_from_server => false, @@ -1281,10 +1282,10 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => String, :allowed_from_server => false, :external => :infinite_tracing, - :description => "Configures the hostname for the trace observer Host. " \ - "When configured, enables tail-based sampling by sending all recorded spans " \ - "to a trace observer for further sampling decisions, irrespective of any usual " \ - "agent sampling decision." + :description => 'Configures the hostname for the trace observer Host. ' \ + 'When configured, enables tail-based sampling by sending all recorded spans ' \ + 'to a trace observer for further sampling decisions, irrespective of any usual ' \ + 'agent sampling decision.' }, :'infinite_tracing.trace_observer.port' => { :default => 443, @@ -1292,7 +1293,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => Integer, :allowed_from_server => false, :external => :infinite_tracing, - :description => "Configures the TCP/IP port for the trace observer Host" + :description => 'Configures the TCP/IP port for the trace observer Host' }, # Instrumentation :'instrumentation.active_support_logger' => { @@ -1361,7 +1362,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => "Controls auto-instrumentation of Excon at start up. May be one of [enabled|disabled]." + :description => 'Controls auto-instrumentation of Excon at start up. May be one of [enabled|disabled].' }, :'instrumentation.grape' => { :default => 'auto', @@ -1369,7 +1370,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => "Controls auto-instrumentation of Grape at start up. May be one of [auto|prepend|chain|disabled]." + :description => 'Controls auto-instrumentation of Grape at start up. May be one of [auto|prepend|chain|disabled].' }, :'instrumentation.grpc_client' => { :default => instrumentation_value_of(:disable_grpc_client), @@ -1404,7 +1405,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => "Controls auto-instrumentation of HTTPClient at start up. May be one of [auto|prepend|chain|disabled]." + :description => 'Controls auto-instrumentation of HTTPClient at start up. May be one of [auto|prepend|chain|disabled].' }, :'instrumentation.httprb' => { :default => 'auto', @@ -1457,7 +1458,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => "Controls auto-instrumentation of Mongo at start up. May be one of [enabled|disabled]." + :description => 'Controls auto-instrumentation of Mongo at start up. May be one of [enabled|disabled].' }, :'instrumentation.net_http' => { :default => 'auto', @@ -1466,7 +1467,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => "Controls auto-instrumentation of Net::HTTP at start up. May be one of [auto|prepend|chain|disabled]." + :description => 'Controls auto-instrumentation of Net::HTTP at start up. May be one of [auto|prepend|chain|disabled].' }, :'instrumentation.puma_rack' => { :default => value_of(:'instrumentation.rack'), @@ -1475,9 +1476,9 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => "Controls auto-instrumentation of Puma::Rack. When enabled, the agent hooks into the " \ - "`to_app` method in Puma::Rack::Builder to find gems to instrument during " \ - "application startup. May be one of [auto|prepend|chain|disabled]." + :description => 'Controls auto-instrumentation of Puma::Rack. When enabled, the agent hooks into the ' \ + '`to_app` method in Puma::Rack::Builder to find gems to instrument during ' \ + 'application startup. May be one of [auto|prepend|chain|disabled].' }, :'instrumentation.puma_rack_urlmap' => { :default => value_of(:'instrumentation.rack_urlmap'), @@ -1495,9 +1496,9 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => "Controls auto-instrumentation of Rack. When enabled, the agent hooks into the " \ - "`to_app` method in Rack::Builder to find gems to instrument during " \ - "application startup. May be one of [auto|prepend|chain|disabled]." + :description => 'Controls auto-instrumentation of Rack. When enabled, the agent hooks into the ' \ + '`to_app` method in Rack::Builder to find gems to instrument during ' \ + 'application startup. May be one of [auto|prepend|chain|disabled].' }, :'instrumentation.rack_urlmap' => { :default => 'auto', @@ -1514,7 +1515,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => "Controls auto-instrumentation of rake at start up. May be one of [auto|prepend|chain|disabled]." + :description => 'Controls auto-instrumentation of rake at start up. May be one of [auto|prepend|chain|disabled].' }, :'instrumentation.redis' => { :default => 'auto', @@ -1522,7 +1523,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => "Controls auto-instrumentation of Redis at start up. May be one of [auto|prepend|chain|disabled]." + :description => 'Controls auto-instrumentation of Redis at start up. May be one of [auto|prepend|chain|disabled].' }, :'instrumentation.resque' => { :default => 'auto', @@ -1531,7 +1532,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => "Controls auto-instrumentation of resque at start up. May be one of [auto|prepend|chain|disabled]." + :description => 'Controls auto-instrumentation of resque at start up. May be one of [auto|prepend|chain|disabled].' }, :'instrumentation.sinatra' => { :default => 'auto', @@ -1539,7 +1540,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => "Controls auto-instrumentation of Sinatra at start up. May be one of [auto|prepend|chain|disabled]." + :description => 'Controls auto-instrumentation of Sinatra at start up. May be one of [auto|prepend|chain|disabled].' }, :'instrumentation.thread' => { :default => 'auto', @@ -1547,24 +1548,24 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => "Controls auto-instrumentation of the Thread class at start up to allow the agent to correctly nest spans inside of an asynchronous transaction. This does not enable the agent to automatically trace all threads created (see `instrumentation.thread.tracing`). May be one of [auto|prepend|chain|disabled]." + :description => 'Controls auto-instrumentation of the Thread class at start up to allow the agent to correctly nest spans inside of an asynchronous transaction. This does not enable the agent to automatically trace all threads created (see `instrumentation.thread.tracing`). May be one of [auto|prepend|chain|disabled].' }, :'instrumentation.thread.tracing' => { :default => true, :public => true, :type => Boolean, :allowed_from_server => false, - :description => "Controls auto-instrumentation of the Thread class at start up to automatically add tracing to all Threads created in the application." + :description => 'Controls auto-instrumentation of the Thread class at start up to automatically add tracing to all Threads created in the application.' }, :'thread_ids_enabled' => { :default => false, :public => false, :type => Boolean, :allowed_from_server => false, - :description => "If enabled, will append the current Thread and Fiber object ids onto the segment names of segments created in Threads and concurrent-ruby" + :description => 'If enabled, will append the current Thread and Fiber object ids onto the segment names of segments created in Threads and concurrent-ruby' }, :'instrumentation.tilt' => { - :default => "auto", + :default => 'auto', :public => true, :type => String, :dynamic_name => true, @@ -1578,7 +1579,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => String, :dynamic_name => true, :allowed_from_server => false, - :description => "Controls auto-instrumentation of Typhoeus at start up. May be one of [auto|prepend|chain|disabled]." + :description => 'Controls auto-instrumentation of Typhoeus at start up. May be one of [auto|prepend|chain|disabled].' }, # Message tracer :'message_tracer.segment_parameters.enabled' => { @@ -1709,7 +1710,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :type => Integer, :allowed_from_server => false, :external => :infinite_tracing, - :description => "Sets the maximum number of span events to buffer when streaming to the trace observer." + :description => 'Sets the maximum number of span events to buffer when streaming to the trace observer.' }, :'span_events.max_samples_stored' => { :default => 2000, @@ -2016,7 +2017,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :public => false, :type => String, :allowed_from_server => false, - :description => "URI for the New Relic data collection service." + :description => 'URI for the New Relic data collection service.' }, :'infinite_tracing.batching' => { :default => true, @@ -2025,7 +2026,7 @@ def self.enforce_fallback(allowed_values: nil, fallback: nil) :allowed_from_server => false, :external => :infinite_tracing, :description => "If `true` (the default), data sent to the trace observer is batched\ninstead of sending " \ - "each span individually." + 'each span individually.' }, :'infinite_tracing.compression_level' => { :default => :high, diff --git a/lib/new_relic/agent/configuration/environment_source.rb b/lib/new_relic/agent/configuration/environment_source.rb index b1e2a0c3a4..f5eadb4f2f 100644 --- a/lib/new_relic/agent/configuration/environment_source.rb +++ b/lib/new_relic/agent/configuration/environment_source.rb @@ -94,14 +94,14 @@ def set_key_by_type(config_key, environment_key) elsif type == Array self[config_key] = value.split(/\s*,\s*/) elsif type == NewRelic::Agent::Configuration::Boolean - if value =~ /false|off|no/i + if /false|off|no/i.match?(value) self[config_key] = false elsif !value.nil? self[config_key] = true end else ::NewRelic::Agent.logger.info("#{environment_key} does not have a corresponding configuration setting (#{config_key} does not exist).") - ::NewRelic::Agent.logger.info("Run `rake newrelic:config:docs` or visit https://newrelic.com/docs/ruby/ruby-agent-configuration to see a list of available configuration settings.") + ::NewRelic::Agent.logger.info('Run `rake newrelic:config:docs` or visit https://newrelic.com/docs/ruby/ruby-agent-configuration to see a list of available configuration settings.') self[config_key] = value end end diff --git a/lib/new_relic/agent/configuration/high_security_source.rb b/lib/new_relic/agent/configuration/high_security_source.rb index 23f7a0a205..9e57ffa246 100644 --- a/lib/new_relic/agent/configuration/high_security_source.rb +++ b/lib/new_relic/agent/configuration/high_security_source.rb @@ -24,9 +24,9 @@ def initialize(local_settings) }) end - OFF = "off".freeze - RAW = "raw".freeze - OBFUSCATED = "obfuscated".freeze + OFF = 'off'.freeze + RAW = 'raw'.freeze + OBFUSCATED = 'obfuscated'.freeze SET_TO_OBFUSCATED = [RAW, OBFUSCATED] diff --git a/lib/new_relic/agent/configuration/manager.rb b/lib/new_relic/agent/configuration/manager.rb index 838da230d9..7254db4731 100644 --- a/lib/new_relic/agent/configuration/manager.rb +++ b/lib/new_relic/agent/configuration/manager.rb @@ -241,8 +241,8 @@ def to_collector_hash end end - MALFORMED_LABELS_WARNING = "Skipping malformed labels configuration" - PARSING_LABELS_FAILURE = "Failure during parsing labels. Ignoring and carrying on with connect." + MALFORMED_LABELS_WARNING = 'Skipping malformed labels configuration' + PARSING_LABELS_FAILURE = 'Failure during parsing labels. Ignoring and carrying on with connect.' MAX_LABEL_COUNT = 64 MAX_LABEL_LENGTH = 255 diff --git a/lib/new_relic/agent/configuration/security_policy_source.rb b/lib/new_relic/agent/configuration/security_policy_source.rb index d21132cbf7..1e4c27338e 100644 --- a/lib/new_relic/agent/configuration/security_policy_source.rb +++ b/lib/new_relic/agent/configuration/security_policy_source.rb @@ -51,7 +51,7 @@ def change_setting(policies, option, new_value) # permitted by the security policy and is also enabled by the config SECURITY_SETTINGS_MAP = { - "record_sql" => [ + 'record_sql' => [ { option: :'transaction_tracer.record_sql', supported: true, @@ -96,7 +96,7 @@ def change_setting(policies, option, new_value) permitted_fn: nil } ], - "attributes_include" => [ + 'attributes_include' => [ { option: :'attributes.include', supported: true, @@ -147,7 +147,7 @@ def change_setting(policies, option, new_value) permitted_fn: nil } ], - "allow_raw_exception_messages" => [ + 'allow_raw_exception_messages' => [ { option: :'strip_exception_messages.enabled', supported: true, @@ -156,7 +156,7 @@ def change_setting(policies, option, new_value) permitted_fn: nil } ], - "custom_events" => [ + 'custom_events' => [ { option: :'custom_insights_events.enabled', supported: true, @@ -165,7 +165,7 @@ def change_setting(policies, option, new_value) permitted_fn: nil } ], - "custom_parameters" => [ + 'custom_parameters' => [ { option: :'custom_attributes.enabled', supported: true, @@ -174,7 +174,7 @@ def change_setting(policies, option, new_value) permitted_fn: nil } ], - "custom_instrumentation_editor" => [ + 'custom_instrumentation_editor' => [ { option: nil, supported: false, @@ -183,7 +183,7 @@ def change_setting(policies, option, new_value) permitted_fn: nil } ], - "message_parameters" => [ + 'message_parameters' => [ { option: :'message_tracer.segment_parameters.enabled', supported: true, @@ -198,8 +198,8 @@ def initialize(security_policies) super(build_overrides(security_policies)) end - ENABLED = "enabled".freeze - COLON_COLON = "::".freeze + ENABLED = 'enabled'.freeze + COLON_COLON = '::'.freeze def build_overrides(security_policies) security_policies.inject({}) do |settings, (policy_name, policy_settings)| @@ -222,7 +222,7 @@ def build_overrides(security_policies) settings[policy[:option]] = policy[:disabled_value] NewRelic::Agent.logger.info( \ "Setting applied: {#{policy[:option]}: #{policy[:disabled_value]}}. " \ - "Source: SecurityPolicySource" + 'Source: SecurityPolicySource' ) end end diff --git a/lib/new_relic/agent/configuration/server_source.rb b/lib/new_relic/agent/configuration/server_source.rb index 91af81afde..4570af338a 100644 --- a/lib/new_relic/agent/configuration/server_source.rb +++ b/lib/new_relic/agent/configuration/server_source.rb @@ -10,27 +10,27 @@ class ServerSource < DottedHash # response, but should still be merged in as config settings to the # main agent configuration. TOP_LEVEL_KEYS = [ - "account_id", - "apdex_t", - "application_id", - "beacon", - "browser_key", - "browser_monitoring.debug", - "browser_monitoring.loader", - "browser_monitoring.loader_version", - "cross_process_id", - "data_report_period", - "encoding_key", - "entity_guid", - "error_beacon", - "js_agent_file", - "js_agent_loader", - "max_payload_size_in_bytes", - "primary_application_id", - "sampling_target", - "sampling_target_period_in_seconds", - "trusted_account_ids", - "trusted_account_key" + 'account_id', + 'apdex_t', + 'application_id', + 'beacon', + 'browser_key', + 'browser_monitoring.debug', + 'browser_monitoring.loader', + 'browser_monitoring.loader_version', + 'cross_process_id', + 'data_report_period', + 'encoding_key', + 'entity_guid', + 'error_beacon', + 'js_agent_file', + 'js_agent_loader', + 'max_payload_size_in_bytes', + 'primary_application_id', + 'sampling_target', + 'sampling_target_period_in_seconds', + 'trusted_account_ids', + 'trusted_account_key' ] def initialize(connect_reply, existing_config = {}) @@ -70,7 +70,7 @@ def merge_agent_config_hash(merged_settings, connect_reply) def fix_transaction_threshold(merged_settings) # when value is "apdex_f" remove the config and defer to default - if merged_settings['transaction_tracer.transaction_threshold'].to_s =~ /apdex_f/i + if /apdex_f/i.match?(merged_settings['transaction_tracer.transaction_threshold'].to_s) merged_settings.delete('transaction_tracer.transaction_threshold') end end @@ -102,8 +102,8 @@ def event_harvest_config_is_valid(connect_reply) if event_harvest_config.nil? \ || event_harvest_config['harvest_limits'].values.min < 0 \ || (event_harvest_config['report_period_ms'] / 1000) <= 0 - NewRelic::Agent.logger.warn("Invalid event harvest config found " \ - "in connect response; using default event report period.") + NewRelic::Agent.logger.warn('Invalid event harvest config found ' \ + 'in connect response; using default event report period.') false else true diff --git a/lib/new_relic/agent/configuration/yaml_source.rb b/lib/new_relic/agent/configuration/yaml_source.rb index 85535344f7..81a99e40f4 100644 --- a/lib/new_relic/agent/configuration/yaml_source.rb +++ b/lib/new_relic/agent/configuration/yaml_source.rb @@ -84,7 +84,7 @@ def warn_missing_config_file(path) # so warn about it since it's very likely to be unintended. NewRelic::Agent.logger.warn( "No configuration file found. Working directory = #{Dir.pwd}", - "Looked in these locations (based on #{based_on}): #{candidate_paths.join(", ")}" + "Looked in these locations (based on #{based_on}): #{candidate_paths.join(', ')}" ) end @@ -96,7 +96,7 @@ def process_erb(file) file.gsub!(/^\s*#.*$/, '#') ERB.new(file).result(binding) rescue ScriptError, StandardError => e - log_failure("Failed ERB processing configuration file. This is typically caused by a Ruby error in <% %> templating blocks in your newrelic.yml file.", e) + log_failure('Failed ERB processing configuration file. This is typically caused by a Ruby error in <% %> templating blocks in your newrelic.yml file.', e) nil end end @@ -124,7 +124,7 @@ def substitute_transaction_threshold(config) config['transaction_tracer']['transaction_threshold'].to_s =~ /apdex_f/i # when value is "apdex_f" remove the config and defer to default config['transaction_tracer'].delete('transaction_threshold') - elsif config['transaction_tracer.transaction_threshold'].to_s =~ /apdex_f/i + elsif /apdex_f/i.match?(config['transaction_tracer.transaction_threshold'].to_s) config.delete('transaction_tracer.transaction_threshold') end end @@ -135,7 +135,7 @@ def booleanify_values(config, *keys) if 'auto' == config[option] config.delete(option) elsif !config[option].nil? && !is_boolean?(config[option]) - coerced_value = !!(config[option].to_s =~ /yes|on|true/i) + coerced_value = config[option].to_s.match?(/yes|on|true/i) if !coerced_value log_failure("Unexpected value (#{config[option]}) for '#{option}' in #{@path}") end diff --git a/lib/new_relic/agent/connect/request_builder.rb b/lib/new_relic/agent/connect/request_builder.rb index f9639231b1..2d852d5e76 100644 --- a/lib/new_relic/agent/connect/request_builder.rb +++ b/lib/new_relic/agent/connect/request_builder.rb @@ -48,7 +48,7 @@ def sanitize_environment_report(environment_report) def environment_metadata env_copy = {} - ENV.keys.each { |k| env_copy[k] = ENV[k] if k =~ /^NEW_RELIC_METADATA_/ } + ENV.keys.each { |k| env_copy[k] = ENV[k] if /^NEW_RELIC_METADATA_/.match?(k) } env_copy end diff --git a/lib/new_relic/agent/connect/response_handler.rb b/lib/new_relic/agent/connect/response_handler.rb index 6be46bfd7c..ec469d6c9f 100644 --- a/lib/new_relic/agent/connect/response_handler.rb +++ b/lib/new_relic/agent/connect/response_handler.rb @@ -37,7 +37,7 @@ def configure_agent(config_data) def add_server_side_config(config_data) if config_data['agent_config'] - ::NewRelic::Agent.logger.debug("Using config from server") + ::NewRelic::Agent.logger.debug('Using config from server') end ::NewRelic::Agent.logger.debug("Server provided config: #{config_data.inspect}") diff --git a/lib/new_relic/agent/custom_event_aggregator.rb b/lib/new_relic/agent/custom_event_aggregator.rb index 5af3cf9aad..c15596fd89 100644 --- a/lib/new_relic/agent/custom_event_aggregator.rb +++ b/lib/new_relic/agent/custom_event_aggregator.rb @@ -27,7 +27,7 @@ def record(type, attributes) return unless enabled? type = @type_strings[type] - unless type =~ EVENT_TYPE_REGEX + unless EVENT_TYPE_REGEX.match?(type) note_dropped_event(type) return false end @@ -71,9 +71,9 @@ def note_dropped_events(total_count, dropped_count) def record_supportability_metrics(total_count, captured_count, dropped_count) engine = NewRelic::Agent.instance.stats_engine - engine.tl_record_supportability_metric_count("Events/Customer/Seen", total_count) - engine.tl_record_supportability_metric_count("Events/Customer/Sent", captured_count) - engine.tl_record_supportability_metric_count("Events/Customer/Dropped", dropped_count) + engine.tl_record_supportability_metric_count('Events/Customer/Seen', total_count) + engine.tl_record_supportability_metric_count('Events/Customer/Sent', captured_count) + engine.tl_record_supportability_metric_count('Events/Customer/Dropped', dropped_count) end def note_dropped_event(type) diff --git a/lib/new_relic/agent/database.rb b/lib/new_relic/agent/database.rb index 20f03b37c6..63b25c8f08 100644 --- a/lib/new_relic/agent/database.rb +++ b/lib/new_relic/agent/database.rb @@ -10,7 +10,7 @@ module NewRelic module Agent module Database MAX_QUERY_LENGTH = 16384 - ELLIPSIS = "...".freeze + ELLIPSIS = '...'.freeze extend self @@ -150,7 +150,7 @@ def get_connection(config, &connector) begin @connections[config] = yield(config) rescue => e - ::NewRelic::Agent.logger.error("Caught exception trying to get connection to DB for explain.", e) + ::NewRelic::Agent.logger.error('Caught exception trying to get connection to DB for explain.', e) nil end end @@ -174,7 +174,7 @@ class Statement attr_accessor :sql, :config, :explainer, :binds, :name, :host, :port_path_or_id, :database_name - DEFAULT_QUERY_NAME = "SQL".freeze + DEFAULT_QUERY_NAME = 'SQL'.freeze def initialize(sql, config = {}, explainer = nil, binds = nil, name = DEFAULT_QUERY_NAME, host = nil, port_path_or_id = nil, database_name = nil) @sql = Database.capture_query(sql) @@ -219,7 +219,7 @@ def explain start = Process.clock_gettime(Process::CLOCK_MONOTONIC) plan = @explainer.call(self) ::NewRelic::Agent.record_metric( - "Supportability/Database/execute_explain_plan", + 'Supportability/Database/execute_explain_plan', Process.clock_gettime(Process::CLOCK_MONOTONIC) - start ) return process_resultset(plan, adapter) if plan diff --git a/lib/new_relic/agent/database/explain_plan_helpers.rb b/lib/new_relic/agent/database/explain_plan_helpers.rb index e851c72c37..55977fa16a 100644 --- a/lib/new_relic/agent/database/explain_plan_helpers.rb +++ b/lib/new_relic/agent/database/explain_plan_helpers.rb @@ -36,7 +36,7 @@ def handle_exception_in_explain rescue => e begin # guarantees no throw from explain_sql - ::NewRelic::Agent.logger.error("Error getting query plan:", e) + ::NewRelic::Agent.logger.error('Error getting query plan:', e) nil rescue # double exception. throw up your hands diff --git a/lib/new_relic/agent/database/obfuscation_helpers.rb b/lib/new_relic/agent/database/obfuscation_helpers.rb index 3b76783f6b..12ae7fd043 100644 --- a/lib/new_relic/agent/database/obfuscation_helpers.rb +++ b/lib/new_relic/agent/database/obfuscation_helpers.rb @@ -49,10 +49,10 @@ module ObfuscationHelpers } PLACEHOLDER = '?'.freeze - FAILED_TO_OBFUSCATE_MESSAGE = "Failed to obfuscate SQL query - quote characters remained after obfuscation".freeze + FAILED_TO_OBFUSCATE_MESSAGE = 'Failed to obfuscate SQL query - quote characters remained after obfuscation'.freeze def obfuscate_single_quote_literals(sql) - return sql unless sql =~ COMPONENTS_REGEX_MAP[:single_quotes] + return sql unless sql&.match?(COMPONENTS_REGEX_MAP[:single_quotes]) sql.gsub(COMPONENTS_REGEX_MAP[:single_quotes], PLACEHOLDER) end diff --git a/lib/new_relic/agent/database/obfuscator.rb b/lib/new_relic/agent/database/obfuscator.rb index 483f56887b..0a90dcdb6c 100644 --- a/lib/new_relic/agent/database/obfuscator.rb +++ b/lib/new_relic/agent/database/obfuscator.rb @@ -13,8 +13,8 @@ class Obfuscator attr_reader :obfuscator - QUERY_TOO_LARGE_MESSAGE = "Query too large (over 16k characters) to safely obfuscate".freeze - ELLIPSIS = "...".freeze + QUERY_TOO_LARGE_MESSAGE = 'Query too large (over 16k characters) to safely obfuscate'.freeze + ELLIPSIS = '...'.freeze def initialize reset diff --git a/lib/new_relic/agent/datastores/metric_helper.rb b/lib/new_relic/agent/datastores/metric_helper.rb index f2ba77d8b9..10d5d66151 100644 --- a/lib/new_relic/agent/datastores/metric_helper.rb +++ b/lib/new_relic/agent/datastores/metric_helper.rb @@ -6,12 +6,12 @@ module NewRelic module Agent module Datastores module MetricHelper - ROLLUP_METRIC = "Datastore/all".freeze - OTHER = "Other".freeze + ROLLUP_METRIC = 'Datastore/all'.freeze + OTHER = 'Other'.freeze - ALL = "all".freeze - ALL_WEB = "allWeb".freeze - ALL_OTHER = "allOther".freeze + ALL = 'all'.freeze + ALL_WEB = 'allWeb'.freeze + ALL_OTHER = 'allOther'.freeze def self.statement_metric_for(product, collection, operation) "Datastore/statement/#{product}/#{collection}/#{operation}" diff --git a/lib/new_relic/agent/datastores/mongo/metric_translator.rb b/lib/new_relic/agent/datastores/mongo/metric_translator.rb index 774b7f24d9..9ba30ef232 100644 --- a/lib/new_relic/agent/datastores/mongo/metric_translator.rb +++ b/lib/new_relic/agent/datastores/mongo/metric_translator.rb @@ -53,7 +53,7 @@ def self.operation_and_collection_for(name, payload) [name.to_s, collection] rescue => e - NewRelic::Agent.logger.debug("Failure during Mongo metric generation", e) + NewRelic::Agent.logger.debug('Failure during Mongo metric generation', e) nil end @@ -64,10 +64,10 @@ def self.collection_in_selector?(payload) NAMES_IN_SELECTOR = [ :findandmodify, - "aggregate", - "count", - "group", - "mapreduce", + 'aggregate', + 'count', + 'group', + 'mapreduce', :distinct, @@ -91,18 +91,18 @@ def self.get_name_from_selector(command_key, payload) if command_key command_key.to_sym else - NewRelic::Agent.increment_metric("Supportability/Mongo/UnknownCollection") + NewRelic::Agent.increment_metric('Supportability/Mongo/UnknownCollection') payload[:selector].first.first unless command_key end end - CMD_COLLECTION = "$cmd".freeze + CMD_COLLECTION = '$cmd'.freeze def self.get_collection_from_selector(command_key, payload) if command_key payload[:selector][command_key] else - NewRelic::Agent.increment_metric("Supportability/Mongo/UnknownCollection") + NewRelic::Agent.increment_metric('Supportability/Mongo/UnknownCollection') CMD_COLLECTION end end @@ -124,11 +124,11 @@ def self.create_indexes?(name, _payload) end def self.create_index?(name, payload) - name == :insert && payload[:collection] == "system.indexes" + name == :insert && payload[:collection] == 'system.indexes' end def self.drop_indexes?(name, payload) - name == :deleteIndexes && payload[:selector] && payload[:selector][:index] == "*" + name == :deleteIndexes && payload[:selector] && payload[:selector][:index] == '*' end def self.drop_index?(name, payload) @@ -166,7 +166,7 @@ def self.collection_name_from_index(payload) end def self.collection_name_from_group_selector(payload) - payload[:selector]["group"]["ns"] + payload[:selector]['group']['ns'] end def self.collection_name_from_rename_selector(payload) diff --git a/lib/new_relic/agent/datastores/redis.rb b/lib/new_relic/agent/datastores/redis.rb index 031a66535e..ea98baedbe 100644 --- a/lib/new_relic/agent/datastores/redis.rb +++ b/lib/new_relic/agent/datastores/redis.rb @@ -6,7 +6,7 @@ module NewRelic module Agent module Datastores module Redis - BINARY_DATA_PLACEHOLDER = "" + BINARY_DATA_PLACEHOLDER = '' MAXIMUM_COMMAND_LENGTH = 1000 MAXIMUM_ARGUMENT_LENGTH = 64 @@ -25,7 +25,7 @@ module Redis def self.format_command(command_with_args) if Agent.config[:'transaction_tracer.record_redis_arguments'] - result = String.new('') + result = +'' append_command_with_args(result, command_with_args) @@ -36,7 +36,7 @@ def self.format_command(command_with_args) end def self.format_pipeline_commands(commands_with_args) - result = String.new('') + result = +'' commands_with_args.each do |command| if result.length >= MAXIMUM_COMMAND_LENGTH @@ -83,7 +83,7 @@ def self.append_command_with_no_args(result, command_with_args) end def self.is_supported_version? - Gem::Version.new(::Redis::VERSION) >= Gem::Version.new("3.0.0") + Gem::Version.new(::Redis::VERSION) >= Gem::Version.new('3.0.0') end def self.ellipsize(result, string) @@ -106,8 +106,8 @@ def self.ellipsize(result, string) end def self.safe_from_third_party_gem? - if NewRelic::LanguageSupport.bundled_gem?("newrelic-redis") - ::NewRelic::Agent.logger.info("Not installing New Relic supported Redis instrumentation because the third party newrelic-redis gem is present") + if NewRelic::LanguageSupport.bundled_gem?('newrelic-redis') + ::NewRelic::Agent.logger.info('Not installing New Relic supported Redis instrumentation because the third party newrelic-redis gem is present') false else true diff --git a/lib/new_relic/agent/distributed_tracing.rb b/lib/new_relic/agent/distributed_tracing.rb index 601dc58a80..9a48023a21 100644 --- a/lib/new_relic/agent/distributed_tracing.rb +++ b/lib/new_relic/agent/distributed_tracing.rb @@ -45,11 +45,11 @@ def insert_distributed_trace_headers(headers = {}) record_api_supportability_metric(:insert_distributed_trace_headers) unless Agent.config[:'distributed_tracing.enabled'] - NewRelic::Agent.logger.warn("Not configured to insert distributed trace headers") + NewRelic::Agent.logger.warn('Not configured to insert distributed trace headers') return nil end - return unless valid_api_argument_class?(headers, "headers", Hash) + return unless valid_api_argument_class?(headers, 'headers', Hash) return unless transaction = Transaction.tl_current @@ -99,12 +99,12 @@ def accept_distributed_trace_headers(headers, transport_type = NewRelic::HTTP) record_api_supportability_metric(:accept_distributed_trace_headers) unless Agent.config[:'distributed_tracing.enabled'] - NewRelic::Agent.logger.warn("Not configured to accept distributed trace headers") + NewRelic::Agent.logger.warn('Not configured to accept distributed trace headers') return nil end - return unless valid_api_argument_class?(headers, "headers", Hash) - return unless valid_api_argument_class?(transport_type, "transport_type", String) + return unless valid_api_argument_class?(headers, 'headers', Hash) + return unless valid_api_argument_class?(transport_type, 'transport_type', String) return unless transaction = Transaction.tl_current diff --git a/lib/new_relic/agent/distributed_tracing/cross_app_tracing.rb b/lib/new_relic/agent/distributed_tracing/cross_app_tracing.rb index 456098818d..aa85ba83a4 100644 --- a/lib/new_relic/agent/distributed_tracing/cross_app_tracing.rb +++ b/lib/new_relic/agent/distributed_tracing/cross_app_tracing.rb @@ -1,4 +1,3 @@ -# -*- ruby -*- # This file is distributed under New Relic's license terms. # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true @@ -28,7 +27,7 @@ def is_cross_app_caller? end def is_cross_app_callee? - cross_app_payload != nil + !cross_app_payload.nil? end def is_cross_app? @@ -36,7 +35,7 @@ def is_cross_app? end def cat_trip_id - cross_app_payload && cross_app_payload.referring_trip_id || transaction.guid + cross_app_payload&.referring_trip_id || transaction.guid end def cross_app_monitor @@ -74,7 +73,7 @@ def add_message_cat_headers(headers) end def record_cross_app_metrics - if (id = cross_app_payload && cross_app_payload.id) + if (id = cross_app_payload&.id) app_time_in_seconds = [ Process.clock_gettime(Process::CLOCK_REALTIME) - transaction.start_time, 0.0 @@ -104,11 +103,11 @@ def record_cat_path_hash(hash) end def cat_referring_path_hash - cross_app_payload && cross_app_payload.referring_path_hash + cross_app_payload&.referring_path_hash end def append_cat_info(payload) - if (referring_guid = cross_app_payload && cross_app_payload.referring_guid) + if (referring_guid = cross_app_payload&.referring_guid) payload[:referring_transaction_guid] = referring_guid end @@ -150,7 +149,7 @@ def valid_cross_process_id? if Agent.config[:cross_process_id] && Agent.config[:cross_process_id].length > 0 true else - NewRelic::Agent.logger.debug("No cross_process_id configured") + NewRelic::Agent.logger.debug('No cross_process_id configured') false end end @@ -159,7 +158,7 @@ def valid_encoding_key? if Agent.config[:encoding_key] && Agent.config[:encoding_key].length > 0 true else - NewRelic::Agent.logger.debug("No encoding_key set") + NewRelic::Agent.logger.debug('No encoding_key set') false end end diff --git a/lib/new_relic/agent/distributed_tracing/distributed_trace_attributes.rb b/lib/new_relic/agent/distributed_tracing/distributed_trace_attributes.rb index 8f6c0acfcf..592ffa6c30 100644 --- a/lib/new_relic/agent/distributed_tracing/distributed_trace_attributes.rb +++ b/lib/new_relic/agent/distributed_tracing/distributed_trace_attributes.rb @@ -9,16 +9,16 @@ module DistributedTraceAttributes # Intrinsic Keys INTRINSIC_KEYS = [ - PARENT_TYPE_KEY = "parent.type", - PARENT_APP_KEY = "parent.app", - PARENT_ACCOUNT_ID_KEY = "parent.account", - PARENT_TRANSPORT_TYPE_KEY = "parent.transportType", - PARENT_TRANSPORT_DURATION_KEY = "parent.transportDuration", - GUID_KEY = "guid", - TRACE_ID_KEY = "traceId", - PARENT_TRANSACTION_ID_KEY = "parentId", - PARENT_SPAN_ID_KEY = "parentSpanId", - SAMPLED_KEY = "sampled" + PARENT_TYPE_KEY = 'parent.type', + PARENT_APP_KEY = 'parent.app', + PARENT_ACCOUNT_ID_KEY = 'parent.account', + PARENT_TRANSPORT_TYPE_KEY = 'parent.transportType', + PARENT_TRANSPORT_DURATION_KEY = 'parent.transportDuration', + GUID_KEY = 'guid', + TRACE_ID_KEY = 'traceId', + PARENT_TRANSACTION_ID_KEY = 'parentId', + PARENT_SPAN_ID_KEY = 'parentSpanId', + SAMPLED_KEY = 'sampled' ].freeze # This method extracts intrinsics from the transaction_payload and diff --git a/lib/new_relic/agent/distributed_tracing/distributed_trace_metrics.rb b/lib/new_relic/agent/distributed_tracing/distributed_trace_metrics.rb index f93b6219dd..39c7f8ac90 100644 --- a/lib/new_relic/agent/distributed_tracing/distributed_trace_metrics.rb +++ b/lib/new_relic/agent/distributed_tracing/distributed_trace_metrics.rb @@ -7,11 +7,11 @@ module Agent module DistributedTraceMetrics extend self - ALL_SUFFIX = "all" - ALL_WEB_SUFFIX = "allWeb" - ALL_OTHER_SUFFIX = "allOther" + ALL_SUFFIX = 'all' + ALL_WEB_SUFFIX = 'allWeb' + ALL_OTHER_SUFFIX = 'allOther' - UNKNOWN_CALLER_PREFIX = "%s/Unknown/Unknown/Unknown/%s" + UNKNOWN_CALLER_PREFIX = '%s/Unknown/Unknown/Unknown/%s' def transaction_type_suffix if Transaction.recording_web_transaction? @@ -45,14 +45,14 @@ def prefix_for_metric(name, transaction, payload) end def record_caller_by_duration_metrics(transaction, payload) - prefix = prefix_for_metric("DurationByCaller", transaction, payload) + prefix = prefix_for_metric('DurationByCaller', transaction, payload) record_unscoped_metric(transaction, prefix, transaction.duration) end def record_transport_duration_metrics(transaction, payload) return unless payload - prefix = prefix_for_metric("TransportDuration", transaction, payload) + prefix = prefix_for_metric('TransportDuration', transaction, payload) duration = transaction.calculate_transport_duration(payload) record_unscoped_metric(transaction, prefix, duration) end @@ -60,7 +60,7 @@ def record_transport_duration_metrics(transaction, payload) def record_errors_by_caller_metrics(transaction, payload) return unless transaction.exceptions.size > 0 - prefix = prefix_for_metric("ErrorsByCaller", transaction, payload) + prefix = prefix_for_metric('ErrorsByCaller', transaction, payload) record_unscoped_metric(transaction, prefix, 1) end diff --git a/lib/new_relic/agent/distributed_tracing/distributed_trace_payload.rb b/lib/new_relic/agent/distributed_tracing/distributed_trace_payload.rb index 40397279d3..f4f932b0fc 100644 --- a/lib/new_relic/agent/distributed_tracing/distributed_trace_payload.rb +++ b/lib/new_relic/agent/distributed_tracing/distributed_trace_payload.rb @@ -17,7 +17,7 @@ class DistributedTracePayload extend Coerce VERSION = [0, 1].freeze - PARENT_TYPE = "App" + PARENT_TYPE = 'App' # Key names for serialization VERSION_KEY = 'v' diff --git a/lib/new_relic/agent/distributed_tracing/distributed_trace_transport_type.rb b/lib/new_relic/agent/distributed_tracing/distributed_trace_transport_type.rb index f52cfc6f97..8e929fff65 100644 --- a/lib/new_relic/agent/distributed_tracing/distributed_trace_transport_type.rb +++ b/lib/new_relic/agent/distributed_tracing/distributed_trace_transport_type.rb @@ -11,12 +11,12 @@ module DistributedTraceTransportType NewRelic::UNKNOWN, NewRelic::HTTP, NewRelic::HTTPS, - "Kafka", - "JMS", - "IronMQ", - "AMQP", - "Queue", - "Other" + 'Kafka', + 'JMS', + 'IronMQ', + 'AMQP', + 'Queue', + 'Other' ].freeze URL_SCHEMES = { diff --git a/lib/new_relic/agent/distributed_tracing/trace_context.rb b/lib/new_relic/agent/distributed_tracing/trace_context.rb index c1f29d10ab..d8d3fe9491 100644 --- a/lib/new_relic/agent/distributed_tracing/trace_context.rb +++ b/lib/new_relic/agent/distributed_tracing/trace_context.rb @@ -29,14 +29,14 @@ class TraceContext TP_UNDEFINED_FIELDS = "(?<#{UNDEFINED_FIELDS_KEY}>-[a-zA-Z\\d-]*)" TRACE_PARENT_REGEX = /\A#{TP_VERSION}-#{TP_TRACE_ID}-#{TP_PARENT_ID}-#{TP_TRACE_FLAGS}#{TP_UNDEFINED_FIELDS}?\z/ - TRACE_PARENT_FORMAT_STRING = "%02x-%s-%s-%02x" + TRACE_PARENT_FORMAT_STRING = '%02x-%s-%s-%02x' MAX_TRACE_STATE_SIZE = 512 # bytes MAX_TRACE_STATE_ENTRY_SIZE = 128 # bytes - SUPPORTABILITY_TRACE_PARENT_PARSE_EXCEPTION = "Supportability/TraceContext/TraceParent/Parse/Exception" - SUPPORTABILITY_TRACE_STATE_PARSE_EXCEPTION = "Supportability/TraceContext/TraceState/Parse/Exception" - SUPPORTABILITY_TRACE_STATE_INVALID_NR_ENTRY = "Supportability/TraceContext/TraceState/InvalidNrEntry" + SUPPORTABILITY_TRACE_PARENT_PARSE_EXCEPTION = 'Supportability/TraceContext/TraceParent/Parse/Exception' + SUPPORTABILITY_TRACE_STATE_PARSE_EXCEPTION = 'Supportability/TraceContext/TraceState/Parse/Exception' + SUPPORTABILITY_TRACE_STATE_INVALID_NR_ENTRY = 'Supportability/TraceContext/TraceState/InvalidNrEntry' class << self def insert(format: NewRelic::FORMAT_NON_RACK, @@ -78,7 +78,7 @@ def parse(format: NewRelic::FORMAT_NON_RACK, end def create_trace_state_entry(entry_key, payload) - "#{entry_key}=#{payload}".dup + +"#{entry_key}=#{payload}" end private @@ -138,7 +138,7 @@ def extract_tracestate(format, carrier, trace_state_entry_key) payload = nil trace_state_size = 0 - trace_state_vendors = String.new + trace_state_vendors = +'' trace_state = header.split(COMMA).map(&:strip) trace_state.reject! do |entry| if entry == NewRelic::EMPTY_STR @@ -223,7 +223,7 @@ def join_trace_state(trace_state_entry_size) max_size = MAX_TRACE_STATE_SIZE - trace_state_entry_size return @trace_state_entries.join(COMMA).prepend(COMMA) if @trace_state_size < max_size - joined_trace_state = ''.dup + joined_trace_state = +'' used_size = 0 diff --git a/lib/new_relic/agent/distributed_tracing/trace_context_payload.rb b/lib/new_relic/agent/distributed_tracing/trace_context_payload.rb index e32b8a127d..7fe29c011e 100644 --- a/lib/new_relic/agent/distributed_tracing/trace_context_payload.rb +++ b/lib/new_relic/agent/distributed_tracing/trace_context_payload.rb @@ -9,8 +9,8 @@ module Agent class TraceContextPayload VERSION = 0 PARENT_TYPE = 0 - DELIMITER = "-".freeze - SUPPORTABILITY_PARSE_EXCEPTION = "Supportability/TraceContext/Parse/Exception".freeze + DELIMITER = '-'.freeze + SUPPORTABILITY_PARSE_EXCEPTION = 'Supportability/TraceContext/Parse/Exception'.freeze TRUE_CHAR = '1'.freeze FALSE_CHAR = '0'.freeze @@ -64,7 +64,7 @@ def now_ms def handle_invalid_payload(error: nil, message: nil) NewRelic::Agent.increment_metric(SUPPORTABILITY_PARSE_EXCEPTION) if error - NewRelic::Agent.logger.warn("Error parsing trace context payload", error) + NewRelic::Agent.logger.warn('Error parsing trace context payload', error) elsif message NewRelic::Agent.logger.warn("Error parsing trace context payload: #{message}") end @@ -118,7 +118,7 @@ def to_s result << DELIMITER << (id || NewRelic::EMPTY_STR) result << DELIMITER << (transaction_id || NewRelic::EMPTY_STR) result << DELIMITER << (sampled ? TRUE_CHAR : FALSE_CHAR) - result << DELIMITER << sprintf("%.6f", priority) + result << DELIMITER << sprintf('%.6f', priority) result << DELIMITER << timestamp.to_s # required result end diff --git a/lib/new_relic/agent/error_collector.rb b/lib/new_relic/agent/error_collector.rb index 3edb728afb..b04a26213a 100644 --- a/lib/new_relic/agent/error_collector.rb +++ b/lib/new_relic/agent/error_collector.rb @@ -156,13 +156,13 @@ def blamed_metric_name(txn, options) end def aggregated_metric_names(txn) - metric_names = ["Errors/all"] + metric_names = ['Errors/all'] return metric_names unless txn if txn.recording_web_transaction? - metric_names << "Errors/allWeb" + metric_names << 'Errors/allWeb' else - metric_names << "Errors/allOther" + metric_names << 'Errors/allOther' end metric_names @@ -227,7 +227,7 @@ def notice_segment_error(segment, exception, options = {}) def notice_error(exception, options = {}, span_id = nil) state = ::NewRelic::Agent::Tracer.state transaction = state.current_transaction - status_code = transaction ? transaction.http_response_code : nil + status_code = transaction&.http_response_code return if skip_notice_error?(exception, status_code) @@ -242,8 +242,8 @@ def notice_error(exception, options = {}, span_id = nil) noticed_error = create_noticed_error(exception, options) error_trace_aggregator.add_to_error_queue(noticed_error) transaction = state.current_transaction - payload = transaction ? transaction.payload : nil - span_id ||= transaction && transaction.current_segment ? transaction.current_segment.guid : nil + payload = transaction&.payload + span_id ||= transaction&.current_segment ? transaction.current_segment.guid : nil error_event_aggregator.record(noticed_error, payload, span_id) exception rescue => e @@ -277,7 +277,7 @@ def create_noticed_error(exception, options) noticed_error.line_number = sense_method(exception, :line_number) noticed_error.stack_trace = truncate_trace(extract_stack_trace(exception)) - noticed_error.expected = !!options.delete(:expected) || expected?(exception) + noticed_error.expected = !options.delete(:expected).nil? || expected?(exception) noticed_error.attributes_from_notice_error = options.delete(:custom_params) || {} @@ -285,6 +285,8 @@ def create_noticed_error(exception, options) # get treated as custom attributes, so merge them into that hash. noticed_error.attributes_from_notice_error.merge!(options) + update_error_group_name(noticed_error, exception, options) + noticed_error end @@ -306,6 +308,32 @@ def drop_buffered_data @error_event_aggregator.reset! nil end + + private + + def update_error_group_name(noticed_error, exception, options) + return unless error_group_callback + + callback_hash = build_customer_callback_hash(noticed_error, exception, options) + result = error_group_callback.call(callback_hash) + noticed_error.error_group = result + rescue StandardError => e + NewRelic::Agent.logger.error("Failed to obtain error group from customer callback: #{e.class} - #{e.message}") + end + + def build_customer_callback_hash(noticed_error, exception, options) + {error: exception, + customAttributes: noticed_error.custom_attributes, + 'request.uri': noticed_error.request_uri, + 'http.statusCode': noticed_error.agent_attributes[:'http.statusCode'], + 'http.method': noticed_error.intrinsic_attributes[:'http.method'], + 'error.expected': noticed_error.expected, + options: options} + end + + def error_group_callback + NewRelic::Agent.error_group_callback + end end end end diff --git a/lib/new_relic/agent/error_filter.rb b/lib/new_relic/agent/error_filter.rb index dd2c49da9a..47b9eb6802 100644 --- a/lib/new_relic/agent/error_filter.rb +++ b/lib/new_relic/agent/error_filter.rb @@ -80,7 +80,7 @@ def ignore(*args) @ignore_messages.update(errors) log_filter(:ignore_messages, errors) when String - if errors =~ /^[\d\,\-]+$/ + if /^[\d\,\-]+$/.match?(errors) @ignore_status_codes |= parse_status_codes(errors) log_filter(:ignore_status_codes, errors) else @@ -104,7 +104,7 @@ def expect(*args) @expected_messages.update(errors) log_filter(:expected_messages, errors) when String - if errors =~ /^[\d\,\-]+$/ + if /^[\d\,\-]+$/.match?(errors) @expected_status_codes |= parse_status_codes(errors) log_filter(:expected_status_codes, errors) else diff --git a/lib/new_relic/agent/error_trace_aggregator.rb b/lib/new_relic/agent/error_trace_aggregator.rb index f0ce048780..8b7f0be28d 100644 --- a/lib/new_relic/agent/error_trace_aggregator.rb +++ b/lib/new_relic/agent/error_trace_aggregator.rb @@ -81,13 +81,14 @@ def notice_agent_error(exception) # Already seen this class once? Bail! return if @errors.any? { |err| err.exception_class_name == exception.class.name } - trace = exception.backtrace || caller.dup - noticed_error = NewRelic::NoticedError.new("NewRelic/AgentError", exception) - noticed_error.stack_trace = trace + noticed_error = NewRelic::Agent.instance.error_collector.create_noticed_error(exception, + {metric: 'NewRelic/AgentError'}) + noticed_error.stack_trace = caller.dup unless exception.backtrace + @errors << noticed_error end rescue => e - NewRelic::Agent.logger.info("Unable to capture internal agent error due to an exception:", e) + NewRelic::Agent.logger.info('Unable to capture internal agent error due to an exception:', e) end def register_config_callbacks diff --git a/lib/new_relic/agent/event_loop.rb b/lib/new_relic/agent/event_loop.rb index c1a4887575..6e2b81901a 100644 --- a/lib/new_relic/agent/event_loop.rb +++ b/lib/new_relic/agent/event_loop.rb @@ -96,7 +96,7 @@ def stop end def run - ::NewRelic::Agent.logger.debug("Running event loop") + ::NewRelic::Agent.logger.debug('Running event loop') while !stopped? run_once end @@ -161,7 +161,7 @@ def dispatch_event(event, args) end def reschedule_timer_for_event(e) - @timers[e].reschedule if @timers[e] + @timers[e]&.reschedule end def on(event, &blk) @@ -187,7 +187,7 @@ def wakeup begin @self_pipe_wr.write_nonblock('.') rescue Errno::EAGAIN - ::NewRelic::Agent.logger.debug("Failed to wakeup event loop") + ::NewRelic::Agent.logger.debug('Failed to wakeup event loop') end end end diff --git a/lib/new_relic/agent/external.rb b/lib/new_relic/agent/external.rb index 48cb174d9b..6154f6d019 100644 --- a/lib/new_relic/agent/external.rb +++ b/lib/new_relic/agent/external.rb @@ -97,7 +97,7 @@ def get_response_metadata obfuscator.obfuscate(::JSON.dump(rmd)) end rescue => e - NewRelic::Agent.logger.error("error during get_response_metadata", e) + NewRelic::Agent.logger.error('error during get_response_metadata', e) end private diff --git a/lib/new_relic/agent/harvester.rb b/lib/new_relic/agent/harvester.rb index fa8d7aae4b..d5a6bb9da9 100644 --- a/lib/new_relic/agent/harvester.rb +++ b/lib/new_relic/agent/harvester.rb @@ -14,9 +14,7 @@ def initialize(events, after_forker = NewRelic::Agent) @starting_pid = nil @after_forker = after_forker - if events - events.subscribe(:start_transaction, &method(:on_transaction)) - end + events&.subscribe(:start_transaction, &method(:on_transaction)) end def on_transaction(*_) diff --git a/lib/new_relic/agent/heap.rb b/lib/new_relic/agent/heap.rb index 343636e60f..c00bfff969 100644 --- a/lib/new_relic/agent/heap.rb +++ b/lib/new_relic/agent/heap.rb @@ -26,7 +26,8 @@ class Heap def initialize(items = nil, &priority_fn) @items = [] @priority_fn = priority_fn || ->(x) { x } - items.each { |item| push(item) } if items + # the following line needs else branch coverage + items.each { |item| push(item) } if items # rubocop:disable Style/SafeNavigation end def [](index) diff --git a/lib/new_relic/agent/hostname.rb b/lib/new_relic/agent/hostname.rb index bcb93ecfd2..2430d247fe 100644 --- a/lib/new_relic/agent/hostname.rb +++ b/lib/new_relic/agent/hostname.rb @@ -39,7 +39,7 @@ def self.get_fqdn def self.heroku_dyno_name_prefix(dyno_name) get_dyno_prefixes.find do |dyno_prefix| - dyno_name.start_with?(dyno_prefix + ".") + dyno_name.start_with?(dyno_prefix + '.') end end diff --git a/lib/new_relic/agent/http_clients/abstract.rb b/lib/new_relic/agent/http_clients/abstract.rb index edbeddb490..21f59b1583 100644 --- a/lib/new_relic/agent/http_clients/abstract.rb +++ b/lib/new_relic/agent/http_clients/abstract.rb @@ -5,8 +5,8 @@ module NewRelic module Agent module HTTPClients - MUST_IMPLEMENT_ERROR = "Subclasses of %s must implement a :%s method" - WHINY_NIL_ERROR = "%s cannot initialize with a nil wrapped_response object." + MUST_IMPLEMENT_ERROR = 'Subclasses of %s must implement a :%s method' + WHINY_NIL_ERROR = '%s cannot initialize with a nil wrapped_response object.' # This class provides a public interface for wrapping HTTP requests. This # may be used to create wrappers that are compatible with New Relic's @@ -14,28 +14,16 @@ module HTTPClients # # @api public class AbstractRequest - def [] - raise NotImplementedError, MUST_IMPLEMENT_ERROR % [self.class, __method__] - end - - def []= - raise NotImplementedError, MUST_IMPLEMENT_ERROR % [self.class, __method__] - end - - def type - raise NotImplementedError, MUST_IMPLEMENT_ERROR % [self.class, __method__] - end - - def host_from_header - raise NotImplementedError, MUST_IMPLEMENT_ERROR % [self.class, __method__] + %i[[] []= type host_from_header host method headers uri].each do |name| + define_method(name) do + not_implemented(name) + end end - def host - raise NotImplementedError, MUST_IMPLEMENT_ERROR % [self.class, __method__] - end + private - def method - raise NotImplementedError, MUST_IMPLEMENT_ERROR % [self.class, __method__] + def not_implemented(method_name) + raise NotImplementedError, MUST_IMPLEMENT_ERROR % [self.class, method_name] end end diff --git a/lib/new_relic/agent/http_clients/curb_wrappers.rb b/lib/new_relic/agent/http_clients/curb_wrappers.rb index c5e829c0a3..6e0fca5b00 100644 --- a/lib/new_relic/agent/http_clients/curb_wrappers.rb +++ b/lib/new_relic/agent/http_clients/curb_wrappers.rb @@ -33,16 +33,20 @@ def method end def [](key) - @curlobj.headers[key] + headers[key] end def []=(key, value) - @curlobj.headers[key] = value + headers[key] = value end def uri @uri ||= URIUtil.parse_and_normalize_url(@curlobj.url) end + + def headers + @curlobj.headers + end end class CurbResponse < AbstractResponse @@ -62,7 +66,7 @@ def to_hash def append_header_data(data) key, value = data.split(/:\s*/, 2) @headers[key.downcase] = value - @wrapped_response._nr_header_str ||= String.new + @wrapped_response._nr_header_str ||= +'' @wrapped_response._nr_header_str << data end diff --git a/lib/new_relic/agent/http_clients/excon_wrappers.rb b/lib/new_relic/agent/http_clients/excon_wrappers.rb index ce65a5fcb3..13e3b51630 100644 --- a/lib/new_relic/agent/http_clients/excon_wrappers.rb +++ b/lib/new_relic/agent/http_clients/excon_wrappers.rb @@ -46,7 +46,7 @@ def get_status_code class ExconHTTPRequest < AbstractRequest attr_reader :method - EXCON = "Excon" + EXCON = 'Excon' LHOST = 'host' UHOST = 'Host' COLON = ':' @@ -65,7 +65,6 @@ def type end def host_from_header - headers = @datum[:headers] if hostname = (headers[LHOST] || headers[UHOST]) hostname.split(COLON).first end @@ -76,18 +75,21 @@ def host end def [](key) - @datum[:headers][key] + headers[key] end def []=(key, value) - @datum[:headers] ||= {} - @datum[:headers][key] = value + headers[key] = value end def uri url = "#{@scheme}://#{host}:#{@port}#{@path}" URIUtil.parse_and_normalize_url(url) end + + def headers + @datum[:headers] + end end end end diff --git a/lib/new_relic/agent/http_clients/http_rb_wrappers.rb b/lib/new_relic/agent/http_clients/http_rb_wrappers.rb index 5ad7d6fa43..b0b041523d 100644 --- a/lib/new_relic/agent/http_clients/http_rb_wrappers.rb +++ b/lib/new_relic/agent/http_clients/http_rb_wrappers.rb @@ -56,6 +56,10 @@ def [](key) def []=(key, value) @wrapped_request.headers[key] = value end + + def headers + @wrapped_request.headers.to_hash + end end end end diff --git a/lib/new_relic/agent/http_clients/httpclient_wrappers.rb b/lib/new_relic/agent/http_clients/httpclient_wrappers.rb index 578df4758c..88578b83d2 100644 --- a/lib/new_relic/agent/http_clients/httpclient_wrappers.rb +++ b/lib/new_relic/agent/http_clients/httpclient_wrappers.rb @@ -25,7 +25,7 @@ def to_hash class HTTPClientRequest < AbstractRequest attr_reader :request - HTTP_CLIENT = "HTTPClient".freeze + HTTP_CLIENT = 'HTTPClient'.freeze LHOST = 'host'.freeze UHOST = 'Host'.freeze COLON = ':'.freeze @@ -57,12 +57,16 @@ def uri end def [](key) - request.headers[key] + headers[key] end def []=(key, value) request.http_header[key] = value end + + def headers + request.headers + end end end end diff --git a/lib/new_relic/agent/http_clients/net_http_wrappers.rb b/lib/new_relic/agent/http_clients/net_http_wrappers.rb index ecf46ebbcd..fa4bb5c122 100644 --- a/lib/new_relic/agent/http_clients/net_http_wrappers.rb +++ b/lib/new_relic/agent/http_clients/net_http_wrappers.rb @@ -61,7 +61,7 @@ def uri ::NewRelic::Agent::HTTPClients::URIUtil.parse_and_normalize_url(@request.path) else connection_address = @connection.address - if connection_address =~ Resolv::IPv6::Regex + if Resolv::IPv6::Regex.match?(connection_address) connection_address = "[#{connection_address}]" end @@ -71,6 +71,10 @@ def uri ) end end + + def headers + @request.instance_variable_get(:@header) + end end end end diff --git a/lib/new_relic/agent/http_clients/typhoeus_wrappers.rb b/lib/new_relic/agent/http_clients/typhoeus_wrappers.rb index c98b06fd20..767edada17 100644 --- a/lib/new_relic/agent/http_clients/typhoeus_wrappers.rb +++ b/lib/new_relic/agent/http_clients/typhoeus_wrappers.rb @@ -42,7 +42,7 @@ def initialize(request) end end - TYPHOEUS = "Typhoeus".freeze + TYPHOEUS = 'Typhoeus'.freeze def type TYPHOEUS @@ -66,14 +66,17 @@ def method end def [](key) - return nil unless @request.options && @request.options[:headers] + return nil unless @request.options && headers - @request.options[:headers][key] + headers[key] end def []=(key, value) - @request.options[:headers] ||= {} - @request.options[:headers][key] = value + headers[key] = value + end + + def headers + @request.options[:headers] || {} end def uri diff --git a/lib/new_relic/agent/http_clients/uri_util.rb b/lib/new_relic/agent/http_clients/uri_util.rb index bea870d9f4..f2f188bada 100644 --- a/lib/new_relic/agent/http_clients/uri_util.rb +++ b/lib/new_relic/agent/http_clients/uri_util.rb @@ -36,11 +36,11 @@ def self.parse_and_normalize_url(url) uri = ::URI.parse(url) end end - uri.host.downcase! unless uri.host.nil? + uri.host&.downcase! uri end - QUESTION_MARK = "?" + QUESTION_MARK = '?' def self.strip_query_string(fragment) if fragment.include?(QUESTION_MARK) diff --git a/lib/new_relic/agent/instrumentation/action_controller_other_subscriber.rb b/lib/new_relic/agent/instrumentation/action_controller_other_subscriber.rb index 5b9ea78216..b6b0680ed3 100644 --- a/lib/new_relic/agent/instrumentation/action_controller_other_subscriber.rb +++ b/lib/new_relic/agent/instrumentation/action_controller_other_subscriber.rb @@ -27,11 +27,14 @@ def metric_name(name, payload) end def controller_name_for_metric(payload) + return unless payload # redirect_to - return payload[:request].controller_class.controller_path if payload[:request] && payload[:request].controller_class + return payload[:request].controller_class.controller_path if payload[:request].respond_to?(:controller_class) && payload[:request].controller_class&.respond_to?(:controller_path) # unpermitted_parameters - ::NewRelic::LanguageSupport.constantize(payload[:context][:controller]).controller_path if payload[:context] && payload[:context][:controller] + if payload[:context]&.[](:controller) && constantized_class = ::NewRelic::LanguageSupport.constantize(payload[:context][:controller]) + constantized_class.respond_to?(:controller_path) ? constantized_class.controller_path : nil + end end end end diff --git a/lib/new_relic/agent/instrumentation/action_controller_subscriber.rb b/lib/new_relic/agent/instrumentation/action_controller_subscriber.rb index d8c58cb7d9..62c567e274 100644 --- a/lib/new_relic/agent/instrumentation/action_controller_subscriber.rb +++ b/lib/new_relic/agent/instrumentation/action_controller_subscriber.rb @@ -19,7 +19,7 @@ def start(name, id, payload) # THREAD_LOCAL_ACCESS else # if this transaction is ignored, make sure child # transaction are also ignored - state.current_transaction.ignore! if state.current_transaction + state.current_transaction&.ignore! NewRelic::Agent.instance.push_trace_execution_flag(false) end rescue => e @@ -90,7 +90,8 @@ def should_ignore(payload, controller_class) end def queue_start(request) - if request && request.respond_to?(:env) + # the following line needs else branch coverage + if request && request.respond_to?(:env) # rubocop:disable Style/SafeNavigation QueueTime.parse_frontend_timestamp(request.env, Process.clock_gettime(Process::CLOCK_REALTIME)) end end diff --git a/lib/new_relic/agent/instrumentation/action_view_subscriber.rb b/lib/new_relic/agent/instrumentation/action_view_subscriber.rb index 6aa9747fdc..adcd969a00 100644 --- a/lib/new_relic/agent/instrumentation/action_view_subscriber.rb +++ b/lib/new_relic/agent/instrumentation/action_view_subscriber.rb @@ -75,7 +75,7 @@ def metric_path(name, identifier) # so do not mistake rendering a collection for rendering a file. if identifier.nil? && name != RENDER_COLLECTION_EVENT_NAME 'file' - elsif identifier =~ /template$/ + elsif /template$/.match?(identifier) identifier elsif identifier && (parts = identifier.split('/')).size > 1 parts[-2..-1].join('/') @@ -99,11 +99,11 @@ def initialize(name, identifier) end def finish - @finishable.finish if @finishable + @finishable&.finish end def notice_error(error) - @finishable.notice_error(error) if @finishable + @finishable&.notice_error(error) end end end diff --git a/lib/new_relic/agent/instrumentation/active_job.rb b/lib/new_relic/agent/instrumentation/active_job.rb index b44fc5d330..650649ac63 100644 --- a/lib/new_relic/agent/instrumentation/active_job.rb +++ b/lib/new_relic/agent/instrumentation/active_job.rb @@ -57,7 +57,7 @@ def self.perform(job, block) # Don't nest transactions if we're already in a web transaction. # Probably inline processing the job if that happens, so just trace. - if txn && txn.recording_web_transaction? + if txn&.recording_web_transaction? run_in_trace(job, block, :Consume) elsif txn && !txn.recording_web_transaction? ::NewRelic::Agent::Transaction.set_default_transaction_name( diff --git a/lib/new_relic/agent/instrumentation/active_record.rb b/lib/new_relic/agent/instrumentation/active_record.rb index e7f666421d..8cdcdcbcd2 100644 --- a/lib/new_relic/agent/instrumentation/active_record.rb +++ b/lib/new_relic/agent/instrumentation/active_record.rb @@ -13,7 +13,8 @@ module ActiveRecord ::ActiveRecord::Base.send("#{statement.config[:adapter]}_connection", statement.config) end - if connection && connection.respond_to?(:execute) + # the following line needs else branch coverage + if connection && connection.respond_to?(:execute) # rubocop:disable Style/SafeNavigation return connection.execute("EXPLAIN #{statement.sql}") end end @@ -43,7 +44,7 @@ def self.included(instrumented_class) end end - if RUBY_VERSION < "2.7.0" + if RUBY_VERSION < '2.7.0' def log_with_newrelic_instrumentation(*args, &block) state = NewRelic::Agent::Tracer.state diff --git a/lib/new_relic/agent/instrumentation/active_record_helper.rb b/lib/new_relic/agent/instrumentation/active_record_helper.rb index 0798db5eb0..4fb323004d 100644 --- a/lib/new_relic/agent/instrumentation/active_record_helper.rb +++ b/lib/new_relic/agent/instrumentation/active_record_helper.rb @@ -49,7 +49,7 @@ def update_all(*args, &blk) alias_method(:delete_all_without_newrelic, :delete_all) - if RUBY_VERSION < "2.7.0" + if RUBY_VERSION < '2.7.0' def delete_all(*args, &blk) ::NewRelic::Agent.with_database_metric_name(self.name, nil, ACTIVE_RECORD) do delete_all_without_newrelic(*args, &blk) @@ -92,9 +92,9 @@ def pluck(*args, &blk) end end - ACTIVE_RECORD = "ActiveRecord".freeze - OTHER = "other".freeze - MAKARA_SUFFIX = "_makara".freeze + ACTIVE_RECORD = 'ActiveRecord'.freeze + OTHER = 'other'.freeze + MAKARA_SUFFIX = '_makara'.freeze # convert vendor (makara, etc.) wrapper names to their bare names # ex: postgresql_makara -> postgresql @@ -102,7 +102,7 @@ def bare_adapter_name(adapter_name) # TODO: OLD RUBIES - RUBY_VERSION < 2.5 # With Ruby 2.5+ we could use #delete_suffix instead of #chomp for a # potential speed boost - return adapter_name.chomp(MAKARA_SUFFIX) if adapter_name && adapter_name.end_with?(MAKARA_SUFFIX) + return adapter_name.chomp(MAKARA_SUFFIX) if adapter_name&.end_with?(MAKARA_SUFFIX) adapter_name end @@ -118,7 +118,7 @@ def product_operation_collection_for(name, sql, adapter_name) SPACE = ' '.freeze def split_name(name) - if name && name.respond_to?(:split) + if name&.respond_to?(:split) name.split(SPACE) else NewRelic::EMPTY_ARRAY @@ -163,47 +163,50 @@ def map_operation(raw_operation) end PRODUCT_NAMES = { - "mysql" => "MySQL", - "mysql2" => "MySQL", + 'mysql' => 'MySQL', + 'mysql2' => 'MySQL', - "postgresql" => "Postgres", + 'postgresql' => 'Postgres', - "sqlite3" => "SQLite", + 'sqlite3' => 'SQLite', # https://rubygems.org/gems/activerecord-jdbcpostgresql-adapter - "jdbcmysql" => "MySQL", + 'jdbcmysql' => 'MySQL', # https://rubygems.org/gems/activerecord-jdbcpostgresql-adapter - "jdbcpostgresql" => "Postgres", + 'jdbcpostgresql' => 'Postgres', # https://rubygems.org/gems/activerecord-postgis-adapter - "postgis" => "Postgres", + 'postgis' => 'Postgres', # https://rubygems.org/gems/activerecord-jdbcsqlite3-adapter - "jdbcsqlite3" => "SQLite", + 'jdbcsqlite3' => 'SQLite', # https://rubygems.org/gems/activerecord-jdbcderby-adapter - "derby" => "Derby", - "jdbcderby" => "Derby", + 'derby' => 'Derby', + 'jdbcderby' => 'Derby', # https://rubygems.org/gems/activerecord-jdbc-adapter - "jdbc" => "JDBC", + 'jdbc' => 'JDBC', # https://rubygems.org/gems/activerecord-jdbcmssql-adapter - "jdbcmssql" => "MSSQL", - "mssql" => "MSSQL", + 'jdbcmssql' => 'MSSQL', + 'mssql' => 'MSSQL', # https://rubygems.org/gems/activerecord-sqlserver-adapter - "sqlserver" => "MSSQL", + 'sqlserver' => 'MSSQL', # https://rubygems.org/gems/activerecord-odbc-adapter - "odbc" => "ODBC", + 'odbc' => 'ODBC', # https://rubygems.org/gems/activerecord-oracle_enhanced-adapter - "oracle_enhanced" => "Oracle" + 'oracle_enhanced' => 'Oracle', + + # https://rubygems.org/gems/activerecord-amazon-timestream-adapter + 'amazon_timestream' => 'Timestream' }.freeze - ACTIVE_RECORD_DEFAULT_PRODUCT_NAME = "ActiveRecord".freeze + ACTIVE_RECORD_DEFAULT_PRODUCT_NAME = 'ActiveRecord'.freeze def map_product(adapter_name) PRODUCT_NAMES.fetch(adapter_name, ACTIVE_RECORD_DEFAULT_PRODUCT_NAME) @@ -213,24 +216,24 @@ module InstanceIdentification extend self PRODUCT_SYMBOLS = { - "mysql" => :mysql, - "mysql2" => :mysql, - "jdbcmysql" => :mysql, + 'mysql' => :mysql, + 'mysql2' => :mysql, + 'jdbcmysql' => :mysql, - "postgresql" => :postgres, - "jdbcpostgresql" => :postgres, - "postgis" => :postgres + 'postgresql' => :postgres, + 'jdbcpostgresql' => :postgres, + 'postgis' => :postgres }.freeze DATASTORE_DEFAULT_PORTS = { - :mysql => "3306", - :postgres => "5432" + :mysql => '3306', + :postgres => '5432' }.freeze - DEFAULT = "default".freeze - UNKNOWN = "unknown".freeze - SLASH = "/".freeze - LOCALHOST = "localhost".freeze + DEFAULT = 'default'.freeze + UNKNOWN = 'unknown'.freeze + SLASH = '/'.freeze + LOCALHOST = 'localhost'.freeze def adapter_from_config(config) bare_name = NewRelic::Agent::Instrumentation::ActiveRecordHelper.bare_adapter_name(config[:adapter]) diff --git a/lib/new_relic/agent/instrumentation/active_record_notifications.rb b/lib/new_relic/agent/instrumentation/active_record_notifications.rb index 1e33ba89f8..84296d147f 100644 --- a/lib/new_relic/agent/instrumentation/active_record_notifications.rb +++ b/lib/new_relic/agent/instrumentation/active_record_notifications.rb @@ -16,7 +16,7 @@ module ActiveRecordNotifications module BaseExtensions4x # https://github.com/rails/rails/blob/4-1-stable/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb#L371 - def log(sql, name = "SQL", binds = [], statement_name = nil) + def log(sql, name = 'SQL', binds = [], statement_name = nil) @instrumenter.instrument( SQL_ACTIVE_RECORD, :sql => sql, @@ -38,7 +38,7 @@ def log(sql, name = "SQL", binds = [], statement_name = nil) module BaseExtensions50 # https://github.com/rails/rails/blob/5-0-stable/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb#L582 - def log(sql, name = "SQL", binds = [], type_casted_binds = [], statement_name = nil) + def log(sql, name = 'SQL', binds = [], type_casted_binds = [], statement_name = nil) @instrumenter.instrument( SQL_ACTIVE_RECORD, sql: sql, @@ -56,7 +56,7 @@ def log(sql, name = "SQL", binds = [], type_casted_binds = [], statement_name = module BaseExtensions51 # https://github.com/rails/rails/blob/5-1-stable/activerecord/lib/active_record/connection_adapters/abstract_adapter.rb#L603 - def log(sql, name = "SQL", binds = [], type_casted_binds = [], statement_name = nil) # :doc: + def log(sql, name = 'SQL', binds = [], type_casted_binds = [], statement_name = nil) # :doc: @instrumenter.instrument( SQL_ACTIVE_RECORD, sql: sql, diff --git a/lib/new_relic/agent/instrumentation/active_record_prepend.rb b/lib/new_relic/agent/instrumentation/active_record_prepend.rb index 7fb126cb2f..376bb1adb2 100644 --- a/lib/new_relic/agent/instrumentation/active_record_prepend.rb +++ b/lib/new_relic/agent/instrumentation/active_record_prepend.rb @@ -11,7 +11,7 @@ module ActiveRecordPrepend ACTIVE_RECORD = 'ActiveRecord'.freeze module BaseExtensions - if RUBY_VERSION < "2.7.0" + if RUBY_VERSION < '2.7.0' def save(*args, &blk) ::NewRelic::Agent.with_database_metric_name(self.class.name, nil, ACTIVE_RECORD) do super @@ -46,7 +46,7 @@ module BaseExtensions516 # Starting in v5.1.6, this call no longer happens. We'll # have to set the database metrics explicitly now. # - if RUBY_VERSION < "2.7.0" + if RUBY_VERSION < '2.7.0' def touch(*args, **kwargs, &blk) ::NewRelic::Agent.with_database_metric_name(self.class.name, nil, ACTIVE_RECORD) do super diff --git a/lib/new_relic/agent/instrumentation/active_record_subscriber.rb b/lib/new_relic/agent/instrumentation/active_record_subscriber.rb index dd54ef50b7..92c11e3e9f 100644 --- a/lib/new_relic/agent/instrumentation/active_record_subscriber.rb +++ b/lib/new_relic/agent/instrumentation/active_record_subscriber.rb @@ -33,7 +33,7 @@ def define_cachedp_method # defensive. return if defined?(cached?) - if defined?(::ActiveRecord) && ::ActiveRecord::VERSION::STRING >= "5.1.0" + if defined?(::ActiveRecord) && ::ActiveRecord::VERSION::STRING >= '5.1.0' def cached?(payload) payload.fetch(:cached, false) end @@ -74,7 +74,8 @@ def get_explain_plan(statement) ::ActiveRecord::Base.send("#{statement.config[:adapter]}_connection", statement.config) end - if connection && connection.respond_to?(:exec_query) + # the following line needs else branch coverage + if connection && connection.respond_to?(:exec_query) # rubocop:disable Style/SafeNavigation return connection.exec_query("EXPLAIN #{statement.sql}", "Explain #{statement.name}", statement.binds) diff --git a/lib/new_relic/agent/instrumentation/bunny/instrumentation.rb b/lib/new_relic/agent/instrumentation/bunny/instrumentation.rb index 3e52829dbe..ea3a5af4ba 100644 --- a/lib/new_relic/agent/instrumentation/bunny/instrumentation.rb +++ b/lib/new_relic/agent/instrumentation/bunny/instrumentation.rb @@ -46,7 +46,7 @@ def publish_with_tracing(payload, opts = {}) exchange_type: type ) rescue => e - NewRelic::Agent.logger.error("Error starting message broker segment in Bunny::Exchange#publish", e) + NewRelic::Agent.logger.error('Error starting message broker segment in Bunny::Exchange#publish', e) yield else NewRelic::Agent::Tracer.capture_segment_error(segment) do @@ -90,7 +90,7 @@ def pop_with_tracing start_time: t0 ) rescue => e - NewRelic::Agent.logger.error("Error starting message broker segment in Bunny::Queue#pop", e) + NewRelic::Agent.logger.error('Error starting message broker segment in Bunny::Queue#pop', e) else if bunny_error segment.notice_error(bunny_error) @@ -113,7 +113,7 @@ def purge_with_tracing destination_name: name ) rescue => e - NewRelic::Agent.logger.error("Error starting message broker segment in Bunny::Queue#purge", e) + NewRelic::Agent.logger.error('Error starting message broker segment in Bunny::Queue#purge', e) yield else NewRelic::Agent::Tracer.capture_segment_error(segment) do diff --git a/lib/new_relic/agent/instrumentation/controller_instrumentation.rb b/lib/new_relic/agent/instrumentation/controller_instrumentation.rb index fad7eca092..90e77bdc5d 100644 --- a/lib/new_relic/agent/instrumentation/controller_instrumentation.rb +++ b/lib/new_relic/agent/instrumentation/controller_instrumentation.rb @@ -236,7 +236,8 @@ def self.name_for(txn, traced_obj, category, options = {}) end def self.prefix_for_category(txn, category = nil) - category ||= (txn && txn.category) + # the following line needs else branch coverage + category ||= (txn && txn.category) # rubocop:disable Style/SafeNavigation case category when :controller then ::NewRelic::Agent::Transaction::CONTROLLER_PREFIX when :web then ::NewRelic::Agent::Transaction::CONTROLLER_PREFIX @@ -360,7 +361,7 @@ def perform_action_with_newrelic_trace(*args, &block) # THREAD_LOCAL_ACCESS skip_tracing = do_not_trace? || !state.is_execution_traced? if skip_tracing - state.current_transaction.ignore! if state.current_transaction + state.current_transaction&.ignore! NewRelic::Agent.disable_all_tracing { return yield } end @@ -386,7 +387,8 @@ def perform_action_with_newrelic_trace(*args, &block) # THREAD_LOCAL_ACCESS raise end ensure - finishable.finish if finishable + # the following line needs else branch coverage + finishable.finish if finishable # rubocop:disable Style/SafeNavigation end end diff --git a/lib/new_relic/agent/instrumentation/curb.rb b/lib/new_relic/agent/instrumentation/curb.rb index 8fdc276ad3..2aa2699e67 100644 --- a/lib/new_relic/agent/instrumentation/curb.rb +++ b/lib/new_relic/agent/instrumentation/curb.rb @@ -8,7 +8,7 @@ DependencyDetection.defer do named :curb - CURB_MIN_VERSION = Gem::Version.new("0.8.1") + CURB_MIN_VERSION = Gem::Version.new('0.8.1') depends_on do defined?(Curl) && defined?(Curl::CURB_VERSION) && diff --git a/lib/new_relic/agent/instrumentation/curb/chain.rb b/lib/new_relic/agent/instrumentation/curb/chain.rb index 2c6dc80244..dc85bda3a3 100644 --- a/lib/new_relic/agent/instrumentation/curb/chain.rb +++ b/lib/new_relic/agent/instrumentation/curb/chain.rb @@ -7,7 +7,7 @@ module NewRelic::Agent::Instrumentation module Curb module Chain - def self.instrument! + def self.instrument! # rubocop:disable Metrics/AbcSize Curl::Easy.class_eval do include NewRelic::Agent::Instrumentation::Curb::Easy diff --git a/lib/new_relic/agent/instrumentation/curb/instrumentation.rb b/lib/new_relic/agent/instrumentation/curb/instrumentation.rb index 3ad3fb5b98..43d9aca30a 100644 --- a/lib/new_relic/agent/instrumentation/curb/instrumentation.rb +++ b/lib/new_relic/agent/instrumentation/curb/instrumentation.rb @@ -81,7 +81,7 @@ def add_with_tracing(curl) def perform_with_tracing return yield if first_request_is_serial? - trace_execution_scoped("External/Multiple/Curb::Multi/perform") do + trace_execution_scoped('External/Multiple/Curb::Multi/perform') do yield end end @@ -107,7 +107,7 @@ def hook_pending_request(request) request._nr_instrumented = true end rescue => err - NewRelic::Agent.logger.error("Untrapped exception", err) + NewRelic::Agent.logger.error('Untrapped exception', err) end # Create request and response adapter objects for the specified +request+ @@ -141,12 +141,12 @@ def install_completion_callback(request, wrapped_response, segment) request._nr_original_on_complete = original_callback request.on_complete do |finished_request| begin - segment.process_response_headers(wrapped_response) if segment + segment&.process_response_headers(wrapped_response) ensure ::NewRelic::Agent::Transaction::Segment.finish(segment) # Make sure the existing completion callback is run, and restore the # on_complete callback to how it was before. - original_callback.call(finished_request) if original_callback + original_callback&.call(finished_request) remove_instrumentation_callbacks(request) end end @@ -173,7 +173,7 @@ def install_failure_callback(request, _wrapped_response, segment) segment.notice_error(noticeable_error) end ensure - original_callback.call(failed_request, error) if original_callback + original_callback&.call(failed_request, error) remove_failure_callback(failed_request) end end diff --git a/lib/new_relic/agent/instrumentation/custom_events_subscriber.rb b/lib/new_relic/agent/instrumentation/custom_events_subscriber.rb index b94b5a5efc..b45fd86a5a 100644 --- a/lib/new_relic/agent/instrumentation/custom_events_subscriber.rb +++ b/lib/new_relic/agent/instrumentation/custom_events_subscriber.rb @@ -23,7 +23,8 @@ def finish(name, id, payload) # THREAD_LOCAL_ACCESS NewRelic::Agent.notice_error(payload[:exception_object]) if payload.key?(:exception_object) finishable = pop_segment(id) - finishable.finish if finishable + # the following line needs else branch coverage + finishable.finish if finishable # rubocop:disable Style/SafeNavigation rescue => e log_notification_error(e, name, 'finish') end diff --git a/lib/new_relic/agent/instrumentation/delayed_job/instrumentation.rb b/lib/new_relic/agent/instrumentation/delayed_job/instrumentation.rb index f6e5acea23..8661938384 100644 --- a/lib/new_relic/agent/instrumentation/delayed_job/instrumentation.rb +++ b/lib/new_relic/agent/instrumentation/delayed_job/instrumentation.rb @@ -22,7 +22,7 @@ def initialize_with_tracing install_newrelic_job_tracer NewRelic::Control.instance.init_plugin(:dispatcher => :delayed_job) else - NewRelic::Agent.logger.warn("Did not find a Delayed::Job class responding to invoke_job, aborting DJ instrumentation") + NewRelic::Agent.logger.warn('Did not find a Delayed::Job class responding to invoke_job, aborting DJ instrumentation') end end end diff --git a/lib/new_relic/agent/instrumentation/delayed_job_instrumentation.rb b/lib/new_relic/agent/instrumentation/delayed_job_instrumentation.rb index 59ad6ea76f..f725821be5 100644 --- a/lib/new_relic/agent/instrumentation/delayed_job_instrumentation.rb +++ b/lib/new_relic/agent/instrumentation/delayed_job_instrumentation.rb @@ -109,6 +109,7 @@ def method_name(payload_object) end def delayed_job_version - Gem.loaded_specs['delayed_job'].version if Gem.loaded_specs['delayed_job'] + # the following line needs else branch coverage + Gem.loaded_specs['delayed_job'].version if Gem.loaded_specs['delayed_job'] # rubocop:disable Style/SafeNavigation end end diff --git a/lib/new_relic/agent/instrumentation/elasticsearch.rb b/lib/new_relic/agent/instrumentation/elasticsearch.rb index 423a9b9f9b..8493d21e9d 100644 --- a/lib/new_relic/agent/instrumentation/elasticsearch.rb +++ b/lib/new_relic/agent/instrumentation/elasticsearch.rb @@ -16,7 +16,7 @@ executes do NewRelic::Agent.logger.info('Installing Elasticsearch instrumentation') - to_instrument = if Gem::Version.create(Elasticsearch::VERSION) < Gem::Version.create("8.0.0") + to_instrument = if Gem::Version.create(Elasticsearch::VERSION) < Gem::Version.create('8.0.0') Elasticsearch::Transport::Client else Elastic::Transport::Client diff --git a/lib/new_relic/agent/instrumentation/elasticsearch/chain.rb b/lib/new_relic/agent/instrumentation/elasticsearch/chain.rb index b88ce20e5d..00242a8ca4 100644 --- a/lib/new_relic/agent/instrumentation/elasticsearch/chain.rb +++ b/lib/new_relic/agent/instrumentation/elasticsearch/chain.rb @@ -6,7 +6,7 @@ module NewRelic::Agent::Instrumentation module Elasticsearch def self.instrument! to_instrument = if ::Gem::Version.create(::Elasticsearch::VERSION) < - ::Gem::Version.create("8.0.0") + ::Gem::Version.create('8.0.0') ::Elasticsearch::Transport::Client else ::Elastic::Transport::Client diff --git a/lib/new_relic/agent/instrumentation/elasticsearch/instrumentation.rb b/lib/new_relic/agent/instrumentation/elasticsearch/instrumentation.rb index 7bca0c1d45..2b92ddbc1d 100644 --- a/lib/new_relic/agent/instrumentation/elasticsearch/instrumentation.rb +++ b/lib/new_relic/agent/instrumentation/elasticsearch/instrumentation.rb @@ -37,7 +37,7 @@ def nr_operation end return nil unless operation_index - caller_locations[operation_index].to_s.split('`')[-1].gsub(/\W/, "") + caller_locations[operation_index].to_s.split('`')[-1].gsub(/\W/, '') end def nr_reported_query(query) @@ -52,10 +52,10 @@ def nr_cluster_name return if nr_hosts.empty? NewRelic::Agent.disable_all_tracing do - @nr_cluster_name ||= perform_request('GET', '_cluster/health').body["cluster_name"] + @nr_cluster_name ||= perform_request('GET', '_cluster/health').body['cluster_name'] end rescue StandardError => e - NewRelic::Agent.logger.error("Failed to get cluster name for elasticsearch", e) + NewRelic::Agent.logger.error('Failed to get cluster name for elasticsearch', e) nil end diff --git a/lib/new_relic/agent/instrumentation/excon.rb b/lib/new_relic/agent/instrumentation/excon.rb index 9203027c48..949920b767 100644 --- a/lib/new_relic/agent/instrumentation/excon.rb +++ b/lib/new_relic/agent/instrumentation/excon.rb @@ -18,7 +18,7 @@ # but alas, it does not yet. # TODO: MAJOR VERSION - update min version to 0.56.0 - EXCON_MIN_VERSION = Gem::Version.new("0.19.0") + EXCON_MIN_VERSION = Gem::Version.new('0.19.0') depends_on do defined?(Excon) && defined?(Excon::VERSION) @@ -46,7 +46,7 @@ deprecation_msg ) - NewRelic::Agent.record_metric("Supportability/Deprecated/Excon", 1) + NewRelic::Agent.record_metric('Supportability/Deprecated/Excon', 1) end def install_excon_instrumentation(excon_version) @@ -64,7 +64,7 @@ def install_middleware_excon_instrumentation if defaults[:middlewares] defaults[:middlewares] << Excon::Middleware::NewRelicCrossAppTracing else - NewRelic::Agent.logger.warn("Did not find :middlewares key in Excon.defaults, skipping Excon instrumentation") + NewRelic::Agent.logger.warn('Did not find :middlewares key in Excon.defaults, skipping Excon instrumentation') end end end diff --git a/lib/new_relic/agent/instrumentation/excon/middleware.rb b/lib/new_relic/agent/instrumentation/excon/middleware.rb index a4cb48e042..82bb4397ba 100644 --- a/lib/new_relic/agent/instrumentation/excon/middleware.rb +++ b/lib/new_relic/agent/instrumentation/excon/middleware.rb @@ -46,7 +46,8 @@ def error_call(datum) end def finish_trace(datum) # THREAD_LOCAL_ACCESS - segment = datum[:connection] && datum[:connection].instance_variable_get(TRACE_DATA_IVAR) + # The following line needs else branch coverage + segment = datum[:connection] && datum[:connection].instance_variable_get(TRACE_DATA_IVAR) # rubocop:disable Style/SafeNavigation if segment begin segment.notice_error(datum[:error]) if datum[:error] diff --git a/lib/new_relic/agent/instrumentation/grape.rb b/lib/new_relic/agent/instrumentation/grape.rb index e5624390ba..26198326d0 100644 --- a/lib/new_relic/agent/instrumentation/grape.rb +++ b/lib/new_relic/agent/instrumentation/grape.rb @@ -19,14 +19,14 @@ depends_on do begin - if defined?(Bundler) && Bundler.rubygems.all_specs.map(&:name).include?("newrelic-grape") - NewRelic::Agent.logger.info("Not installing New Relic supported Grape instrumentation because the third party newrelic-grape gem is present") + if defined?(Bundler) && Bundler.rubygems.all_specs.map(&:name).include?('newrelic-grape') + NewRelic::Agent.logger.info('Not installing New Relic supported Grape instrumentation because the third party newrelic-grape gem is present') false else true end rescue => e - NewRelic::Agent.logger.info("Could not determine if third party newrelic-grape gem is installed", e) + NewRelic::Agent.logger.info('Could not determine if third party newrelic-grape gem is installed', e) true end end diff --git a/lib/new_relic/agent/instrumentation/grape/instrumentation.rb b/lib/new_relic/agent/instrumentation/grape/instrumentation.rb index 8f900c1002..1e7ad1eb08 100644 --- a/lib/new_relic/agent/instrumentation/grape/instrumentation.rb +++ b/lib/new_relic/agent/instrumentation/grape/instrumentation.rb @@ -23,12 +23,12 @@ def capture_transaction(env, context) api_class = (context.class.respond_to?(:base) && context.class.base) || context.class handle_transaction(endpoint, api_class.name, version) rescue => e - ::NewRelic::Agent.logger.warn("Error in Grape instrumentation", e) + ::NewRelic::Agent.logger.warn('Error in Grape instrumentation', e) end end def prepare! - if defined?(::Grape::VERSION) && Gem::Version.new(::Grape::VERSION) >= Gem::Version.new("0.16.0") + if defined?(::Grape::VERSION) && Gem::Version.new(::Grape::VERSION) >= Gem::Version.new('0.16.0') send(:remove_method, :name_for_transaction_deprecated) else send(:remove_method, :name_for_transaction) @@ -40,7 +40,7 @@ def prepare! API_VERSION = 'api.version'.freeze FORMAT_REGEX = /\(\/?\.[\:\w]*\)/.freeze # either :format (< 0.12.0) or .ext (>= 0.12.0) VERSION_REGEX = /:version(\/|$)/.freeze - MIN_VERSION = Gem::Version.new("0.2.0") + MIN_VERSION = Gem::Version.new('0.2.0') PIPE_STRING = '|'.freeze def handle_transaction(endpoint, class_name, version) @@ -91,7 +91,7 @@ def capture_params(endpoint) txn = ::NewRelic::Agent::Transaction.tl_current env = endpoint.request.env params = ::NewRelic::Agent::ParameterFiltering::apply_filters(env, endpoint.params) - params.delete("route_info") + params.delete('route_info') txn.filtered_params = params txn.merge_request_parameters(params) end diff --git a/lib/new_relic/agent/instrumentation/grpc/client/instrumentation.rb b/lib/new_relic/agent/instrumentation/grpc/client/instrumentation.rb index 1a9be33b1c..c3cbc5a8c6 100644 --- a/lib/new_relic/agent/instrumentation/grpc/client/instrumentation.rb +++ b/lib/new_relic/agent/instrumentation/grpc/client/instrumentation.rb @@ -18,7 +18,8 @@ def issue_request_with_tracing(grpc_type, method, requests, marshal, unmarshal, segment = request_segment(method) request_wrapper = NewRelic::Agent::Instrumentation::GRPC::Client::RequestWrapper.new(@host) - segment.add_request_headers(request_wrapper) + # do not insert CAT headers for gRPC requests https://github.com/newrelic/newrelic-ruby-agent/issues/1730 + segment.add_request_headers(request_wrapper) unless CrossAppTracing.cross_app_enabled? metadata.merge!(request_wrapper.instance_variable_get(:@newrelic_metadata)) grpc_message = nil grpc_status = 0 diff --git a/lib/new_relic/agent/instrumentation/grpc/server/instrumentation.rb b/lib/new_relic/agent/instrumentation/grpc/server/instrumentation.rb index 383b214173..d8f2a3193a 100644 --- a/lib/new_relic/agent/instrumentation/grpc/server/instrumentation.rb +++ b/lib/new_relic/agent/instrumentation/grpc/server/instrumentation.rb @@ -37,7 +37,7 @@ def handle_with_tracing(streamer_type, active_call, mth, _inter_ctx) raise end ensure - txn.finish if txn + txn&.finish end def add_http2_port_with_tracing(*args) @@ -55,12 +55,12 @@ def run_with_tracing(*args) def add_attributes(txn, metadata, streamer_type) grpc_params(metadata, streamer_type).each do |attr, value| txn.add_agent_attribute(attr, value, DESTINATIONS) - txn.current_segment.add_agent_attribute(attr, value) if txn.current_segment + txn.current_segment&.add_agent_attribute(attr, value) end end def metadata_for_call(active_call) - return NewRelic::EMPTY_HASH unless active_call && active_call.metadata + return NewRelic::EMPTY_HASH unless active_call&.metadata active_call.metadata end diff --git a/lib/new_relic/agent/instrumentation/httprb.rb b/lib/new_relic/agent/instrumentation/httprb.rb index 6aabe5efe2..822a2b0469 100644 --- a/lib/new_relic/agent/instrumentation/httprb.rb +++ b/lib/new_relic/agent/instrumentation/httprb.rb @@ -14,7 +14,7 @@ end executes do - NewRelic::Agent.logger.info("Installing http.rb Wrappers") + NewRelic::Agent.logger.info('Installing http.rb Wrappers') require 'new_relic/agent/distributed_tracing/cross_app_tracing' require 'new_relic/agent/http_clients/http_rb_wrappers' end diff --git a/lib/new_relic/agent/instrumentation/ignore_actions.rb b/lib/new_relic/agent/instrumentation/ignore_actions.rb index d776cfffbf..7c467cd4d5 100644 --- a/lib/new_relic/agent/instrumentation/ignore_actions.rb +++ b/lib/new_relic/agent/instrumentation/ignore_actions.rb @@ -21,7 +21,7 @@ def self.is_filtered?(key, klass, action_name) only_actions.include?(action_name) || (!except_actions.empty? && !except_actions.include?(action_name)) else - !!ignore_actions + !ignore_actions.nil? end return true if should_filter diff --git a/lib/new_relic/agent/instrumentation/logger.rb b/lib/new_relic/agent/instrumentation/logger.rb index f565bb7ccc..c351fa6f59 100644 --- a/lib/new_relic/agent/instrumentation/logger.rb +++ b/lib/new_relic/agent/instrumentation/logger.rb @@ -15,7 +15,7 @@ end executes do - NewRelic::Agent.logger.info("Installing Logger instrumentation") + NewRelic::Agent.logger.info('Installing Logger instrumentation') if use_prepend? prepend_instrument Logger, NewRelic::Agent::Instrumentation::Logger::Prepend diff --git a/lib/new_relic/agent/instrumentation/memcache.rb b/lib/new_relic/agent/instrumentation/memcache.rb index f61a719aa9..d761eec3ff 100644 --- a/lib/new_relic/agent/instrumentation/memcache.rb +++ b/lib/new_relic/agent/instrumentation/memcache.rb @@ -23,9 +23,9 @@ executes do if use_prepend? prepend_module = NewRelic::Agent::Instrumentation::Memcache::Prepend.client_prepender(MemCache) - prepend_instrument MemCache, prepend_module, "MemcacheClient" + prepend_instrument MemCache, prepend_module, 'MemcacheClient' else - chain_instrument_target MemCache, NewRelic::Agent::Instrumentation::Memcache::Chain, "MemcacheClient" + chain_instrument_target MemCache, NewRelic::Agent::Instrumentation::Memcache::Chain, 'MemcacheClient' end end end @@ -38,9 +38,9 @@ executes do if use_prepend? prepend_module = NewRelic::Agent::Instrumentation::Memcache::Prepend.client_prepender(Memcached) - prepend_instrument Memcached, prepend_module, "Memcached" + prepend_instrument Memcached, prepend_module, 'Memcached' else - chain_instrument_target Memcached, NewRelic::Agent::Instrumentation::Memcache::Chain, "Memcached" + chain_instrument_target Memcached, NewRelic::Agent::Instrumentation::Memcache::Chain, 'Memcached' end end end @@ -55,7 +55,7 @@ if use_prepend? prepend_module = NewRelic::Agent::Instrumentation::Memcache::Prepend prepend_module.dalli_prependers do |client_class, instrumenting_module| - prepend_instrument client_class, instrumenting_module, "MemcachedDalli" + prepend_instrument client_class, instrumenting_module, 'MemcachedDalli' end else chain_instrument NewRelic::Agent::Instrumentation::Memcache::Dalli @@ -78,7 +78,7 @@ if use_prepend? prepend_module = NewRelic::Agent::Instrumentation::Memcache::Prepend prepend_module.dalli_cas_prependers do |client_class, instrumenting_module| - prepend_instrument client_class, instrumenting_module, "MemcachedDalliCAS" + prepend_instrument client_class, instrumenting_module, 'MemcachedDalliCAS' end else chain_instrument NewRelic::Agent::Instrumentation::Memcache::DalliCAS diff --git a/lib/new_relic/agent/instrumentation/memcache/instrumentation.rb b/lib/new_relic/agent/instrumentation/memcache/instrumentation.rb index 2107b40bc4..02d7d3643b 100644 --- a/lib/new_relic/agent/instrumentation/memcache/instrumentation.rb +++ b/lib/new_relic/agent/instrumentation/memcache/instrumentation.rb @@ -8,8 +8,8 @@ module Tracer SLASH = '/' UNKNOWN = 'unknown' LOCALHOST = 'localhost' - MULTIGET_METRIC_NAME = "get_multi_request" - MEMCACHED = "Memcached" + MULTIGET_METRIC_NAME = 'get_multi_request' + MEMCACHED = 'Memcached' def with_newrelic_tracing(operation, *args) segment = NewRelic::Agent::Tracer.start_datastore_segment( \ diff --git a/lib/new_relic/agent/instrumentation/middleware_proxy.rb b/lib/new_relic/agent/instrumentation/middleware_proxy.rb index 0317a46b2b..8986c2fbde 100644 --- a/lib/new_relic/agent/instrumentation/middleware_proxy.rb +++ b/lib/new_relic/agent/instrumentation/middleware_proxy.rb @@ -15,8 +15,8 @@ module Instrumentation class MiddlewareProxy include MiddlewareTracing - ANONYMOUS_CLASS = "AnonymousClass".freeze - OBJECT_CLASS_NAME = "Object".freeze + ANONYMOUS_CLASS = 'AnonymousClass'.freeze + OBJECT_CLASS_NAME = 'Object'.freeze # This class is used to wrap classes that are passed to # Rack::Builder#use without synchronously instantiating those classes. @@ -92,7 +92,7 @@ def determine_class_name clazz = class_for_target name = clazz.name - name = clazz.superclass.name if name.nil? || name == "" + name = clazz.superclass.name if name.nil? || name == '' name = ANONYMOUS_CLASS if name.nil? || name == OBJECT_CLASS_NAME name end diff --git a/lib/new_relic/agent/instrumentation/middleware_tracing.rb b/lib/new_relic/agent/instrumentation/middleware_tracing.rb index c1773f099a..9215227d54 100644 --- a/lib/new_relic/agent/instrumentation/middleware_tracing.rb +++ b/lib/new_relic/agent/instrumentation/middleware_tracing.rb @@ -108,7 +108,7 @@ def call(env) NewRelic::Agent.notice_error(e) raise e ensure - finishable.finish if finishable + finishable&.finish end end diff --git a/lib/new_relic/agent/instrumentation/mongodb_command_subscriber.rb b/lib/new_relic/agent/instrumentation/mongodb_command_subscriber.rb index 776dd0d293..4b75289181 100644 --- a/lib/new_relic/agent/instrumentation/mongodb_command_subscriber.rb +++ b/lib/new_relic/agent/instrumentation/mongodb_command_subscriber.rb @@ -9,7 +9,7 @@ module Agent module Instrumentation class MongodbCommandSubscriber MONGODB = 'MongoDB'.freeze - COLLECTION = "collection".freeze + COLLECTION = 'collection'.freeze def started(event) begin @@ -43,7 +43,7 @@ def completed(event) if error_key = error_key_present?(event) # taking the last error as there can potentially be many attributes = event.reply[error_key][-1] - segment.notice_error(Mongo::Error.new("%s (%s)" % [attributes["errmsg"], attributes["code"]])) + segment.notice_error(Mongo::Error.new('%s (%s)' % [attributes['errmsg'], attributes['code']])) # failing commands return a CommandFailed event with an error message # in the form of "% (%s)" for the message and code @@ -106,8 +106,8 @@ def generate_statement(event) ) end - UNKNOWN = "unknown".freeze - LOCALHOST = "localhost".freeze + UNKNOWN = 'unknown'.freeze + LOCALHOST = 'localhost'.freeze def host_from_address(address) if unix_domain_socket?(address.host) @@ -131,7 +131,7 @@ def port_path_or_id_from_address(address) UNKNOWN end - SLASH = "/".freeze + SLASH = '/'.freeze def unix_domain_socket?(host) host.start_with?(SLASH) diff --git a/lib/new_relic/agent/instrumentation/net_http.rb b/lib/new_relic/agent/instrumentation/net_http.rb index 53e2f83fa8..42d179ac1b 100644 --- a/lib/new_relic/agent/instrumentation/net_http.rb +++ b/lib/new_relic/agent/instrumentation/net_http.rb @@ -31,7 +31,7 @@ end conflicts_with_prepend do - source_location_for(Net::HTTP, "request") =~ /airbrake|profiler/i + source_location_for(Net::HTTP, 'request') =~ /airbrake|profiler/i end executes do diff --git a/lib/new_relic/agent/instrumentation/notifications_subscriber.rb b/lib/new_relic/agent/instrumentation/notifications_subscriber.rb index 3db9809621..1bff8b2732 100644 --- a/lib/new_relic/agent/instrumentation/notifications_subscriber.rb +++ b/lib/new_relic/agent/instrumentation/notifications_subscriber.rb @@ -118,7 +118,7 @@ def define_exception_method return if defined?(exception_object) return unless defined?(::ActiveSupport::VERSION) - if ::ActiveSupport::VERSION::STRING < "5.0.0" + if ::ActiveSupport::VERSION::STRING < '5.0.0' # Earlier versions of Rails did not add the exception itself to the # payload accessible via :exception_object, so we create a stand-in # error object from the given class name and message. diff --git a/lib/new_relic/agent/instrumentation/padrino/instrumentation.rb b/lib/new_relic/agent/instrumentation/padrino/instrumentation.rb index d22ff3f79c..3f1fd096e9 100644 --- a/lib/new_relic/agent/instrumentation/padrino/instrumentation.rb +++ b/lib/new_relic/agent/instrumentation/padrino/instrumentation.rb @@ -6,9 +6,9 @@ module NewRelic::Agent::Instrumentation module Padrino def invoke_route_with_tracing(*args) begin - env["newrelic.last_route"] = args[0].original_path + env['newrelic.last_route'] = args[0].original_path rescue => e - ::NewRelic::Agent.logger.debug("Failed determining last route in Padrino", e) + ::NewRelic::Agent.logger.debug('Failed determining last route in Padrino', e) end begin @@ -19,7 +19,7 @@ def invoke_route_with_tracing(*args) ) end rescue => e - ::NewRelic::Agent.logger.debug("Failed during invoke_route to set transaction name", e) + ::NewRelic::Agent.logger.debug('Failed during invoke_route to set transaction name', e) end yield diff --git a/lib/new_relic/agent/instrumentation/passenger_instrumentation.rb b/lib/new_relic/agent/instrumentation/passenger_instrumentation.rb index c620bc80ac..857c87f096 100644 --- a/lib/new_relic/agent/instrumentation/passenger_instrumentation.rb +++ b/lib/new_relic/agent/instrumentation/passenger_instrumentation.rb @@ -10,10 +10,10 @@ end executes do - NewRelic::Agent.logger.debug("Installing Passenger event hooks.") + NewRelic::Agent.logger.debug('Installing Passenger event hooks.') PhusionPassenger.on_event(:stopping_worker_process) do - NewRelic::Agent.logger.debug("Passenger stopping this process, shutdown the agent.") + NewRelic::Agent.logger.debug('Passenger stopping this process, shutdown the agent.') NewRelic::Agent.instance.shutdown end diff --git a/lib/new_relic/agent/instrumentation/rack/instrumentation.rb b/lib/new_relic/agent/instrumentation/rack/instrumentation.rb index 7458ac6b19..f72bbb176f 100644 --- a/lib/new_relic/agent/instrumentation/rack/instrumentation.rb +++ b/lib/new_relic/agent/instrumentation/rack/instrumentation.rb @@ -16,7 +16,7 @@ class << builder_class def deferred_dependency_check return if self.class._nr_deferred_detection_ran - NewRelic::Agent.logger.info("Doing deferred dependency-detection before Rack startup") + NewRelic::Agent.logger.info('Doing deferred dependency-detection before Rack startup') DependencyDetection.detect! self.class._nr_deferred_detection_ran = true end diff --git a/lib/new_relic/agent/instrumentation/rails3/action_controller.rb b/lib/new_relic/agent/instrumentation/rails3/action_controller.rb index 8e17182f81..4c193cb0f9 100644 --- a/lib/new_relic/agent/instrumentation/rails3/action_controller.rb +++ b/lib/new_relic/agent/instrumentation/rails3/action_controller.rb @@ -37,7 +37,7 @@ module NewRelic extend self def template_metric(identifier, options = {}) if options[:file] - "file" + 'file' elsif identifier.nil? ::NewRelic::Agent::UNKNOWN_METRIC elsif identifier.include?('/') # this is a filepath @@ -112,7 +112,8 @@ class ActionController::Base def render_with_newrelic(context, options) # This is needed for rails 3.2 compatibility @details = extract_details(options) if respond_to?(:extract_details, true) - identifier = determine_template(options) ? determine_template(options).identifier : nil + # this file can't be found in SimpleCov, need to check test coverage + identifier = determine_template(options) ? determine_template(options).identifier : nil # rubocop:disable Style/SafeNavigation scope_name = "View/#{NewRelic::Agent::Instrumentation::Rails3::ActionView::NewRelic.template_metric(identifier, options)}/Rendering" trace_execution_scoped(scope_name) do render_without_newrelic(context, options) diff --git a/lib/new_relic/agent/instrumentation/rails_middleware.rb b/lib/new_relic/agent/instrumentation/rails_middleware.rb index 126704f478..40fe3d280a 100644 --- a/lib/new_relic/agent/instrumentation/rails_middleware.rb +++ b/lib/new_relic/agent/instrumentation/rails_middleware.rb @@ -16,7 +16,7 @@ end executes do - NewRelic::Agent.logger.info("Installing Rails 3+ middleware instrumentation") + NewRelic::Agent.logger.info('Installing Rails 3+ middleware instrumentation') module ActionDispatch class MiddlewareStack class Middleware diff --git a/lib/new_relic/agent/instrumentation/rake.rb b/lib/new_relic/agent/instrumentation/rake.rb index 579ad32661..543b52b50d 100644 --- a/lib/new_relic/agent/instrumentation/rake.rb +++ b/lib/new_relic/agent/instrumentation/rake.rb @@ -12,12 +12,12 @@ configure_with :rake depends_on { defined?(Rake) && defined?(Rake::VERSION) } - depends_on { Gem::Version.new(Rake::VERSION) >= Gem::Version.new("10.0.0") } + depends_on { Gem::Version.new(Rake::VERSION) >= Gem::Version.new('10.0.0') } depends_on { NewRelic::Agent.config[:'rake.tasks'].any? } depends_on { NewRelic::Agent::Instrumentation::Rake.safe_from_third_party_gem? } executes do - NewRelic::Agent.logger.info("Installing Rake instrumentation") + NewRelic::Agent.logger.info('Installing Rake instrumentation') NewRelic::Agent.logger.debug("Instrumenting Rake tasks: #{NewRelic::Agent.config[:'rake.tasks']}") end diff --git a/lib/new_relic/agent/instrumentation/rake/instrumentation.rb b/lib/new_relic/agent/instrumentation/rake/instrumentation.rb index d18477210e..43e5752f5c 100644 --- a/lib/new_relic/agent/instrumentation/rake/instrumentation.rb +++ b/lib/new_relic/agent/instrumentation/rake/instrumentation.rb @@ -16,7 +16,7 @@ def invoke_with_newrelic_tracing(*args) timeout = NewRelic::Agent.config[:'rake.connect_timeout'] NewRelic::Agent.instance.wait_on_connect(timeout) rescue => e - NewRelic::Agent.logger.error("Exception in wait_on_connect", e) + NewRelic::Agent.logger.error('Exception in wait_on_connect', e) return yield end @@ -36,9 +36,9 @@ def should_install? end def safe_from_third_party_gem? - return true unless NewRelic::LanguageSupport.bundled_gem?("newrelic-rake") + return true unless NewRelic::LanguageSupport.bundled_gem?('newrelic-rake') - ::NewRelic::Agent.logger.info("Not installing New Relic supported Rake instrumentation because the third party newrelic-rake gem is present") + ::NewRelic::Agent.logger.info('Not installing New Relic supported Rake instrumentation because the third party newrelic-rake gem is present') false end @@ -72,7 +72,7 @@ def execute(*args, &block) def instrument_invoke_prerequisites_concurrently(task) task.instance_eval do def invoke_prerequisites_concurrently(*_) - NewRelic::Agent::MethodTracer.trace_execution_scoped("Rake/execute/multitask") do + NewRelic::Agent::MethodTracer.trace_execution_scoped('Rake/execute/multitask') do super end end @@ -87,11 +87,11 @@ def before_invoke_transaction(task) instrument_invoke_prerequisites_concurrently(task) end rescue => e - NewRelic::Agent.logger.error("Error during Rake task invoke", e) + NewRelic::Agent.logger.error('Error during Rake task invoke', e) end def record_attributes(args, task) - command_line = task.application.top_level_tasks.join(" ") + command_line = task.application.top_level_tasks.join(' ') NewRelic::Agent::Transaction.merge_untrusted_agent_attributes({:command => command_line}, :'job.rake', NewRelic::Agent::AttributeFilter::DST_NONE) @@ -102,7 +102,7 @@ def record_attributes(args, task) NewRelic::Agent::AttributeFilter::DST_NONE) end rescue => e - NewRelic::Agent.logger.error("Error during Rake task attribute recording.", e) + NewRelic::Agent.logger.error('Error during Rake task attribute recording.', e) end # Expects literal args passed to the task and array of task names diff --git a/lib/new_relic/agent/instrumentation/redis/constants.rb b/lib/new_relic/agent/instrumentation/redis/constants.rb index 9ab31b3c89..d7da5af0a4 100644 --- a/lib/new_relic/agent/instrumentation/redis/constants.rb +++ b/lib/new_relic/agent/instrumentation/redis/constants.rb @@ -12,6 +12,6 @@ class Constants PIPELINE_OPERATION = 'pipeline' HAS_REDIS_CLIENT = defined?(::Redis) && Gem::Version.new(::Redis::VERSION) >= Gem::Version.new('5.0.0') && - !!defined?(::RedisClient) + !defined?(::RedisClient).nil? end end diff --git a/lib/new_relic/agent/instrumentation/redis/instrumentation.rb b/lib/new_relic/agent/instrumentation/redis/instrumentation.rb index 6c9a57283a..60fdf23ace 100644 --- a/lib/new_relic/agent/instrumentation/redis/instrumentation.rb +++ b/lib/new_relic/agent/instrumentation/redis/instrumentation.rb @@ -79,7 +79,8 @@ def _nr_redis_client_config self # redis-client gem v0.11+ (self is a RedisClient::Middlewares) elsif respond_to?(:client) - client && client.config + # The following line needs else branch coverage + client && client.config # rubocop:disable Style/SafeNavigation # redis-client gem <0.11 (self is a RedisClient::Middlewares) elsif defined?(::RedisClient) ::RedisClient.config if ::RedisClient.respond_to?(:config) diff --git a/lib/new_relic/agent/instrumentation/resque/helper.rb b/lib/new_relic/agent/instrumentation/resque/helper.rb index 30438819fb..6af27e7823 100644 --- a/lib/new_relic/agent/instrumentation/resque/helper.rb +++ b/lib/new_relic/agent/instrumentation/resque/helper.rb @@ -10,7 +10,7 @@ module Helper extend self def resque_fork_per_job? - ENV["FORK_PER_JOB"] != 'false' && NewRelic::LanguageSupport.can_fork? + ENV['FORK_PER_JOB'] != 'false' && NewRelic::LanguageSupport.can_fork? end end end diff --git a/lib/new_relic/agent/instrumentation/sequel.rb b/lib/new_relic/agent/instrumentation/sequel.rb index e6396617d7..0177b90ae5 100644 --- a/lib/new_relic/agent/instrumentation/sequel.rb +++ b/lib/new_relic/agent/instrumentation/sequel.rb @@ -28,9 +28,9 @@ def supported_sequel_version? if Sequel::Database.respond_to?(:extension) Sequel::Database.extension(:new_relic_instrumentation) else - NewRelic::Agent.logger.info("Detected Sequel version %s." % [Sequel::VERSION]) - NewRelic::Agent.logger.info("Please see additional documentation: " + - "https://newrelic.com/docs/ruby/sequel-instrumentation") + NewRelic::Agent.logger.info('Detected Sequel version %s.' % [Sequel::VERSION]) + NewRelic::Agent.logger.info('Please see additional documentation: ' + + 'https://newrelic.com/docs/ruby/sequel-instrumentation') end Sequel.synchronize { Sequel::DATABASES.dup }.each do |db| @@ -40,7 +40,7 @@ def supported_sequel_version? Sequel::Model.plugin(:new_relic_instrumentation) if defined?(Sequel::Model) else - NewRelic::Agent.logger.info("Sequel instrumentation requires at least version 3.37.0.") + NewRelic::Agent.logger.info('Sequel instrumentation requires at least version 3.37.0.') end end diff --git a/lib/new_relic/agent/instrumentation/sequel_helper.rb b/lib/new_relic/agent/instrumentation/sequel_helper.rb index 3d52ef7143..8a0345749d 100644 --- a/lib/new_relic/agent/instrumentation/sequel_helper.rb +++ b/lib/new_relic/agent/instrumentation/sequel_helper.rb @@ -9,22 +9,22 @@ module SequelHelper extend self # Fallback if the product cannot be determined - DEFAULT_PRODUCT_NAME = "Sequel".freeze + DEFAULT_PRODUCT_NAME = 'Sequel'.freeze # A Sequel adapter is called an "adapter_scheme" and can be accessed from # the database: # # DB.adapter_scheme PRODUCT_NAMES = { - :ibmdb => "IBMDB2", - :firebird => "Firebird", - :informix => "Informix", - :jdbc => "JDBC", - :mysql => "MySQL", - :mysql2 => "MySQL", - :oracle => "Oracle", - :postgres => "Postgres", - :sqlite => "SQLite" + :ibmdb => 'IBMDB2', + :firebird => 'Firebird', + :informix => 'Informix', + :jdbc => 'JDBC', + :mysql => 'MySQL', + :mysql2 => 'MySQL', + :oracle => 'Oracle', + :postgres => 'Postgres', + :sqlite => 'SQLite' }.freeze def product_name_from_adapter(adapter) diff --git a/lib/new_relic/agent/instrumentation/sidekiq/extensions/delayed_class.rb b/lib/new_relic/agent/instrumentation/sidekiq/extensions/delayed_class.rb index dde9c3e68a..2de46dd2e5 100644 --- a/lib/new_relic/agent/instrumentation/sidekiq/extensions/delayed_class.rb +++ b/lib/new_relic/agent/instrumentation/sidekiq/extensions/delayed_class.rb @@ -23,7 +23,7 @@ def newrelic_trace_args(msg, queue) :category => 'OtherTransaction/SidekiqJob' } rescue => e - NewRelic::Agent.logger.error("Failure during deserializing YAML for Sidekiq::Extensions::DelayedClass", e) + NewRelic::Agent.logger.error('Failure during deserializing YAML for Sidekiq::Extensions::DelayedClass', e) NewRelic::Agent::Instrumentation::Sidekiq::Server.default_trace_args(msg) end end diff --git a/lib/new_relic/agent/instrumentation/sidekiq/server.rb b/lib/new_relic/agent/instrumentation/sidekiq/server.rb index 8c3a0b370c..b15a2cc998 100644 --- a/lib/new_relic/agent/instrumentation/sidekiq/server.rb +++ b/lib/new_relic/agent/instrumentation/sidekiq/server.rb @@ -21,7 +21,7 @@ def call(worker, msg, queue, *_) NewRelic::Agent::Transaction.merge_untrusted_agent_attributes(msg['args'], :'job.sidekiq.args', NewRelic::Agent::AttributeFilter::DST_NONE) - ::NewRelic::Agent::DistributedTracing::accept_distributed_trace_headers(trace_headers, "Other") if ::NewRelic::Agent.config[:'distributed_tracing.enabled'] + ::NewRelic::Agent::DistributedTracing::accept_distributed_trace_headers(trace_headers, 'Other') if ::NewRelic::Agent.config[:'distributed_tracing.enabled'] && trace_headers&.any? yield end end diff --git a/lib/new_relic/agent/instrumentation/sinatra/ignorer.rb b/lib/new_relic/agent/instrumentation/sinatra/ignorer.rb index 2483dfa995..6e01b9a931 100644 --- a/lib/new_relic/agent/instrumentation/sinatra/ignorer.rb +++ b/lib/new_relic/agent/instrumentation/sinatra/ignorer.rb @@ -33,7 +33,7 @@ def set_newrelic_ignore(type, *routes) set(:newrelic_ignores, Hash.new([])) if !respond_to?(:newrelic_ignores) # If we call an ignore without a route, it applies to the whole app - routes = ["*"] if routes.empty? + routes = ['*'] if routes.empty? settings.newrelic_ignores[type] += routes.map do |r| # Ugly sending to private Base#compile, but we want to mimic diff --git a/lib/new_relic/agent/instrumentation/sinatra/instrumentation.rb b/lib/new_relic/agent/instrumentation/sinatra/instrumentation.rb index e79efab70c..c9ff847c0c 100644 --- a/lib/new_relic/agent/instrumentation/sinatra/instrumentation.rb +++ b/lib/new_relic/agent/instrumentation/sinatra/instrumentation.rb @@ -45,7 +45,8 @@ def install_lock def try_to_use(app, clazz) install_lock.synchronize do - has_middleware = app.middleware && app.middleware.any? { |info| info && info[0] == clazz } + # The following line needs else branch coverage + has_middleware = app.middleware && app.middleware.any? { |info| info && info[0] == clazz } # rubocop:disable Style/SafeNavigation app.use(clazz) unless has_middleware end end @@ -53,9 +54,9 @@ def try_to_use(app, clazz) # Capture last route we've seen. Will set for transaction on route_eval def process_route_with_tracing(*args) begin - env["newrelic.last_route"] = args[0] + env['newrelic.last_route'] = args[0] rescue => e - ::NewRelic::Agent.logger.debug("Failed determining last route in Sinatra", e) + ::NewRelic::Agent.logger.debug('Failed determining last route in Sinatra', e) end yield end @@ -74,7 +75,7 @@ def route_eval_with_tracing(*args) ) end rescue => e - ::NewRelic::Agent.logger.debug("Failed during route_eval to set transaction name", e) + ::NewRelic::Agent.logger.debug('Failed during route_eval to set transaction name', e) end yield end @@ -83,7 +84,7 @@ def get_request_params begin @request.params rescue => e - NewRelic::Agent.logger.debug("Failed to get params from Rack request.", e) + NewRelic::Agent.logger.debug('Failed to get params from Rack request.', e) nil end end diff --git a/lib/new_relic/agent/instrumentation/sinatra/transaction_namer.rb b/lib/new_relic/agent/instrumentation/sinatra/transaction_namer.rb index 702e874443..b5f553c68d 100644 --- a/lib/new_relic/agent/instrumentation/sinatra/transaction_namer.rb +++ b/lib/new_relic/agent/instrumentation/sinatra/transaction_namer.rb @@ -47,7 +47,7 @@ def http_verb(request) # For bare Sinatra, our override on process_route captures the last # route into the environment for us to use later on def route_for_sinatra(env) - env["newrelic.last_route"] + env['newrelic.last_route'] end # For Padrino, the request object has a copy of the matched route diff --git a/lib/new_relic/agent/instrumentation/tilt/instrumentation.rb b/lib/new_relic/agent/instrumentation/tilt/instrumentation.rb index 3a65ba04b4..8255b6ed84 100644 --- a/lib/new_relic/agent/instrumentation/tilt/instrumentation.rb +++ b/lib/new_relic/agent/instrumentation/tilt/instrumentation.rb @@ -32,7 +32,8 @@ def render_with_tracing(*args, &block) raise end ensure - finishable.finish if finishable + # The following line needs else branch coverage + finishable.finish if finishable # rubocop:disable Style/SafeNavigation end end end diff --git a/lib/new_relic/agent/instrumentation/typhoeus/instrumentation.rb b/lib/new_relic/agent/instrumentation/typhoeus/instrumentation.rb index cd1b5d54b9..4a7f6a648b 100644 --- a/lib/new_relic/agent/instrumentation/typhoeus/instrumentation.rb +++ b/lib/new_relic/agent/instrumentation/typhoeus/instrumentation.rb @@ -6,10 +6,10 @@ module NewRelic module Agent module Instrumentation module Typhoeus - HYDRA_SEGMENT_NAME = "External/Multiple/Typhoeus::Hydra/run" - NOTICEABLE_ERROR_CLASS = "Typhoeus::Errors::TyphoeusError" + HYDRA_SEGMENT_NAME = 'External/Multiple/Typhoeus::Hydra/run' + NOTICEABLE_ERROR_CLASS = 'Typhoeus::Errors::TyphoeusError' - EARLIEST_VERSION = Gem::Version.new("0.5.3") + EARLIEST_VERSION = Gem::Version.new('0.5.3') def self.is_supported_version? Gem::Version.new(::Typhoeus::VERSION) >= EARLIEST_VERSION @@ -26,7 +26,7 @@ def self.response_message(response) response.return_message else # 0.5.4 seems to have lost xxxx_message methods altogether. - "timeout" + 'timeout' end end @@ -72,7 +72,7 @@ def self.trace(request) end request.on_complete.unshift(callback) rescue => e - NewRelic::Agent.logger.error("Exception during trace setup for Typhoeus request", e) + NewRelic::Agent.logger.error('Exception during trace setup for Typhoeus request', e) end end end diff --git a/lib/new_relic/agent/javascript_instrumentor.rb b/lib/new_relic/agent/javascript_instrumentor.rb index 1eeea85f78..6bce7fb51c 100644 --- a/lib/new_relic/agent/javascript_instrumentor.rb +++ b/lib/new_relic/agent/javascript_instrumentor.rb @@ -23,7 +23,7 @@ def log_configuration "JS agent loader version: #{NewRelic::Agent.config[:'browser_monitoring.loader_version']}") if !NewRelic::Agent.config[:'rum.enabled'] - NewRelic::Agent.logger.debug("Real User Monitoring is disabled for this agent. Edit your configuration to change this.") + NewRelic::Agent.logger.debug('Real User Monitoring is disabled for this agent. Edit your configuration to change this.') end end @@ -38,19 +38,19 @@ def obfuscator def js_enabled_and_ready? if !enabled? ::NewRelic::Agent.logger.log_once(:debug, :js_agent_disabled, - "JS agent instrumentation is disabled.") + 'JS agent instrumentation is disabled.') false elsif missing_config?(:js_agent_loader) ::NewRelic::Agent.logger.log_once(:debug, :missing_js_agent_loader, - "Missing :js_agent_loader. Skipping browser instrumentation.") + 'Missing :js_agent_loader. Skipping browser instrumentation.') false elsif missing_config?(:beacon) ::NewRelic::Agent.logger.log_once(:debug, :missing_beacon, - "Beacon configuration not received (yet?). Skipping browser instrumentation.") + 'Beacon configuration not received (yet?). Skipping browser instrumentation.') false elsif missing_config?(:browser_key) ::NewRelic::Agent.logger.log_once(:debug, :missing_browser_key, - "Browser key is not set. Skipping browser instrumentation.") + 'Browser key is not set. Skipping browser instrumentation.') false else true @@ -62,19 +62,19 @@ def js_enabled_and_ready? def insert_js?(state) if !state.current_transaction - ::NewRelic::Agent.logger.debug("Not in transaction. Skipping browser instrumentation.") + ::NewRelic::Agent.logger.debug('Not in transaction. Skipping browser instrumentation.') false elsif !state.is_execution_traced? - ::NewRelic::Agent.logger.debug("Execution is not traced. Skipping browser instrumentation.") + ::NewRelic::Agent.logger.debug('Execution is not traced. Skipping browser instrumentation.') false elsif state.current_transaction.ignore_enduser? - ::NewRelic::Agent.logger.debug("Ignore end user for this transaction is set. Skipping browser instrumentation.") + ::NewRelic::Agent.logger.debug('Ignore end user for this transaction is set. Skipping browser instrumentation.') false else true end rescue => e - ::NewRelic::Agent.logger.debug("Failure during insert_js", e) + ::NewRelic::Agent.logger.debug('Failure during insert_js', e) false end @@ -95,7 +95,7 @@ def browser_timing_header(nonce = nil) # THREAD_LOCAL_ACCESS bt_config + browser_timing_loader(nonce) rescue => e - ::NewRelic::Agent.logger.debug("Failure during RUM browser_timing_header construction", e) + ::NewRelic::Agent.logger.debug('Failure during RUM browser_timing_header construction', e) '' end @@ -122,18 +122,18 @@ def create_nonce(nonce = nil) " nonce=\"#{nonce.to_s}\"" end - BEACON_KEY = "beacon".freeze - ERROR_BEACON_KEY = "errorBeacon".freeze - LICENSE_KEY_KEY = "licenseKey".freeze - APPLICATIONID_KEY = "applicationID".freeze - TRANSACTION_NAME_KEY = "transactionName".freeze - QUEUE_TIME_KEY = "queueTime".freeze - APPLICATION_TIME_KEY = "applicationTime".freeze - AGENT_KEY = "agent".freeze - SSL_FOR_HTTP_KEY = "sslForHttp".freeze - ATTS_KEY = "atts".freeze - ATTS_USER_SUBKEY = "u".freeze - ATTS_AGENT_SUBKEY = "a".freeze + BEACON_KEY = 'beacon'.freeze + ERROR_BEACON_KEY = 'errorBeacon'.freeze + LICENSE_KEY_KEY = 'licenseKey'.freeze + APPLICATIONID_KEY = 'applicationID'.freeze + TRANSACTION_NAME_KEY = 'transactionName'.freeze + QUEUE_TIME_KEY = 'queueTime'.freeze + APPLICATION_TIME_KEY = 'applicationTime'.freeze + AGENT_KEY = 'agent'.freeze + SSL_FOR_HTTP_KEY = 'sslForHttp'.freeze + ATTS_KEY = 'atts'.freeze + ATTS_USER_SUBKEY = 'u'.freeze + ATTS_AGENT_SUBKEY = 'a'.freeze # NOTE: Internal prototyping may override this, so leave name stable! def data_for_js_agent(transaction) @@ -185,9 +185,14 @@ def add_attributes(data, txn) def append_custom_attributes!(txn, atts) custom_attributes = txn.attributes.custom_attributes_for(NewRelic::Agent::AttributeFilter::DST_BROWSER_MONITORING) - unless custom_attributes.empty? - atts[ATTS_USER_SUBKEY] = custom_attributes + if custom_attributes.empty? + NewRelic::Agent.logger.debug("#{self.class}: No custom attributes found to append.") + return end + + NewRelic::Agent.logger.debug("#{self.class}: Appending the following custom attribute keys for browser " \ + "monitoring: #{custom_attributes.keys}") + atts[ATTS_USER_SUBKEY] = custom_attributes end def append_agent_attributes!(txn, atts) diff --git a/lib/new_relic/agent/linking_metadata.rb b/lib/new_relic/agent/linking_metadata.rb index 63a0e52aad..de37b4b888 100644 --- a/lib/new_relic/agent/linking_metadata.rb +++ b/lib/new_relic/agent/linking_metadata.rb @@ -11,7 +11,7 @@ module LinkingMetadata extend self def append_service_linking_metadata(metadata) - raise ArgumentError, "Missing argument `metadata`" if metadata.nil? + raise ArgumentError, 'Missing argument `metadata`' if metadata.nil? config = ::NewRelic::Agent.config @@ -27,7 +27,7 @@ def append_service_linking_metadata(metadata) end def append_trace_linking_metadata(metadata) - raise ArgumentError, "Missing argument `metadata`" if metadata.nil? + raise ArgumentError, 'Missing argument `metadata`' if metadata.nil? if trace_id = Tracer.current_trace_id metadata[TRACE_ID_KEY] = trace_id diff --git a/lib/new_relic/agent/log_event_aggregator.rb b/lib/new_relic/agent/log_event_aggregator.rb index c8273d0759..0666962d18 100644 --- a/lib/new_relic/agent/log_event_aggregator.rb +++ b/lib/new_relic/agent/log_event_aggregator.rb @@ -9,20 +9,20 @@ module NewRelic module Agent class LogEventAggregator < EventAggregator # Per-message keys - LEVEL_KEY = "level".freeze - MESSAGE_KEY = "message".freeze - TIMESTAMP_KEY = "timestamp".freeze - PRIORITY_KEY = "priority".freeze + LEVEL_KEY = 'level'.freeze + MESSAGE_KEY = 'message'.freeze + TIMESTAMP_KEY = 'timestamp'.freeze + PRIORITY_KEY = 'priority'.freeze # Metric keys - LINES = "Logging/lines".freeze - DROPPED_METRIC = "Logging/Forwarding/Dropped".freeze - SEEN_METRIC = "Supportability/Logging/Forwarding/Seen".freeze - SENT_METRIC = "Supportability/Logging/Forwarding/Sent".freeze - OVERALL_SUPPORTABILITY_FORMAT = "Supportability/Logging/Ruby/Logger/%s".freeze - METRICS_SUPPORTABILITY_FORMAT = "Supportability/Logging/Metrics/Ruby/%s".freeze - FORWARDING_SUPPORTABILITY_FORMAT = "Supportability/Logging/Forwarding/Ruby/%s".freeze - DECORATING_SUPPORTABILITY_FORMAT = "Supportability/Logging/LocalDecorating/Ruby/%s".freeze + LINES = 'Logging/lines'.freeze + DROPPED_METRIC = 'Logging/Forwarding/Dropped'.freeze + SEEN_METRIC = 'Supportability/Logging/Forwarding/Seen'.freeze + SENT_METRIC = 'Supportability/Logging/Forwarding/Sent'.freeze + OVERALL_SUPPORTABILITY_FORMAT = 'Supportability/Logging/Ruby/Logger/%s'.freeze + METRICS_SUPPORTABILITY_FORMAT = 'Supportability/Logging/Metrics/Ruby/%s'.freeze + FORWARDING_SUPPORTABILITY_FORMAT = 'Supportability/Logging/Forwarding/Ruby/%s'.freeze + DECORATING_SUPPORTABILITY_FORMAT = 'Supportability/Logging/LocalDecorating/Ruby/%s'.freeze MAX_BYTES = 32768 # 32 * 1024 bytes (32 kibibytes) named :LogEventAggregator @@ -54,7 +54,7 @@ def capacity def record(formatted_message, severity) return unless enabled? - severity = "UNKNOWN" if severity.nil? || severity.empty? + severity = 'UNKNOWN' if severity.nil? || severity.empty? if NewRelic::Agent.config[METRICS_ENABLED_KEY] @counter_lock.synchronize do @@ -174,9 +174,9 @@ def register_for_done_configuring(events) def record_configuration_metric(format, key) state = NewRelic::Agent.config[key] label = if !enabled? - "disabled" + 'disabled' else - state ? "enabled" : "disabled" + state ? 'enabled' : 'disabled' end NewRelic::Agent.increment_metric(format % label) end diff --git a/lib/new_relic/agent/logging.rb b/lib/new_relic/agent/logging.rb index 7604dfeb0b..69d58de716 100644 --- a/lib/new_relic/agent/logging.rb +++ b/lib/new_relic/agent/logging.rb @@ -22,16 +22,21 @@ module Logging # # @api public class DecoratingFormatter < ::Logger::Formatter - TIMESTAMP_KEY = 'timestamp'.freeze - MESSAGE_KEY = 'message'.freeze - LOG_LEVEL_KEY = 'log.level'.freeze - LOG_NAME_KEY = 'logger.name'.freeze - NEWLINE = "\n".freeze - - QUOTE = '"'.freeze - COLON = ':'.freeze - COMMA = ','.freeze - CLOSING_BRACE = '}'.freeze + MESSAGE_ELEMENT = 'message' + LOG_LEVEL_ELEMENT = 'log_level' + PROG_NAME_ELEMENT = 'prog_name' + ELEMENTS = ['app_name', 'entity_type', 'hostname', 'entity_guid', 'trace_id', 'span_id', MESSAGE_ELEMENT, + LOG_LEVEL_ELEMENT, PROG_NAME_ELEMENT].freeze + TIMESTAMP_KEY = 'timestamp' + MESSAGE_KEY = 'message' + LOG_LEVEL_KEY = 'log.level' + LOG_NAME_KEY = 'logger.name' + NEWLINE = "\n" + + QUOTE = '"' + COLON = ':' + COMMA = ',' + CLOSING_BRACE = '}' REPLACEMENT_CHAR = '�' def initialize @@ -41,41 +46,76 @@ def initialize end def call(severity, time, progname, msg) - message = String.new('{') - if app_name - add_key_value(message, ENTITY_NAME_KEY, app_name) - message << COMMA + message = +'{' + ELEMENTS.each do |element| + args = case element + when MESSAGE_ELEMENT then [message, msg] + when LOG_LEVEL_ELEMENT then [message, severity] + when PROG_NAME_ELEMENT then [message, progname] + else [message] + end + + send("add_#{element}", *args) end + message << COMMA + message << QUOTE << TIMESTAMP_KEY << QUOTE << COLON << (time.to_f * 1000).round.to_s + message << CLOSING_BRACE << NEWLINE + end + + private + + def add_app_name(message) + return unless app_name + + add_key_value(message, ENTITY_NAME_KEY, app_name) + message << COMMA + end + + def add_entity_type(message) add_key_value(message, ENTITY_TYPE_KEY, ENTITY_TYPE) message << COMMA + end + + def add_hostname(message) add_key_value(message, HOSTNAME_KEY, Hostname.get) + end - if entity_guid = Agent.config[:entity_guid] - message << COMMA - add_key_value(message, ENTITY_GUID_KEY, entity_guid) - end + def add_entity_guid(message) + return unless entity_guid = Agent.config[:entity_guid] - if trace_id = Tracer.trace_id - message << COMMA - add_key_value(message, TRACE_ID_KEY, trace_id) - end - if span_id = Tracer.span_id - message << COMMA - add_key_value(message, SPAN_ID_KEY, span_id) - end + message << COMMA + add_key_value(message, ENTITY_GUID_KEY, entity_guid) + end + + def add_trace_id(message) + return unless trace_id = Tracer.trace_id + message << COMMA + add_key_value(message, TRACE_ID_KEY, trace_id) + end + + def add_span_id(message) + return unless span_id = Tracer.span_id + + message << COMMA + add_key_value(message, SPAN_ID_KEY, span_id) + end + + def add_message(message, msg) message << COMMA message << QUOTE << MESSAGE_KEY << QUOTE << COLON << escape(msg) message << COMMA + end + + def add_log_level(message, severity) add_key_value(message, LOG_LEVEL_KEY, severity) - if progname - message << COMMA - add_key_value(message, LOG_NAME_KEY, progname) - end + end + + def add_prog_name(message, progname) + return unless progname message << COMMA - message << QUOTE << TIMESTAMP_KEY << QUOTE << COLON << (time.to_f * 1000).round.to_s - message << CLOSING_BRACE << NEWLINE + add_key_value(message, LOG_NAME_KEY, progname) end def app_name @@ -125,7 +165,7 @@ class DecoratingLogger < (defined?(::ActiveSupport) && defined?(::ActiveSupport: # Positional and Keyword arguments are separated beginning with Ruby 2.7 # Signature of ::Logger constructor changes in Ruby 2.4 to have both positional and keyword args # We pivot on Ruby 2.7 for widest supportability with least amount of hassle. - if RUBY_VERSION < "2.7.0" + if RUBY_VERSION < '2.7.0' def initialize(*args) super(*args) self.formatter = DecoratingFormatter.new diff --git a/lib/new_relic/agent/messaging.rb b/lib/new_relic/agent/messaging.rb index a701ce2523..9ead4adb9c 100644 --- a/lib/new_relic/agent/messaging.rb +++ b/lib/new_relic/agent/messaging.rb @@ -14,7 +14,7 @@ module Agent module Messaging extend self - RABBITMQ_TRANSPORT_TYPE = "RabbitMQ" + RABBITMQ_TRANSPORT_TYPE = 'RabbitMQ' ATTR_DESTINATION = AttributeFilter::DST_TRANSACTION_EVENTS | AttributeFilter::DST_TRANSACTION_TRACER | @@ -142,15 +142,16 @@ def wrap_message_broker_consume_transaction(library:, txn.add_agent_attribute(:'message.queueName', queue_name, ATTR_DESTINATION) if queue_name txn.add_agent_attribute(:'message.replyTo', reply_to, AttributeFilter::DST_NONE) if reply_to rescue => e - NewRelic::Agent.logger.error("Error starting Message Broker consume transaction", e) + NewRelic::Agent.logger.error('Error starting Message Broker consume transaction', e) end yield ensure begin - txn.finish if txn + # the following line needs else branch coverage + txn.finish if txn # rubocop:disable Style/SafeNavigation rescue => e - NewRelic::Agent.logger.error("Error stopping Message Broker consume transaction", e) + NewRelic::Agent.logger.error('Error stopping Message Broker consume transaction', e) end end @@ -190,7 +191,8 @@ def start_amqp_publish_segment(library:, raise ArgumentError, 'missing required argument: headers' if headers.nil? && CrossAppTracing.cross_app_enabled? - original_headers = headers.nil? ? nil : headers.dup + # The following line needs else branch coverage + original_headers = headers.nil? ? nil : headers.dup # rubocop:disable Style/SafeNavigation segment = Tracer.start_message_broker_segment( action: :produce, diff --git a/lib/new_relic/agent/method_tracer.rb b/lib/new_relic/agent/method_tracer.rb index f86c0d9c45..31115cfccd 100644 --- a/lib/new_relic/agent/method_tracer.rb +++ b/lib/new_relic/agent/method_tracer.rb @@ -103,7 +103,7 @@ module ClassMethods module AddMethodTracer ALLOWED_KEYS = [:metric, :push_scope, :code_header, :code_information, :code_footer].freeze - DEFAULT_SETTINGS = {:push_scope => true, :metric => true, :code_header => "", :code_footer => ""}.freeze + DEFAULT_SETTINGS = {:push_scope => true, :metric => true, :code_header => '', :code_footer => ''}.freeze # Checks the provided options to make sure that they make # sense. Raises an error if the options are incorrect to @@ -170,14 +170,14 @@ def _nr_clear_traced_methods! def _nr_derived_class_name return self.name if self.name && !self.name.empty? - return "AnonymousModule" if self.to_s.start_with?("#" name = self.to_s[/^#$/, 1] - if name.start_with?("0x") - "AnonymousClass" - elsif name.start_with?("#> 31)) & 0xffffffff app_name = NewRelic::Agent.config[:app_name].first identifier = "#{app_name};#{txn_name}" - sprintf("%08x", rotated ^ hash_transaction_name(identifier)) + sprintf('%08x', rotated ^ hash_transaction_name(identifier)) end private @@ -44,7 +44,7 @@ def path_hash(txn_name, seed) # :after_call will write our response headers/metrics and clean up the thread def register_event_listeners(events) NewRelic::Agent.logger - .debug("Wiring up Cross Application Tracing to events after finished configuring") + .debug('Wiring up Cross Application Tracing to events after finished configuring') events.subscribe(:before_call) do |env| # THREAD_LOCAL_ACCESS if id = decoded_id(env) and should_process_request?(id) @@ -109,7 +109,7 @@ def content_length_from_request(request) end def hash_transaction_name(identifier) - Digest::MD5.digest(identifier).unpack("@12N").first & 0xffffffff + Digest::MD5.digest(identifier).unpack('@12N').first & 0xffffffff end end end diff --git a/lib/new_relic/agent/monitors/distributed_tracing_monitor.rb b/lib/new_relic/agent/monitors/distributed_tracing_monitor.rb index 0f82808161..9218670549 100644 --- a/lib/new_relic/agent/monitors/distributed_tracing_monitor.rb +++ b/lib/new_relic/agent/monitors/distributed_tracing_monitor.rb @@ -14,7 +14,7 @@ def on_finished_configuring(events) def on_before_call(request) unless NewRelic::Agent.config[:'distributed_tracing.enabled'] - NewRelic::Agent.logger.warn("Not configured to accept distributed trace headers") + NewRelic::Agent.logger.warn('Not configured to accept distributed trace headers') return end diff --git a/lib/new_relic/agent/new_relic_service.rb b/lib/new_relic/agent/new_relic_service.rb index 225e1f2e8f..6625cb256c 100644 --- a/lib/new_relic/agent/new_relic_service.rb +++ b/lib/new_relic/agent/new_relic_service.rb @@ -65,7 +65,7 @@ def prep_marshaller Agent.config.register_callback(:marshaller) do |marshaller| if marshaller != 'json' ::NewRelic::Agent.logger.warn("Non-JSON marshaller '#{marshaller}' requested but not supported, using " \ - "JSON marshaller instead. pruby marshalling has been removed as of version 3.14.0.") + 'JSON marshaller instead. pruby marshalling has been removed as of version 3.14.0.') end @marshaller = JsonMarshaller.new @@ -195,16 +195,16 @@ def log_event_data(data) def error_event_data(data) metadata, items = data response = invoke_remote(:error_event_data, [@agent_id, *data], :item_count => items.size) - NewRelic::Agent.record_metric("Supportability/Events/TransactionError/Sent", :count => items.size) - NewRelic::Agent.record_metric("Supportability/Events/TransactionError/Seen", :count => metadata[:events_seen]) + NewRelic::Agent.record_metric('Supportability/Events/TransactionError/Sent', :count => items.size) + NewRelic::Agent.record_metric('Supportability/Events/TransactionError/Seen', :count => metadata[:events_seen]) response end def span_event_data(data) metadata, items = data response = invoke_remote(:span_event_data, [@agent_id, *data], :item_count => items.size) - NewRelic::Agent.record_metric("Supportability/Events/SpanEvents/Sent", :count => items.size) - NewRelic::Agent.record_metric("Supportability/Events/SpanEvents/Seen", :count => metadata[:events_seen]) + NewRelic::Agent.record_metric('Supportability/Events/SpanEvents/Sent', :count => items.size) + NewRelic::Agent.record_metric('Supportability/Events/SpanEvents/Seen', :count => metadata[:events_seen]) response end @@ -305,7 +305,7 @@ def setup_connection_for_ssl(conn) conn.verify_mode = OpenSSL::SSL::VERIFY_PEER set_cert_store(conn) rescue StandardError, LoadError - msg = "SSL is not available in the environment; please install SSL support." + msg = 'SSL is not available in the environment; please install SSL support.' raise UnrecoverableAgentException.new(msg) end @@ -313,7 +313,7 @@ def set_cert_store(conn) if NewRelic::Agent.config[:ca_bundle_path] conn.cert_store = ssl_cert_store else - ::NewRelic::Agent.logger.debug("Using default security certificates") + ::NewRelic::Agent.logger.debug('Using default security certificates') end end @@ -363,7 +363,7 @@ def create_and_start_http_connection start_connection(conn) conn rescue Timeout::Error - ::NewRelic::Agent.logger.info("Timeout while attempting to connect. You may need to install system-level CA Certificates, as the ruby agent no longer includes these.") + ::NewRelic::Agent.logger.info('Timeout while attempting to connect. You may need to install system-level CA Certificates, as the ruby agent no longer includes these.') raise end @@ -380,7 +380,7 @@ def valid_to_marshal?(data) @marshaller.dump(data) true rescue StandardError, SystemStackError => e - NewRelic::Agent.logger.warn("Unable to marshal environment report on connect.", e) + NewRelic::Agent.logger.warn('Unable to marshal environment report on connect.', e) false end @@ -409,7 +409,7 @@ def prep_request(opts) end @audit_logger.log_request_headers(opts[:uri], headers) request['user-agent'] = user_agent - request.content_type = "application/octet-stream" + request.content_type = 'application/octet-stream' request.body = opts[:data] request end @@ -521,7 +521,7 @@ def generate_remote_method_uri(method) # ruled out; see the initializer } - uri = String.new('/agent_listener/invoke_raw_method?') + uri = +'/agent_listener/invoke_raw_method?' uri << params.map do |k, v| next unless v @@ -551,7 +551,7 @@ def invoke_remote(method, payload = [], options = {}) end def handle_serialization_error(method, e) - NewRelic::Agent.increment_metric("Supportability/serialization_failure") + NewRelic::Agent.increment_metric('Supportability/serialization_failure') NewRelic::Agent.increment_metric("Supportability/serialization_failure/#{method}") msg = "Failed to serialize #{method} data using #{@marshaller.class}: #{e.inspect}" error = SerializationError.new(msg) @@ -566,7 +566,7 @@ def record_timing_supportability_metrics(method, start_ts, serialize_finish_ts, NewRelic::Agent.record_metric("Supportability/Agent/Collector/#{method}/Duration", request_duration) end if serialize_time - NewRelic::Agent.record_metric("Supportability/invoke_remote_serialize", serialize_time) + NewRelic::Agent.record_metric('Supportability/invoke_remote_serialize', serialize_time) NewRelic::Agent.record_metric("Supportability/invoke_remote_serialize/#{method}", serialize_time) end end @@ -581,7 +581,7 @@ def record_timing_supportability_metrics(method, start_ts, serialize_finish_ts, # of items as arguments. def record_size_supportability_metrics(method, size_bytes, item_count) metrics = [ - "Supportability/Ruby/Collector/Output/Bytes", + 'Supportability/Ruby/Collector/Output/Bytes', "Supportability/Ruby/Collector/#{method}/Output/Bytes" ] # we may not have an item count, in which case, just record 0 for the exclusive time diff --git a/lib/new_relic/agent/new_relic_service/encoders.rb b/lib/new_relic/agent/new_relic_service/encoders.rb index 3868f699bd..b588b7ced5 100644 --- a/lib/new_relic/agent/new_relic_service/encoders.rb +++ b/lib/new_relic/agent/new_relic_service/encoders.rb @@ -25,7 +25,7 @@ def self.encode(data, opts = nil) end module Gzip - BINARY = "BINARY".freeze + BINARY = 'BINARY'.freeze def self.encode(data, opts = nil) output = StringIO.new diff --git a/lib/new_relic/agent/new_relic_service/json_marshaller.rb b/lib/new_relic/agent/new_relic_service/json_marshaller.rb index 9693dd2a66..26a08909ef 100644 --- a/lib/new_relic/agent/new_relic_service/json_marshaller.rb +++ b/lib/new_relic/agent/new_relic_service/json_marshaller.rb @@ -14,7 +14,7 @@ def initialize warn_for_yajl end - OK_YAJL_VERSION = Gem::Version.new("1.2.1") + OK_YAJL_VERSION = Gem::Version.new('1.2.1') def warn_for_yajl if defined?(::Yajl) @@ -24,7 +24,7 @@ def warn_for_yajl end end rescue => err - ::NewRelic::Agent.logger.warn("Failed trying to watch for problematic yajl-ruby version.", err) + ::NewRelic::Agent.logger.warn('Failed trying to watch for problematic yajl-ruby version.', err) end def dump(ruby, opts = {}) diff --git a/lib/new_relic/agent/obfuscator.rb b/lib/new_relic/agent/obfuscator.rb index 1961c5352f..12bc9806bb 100644 --- a/lib/new_relic/agent/obfuscator.rb +++ b/lib/new_relic/agent/obfuscator.rb @@ -33,7 +33,7 @@ def deobfuscate(text) def encode(text) return text unless key_bytes - encoded = String.new('') + encoded = +'' encoded.force_encoding('binary') if encoded.respond_to?(:force_encoding) index = 0 text.each_byte do |byte| diff --git a/lib/new_relic/agent/parameter_filtering.rb b/lib/new_relic/agent/parameter_filtering.rb index 0eeed8890c..60f7645ad2 100644 --- a/lib/new_relic/agent/parameter_filtering.rb +++ b/lib/new_relic/agent/parameter_filtering.rb @@ -7,7 +7,7 @@ module Agent module ParameterFiltering extend self - ACTION_DISPATCH_PARAMETER_FILTER ||= "action_dispatch.parameter_filter".freeze + ACTION_DISPATCH_PARAMETER_FILTER ||= 'action_dispatch.parameter_filter'.freeze if defined?(Rails) && Gem::Version.new(::Rails::VERSION::STRING) >= Gem::Version.new('5.0.0') Rails.application.config.to_prepare do @@ -41,12 +41,12 @@ def filter_using_rails(params, filters) end def filter_rack_file_data(env, params) - content_type = env["CONTENT_TYPE"] - multipart = content_type && content_type.start_with?("multipart") + content_type = env['CONTENT_TYPE'] + multipart = content_type&.start_with?('multipart') params.inject({}) do |memo, (k, v)| if multipart && v.is_a?(Hash) && v[:tempfile] - memo[k] = "[FILE]" + memo[k] = '[FILE]' else memo[k] = v end @@ -56,8 +56,8 @@ def filter_rack_file_data(env, params) def filter_rails_request_parameters(params) result = params.dup - result.delete("controller") - result.delete("action") + result.delete('controller') + result.delete('action') result end diff --git a/lib/new_relic/agent/pipe_channel_manager.rb b/lib/new_relic/agent/pipe_channel_manager.rb index 592c8bc859..4ae8a85234 100644 --- a/lib/new_relic/agent/pipe_channel_manager.rb +++ b/lib/new_relic/agent/pipe_channel_manager.rb @@ -55,7 +55,7 @@ def listener # 4 GB - much larger than we'd ever need or want for this application. # class Pipe - READY_MARKER = "READY" + READY_MARKER = 'READY' NUM_LENGTH_BYTES = 4 attr_accessor :in, :out @@ -76,11 +76,11 @@ def close end def serialize_message_length(data) - [data.bytesize].pack("L>") + [data.bytesize].pack('L>') end def deserialize_message_length(data) - data.unpack("L>").first + data.unpack('L>').first end def write(data) @@ -103,7 +103,7 @@ def read nil end else - NewRelic::Agent.logger.error("Failed to read bytes for length from pipe.") + NewRelic::Agent.logger.error('Failed to read bytes for length from pipe.') nil end end @@ -218,7 +218,8 @@ def stop def close_all_pipes @pipes_lock.synchronize do @pipes.each do |id, pipe| - pipe.close if pipe + # Needs else branch coverage + pipe.close if pipe # rubocop:disable Style/SafeNavigation end @pipes = {} end @@ -255,7 +256,7 @@ def merge_data_from_pipe(pipe_handle) def unmarshal(data) Marshal.load(data) rescue StandardError => e - ::NewRelic::Agent.logger.error("Failure unmarshalling message from Resque child process", e) + ::NewRelic::Agent.logger.error('Failure unmarshalling message from Resque child process', e) ::NewRelic::Agent.logger.debug(Base64.encode64(data)) nil end diff --git a/lib/new_relic/agent/pipe_service.rb b/lib/new_relic/agent/pipe_service.rb index 53deed6e11..57797bfe94 100644 --- a/lib/new_relic/agent/pipe_service.rb +++ b/lib/new_relic/agent/pipe_service.rb @@ -15,7 +15,7 @@ def initialize(channel_id) if @pipe && @pipe.parent_pid != $$ @pipe.after_fork_in_child else - NewRelic::Agent.logger.error("No communication channel to parent process, please see https://newrelic.com/docs/ruby/resque-instrumentation for more information.") + NewRelic::Agent.logger.error('No communication channel to parent process, please see https://newrelic.com/docs/ruby/resque-instrumentation for more information.') end end @@ -65,7 +65,8 @@ def log_event_data(logs) end def shutdown - @pipe.close if @pipe + # no else branch coverage + @pipe.close if @pipe # rubocop:disable Style/SafeNavigation end # Invokes the block it is passed. This is used to implement HTTP @@ -82,7 +83,8 @@ def marshal_payload(data) end def write_to_pipe(endpoint, data) - @pipe.write(marshal_payload([endpoint, data])) if @pipe + # the following line needs else branch coverage + @pipe.write(marshal_payload([endpoint, data])) if @pipe # rubocop:disable Style/SafeNavigation end end end diff --git a/lib/new_relic/agent/priority_sampled_buffer.rb b/lib/new_relic/agent/priority_sampled_buffer.rb index 5dd8adce57..ccf73ece1e 100644 --- a/lib/new_relic/agent/priority_sampled_buffer.rb +++ b/lib/new_relic/agent/priority_sampled_buffer.rb @@ -8,7 +8,7 @@ module NewRelic module Agent class PrioritySampledBuffer < EventBuffer - PRIORITY_KEY = "priority".freeze + PRIORITY_KEY = 'priority'.freeze attr_reader :seen_lifetime, :captured_lifetime diff --git a/lib/new_relic/agent/sampler.rb b/lib/new_relic/agent/sampler.rb index 3c7588d287..919bde7746 100644 --- a/lib/new_relic/agent/sampler.rb +++ b/lib/new_relic/agent/sampler.rb @@ -56,7 +56,7 @@ def initialize(id = nil) end def poll - raise "Implement in the subclass" + raise 'Implement in the subclass' end end end diff --git a/lib/new_relic/agent/sampler_collection.rb b/lib/new_relic/agent/sampler_collection.rb index 8298fa0edd..a0cd2d02f8 100644 --- a/lib/new_relic/agent/sampler_collection.rb +++ b/lib/new_relic/agent/sampler_collection.rb @@ -64,7 +64,7 @@ def add_sampler(sampler_class) rescue NewRelic::Agent::Sampler::Unsupported => e ::NewRelic::Agent.logger.info("#{sampler_class.name} not available: #{e}") rescue => e - ::NewRelic::Agent.logger.error("Error registering sampler:", e) + ::NewRelic::Agent.logger.error('Error registering sampler:', e) end end end diff --git a/lib/new_relic/agent/samplers/cpu_sampler.rb b/lib/new_relic/agent/samplers/cpu_sampler.rb index 673e0e3164..3dcb65bf2d 100644 --- a/lib/new_relic/agent/samplers/cpu_sampler.rb +++ b/lib/new_relic/agent/samplers/cpu_sampler.rb @@ -16,26 +16,26 @@ def initialize @last_time = nil @processor_count = NewRelic::Agent::SystemInfo.num_logical_processors if @processor_count.nil? - NewRelic::Agent.logger.warn("Failed to determine processor count, assuming 1") + NewRelic::Agent.logger.warn('Failed to determine processor count, assuming 1') @processor_count = 1 end poll end def record_user_util(value) - NewRelic::Agent.record_metric("CPU/User/Utilization", value) + NewRelic::Agent.record_metric('CPU/User/Utilization', value) end def record_system_util(value) - NewRelic::Agent.record_metric("CPU/System/Utilization", value) + NewRelic::Agent.record_metric('CPU/System/Utilization', value) end def record_usertime(value) - NewRelic::Agent.record_metric("CPU/User Time", value) + NewRelic::Agent.record_metric('CPU/User Time', value) end def record_systemtime(value) - NewRelic::Agent.record_metric("CPU/System Time", value) + NewRelic::Agent.record_metric('CPU/System Time', value) end def self.supported_on_this_platform? diff --git a/lib/new_relic/agent/samplers/delayed_job_sampler.rb b/lib/new_relic/agent/samplers/delayed_job_sampler.rb index 5e680e6f32..672f527fda 100644 --- a/lib/new_relic/agent/samplers/delayed_job_sampler.rb +++ b/lib/new_relic/agent/samplers/delayed_job_sampler.rb @@ -21,21 +21,21 @@ class DelayedJobSampler < NewRelic::Agent::Sampler # DelayedJob supports multiple backends, only some of which we can # handle. Check whether we think we've got what we need here. def self.supported_backend? - ::Delayed::Worker.backend.to_s == "Delayed::Backend::ActiveRecord::Job" + ::Delayed::Worker.backend.to_s == 'Delayed::Backend::ActiveRecord::Job' end def initialize - raise Unsupported, "DJ queue sampler disabled" if Agent.config[:'instrumentation.delayed_job'] == 'disabled' + raise Unsupported, 'DJ queue sampler disabled' if Agent.config[:'instrumentation.delayed_job'] == 'disabled' raise Unsupported, "DJ queue sampling unsupported with backend '#{::Delayed::Worker.backend}'" unless self.class.supported_backend? - raise Unsupported, "No DJ worker present. Skipping DJ queue sampler" unless NewRelic::DelayedJobInjection.worker_name + raise Unsupported, 'No DJ worker present. Skipping DJ queue sampler' unless NewRelic::DelayedJobInjection.worker_name end def record_failed_jobs(value) - NewRelic::Agent.record_metric("Workers/DelayedJob/failed_jobs", value) + NewRelic::Agent.record_metric('Workers/DelayedJob/failed_jobs', value) end def record_locked_jobs(value) - NewRelic::Agent.record_metric("Workers/DelayedJob/locked_jobs", value) + NewRelic::Agent.record_metric('Workers/DelayedJob/locked_jobs', value) end FAILED_QUERY = 'failed_at is not NULL'.freeze @@ -74,10 +74,10 @@ def poll def record_queue_length_metrics counts = [] - counts << record_counts_by("queue", "name") if ::Delayed::Job.instance_methods.include?(:queue) - counts << record_counts_by("priority") + counts << record_counts_by('queue', 'name') if ::Delayed::Job.instance_methods.include?(:queue) + counts << record_counts_by('priority') - all_metric = "Workers/DelayedJob/queue_length/all" + all_metric = 'Workers/DelayedJob/queue_length/all' NewRelic::Agent.record_metric(all_metric, counts.max) end @@ -87,7 +87,7 @@ def record_counts_by(column_name, metric_node = column_name) all_count = 0 queue_counts(column_name).each do |column_val, count| all_count += count - column_val = "default" if column_val.nil? || column_val == NewRelic::EMPTY_STR + column_val = 'default' if column_val.nil? || column_val == NewRelic::EMPTY_STR metric = "Workers/DelayedJob/queue_length/#{metric_node}/#{column_val}" NewRelic::Agent.record_metric(metric, count) end diff --git a/lib/new_relic/agent/samplers/memory_sampler.rb b/lib/new_relic/agent/samplers/memory_sampler.rb index 903e979934..b141008dc1 100644 --- a/lib/new_relic/agent/samplers/memory_sampler.rb +++ b/lib/new_relic/agent/samplers/memory_sampler.rb @@ -23,18 +23,18 @@ def initialize @sampler = ProcStatus.new if !@sampler.can_run? ::NewRelic::Agent.logger.debug("Error attempting to use /proc/#{$$}/status file for reading memory. Using ps command instead.") - @sampler = ShellPS.new("ps -o rsz") + @sampler = ShellPS.new('ps -o rsz') else ::NewRelic::Agent.logger.debug("Using /proc/#{$$}/status for reading process memory.") end elsif platform.include?('darwin9') # 10.5 - @sampler = ShellPS.new("ps -o rsz") - elsif platform =~ /darwin(1|2)\d+/ # >= 10.6 - @sampler = ShellPS.new("ps -o rss") + @sampler = ShellPS.new('ps -o rsz') + elsif /darwin(1|2)\d+/.match?(platform) # >= 10.6 + @sampler = ShellPS.new('ps -o rss') elsif platform.include?('freebsd') - @sampler = ShellPS.new("ps -o rss") + @sampler = ShellPS.new('ps -o rss') elsif platform.include?('solaris') - @sampler = ShellPS.new("/usr/bin/ps -o rss -p") + @sampler = ShellPS.new('/usr/bin/ps -o rss -p') end raise Unsupported, "Unsupported platform for getting memory: #{platform}" if @sampler.nil? @@ -64,7 +64,7 @@ def platform def poll sample = @sampler.get_sample if sample - NewRelic::Agent.record_metric("Memory/Physical", sample) + NewRelic::Agent.record_metric('Memory/Physical', sample) end end @@ -106,7 +106,7 @@ def get_memory end def to_s - "JRuby Java heap sampler" + 'JRuby Java heap sampler' end end @@ -140,7 +140,7 @@ def to_s class ProcStatus < Base # Returns the amount of resident memory this process is using in MB def get_memory - proc_status = File.open(proc_status_file, "r") { |f| f.read_nonblock(4096).strip } + proc_status = File.open(proc_status_file, 'r') { |f| f.read_nonblock(4096).strip } if proc_status =~ /RSS:\s*(\d+) kB/i return $1.to_f / 1024.0 end diff --git a/lib/new_relic/agent/samplers/object_sampler.rb b/lib/new_relic/agent/samplers/object_sampler.rb index cd82ac1887..e5ef0eeeea 100644 --- a/lib/new_relic/agent/samplers/object_sampler.rb +++ b/lib/new_relic/agent/samplers/object_sampler.rb @@ -16,7 +16,7 @@ def self.supported_on_this_platform? def poll live_objects = ObjectSpace.live_objects - NewRelic::Agent.record_metric("GC/objects", live_objects) + NewRelic::Agent.record_metric('GC/objects', live_objects) end end end diff --git a/lib/new_relic/agent/span_event_aggregator.rb b/lib/new_relic/agent/span_event_aggregator.rb index a90542c0a6..885ff6ca1c 100644 --- a/lib/new_relic/agent/span_event_aggregator.rb +++ b/lib/new_relic/agent/span_event_aggregator.rb @@ -18,7 +18,7 @@ class SpanEventAggregator < EventAggregator def record(priority: nil, event: nil, &blk) unless event || priority && blk - raise ArgumentError, "Expected priority and block, or event" + raise ArgumentError, 'Expected priority and block, or event' end return unless enabled? @@ -29,9 +29,9 @@ def record(priority: nil, event: nil, &blk) end end - SUPPORTABILITY_TOTAL_SEEN = "Supportability/SpanEvent/TotalEventsSeen".freeze - SUPPORTABILITY_TOTAL_SENT = "Supportability/SpanEvent/TotalEventsSent".freeze - SUPPORTABILITY_DISCARDED = "Supportability/SpanEvent/Discarded".freeze + SUPPORTABILITY_TOTAL_SEEN = 'Supportability/SpanEvent/TotalEventsSeen'.freeze + SUPPORTABILITY_TOTAL_SENT = 'Supportability/SpanEvent/TotalEventsSent'.freeze + SUPPORTABILITY_DISCARDED = 'Supportability/SpanEvent/Discarded'.freeze def after_harvest(metadata) seen = metadata[:seen] diff --git a/lib/new_relic/agent/span_event_primitive.rb b/lib/new_relic/agent/span_event_primitive.rb index 2262a011ab..2e33cc4931 100644 --- a/lib/new_relic/agent/span_event_primitive.rb +++ b/lib/new_relic/agent/span_event_primitive.rb @@ -37,8 +37,8 @@ module SpanEventPrimitive PEER_HOSTNAME_KEY = 'peer.hostname' SPAN_KIND_KEY = 'span.kind' ENTRY_POINT_KEY = 'nr.entryPoint' - TRUSTED_PARENT_KEY = "trustedParentId" - TRACING_VENDORS_KEY = "tracingVendors" + TRUSTED_PARENT_KEY = 'trustedParentId' + TRACING_VENDORS_KEY = 'tracingVendors' TRANSACTION_NAME_KEY = 'transaction.name' # Strings for static values of the event structure diff --git a/lib/new_relic/agent/sql_sampler.rb b/lib/new_relic/agent/sql_sampler.rb index f9dc67f757..0ff0f08a08 100644 --- a/lib/new_relic/agent/sql_sampler.rb +++ b/lib/new_relic/agent/sql_sampler.rb @@ -154,12 +154,12 @@ def notice_sql(sql, metric_name, config, duration, state = nil, explainer = nil, end end - PRIORITY = "priority".freeze + PRIORITY = 'priority'.freeze def distributed_trace_attributes(state) transaction = state.current_transaction params = nil - if transaction && transaction.distributed_tracer.distributed_trace_payload + if transaction&.distributed_tracer&.distributed_trace_payload params = {} payload = transaction.distributed_tracer.distributed_trace_payload DistributedTraceAttributes.copy_from_transaction(transaction, payload, params) diff --git a/lib/new_relic/agent/stats.rb b/lib/new_relic/agent/stats.rb index 14536889c6..c54ffa8cd2 100644 --- a/lib/new_relic/agent/stats.rb +++ b/lib/new_relic/agent/stats.rb @@ -118,7 +118,7 @@ def increment_count(value = 1) def inspect_full variables = instance_variables.map do |ivar| "#{ivar.to_s}=#{instance_variable_get(ivar).inspect}" - end.join(" ") + end.join(' ') "#" end diff --git a/lib/new_relic/agent/synthetics_event_aggregator.rb b/lib/new_relic/agent/synthetics_event_aggregator.rb index 9467433137..10ed757acf 100644 --- a/lib/new_relic/agent/synthetics_event_aggregator.rb +++ b/lib/new_relic/agent/synthetics_event_aggregator.rb @@ -37,7 +37,7 @@ def record_dropped_synthetics(metadata) NewRelic::Agent.logger.debug("Synthetics transaction event limit (#{metadata[:capacity]}) reached. Further synthetics events this harvest period dropped.") engine = NewRelic::Agent.instance.stats_engine - engine.tl_record_supportability_metric_count("SyntheticsEventAggregator/synthetics_events_dropped", num_dropped) + engine.tl_record_supportability_metric_count('SyntheticsEventAggregator/synthetics_events_dropped', num_dropped) end end end diff --git a/lib/new_relic/agent/system_info.rb b/lib/new_relic/agent/system_info.rb index 5080ac574a..5d72674445 100644 --- a/lib/new_relic/agent/system_info.rb +++ b/lib/new_relic/agent/system_info.rb @@ -128,7 +128,7 @@ def self.parse_cpuinfo(cpuinfo) num_physical_packages = cores.keys.map(&:first).uniq.size num_physical_cores = cores.size - num_logical_processors = cores.values.reduce(0, :+) + num_logical_processors = cores.values.sum if num_physical_cores == 0 num_logical_processors = total_processors @@ -202,7 +202,7 @@ def self.parse_docker_container_id(cgroup_info) return when /docker/ ::NewRelic::Agent.logger.debug("Cgroup indicates docker but container_id unrecognized: '#{cpu_cgroup}'") - ::NewRelic::Agent.increment_metric("Supportability/utilization/docker/error") + ::NewRelic::Agent.increment_metric('Supportability/utilization/docker/error') return else ::NewRelic::Agent.logger.debug("Ignoring unrecognized cgroup ID format: '#{cpu_cgroup}'") @@ -211,7 +211,7 @@ def self.parse_docker_container_id(cgroup_info) if container_id && container_id.size != 64 ::NewRelic::Agent.logger.debug("Found docker container_id with invalid length: #{container_id}") - ::NewRelic::Agent.increment_metric("Supportability/utilization/docker/error") + ::NewRelic::Agent.increment_metric('Supportability/utilization/docker/error') nil else container_id @@ -242,7 +242,7 @@ def self.parse_cgroup_ids(cgroup_info) def self.proc_try_read(path) return nil unless File.exist?(path) - content = String.new('') + content = +'' File.open(path) do |f| loop do begin @@ -289,8 +289,8 @@ def self.boot_id if bid.ascii_only? if bid.empty? - ::NewRelic::Agent.logger.debug("boot_id not found in /proc/sys/kernel/random/boot_id") - ::NewRelic::Agent.increment_metric("Supportability/utilization/boot_id/error") + ::NewRelic::Agent.logger.debug('boot_id not found in /proc/sys/kernel/random/boot_id') + ::NewRelic::Agent.increment_metric('Supportability/utilization/boot_id/error') nil elsif bid.bytesize == 36 @@ -298,19 +298,19 @@ def self.boot_id else ::NewRelic::Agent.logger.debug("Found boot_id with invalid length: #{bid}") - ::NewRelic::Agent.increment_metric("Supportability/utilization/boot_id/error") + ::NewRelic::Agent.increment_metric('Supportability/utilization/boot_id/error') bid[0, 128] end else ::NewRelic::Agent.logger.debug("Found boot_id with non-ASCII characters: #{bid}") - ::NewRelic::Agent.increment_metric("Supportability/utilization/boot_id/error") + ::NewRelic::Agent.increment_metric('Supportability/utilization/boot_id/error') nil end else - ::NewRelic::Agent.logger.debug("boot_id not found in /proc/sys/kernel/random/boot_id") - ::NewRelic::Agent.increment_metric("Supportability/utilization/boot_id/error") + ::NewRelic::Agent.logger.debug('boot_id not found in /proc/sys/kernel/random/boot_id') + ::NewRelic::Agent.increment_metric('Supportability/utilization/boot_id/error') nil end diff --git a/lib/new_relic/agent/threading/agent_thread.rb b/lib/new_relic/agent/threading/agent_thread.rb index 3b364475c7..21e16d53c0 100644 --- a/lib/new_relic/agent/threading/agent_thread.rb +++ b/lib/new_relic/agent/threading/agent_thread.rb @@ -45,7 +45,7 @@ def self.bucket_thread(thread, profile_agent_code) # THREAD_LOCAL_ACCESS if txn && !txn.recording_web_transaction? :background - elsif txn && txn.recording_web_transaction? + elsif txn&.recording_web_transaction? :request else :other diff --git a/lib/new_relic/agent/threading/backtrace_node.rb b/lib/new_relic/agent/threading/backtrace_node.rb index 8c5babfbb5..d074f718ca 100644 --- a/lib/new_relic/agent/threading/backtrace_node.rb +++ b/lib/new_relic/agent/threading/backtrace_node.rb @@ -70,7 +70,7 @@ def aggregate(backtrace) end def dump_string - result = String.new("#") + result = +"#" child_results = @children.map { |c| c.dump_string(2) }.join("\n") result << "\n" unless child_results.empty? result << child_results @@ -116,8 +116,8 @@ def complete_array_conversion def dump_string(indent = 0) @file, @method, @line_no = parse_backtrace_frame(@raw_line) indentation = ' ' * indent - result = String.new("#{indentation}#") + result = +"#{indentation}#" child_results = @children.map { |c| c.dump_string(indent + 2) }.join("\n") result << "\n" unless child_results.empty? result << child_results diff --git a/lib/new_relic/agent/threading/backtrace_service.rb b/lib/new_relic/agent/threading/backtrace_service.rb index e0a268658c..3e2bdaa0f9 100644 --- a/lib/new_relic/agent/threading/backtrace_service.rb +++ b/lib/new_relic/agent/threading/backtrace_service.rb @@ -6,7 +6,7 @@ module NewRelic module Agent module Threading class BacktraceService - ALL_TRANSACTIONS = "**ALL**".freeze + ALL_TRANSACTIONS = '**ALL**'.freeze def self.is_supported? !is_resque? @@ -41,9 +41,7 @@ def initialize(event_listener = nil) @overhead_percent_threshold = new_value end - if event_listener - event_listener.subscribe(:transaction_finished, &method(:on_transaction_finished)) - end + event_listener&.subscribe(:transaction_finished, &method(:on_transaction_finished)) end # Public interface @@ -221,9 +219,7 @@ def buffer_backtrace_for_thread(thread, timestamp, backtrace, bucket) # This method is expected to be called with @lock held. def aggregate_global_backtrace(backtrace, bucket, thread) - if @profiles[ALL_TRANSACTIONS] - @profiles[ALL_TRANSACTIONS].aggregate(backtrace, bucket, thread) - end + @profiles[ALL_TRANSACTIONS]&.aggregate(backtrace, bucket, thread) end # This method is expected to be called with @lock held. diff --git a/lib/new_relic/agent/threading/thread_profile.rb b/lib/new_relic/agent/threading/thread_profile.rb index 41765bb271..19a78a0fce 100644 --- a/lib/new_relic/agent/threading/thread_profile.rb +++ b/lib/new_relic/agent/threading/thread_profile.rb @@ -72,7 +72,7 @@ def convert_N_trace_nodes_to_arrays(count_to_keep) # THREAD_LOCAL_ACCESS all_nodes = @traces.values.map { |n| n.flattened }.flatten NewRelic::Agent.instance.stats_engine - .tl_record_supportability_metric_count("ThreadProfiler/NodeCount", all_nodes.size) + .tl_record_supportability_metric_count('ThreadProfiler/NodeCount', all_nodes.size) all_nodes.sort! do |a, b| # we primarily prefer higher runnable_count @@ -103,10 +103,10 @@ def generate_traces convert_N_trace_nodes_to_arrays(THREAD_PROFILER_NODES) { - "OTHER" => @traces[:other].as_array, - "REQUEST" => @traces[:request].as_array, - "AGENT" => @traces[:agent].as_array, - "BACKGROUND" => @traces[:background].as_array + 'OTHER' => @traces[:other].as_array, + 'REQUEST' => @traces[:request].as_array, + 'AGENT' => @traces[:agent].as_array, + 'BACKGROUND' => @traces[:background].as_array } end diff --git a/lib/new_relic/agent/timestamp_sampled_buffer.rb b/lib/new_relic/agent/timestamp_sampled_buffer.rb index 507f55e737..9959542aad 100644 --- a/lib/new_relic/agent/timestamp_sampled_buffer.rb +++ b/lib/new_relic/agent/timestamp_sampled_buffer.rb @@ -7,7 +7,7 @@ module NewRelic module Agent class TimestampSampledBuffer < PrioritySampledBuffer - TIMESTAMP_KEY = "timestamp".freeze + TIMESTAMP_KEY = 'timestamp'.freeze private diff --git a/lib/new_relic/agent/tracer.rb b/lib/new_relic/agent/tracer.rb index 74e9f91b81..4e1b0383e4 100644 --- a/lib/new_relic/agent/tracer.rb +++ b/lib/new_relic/agent/tracer.rb @@ -107,7 +107,7 @@ def in_transaction(name: nil, current_transaction.notice_error(exception) raise ensure - finishable.finish if finishable + finishable&.finish end end @@ -246,8 +246,8 @@ def start_segment(name:, log_error('start_segment', exception) end - UNKNOWN = "Unknown".freeze - OTHER = "other".freeze + UNKNOWN = 'Unknown'.freeze + OTHER = 'other'.freeze # Creates and starts a datastore segment used to time # datastore operations. @@ -355,7 +355,8 @@ def capture_segment_error(segment) yield rescue => exception - if segment && segment.is_a?(Transaction::AbstractSegment) + # needs else branch coverage + if segment && segment.is_a?(Transaction::AbstractSegment) # rubocop:disable Style/SafeNavigation segment.notice_error(exception) end raise @@ -425,6 +426,7 @@ def thread_block_with_current_transaction(*args, segment_name:, parent: nil, &bl begin if current_txn NewRelic::Agent::Tracer.state.current_transaction = current_txn + current_txn.async = true segment_name += "/Thread#{::Thread.current.object_id}/Fiber#{::Fiber.current.object_id}" if NewRelic::Agent.config[:'thread_ids_enabled'] segment = NewRelic::Agent::Tracer.start_segment(name: segment_name, parent: parent) end @@ -487,7 +489,8 @@ def push_traced(should_trace) end def pop_traced - @untraced.pop if @untraced + # needs else branch coverage + @untraced.pop if @untraced # rubocop:disable Style/SafeNavigation end def is_execution_traced? @@ -507,7 +510,5 @@ def is_sql_recorded? attr_accessor :sql_sampler_transaction_data end end - - TransactionState = Tracer end end diff --git a/lib/new_relic/agent/transaction.rb b/lib/new_relic/agent/transaction.rb index 01ddf3f9ba..ec515c1a32 100644 --- a/lib/new_relic/agent/transaction.rb +++ b/lib/new_relic/agent/transaction.rb @@ -23,10 +23,10 @@ class Transaction include Tracing # for nested transactions - NESTED_TRANSACTION_PREFIX = "Nested/" - CONTROLLER_PREFIX = "Controller/" - MIDDLEWARE_PREFIX = "Middleware/Rack/" - OTHER_TRANSACTION_PREFIX = "OtherTransaction/" + NESTED_TRANSACTION_PREFIX = 'Nested/' + CONTROLLER_PREFIX = 'Controller/' + MIDDLEWARE_PREFIX = 'Middleware/Rack/' + OTHER_TRANSACTION_PREFIX = 'OtherTransaction/' TASK_PREFIX = "#{OTHER_TRANSACTION_PREFIX}Background/" RAKE_PREFIX = "#{OTHER_TRANSACTION_PREFIX}Rake/" MESSAGE_PREFIX = "#{OTHER_TRANSACTION_PREFIX}Message/" @@ -37,21 +37,21 @@ class Transaction WEB_TRANSACTION_CATEGORIES = [:web, :controller, :uri, :rack, :sinatra, :grape, :middleware, :action_cable].freeze - MIDDLEWARE_SUMMARY_METRICS = ["Middleware/all"].freeze - WEB_SUMMARY_METRIC = "HttpDispatcher" + MIDDLEWARE_SUMMARY_METRICS = ['Middleware/all'].freeze + WEB_SUMMARY_METRIC = 'HttpDispatcher' OTHER_SUMMARY_METRIC = "#{OTHER_TRANSACTION_PREFIX}all" - QUEUE_TIME_METRIC = "WebFrontend/QueueTime" + QUEUE_TIME_METRIC = 'WebFrontend/QueueTime' - APDEX_S = "S" - APDEX_T = "T" - APDEX_F = "F" - APDEX_ALL_METRIC = "ApdexAll" - APDEX_METRIC = "Apdex" - APDEX_OTHER_METRIC = "ApdexOther" - APDEX_TXN_METRIC_PREFIX = "Apdex/" - APDEX_OTHER_TXN_METRIC_PREFIX = "ApdexOther/Transaction/" + APDEX_S = 'S' + APDEX_T = 'T' + APDEX_F = 'F' + APDEX_ALL_METRIC = 'ApdexAll' + APDEX_METRIC = 'Apdex' + APDEX_OTHER_METRIC = 'ApdexOther' + APDEX_TXN_METRIC_PREFIX = 'Apdex/' + APDEX_OTHER_TXN_METRIC_PREFIX = 'ApdexOther/Transaction/' - JRUBY_CPU_TIME_ERROR = "Error calculating JRuby CPU Time" + JRUBY_CPU_TIME_ERROR = 'Error calculating JRuby CPU Time' # A Time instance for the start time, never nil attr_accessor :start_time @@ -155,7 +155,7 @@ def self.recording_web_transaction? # THREAD_LOCAL_ACCESS NewRelic::Agent.record_api_supportability_metric(:recording_web_transaction?) txn = tl_current - txn && txn.recording_web_transaction? + txn&.recording_web_transaction? end def self.apdex_bucket(duration, failed, apdex_t) @@ -181,20 +181,21 @@ def self.add_agent_attribute(key, value, default_destinations) def add_agent_attribute(key, value, default_destinations) @attributes.add_agent_attribute(key, value, default_destinations) - current_segment.add_agent_attribute(key, value) if current_segment + # the following line needs else branch coverage + current_segment.add_agent_attribute(key, value) if current_segment # rubocop:disable Style/SafeNavigation end def self.merge_untrusted_agent_attributes(attributes, prefix, default_destinations) if txn = tl_current txn.merge_untrusted_agent_attributes(attributes, prefix, default_destinations) else - NewRelic::Agent.logger.debug("Attempted to merge untrusted attributes without transaction") + NewRelic::Agent.logger.debug('Attempted to merge untrusted attributes without transaction') end end def merge_untrusted_agent_attributes(attributes, prefix, default_destinations) @attributes.merge_untrusted_agent_attributes(attributes, prefix, default_destinations) - current_segment.merge_untrusted_agent_attributes(attributes, prefix, default_destinations) if current_segment + current_segment&.merge_untrusted_agent_attributes(attributes, prefix, default_destinations) end @@java_classes_loaded = false @@ -209,7 +210,7 @@ def merge_untrusted_agent_attributes(attributes, prefix, default_destinations) end end - def initialize(category, options) + def initialize(category, options) # rubocop:disable Metrics/AbcSize @nesting_max_depth = 0 @current_segment_by_thread = {} @current_segment_lock = Mutex.new @@ -309,15 +310,15 @@ def priority end def referer - @request_attributes && @request_attributes.referer + @request_attributes&.referer end def request_path - @request_attributes && @request_attributes.request_path + @request_attributes&.request_path end def request_port - @request_attributes && @request_attributes.port + @request_attributes&.port end # This transaction-local hash may be used as temporary storage by @@ -533,7 +534,7 @@ def finish commit!(initial_segment.name) unless @ignore_this_transaction rescue => e - NewRelic::Agent.logger.error("Exception during Transaction#finish", e) + NewRelic::Agent.logger.error('Exception during Transaction#finish', e) nil ensure state.reset @@ -594,9 +595,7 @@ def assign_agent_attributes add_agent_attribute(:'response.headers.contentType', response_content_type, default_destinations) end - if @request_attributes - @request_attributes.assign_agent_attributes(self) - end + @request_attributes&.assign_agent_attributes(self) display_host = Agent.config[:'process_host.display_name'] unless display_host == NewRelic::Agent::Hostname.get @@ -735,15 +734,19 @@ def merge_metrics def record_exceptions error_recorded = false @exceptions.each do |exception, options| - options[:uri] ||= request_path if request_path - options[:port] = request_port if request_port - options[:metric] = best_name - options[:attributes] = @attributes - - span_id = options.delete(:span_id) - error_recorded = !!agent.error_collector.notice_error(exception, options, span_id) || error_recorded + error_recorded = record_exception(exception, options, error_recorded) end - payload[:error] = error_recorded if payload + payload&.[]=(:error, error_recorded) + end + + def record_exception(exception, options, error_recorded) + options[:uri] ||= request_path if request_path + options[:port] = request_port if request_port + options[:metric] = best_name + options[:attributes] = @attributes + + span_id = options.delete(:span_id) + !!agent.error_collector.notice_error(exception, options, span_id) || error_recorded end # Do not call this. Invoke the class method instead. diff --git a/lib/new_relic/agent/transaction/abstract_segment.rb b/lib/new_relic/agent/transaction/abstract_segment.rb index 92e677ea1e..072348aaf3 100644 --- a/lib/new_relic/agent/transaction/abstract_segment.rb +++ b/lib/new_relic/agent/transaction/abstract_segment.rb @@ -56,7 +56,7 @@ def start @start_time ||= Process.clock_gettime(Process::CLOCK_REALTIME) return unless transaction - parent.child_start(self) if parent + parent&.child_start(self) end def finish @@ -228,7 +228,7 @@ def child_complete(segment) if finished? transaction.async = true - parent.descendant_complete(self, segment) if parent + parent&.descendant_complete(self, segment) end end @@ -262,19 +262,19 @@ def add_child_timing(segment) def force_finish finish - NewRelic::Agent.logger.warn("Segment: #{name} was unfinished at " \ - "the end of transaction. Timing information for this segment's" \ - "parent #{parent.name} in #{transaction.best_name} may be inaccurate.") + NewRelic::Agent.logger.send(transaction.async? ? :debug : :warn, "Segment: #{name} was unfinished at " \ + "the end of transaction. Timing information for this segment's " \ + "parent #{parent&.name} in #{transaction.best_name} may be inaccurate.") end def run_complete_callbacks segment_complete - parent.child_complete(self) if parent + parent&.child_complete(self) transaction.segment_complete(self) end def record_metrics - raise NotImplementedError, "Subclasses must implement record_metrics" + raise NotImplementedError, 'Subclasses must implement record_metrics' end # callback for subclasses to override diff --git a/lib/new_relic/agent/transaction/datastore_segment.rb b/lib/new_relic/agent/transaction/datastore_segment.rb index d6c529a7d1..01d119b83c 100644 --- a/lib/new_relic/agent/transaction/datastore_segment.rb +++ b/lib/new_relic/agent/transaction/datastore_segment.rb @@ -24,7 +24,7 @@ def initialize(product, operation, collection = nil, host = nil, port_path_or_id @nosql_statement = nil @record_sql = true set_instance_info(host, port_path_or_id) - @database_name = database_name ? database_name.to_s : nil + @database_name = database_name&.to_s super(Datastores::MetricHelper.scoped_metric_for(product, operation, collection), nil, start_time) diff --git a/lib/new_relic/agent/transaction/distributed_tracer.rb b/lib/new_relic/agent/transaction/distributed_tracer.rb index 198428efbe..f14a2bd88d 100644 --- a/lib/new_relic/agent/transaction/distributed_tracer.rb +++ b/lib/new_relic/agent/transaction/distributed_tracer.rb @@ -35,7 +35,7 @@ def accept_incoming_request(request, transport_type = nil) end def caller_transport_type - @caller_transport_type ||= "Unknown" + @caller_transport_type ||= 'Unknown' end def accept_transport_type_from_api(value) @@ -68,8 +68,9 @@ def append_payload(payload) ) end - def log_request_headers(headers, direction = "OUTGOING") - NewRelic::Agent.logger.debug("#{direction} REQUEST HEADERS: #{headers}") + def log_request_headers(headers, direction = 'OUTGOING') + printed_headers = headers.is_a?(NewRelic::Agent::HTTPClients::AbstractRequest) ? headers.headers : headers + NewRelic::Agent.logger.debug("#{direction} REQUEST HEADERS: #{printed_headers}") end def insert_headers(headers) @@ -82,12 +83,12 @@ def insert_headers(headers) end def consume_message_headers(headers, tracer_state, transport_type) - log_request_headers(headers, "INCOMING") + log_request_headers(headers, 'INCOMING') consume_message_distributed_tracing_headers(headers, transport_type) consume_message_cross_app_tracing_headers(headers, tracer_state) consume_message_synthetics_headers(headers) rescue => e - NewRelic::Agent.logger.error("Error in consume_message_headers", e) + NewRelic::Agent.logger.error('Error in consume_message_headers', e) end def assign_intrinsics @@ -135,7 +136,7 @@ def consume_message_synthetics_headers(headers) transaction.synthetics_payload = incoming_payload end rescue => e - NewRelic::Agent.logger.error("Error in consume_message_synthetics_header", e) + NewRelic::Agent.logger.error('Error in consume_message_synthetics_header', e) end def consume_message_distributed_tracing_headers(headers, transport_type) diff --git a/lib/new_relic/agent/transaction/distributed_tracing.rb b/lib/new_relic/agent/transaction/distributed_tracing.rb index cb0e7f2dc5..e022e122eb 100644 --- a/lib/new_relic/agent/transaction/distributed_tracing.rb +++ b/lib/new_relic/agent/transaction/distributed_tracing.rb @@ -13,7 +13,7 @@ module DistributedTracing attr_accessor :distributed_trace_payload attr_writer :distributed_trace_payload_created - SUPPORTABILITY_DISTRIBUTED_TRACE = "Supportability/DistributedTrace" + SUPPORTABILITY_DISTRIBUTED_TRACE = 'Supportability/DistributedTrace' CREATE_PREFIX = "#{SUPPORTABILITY_DISTRIBUTED_TRACE}/CreatePayload" ACCEPT_PREFIX = "#{SUPPORTABILITY_DISTRIBUTED_TRACE}/AcceptPayload" IGNORE_PREFIX = "#{ACCEPT_PREFIX}/Ignored" @@ -30,10 +30,10 @@ module DistributedTracing IGNORE_ACCEPT_MAJOR_VERSION_METRIC = "#{IGNORE_PREFIX}/MajorVersion" IGNORE_ACCEPT_UNTRUSTED_ACCOUNT_METRIC = "#{IGNORE_PREFIX}/UntrustedAccount" - LBRACE = "{" + LBRACE = '{' NULL_PAYLOAD = 'null' - NEWRELIC_TRACE_KEY = "HTTP_NEWRELIC" + NEWRELIC_TRACE_KEY = 'HTTP_NEWRELIC' def accept_distributed_tracing_incoming_request(request) return unless Agent.config[:'distributed_tracing.enabled'] @@ -55,7 +55,7 @@ def create_distributed_trace_payload payload rescue => e NewRelic::Agent.increment_metric(CREATE_EXCEPTION_METRIC) - NewRelic::Agent.logger.warn("Failed to create distributed trace payload", e) + NewRelic::Agent.logger.warn('Failed to create distributed trace payload', e) nil end @@ -75,7 +75,7 @@ def accept_distributed_trace_payload(payload) true rescue => e NewRelic::Agent.increment_metric(ACCEPT_EXCEPTION_METRIC) - NewRelic::Agent.logger.warn("Failed to accept distributed trace payload", e) + NewRelic::Agent.logger.warn('Failed to accept distributed trace payload', e) false end @@ -114,7 +114,7 @@ def decode_payload(payload) decoded rescue => e NewRelic::Agent.increment_metric(ACCEPT_PARSE_EXCEPTION_METRIC) - NewRelic::Agent.logger.warn("Error parsing distributed trace payload", e) + NewRelic::Agent.logger.warn('Error parsing distributed trace payload', e) nil end diff --git a/lib/new_relic/agent/transaction/external_request_segment.rb b/lib/new_relic/agent/transaction/external_request_segment.rb index d480e39676..303b0d7a76 100644 --- a/lib/new_relic/agent/transaction/external_request_segment.rb +++ b/lib/new_relic/agent/transaction/external_request_segment.rb @@ -16,10 +16,10 @@ class ExternalRequestSegment < Segment NR_SYNTHETICS_HEADER = 'X-NewRelic-Synthetics' APP_DATA_KEY = 'NewRelicAppData' - EXTERNAL_ALL = "External/all" - EXTERNAL_ALL_WEB = "External/allWeb" - EXTERNAL_ALL_OTHER = "External/allOther" - MISSING_STATUS_CODE = "MissingHTTPStatusCode" + EXTERNAL_ALL = 'External/all' + EXTERNAL_ALL_WEB = 'External/allWeb' + EXTERNAL_ALL_OTHER = 'External/allOther' + MISSING_STATUS_CODE = 'MissingHTTPStatusCode' attr_reader :library, :uri, :procedure, :http_status_code attr_writer :record_agent_attributes @@ -62,14 +62,14 @@ def record_agent_attributes? # @api public def add_request_headers(request) process_host_header(request) - synthetics_header = transaction && transaction.raw_synthetics_header + synthetics_header = transaction&.raw_synthetics_header insert_synthetics_header(request, synthetics_header) if synthetics_header return unless record_metrics? transaction.distributed_tracer.insert_headers(request) rescue => e - NewRelic::Agent.logger.error("Error in add_request_headers", e) + NewRelic::Agent.logger.error('Error in add_request_headers', e) end # This method extracts app data from an external response if present. If @@ -92,10 +92,10 @@ def read_response_headers(response) @app_data = data update_segment_name else - NewRelic::Agent.logger.debug("External segment response has invalid cross_app_id") + NewRelic::Agent.logger.debug('External segment response has invalid cross_app_id') end rescue => e - NewRelic::Agent.logger.error("Error in read_response_headers", e) + NewRelic::Agent.logger.error('Error in read_response_headers', e) end def cross_app_request? # :nodoc: @@ -154,7 +154,7 @@ def get_request_metadata end rescue => e - NewRelic::Agent.logger.error("error during get_request_metadata", e) + NewRelic::Agent.logger.error('error during get_request_metadata', e) end # Process obfuscated +String+ sent from a called application that is also running a New Relic agent and @@ -176,13 +176,13 @@ def process_response_metadata(response_metadata) @app_data = app_data update_segment_name else - NewRelic::Agent.logger.error("error processing response metadata: invalid/non-trusted ID") + NewRelic::Agent.logger.error('error processing response metadata: invalid/non-trusted ID') end end nil rescue => e - NewRelic::Agent.logger.error("error during process_response_metadata", e) + NewRelic::Agent.logger.error('error during process_response_metadata', e) end def record_metrics diff --git a/lib/new_relic/agent/transaction/message_broker_segment.rb b/lib/new_relic/agent/transaction/message_broker_segment.rb index 32fbc98513..4d0d145ff1 100644 --- a/lib/new_relic/agent/transaction/message_broker_segment.rb +++ b/lib/new_relic/agent/transaction/message_broker_segment.rb @@ -91,7 +91,7 @@ def transaction_assigned transaction.distributed_tracer.log_request_headers(headers) end rescue => e - NewRelic::Agent.logger.error("Error during message header processing", e) + NewRelic::Agent.logger.error('Error during message header processing', e) end end end diff --git a/lib/new_relic/agent/transaction/request_attributes.rb b/lib/new_relic/agent/transaction/request_attributes.rb index 45318b7600..ad68d27be0 100644 --- a/lib/new_relic/agent/transaction/request_attributes.rb +++ b/lib/new_relic/agent/transaction/request_attributes.rb @@ -11,7 +11,7 @@ class RequestAttributes attr_reader :request_path, :referer, :accept, :content_length, :content_type, :host, :port, :user_agent, :request_method - HTTP_ACCEPT_HEADER_KEY = "HTTP_ACCEPT".freeze + HTTP_ACCEPT_HEADER_KEY = 'HTTP_ACCEPT'.freeze def initialize(request) @request_path = path_from_request(request) @@ -85,7 +85,7 @@ def referer_from_request(request) # rails construct the PATH_INFO enviroment variable improperly and we're generally # being defensive. - ROOT_PATH = "/".freeze + ROOT_PATH = '/'.freeze def path_from_request(request) path = attribute_from_request(request, :path) || '' diff --git a/lib/new_relic/agent/transaction/segment.rb b/lib/new_relic/agent/transaction/segment.rb index 4cdda45d90..b8b1f7a9dc 100644 --- a/lib/new_relic/agent/transaction/segment.rb +++ b/lib/new_relic/agent/transaction/segment.rb @@ -32,7 +32,7 @@ def self.merge_untrusted_agent_attributes(attributes, prefix, default_destinatio if segment = NewRelic::Agent::Tracer.current_segment segment.merge_untrusted_agent_attributes(attributes, prefix, default_destinations) else - NewRelic::Agent.logger.debug("Attempted to merge untrusted attributes without segment") + NewRelic::Agent.logger.debug('Attempted to merge untrusted attributes without segment') end end diff --git a/lib/new_relic/agent/transaction/synthetics_sample_buffer.rb b/lib/new_relic/agent/transaction/synthetics_sample_buffer.rb index 1d0631013f..5b384ec156 100644 --- a/lib/new_relic/agent/transaction/synthetics_sample_buffer.rb +++ b/lib/new_relic/agent/transaction/synthetics_sample_buffer.rb @@ -13,7 +13,7 @@ def capacity end def allow_sample?(sample) - sample.synthetics_resource_id != nil + !sample.synthetics_resource_id.nil? end def truncate_samples diff --git a/lib/new_relic/agent/transaction/trace.rb b/lib/new_relic/agent/transaction/trace.rb index 6e3a2fda10..2052a2818d 100644 --- a/lib/new_relic/agent/transaction/trace.rb +++ b/lib/new_relic/agent/transaction/trace.rb @@ -14,7 +14,7 @@ class FinishedTraceError < StandardError; end attr_accessor :transaction_name, :guid, :attributes, :node_count, :finished, :threshold, :profile - ROOT = "ROOT".freeze + ROOT = 'ROOT'.freeze def initialize(start_time) @start_time = start_time diff --git a/lib/new_relic/agent/transaction/trace_context.rb b/lib/new_relic/agent/transaction/trace_context.rb index 054ebec626..26b267161f 100644 --- a/lib/new_relic/agent/transaction/trace_context.rb +++ b/lib/new_relic/agent/transaction/trace_context.rb @@ -20,7 +20,7 @@ def trace_state_entry_key end end - SUPPORTABILITY_PREFIX = "Supportability/TraceContext" + SUPPORTABILITY_PREFIX = 'Supportability/TraceContext' CREATE_PREFIX = "#{SUPPORTABILITY_PREFIX}/Create" ACCEPT_PREFIX = "#{SUPPORTABILITY_PREFIX}/Accept" TRACESTATE_PREFIX = "#{SUPPORTABILITY_PREFIX}/TraceState" @@ -73,7 +73,7 @@ def insert_trace_context_header(header, format = NewRelic::FORMAT_NON_RACK) true rescue Exception => e NewRelic::Agent.increment_metric(CREATE_EXCEPTION_METRIC) - NewRelic::Agent.logger.warn("Failed to create trace context payload", e) + NewRelic::Agent.logger.warn('Failed to create trace context payload', e) false end @@ -95,7 +95,7 @@ def create_trace_state def create_trace_state_payload unless Agent.config[:'distributed_tracing.enabled'] - NewRelic::Agent.logger.warn("Not configured to create WC3 trace context payload") + NewRelic::Agent.logger.warn('Not configured to create WC3 trace context payload') return end @@ -144,7 +144,7 @@ def accept_trace_context(header_data) true rescue => e NewRelic::Agent.increment_metric(ACCEPT_EXCEPTION_METRIC) - NewRelic::Agent.logger.warn("Failed to accept trace context payload", e) + NewRelic::Agent.logger.warn('Failed to accept trace context payload', e) false end diff --git a/lib/new_relic/agent/transaction/trace_node.rb b/lib/new_relic/agent/transaction/trace_node.rb index 419da176b9..c0f929fbf4 100644 --- a/lib/new_relic/agent/transaction/trace_node.rb +++ b/lib/new_relic/agent/transaction/trace_node.rb @@ -58,7 +58,7 @@ def path_string end def to_s_compact - str = String.new('') + str = +'' str << metric_name if children.any? str << "{#{children.map { |cs| cs.to_s_compact }.join(',')}}" @@ -67,9 +67,9 @@ def to_s_compact end def to_debug_str(depth) - tab = String.new(' ') * depth + tab = (+' ') * depth s = tab.clone - s << ">> #{'%3i ms' % (@entry_timestamp * 1000)} [#{self.class.name.split("::").last}] #{metric_name} \n" + s << ">> #{'%3i ms' % (@entry_timestamp * 1000)} [#{self.class.name.split('::').last}] #{metric_name} \n" unless params.empty? params.each do |k, v| s << "#{tab} -#{'%-16s' % k}: #{v.to_s[0..80]}\n" @@ -136,10 +136,8 @@ def [](key) def each_node(&block) yield(self) - if @children - @children.each do |node| - node.each_node(&block) - end + @children&.each do |node| + node.each_node(&block) end end @@ -149,11 +147,14 @@ def each_node_with_nest_tracking(&block) summary = yield(self) summary.current_nest_count += 1 if summary + # no then branch coverage + # rubocop:disable Style/SafeNavigation if @children @children.each do |node| node.each_node_with_nest_tracking(&block) end end + # rubocop:enable Style/SafeNavigation summary.current_nest_count -= 1 if summary end diff --git a/lib/new_relic/agent/transaction/tracing.rb b/lib/new_relic/agent/transaction/tracing.rb index 5166455920..1ed62d462c 100644 --- a/lib/new_relic/agent/transaction/tracing.rb +++ b/lib/new_relic/agent/transaction/tracing.rb @@ -52,8 +52,8 @@ def finalize_segments segments.each { |s| s.finalize } end - WEB_TRANSACTION_TOTAL_TIME = "WebTransactionTotalTime".freeze - OTHER_TRANSACTION_TOTAL_TIME = "OtherTransactionTotalTime".freeze + WEB_TRANSACTION_TOTAL_TIME = 'WebTransactionTotalTime'.freeze + OTHER_TRANSACTION_TOTAL_TIME = 'OtherTransactionTotalTime'.freeze def record_total_time_metrics total_time_metric = if recording_web_transaction? diff --git a/lib/new_relic/agent/transaction/transaction_sample_buffer.rb b/lib/new_relic/agent/transaction/transaction_sample_buffer.rb index 88cf33b3d8..9700a90449 100644 --- a/lib/new_relic/agent/transaction/transaction_sample_buffer.rb +++ b/lib/new_relic/agent/transaction/transaction_sample_buffer.rb @@ -63,7 +63,7 @@ def full? # # This value will be forcibly capped by the max_capacity def capacity - raise NotImplementedError.new("TransactionSampleBuffer subclasses must provide a capacity override") + raise NotImplementedError.new('TransactionSampleBuffer subclasses must provide a capacity override') end # Apply hard upper limit to the capacity to prevent users from diff --git a/lib/new_relic/agent/transaction_error_primitive.rb b/lib/new_relic/agent/transaction_error_primitive.rb index 5b00810cf2..38333ef533 100644 --- a/lib/new_relic/agent/transaction_error_primitive.rb +++ b/lib/new_relic/agent/transaction_error_primitive.rb @@ -28,11 +28,11 @@ module TransactionErrorPrimitive SAMPLED_KEY = 'sampled'.freeze GUID_KEY = 'nr.transactionGuid'.freeze REFERRING_TRANSACTION_GUID_KEY = 'nr.referringTransactionGuid'.freeze - SYNTHETICS_RESOURCE_ID_KEY = "nr.syntheticsResourceId".freeze - SYNTHETICS_JOB_ID_KEY = "nr.syntheticsJobId".freeze - SYNTHETICS_MONITOR_ID_KEY = "nr.syntheticsMonitorId".freeze - PRIORITY_KEY = "priority".freeze - SPAN_ID_KEY = "spanId".freeze + SYNTHETICS_RESOURCE_ID_KEY = 'nr.syntheticsResourceId'.freeze + SYNTHETICS_JOB_ID_KEY = 'nr.syntheticsJobId'.freeze + SYNTHETICS_MONITOR_ID_KEY = 'nr.syntheticsMonitorId'.freeze + PRIORITY_KEY = 'priority'.freeze + SPAN_ID_KEY = 'spanId'.freeze def create(noticed_error, payload, span_id) [ diff --git a/lib/new_relic/agent/transaction_event_aggregator.rb b/lib/new_relic/agent/transaction_event_aggregator.rb index 64e0cc9f9a..39000404b7 100644 --- a/lib/new_relic/agent/transaction_event_aggregator.rb +++ b/lib/new_relic/agent/transaction_event_aggregator.rb @@ -18,7 +18,7 @@ class TransactionEventAggregator < EventAggregator def record(priority: nil, event: nil, &blk) unless event || priority && blk - raise ArgumentError, "Expected priority and block, or event" + raise ArgumentError, 'Expected priority and block, or event' end return unless enabled? @@ -38,7 +38,7 @@ def after_harvest(metadata) end def record_sampling_rate(metadata) # THREAD_LOCAL_ACCESS - NewRelic::Agent.logger.debug("Sampled %d / %d (%.1f %%) requests this cycle, %d / %d (%.1f %%) since startup" % [ + NewRelic::Agent.logger.debug('Sampled %d / %d (%.1f %%) requests this cycle, %d / %d (%.1f %%) since startup' % [ metadata[:captured], metadata[:seen], (metadata[:captured].to_f / metadata[:seen] * 100.0), @@ -48,8 +48,8 @@ def record_sampling_rate(metadata) # THREAD_LOCAL_ACCESS ]) engine = NewRelic::Agent.instance.stats_engine - engine.tl_record_supportability_metric_count("TransactionEventAggregator/requests", metadata[:seen]) - engine.tl_record_supportability_metric_count("TransactionEventAggregator/samples", metadata[:captured]) + engine.tl_record_supportability_metric_count('TransactionEventAggregator/requests', metadata[:seen]) + engine.tl_record_supportability_metric_count('TransactionEventAggregator/samples', metadata[:captured]) end end end diff --git a/lib/new_relic/agent/transaction_event_primitive.rb b/lib/new_relic/agent/transaction_event_primitive.rb index f430b8149e..f1fc99a0aa 100644 --- a/lib/new_relic/agent/transaction_event_primitive.rb +++ b/lib/new_relic/agent/transaction_event_primitive.rb @@ -35,9 +35,9 @@ module TransactionEventPrimitive CAT_REFERRING_PATH_HASH_KEY = 'nr.referringPathHash' CAT_ALTERNATE_PATH_HASHES_KEY = 'nr.alternatePathHashes' APDEX_PERF_ZONE_KEY = 'nr.apdexPerfZone' - SYNTHETICS_RESOURCE_ID_KEY = "nr.syntheticsResourceId" - SYNTHETICS_JOB_ID_KEY = "nr.syntheticsJobId" - SYNTHETICS_MONITOR_ID_KEY = "nr.syntheticsMonitorId" + SYNTHETICS_RESOURCE_ID_KEY = 'nr.syntheticsResourceId' + SYNTHETICS_JOB_ID_KEY = 'nr.syntheticsJobId' + SYNTHETICS_MONITOR_ID_KEY = 'nr.syntheticsMonitorId' def create(payload) intrinsics = { diff --git a/lib/new_relic/agent/transaction_sampler.rb b/lib/new_relic/agent/transaction_sampler.rb index a4100fe383..d9614a6c3d 100644 --- a/lib/new_relic/agent/transaction_sampler.rb +++ b/lib/new_relic/agent/transaction_sampler.rb @@ -34,13 +34,13 @@ def initialize threshold = Agent.config[:'transaction_tracer.transaction_threshold'] ::NewRelic::Agent.logger.debug("Transaction tracing threshold is #{threshold} seconds.") else - ::NewRelic::Agent.logger.debug("Transaction traces will not be sent to the New Relic service.") + ::NewRelic::Agent.logger.debug('Transaction traces will not be sent to the New Relic service.') end end Agent.config.register_callback(:'transaction_tracer.record_sql') do |config| if config == 'raw' - ::NewRelic::Agent.logger.warn("Agent is configured to send raw SQL to the service") + ::NewRelic::Agent.logger.warn('Agent is configured to send raw SQL to the service') end end end @@ -81,7 +81,7 @@ def prepare_samples(samples) begin sample.prepare_to_send! rescue => e - NewRelic::Agent.logger.error("Failed to prepare transaction trace. Error: ", e) + NewRelic::Agent.logger.error('Failed to prepare transaction trace. Error: ', e) false else true diff --git a/lib/new_relic/agent/transaction_time_aggregator.rb b/lib/new_relic/agent/transaction_time_aggregator.rb index bf19314d7a..c0e445ab3b 100644 --- a/lib/new_relic/agent/transaction_time_aggregator.rb +++ b/lib/new_relic/agent/transaction_time_aggregator.rb @@ -101,7 +101,8 @@ def current_thread def thread_is_alive?(thread_id) thread = thread_by_id(thread_id) - thread && thread.alive? + # needs else branch coverage + thread && thread.alive? # rubocop:disable Style/SafeNavigation rescue StandardError false end @@ -144,10 +145,13 @@ def transaction_time_in_thread(timestamp, thread_id, entry) elapsed end + # this method has no test coverage def log_missing_elapsed_transaction_time - transaction_name = Tracer.current_transaction && + # rubocop:disable Style/SafeNavigation + transaction_name = transaction_name = Tracer.current_transaction && Tracer.current_transaction.best_name || - "unknown" + 'unknown' + # rubocop:enable Style/SafeNavigation NewRelic::Agent.logger.warn("Unable to calculate elapsed transaction time for #{transaction_name}") end end diff --git a/lib/new_relic/agent/utilization/aws.rb b/lib/new_relic/agent/utilization/aws.rb index 0856ac46b4..8ecb2532b3 100644 --- a/lib/new_relic/agent/utilization/aws.rb +++ b/lib/new_relic/agent/utilization/aws.rb @@ -37,7 +37,7 @@ def imds_token end end - vendor_name "aws" + vendor_name 'aws' endpoint "#{IMDS_BASE_URL}/dynamic/instance-identity/document" keys IMDS_KEYS headers 'X-aws-ec2-metadata-token' => -> { imds_token } diff --git a/lib/new_relic/agent/utilization/azure.rb b/lib/new_relic/agent/utilization/azure.rb index 2ff289ef7a..cf47c2a617 100644 --- a/lib/new_relic/agent/utilization/azure.rb +++ b/lib/new_relic/agent/utilization/azure.rb @@ -6,9 +6,9 @@ module NewRelic module Agent module Utilization class Azure < Vendor - vendor_name "azure" - endpoint "http://169.254.169.254/metadata/instance/compute?api-version=2017-03-01" - headers "Metadata" => "true" + vendor_name 'azure' + endpoint 'http://169.254.169.254/metadata/instance/compute?api-version=2017-03-01' + headers 'Metadata' => 'true' keys %w[vmId name vmSize location] key_transforms :to_sym end diff --git a/lib/new_relic/agent/utilization/gcp.rb b/lib/new_relic/agent/utilization/gcp.rb index a578c9f63a..06d67cac29 100644 --- a/lib/new_relic/agent/utilization/gcp.rb +++ b/lib/new_relic/agent/utilization/gcp.rb @@ -8,9 +8,9 @@ module NewRelic module Agent module Utilization class GCP < Vendor - vendor_name "gcp" - endpoint "http://metadata.google.internal/computeMetadata/v1/instance/?recursive=true" - headers "Metadata-Flavor" => "Google" + vendor_name 'gcp' + endpoint 'http://metadata.google.internal/computeMetadata/v1/instance/?recursive=true' + headers 'Metadata-Flavor' => 'Google' keys %w[id machineType name zone] key_transforms :to_sym diff --git a/lib/new_relic/agent/utilization/pcf.rb b/lib/new_relic/agent/utilization/pcf.rb index a0aad26fb3..81068488a7 100644 --- a/lib/new_relic/agent/utilization/pcf.rb +++ b/lib/new_relic/agent/utilization/pcf.rb @@ -8,7 +8,7 @@ module NewRelic module Agent module Utilization class PCF < Vendor - vendor_name "pcf" + vendor_name 'pcf' keys %w[CF_INSTANCE_GUID CF_INSTANCE_IP MEMORY_LIMIT] key_transforms [:downcase, :to_sym] diff --git a/lib/new_relic/agent/utilization/vendor.rb b/lib/new_relic/agent/utilization/vendor.rb index 0271adb72d..bceac3932e 100644 --- a/lib/new_relic/agent/utilization/vendor.rb +++ b/lib/new_relic/agent/utilization/vendor.rb @@ -133,7 +133,7 @@ def valid_length?(value) def valid_chars?(value) value.each_char do |ch| - next if ch =~ VALID_CHARS + next if VALID_CHARS.match?(ch) code_point = ch[0].ord # this works in Ruby 1.8.7 - 2.1.2 next if code_point >= 0x80 diff --git a/lib/new_relic/agent/vm/monotonic_gc_profiler.rb b/lib/new_relic/agent/vm/monotonic_gc_profiler.rb index f09f322454..a70bfac0fc 100644 --- a/lib/new_relic/agent/vm/monotonic_gc_profiler.rb +++ b/lib/new_relic/agent/vm/monotonic_gc_profiler.rb @@ -34,7 +34,7 @@ def total_time_s end else NewRelic::Agent.logger.log_once(:warn, :gc_profiler_disabled, - "Tried to measure GC time, but GC::Profiler was not enabled.") + 'Tried to measure GC time, but GC::Profiler was not enabled.') end @total_time_s diff --git a/lib/new_relic/agent/vm/mri_vm.rb b/lib/new_relic/agent/vm/mri_vm.rb index 8eb595b730..93dedba5f0 100644 --- a/lib/new_relic/agent/vm/mri_vm.rb +++ b/lib/new_relic/agent/vm/mri_vm.rb @@ -82,18 +82,19 @@ def gather_thread_stats(snap) def supports?(key) case key - when :gc_runs, :total_allocated_object, :heap_live, :heap_free, :thread_count + when :gc_runs, + :total_allocated_object, + :heap_live, + :heap_free, + :thread_count, + :major_gc_count, + :minor_gc_count, + :constant_cache_invalidations true when :gc_total_time NewRelic::LanguageSupport.gc_profiler_enabled? - when :major_gc_count - RUBY_VERSION >= '2.1.0' - when :minor_gc_count - RUBY_VERSION >= '2.1.0' when :method_cache_invalidations - RUBY_VERSION >= '2.1.0' && RUBY_VERSION < '3.0.0' - when :constant_cache_invalidations - RUBY_VERSION >= '2.1.0' + RUBY_VERSION < '3.0.0' when :constant_cache_misses RUBY_VERSION >= '3.2.0' else diff --git a/lib/new_relic/agent/worker_loop.rb b/lib/new_relic/agent/worker_loop.rb index f4454296b5..5a47875c6b 100644 --- a/lib/new_relic/agent/worker_loop.rb +++ b/lib/new_relic/agent/worker_loop.rb @@ -88,7 +88,7 @@ def run_task raise rescue => e # Don't blow out the stack for anything that hasn't already propagated - ::NewRelic::Agent.logger.error("Error running task in Agent Worker Loop:", e) + ::NewRelic::Agent.logger.error('Error running task in Agent Worker Loop:', e) end end end diff --git a/lib/new_relic/cli/command.rb b/lib/new_relic/cli/command.rb index d01ba47989..099dc1ea78 100644 --- a/lib/new_relic/cli/command.rb +++ b/lib/new_relic/cli/command.rb @@ -38,7 +38,7 @@ def initialize(command_line_args) else # parse command line args. Throw an exception on a bad arg. @options = options do |opts| - opts.on("-h", "Show this help") { raise CommandFailure, opts.to_s } + opts.on('-h', 'Show this help') { raise CommandFailure, opts.to_s } end @leftover = @options.parse(command_line_args) end @@ -60,11 +60,11 @@ def self.run extra = [] options = ARGV.options do |opts| script_name = File.basename($0) - if script_name =~ /newrelic_cmd$/ + if /newrelic_cmd$/.match?(script_name) $stdout.puts "warning: the 'newrelic_cmd' script has been renamed 'newrelic'" script_name = 'newrelic' end - opts.banner = "Usage: #{script_name} [ #{@command_names.join(" | ")} ] [options]" + opts.banner = "Usage: #{script_name} [ #{@command_names.join(' | ')} ] [options]" opts.separator("use '#{script_name} -h' to see detailed command options") opts end diff --git a/lib/new_relic/cli/commands/deployments.rb b/lib/new_relic/cli/commands/deployments.rb index 2192de0b7d..a191d1dd92 100644 --- a/lib/new_relic/cli/commands/deployments.rb +++ b/lib/new_relic/cli/commands/deployments.rb @@ -16,7 +16,7 @@ class NewRelic::Cli::Deployments < NewRelic::Cli::Command attr_reader :control - def self.command; "deployments"; end + def self.command; 'deployments'; end # Initialize the deployment uploader with command line args. # Use -h to see options. @@ -33,7 +33,8 @@ def initialize(command_line_args) @changelog = nil @user = nil super(command_line_args) - @description ||= @leftover && @leftover.join(" ") + # needs else branch coverage + @description ||= @leftover && @leftover.join(' ') # rubocop:disable Style/SafeNavigation @user ||= ENV['USER'] control.env = @environment if @environment @@ -71,17 +72,17 @@ def run end if !api_v1? && (@revision.nil? || @revision.empty?) - raise "revision required when using New Relic REST API v2 with api_key. Pass in revision using: -r, --revision=REV" + raise 'revision required when using New Relic REST API v2 with api_key. Pass in revision using: -r, --revision=REV' end request = if api_v1? - uri = "/deployments.xml" - create_request(uri, {'x-license-key' => @license_key}, "application/octet-stream").tap do |req| + uri = '/deployments.xml' + create_request(uri, {'x-license-key' => @license_key}, 'application/octet-stream').tap do |req| set_params_v1(req) end else uri = "/v2/applications/#{application_id}/deployments.json" - create_request(uri, {"Api-Key" => @api_key}, "application/json").tap do |req| + create_request(uri, {'Api-Key' => @api_key}, 'application/json').tap do |req| set_params_v2(req) end end @@ -92,7 +93,7 @@ def run if response.is_a?(Net::HTTPSuccess) info("Recorded deployment to '#{@appname}' (#{@description || Time.now})") else - err_string = REXML::Document.new(response.body).elements['errors/error'].map(&:to_s).join("; ") rescue response.message + err_string = REXML::Document.new(response.body).elements['errors/error'].map(&:to_s).join('; ') rescue response.message raise NewRelic::Cli::Command::CommandFailure, "Deployment not recorded: #{err_string}" end rescue SystemCallError, SocketError => e @@ -150,7 +151,7 @@ def set_params_v1(request) def set_params_v2(request) request.body = { - "deployment" => { + 'deployment' => { :description => @description, :user => @user, :revision => @revision, @@ -161,25 +162,25 @@ def set_params_v2(request) def options OptionParser.new(%Q(Usage: #{$0} #{self.class.command} [OPTIONS] ["description"] ), 40) do |o| - o.separator("OPTIONS:") - o.on("-a", "--appname=NAME", String, - "Set the application name.", - "Default is app_name setting in newrelic.yml. Available only when using API v1.") { |e| @appname = e } - o.on("-i", "--appid=ID", String, - "Set the application ID", - "If not provided, will connect to the New Relic collector to get it") { |i| @application_id = i } - o.on("-e", "--environment=name", String, - "Override the (RAILS|RUBY|RACK)_ENV setting", + o.separator('OPTIONS:') + o.on('-a', '--appname=NAME', String, + 'Set the application name.', + 'Default is app_name setting in newrelic.yml. Available only when using API v1.') { |e| @appname = e } + o.on('-i', '--appid=ID', String, + 'Set the application ID', + 'If not provided, will connect to the New Relic collector to get it') { |i| @application_id = i } + o.on('-e', '--environment=name', String, + 'Override the (RAILS|RUBY|RACK)_ENV setting', "currently: #{control.env}") { |e| @environment = e } - o.on("-u", "--user=USER", String, - "Specify the user deploying, for information only", + o.on('-u', '--user=USER', String, + 'Specify the user deploying, for information only', "Default: #{@user || ''}") { |u| @user = u } - o.on("-r", "--revision=REV", String, - "Specify the revision being deployed. Required when using New Relic REST API v2") { |r| @revision = r } - o.on("-l", "--license-key=KEY", String, - "Specify the license key of the account for the app being deployed") { |l| @license_key = l } - o.on("-c", "--changes", - "Read in a change log from the standard input") { @changelog = STDIN.read } + o.on('-r', '--revision=REV', String, + 'Specify the revision being deployed. Required when using New Relic REST API v2') { |r| @revision = r } + o.on('-l', '--license-key=KEY', String, + 'Specify the license key of the account for the app being deployed') { |l| @license_key = l } + o.on('-c', '--changes', + 'Read in a change log from the standard input') { @changelog = STDIN.read } yield(o) if block_given? end end diff --git a/lib/new_relic/cli/commands/install.rb b/lib/new_relic/cli/commands/install.rb index 05f2432bc3..ea3a4b72c3 100644 --- a/lib/new_relic/cli/commands/install.rb +++ b/lib/new_relic/cli/commands/install.rb @@ -7,9 +7,9 @@ require 'erb' class NewRelic::Cli::Install < NewRelic::Cli::Command - NO_LICENSE_KEY = "" + NO_LICENSE_KEY = '' - def self.command; "install"; end + def self.command; 'install'; end # Use -h to see options. # When command_line_args is a hash, we are invoking directly and @@ -25,22 +25,22 @@ def initialize(command_line_args = {}) super(command_line_args) if @dest_dir.nil? # Install a newrelic.yml file into the local config directory. - if File.directory?("config") - @dest_dir = "config" + if File.directory?('config') + @dest_dir = 'config' else - @dest_dir = "." + @dest_dir = '.' end end @license_key ||= NO_LICENSE_KEY - @app_name ||= @leftover.join(" ") + @app_name ||= @leftover.join(' ') @agent_version = NewRelic::VERSION::STRING - raise CommandFailure.new("Application name required.", @options) unless @app_name && @app_name.size > 0 + raise CommandFailure.new('Application name required.', @options) unless @app_name && @app_name.size > 0 end def run - dest_file = File.expand_path(@dest_dir + "/newrelic.yml") + dest_file = File.expand_path(@dest_dir + '/newrelic.yml') if File.exist?(dest_file) && !@force - raise NewRelic::Cli::Command::CommandFailure, "newrelic.yml file already exists. Use --force flag to overwrite." + raise NewRelic::Cli::Command::CommandFailure, 'newrelic.yml file already exists. Use --force flag to overwrite.' end File.open(dest_file, 'w') { |out| out.puts(content) } @@ -63,7 +63,7 @@ def run end def content - @src_file ||= File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "..", "..", "newrelic.yml")) + @src_file ||= File.expand_path(File.join(File.dirname(__FILE__), '..', '..', '..', '..', 'newrelic.yml')) template = File.read(@src_file) ERB.new(template).result(binding) end @@ -72,10 +72,10 @@ def content def options OptionParser.new("Usage: #{$0} #{self.class.command} [ OPTIONS] 'application name'", 40) do |o| - o.on("-f", "--force", "Overwrite newrelic.yml if it exists") { |e| @force = true } - o.on("-l", "--license_key=NAME", String, - "Use the given license key") { |e| @license_key = e } - o.on("-d", "--destdir=name", String, + o.on('-f', '--force', 'Overwrite newrelic.yml if it exists') { |e| @force = true } + o.on('-l', '--license_key=NAME', String, + 'Use the given license key') { |e| @license_key = e } + o.on('-d', '--destdir=name', String, "Write the newrelic.yml to the given directory, default is '.'") { |e| @dest_dir = e } yield(o) if block_given? end diff --git a/lib/new_relic/collection_helper.rb b/lib/new_relic/collection_helper.rb index 9005c36506..5ba0992f2d 100644 --- a/lib/new_relic/collection_helper.rb +++ b/lib/new_relic/collection_helper.rb @@ -40,7 +40,7 @@ def flatten(object) when nil then '' when object.instance_of?(String) then object when String then String.new(object) # convert string subclasses to strings - else String.new("#<#{object.class}>") + else +"#<#{object.class}>" end end @@ -52,7 +52,7 @@ def truncate(string, len = DEFAULT_TRUNCATION_SIZE) real_string = flatten(string) if real_string.size > len real_string = real_string.slice(0...len) - real_string << "..." + real_string << '...' end real_string else diff --git a/lib/new_relic/constants.rb b/lib/new_relic/constants.rb index 58a5c5280b..847b73a994 100644 --- a/lib/new_relic/constants.rb +++ b/lib/new_relic/constants.rb @@ -7,16 +7,16 @@ module NewRelic EMPTY_ARRAY = [].freeze EMPTY_HASH = {}.freeze - EMPTY_STR = "" + EMPTY_STR = '' - HTTP = "HTTP" - HTTPS = "HTTPS" - UNKNOWN = "Unknown" + HTTP = 'HTTP' + HTTPS = 'HTTPS' + UNKNOWN = 'Unknown' FORMAT_NON_RACK = 0 FORMAT_RACK = 1 - NEWRELIC_KEY = "newrelic" + NEWRELIC_KEY = 'newrelic' CANDIDATE_NEWRELIC_KEYS = [ NEWRELIC_KEY, 'NEWRELIC', @@ -24,8 +24,8 @@ module NewRelic 'Newrelic' ].freeze - TRACEPARENT_KEY = "traceparent" - TRACESTATE_KEY = "tracestate" + TRACEPARENT_KEY = 'traceparent' + TRACESTATE_KEY = 'tracestate' STANDARD_OUT = 'STDOUT' @@ -34,6 +34,5 @@ module NewRelic HTTP_NEWRELIC_KEY = "HTTP_#{NEWRELIC_KEY.upcase}" CONNECT_RETRY_PERIODS = [15, 15, 30, 60, 120, 300] - MIN_RETRY_PERIOD = 15 MAX_RETRY_PERIOD = 300 end diff --git a/lib/new_relic/control/class_methods.rb b/lib/new_relic/control/class_methods.rb index 8e3b1f4717..bdd900fa70 100644 --- a/lib/new_relic/control/class_methods.rb +++ b/lib/new_relic/control/class_methods.rb @@ -35,8 +35,8 @@ def new_instance # nb this does not 'load test' the framework, it loads the 'test framework' def load_test_framework - config = File.expand_path(File.join('..', '..', '..', '..', "test", "config", "newrelic.yml"), __FILE__) - require "config/test_control" + config = File.expand_path(File.join('..', '..', '..', '..', 'test', 'config', 'newrelic.yml'), __FILE__) + require 'config/test_control' NewRelic::Control::Frameworks::Test.new(local_env, config) end @@ -54,7 +54,7 @@ def load_framework_class(framework) # The root directory for the plugin or gem def newrelic_root - File.expand_path(File.join("..", "..", "..", ".."), __FILE__) + File.expand_path(File.join('..', '..', '..', '..'), __FILE__) end def camelize(snake_case_name) diff --git a/lib/new_relic/control/frameworks/rails.rb b/lib/new_relic/control/frameworks/rails.rb index 9705f7a46c..e53d326897 100644 --- a/lib/new_relic/control/frameworks/rails.rb +++ b/lib/new_relic/control/frameworks/rails.rb @@ -44,26 +44,38 @@ def rails_config # find a config and use that. def init_config(options = {}) @config = options[:config] - # Install the dependency detection, - if rails_config && ::Rails.configuration.respond_to?(:after_initialize) - rails_config.after_initialize do - # This will insure we load all the instrumentation as late as possible. If the agent - # is not enabled, it will load a limited amount of instrumentation. - DependencyDetection.detect! - end + install_dependency_detection + install_browser_monitoring_and_agent_hooks + rescue => e + ::NewRelic::Agent.logger.error('Failure during init_config for Rails. Is Rails required in a non-Rails ' \ + 'app? Set NEW_RELIC_FRAMEWORK=ruby to avoid this message. The Ruby agent ' \ + 'will continue running, but Rails-specific features may be missing. ' \ + "#{e.class} - #{e.message}") + end + + def install_dependency_detection + return unless rails_config && ::Rails.configuration.respond_to?(:after_initialize) + + rails_config.after_initialize do + # This will insure we load all the instrumentation as late as + # possible. If the agent is not enabled, it will load a limited + # amount of instrumentation. + DependencyDetection.detect! end + end + + def install_browser_monitoring_and_agent_hooks + return unless rails_config + if !Agent.config[:agent_enabled] - # Might not be running if it does not think mongrel, thin, passenger, etc - # is running, if it thinks it's a rake task, or if the agent_enabled is false. - ::NewRelic::Agent.logger.info("New Relic Agent not running.") + # Might not be running if it does not think mongrel, thin, + # passenger, etc. is running, if it thinks it's a rake task, or + # if the agent_enabled is false. + ::NewRelic::Agent.logger.info('New Relic Agent not running. Skipping browser monitoring and agent hooks.') else install_browser_monitoring(rails_config) install_agent_hooks(rails_config) end - rescue => e - ::NewRelic::Agent.logger.error("Failure during init_config for Rails. Is Rails required in a non-Rails app? Set NEW_RELIC_FRAMEWORK=ruby to avoid this message.", - "The Ruby agent will continue running, but Rails-specific features may be missing.", - e) end def install_agent_hooks(config) @@ -77,9 +89,9 @@ def install_agent_hooks(config) return unless NewRelic::Rack::AgentHooks.needed? config.middleware.use(NewRelic::Rack::AgentHooks) - ::NewRelic::Agent.logger.debug("Installed New Relic Agent Hooks middleware") + ::NewRelic::Agent.logger.debug('Installed New Relic Agent Hooks middleware') rescue => e - ::NewRelic::Agent.logger.warn("Error installing New Relic Agent Hooks middleware", e) + ::NewRelic::Agent.logger.warn('Error installing New Relic Agent Hooks middleware', e) end end @@ -93,9 +105,9 @@ def install_browser_monitoring(config) begin require 'new_relic/rack/browser_monitoring' config.middleware.use(NewRelic::Rack::BrowserMonitoring) - ::NewRelic::Agent.logger.debug("Installed New Relic Browser Monitoring middleware") + ::NewRelic::Agent.logger.debug('Installed New Relic Browser Monitoring middleware') rescue => e - ::NewRelic::Agent.logger.warn("Error installing New Relic Browser Monitoring middleware", e) + ::NewRelic::Agent.logger.warn('Error installing New Relic Browser Monitoring middleware', e) end end end diff --git a/lib/new_relic/control/instance_methods.rb b/lib/new_relic/control/instance_methods.rb index 1fe5738984..44e8f1dd47 100644 --- a/lib/new_relic/control/instance_methods.rb +++ b/lib/new_relic/control/instance_methods.rb @@ -82,10 +82,10 @@ def determine_env(options) if @started_in_env && @started_in_env != env Agent.logger.error("Attempted to start agent in #{env.inspect} environment, but agent was already running " \ "in #{@started_in_env.inspect}", "The agent will continue running in #{@started_in_env.inspect}. To " \ - "alter this, ensure the desired environment is set before the agent starts.") + 'alter this, ensure the desired environment is set before the agent starts.') else Agent.logger.info("Starting the New Relic agent version #{NewRelic::VERSION::STRING} in #{env.inspect} " \ - "environment.", "To prevent agent startup add a NEW_RELIC_AGENT_ENABLED=false environment variable or " \ + 'environment.', 'To prevent agent startup add a NEW_RELIC_AGENT_ENABLED=false environment variable or ' \ "modify the #{env.inspect} section of your newrelic.yml.") end @@ -106,9 +106,9 @@ def security_settings_valid? end def handle_invalid_security_settings - NewRelic::Agent.logger.error("Security Policies and High Security Mode cannot both be present in the agent " \ - "configuration. If Security Policies have been set for your account, please ensure the " \ - "security_policies_token is set but high_security is disabled (default).") + NewRelic::Agent.logger.error('Security Policies and High Security Mode cannot both be present in the agent ' \ + 'configuration. If Security Policies have been set for your account, please ensure the ' \ + 'security_policies_token is set but high_security is disabled (default).') install_shim end diff --git a/lib/new_relic/control/instrumentation.rb b/lib/new_relic/control/instrumentation.rb index db502b3430..00cb66d2d2 100644 --- a/lib/new_relic/control/instrumentation.rb +++ b/lib/new_relic/control/instrumentation.rb @@ -64,7 +64,7 @@ def _install_instrumentation DependencyDetection.detect! ruby_deprecation rails_32_deprecation - ::NewRelic::Agent.logger.info("Finished instrumentation") + ::NewRelic::Agent.logger.info('Finished instrumentation') end end diff --git a/lib/new_relic/control/private_instance_methods.rb b/lib/new_relic/control/private_instance_methods.rb index 2640f491e6..bcd14c7a81 100644 --- a/lib/new_relic/control/private_instance_methods.rb +++ b/lib/new_relic/control/private_instance_methods.rb @@ -12,7 +12,7 @@ module PrivateInstanceMethods def configure_high_security if security_settings_valid? && Agent.config[:high_security] - Agent.logger.info("Installing high security configuration based on local configuration") + Agent.logger.info('Installing high security configuration based on local configuration') Agent.config.replace_or_add_config(Agent::Configuration::HighSecuritySource.new(Agent.config)) end end diff --git a/lib/new_relic/dependency_detection.rb b/lib/new_relic/dependency_detection.rb index bc90651ebc..49a7ce2c41 100644 --- a/lib/new_relic/dependency_detection.rb +++ b/lib/new_relic/dependency_detection.rb @@ -35,19 +35,6 @@ def dependency_by_name(name) @items.find { |i| i.name == name } end - def installed?(name) - item = dependency_by_name(name) - item && item.executed - end - - def items - @items - end - - def items=(new_items) - @items = new_items - end - class Dependent attr_reader :executed attr_accessor :name @@ -83,7 +70,7 @@ def source_location_for(klass, method_name) # Given "NewRelic::Agent::Instrumentation::NetHTTP::Prepend" # Will extract "NetHTTP" which is in the 2nd to last spot def extract_supportability_name(instrumenting_module) - instrumenting_module.to_s.split("::")[-2] + instrumenting_module.to_s.split('::')[-2] end def log_and_instrument(method, instrumenting_module, supportability_name) @@ -94,20 +81,20 @@ def log_and_instrument(method, instrumenting_module, supportability_name) end def prepend_instrument(target_class, instrumenting_module, supportability_name = nil) - log_and_instrument("Prepend", instrumenting_module, supportability_name) do + log_and_instrument('Prepend', instrumenting_module, supportability_name) do target_class.send(:prepend, instrumenting_module) end end def chain_instrument(instrumenting_module, supportability_name = nil) - log_and_instrument("MethodChaining", instrumenting_module, supportability_name) do + log_and_instrument('MethodChaining', instrumenting_module, supportability_name) do instrumenting_module.instrument! end end def chain_instrument_target(target, instrumenting_module, supportability_name = nil) NewRelic::Agent.logger.info("Installing deferred #{target} instrumentation") - log_and_instrument("MethodChaining", instrumenting_module, supportability_name) do + log_and_instrument('MethodChaining', instrumenting_module, supportability_name) do instrumenting_module.instrument!(target) end end diff --git a/lib/new_relic/environment_report.rb b/lib/new_relic/environment_report.rb index 37026c1620..b9ea4b330b 100644 --- a/lib/new_relic/environment_report.rb +++ b/lib/new_relic/environment_report.rb @@ -52,7 +52,7 @@ def self.registered_reporters=(logic) # though so try it if the above fails. Bundler.load.specs.map do |spec| version = (spec.respond_to?(:version) && spec.version) - spec.name + (version ? "(#{version})" : "") + spec.name + (version ? "(#{version})" : '') end end end @@ -118,19 +118,19 @@ def to_a def record_value(data, key, value) data[key] = value - Agent.record_metric("Supportability/EnvironmentReport/success", 0.0) + Agent.record_metric('Supportability/EnvironmentReport/success', 0.0) Agent.record_metric("Supportability/EnvironmentReport/success/#{key}", 0.0) end def record_empty_value(key, value) Agent.logger.debug("EnvironmentReport ignoring value for #{key.inspect} which came back falsey: #{value.inspect}") - Agent.record_metric("Supportability/EnvironmentReport/empty", 0.0) + Agent.record_metric('Supportability/EnvironmentReport/empty', 0.0) Agent.record_metric("Supportability/EnvironmentReport/empty/#{key}", 0.0) end def rescue_initialize(key, exception) Agent.logger.debug("EnvironmentReport failed to retrieve value for #{key.inspect}: #{exception}") - Agent.record_metric("Supportability/EnvironmentReport/error", 0.0) + Agent.record_metric('Supportability/EnvironmentReport/error', 0.0) Agent.record_metric("Supportability/EnvironmentReport/error/#{key}", 0.0) end end diff --git a/lib/new_relic/helper.rb b/lib/new_relic/helper.rb index 0cd415030a..7d17c89908 100644 --- a/lib/new_relic/helper.rb +++ b/lib/new_relic/helper.rb @@ -63,7 +63,8 @@ def run_command(command) raise NewRelic::CommandRunFailedError.new("Failed to run command '#{command}': #{message}") end - output.chomp if output + # needs else branch coverage + output.chomp if output # rubocop:disable Style/SafeNavigation end # TODO: Open3 defers the actual execution of a binary to Process.spawn, diff --git a/lib/new_relic/language_support.rb b/lib/new_relic/language_support.rb index 5014c27764..e95fe1c391 100644 --- a/lib/new_relic/language_support.rb +++ b/lib/new_relic/language_support.rb @@ -62,7 +62,7 @@ def constantize(const_name) # # Can't help if the constant isn't a class... if result.is_a?(Module) - expected_name = "#{namespace}::#{name}".gsub(/^Object::/, "") + expected_name = "#{namespace}::#{name}".gsub(/^Object::/, '') return unless expected_name == result.to_s end diff --git a/lib/new_relic/latest_changes.rb b/lib/new_relic/latest_changes.rb index 6d2ce135e3..68c194bb1a 100644 --- a/lib/new_relic/latest_changes.rb +++ b/lib/new_relic/latest_changes.rb @@ -26,12 +26,12 @@ def self.read(changelog = default_changelog) # * This is a patch item (3.7.1.188) def self.read_patch(patch_level, changelog = default_changelog) latest = extract_latest_changes(File.read(changelog)) - changes = ["## v#{patch_level}", ""] + changes = ["## v#{patch_level}", ''] current_item = nil latest.each do |line| - if line =~ /^\s*\*.*/ - if line =~ /\(#{patch_level}\)/ + if /^\s*\*.*/.match?(line) + if /\(#{patch_level}\)/.match?(line) # Found a patch level item, so start tracking the lines! current_item = line else @@ -52,12 +52,12 @@ def self.extract_latest_changes(contents) changes = [] version_count = 0 contents.each_line do |line| - if line =~ /##\s+v[\d.]+/ + if /##\s+v[\d.]+/.match?(line) version_count += 1 end break if version_count >= 2 - changes << line.sub(/^ \* /, "* ").chomp + changes << line.sub(/^ \* /, '* ').chomp end changes end diff --git a/lib/new_relic/noticed_error.rb b/lib/new_relic/noticed_error.rb index 8a949066a6..121c8e43ad 100644 --- a/lib/new_relic/noticed_error.rb +++ b/lib/new_relic/noticed_error.rb @@ -15,18 +15,20 @@ class NewRelic::NoticedError :stack_trace, :attributes_from_notice_error, :attributes, :expected - attr_reader :exception_id, :is_internal + attr_reader :error_group, :exception_id, :is_internal STRIPPED_EXCEPTION_REPLACEMENT_MESSAGE = "Message removed by New Relic 'strip_exception_messages' setting" UNKNOWN_ERROR_CLASS_NAME = 'Error' NIL_ERROR_MESSAGE = '' - USER_ATTRIBUTES = "userAttributes" - AGENT_ATTRIBUTES = "agentAttributes" - INTRINSIC_ATTRIBUTES = "intrinsics" + USER_ATTRIBUTES = 'userAttributes' + AGENT_ATTRIBUTES = 'agentAttributes' + INTRINSIC_ATTRIBUTES = 'intrinsics' DESTINATION = NewRelic::Agent::AttributeFilter::DST_ERROR_COLLECTOR + AGENT_ATTRIBUTE_ERROR_GROUP = :'error.group.name' + ERROR_PREFIX_KEY = 'error' ERROR_MESSAGE_KEY = "#{ERROR_PREFIX_KEY}.message" ERROR_CLASS_KEY = "#{ERROR_PREFIX_KEY}.class" @@ -141,21 +143,9 @@ def build_error_attributes end def build_agent_attributes(merged_attributes) - agent_attributes = if @attributes - @attributes.agent_attributes_for(DESTINATION) - else - NewRelic::EMPTY_HASH - end - - # It's possible to override the request_uri from the transaction attributes - # with a uri passed to notice_error. Add it to merged_attributes filter and - # merge with the transaction attributes, possibly overriding the request_uri - if request_uri - merged_attributes.add_agent_attribute(:'request.uri', request_uri, DESTINATION) - agent_attributes.merge(merged_attributes.agent_attributes_for(DESTINATION)) - end + return NewRelic::EMPTY_HASH unless @attributes - agent_attributes + @attributes.agent_attributes_for(DESTINATION) end def build_intrinsic_attributes @@ -197,4 +187,16 @@ def extract_class_name_and_message_from(exception) @message = exception.to_s end end + + def error_group=(name) + return if name.nil? || name.empty? + + if agent_attributes.frozen? + processed_attributes[AGENT_ATTRIBUTES] = agent_attributes.merge(AGENT_ATTRIBUTE_ERROR_GROUP => name) + else + agent_attributes[AGENT_ATTRIBUTE_ERROR_GROUP] = name + end + + @error_group = name + end end diff --git a/lib/new_relic/rack/browser_monitoring.rb b/lib/new_relic/rack/browser_monitoring.rb index e366f2be0b..83cd7c2718 100644 --- a/lib/new_relic/rack/browser_monitoring.rb +++ b/lib/new_relic/rack/browser_monitoring.rb @@ -26,11 +26,11 @@ class BrowserMonitoring < AgentMiddleware ATTACHMENT = 'attachment'.freeze TEXT_HTML = 'text/html'.freeze - BODY_START = "]+charset\s*=[^>]*>/im.freeze X_UA_COMPATIBLE_RE = /<\s*meta[^>]+http-equiv\s*=\s*['"]x-ua-compatible['"][^>]*>/im.freeze @@ -40,7 +40,7 @@ def traced_call(env) js_to_inject = NewRelic::Agent.browser_timing_header if (js_to_inject != NewRelic::EMPTY_STR) && should_instrument?(env, status, headers) - response_string = autoinstrument_source(response, headers, js_to_inject) + response_string = autoinstrument_source(response, js_to_inject) if headers.key?(CONTENT_LENGTH) content_length = response_string ? response_string.bytesize : 0 headers[CONTENT_LENGTH] = content_length.to_s @@ -69,11 +69,17 @@ def should_instrument?(env, status, headers) private - def autoinstrument_source(response, headers, js_to_inject) + def autoinstrument_source(response, js_to_inject) source = gather_source(response) close_old_response(response) - return nil unless source + return unless source + modify_source(source, js_to_inject) + rescue => e + NewRelic::Agent.logger.debug("Skipping RUM instrumentation on exception: #{e.class} - #{e.message}") + end + + def modify_source(source, js_to_inject) # Only scan the first 50k (roughly) then give up. beginning_of_source = source[0..SCAN_LIMIT] meta_tag_positions = find_meta_tag_positions(beginning_of_source) @@ -81,26 +87,24 @@ def autoinstrument_source(response, headers, js_to_inject) if insertion_index = find_insertion_index(meta_tag_positions, beginning_of_source, body_start) source = source_injection(source, insertion_index, js_to_inject) else - NewRelic::Agent.logger.debug("Skipping RUM instrumentation. Could not properly determine location to inject script.") + NewRelic::Agent.logger.debug('Skipping RUM instrumentation. Could not properly determine location to ' \ + 'inject script.') end else msg = "Skipping RUM instrumentation. Unable to find tag in first #{SCAN_LIMIT} bytes of document." NewRelic::Agent.logger.log_once(:warn, :rum_insertion_failure, msg) NewRelic::Agent.logger.debug(msg) end - source - rescue => e - NewRelic::Agent.logger.debug("Skipping RUM instrumentation on exception.", e) - nil end def html?(headers) - headers[CONTENT_TYPE] && headers[CONTENT_TYPE].include?(TEXT_HTML) + # needs else branch coverage + headers[CONTENT_TYPE] && headers[CONTENT_TYPE].include?(TEXT_HTML) # rubocop:disable Style/SafeNavigation end def attachment?(headers) - headers[CONTENT_DISPOSITION] && headers[CONTENT_DISPOSITION].include?(ATTACHMENT) + headers[CONTENT_DISPOSITION]&.include?(ATTACHMENT) end def streaming?(env, headers) @@ -150,12 +154,12 @@ def find_body_start(beginning_of_source) def find_x_ua_compatible_position(beginning_of_source) match = X_UA_COMPATIBLE_RE.match(beginning_of_source) - match.end(0) if match + match&.end(0) end def find_charset_position(beginning_of_source) match = CHARSET_RE.match(beginning_of_source) - match.end(0) if match + match&.end(0) end def find_end_of_head_open(beginning_of_source) diff --git a/lib/new_relic/recipes/capistrano3.rb b/lib/new_relic/recipes/capistrano3.rb index acbe4d81ca..f841a00702 100644 --- a/lib/new_relic/recipes/capistrano3.rb +++ b/lib/new_relic/recipes/capistrano3.rb @@ -8,7 +8,7 @@ namespace :newrelic do include SendDeployment # notifies New Relic of a deployment - desc "Record a deployment in New Relic (newrelic.com)" + desc 'Record a deployment in New Relic (newrelic.com)' task :notice_deployment do if fetch(:newrelic_role) on roles(fetch(:newrelic_role)) do diff --git a/lib/new_relic/recipes/capistrano_legacy.rb b/lib/new_relic/recipes/capistrano_legacy.rb index 8f72367b4c..6d329eb765 100644 --- a/lib/new_relic/recipes/capistrano_legacy.rb +++ b/lib/new_relic/recipes/capistrano_legacy.rb @@ -5,9 +5,9 @@ make_notify_task = proc do namespace(:newrelic) do # on all deployments, notify New Relic - desc("Record a deployment in New Relic (newrelic.com)") + desc('Record a deployment in New Relic (newrelic.com)') task(:notice_deployment, :roles => :app, :except => {:no_release => true}) do - rails_env = fetch(:newrelic_rails_env, fetch(:rails_env, "production")) + rails_env = fetch(:newrelic_rails_env, fetch(:rails_env, 'production')) require 'new_relic/cli/command' @@ -36,14 +36,14 @@ :license_key => license_key } - logger.debug("Uploading deployment to New Relic") + logger.debug('Uploading deployment to New Relic') deployment = NewRelic::Cli::Deployments.new(deploy_options) deployment.run - logger.info("Uploaded deployment information to New Relic") + logger.info('Uploaded deployment information to New Relic') rescue NewRelic::Cli::Command::CommandFailure => e logger.info(e.message) rescue Capistrano::CommandError - logger.info("Unable to notify New Relic of the deployment... skipping") + logger.info('Unable to notify New Relic of the deployment... skipping') rescue => e logger.info("Error creating New Relic deployment (#{e})\n#{e.backtrace.join("\n")}") end @@ -51,7 +51,7 @@ def lookup_changelog(changelog) if !changelog - logger.debug("Getting log of changes for New Relic Deployment details") + logger.debug('Getting log of changes for New Relic Deployment details') from_revision = source.next_revision(current_revision) if scm == :git diff --git a/lib/new_relic/recipes/helpers/send_deployment.rb b/lib/new_relic/recipes/helpers/send_deployment.rb index f3d83f64d3..7304fd4a82 100644 --- a/lib/new_relic/recipes/helpers/send_deployment.rb +++ b/lib/new_relic/recipes/helpers/send_deployment.rb @@ -5,9 +5,9 @@ module SendDeployment def send_deployment_notification_to_newrelic require 'new_relic/cli/command' - debug("Uploading deployment to New Relic") + debug('Uploading deployment to New Relic') NewRelic::Cli::Deployments.new(deploy_options).run - info("Uploaded deployment information to New Relic") + info('Uploaded deployment information to New Relic') rescue NewRelic::Cli::Command::CommandFailure => e info(e.message) rescue => e @@ -34,7 +34,7 @@ def fetch_changelog end def fetch_environment - fetch(:newrelic_rails_env, fetch(:rack_env, fetch(:rails_env, fetch(:stage, "production")))) + fetch(:newrelic_rails_env, fetch(:rack_env, fetch(:rails_env, fetch(:stage, 'production')))) end def fetch_rev @@ -59,9 +59,9 @@ def lookup_changelog current_revision = fetch(:current_revision) return unless current_revision && previous_revision - debug("Retrieving changelog for New Relic Deployment details") + debug('Retrieving changelog for New Relic Deployment details') - if Rake::Task.task_defined?("git:check") + if Rake::Task.task_defined?('git:check') log_command = "git --no-pager log --no-color --pretty=format:' * %an: %s' " + "--abbrev-commit --no-merges #{previous_revision}..#{current_revision}" `#{log_command}` diff --git a/lib/new_relic/supportability_helper.rb b/lib/new_relic/supportability_helper.rb index abee118dac..d7b43eb200 100644 --- a/lib/new_relic/supportability_helper.rb +++ b/lib/new_relic/supportability_helper.rb @@ -44,8 +44,10 @@ module SupportabilityHelper :record_metric, :recording_web_transaction?, :require_test_helper, + :set_error_group_callback, :set_sql_obfuscator, :set_transaction_name, + :set_user_id, :shutdown, :start_segment, :trace, diff --git a/lib/new_relic/version.rb b/lib/new_relic/version.rb index 1bd701fd79..854f9f02b5 100644 --- a/lib/new_relic/version.rb +++ b/lib/new_relic/version.rb @@ -6,7 +6,7 @@ module NewRelic module VERSION # :nodoc: MAJOR = 9 - MINOR = 0 + MINOR = 1 TINY = 0 STRING = "#{MAJOR}.#{MINOR}.#{TINY}" diff --git a/lib/newrelic_rpm.rb b/lib/newrelic_rpm.rb index 67c472cd9a..3d70f829d3 100644 --- a/lib/newrelic_rpm.rb +++ b/lib/newrelic_rpm.rb @@ -21,16 +21,16 @@ module NewRelic class Railtie < Rails::Railtie if ENV['NEW_RELIC_DEFER_RAILS_INITIALIZATION'] - initializer "newrelic_rpm.include_method_tracers", before: :load_config_initializers do |app| + initializer 'newrelic_rpm.include_method_tracers', before: :load_config_initializers do |app| Module.send(:include, NewRelic::Agent::MethodTracer::ClassMethods) Module.send(:include, NewRelic::Agent::MethodTracer) end - initializer "newrelic_rpm.start_plugin", after: :load_config_initializers do |app| + initializer 'newrelic_rpm.start_plugin', after: :load_config_initializers do |app| NewRelic::Control.instance.init_plugin(config: app.config) end else - initializer "newrelic_rpm.start_plugin", before: :load_config_initializers do |app| + initializer 'newrelic_rpm.start_plugin', before: :load_config_initializers do |app| NewRelic::Control.instance.init_plugin(config: app.config) end end diff --git a/lib/sequel/extensions/new_relic_instrumentation.rb b/lib/sequel/extensions/new_relic_instrumentation.rb index 02d3c0dcda..a235f68c3c 100644 --- a/lib/sequel/extensions/new_relic_instrumentation.rb +++ b/lib/sequel/extensions/new_relic_instrumentation.rb @@ -32,7 +32,7 @@ module Sequel module NewRelicInstrumentation module Naming def self.query_method_name - if Sequel::VERSION >= "4.35.0" + if Sequel::VERSION >= '4.35.0' :log_connection_yield else :log_yield @@ -86,13 +86,13 @@ def explainer_for(sql) if THREAD_SAFE_CONNECTION_POOL_CLASSES.include?(self.pool.class) self[sql].explain else - NewRelic::Agent.logger.log_once(:info, :sequel_explain_skipped, "Not running SQL explains because Sequel is not in recognized multi-threaded mode") + NewRelic::Agent.logger.log_once(:info, :sequel_explain_skipped, 'Not running SQL explains because Sequel is not in recognized multi-threaded mode') nil end end end end # module NewRelicInstrumentation - NewRelic::Agent.logger.debug("Registering the :new_relic_instrumentation extension.") + NewRelic::Agent.logger.debug('Registering the :new_relic_instrumentation extension.') Database.register_extension(:new_relic_instrumentation, NewRelicInstrumentation) end # module Sequel diff --git a/lib/sequel/plugins/new_relic_instrumentation.rb b/lib/sequel/plugins/new_relic_instrumentation.rb index 8271e0d24b..106dd9af09 100644 --- a/lib/sequel/plugins/new_relic_instrumentation.rb +++ b/lib/sequel/plugins/new_relic_instrumentation.rb @@ -54,7 +54,7 @@ module InstanceMethods module ClassMethods extend Sequel::Plugins::NewRelicInstrumentation::MethodWrapping - wrap_sequel_method :[], "get" + wrap_sequel_method :[], 'get' wrap_sequel_method :all wrap_sequel_method :first wrap_sequel_method :create diff --git a/lib/tasks/config.rake b/lib/tasks/config.rake index 4d82d2670e..9775fb9a7b 100644 --- a/lib/tasks/config.rake +++ b/lib/tasks/config.rake @@ -7,9 +7,9 @@ include Format namespace :newrelic do namespace :config do - GENERAL = "general" - DISABLING = "disabling" - ATTRIBUTES = "attributes" + GENERAL = 'general' + DISABLING = 'disabling' + ATTRIBUTES = 'attributes' # these configuration options are not able to be set using environment variables NON_ENV_CONFIGS = ['error_collector.ignore_classes', 'error_collector.ignore_messages', 'error_collector.expected_classes', 'error_collector.expected_messages'] @@ -18,21 +18,21 @@ namespace :newrelic do GENERAL => 'These settings are available for agent configuration. Some settings depend on your New Relic subscription level.', DISABLING => 'Use these settings to toggle instrumentation types during agent startup.', ATTRIBUTES => '[Attributes](/docs/features/agent-attributes) are key-value pairs containing information that determines the properties of an event or transaction. These key-value pairs can be viewed within transaction traces in APM, traced errors in APM, transaction events in dashboards, and page views in dashboards. You can customize exactly which attributes will be sent to each of these destinations', - "transaction_tracer" => 'The [transaction traces](/docs/apm/traces/transaction-traces/transaction-traces) feature collects detailed information from a selection of transactions, including a summary of the calling sequence, a breakdown of time spent, and a list of SQL queries and their query plans (on mysql and postgresql). Available features depend on your New Relic subscription level.', - "error_collector" => "The agent collects and reports all uncaught exceptions by default. These configuration options allow you to customize the error collection.\n\nFor information on ignored and expected errors, [see this page on Error Analytics in APM](/docs/agents/manage-apm-agents/agent-data/manage-errors-apm-collect-ignore-or-mark-expected/). To set expected errors via the `NewRelic::Agent.notice_error` Ruby method, [consult the Ruby Agent API](/docs/agents/ruby-agent/api-guides/sending-handled-errors-new-relic/).", - "browser_monitoring" => "The browser monitoring [page load timing](/docs/browser/new-relic-browser/page-load-timing/page-load-timing-process) feature (sometimes referred to as real user monitoring or RUM) gives you insight into the performance real users are experiencing with your website. This is accomplished by measuring the time it takes for your users' browsers to download and render your web pages by injecting a small amount of JavaScript code into the header and footer of each page.", - "analytics_events" => '[New Relic dashboards](/docs/query-your-data/explore-query-data/dashboards/introduction-new-relic-one-dashboards) is a resource to gather and visualize data about your software and what it says about your business. With it you can quickly and easily create real-time dashboards to get immediate answers about end-user experiences, clickstreams, mobile activities, and server transactions.' + 'transaction_tracer' => 'The [transaction traces](/docs/apm/traces/transaction-traces/transaction-traces) feature collects detailed information from a selection of transactions, including a summary of the calling sequence, a breakdown of time spent, and a list of SQL queries and their query plans (on mysql and postgresql). Available features depend on your New Relic subscription level.', + 'error_collector' => "The agent collects and reports all uncaught exceptions by default. These configuration options allow you to customize the error collection.\n\nFor information on ignored and expected errors, [see this page on Error Analytics in APM](/docs/agents/manage-apm-agents/agent-data/manage-errors-apm-collect-ignore-or-mark-expected/). To set expected errors via the `NewRelic::Agent.notice_error` Ruby method, [consult the Ruby Agent API](/docs/agents/ruby-agent/api-guides/sending-handled-errors-new-relic/).", + 'browser_monitoring' => "The browser monitoring [page load timing](/docs/browser/new-relic-browser/page-load-timing/page-load-timing-process) feature (sometimes referred to as real user monitoring or RUM) gives you insight into the performance real users are experiencing with your website. This is accomplished by measuring the time it takes for your users' browsers to download and render your web pages by injecting a small amount of JavaScript code into the header and footer of each page.", + 'analytics_events' => '[New Relic dashboards](/docs/query-your-data/explore-query-data/dashboards/introduction-new-relic-one-dashboards) is a resource to gather and visualize data about your software and what it says about your business. With it you can quickly and easily create real-time dashboards to get immediate answers about end-user experiences, clickstreams, mobile activities, and server transactions.' } NAME_OVERRIDES = { - "slow_sql" => "Slow SQL", - "custom_insights_events" => "Custom Events" + 'slow_sql' => 'Slow SQL', + 'custom_insights_events' => 'Custom Events' } - desc "Describe available New Relic configuration settings" + desc 'Describe available New Relic configuration settings' task :docs, [:format] => [] do |t, args| - require File.expand_path(File.join(File.dirname(__FILE__), "..", "new_relic", "agent", "configuration", "default_source.rb")) - format = args[:format] || "text" + require File.expand_path(File.join(File.dirname(__FILE__), '..', 'new_relic', 'agent', 'configuration', 'default_source.rb')) + format = args[:format] || 'text' output(format) end end diff --git a/lib/tasks/coverage_report.rake b/lib/tasks/coverage_report.rake index c87ea1652f..0a632fc36b 100644 --- a/lib/tasks/coverage_report.rake +++ b/lib/tasks/coverage_report.rake @@ -4,7 +4,7 @@ if ENV['CI'] namespace :coverage do - desc "Collates all result sets generated by the different test runners" + desc 'Collates all result sets generated by the different test runners' task :report do require 'simplecov' require 'fileutils' @@ -19,10 +19,10 @@ if ENV['CI'] Dir['lib/coverage_{[!r][!e][!s][!u][!l][!t][!s]}*'].each { |dir| FileUtils.rm_rf(dir) } end - desc "Removes all coverage_* directories" + desc 'Removes all coverage_* directories' task :clear do require 'fileutils' - Dir["lib/coverage_*"].each { |dir| FileUtils.rm_rf(dir) } + Dir['lib/coverage_*'].each { |dir| FileUtils.rm_rf(dir) } end end end diff --git a/lib/tasks/helpers/format.rb b/lib/tasks/helpers/format.rb index 033adf91d2..4a0890ed35 100644 --- a/lib/tasks/helpers/format.rb +++ b/lib/tasks/helpers/format.rb @@ -66,24 +66,24 @@ def format_default_value(spec) def format_description(value) description = '' - description += "DEPRECATED " if value[:deprecated] + description += 'DEPRECATED ' if value[:deprecated] description += value[:description] description end def format_env_var(key) - return "None" if NON_ENV_CONFIGS.include?(key) + return 'None' if NON_ENV_CONFIGS.include?(key) - "NEW_RELIC_#{key.tr(".", "_").upcase}" + "NEW_RELIC_#{key.tr('.', '_').upcase}" end def format_name(key) name = NAME_OVERRIDES[key] return name if name - key.split("_") + key.split('_') .each { |fragment| fragment[0] = fragment[0].upcase } - .join(" ") + .join(' ') end def format_sections(key, value) @@ -98,7 +98,7 @@ def format_sections(key, value) def format_type(type) if type == NewRelic::Agent::Configuration::Boolean - "Boolean" + 'Boolean' else type end @@ -110,11 +110,11 @@ def pluck(key, config_hash) end def section_key(key, components) - if key =~ /^disable_/ # "disable_httpclient" + if /^disable_/.match?(key) # "disable_httpclient" DISABLING - elsif components.length >= 2 && !(components[1] == "attributes") # "analytics_events.enabled" + elsif components.length >= 2 && !(components[1] == 'attributes') # "analytics_events.enabled" components.first - elsif components[1] == "attributes" # "transaction_tracer.attributes.enabled" + elsif components[1] == 'attributes' # "transaction_tracer.attributes.enabled" ATTRIBUTES else GENERAL diff --git a/lib/tasks/helpers/removers.rb b/lib/tasks/helpers/removers.rb index 9c3c64ec73..50d10304b3 100644 --- a/lib/tasks/helpers/removers.rb +++ b/lib/tasks/helpers/removers.rb @@ -11,21 +11,21 @@ def remove_local_multiverse_databases `echo "drop database #{database}" | mysql -u root` end rescue => error - puts "ERROR: Cannot get MySQL databases..." + puts 'ERROR: Cannot get MySQL databases...' puts error.message end def remove_generated_gemfiles - file_path = File.expand_path("test/multiverse/suites") - Dir.glob(File.join(file_path, "**", "Gemfile*")).each do |fn| + file_path = File.expand_path('test/multiverse/suites') + Dir.glob(File.join(file_path, '**', 'Gemfile*')).each do |fn| puts "Removing #{fn.gsub(file_path, '.../suites')}" FileUtils.rm(fn) end end def remove_generated_gemfile_lockfiles - file_path = File.expand_path("test/environments") - Dir.glob(File.join(file_path, "**", "Gemfile.lock")).each do |fn| + file_path = File.expand_path('test/environments') + Dir.glob(File.join(file_path, '**', 'Gemfile.lock')).each do |fn| puts "Removing #{fn.gsub(file_path, '.../environments')}" FileUtils.rm(fn) end diff --git a/lib/tasks/install.rake b/lib/tasks/install.rake index a85210ca54..7ccb113fa9 100644 --- a/lib/tasks/install.rake +++ b/lib/tasks/install.rake @@ -3,13 +3,13 @@ # frozen_string_literal: true namespace :newrelic do - desc "Install a default config/newrelic.yml file" + desc 'Install a default config/newrelic.yml file' task :install do - load File.expand_path(File.join(File.dirname(__FILE__), "..", "..", "install.rb")) + load File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'install.rb')) end - desc "Gratefulness is always appreciated" + desc 'Gratefulness is always appreciated' task :thanks do - puts "The Ruby agent team is grateful to Jim Weirich for his kindness and his code. He will be missed." + puts 'The Ruby agent team is grateful to Jim Weirich for his kindness and his code. He will be missed.' end end diff --git a/lib/tasks/multiverse.rb b/lib/tasks/multiverse.rb index 4ec423025f..52536b3cb2 100644 --- a/lib/tasks/multiverse.rb +++ b/lib/tasks/multiverse.rb @@ -39,12 +39,14 @@ include Removers namespace :test do - desc "Run functional test suite for New Relic" + desc 'Run functional test suite for New Relic' task :multiverse, [:suite, :param1, :param2, :param3, :param4] => ['multiverse:env'] do |_, args| Multiverse::Runner.run(args.suite, Multiverse::Runner.parse_args(args)) end namespace :multiverse do + # task :prerequisites + task :env do # ENV['SUITES_DIRECTORY'] = File.expand_path('../../test/multiverse/suites', __FILE__) require File.expand_path('../../../test/multiverse/lib/multiverse', __FILE__) @@ -56,22 +58,26 @@ remove_generated_gemfile_lockfiles end - desc "Clean cached gemfiles from Bundler.bundle_path" + desc 'Clean cached gemfiles from Bundler.bundle_path' task :clean_gemfile_cache do glob = File.expand_path('multiverse-cache/Gemfile.*.lock', Bundler.bundle_path) File.delete(*Dir[glob]) end - desc "Test the multiverse testing framework by executing tests in test/multiverse/test. Get meta with it." + desc 'Test the multiverse testing framework by executing tests in test/multiverse/test. Get meta with it.' task :self, [:suite, :mode] do |_, args| - args.with_defaults(:suite => "", :mode => "") - puts ("Testing the multiverse testing framework...") + args.with_defaults(:suite => '', :mode => '') + puts ('Testing the multiverse testing framework...') test_files = FileList['test/multiverse/test/*_test.rb'] - ruby test_files.join(" ") + ruby test_files.join(' ') end task :prime, [:suite] => [:env] do |_, args| Multiverse::Runner.prime(args.suite, Multiverse::Runner.parse_args(args)) end + + task :gem_manifest => :env do + Multiverse::GemManifest.new.report + end end end diff --git a/lib/tasks/tests.rake b/lib/tasks/tests.rake index 9e6bed8922..a86adbab91 100644 --- a/lib/tasks/tests.rake +++ b/lib/tasks/tests.rake @@ -13,19 +13,19 @@ end if defined? Rake::TestTask namespace :test do tasks = Rake.application.top_level_tasks - ENV["TESTOPTS"] ||= "" - if tasks.any? { |t| t.include?("verbose") } - ENV["TESTOPTS"] += " -v" + ENV['TESTOPTS'] ||= '' + if tasks.any? { |t| t.include?('verbose') } + ENV['TESTOPTS'] += ' -v' end if seed = look_for_seed(tasks) - ENV["TESTOPTS"] += " --" + seed + ENV['TESTOPTS'] += ' --' + seed end agent_home = File.expand_path(File.join(File.dirname(__FILE__), '..', '..')) Rake::TestTask.new(:newrelic) do |t| - file_pattern = ENV["file"] - file_pattern = file_pattern.split(",").map { |f| "#{agent_home}/#{f}".gsub("//", "/") } if file_pattern + file_pattern = ENV['file'] + file_pattern = file_pattern.split(',').map { |f| "#{agent_home}/#{f}".gsub('//', '/') } if file_pattern file_pattern ||= "#{agent_home}/test/new_relic/**/*_test.rb" t.libs << "#{agent_home}/test" diff --git a/newrelic_rpm.gemspec b/newrelic_rpm.gemspec index a2a5c5449b..9cb2889314 100644 --- a/newrelic_rpm.gemspec +++ b/newrelic_rpm.gemspec @@ -6,11 +6,11 @@ require 'new_relic/version' require 'new_relic/latest_changes' Gem::Specification.new do |s| - s.name = "newrelic_rpm" + s.name = 'newrelic_rpm' s.version = NewRelic::VERSION::STRING s.required_ruby_version = '>= 2.4.0' - s.required_rubygems_version = Gem::Requirement.new("> 1.3.1") if s.respond_to?(:required_rubygems_version=) - s.authors = ["Tanna McClure", "Kayla Reopelle", "James Bunch", "Hannah Ramadan"] + s.required_rubygems_version = Gem::Requirement.new('> 1.3.1') if s.respond_to?(:required_rubygems_version=) + s.authors = ['Tanna McClure', 'Kayla Reopelle', 'James Bunch', 'Hannah Ramadan'] s.licenses = ['Apache-2.0'] s.description = <<~EOS New Relic is a performance management system, developed by New Relic, @@ -20,14 +20,14 @@ Gem::Specification.new do |s| Gem or plugin, hosted on https://github.com/newrelic/newrelic-ruby-agent/ EOS - s.email = "support@newrelic.com" + s.email = 'support@newrelic.com' s.executables = %w[newrelic_cmd newrelic nrdebug] s.extra_rdoc_files = [ - "CHANGELOG.md", - "LICENSE", - "README.md", - "CONTRIBUTING.md", - "newrelic.yml" + 'CHANGELOG.md', + 'LICENSE', + 'README.md', + 'CONTRIBUTING.md', + 'newrelic.yml' ] s.metadata = { @@ -35,7 +35,7 @@ Gem::Specification.new do |s| 'changelog_uri' => 'https://github.com/newrelic/newrelic-ruby-agent/blob/main/CHANGELOG.md', 'documentation_uri' => 'https://docs.newrelic.com/docs/agents/ruby-agent', 'source_code_uri' => 'https://github.com/newrelic/newrelic-ruby-agent', - "homepage_uri" => "https://newrelic.com/ruby" + 'homepage_uri' => 'https://newrelic.com/ruby' } file_list = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features|infinite_tracing|\.github)/(?!agent_helper.rb)}) } @@ -43,9 +43,9 @@ Gem::Specification.new do |s| file_list << build_file_path if File.exist?(build_file_path) s.files = file_list - s.homepage = "https://github.com/newrelic/rpm" - s.require_paths = ["lib"] - s.summary = "New Relic Ruby Agent" + s.homepage = 'https://github.com/newrelic/rpm' + s.require_paths = ['lib'] + s.summary = 'New Relic Ruby Agent' s.add_development_dependency 'bundler' s.add_development_dependency 'feedjira', '3.2.1' unless ENV['CI'] || RUBY_VERSION < '2.5' # for Gabby s.add_development_dependency 'httparty' unless ENV['CI'] # for perf tests and Gabby diff --git a/test/agent_helper.rb b/test/agent_helper.rb index c8e80b5221..39cf6f4cb8 100644 --- a/test/agent_helper.rb +++ b/test/agent_helper.rb @@ -111,7 +111,8 @@ def assert_equal_unordered(left, right) def assert_log_contains(log, message) lines = log.array - assert (lines.any? { |line| line.match(message) }) + assert (lines.any? { |line| line.match(message) }), + "Could not find message. Log contained: #{lines.join("\n")}" end def assert_audit_log_contains(audit_log_contents, needle) @@ -147,7 +148,7 @@ def assert_audit_log_contains_object(audit_log_contents, o, format = :json) end when NilClass - assert_audit_log_contains(audit_log_contents, format == :json ? "null" : "nil") + assert_audit_log_contains(audit_log_contents, format == :json ? 'null' : 'nil') else assert_audit_log_contains(audit_log_contents, o.inspect) end @@ -182,7 +183,7 @@ def _normalize_metric_expectations(expectations) end def dump_stats(stats) - str = String.new(" Call count: #{stats.call_count}\n") + str = +" Call count: #{stats.call_count}\n" str << " Total call time: #{stats.total_call_time}\n" str << " Total exclusive time: #{stats.total_exclusive_time}\n" str << " Min call time: #{stats.min_call_time}\n" @@ -379,8 +380,8 @@ def assert_false(expected) # in_transaction('foobar', :category => :controller) { ... } # def in_transaction(*args, &blk) - opts = args.last && args.last.is_a?(Hash) ? args.pop : {} - category = (opts && opts.delete(:category)) || :other + opts = args.last&.is_a?(Hash) ? args.pop : {} + category = (opts&.delete(:category)) || :other # At least one test passes `:transaction_name => nil`, so handle it gently name = opts.key?(:transaction_name) ? opts.delete(:transaction_name) : args.first || 'dummy' @@ -434,10 +435,10 @@ def capture_segment_with_error segment_with_error = nil with_segment do |segment| segment_with_error = segment - raise "oops!" + raise 'oops!' end rescue Exception => exception - assert segment_with_error, "expected to have a segment_with_error" + assert segment_with_error, 'expected to have a segment_with_error' build_deferred_error_attributes(segment_with_error) return segment_with_error, exception end @@ -476,7 +477,7 @@ def last_transaction_trace def last_transaction_trace_request_params agent_attributes = attributes_for(last_transaction_trace, :agent) agent_attributes.inject({}) do |memo, (key, value)| - memo[key] = value if key.to_s.start_with?("request.parameters.") + memo[key] = value if key.to_s.start_with?('request.parameters.') memo end end @@ -671,7 +672,7 @@ def undefine_constant(constant_symbol) const_str = constant_symbol.to_s parent = get_parent(const_str) const_name = const_str.gsub(/.*::/, '') - return yield unless parent && parent.constants.include?(const_name.to_sym) + return yield unless parent&.constants&.include?(const_name.to_sym) removed_constant = parent.send(:remove_const, const_name) yield @@ -693,13 +694,13 @@ def with_debug_logging end def create_agent_command(args = {}) - NewRelic::Agent::Commands::AgentCommand.new([-1, {"name" => "command_name", "arguments" => args}]) + NewRelic::Agent::Commands::AgentCommand.new([-1, {'name' => 'command_name', 'arguments' => args}]) end def wait_for_backtrace_service_poll(opts = {}) defaults = { :timeout => 10.0, - :service => NewRelic::Agent.agent.agent_command_router.backtrace_service, + :service => NewRelic::Agent.agent.instance_variable_get(:@agent_command_router).backtrace_service, :iterations => 1 } opts = defaults.merge(opts) @@ -729,7 +730,7 @@ def with_array_logger(level = :info) override_logger = Logger.new(logdev) with_config(config) do - NewRelic::Agent.logger = NewRelic::Agent::AgentLogger.new("", override_logger) + NewRelic::Agent.logger = NewRelic::Agent::AgentLogger.new('', override_logger) yield end @@ -876,7 +877,7 @@ def load_cross_agent_test(name) end def each_cross_agent_test(options) - options = {:dir => nil, :pattern => "*"}.update(options) + options = {:dir => nil, :pattern => '*'}.update(options) path = File.join([cross_agent_tests_dir, options[:dir], options[:pattern]].compact) Dir.glob(path).each { |file| yield(file) } end @@ -891,7 +892,7 @@ def assert_event_attributes(event, test_name, expected_attributes, non_expected_ incorrect_attributes << name unless actual_value == expected_value end - msg = String.new("Found missing or incorrect attribute values in #{test_name}:\n") + msg = +"Found missing or incorrect attribute values in #{test_name}:\n" incorrect_attributes.each do |name| msg << " #{name}: expected = #{expected_attributes[name].inspect}, actual = #{event_attrs[name].inspect}\n" @@ -930,10 +931,10 @@ def message_for_status_code(code) end case code - when 200 then "OK" - when 404 then "Not Found" - when 403 then "Forbidden" - else "Unknown" + when 200 then 'OK' + when 404 then 'Not Found' + when 403 then 'Forbidden' + else 'Unknown' end end @@ -942,7 +943,7 @@ def message_for_status_code(code) # a "status_code" may be passed in the headers to alter the HTTP Status Code # that is wrapped in the response. def mock_http_response(headers, wrap_it = true) - status_code = (headers.delete("status_code") || 200).to_i + status_code = (headers.delete('status_code') || 200).to_i net_http_resp = Net::HTTPResponse.new(1.0, status_code, message_for_status_code(status_code)) headers.each do |key, value| net_http_resp.add_field(key.to_s, value) @@ -966,7 +967,7 @@ def assert_match_or_equal(expected, value) def assert_segment_noticed_error(txn, segment_name, error_classes, error_message) error_segment = txn.segments.reverse.detect { |s| s.noticed_error } - assert error_segment, "Expected at least one segment with a noticed_error" + assert error_segment, 'Expected at least one segment with a noticed_error' assert_match_or_equal segment_name, error_segment.name @@ -977,15 +978,15 @@ def assert_segment_noticed_error(txn, segment_name, error_classes, error_message end def assert_transaction_noticed_error(txn, error_classes) - refute_empty txn.exceptions, "Expected transaction to notice the error" + refute_empty txn.exceptions, 'Expected transaction to notice the error' assert_match_or_equal error_classes, txn.exceptions.keys.first.class.name end def refute_transaction_noticed_error(txn, error_class) error_segment = txn.segments.reverse.detect { |s| s.noticed_error } - assert error_segment, "Expected at least one segment with a noticed_error" - assert_empty txn.exceptions, "Expected transaction to NOT notice any segment errors" + assert error_segment, 'Expected at least one segment with a noticed_error' + assert_empty txn.exceptions, 'Expected transaction to NOT notice any segment errors' end def refute_raises(*exp) @@ -1021,6 +1022,6 @@ def defer_testing_to_min_supported_rails(test_file, min_rails_version, supports_ yield else - puts "Skipping tests in #{File.basename(test_file)} because Rails >= #{min_rails_version} is unavailable" if ENV["VERBOSE_TEST_OUTPUT"] + puts "Skipping tests in #{File.basename(test_file)} because Rails >= #{min_rails_version} is unavailable" if ENV['VERBOSE_TEST_OUTPUT'] end end diff --git a/test/environments/lib/environments/runner.rb b/test/environments/lib/environments/runner.rb index 83166e2506..02071b5224 100644 --- a/test/environments/lib/environments/runner.rb +++ b/test/environments/lib/environments/runner.rb @@ -24,14 +24,14 @@ def run_and_report overall_status = 0 failures = [] - puts yellow("Tests to run:\n\t#{tests_to_run.map { |s| s.gsub(env_root + "/", "") }.join("\n\t")}") if ENV['VERBOSE_TEST_OUTPUT'] - env_file = ENV["file"] + puts yellow("Tests to run:\n\t#{tests_to_run.map { |s| s.gsub(env_root + '/', '') }.join("\n\t")}") if ENV['VERBOSE_TEST_OUTPUT'] + env_file = ENV['file'] tests_to_run.each do |dir| Bundler.with_unbundled_env do - ENV["file"] = env_file if env_file + ENV['file'] = env_file if env_file dir = File.expand_path(dir) - puts "", yellow("Running tests for #{dir}") if ENV['VERBOSE_TEST_OUTPUT'] + puts '', yellow("Running tests for #{dir}") if ENV['VERBOSE_TEST_OUTPUT'] status = bundle(dir) status = run(dir) if status.success? @@ -43,16 +43,16 @@ def run_and_report end if overall_status == 0 - puts green("All good to go. Yippy!") + puts green('All good to go. Yippy!') else - puts red("Oh no, #{overall_status} environments failed!"), "", red(failures.join("\n")) + puts red("Oh no, #{overall_status} environments failed!"), '', red(failures.join("\n")) end exit(overall_status) end def tests_to_run - original_dirs = Dir["#{env_root}/*"].reject { |d| File.basename(d) == "lib" } + original_dirs = Dir["#{env_root}/*"].reject { |d| File.basename(d) == 'lib' } return original_dirs if envs.empty? @@ -65,18 +65,18 @@ def tests_to_run # Ensures we bundle will recognize an explicit version number on command line def safe_explicit(version) - return version if version.to_s == "" + return version if version.to_s == '' test_version = `bundle #{version} --version`.include?('Could not find command') - test_version ? "" : version + test_version ? '' : version end def explicit_bundler_version(dir) return if RUBY_PLATFORM == 'java' - fn = File.join(dir, ".bundler-version") + fn = File.join(dir, '.bundler-version') version = File.exist?(fn) ? File.read(fn).chomp!.strip : nil - safe_explicit(version.to_s == "" ? nil : "_#{version}_") + safe_explicit(version.to_s == '' ? nil : "_#{version}_") end def bundle_config(dir, bundle_cmd) @@ -93,16 +93,16 @@ def bundle(dir) result = Multiverse::ShellUtils.try_command_n_times(command, 3) result = red(result) unless $?.success? - puts result if ENV["VERBOSE_TEST_OUTPUT"] + puts result if ENV['VERBOSE_TEST_OUTPUT'] $? end def run(dir) puts "Starting tests for dir '#{dir}'..." if ENV['VERBOSE_TEST_OUTPUT'] - cmd = String.new("cd #{dir} && bundle exec rake") + cmd = +"cd #{dir} && bundle exec rake" # if the shell running the original test:env rake task has a "file" env # var, replicate it here in the subshell - cmd << " file=#{ENV['file']}" if ENV["file"] + cmd << " file=#{ENV['file']}" if ENV['file'] # if the shell running the original test:env rake task has CLI args (not # Rake task args) such as '--trace', replicate them here in the subshell cmd << " #{ARGV[1..-1].join(' ')}" if ARGV.size > 1 diff --git a/test/environments/norails/Gemfile b/test/environments/norails/Gemfile index 2b931df0d9..0bcf811586 100644 --- a/test/environments/norails/Gemfile +++ b/test/environments/norails/Gemfile @@ -13,6 +13,6 @@ gem 'newrelic_rpm', :path => '../../..' gem 'pry', '~> 0.14.1' gem 'pry-nav' -gem 'simplecov' if ENV["VERBOSE_TEST_OUTPUT"] +gem 'simplecov' if ENV['VERBOSE_TEST_OUTPUT'] gem 'warning' if RUBY_VERSION >= '2.4.0' diff --git a/test/environments/norails/Rakefile b/test/environments/norails/Rakefile index 4c43851f2f..d15efb4d93 100644 --- a/test/environments/norails/Rakefile +++ b/test/environments/norails/Rakefile @@ -10,6 +10,6 @@ require_relative '../../warning_test_helper' require 'rake' require 'tasks/all' -ENV["NO_RAILS"] = "1" +ENV['NO_RAILS'] = '1' task :default => [:'test:newrelic'] diff --git a/test/environments/rails32/.bundler-version b/test/environments/rails32/.bundler-version deleted file mode 100644 index b9a05a6dc1..0000000000 --- a/test/environments/rails32/.bundler-version +++ /dev/null @@ -1 +0,0 @@ -1.17.3 diff --git a/test/environments/rails32/Gemfile b/test/environments/rails32/Gemfile deleted file mode 100644 index 5900207cca..0000000000 --- a/test/environments/rails32/Gemfile +++ /dev/null @@ -1,26 +0,0 @@ -# frozen_string_literal: true -source 'https://rubygems.org' - -gem 'rails', '~> 3.2.0' -gem 'i18n', '0.6.11' -gem 'rake', '~> 12.3.3' -gem 'minitest', '4.7.5' # Minitest ~> 4.2 required for Rails 3.2 -gem 'minitest-stub-const', '~> 0.6' -gem 'mocha', '~> 1.16', :require => false -gem 'rack', '< 2.0.0' -gem 'rack-test' - -gem "newrelic_rpm", :path => "../../.." - -platforms :jruby do - gem "activerecord-jdbcmysql-adapter" - gem "activerecord-jdbcsqlite3-adapter" -end - -platforms :ruby, :rbx do - gem "mysql2", '~> 0.3.10' - gem 'sqlite3', '~> 1.3.13' -end - -gem 'pry', '~> 0.9.12' -gem 'warning' if RUBY_VERSION >= '2.4.0' diff --git a/test/environments/rails32/Rakefile b/test/environments/rails32/Rakefile deleted file mode 100644 index fb23b18f14..0000000000 --- a/test/environments/rails32/Rakefile +++ /dev/null @@ -1,17 +0,0 @@ -# This file is distributed under New Relic's license terms. -# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. -# frozen_string_literal: true - -# Add your own tasks in files placed in lib/tasks ending in .rake, -# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. - -require_relative '../../warning_test_helper' -require_relative 'config/application' -require 'rake' - -RpmTestApp::Application.load_tasks -require 'tasks/all' - -Rake::Task["default"].clear -task :default => [:'test:newrelic_with_db'] -task :'test:newrelic_with_db' => [:'db:create', :'test:newrelic'] diff --git a/test/environments/rails32/config/application.rb b/test/environments/rails32/config/application.rb deleted file mode 100644 index 3d090d8975..0000000000 --- a/test/environments/rails32/config/application.rb +++ /dev/null @@ -1,19 +0,0 @@ -# This file is distributed under New Relic's license terms. -# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. -# frozen_string_literal: true - -require_relative 'boot' - -require 'rails/all' - -Bundler.require(:default, Rails.env) if defined?(Bundler) - -module RpmTestApp - class Application < Rails::Application - config.encoding = "utf-8" - config.filter_parameters += [:password] - config.secret_key_base = '414fd9af0cc192729b2b6bffe9e7077c9ac8eed5cbb74c8c4cd628906b716770598a2b7e1f328052753a4df72e559969dc05b408de73ce040c93cac7c51a348e' - config.active_support.deprecation = :notify - config.eager_load = false - end -end diff --git a/test/environments/rails32/config/boot.rb b/test/environments/rails32/config/boot.rb deleted file mode 100644 index 00857d182a..0000000000 --- a/test/environments/rails32/config/boot.rb +++ /dev/null @@ -1,10 +0,0 @@ -# This file is distributed under New Relic's license terms. -# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. -# frozen_string_literal: true - -require 'rubygems' - -# Set up gems listed in the Gemfile. -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) - -require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) diff --git a/test/environments/rails32/config/database.yml b/test/environments/rails32/config/database.yml deleted file mode 100644 index 8d7abf9da6..0000000000 --- a/test/environments/rails32/config/database.yml +++ /dev/null @@ -1,26 +0,0 @@ -mysql: &mysql - adapter: mysql2 - username: root - password: <%= ENV['MYSQL_PASSWORD'] %> - host: localhost - database: <%= db = "#{ENV['RUBY_VERSION']}#{ENV['BRANCH']}"; db.empty? ? "rails_blog" : db %> - -sqlite3: &sqlite3 -<% if defined?(JRuby) %> - adapter: jdbcsqlite3 -<% else %> - adapter: sqlite3 -<% end %> - database: db/all.sqlite3 - pool: 5 - timeout: 5000 - host: localhost - -development: - <<: *sqlite3 - -test: - <<: *mysql - -production: - <<: *mysql diff --git a/test/environments/rails32/config/environment.rb b/test/environments/rails32/config/environment.rb deleted file mode 100644 index 75ed67ed20..0000000000 --- a/test/environments/rails32/config/environment.rb +++ /dev/null @@ -1,6 +0,0 @@ -# This file is distributed under New Relic's license terms. -# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. -# frozen_string_literal: true - -require_relative 'application' -RpmTestApp::Application.initialize! diff --git a/test/environments/rails32/db/schema.rb b/test/environments/rails32/db/schema.rb deleted file mode 100644 index 2d964da716..0000000000 --- a/test/environments/rails32/db/schema.rb +++ /dev/null @@ -1,5 +0,0 @@ -# This file is distributed under New Relic's license terms. -# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. -# frozen_string_literal: true - -# File is required to exist by Rails diff --git a/test/environments/rails40/Rakefile b/test/environments/rails40/Rakefile index 42acaf4061..23b5351403 100644 --- a/test/environments/rails40/Rakefile +++ b/test/environments/rails40/Rakefile @@ -13,5 +13,5 @@ require 'rake' RpmTestApp::Application.load_tasks require 'tasks/all' -Rake::Task["default"].clear +Rake::Task['default'].clear task :default => [:'test:newrelic'] diff --git a/test/environments/rails40/config/application.rb b/test/environments/rails40/config/application.rb index eb82b81f75..e0427038e0 100644 --- a/test/environments/rails40/config/application.rb +++ b/test/environments/rails40/config/application.rb @@ -10,7 +10,7 @@ module RpmTestApp class Application < Rails::Application - config.encoding = "utf-8" + config.encoding = 'utf-8' config.filter_parameters += [:password] config.secret_key_base = '414fd9af0cc192729b2b6bffe9e7077c9ac8eed5cbb74c8c4cd628906b716770598a2b7e1f328052753a4df72e559969dc05b408de73ce040c93cac7c51a348e' config.eager_load = false diff --git a/test/environments/rails40/config/initializers/test.rb b/test/environments/rails40/config/initializers/test.rb index 1d88e77b0a..9981aac1a3 100644 --- a/test/environments/rails40/config/initializers/test.rb +++ b/test/environments/rails40/config/initializers/test.rb @@ -8,10 +8,10 @@ class Bloodhound < ActiveRecord::Base include ::NewRelic::Agent::MethodTracer def sniff - puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), " \ + puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), ' \ "air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's " \ - "scent receptors. " \ - "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/" + 'scent receptors. ' \ + 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/' end add_method_tracer :sniff diff --git a/test/environments/rails41/Gemfile b/test/environments/rails41/Gemfile index c5b7e97155..db9edabac2 100644 --- a/test/environments/rails41/Gemfile +++ b/test/environments/rails41/Gemfile @@ -11,16 +11,16 @@ gem 'rack', '~> 1.5.2' gem 'rack-test' platforms :jruby do - gem "activerecord-jdbcmysql-adapter", "~>1.3.0" - gem "activerecord-jdbcsqlite3-adapter", "~>1.3.0" + gem 'activerecord-jdbcmysql-adapter', '~>1.3.0' + gem 'activerecord-jdbcsqlite3-adapter', '~>1.3.0' end platforms :ruby do - gem "mysql2", '~> 0.3.20' + gem 'mysql2', '~> 0.3.20' gem 'sqlite3', '~> 1.3.13' end -gem "newrelic_rpm", :path => "../../.." +gem 'newrelic_rpm', :path => '../../..' gem 'pry', '~> 0.9.12' gem 'warning' if RUBY_VERSION >= '2.4.0' diff --git a/test/environments/rails41/Rakefile b/test/environments/rails41/Rakefile index 42acaf4061..23b5351403 100644 --- a/test/environments/rails41/Rakefile +++ b/test/environments/rails41/Rakefile @@ -13,5 +13,5 @@ require 'rake' RpmTestApp::Application.load_tasks require 'tasks/all' -Rake::Task["default"].clear +Rake::Task['default'].clear task :default => [:'test:newrelic'] diff --git a/test/environments/rails41/config/application.rb b/test/environments/rails41/config/application.rb index eb82b81f75..e0427038e0 100644 --- a/test/environments/rails41/config/application.rb +++ b/test/environments/rails41/config/application.rb @@ -10,7 +10,7 @@ module RpmTestApp class Application < Rails::Application - config.encoding = "utf-8" + config.encoding = 'utf-8' config.filter_parameters += [:password] config.secret_key_base = '414fd9af0cc192729b2b6bffe9e7077c9ac8eed5cbb74c8c4cd628906b716770598a2b7e1f328052753a4df72e559969dc05b408de73ce040c93cac7c51a348e' config.eager_load = false diff --git a/test/environments/rails41/config/initializers/test.rb b/test/environments/rails41/config/initializers/test.rb index 06be89db54..b2c0d06c23 100644 --- a/test/environments/rails41/config/initializers/test.rb +++ b/test/environments/rails41/config/initializers/test.rb @@ -8,9 +8,9 @@ class Bloodhound < ActiveRecord::Base include ::NewRelic::Agent::MethodTracer def sniff - puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject)," \ + puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject),' \ "air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's scent receptors. " \ - "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/" + 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/' end add_method_tracer :sniff diff --git a/test/environments/rails42/Gemfile b/test/environments/rails42/Gemfile index 7a5282de78..c3a8e99d88 100644 --- a/test/environments/rails42/Gemfile +++ b/test/environments/rails42/Gemfile @@ -13,16 +13,16 @@ gem 'rack-test' gem 'sprockets', '3.7.2' platforms :jruby do - gem "activerecord-jdbcmysql-adapter", "~>1.3.0" - gem "activerecord-jdbcsqlite3-adapter", "~>1.3.0" + gem 'activerecord-jdbcmysql-adapter', '~>1.3.0' + gem 'activerecord-jdbcsqlite3-adapter', '~>1.3.0' end platforms :ruby, :rbx do - gem "mysql2" + gem 'mysql2' gem 'sqlite3', '~> 1.3.13' end -gem "newrelic_rpm", :path => "../../.." +gem 'newrelic_rpm', :path => '../../..' gem 'pry', '~> 0.12.2' gem 'pry-nav' diff --git a/test/environments/rails42/Rakefile b/test/environments/rails42/Rakefile index 42acaf4061..23b5351403 100644 --- a/test/environments/rails42/Rakefile +++ b/test/environments/rails42/Rakefile @@ -13,5 +13,5 @@ require 'rake' RpmTestApp::Application.load_tasks require 'tasks/all' -Rake::Task["default"].clear +Rake::Task['default'].clear task :default => [:'test:newrelic'] diff --git a/test/environments/rails42/config/application.rb b/test/environments/rails42/config/application.rb index eb82b81f75..e0427038e0 100644 --- a/test/environments/rails42/config/application.rb +++ b/test/environments/rails42/config/application.rb @@ -10,7 +10,7 @@ module RpmTestApp class Application < Rails::Application - config.encoding = "utf-8" + config.encoding = 'utf-8' config.filter_parameters += [:password] config.secret_key_base = '414fd9af0cc192729b2b6bffe9e7077c9ac8eed5cbb74c8c4cd628906b716770598a2b7e1f328052753a4df72e559969dc05b408de73ce040c93cac7c51a348e' config.eager_load = false diff --git a/test/environments/rails42/config/initializers/test.rb b/test/environments/rails42/config/initializers/test.rb index 1d88e77b0a..9981aac1a3 100644 --- a/test/environments/rails42/config/initializers/test.rb +++ b/test/environments/rails42/config/initializers/test.rb @@ -8,10 +8,10 @@ class Bloodhound < ActiveRecord::Base include ::NewRelic::Agent::MethodTracer def sniff - puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), " \ + puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), ' \ "air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's " \ - "scent receptors. " \ - "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/" + 'scent receptors. ' \ + 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/' end add_method_tracer :sniff diff --git a/test/environments/rails50/Gemfile b/test/environments/rails50/Gemfile index 2eec576c15..b887840b89 100644 --- a/test/environments/rails50/Gemfile +++ b/test/environments/rails50/Gemfile @@ -13,16 +13,16 @@ gem 'rack-test' gem 'sprockets', '3.7.2' platforms :jruby do - gem "activerecord-jdbcmysql-adapter", "~> 50.0" - gem "activerecord-jdbcsqlite3-adapter", "~> 50.0" + gem 'activerecord-jdbcmysql-adapter', '~> 50.0' + gem 'activerecord-jdbcsqlite3-adapter', '~> 50.0' end platforms :ruby, :rbx do - gem "mysql2" + gem 'mysql2' gem 'sqlite3', '~> 1.3.13' end -gem "newrelic_rpm", :path => "../../.." +gem 'newrelic_rpm', :path => '../../..' gem 'pry', '~> 0.12.2' gem 'pry-nav' diff --git a/test/environments/rails50/Rakefile b/test/environments/rails50/Rakefile index 42acaf4061..23b5351403 100644 --- a/test/environments/rails50/Rakefile +++ b/test/environments/rails50/Rakefile @@ -13,5 +13,5 @@ require 'rake' RpmTestApp::Application.load_tasks require 'tasks/all' -Rake::Task["default"].clear +Rake::Task['default'].clear task :default => [:'test:newrelic'] diff --git a/test/environments/rails50/config/application.rb b/test/environments/rails50/config/application.rb index eb82b81f75..e0427038e0 100644 --- a/test/environments/rails50/config/application.rb +++ b/test/environments/rails50/config/application.rb @@ -10,7 +10,7 @@ module RpmTestApp class Application < Rails::Application - config.encoding = "utf-8" + config.encoding = 'utf-8' config.filter_parameters += [:password] config.secret_key_base = '414fd9af0cc192729b2b6bffe9e7077c9ac8eed5cbb74c8c4cd628906b716770598a2b7e1f328052753a4df72e559969dc05b408de73ce040c93cac7c51a348e' config.eager_load = false diff --git a/test/environments/rails50/config/initializers/test.rb b/test/environments/rails50/config/initializers/test.rb index 1d88e77b0a..9981aac1a3 100644 --- a/test/environments/rails50/config/initializers/test.rb +++ b/test/environments/rails50/config/initializers/test.rb @@ -8,10 +8,10 @@ class Bloodhound < ActiveRecord::Base include ::NewRelic::Agent::MethodTracer def sniff - puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), " \ + puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), ' \ "air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's " \ - "scent receptors. " \ - "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/" + 'scent receptors. ' \ + 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/' end add_method_tracer :sniff diff --git a/test/environments/rails51/Gemfile b/test/environments/rails51/Gemfile index 75e9578dcc..50c0d6fb58 100644 --- a/test/environments/rails51/Gemfile +++ b/test/environments/rails51/Gemfile @@ -12,16 +12,16 @@ gem 'rack-test' gem 'sprockets', '3.7.2' platforms :jruby do - gem "activerecord-jdbcmysql-adapter", "~> 51.0" - gem "activerecord-jdbcsqlite3-adapter", "~> 51.0" + gem 'activerecord-jdbcmysql-adapter', '~> 51.0' + gem 'activerecord-jdbcsqlite3-adapter', '~> 51.0' end platforms :ruby, :rbx do - gem "mysql2" + gem 'mysql2' gem 'sqlite3', '~> 1.3.13' end -gem "newrelic_rpm", :path => "../../.." +gem 'newrelic_rpm', :path => '../../..' gem 'pry', '~> 0.12.2' gem 'pry-nav' diff --git a/test/environments/rails51/Rakefile b/test/environments/rails51/Rakefile index 4e16c4f323..716450b039 100644 --- a/test/environments/rails51/Rakefile +++ b/test/environments/rails51/Rakefile @@ -11,5 +11,5 @@ require 'rake' RpmTestApp::Application.load_tasks require 'tasks/all' -Rake::Task["default"].clear +Rake::Task['default'].clear task :default => [:'test:newrelic'] diff --git a/test/environments/rails51/config/application.rb b/test/environments/rails51/config/application.rb index eb82b81f75..e0427038e0 100644 --- a/test/environments/rails51/config/application.rb +++ b/test/environments/rails51/config/application.rb @@ -10,7 +10,7 @@ module RpmTestApp class Application < Rails::Application - config.encoding = "utf-8" + config.encoding = 'utf-8' config.filter_parameters += [:password] config.secret_key_base = '414fd9af0cc192729b2b6bffe9e7077c9ac8eed5cbb74c8c4cd628906b716770598a2b7e1f328052753a4df72e559969dc05b408de73ce040c93cac7c51a348e' config.eager_load = false diff --git a/test/environments/rails51/config/initializers/test.rb b/test/environments/rails51/config/initializers/test.rb index 1d88e77b0a..9981aac1a3 100644 --- a/test/environments/rails51/config/initializers/test.rb +++ b/test/environments/rails51/config/initializers/test.rb @@ -8,10 +8,10 @@ class Bloodhound < ActiveRecord::Base include ::NewRelic::Agent::MethodTracer def sniff - puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), " \ + puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), ' \ "air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's " \ - "scent receptors. " \ - "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/" + 'scent receptors. ' \ + 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/' end add_method_tracer :sniff diff --git a/test/environments/rails52/Gemfile b/test/environments/rails52/Gemfile index 88ebe8f763..4b8916b9f1 100644 --- a/test/environments/rails52/Gemfile +++ b/test/environments/rails52/Gemfile @@ -12,8 +12,8 @@ gem 'rack-test' gem 'sprockets', '3.7.2' platforms :jruby do - gem "activerecord-jdbcmysql-adapter", "~> 52.0" - gem "activerecord-jdbcsqlite3-adapter", "~> 52.0" + gem 'activerecord-jdbcmysql-adapter', '~> 52.0' + gem 'activerecord-jdbcsqlite3-adapter', '~> 52.0' end platforms :ruby, :rbx do @@ -21,7 +21,7 @@ platforms :ruby, :rbx do gem 'sqlite3', '~> 1.3.13' end -gem 'newrelic_rpm', :path => "../../.." +gem 'newrelic_rpm', :path => '../../..' gem 'pry', '~> 0.12.2' gem 'pry-nav' diff --git a/test/environments/rails52/Rakefile b/test/environments/rails52/Rakefile index 42acaf4061..23b5351403 100644 --- a/test/environments/rails52/Rakefile +++ b/test/environments/rails52/Rakefile @@ -13,5 +13,5 @@ require 'rake' RpmTestApp::Application.load_tasks require 'tasks/all' -Rake::Task["default"].clear +Rake::Task['default'].clear task :default => [:'test:newrelic'] diff --git a/test/environments/rails52/config/application.rb b/test/environments/rails52/config/application.rb index 004028ff9f..c4535fb6c6 100644 --- a/test/environments/rails52/config/application.rb +++ b/test/environments/rails52/config/application.rb @@ -11,7 +11,7 @@ module RpmTestApp class Application < Rails::Application - config.encoding = "utf-8" + config.encoding = 'utf-8' config.active_record.sqlite3.represent_boolean_as_integer = true config.filter_parameters += [:password] config.secret_key_base = '414fd9af0cc192729b2b6bffe9e7077c9ac8eed5cbb74c8c4cd628906b716770598a2b7e1f328052753a4df72e559969dc05b408de73ce040c93cac7c51a348e' diff --git a/test/environments/rails52/config/initializers/test.rb b/test/environments/rails52/config/initializers/test.rb index 1d88e77b0a..9981aac1a3 100644 --- a/test/environments/rails52/config/initializers/test.rb +++ b/test/environments/rails52/config/initializers/test.rb @@ -8,10 +8,10 @@ class Bloodhound < ActiveRecord::Base include ::NewRelic::Agent::MethodTracer def sniff - puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), " \ + puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), ' \ "air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's " \ - "scent receptors. " \ - "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/" + 'scent receptors. ' \ + 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/' end add_method_tracer :sniff diff --git a/test/environments/rails60/Gemfile b/test/environments/rails60/Gemfile index 7c8cd74afc..6bfbaf6a5e 100644 --- a/test/environments/rails60/Gemfile +++ b/test/environments/rails60/Gemfile @@ -13,12 +13,12 @@ gem 'rack-test' gem 'sprockets', '3.7.2' platforms :jruby do - gem "activerecord-jdbcmysql-adapter", "~> 60.0" - gem "activerecord-jdbcsqlite3-adapter", "~> 60.0" + gem 'activerecord-jdbcmysql-adapter', '~> 60.0' + gem 'activerecord-jdbcsqlite3-adapter', '~> 60.0' end platforms :ruby, :rbx do - gem "mysql2", '>= 0.5.4' + gem 'mysql2', '>= 0.5.4' if RUBY_VERSION < '2.6' gem 'sqlite3', '~> 1.4.0' elsif RUBY_VERSION < '2.7' @@ -28,9 +28,9 @@ platforms :ruby, :rbx do end end -gem "newrelic_rpm", :path => "../../.." +gem 'newrelic_rpm', :path => '../../..' gem 'pry', '~> 0.14.1' gem 'pry-nav' -gem 'simplecov' if ENV["VERBOSE_TEST_OUTPUT"] +gem 'simplecov' if ENV['VERBOSE_TEST_OUTPUT'] gem 'warning' if RUBY_VERSION >= '2.4.0' diff --git a/test/environments/rails60/Rakefile b/test/environments/rails60/Rakefile index 42acaf4061..23b5351403 100644 --- a/test/environments/rails60/Rakefile +++ b/test/environments/rails60/Rakefile @@ -13,5 +13,5 @@ require 'rake' RpmTestApp::Application.load_tasks require 'tasks/all' -Rake::Task["default"].clear +Rake::Task['default'].clear task :default => [:'test:newrelic'] diff --git a/test/environments/rails60/config/application.rb b/test/environments/rails60/config/application.rb index f9e971b51d..3d231afcf4 100644 --- a/test/environments/rails60/config/application.rb +++ b/test/environments/rails60/config/application.rb @@ -16,7 +16,7 @@ module RpmTestApp class Application < Rails::Application - config.encoding = "utf-8" + config.encoding = 'utf-8' config.filter_parameters += [:password] config.secret_key_base = '414fd9af0cc192729b2b6bffe9e7077c9ac8eed5cbb74c8c4cd628906b716770598a2b7e1f328052753a4df72e559969dc05b408de73ce040c93cac7c51a348e' config.eager_load = false diff --git a/test/environments/rails60/config/initializers/test.rb b/test/environments/rails60/config/initializers/test.rb index 1d88e77b0a..9981aac1a3 100644 --- a/test/environments/rails60/config/initializers/test.rb +++ b/test/environments/rails60/config/initializers/test.rb @@ -8,10 +8,10 @@ class Bloodhound < ActiveRecord::Base include ::NewRelic::Agent::MethodTracer def sniff - puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), " \ + puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), ' \ "air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's " \ - "scent receptors. " \ - "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/" + 'scent receptors. ' \ + 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/' end add_method_tracer :sniff diff --git a/test/environments/rails60/config/psych4_monkeypatch.rb b/test/environments/rails60/config/psych4_monkeypatch.rb index dab4849946..706390de26 100644 --- a/test/environments/rails60/config/psych4_monkeypatch.rb +++ b/test/environments/rails60/config/psych4_monkeypatch.rb @@ -14,34 +14,34 @@ module Rails class Application class Configuration < ::Rails::Engine::Configuration def database_configuration - path = paths["config/database"].existent.first + path = paths['config/database'].existent.first yaml = Pathname.new(path) if path - config = if yaml && yaml.exist? - require "yaml" - require "erb" + config = if yaml&.exist? + require 'yaml' + require 'erb' # THIS LINE CHANGED # loaded_yaml = YAML.load(ERB.new(yaml.read).result) || {} loaded_yaml = YAML.unsafe_load(ERB.new(yaml.read).result) || {} - shared = loaded_yaml.delete("shared") + shared = loaded_yaml.delete('shared') if shared loaded_yaml.each do |_k, values| values.reverse_merge!(shared) end end Hash.new(shared).merge(loaded_yaml) - elsif ENV["DATABASE_URL"] + elsif ENV['DATABASE_URL'] {} else - raise "Could not load database configuration. No such file - #{paths["config/database"].instance_variable_get(:@paths)}" + raise "Could not load database configuration. No such file - #{paths['config/database'].instance_variable_get(:@paths)}" end config rescue Psych::SyntaxError => e - raise "YAML syntax error occurred while parsing #{paths["config/database"].first}. " \ - "Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \ + raise "YAML syntax error occurred while parsing #{paths['config/database'].first}. " \ + 'Please note that YAML must be consistently indented using spaces. Tabs are not allowed. ' \ "Error: #{e.message}" rescue => e raise e, "Cannot load database configuration:\n#{e.message}", e.backtrace diff --git a/test/environments/rails61/Gemfile b/test/environments/rails61/Gemfile index 40de29dcb4..08486cbe07 100644 --- a/test/environments/rails61/Gemfile +++ b/test/environments/rails61/Gemfile @@ -12,8 +12,8 @@ gem 'rack-test' gem 'sprockets', '3.7.2' platforms :jruby do - gem "activerecord-jdbcmysql-adapter", "~> 61.0" - gem "activerecord-jdbcsqlite3-adapter", "~> 61.0" + gem 'activerecord-jdbcmysql-adapter', '~> 61.0' + gem 'activerecord-jdbcsqlite3-adapter', '~> 61.0' end platforms :ruby, :rbx do @@ -31,5 +31,5 @@ gem 'newrelic_rpm', path: '../../..' gem 'pry', '~> 0.14.1' gem 'pry-nav' -gem 'simplecov' if ENV["VERBOSE_TEST_OUTPUT"] +gem 'simplecov' if ENV['VERBOSE_TEST_OUTPUT'] gem 'warning' if RUBY_VERSION >= '2.4.0' diff --git a/test/environments/rails61/Rakefile b/test/environments/rails61/Rakefile index b54e9115f5..8723f412b9 100644 --- a/test/environments/rails61/Rakefile +++ b/test/environments/rails61/Rakefile @@ -13,5 +13,5 @@ require 'rake' RpmTestApp::Application.load_tasks require 'tasks/all' -Rake::Task["default"].clear +Rake::Task['default'].clear task :default => [:'test:newrelic'] diff --git a/test/environments/rails61/config/application.rb b/test/environments/rails61/config/application.rb index 9c9b5c07ba..47b5b8020f 100644 --- a/test/environments/rails61/config/application.rb +++ b/test/environments/rails61/config/application.rb @@ -11,7 +11,7 @@ module RpmTestApp class Application < Rails::Application - config.encoding = "utf-8" + config.encoding = 'utf-8' config.filter_parameters += [:password] config.secret_key_base = '414fd9af0cc192729b2b6bffe9e7077c9ac8eed5cbb74c8c4cd628906b716770598a2b7e1f328052753a4df72e559969dc05b408de73ce040c93cac7c51a348e' config.eager_load = false diff --git a/test/environments/rails61/config/initializers/test.rb b/test/environments/rails61/config/initializers/test.rb index 1d88e77b0a..9981aac1a3 100644 --- a/test/environments/rails61/config/initializers/test.rb +++ b/test/environments/rails61/config/initializers/test.rb @@ -8,10 +8,10 @@ class Bloodhound < ActiveRecord::Base include ::NewRelic::Agent::MethodTracer def sniff - puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), " \ + puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), ' \ "air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's " \ - "scent receptors. " \ - "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/" + 'scent receptors. ' \ + 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/' end add_method_tracer :sniff diff --git a/test/environments/rails70/Gemfile b/test/environments/rails70/Gemfile index d4593b99c0..b4733517ef 100644 --- a/test/environments/rails70/Gemfile +++ b/test/environments/rails70/Gemfile @@ -2,7 +2,7 @@ source 'https://rubygems.org' gem 'rails', '~> 7.0.4' -gem "bootsnap", ">= 1.4.4", require: false +gem 'bootsnap', '>= 1.4.4', require: false gem 'minitest', '5.2.3' gem 'minitest-stub-const', '~> 0.6' @@ -17,5 +17,5 @@ gem 'newrelic_rpm', path: '../../..' gem 'pry', '~> 0.14.1' gem 'pry-nav' -gem 'simplecov' if ENV["VERBOSE_TEST_OUTPUT"] +gem 'simplecov' if ENV['VERBOSE_TEST_OUTPUT'] gem 'warning' if RUBY_VERSION >= '2.4.0' diff --git a/test/environments/rails70/Rakefile b/test/environments/rails70/Rakefile index 525c85931c..8c74a5a9a9 100644 --- a/test/environments/rails70/Rakefile +++ b/test/environments/rails70/Rakefile @@ -13,5 +13,5 @@ Rails.application.load_tasks require 'tasks/all' -Rake::Task["default"].clear +Rake::Task['default'].clear task :default => [:'test:newrelic'] diff --git a/test/environments/rails70/config/boot.rb b/test/environments/rails70/config/boot.rb index 30155f0617..a8d25cb53d 100644 --- a/test/environments/rails70/config/boot.rb +++ b/test/environments/rails70/config/boot.rb @@ -2,7 +2,7 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) -require "bundler/setup" # Set up gems listed in the Gemfile. -require "bootsnap/setup" # Speed up boot time by caching expensive operations. +require 'bundler/setup' # Set up gems listed in the Gemfile. +require 'bootsnap/setup' # Speed up boot time by caching expensive operations. diff --git a/test/environments/rails70/config/initializers/test.rb b/test/environments/rails70/config/initializers/test.rb index 1d88e77b0a..9981aac1a3 100644 --- a/test/environments/rails70/config/initializers/test.rb +++ b/test/environments/rails70/config/initializers/test.rb @@ -8,10 +8,10 @@ class Bloodhound < ActiveRecord::Base include ::NewRelic::Agent::MethodTracer def sniff - puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), " \ + puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), ' \ "air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's " \ - "scent receptors. " \ - "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/" + 'scent receptors. ' \ + 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/' end add_method_tracer :sniff diff --git a/test/environments/railsedge/Gemfile b/test/environments/railsedge/Gemfile index 2ba0840b06..82aab5b670 100644 --- a/test/environments/railsedge/Gemfile +++ b/test/environments/railsedge/Gemfile @@ -2,7 +2,7 @@ source 'https://rubygems.org' gem 'rails', git: 'https://github.com/rails/rails.git', branch: 'main' -gem "bootsnap", ">= 1.4.4", require: false +gem 'bootsnap', '>= 1.4.4', require: false gem 'minitest', '5.2.3' gem 'minitest-stub-const', '~> 0.6' @@ -17,5 +17,5 @@ gem 'newrelic_rpm', path: '../../..' gem 'pry', '~> 0.14.1' gem 'pry-nav' -gem 'simplecov' if ENV["VERBOSE_TEST_OUTPUT"] +gem 'simplecov' if ENV['VERBOSE_TEST_OUTPUT'] gem 'warning' if RUBY_VERSION >= '2.4.0' diff --git a/test/environments/railsedge/Rakefile b/test/environments/railsedge/Rakefile index 1a559d41a9..8c74a5a9a9 100644 --- a/test/environments/railsedge/Rakefile +++ b/test/environments/railsedge/Rakefile @@ -7,11 +7,11 @@ require_relative '../../warning_test_helper' -require_relative "config/application" +require_relative 'config/application' Rails.application.load_tasks require 'tasks/all' -Rake::Task["default"].clear +Rake::Task['default'].clear task :default => [:'test:newrelic'] diff --git a/test/environments/railsedge/config/application.rb b/test/environments/railsedge/config/application.rb index 29b647d892..2565b8762e 100644 --- a/test/environments/railsedge/config/application.rb +++ b/test/environments/railsedge/config/application.rb @@ -2,9 +2,9 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -require_relative "boot" +require_relative 'boot' -require "rails/all" +require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. diff --git a/test/environments/railsedge/config/boot.rb b/test/environments/railsedge/config/boot.rb index 30155f0617..a8d25cb53d 100644 --- a/test/environments/railsedge/config/boot.rb +++ b/test/environments/railsedge/config/boot.rb @@ -2,7 +2,7 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) -require "bundler/setup" # Set up gems listed in the Gemfile. -require "bootsnap/setup" # Speed up boot time by caching expensive operations. +require 'bundler/setup' # Set up gems listed in the Gemfile. +require 'bootsnap/setup' # Speed up boot time by caching expensive operations. diff --git a/test/environments/railsedge/config/environment.rb b/test/environments/railsedge/config/environment.rb index c2744831ac..d0c0782949 100644 --- a/test/environments/railsedge/config/environment.rb +++ b/test/environments/railsedge/config/environment.rb @@ -3,7 +3,7 @@ # frozen_string_literal: true # Load the Rails application. -require_relative "application" +require_relative 'application' # Initialize the Rails application. Rails.application.initialize! diff --git a/test/environments/railsedge/config/initializers/test.rb b/test/environments/railsedge/config/initializers/test.rb index 1d88e77b0a..9981aac1a3 100644 --- a/test/environments/railsedge/config/initializers/test.rb +++ b/test/environments/railsedge/config/initializers/test.rb @@ -8,10 +8,10 @@ class Bloodhound < ActiveRecord::Base include ::NewRelic::Agent::MethodTracer def sniff - puts "When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), " \ + puts 'When a bloodhound sniffs a scent article (a piece of clothing or item touched only by the subject), ' \ "air rushes through its nasal cavity and chemical vapors — or odors — lodge in the mucus and bombard the dog's " \ - "scent receptors. " \ - "Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/" + 'scent receptors. ' \ + 'Source: https://www.pbs.org/wnet/nature/underdogs-the-bloodhounds-amazing-sense-of-smell/350/' end add_method_tracer :sniff diff --git a/test/helpers/file_searching.rb b/test/helpers/file_searching.rb index 999046bdb5..3e97344b30 100644 --- a/test/helpers/file_searching.rb +++ b/test/helpers/file_searching.rb @@ -6,22 +6,22 @@ module NewRelic module TestHelpers module FileSearching def all_rb_files - pattern = File.expand_path(gem_root + "/**/*.{rb,rhtml}") + pattern = File.expand_path(gem_root + '/**/*.{rb,rhtml}') Dir[pattern] end def all_rb_and_js_files - pattern = File.expand_path(gem_root + "/**/*.{rb,js}") + pattern = File.expand_path(gem_root + '/**/*.{rb,js}') Dir[pattern] end def all_files - pattern = File.expand_path(gem_root + "/**/*") + pattern = File.expand_path(gem_root + '/**/*') Dir[pattern] end def gem_root - File.expand_path(File.dirname(__FILE__) + "/../../") + File.expand_path(File.dirname(__FILE__) + '/../../') end end end diff --git a/test/helpers/misc.rb b/test/helpers/misc.rb index 924e483174..00d6493967 100644 --- a/test/helpers/misc.rb +++ b/test/helpers/misc.rb @@ -30,7 +30,7 @@ def default_service(stubbed_method_overrides = {}) def fixture_tcp_socket(response) # Don't actually talk to Google. - socket = stub("socket").tap do |s| + socket = stub('socket').tap do |s| s.stubs(:closed?).returns(false) s.stubs(:close) s.stubs(:setsockopt) @@ -48,7 +48,7 @@ def fixture_tcp_socket(response) stubs(:check_write) { self.write_checker = Proc.new } stubs(:write) do |buf| - self.write_checker.call(buf) if self.write_checker + self.write_checker&.call(buf) buf.length end diff --git a/test/helpers/mongo_metric_builder.rb b/test/helpers/mongo_metric_builder.rb index 4493e36dce..8f2a8beea0 100644 --- a/test/helpers/mongo_metric_builder.rb +++ b/test/helpers/mongo_metric_builder.rb @@ -17,7 +17,7 @@ def build_test_metrics(name, instance_metrics = false) end NewRelic::Agent::Datastores::MetricHelper.metrics_for( - "MongoDB", name, @collection_name, host, port + 'MongoDB', name, @collection_name, host, port ) end diff --git a/test/helpers/transaction_sample.rb b/test/helpers/transaction_sample.rb index 0a28bb64c9..7cfbe97ed7 100644 --- a/test/helpers/transaction_sample.rb +++ b/test/helpers/transaction_sample.rb @@ -11,12 +11,12 @@ def make_sql_transaction(*sql) in_transaction('/path') do sampler = NewRelic::Agent.instance.transaction_sampler - sampler.notice_push_frame(state, "a") + sampler.notice_push_frame(state, 'a') explainer = NewRelic::Agent::Instrumentation::ActiveRecord::EXPLAINER - sql.each { |sql_statement| sampler.notice_sql(sql_statement, {:adapter => "mysql"}, 0, state, explainer) } + sql.each { |sql_statement| sampler.notice_sql(sql_statement, {:adapter => 'mysql'}, 0, state, explainer) } sleep(0.02) yield if block_given? - sampler.notice_pop_frame(state, "a") + sampler.notice_pop_frame(state, 'a') end return sampler.last_sample diff --git a/test/minitest/test_time_reporter.rb b/test/minitest/test_time_reporter.rb index 79c18c26e3..9523341f70 100644 --- a/test/minitest/test_time_reporter.rb +++ b/test/minitest/test_time_reporter.rb @@ -57,7 +57,7 @@ def ten_slowest_tests end def output_report - return unless ENV["VERBOSE_TEST_OUTPUT"] + return unless ENV['VERBOSE_TEST_OUTPUT'] puts "\n====== Ten slowest tests ======\n" ten_slowest_tests.each_with_index do |element, index| diff --git a/test/multiverse/lib/multiverse.rb b/test/multiverse/lib/multiverse.rb index 8c3512408b..c1bfd8ba3f 100644 --- a/test/multiverse/lib/multiverse.rb +++ b/test/multiverse/lib/multiverse.rb @@ -35,3 +35,4 @@ module Multiverse require 'multiverse/runner' require 'multiverse/envfile' require 'multiverse/suite' +require 'multiverse/gem_manifest' diff --git a/test/multiverse/lib/multiverse/color.rb b/test/multiverse/lib/multiverse/color.rb index 62705c4ed6..c3fd940848 100644 --- a/test/multiverse/lib/multiverse/color.rb +++ b/test/multiverse/lib/multiverse/color.rb @@ -9,15 +9,15 @@ def colorize(color_code, content) end def red(string) - colorize("0;31;49", string) + colorize('0;31;49', string) end def green(string) - colorize("0;32;49", string) + colorize('0;32;49', string) end def yellow(string) - colorize("0;33;49", string) + colorize('0;33;49', string) end end end diff --git a/test/multiverse/lib/multiverse/envfile.rb b/test/multiverse/lib/multiverse/envfile.rb index b0aa9c3e01..2c5fb4a53e 100644 --- a/test/multiverse/lib/multiverse/envfile.rb +++ b/test/multiverse/lib/multiverse/envfile.rb @@ -10,11 +10,12 @@ class Envfile attr_reader :before, :after, :mode, :skip_message, :omit_collector attr_reader :instrumentation_permutations - def initialize(file_path) + def initialize(file_path, options = {}) self.file_path = file_path - @instrumentation_permutations = ["chain"] + @instrumentation_permutations = ['chain'] @gemfiles = [] @mode = 'fork' + @ignore_ruby_version = options[:ignore_ruby_version] if options.key?(:ignore_ruby_version) if File.exist?(file_path) @text = File.read(self.file_path) instance_eval(@text) @@ -37,7 +38,7 @@ def create_gemfiles(versions) ) end - version = if version && version.start_with?('=') + version = if version&.start_with?('=') add_version(version.sub('= ', ''), false) # don't twiddle wakka else add_version(version) @@ -48,6 +49,8 @@ def create_gemfiles(versions) end def unsupported_ruby_version?(last_supported_ruby_version, first_supported_ruby_version) + return false if @ignore_ruby_version + last_supported_ruby_version?(last_supported_ruby_version) || first_supported_ruby_version?(first_supported_ruby_version) end @@ -62,7 +65,7 @@ def gemfile(content) end def ruby3_gem_sorted_set - RUBY_VERSION >= "3.0.0" ? "gem 'sorted_set'" : "" + RUBY_VERSION >= '3.0.0' ? "gem 'sorted_set'" : '' end def omit_collector! @@ -99,6 +102,10 @@ def [](key) @gemfiles[key] end + def to_ary + @gemfiles + end + def permutations @instrumentation_permutations.size end diff --git a/test/multiverse/lib/multiverse/gem_manifest.rb b/test/multiverse/lib/multiverse/gem_manifest.rb new file mode 100755 index 0000000000..d8e8b2d708 --- /dev/null +++ b/test/multiverse/lib/multiverse/gem_manifest.rb @@ -0,0 +1,120 @@ +#!/usr/bin/env ruby +# This file is distributed under New Relic's license terms. +# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. +# frozen_string_literal: true + +require 'fileutils' +require 'json' +require 'tmpdir' + +module Multiverse + class GemManifest + GEMFILE_HEADER = %q(source 'https://rubygems.org') + LOCKFILE = 'Gemfile.lock' + OUTPUT_FILE = "gem_manifest_#{RUBY_VERSION}.json" + SUITES_DIR = File.expand_path('../../../suites', __FILE__) + + def initialize(args = []) + @suite_paths = [] + @gems = {} + @opwd = Dir.pwd + discover_suites + end + + def report + process_suites + determine_latest_versions + deliver_output + end + + private + + def create_lockfile(dir) + Bundler.with_unbundled_env do + `cd #{dir} && bundle lock --lockfile=#{File.join(dir, LOCKFILE)}` + end + end + + def deliver_output + results = @gems.each_with_object({}) do |(name, versions), hash| + hash[name] = versions.keys + puts "#{name} => #{hash[name]}" + end + FileUtils.rm_f(OUTPUT_FILE) + File.open(OUTPUT_FILE, 'w') { |f| f.print results.to_json } + puts + puts "Results written to #{OUTPUT_FILE}" + end + + def determine_latest_versions + gems_wanting_latest = @gems.select { |_name, versions| versions.key?(nil) }.keys + gemfile_body = gems_wanting_latest.map { |name| "gem '#{name}'" }.join("\n") + dir = Dir.mktmpdir + File.open(File.join(dir, 'Gemfile'), 'w') do |f| + f.puts GEMFILE_HEADER + f.puts gemfile_body + end + create_lockfile(dir) + parse_lockfile(dir) + end + + def discover_suites + Dir.glob(File.join(SUITES_DIR, '*')).each do |path| + @suite_paths << path if File.directory?(path) + end + end + + def gems_from_gemfile_body(body, path) + body.split("\n").each do |line| + next if line.empty? || line.match?(/(?:^\s*(?:#|if|else|end))|newrelic_(?:rpm|prepender)/) + + if line =~ /.*gem\s+['"]([^'"]+)['"](?:,\s+['"]([^'"]+)['"])?/ + gem = Regexp.last_match(1) + version = Regexp.last_match(2) + @gems[gem] ||= {} + @gems[gem][version] = 1 + else + raise "Couldn't figure out how to parse lines from evaluating the Envfile file at #{path}!" + end + end + end + + def parse_lockfile(dir) + content = File.read(File.join(dir, LOCKFILE)) + gem_specs = Regexp.last_match(1) if content =~ /\AGEM\n.*\n\s+specs:\n(.*?)\n\n/m + desired_indentation = nil + hash = gem_specs.split("\n").each_with_object({}) do |line, h| + indentation = Regexp.last_match(1) if line =~ /^(\s+)/ + desired_indentation ||= indentation + next unless indentation == desired_indentation + + h[Regexp.last_match(1).strip] = Regexp.last_match(2).strip if line =~ /^(.*?)\s+\((.*?)\)/ + end + process_lockfile_hash(hash) + end + + def process_lockfile_hash(hash) + hash.each do |gem, version| + next unless @gems.key?(gem) + + @gems[gem].delete(nil) + @gems[gem]["latest (#{version})"] = 1 + end + end + + def process_suites + @suite_paths.each do |path| + Dir.chdir(path) # needed for Envfile.new's instance_eval call + Multiverse::Envfile.new(File.join(path, 'Envfile'), ignore_ruby_version: true).map do |body| + gems_from_gemfile_body(body, path) + end + end + ensure + Dir.chdir(@opwd) + end + + def verify_mode + raise "Invalid mode '#{@mode}' - must be one of #{MODES}" unless MODES.include?(@mode) + end + end +end diff --git a/test/multiverse/lib/multiverse/output_collector.rb b/test/multiverse/lib/multiverse/output_collector.rb index debe99d4f6..b12fcece65 100644 --- a/test/multiverse/lib/multiverse/output_collector.rb +++ b/test/multiverse/lib/multiverse/output_collector.rb @@ -26,7 +26,7 @@ def self.buffer(suite, env) key = [suite, env] @buffer_lock.synchronize do @buffers ||= {} - @buffers[key] ||= String.new('') + @buffers[key] ||= +'' @buffers[key] end end @@ -50,7 +50,7 @@ def self.suite_report(suite, env) def self.overall_report output('', '') if failing_output.empty? - output(green("There were no test failures")) + output(green('There were no test failures')) else to_output = failing_output_header + failing_output + failing_output_footer output(*to_output) @@ -60,27 +60,27 @@ def self.overall_report end def self.failing_output_header - [red("*" * 80), - red("Repeating failed test output"), - red("*" * 80), - ""] + [red('*' * 80), + red('Repeating failed test output'), + red('*' * 80), + ''] end def self.failing_output_footer - ["", - red("*" * 80), + ['', + red('*' * 80), red("There were failures in #{failing_output.size} test suites"), - "", + '', @failing_suites.map { |suite, env| red("#{suite} failed in env #{env}") }, - red("*" * 80)] + red('*' * 80)] end # Saves the failing out put to the working directory of the container # where it is later read and output as annotations of the github workflow def self.save_output_to_error_file(lines) @output_lock.synchronize do - filepath = ENV["GITHUB_WORKSPACE"] || File.expand_path(File.dirname(__FILE__)) - output_file = File.join(filepath, "errors.txt") + filepath = ENV['GITHUB_WORKSPACE'] || File.expand_path(File.dirname(__FILE__)) + output_file = File.join(filepath, 'errors.txt') existing_lines = [] if File.exist?(output_file) @@ -90,7 +90,7 @@ def self.save_output_to_error_file(lines) lines = lines.split("\n") if lines.is_a?(String) File.open(output_file, 'w') do |f| f.puts existing_lines - f.puts "*" * 80 + f.puts '*' * 80 f.puts lines end end diff --git a/test/multiverse/lib/multiverse/runner.rb b/test/multiverse/lib/multiverse/runner.rb index 0a89a94560..d67b079c86 100644 --- a/test/multiverse/lib/multiverse/runner.rb +++ b/test/multiverse/lib/multiverse/runner.rb @@ -33,12 +33,12 @@ def notice_exit_status(i) def parse_args(args) opts = {} args.each do |(k, v)| - if v.index("name=") == 0 - parts = v.split("=") + if v.index('name=') == 0 + parts = v.split('=') opts[:names] ||= [] opts[:names] << parts.last - elsif v.include?("=") - parts = v.split("=") + elsif v.include?('=') + parts = v.split('=') opts[parts.first.to_sym] = parts.last elsif k != :suite opts[v.to_sym] = true @@ -47,7 +47,7 @@ def parse_args(args) opts end - def run(filter = "", opts = {}) + def run(filter = '', opts = {}) # This file is generated by TestTimeReporter. # TestTimeReporter cannot be loaded until minitest has been loaded by an # individual suite, so we cannot define this inside the TestTimeReporter @@ -59,7 +59,7 @@ def run(filter = "", opts = {}) puts yellow(suite.execution_message) suite.each_instrumentation_method do |method| if opts.key?(:method) && method != opts[:method] && suite.instrumentation_permutations.length > 1 - puts "Skipping method '#{method}' while focusing only on '#{opts[:method]}'" if ENV["VERBOSE_TEST_OUTPUT"] + puts "Skipping method '#{method}' while focusing only on '#{opts[:method]}'" if ENV['VERBOSE_TEST_OUTPUT'] next end suite.execute(method) @@ -67,7 +67,7 @@ def run(filter = "", opts = {}) end end - def prime(filter = "", opts = {}) + def prime(filter = '', opts = {}) execute_suites(filter, opts) do |suite| suite.prime end @@ -79,7 +79,7 @@ def execute_suites(filter, opts) next if dir.start_with?('.') next unless passes_filter?(dir, filter) - next unless File.exist?(File.join(full_path, "Envfile")) + next unless File.exist?(File.join(full_path, 'Envfile')) begin suite = Suite.new(full_path, opts) @@ -98,20 +98,20 @@ def execute_suites(filter, opts) end GROUPS = { - "agent" => %w[agent_only bare config_file_loading deferred_instrumentation high_security no_json json marshalling thread yajl], - "background" => %w[delayed_job sidekiq resque], - "background_2" => ["rake"], - "database" => %w[elasticsearch mongo redis sequel], - "rails" => %w[active_record active_record_pg rails rails_prepend activemerchant], - "frameworks" => %w[sinatra padrino grape], - "httpclients" => %w[curb excon httpclient], - "httpclients_2" => %w[typhoeus net_http httprb], - "infinite_tracing" => ["infinite_tracing"], - - "rest" => [] # Specially handled below + 'agent' => %w[agent_only bare config_file_loading deferred_instrumentation high_security no_json json marshalling thread yajl], + 'background' => %w[delayed_job sidekiq resque], + 'background_2' => ['rake'], + 'database' => %w[elasticsearch mongo redis sequel], + 'rails' => %w[active_record active_record_pg rails rails_prepend activemerchant], + 'frameworks' => %w[sinatra padrino grape], + 'httpclients' => %w[curb excon httpclient], + 'httpclients_2' => %w[typhoeus net_http httprb], + 'infinite_tracing' => ['infinite_tracing'], + + 'rest' => [] # Specially handled below } - if RUBY_PLATFORM == "java" + if RUBY_PLATFORM == 'java' GROUPS['agent'].delete('agent_only') end @@ -122,7 +122,7 @@ def execute_suites(filter, opts) end def excluded?(suite) - return true if suite == 'agent_only' and RUBY_PLATFORM == "java" + return true if suite == 'agent_only' and RUBY_PLATFORM == 'java' return true if suite == 'active_record' and RUBY_VERSION >= '3.0.0' end @@ -131,8 +131,8 @@ def passes_filter?(dir, filter) return false if excluded?(dir) - if filter.include?("group=") - keys = filter.sub("group=", "").split(';') # supports multiple groups passed in ";" delimited + if filter.include?('group=') + keys = filter.sub('group=', '').split(';') # supports multiple groups passed in ";" delimited combined_groups = [] # grabs all the suites that are in each of the groups passed in @@ -151,7 +151,7 @@ def passes_filter?(dir, filter) # the "rest" group is one of the groups being passed in AND the directory is not in any other group # OR # the directory is one of the suites included in one of the non-rest groups passed in - (keys.include?("rest") && !GROUPS.values.flatten.include?(dir)) || (combined_groups.any? && combined_groups.include?(dir)) + (keys.include?('rest') && !GROUPS.values.flatten.include?(dir)) || (combined_groups.any? && combined_groups.include?(dir)) else dir.eql?(filter) end diff --git a/test/multiverse/lib/multiverse/suite.rb b/test/multiverse/lib/multiverse/suite.rb index 87df88e182..8864aeadb5 100755 --- a/test/multiverse/lib/multiverse/suite.rb +++ b/test/multiverse/lib/multiverse/suite.rb @@ -29,7 +29,7 @@ class Suite def initialize(directory, opts = {}) self.directory = File.expand_path(directory) self.opts = opts - ENV["VERBOSE"] = '1' if opts[:verbose] + ENV['VERBOSE'] = '1' if opts[:verbose] end def self.encode_options(decoded_opts) @@ -45,7 +45,7 @@ def suite end def seed - opts.fetch(:seed, "") + opts.fetch(:seed, '') end def debug @@ -100,7 +100,7 @@ def environments # load the environment for this suite after we've forked def load_dependencies(gemfile_text, env_index, should_print = true) - ENV["BUNDLE_GEMFILE"] = "Gemfile.#{env_index}" + ENV['BUNDLE_GEMFILE'] = "Gemfile.#{env_index}" clean_gemfiles(env_index) begin generate_gemfile(gemfile_text, env_index) @@ -109,7 +109,7 @@ def load_dependencies(gemfile_text, env_index, should_print = true) if verbose? puts "#{e.class}: #{e}" puts e.backtrace - puts "Fast local bundle failed. Attempting to install from rubygems.org" + puts 'Fast local bundle failed. Attempting to install from rubygems.org' end clean_gemfiles(env_index) generate_gemfile(gemfile_text, env_index, false) @@ -127,7 +127,7 @@ def with_potentially_mismatched_bundler puts "Encountered Bundler error: #{error.message}" puts "Currently Active Bundler Version: #{::Bundler::VERSION}" end - change_lock_version(`pwd`, ENV["BUNDLE_GEMFILE"]) + change_lock_version(`pwd`, ENV['BUNDLE_GEMFILE']) @retried = true retry end @@ -146,20 +146,20 @@ def bundler_cache_dir # Ensures we bundle will recognize an explicit version number on command line def safe_explicit(version) - return version if version.to_s == "" + return version if version.to_s == '' test_version = `bundle #{version} --version`.include?('Could not find command') - test_version ? "" : version + test_version ? '' : version end def explicit_bundler_version(dir) - fn = File.join(dir, ".bundler-version") + fn = File.join(dir, '.bundler-version') version = File.exist?(fn) ? File.read(fn).chomp.to_s.strip : nil - safe_explicit(version.to_s == "" ? nil : "_#{version}_") + safe_explicit(version.to_s == '' ? nil : "_#{version}_") end def bundle_show_env(bundle_cmd) - return unless ENV["BUNDLE_SHOW_ENV"] + return unless ENV['BUNDLE_SHOW_ENV'] puts `#{bundle_cmd} env` end @@ -176,13 +176,13 @@ def bundle_install(dir) full_bundle_cmd = "#{bundle_cmd} install" result = ShellUtils.try_command_n_times(full_bundle_cmd, 3) unless $?.success? - puts "Failed local bundle, trying again without the version lock..." - change_lock_version(dir, ENV["BUNDLE_GEMFILE"]) + puts 'Failed local bundle, trying again without the version lock...' + change_lock_version(dir, ENV['BUNDLE_GEMFILE']) result = ShellUtils.try_command_n_times(full_bundle_cmd, 3) end result = red(result) unless $?.success? - puts result if ENV["VERBOSE_TEST_OUTPUT"] + puts result if ENV['VERBOSE_TEST_OUTPUT'] $? end @@ -267,7 +267,7 @@ def ensure_bundle_uncached(env_index) end def ruby3_gem_webrick - RUBY_VERSION >= "3.0.0" ? "gem 'webrick'" : "" + RUBY_VERSION >= '3.0.0' ? "gem 'webrick'" : '' end def generate_gemfile(gemfile_text, env_index, local = true) @@ -275,8 +275,8 @@ def generate_gemfile(gemfile_text, env_index, local = true) File.open(gemfile, 'w') do |f| f.puts 'source "https://rubygems.org"' f.print gemfile_text - f.puts newrelic_gemfile_line unless gemfile_text =~ /^\s*gem .newrelic_rpm./ - f.puts minitest_line unless gemfile_text =~ /^\s*gem .minitest[^_]./ + f.puts newrelic_gemfile_line unless /^\s*gem .newrelic_rpm./.match?(gemfile_text) + f.puts minitest_line unless /^\s*gem .minitest[^_]./.match?(gemfile_text) f.puts "gem 'rake'" unless gemfile_text =~ /^\s*gem .rake[^_]./ || suite == 'rake' f.puts "gem 'rackup'" if need_rackup?(gemfile_text) @@ -348,7 +348,7 @@ def require_minitest end def print_environment - puts yellow("Environment loaded with:") if verbose? + puts yellow('Environment loaded with:') if verbose? gems = with_potentially_mismatched_bundler do ::Bundler.definition.specs.inject([]) do |m, s| next m if s.name == 'bundler' @@ -383,17 +383,17 @@ def print_environment # continuous integration server. We do this by passing -Xverify:none to # the JVM. def optimize_jruby_startups - return unless RUBY_PLATFORM == "java" + return unless RUBY_PLATFORM == 'java' - ENV["JRUBY_OPTS"] = "--dev" + ENV['JRUBY_OPTS'] = '--dev' end def execute_child_environment(env_index, instrumentation_method) with_unbundled_env do configure_instrumentation_method(instrumentation_method) optimize_jruby_startups - ENV["MULTIVERSE_ENV"] = env_index.to_s - ENV["MULTIVERSE_INSTRUMENTATION_METHOD"] = instrumentation_method + ENV['MULTIVERSE_ENV'] = env_index.to_s + ENV['MULTIVERSE_INSTRUMENTATION_METHOD'] = instrumentation_method log_test_running_process configure_before_bundling @@ -427,7 +427,7 @@ def check_environment_condition end def prime - ENV["VERBOSE"] = "1" + ENV['VERBOSE'] = '1' return unless check_environment_condition puts yellow("\nPriming #{directory.inspect}") @@ -462,17 +462,17 @@ def execute(instrumentation_method) configure_instrumentation_method(instrumentation_method) - environments.before.call if environments.before + environments.before&.call if should_serialize? execute_serial(instrumentation_method) else execute_parallel(instrumentation_method) end - environments.after.call if environments.after + environments.after&.call rescue => e puts e.backtrace puts red("Failure during execution of suite #{directory.inspect}.") - puts red("This typically is a result of a Ruby failure in your Envfile.") + puts red('This typically is a result of a Ruby failure in your Envfile.') puts puts red(e.class) puts red(e.message) @@ -567,17 +567,17 @@ def trigger_test_run # Autorun behaves differently across the different Ruby version we have # to support, so this is simplest for making our test running consistent options = [] - options << "-v" if verbose? - options << "--seed=#{seed}" unless seed == "" - options << "--name=/#{names.map { |n| n + ".*" }.join("|")}/" unless names == [] + options << '-v' if verbose? + options << "--seed=#{seed}" unless seed == '' + options << "--name=/#{names.map { |n| n + '.*' }.join('|')}/" unless names == [] original_options = options.dup # MiniTest 5.0 moved things around, so choose which way to run it if ::MiniTest.respond_to?(:run) - test_run = ::MiniTest.run(options) + passed = ::MiniTest.run(options) else - test_run = ::MiniTest::Unit.new.run(options) + passed = ::MiniTest::Unit.new.run(options) end load(@after_file) if @after_file @@ -593,13 +593,9 @@ def trigger_test_run end end - if test_run - exit(test_run) - else - puts "No tests found with those options." - puts "options: #{original_options}" - exit(1) - end + puts 'One or more failures or errors were seen!' unless passed + puts "Options used: #{original_options}" + exit(passed) # `exit true` returns 0, `exit false` returns 1 end def configure_before_bundling @@ -652,15 +648,15 @@ def disable_harvest_thread # destabilizing if it's running. Also, multiple restarts result in lots of # threads running in some test suites. - ENV["NEWRELIC_DISABLE_HARVEST_THREAD"] = "true" + ENV['NEWRELIC_DISABLE_HARVEST_THREAD'] = 'true' end def configure_fake_collector - ENV["NEWRELIC_OMIT_FAKE_COLLECTOR"] = "true" if environments.omit_collector + ENV['NEWRELIC_OMIT_FAKE_COLLECTOR'] = 'true' if environments.omit_collector end def configure_instrumentation_method(method) - ENV["MULTIVERSE_INSTRUMENTATION_METHOD"] = $instrumentation_method = method + ENV['MULTIVERSE_INSTRUMENTATION_METHOD'] = $instrumentation_method = method end def require_helpers @@ -677,15 +673,15 @@ def execute_ruby_files next if exclude?(file) ENV['FILTER_FILE'] = filter_file if filter_file && infinite_tracing_suite? - require "./" + File.basename(file, ".rb") + require './' + File.basename(file, '.rb') end end def ordered_ruby_files(directory) files = Dir[File.join(directory, '*.rb')] - @before_file = files.find { |file| File.basename(file) == "before_suite.rb" } - @after_file = files.find { |file| File.basename(file) == "after_suite.rb" } + @before_file = files.find { |file| File.basename(file) == 'before_suite.rb' } + @after_file = files.find { |file| File.basename(file) == 'after_suite.rb' } files.delete(@before_file) files.delete(@after_file) @@ -702,7 +698,7 @@ def ordered_ruby_files(directory) end def verbose? - ENV['VERBOSE'] == "1" || ENV['VERBOSE'] == "true" + ENV['VERBOSE'] == '1' || ENV['VERBOSE'] == 'true' end # Sidekiq v4.2.0 and later will bail out at startup if we try to diff --git a/test/multiverse/lib/multiverse/time_report_output.rb b/test/multiverse/lib/multiverse/time_report_output.rb index 3d7502845e..9127caa66d 100644 --- a/test/multiverse/lib/multiverse/time_report_output.rb +++ b/test/multiverse/lib/multiverse/time_report_output.rb @@ -9,7 +9,7 @@ def sort_and_print_test_times test_times = hash_values_to_float(test_times) print_top_ten(sort_ten_slowest_tests(test_times)) else - puts yellow('Test timing data not found.') if ENV["VERBOSE_TEST_OUTPUT"] + puts yellow('Test timing data not found.') if ENV['VERBOSE_TEST_OUTPUT'] end end @@ -27,7 +27,7 @@ def hash_values_to_float(original_hash) end def print_top_ten(top_ten) - return unless ENV["VERBOSE_TEST_OUTPUT"] + return unless ENV['VERBOSE_TEST_OUTPUT'] puts "\n====== Ten slowest tests ======\n" top_ten.each_with_index do |element, index| diff --git a/test/multiverse/suites/active_record/Rakefile b/test/multiverse/suites/active_record/Rakefile index 897a142a8d..92eeebd24e 100644 --- a/test/multiverse/suites/active_record/Rakefile +++ b/test/multiverse/suites/active_record/Rakefile @@ -4,7 +4,7 @@ require_relative 'config/database' -desc "Setup for ActiveRecord" +desc 'Setup for ActiveRecord' task :environment do if defined?(DatabaseTasks) ActiveRecord::Base.configurations = DatabaseTasks.database_configuration diff --git a/test/multiverse/suites/active_record/active_record_test.rb b/test/multiverse/suites/active_record/active_record_test.rb index 7d5818d29d..4fc0f0e1b9 100644 --- a/test/multiverse/suites/active_record/active_record_test.rb +++ b/test/multiverse/suites/active_record/active_record_test.rb @@ -29,7 +29,7 @@ def active_record_version if defined?(::ActiveRecord::VERSION::MINOR) Gem::Version.new(::ActiveRecord::VERSION::STRING) else - Gem::Version.new("2.1.0") # Can't tell between 2.1 and 2.2. Meh. + Gem::Version.new('2.1.0') # Can't tell between 2.1 and 2.2. Meh. end end end @@ -159,7 +159,7 @@ def test_metrics_for_find_via_named_scope def test_metrics_for_exists in_web_transaction do - Order.exists?(["name=?", "jeff"]) + Order.exists?(['name=?', 'jeff']) end if active_record_major_version == 3 && [0, 1].include?(active_record_minor_version) @@ -201,7 +201,7 @@ def test_metrics_for_delete_all def test_metrics_for_relation_delete in_web_transaction do - order = Order.create(:name => "lava") + order = Order.create(:name => 'lava') Order.delete(order.id) end @@ -216,7 +216,7 @@ def test_metrics_for_relation_delete if active_record_version >= Gem::Version.new('3.0.0') def test_metrics_for_delete in_web_transaction do - order = Order.create("name" => "burt") + order = Order.create('name' => 'burt') order.delete end @@ -225,7 +225,7 @@ def test_metrics_for_delete def test_metrics_for_touch in_web_transaction do - order = Order.create("name" => "wendy") + order = Order.create('name' => 'wendy') order.touch end @@ -353,7 +353,7 @@ def test_destroy_via_dependent_destroy if active_record_version >= Gem::Version.new('4.0.0') def test_metrics_for_update in_web_transaction do - order = Order.create(:name => "wendy") + order = Order.create(:name => 'wendy') order.update(:name => 'walter') end @@ -362,7 +362,7 @@ def test_metrics_for_update def test_metrics_for_update_bang in_web_transaction do - order = Order.create(:name => "wendy") + order = Order.create(:name => 'wendy') order.update!(:name => 'walter') end @@ -372,7 +372,7 @@ def test_metrics_for_update_bang def test_metrics_for_update_attribute in_web_transaction do - order = Order.create(:name => "wendy") + order = Order.create(:name => 'wendy') order.update_attribute(:name, 'walter') end @@ -381,7 +381,7 @@ def test_metrics_for_update_attribute def test_metrics_for_save in_web_transaction do - order = Order.create(:name => "wendy") + order = Order.create(:name => 'wendy') order.name = 'walter' order.save end @@ -391,7 +391,7 @@ def test_metrics_for_save def test_metrics_for_save_bang in_web_transaction do - order = Order.create(:name => "wendy") + order = Order.create(:name => 'wendy') order.name = 'walter' order.save! end @@ -401,18 +401,18 @@ def test_metrics_for_save_bang def test_nested_metrics_dont_get_model_name in_web_transaction do - order = Order.create(:name => "wendy") + order = Order.create(:name => 'wendy') order.name = 'walter' order.save! end - assert_metrics_recorded(["Datastore/operation/Memcached/get"]) + assert_metrics_recorded(['Datastore/operation/Memcached/get']) refute_metrics_match(/Memcached.*Order/) end def test_metrics_for_destroy in_web_transaction do - order = Order.create("name" => "burt") + order = Order.create('name' => 'burt') order.destroy end @@ -431,8 +431,8 @@ def test_metrics_for_direct_sql_select def test_metrics_for_direct_sql_other in_web_transaction do conn = Order.connection - conn.execute("begin") - conn.execute("commit") + conn.execute('begin') + conn.execute('commit') end assert_generic_rollup_metrics('other') @@ -442,7 +442,7 @@ def test_metrics_for_direct_sql_show if supports_show_tables? in_web_transaction do conn = Order.connection - conn.execute("show tables") + conn.execute('show tables') end assert_generic_rollup_metrics('show') @@ -453,7 +453,7 @@ def test_still_records_metrics_in_error_cases # Let's trigger an active record SQL StatementInvalid error assert_raises ::ActiveRecord::StatementInvalid do in_web_transaction do - Order.connection.select_rows("select * from askdjfhkajsdhflkjh") + Order.connection.select_rows('select * from askdjfhkajsdhflkjh') end end @@ -480,8 +480,8 @@ def test_only_supportability_metrics_recorded_with_disable_all_tracing refute last_transaction_trace assert_metrics_recorded_exclusive([ - "Supportability/API/disable_all_tracing", - "Supportability/API/drop_buffered_data" + 'Supportability/API/disable_all_tracing', + 'Supportability/API/drop_buffered_data' ]) end @@ -585,7 +585,7 @@ def test_cached_calls_are_not_recorded_with_select_all def test_with_database_metric_name in_web_transaction do - Order.create(:name => "eely") + Order.create(:name => 'eely') NewRelic::Agent.with_database_metric_name('Eel', 'squirm') do Order.connection.select_rows("SELECT id FROM #{Order.table_name}") end @@ -636,16 +636,16 @@ def assert_activerecord_metrics(model, operation, stats = {}) assert_metrics_recorded({ "Datastore/statement/#{current_product}/#{model}/#{operation}" => stats, "Datastore/operation/#{current_product}/#{operation}" => {}, - "Datastore/allWeb" => {}, - "Datastore/all" => {} + 'Datastore/allWeb' => {}, + 'Datastore/all' => {} }) end def assert_generic_rollup_metrics(operation) assert_metrics_recorded([ "Datastore/operation/#{current_product}/#{operation}", - "Datastore/allWeb", - "Datastore/all" + 'Datastore/allWeb', + 'Datastore/all' ]) end end diff --git a/test/multiverse/suites/active_record/app/models/models.rb b/test/multiverse/suites/active_record/app/models/models.rb index 5a104a6f79..75236a79e8 100644 --- a/test/multiverse/suites/active_record/app/models/models.rb +++ b/test/multiverse/suites/active_record/app/models/models.rb @@ -23,7 +23,7 @@ class Order < ActiveRecord::Base validate :touches_another_datastore def touches_another_datastore - NewRelic::Agent::Datastores.wrap("Memcached", "get") do + NewRelic::Agent::Datastores.wrap('Memcached', 'get') do # Fake hitting a cache during validation end end diff --git a/test/multiverse/suites/active_record/ar_method_aliasing.rb b/test/multiverse/suites/active_record/ar_method_aliasing.rb index 0b229dc15a..03825b084b 100644 --- a/test/multiverse/suites/active_record/ar_method_aliasing.rb +++ b/test/multiverse/suites/active_record/ar_method_aliasing.rb @@ -15,7 +15,7 @@ class InstrumentActiveRecordMethods < Minitest::Test setup_and_teardown_agent def test_basic_creation - a_user = User.new(:name => "Bob") + a_user = User.new(:name => 'Bob') assert_predicate a_user, :new_record? a_user.save! @@ -25,14 +25,14 @@ def test_basic_creation end def test_alias_collection_query_method - a_user = User.new(:name => "Bob") + a_user = User.new(:name => 'Bob') a_user.save! a_user = User.first assert_predicate User, :connected? - an_alias = Alias.new(:user_id => a_user.id, :aka => "the Blob") + an_alias = Alias.new(:user_id => a_user.id, :aka => 'the Blob') assert_predicate an_alias, :new_record? an_alias.save! diff --git a/test/multiverse/suites/active_record/before_suite.rb b/test/multiverse/suites/active_record/before_suite.rb index c83d2fc714..46cd044e77 100644 --- a/test/multiverse/suites/active_record/before_suite.rb +++ b/test/multiverse/suites/active_record/before_suite.rb @@ -4,7 +4,7 @@ def redefine_mysql_primary_key(const_str) const = Object.const_get(const_str) rescue return - const[:primary_key] = "int(11) auto_increment PRIMARY KEY" + const[:primary_key] = 'int(11) auto_increment PRIMARY KEY' end # MySql 5.7 and later no longer support NULL in primary keys @@ -14,8 +14,8 @@ def redefine_mysql_primary_key(const_str) require 'active_record' require 'active_record/connection_adapters/mysql2_adapter' - redefine_mysql_primary_key "::ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter::NATIVE_DATABASE_TYPES" - redefine_mysql_primary_key "::ActiveRecord::ConnectionAdapters::Mysql2Adapter::NATIVE_DATABASE_TYPES" + redefine_mysql_primary_key '::ActiveRecord::ConnectionAdapters::AbstractMysqlAdapter::NATIVE_DATABASE_TYPES' + redefine_mysql_primary_key '::ActiveRecord::ConnectionAdapters::Mysql2Adapter::NATIVE_DATABASE_TYPES' end begin diff --git a/test/multiverse/suites/active_record/config/database.rb b/test/multiverse/suites/active_record/config/database.rb index f0d71700a5..57510fe964 100644 --- a/test/multiverse/suites/active_record/config/database.rb +++ b/test/multiverse/suites/active_record/config/database.rb @@ -12,9 +12,9 @@ config_dir = File.expand_path(File.dirname(__FILE__)) if defined?(ActiveRecord::VERSION) - ENV['DATABASE_NAME'] = "multiverse_activerecord_#{ActiveRecord::VERSION::STRING}_#{RUBY_VERSION}_#{RUBY_ENGINE}".tr(".", "_") + ENV['DATABASE_NAME'] = "multiverse_activerecord_#{ActiveRecord::VERSION::STRING}_#{RUBY_VERSION}_#{RUBY_ENGINE}".tr('.', '_') else - ENV['DATABASE_NAME'] = "multiverse_activerecord_2_x_#{ENV["MULTIVERSE_ENV"]}_#{RUBY_VERSION}_#{RUBY_ENGINE}".tr(".", "_") + ENV['DATABASE_NAME'] = "multiverse_activerecord_2_x_#{ENV['MULTIVERSE_ENV']}_#{RUBY_VERSION}_#{RUBY_ENGINE}".tr('.', '_') end config_raw = File.read(File.join(config_dir, 'database.yml')) @@ -26,12 +26,12 @@ end # Rails 2.x didn't keep the Rails out of ActiveRecord much... -RAILS_ENV = "test" -RAILS_ROOT = File.join(db_dir, "..") +RAILS_ENV = 'test' +RAILS_ROOT = File.join(db_dir, '..') ActiveRecord::Base.configurations = config_yml ActiveRecord::Base.establish_connection(:test) -ActiveRecord::Base.logger = Logger.new(ENV["VERBOSE"] ? STDOUT : StringIO.new) +ActiveRecord::Base.logger = Logger.new(ENV['VERBOSE'] ? STDOUT : StringIO.new) begin load('active_record/railties/databases.rake') @@ -48,7 +48,7 @@ def self.load_seed end end - DatabaseTasks.env = "test" + DatabaseTasks.env = 'test' DatabaseTasks.db_dir = db_dir DatabaseTasks.migrations_paths = File.join(db_dir, 'migrate') DatabaseTasks.database_configuration = config_yml @@ -63,7 +63,7 @@ def root end def env - ActiveSupport::StringInquirer.new(ENV["RACK_ENV"] || "development") + ActiveSupport::StringInquirer.new(ENV['RACK_ENV'] || 'development') end def application @@ -77,7 +77,7 @@ def load_seed end end - Rake::Task.define_task("db:environment") - Rake::Task["db:load_config"].clear if Rake::Task.task_defined?("db:load_config") - Rake::Task.define_task("db:rails_env") + Rake::Task.define_task('db:environment') + Rake::Task['db:load_config'].clear if Rake::Task.task_defined?('db:load_config') + Rake::Task.define_task('db:rails_env') end diff --git a/test/multiverse/suites/active_record_pg/Rakefile b/test/multiverse/suites/active_record_pg/Rakefile index a381a6c84a..8ad535f61c 100644 --- a/test/multiverse/suites/active_record_pg/Rakefile +++ b/test/multiverse/suites/active_record_pg/Rakefile @@ -4,7 +4,7 @@ require File.expand_path('config/database') -desc "Setup for ActiveRecord" +desc 'Setup for ActiveRecord' task :environment do if defined?(DatabaseTasks) ActiveRecord::Base.configurations = DatabaseTasks.database_configuration diff --git a/test/multiverse/suites/active_record_pg/active_record_test.rb b/test/multiverse/suites/active_record_pg/active_record_test.rb index 9e17772543..2b64e22ce5 100644 --- a/test/multiverse/suites/active_record_pg/active_record_test.rb +++ b/test/multiverse/suites/active_record_pg/active_record_test.rb @@ -158,7 +158,7 @@ def test_metrics_for_find_via_named_scope def test_metrics_for_exists in_web_transaction do - Order.exists?(["name=?", "jeff"]) + Order.exists?(['name=?', 'jeff']) end if active_record_major_version >= 6 @@ -195,7 +195,7 @@ def test_metrics_for_delete_all def test_metrics_for_relation_delete in_web_transaction do - order = Order.create(:name => "lava") + order = Order.create(:name => 'lava') Order.delete(order.id) end @@ -204,7 +204,7 @@ def test_metrics_for_relation_delete def test_metrics_for_delete in_web_transaction do - order = Order.create("name" => "burt") + order = Order.create('name' => 'burt') order.delete end @@ -217,7 +217,7 @@ def test_metrics_for_delete def test_metrics_for_touch in_web_transaction do - order = Order.create("name" => "wendy") + order = Order.create('name' => 'wendy') order.touch end @@ -333,7 +333,7 @@ def test_destroy_via_dependent_destroy if active_record_version >= Gem::Version.new('4.0.0') def test_metrics_for_update in_web_transaction do - order = Order.create(:name => "wendy") + order = Order.create(:name => 'wendy') order.update(:name => 'walter') end @@ -342,7 +342,7 @@ def test_metrics_for_update def test_metrics_for_update_bang in_web_transaction do - order = Order.create(:name => "wendy") + order = Order.create(:name => 'wendy') order.update!(:name => 'walter') end @@ -352,7 +352,7 @@ def test_metrics_for_update_bang def test_metrics_for_update_attribute in_web_transaction do - order = Order.create(:name => "wendy") + order = Order.create(:name => 'wendy') order.update_attribute(:name, 'walter') end @@ -361,7 +361,7 @@ def test_metrics_for_update_attribute def test_metrics_for_save in_web_transaction do - order = Order.create(:name => "wendy") + order = Order.create(:name => 'wendy') order.name = 'walter' order.save end @@ -371,7 +371,7 @@ def test_metrics_for_save def test_metrics_for_save_bang in_web_transaction do - order = Order.create(:name => "wendy") + order = Order.create(:name => 'wendy') order.name = 'walter' order.save! end @@ -381,18 +381,18 @@ def test_metrics_for_save_bang def test_nested_metrics_dont_get_model_name in_web_transaction do - order = Order.create(:name => "wendy") + order = Order.create(:name => 'wendy') order.name = 'walter' order.save! end - assert_metrics_recorded(["Datastore/operation/Memcached/get"]) + assert_metrics_recorded(['Datastore/operation/Memcached/get']) refute_metrics_match(/Memcached.*Order/) end def test_metrics_for_destroy in_web_transaction do - order = Order.create("name" => "burt") + order = Order.create('name' => 'burt') order.destroy end @@ -415,8 +415,8 @@ def test_metrics_for_direct_sql_select def test_metrics_for_direct_sql_other in_web_transaction do conn = Order.connection - conn.execute("begin") - conn.execute("commit") + conn.execute('begin') + conn.execute('commit') end assert_generic_rollup_metrics('other') @@ -426,7 +426,7 @@ def test_metrics_for_direct_sql_show if supports_show_tables? in_web_transaction do conn = Order.connection - conn.execute("show tables") + conn.execute('show tables') end assert_generic_rollup_metrics('show') @@ -437,7 +437,7 @@ def test_still_records_metrics_in_error_cases # Let's trigger an active record SQL StatementInvalid error assert_raises ::ActiveRecord::StatementInvalid do in_web_transaction do - Order.connection.select_rows("select * from askdjfhkajsdhflkjh") + Order.connection.select_rows('select * from askdjfhkajsdhflkjh') end end @@ -464,8 +464,8 @@ def test_only_supportability_metrics_recorded_with_disable_all_tracing refute last_transaction_trace assert_metrics_recorded_exclusive([ - "Supportability/API/disable_all_tracing", - "Supportability/API/drop_buffered_data" + 'Supportability/API/disable_all_tracing', + 'Supportability/API/drop_buffered_data' ]) end @@ -569,7 +569,7 @@ def test_cached_calls_are_not_recorded_with_select_all def test_with_database_metric_name in_web_transaction do - Order.create(:name => "eely") + Order.create(:name => 'eely') NewRelic::Agent.with_database_metric_name('Eel', 'squirm') do Order.connection.select_rows("SELECT id FROM #{Order.table_name}") end @@ -626,16 +626,16 @@ def assert_activerecord_metrics(model, operation, stats = {}) assert_metrics_recorded({ "Datastore/statement/#{current_product}/#{model}/#{operation}" => stats, "Datastore/operation/#{current_product}/#{operation}" => {}, - "Datastore/allWeb" => {}, - "Datastore/all" => {} + 'Datastore/allWeb' => {}, + 'Datastore/all' => {} }) end def assert_generic_rollup_metrics(operation) assert_metrics_recorded([ "Datastore/operation/#{current_product}/#{operation}", - "Datastore/allWeb", - "Datastore/all" + 'Datastore/allWeb', + 'Datastore/all' ]) end end diff --git a/test/multiverse/suites/active_record_pg/app/models/models.rb b/test/multiverse/suites/active_record_pg/app/models/models.rb index 7cb68a0568..8da34c39ec 100644 --- a/test/multiverse/suites/active_record_pg/app/models/models.rb +++ b/test/multiverse/suites/active_record_pg/app/models/models.rb @@ -25,7 +25,7 @@ class Order < ActiveRecord::Base validate :touches_another_datastore def touches_another_datastore - NewRelic::Agent::Datastores.wrap("Memcached", "get") do + NewRelic::Agent::Datastores.wrap('Memcached', 'get') do # Fake hitting a cache during validation end end diff --git a/test/multiverse/suites/active_record_pg/ar_method_aliasing.rb b/test/multiverse/suites/active_record_pg/ar_method_aliasing.rb index 0b229dc15a..03825b084b 100644 --- a/test/multiverse/suites/active_record_pg/ar_method_aliasing.rb +++ b/test/multiverse/suites/active_record_pg/ar_method_aliasing.rb @@ -15,7 +15,7 @@ class InstrumentActiveRecordMethods < Minitest::Test setup_and_teardown_agent def test_basic_creation - a_user = User.new(:name => "Bob") + a_user = User.new(:name => 'Bob') assert_predicate a_user, :new_record? a_user.save! @@ -25,14 +25,14 @@ def test_basic_creation end def test_alias_collection_query_method - a_user = User.new(:name => "Bob") + a_user = User.new(:name => 'Bob') a_user.save! a_user = User.first assert_predicate User, :connected? - an_alias = Alias.new(:user_id => a_user.id, :aka => "the Blob") + an_alias = Alias.new(:user_id => a_user.id, :aka => 'the Blob') assert_predicate an_alias, :new_record? an_alias.save! diff --git a/test/multiverse/suites/active_record_pg/before_suite.rb b/test/multiverse/suites/active_record_pg/before_suite.rb index f0fc5aa88f..70a2d932ee 100644 --- a/test/multiverse/suites/active_record_pg/before_suite.rb +++ b/test/multiverse/suites/active_record_pg/before_suite.rb @@ -4,7 +4,7 @@ def redefine_mysql_primary_key(const_str) const = Object.const_get(const_str) rescue return - const[:primary_key] = "int(11) auto_increment PRIMARY KEY" + const[:primary_key] = 'int(11) auto_increment PRIMARY KEY' end begin diff --git a/test/multiverse/suites/active_record_pg/config/database.rb b/test/multiverse/suites/active_record_pg/config/database.rb index f0d71700a5..57510fe964 100644 --- a/test/multiverse/suites/active_record_pg/config/database.rb +++ b/test/multiverse/suites/active_record_pg/config/database.rb @@ -12,9 +12,9 @@ config_dir = File.expand_path(File.dirname(__FILE__)) if defined?(ActiveRecord::VERSION) - ENV['DATABASE_NAME'] = "multiverse_activerecord_#{ActiveRecord::VERSION::STRING}_#{RUBY_VERSION}_#{RUBY_ENGINE}".tr(".", "_") + ENV['DATABASE_NAME'] = "multiverse_activerecord_#{ActiveRecord::VERSION::STRING}_#{RUBY_VERSION}_#{RUBY_ENGINE}".tr('.', '_') else - ENV['DATABASE_NAME'] = "multiverse_activerecord_2_x_#{ENV["MULTIVERSE_ENV"]}_#{RUBY_VERSION}_#{RUBY_ENGINE}".tr(".", "_") + ENV['DATABASE_NAME'] = "multiverse_activerecord_2_x_#{ENV['MULTIVERSE_ENV']}_#{RUBY_VERSION}_#{RUBY_ENGINE}".tr('.', '_') end config_raw = File.read(File.join(config_dir, 'database.yml')) @@ -26,12 +26,12 @@ end # Rails 2.x didn't keep the Rails out of ActiveRecord much... -RAILS_ENV = "test" -RAILS_ROOT = File.join(db_dir, "..") +RAILS_ENV = 'test' +RAILS_ROOT = File.join(db_dir, '..') ActiveRecord::Base.configurations = config_yml ActiveRecord::Base.establish_connection(:test) -ActiveRecord::Base.logger = Logger.new(ENV["VERBOSE"] ? STDOUT : StringIO.new) +ActiveRecord::Base.logger = Logger.new(ENV['VERBOSE'] ? STDOUT : StringIO.new) begin load('active_record/railties/databases.rake') @@ -48,7 +48,7 @@ def self.load_seed end end - DatabaseTasks.env = "test" + DatabaseTasks.env = 'test' DatabaseTasks.db_dir = db_dir DatabaseTasks.migrations_paths = File.join(db_dir, 'migrate') DatabaseTasks.database_configuration = config_yml @@ -63,7 +63,7 @@ def root end def env - ActiveSupport::StringInquirer.new(ENV["RACK_ENV"] || "development") + ActiveSupport::StringInquirer.new(ENV['RACK_ENV'] || 'development') end def application @@ -77,7 +77,7 @@ def load_seed end end - Rake::Task.define_task("db:environment") - Rake::Task["db:load_config"].clear if Rake::Task.task_defined?("db:load_config") - Rake::Task.define_task("db:rails_env") + Rake::Task.define_task('db:environment') + Rake::Task['db:load_config'].clear if Rake::Task.task_defined?('db:load_config') + Rake::Task.define_task('db:rails_env') end diff --git a/test/multiverse/suites/activemerchant/activemerchant_test.rb b/test/multiverse/suites/activemerchant/activemerchant_test.rb index 7c4d6be054..784e059af0 100644 --- a/test/multiverse/suites/activemerchant/activemerchant_test.rb +++ b/test/multiverse/suites/activemerchant/activemerchant_test.rb @@ -18,7 +18,7 @@ def update(*_) class BadGateway < ActiveMerchant::Billing::BogusGateway def purchase(*args) super(*args) - raise StandardError.new("whoops!") + raise StandardError.new('whoops!') end end @@ -56,11 +56,11 @@ def test_store end def test_unstore - assert_merchant_transaction(:unstore, "1") + assert_merchant_transaction(:unstore, '1') end def test_noticed_error_at_segment_and_txn_on_error - expected_error_class = "StandardError" + expected_error_class = 'StandardError' txn = nil gateway = BadGateway.new begin @@ -77,7 +77,7 @@ def test_noticed_error_at_segment_and_txn_on_error end def test_noticed_error_only_at_segment_on_error - expected_error_class = "StandardError" + expected_error_class = 'StandardError' txn = nil gateway = BadGateway.new in_transaction do |local_txn| @@ -106,8 +106,8 @@ def assert_merchant_transaction(operation, *args) end assert_metrics_recorded([ - ["ActiveMerchant/gateway/BogusGateway/#{operation}", "txn"], - "ActiveMerchant/gateway/BogusGateway", + ["ActiveMerchant/gateway/BogusGateway/#{operation}", 'txn'], + 'ActiveMerchant/gateway/BogusGateway', "ActiveMerchant/operation/#{operation}" ]) end diff --git a/test/multiverse/suites/agent_only/adaptive_sampler_test.rb b/test/multiverse/suites/agent_only/adaptive_sampler_test.rb index 9752850aa5..ed66dead16 100644 --- a/test/multiverse/suites/agent_only/adaptive_sampler_test.rb +++ b/test/multiverse/suites/agent_only/adaptive_sampler_test.rb @@ -31,7 +31,7 @@ def test_adaptive_sampler_valid_stats_and_reset_after_harvest advance_process_time(60) - in_transaction("test_txn_20") {} + in_transaction('test_txn_20') {} stats = NewRelic::Agent.instance.adaptive_sampler.stats diff --git a/test/multiverse/suites/agent_only/agent_attributes_test.rb b/test/multiverse/suites/agent_only/agent_attributes_test.rb index fc4557498c..01d8837d69 100644 --- a/test/multiverse/suites/agent_only/agent_attributes_test.rb +++ b/test/multiverse/suites/agent_only/agent_attributes_test.rb @@ -12,11 +12,11 @@ def test_http_response_code_default_destinations txn.http_response_code = 418 end - assert_transaction_trace_has_agent_attribute("http.statusCode", 418) - assert_event_has_agent_attribute("http.statusCode", 418) - assert_error_has_agent_attribute("http.statusCode", 418) + assert_transaction_trace_has_agent_attribute('http.statusCode', 418) + assert_event_has_agent_attribute('http.statusCode', 418) + assert_error_has_agent_attribute('http.statusCode', 418) - refute_browser_monitoring_has_agent_attribute("http.statusCode") + refute_browser_monitoring_has_agent_attribute('http.statusCode') end def test_response_content_type_default_destinations @@ -24,11 +24,11 @@ def test_response_content_type_default_destinations txn.response_content_type = 'application/json' end - assert_transaction_trace_has_agent_attribute("response.headers.contentType", "application/json") - assert_event_has_agent_attribute("response.headers.contentType", "application/json") - assert_error_has_agent_attribute("response.headers.contentType", "application/json") + assert_transaction_trace_has_agent_attribute('response.headers.contentType', 'application/json') + assert_event_has_agent_attribute('response.headers.contentType', 'application/json') + assert_error_has_agent_attribute('response.headers.contentType', 'application/json') - refute_browser_monitoring_has_agent_attribute("response.headers.contentType") + refute_browser_monitoring_has_agent_attribute('response.headers.contentType') end def test_response_content_length_default_destinations @@ -36,97 +36,97 @@ def test_response_content_length_default_destinations txn.response_content_length = 100 end - assert_transaction_trace_has_agent_attribute("response.headers.contentLength", 100) - assert_event_has_agent_attribute("response.headers.contentLength", 100) - assert_error_has_agent_attribute("response.headers.contentLength", 100) + assert_transaction_trace_has_agent_attribute('response.headers.contentLength', 100) + assert_event_has_agent_attribute('response.headers.contentLength', 100) + assert_error_has_agent_attribute('response.headers.contentLength', 100) - refute_browser_monitoring_has_agent_attribute("response.headers.contentLength") + refute_browser_monitoring_has_agent_attribute('response.headers.contentLength') end def test_request_headers_referer_default_destinations - txn_options = {:request => stub(:referer => "referrer", :path => "/")} + txn_options = {:request => stub(:referer => 'referrer', :path => '/')} run_transaction({}, txn_options) do |txn| end - assert_error_has_agent_attribute("request.headers.referer", "referrer") + assert_error_has_agent_attribute('request.headers.referer', 'referrer') - refute_transaction_trace_has_agent_attribute("request.headers.referer") - refute_event_has_agent_attribute("request.headers.referer") - refute_browser_monitoring_has_agent_attribute("request.headers.referer") + refute_transaction_trace_has_agent_attribute('request.headers.referer') + refute_event_has_agent_attribute('request.headers.referer') + refute_browser_monitoring_has_agent_attribute('request.headers.referer') end def test_request_parameters_default_destinations_without_capture_params run_transaction(:capture_params => false) do |txn| - txn.merge_request_parameters(:duly => "noted") + txn.merge_request_parameters(:duly => 'noted') end - refute_transaction_trace_has_agent_attribute("request.parameters.duly") - refute_event_has_agent_attribute("request.parameters.duly") - refute_error_has_agent_attribute("request.parameters.duly") - refute_browser_monitoring_has_agent_attribute("request.parameters.duly") + refute_transaction_trace_has_agent_attribute('request.parameters.duly') + refute_event_has_agent_attribute('request.parameters.duly') + refute_error_has_agent_attribute('request.parameters.duly') + refute_browser_monitoring_has_agent_attribute('request.parameters.duly') end def test_request_parameters_default_destinations_with_capture_params run_transaction(:capture_params => true) do |txn| - txn.merge_request_parameters(:duly => "noted") + txn.merge_request_parameters(:duly => 'noted') end - assert_transaction_trace_has_agent_attribute("request.parameters.duly", "noted") - assert_error_has_agent_attribute("request.parameters.duly", "noted") + assert_transaction_trace_has_agent_attribute('request.parameters.duly', 'noted') + assert_error_has_agent_attribute('request.parameters.duly', 'noted') - refute_event_has_agent_attribute("request.parameters.duly") - refute_browser_monitoring_has_agent_attribute("request.parameters.duly") + refute_event_has_agent_attribute('request.parameters.duly') + refute_browser_monitoring_has_agent_attribute('request.parameters.duly') end def test_agent_attributes_assigned_from_request request = stub( - :path => "/", - :referer => "http://docs.newrelic.com", - :env => {"HTTP_ACCEPT" => "application/json"}, + :path => '/', + :referer => 'http://docs.newrelic.com', + :env => {'HTTP_ACCEPT' => 'application/json'}, :content_length => 103, - :content_type => "application/json", + :content_type => 'application/json', :host => 'chippy', :user_agent => 'Use This!', - :request_method => "GET" + :request_method => 'GET' ) run_transaction({}, {:request => request}) do |txn| end - assert_error_has_agent_attribute "request.headers.referer", "http://docs.newrelic.com" - refute_transaction_trace_has_agent_attribute "request.headers.referer" - refute_event_has_agent_attribute "request.headers.referer" - refute_browser_monitoring_has_agent_attribute "request.headers.referer" - - assert_transaction_trace_has_agent_attribute "request.headers.accept", "application/json" - assert_event_has_agent_attribute "request.headers.accept", "application/json" - assert_error_has_agent_attribute "request.headers.accept", "application/json" - refute_browser_monitoring_has_agent_attribute "request.headers.accept" - - assert_transaction_trace_has_agent_attribute "request.headers.contentLength", 103 - assert_event_has_agent_attribute "request.headers.contentLength", 103 - assert_error_has_agent_attribute "request.headers.contentLength", 103 - refute_browser_monitoring_has_agent_attribute "request.headers.contentLength" - - assert_transaction_trace_has_agent_attribute "request.headers.contentType", "application/json" - assert_event_has_agent_attribute "request.headers.contentType", "application/json" - assert_error_has_agent_attribute "request.headers.contentType", "application/json" - refute_browser_monitoring_has_agent_attribute "request.headers.contentType" - - assert_transaction_trace_has_agent_attribute "request.headers.host", "chippy" - assert_event_has_agent_attribute "request.headers.host", "chippy" - assert_error_has_agent_attribute "request.headers.host", "chippy" - refute_browser_monitoring_has_agent_attribute "request.headers.host" - - assert_transaction_trace_has_agent_attribute "request.headers.userAgent", "Use This!" - assert_event_has_agent_attribute "request.headers.userAgent", "Use This!" - assert_error_has_agent_attribute "request.headers.userAgent", "Use This!" - refute_browser_monitoring_has_agent_attribute "request.headers.userAgent" - - assert_transaction_trace_has_agent_attribute "request.method", "GET" - assert_event_has_agent_attribute "request.method", "GET" - assert_error_has_agent_attribute "request.method", "GET" - refute_browser_monitoring_has_agent_attribute "request.method" + assert_error_has_agent_attribute 'request.headers.referer', 'http://docs.newrelic.com' + refute_transaction_trace_has_agent_attribute 'request.headers.referer' + refute_event_has_agent_attribute 'request.headers.referer' + refute_browser_monitoring_has_agent_attribute 'request.headers.referer' + + assert_transaction_trace_has_agent_attribute 'request.headers.accept', 'application/json' + assert_event_has_agent_attribute 'request.headers.accept', 'application/json' + assert_error_has_agent_attribute 'request.headers.accept', 'application/json' + refute_browser_monitoring_has_agent_attribute 'request.headers.accept' + + assert_transaction_trace_has_agent_attribute 'request.headers.contentLength', 103 + assert_event_has_agent_attribute 'request.headers.contentLength', 103 + assert_error_has_agent_attribute 'request.headers.contentLength', 103 + refute_browser_monitoring_has_agent_attribute 'request.headers.contentLength' + + assert_transaction_trace_has_agent_attribute 'request.headers.contentType', 'application/json' + assert_event_has_agent_attribute 'request.headers.contentType', 'application/json' + assert_error_has_agent_attribute 'request.headers.contentType', 'application/json' + refute_browser_monitoring_has_agent_attribute 'request.headers.contentType' + + assert_transaction_trace_has_agent_attribute 'request.headers.host', 'chippy' + assert_event_has_agent_attribute 'request.headers.host', 'chippy' + assert_error_has_agent_attribute 'request.headers.host', 'chippy' + refute_browser_monitoring_has_agent_attribute 'request.headers.host' + + assert_transaction_trace_has_agent_attribute 'request.headers.userAgent', 'Use This!' + assert_event_has_agent_attribute 'request.headers.userAgent', 'Use This!' + assert_error_has_agent_attribute 'request.headers.userAgent', 'Use This!' + refute_browser_monitoring_has_agent_attribute 'request.headers.userAgent' + + assert_transaction_trace_has_agent_attribute 'request.method', 'GET' + assert_event_has_agent_attribute 'request.method', 'GET' + assert_error_has_agent_attribute 'request.method', 'GET' + refute_browser_monitoring_has_agent_attribute 'request.method' end def test_custom_attributes_included @@ -194,46 +194,46 @@ def test_custom_attributes_excluded_with_global_config def test_request_parameters_captured_on_transaction_events_when_enabled config = {:'transaction_events.attributes.include' => 'request.parameters.*'} txn_options = { - :filtered_params => {:foo => "bar", :bar => "baz"} + :filtered_params => {:foo => 'bar', :bar => 'baz'} } run_transaction(config, txn_options) - assert_event_has_agent_attribute("request.parameters.foo", "bar") - assert_event_has_agent_attribute("request.parameters.bar", "baz") + assert_event_has_agent_attribute('request.parameters.foo', 'bar') + assert_event_has_agent_attribute('request.parameters.bar', 'baz') end def test_request_parameters_captured_in_bam_when_enabled config = {:'browser_monitoring.attributes.include' => 'request.parameters.*'} txn_options = { - :filtered_params => {:foo => "bar", :bar => "baz"} + :filtered_params => {:foo => 'bar', :bar => 'baz'} } run_transaction(config, txn_options) - assert_browser_monitoring_has_agent_attribute("request.parameters.foo", "bar") - assert_browser_monitoring_has_agent_attribute("request.parameters.bar", "baz") + assert_browser_monitoring_has_agent_attribute('request.parameters.foo', 'bar') + assert_browser_monitoring_has_agent_attribute('request.parameters.bar', 'baz') end def test_request_uri_collected_on_default_destinations config = {} txn_options = { - :request => stub(:path => "/foobar") + :request => stub(:path => '/foobar') } run_transaction(config, txn_options) last_transaction_trace = single_transaction_trace_posted - assert_equal "/foobar", last_transaction_trace.uri - assert_transaction_trace_has_agent_attribute("request.uri", "/foobar") + assert_equal '/foobar', last_transaction_trace.uri + assert_transaction_trace_has_agent_attribute('request.uri', '/foobar') - assert_error_has_agent_attribute("request.uri", "/foobar") - refute_event_has_agent_attribute("request.uri") - refute_browser_monitoring_has_agent_attribute("request.uri") + assert_error_has_agent_attribute('request.uri', '/foobar') + refute_event_has_agent_attribute('request.uri') + refute_browser_monitoring_has_agent_attribute('request.uri') end def test_request_uri_can_be_disabled_on_tts config = {:'transaction_tracer.attributes.exclude' => 'request.uri'} txn_options = { - :request => stub(:path => "/foobar") + :request => stub(:path => '/foobar') } run_transaction(config, txn_options) @@ -241,40 +241,40 @@ def test_request_uri_can_be_disabled_on_tts refute last_transaction_trace.uri - assert_error_has_agent_attribute("request.uri", "/foobar") - refute_transaction_trace_has_agent_attribute("request.uri") - refute_event_has_agent_attribute("request.uri") - refute_browser_monitoring_has_agent_attribute("request.uri") + assert_error_has_agent_attribute('request.uri', '/foobar') + refute_transaction_trace_has_agent_attribute('request.uri') + refute_event_has_agent_attribute('request.uri') + refute_browser_monitoring_has_agent_attribute('request.uri') end def test_request_uri_can_be_disabled_on_error_traces config = {:'error_collector.attributes.exclude' => 'request.uri'} txn_options = { - :request => stub(:path => "/foobar") + :request => stub(:path => '/foobar') } run_transaction(config, txn_options) last_error_trace = single_error_posted - refute last_error_trace.params["agentAttributes"]["request.uri"] + refute last_error_trace.params['agentAttributes']['request.uri'] - assert_transaction_trace_has_agent_attribute("request.uri", "/foobar") - refute_error_has_agent_attribute("request.uri") - refute_event_has_agent_attribute("request.uri") - refute_browser_monitoring_has_agent_attribute("request.uri") + assert_transaction_trace_has_agent_attribute('request.uri', '/foobar') + refute_error_has_agent_attribute('request.uri') + refute_event_has_agent_attribute('request.uri') + refute_browser_monitoring_has_agent_attribute('request.uri') end def test_request_uri_can_be_disabled_by_global_attributes_config config = {:'attributes.exclude' => 'request.uri'} txn_options = { - :request => stub(:path => "/foobar") + :request => stub(:path => '/foobar') } run_transaction(config, txn_options) - refute_transaction_trace_has_agent_attribute("request.uri") - refute_error_has_agent_attribute("request.uri") - refute_event_has_agent_attribute("request.uri") - refute_browser_monitoring_has_agent_attribute("request.uri") + refute_transaction_trace_has_agent_attribute('request.uri') + refute_error_has_agent_attribute('request.uri') + refute_event_has_agent_attribute('request.uri') + refute_browser_monitoring_has_agent_attribute('request.uri') end def test_http_response_code_excluded_in_txn_events_when_disabled @@ -322,7 +322,7 @@ def run_transaction(config = {}, txn_options = {}) capture_js_data # Have to raise an error to exercise attribute capture there - raise "O_o" + raise 'O_o' end end end diff --git a/test/multiverse/suites/agent_only/agent_run_id_handling_test.rb b/test/multiverse/suites/agent_only/agent_run_id_handling_test.rb index b877271ddd..dc5a804966 100644 --- a/test/multiverse/suites/agent_only/agent_run_id_handling_test.rb +++ b/test/multiverse/suites/agent_only/agent_run_id_handling_test.rb @@ -10,7 +10,7 @@ class AgentRunIdHandlingTest < Minitest::Test NON_NUMERIC_RUN_ID = 'some-crazy-non-integer-thing' setup_and_teardown_agent do - $collector.stub('connect', {"agent_run_id" => NON_NUMERIC_RUN_ID}) + $collector.stub('connect', {'agent_run_id' => NON_NUMERIC_RUN_ID}) end # This test verifies that the Ruby agent is able to accept non-numeric values @@ -34,7 +34,7 @@ def test_handles_non_numeric_agent_run_id_on_slow_sql_traces def simulate_slow_sql_trace in_transaction do - agent.sql_sampler.notice_sql("select * from test", "Database/test/select", nil, 1.5) + agent.sql_sampler.notice_sql('select * from test', 'Database/test/select', nil, 1.5) end NewRelic::Agent.agent.send(:harvest_and_send_slowest_sql) end diff --git a/test/multiverse/suites/agent_only/audit_log_test.rb b/test/multiverse/suites/agent_only/audit_log_test.rb index ddcd1b218d..0ec7a3d4d7 100644 --- a/test/multiverse/suites/agent_only/audit_log_test.rb +++ b/test/multiverse/suites/agent_only/audit_log_test.rb @@ -55,8 +55,8 @@ def test_logs_request_bodies_human_readably_ish def perform_actions state = NewRelic::Agent::Tracer.state NewRelic::Agent.instance.sql_sampler.on_start_transaction(state) - NewRelic::Agent.instance.sql_sampler.notice_sql("select * from test", - "Database/test/select", + NewRelic::Agent.instance.sql_sampler.notice_sql('select * from test', + 'Database/test/select', nil, 1.5, state) NewRelic::Agent.instance.sql_sampler.on_finishing_transaction(state, 'txn') NewRelic::Agent.instance.send(:harvest_and_send_slowest_sql) diff --git a/test/multiverse/suites/agent_only/cross_application_tracing_test.rb b/test/multiverse/suites/agent_only/cross_application_tracing_test.rb index a294d599c8..7ac4a14064 100644 --- a/test/multiverse/suites/agent_only/cross_application_tracing_test.rb +++ b/test/multiverse/suites/agent_only/cross_application_tracing_test.rb @@ -11,14 +11,14 @@ class CrossApplicationTracingTest < Minitest::Test include MultiverseHelpers setup_and_teardown_agent(:'cross_application_tracer.enabled' => true, :'distributed_tracing.enabled' => false, - :cross_process_id => "boo", + :cross_process_id => 'boo', :encoding_key => "\0", :trusted_account_ids => [1]) \ do |collector| collector.stub('connect', { 'agent_run_id' => 666, - 'transaction_name_rules' => [{"match_expression" => "ignored_transaction", - "ignore" => true}] + 'transaction_name_rules' => [{'match_expression' => 'ignored_transaction', + 'ignore' => true}] }) end @@ -31,26 +31,26 @@ def app def test_cross_app_doesnt_modify_without_header get('/') - refute last_response.headers["X-NewRelic-App-Data"] + refute last_response.headers['X-NewRelic-App-Data'] end def test_cross_app_doesnt_modify_with_invalid_header get('/', nil, {'HTTP_X_NEWRELIC_ID' => Base64.encode64('otherjunk')}) - refute last_response.headers["X-NewRelic-App-Data"] + refute last_response.headers['X-NewRelic-App-Data'] end def test_cross_app_writes_out_information get('/', nil, {'HTTP_X_NEWRELIC_ID' => Base64.encode64('1#234')}) - refute_nil last_response.headers["X-NewRelic-App-Data"] + refute_nil last_response.headers['X-NewRelic-App-Data'] assert_metrics_recorded(['ClientApplication/1#234/all']) end def test_cross_app_doesnt_modify_if_txn_is_ignored get('/', {'transaction_name' => 'ignored_transaction'}, {'HTTP_X_NEWRELIC_ID' => Base64.encode64('1#234')}) - refute last_response.headers["X-NewRelic-App-Data"] + refute last_response.headers['X-NewRelic-App-Data'] end def test_cross_app_error_attaches_process_id_to_intrinsics @@ -61,9 +61,9 @@ def test_cross_app_error_attaches_process_id_to_intrinsics assert_includes attributes_for(last_traced_error, :intrinsic), :client_cross_process_id end - load_cross_agent_test("cat_map").each do |test_case| + load_cross_agent_test('cat_map').each do |test_case| # We only can do test cases here that don't involve outgoing calls - if !test_case["outboundRequests"] + if !test_case['outboundRequests'] if test_case['inboundPayload'] request_headers = { 'HTTP_X_NEWRELIC_ID' => Base64.encode64('1#234'), diff --git a/test/multiverse/suites/agent_only/custom_analytics_events_test.rb b/test/multiverse/suites/agent_only/custom_analytics_events_test.rb index 1cc7050196..8898a9c029 100644 --- a/test/multiverse/suites/agent_only/custom_analytics_events_test.rb +++ b/test/multiverse/suites/agent_only/custom_analytics_events_test.rb @@ -75,7 +75,7 @@ def test_post_includes_metadata NewRelic::Agent.agent.send(:harvest_and_send_custom_event_data) post = last_custom_event_post - assert_equal({"reservoir_size" => 3000, "events_seen" => 10}, post.reservoir_metadata) + assert_equal({'reservoir_size' => 3000, 'events_seen' => 10}, post.reservoir_metadata) end def last_custom_event_post diff --git a/test/multiverse/suites/agent_only/custom_queue_time_test.rb b/test/multiverse/suites/agent_only/custom_queue_time_test.rb index fd045d99f8..6c10401289 100644 --- a/test/multiverse/suites/agent_only/custom_queue_time_test.rb +++ b/test/multiverse/suites/agent_only/custom_queue_time_test.rb @@ -11,7 +11,7 @@ class CustomQueueTimeTest < Minitest::Test DummyRequest = Struct.new(:headers, :cookies) do def path - "/" + '/' end end diff --git a/test/multiverse/suites/agent_only/encoding_handling_test.rb b/test/multiverse/suites/agent_only/encoding_handling_test.rb index 49a12b2d96..efb4add481 100644 --- a/test/multiverse/suites/agent_only/encoding_handling_test.rb +++ b/test/multiverse/suites/agent_only/encoding_handling_test.rb @@ -130,7 +130,7 @@ def object_graph_contains_string?(object_graph, string) end def bad_string - [128].to_a.pack("C*").force_encoding('UTF-8') + [128].to_a.pack('C*').force_encoding('UTF-8') end def normalized_bad_string diff --git a/test/multiverse/suites/agent_only/error_events_test.rb b/test/multiverse/suites/agent_only/error_events_test.rb index 4c5124ba06..0309cbfd88 100644 --- a/test/multiverse/suites/agent_only/error_events_test.rb +++ b/test/multiverse/suites/agent_only/error_events_test.rb @@ -16,12 +16,12 @@ def test_error_events_are_submitted intrinsics, _, _ = last_error_event - assert_equal txn.best_name, intrinsics["transactionName"] - assert_equal "RuntimeError", intrinsics["error.class"] - assert_equal "Big Controller", intrinsics["error.message"] - refute intrinsics["error.expected"] - assert_equal "TransactionError", intrinsics["type"] - assert_equal txn.payload[:duration], intrinsics["duration"] + assert_equal txn.best_name, intrinsics['transactionName'] + assert_equal 'RuntimeError', intrinsics['error.class'] + assert_equal 'Big Controller', intrinsics['error.message'] + refute intrinsics['error.expected'] + assert_equal 'TransactionError', intrinsics['type'] + assert_equal txn.payload[:duration], intrinsics['duration'] end def test_error_events_honor_expected_option @@ -31,7 +31,7 @@ def test_error_events_honor_expected_option intrinsics, _, _ = last_error_event - assert intrinsics["error.expected"] + assert intrinsics['error.expected'] end def test_records_supportability_metrics @@ -41,8 +41,8 @@ def test_records_supportability_metrics NewRelic::Agent.agent.send(:harvest_and_send_error_event_data) assert_metrics_recorded({ - "Supportability/Events/TransactionError/Sent" => {:call_count => 10}, - "Supportability/Events/TransactionError/Seen" => {:call_count => 15} + 'Supportability/Events/TransactionError/Sent' => {:call_count => 10}, + 'Supportability/Events/TransactionError/Seen' => {:call_count => 15} }) end end @@ -94,21 +94,21 @@ def test_does_not_record_error_events_when_disabled_by_feature_gate end def test_error_events_created_outside_of_transaction - NewRelic::Agent.notice_error(RuntimeError.new("No Txn")) + NewRelic::Agent.notice_error(RuntimeError.new('No Txn')) NewRelic::Agent.agent.send(:harvest_and_send_error_event_data) intrinsics, _, _ = last_error_event - assert_equal "TransactionError", intrinsics["type"] - assert_in_delta Process.clock_gettime(Process::CLOCK_REALTIME), intrinsics["timestamp"], 0.001 - assert_equal "RuntimeError", intrinsics["error.class"] - assert_equal "No Txn", intrinsics["error.message"] - assert intrinsics["priority"], "Priority is nil" + assert_equal 'TransactionError', intrinsics['type'] + assert_in_delta Process.clock_gettime(Process::CLOCK_REALTIME), intrinsics['timestamp'], 0.001 + assert_equal 'RuntimeError', intrinsics['error.class'] + assert_equal 'No Txn', intrinsics['error.message'] + assert intrinsics['priority'], 'Priority is nil' end def test_error_events_during_txn_abide_by_custom_attributes_config with_config(:'custom_attributes.enabled' => false) do - generate_errors(1, {:foo => "bar"}) + generate_errors(1, {:foo => 'bar'}) end NewRelic::Agent.agent.send(:harvest_and_send_error_event_data) @@ -120,7 +120,7 @@ def test_error_events_during_txn_abide_by_custom_attributes_config def test_error_events_outside_txn_abide_by_custom_attributes_config with_config(:'custom_attributes.enabled' => false) do - NewRelic::Agent.notice_error(RuntimeError.new("Big Controller"), {:foo => "bar"}) + NewRelic::Agent.notice_error(RuntimeError.new('Big Controller'), {:foo => 'bar'}) end NewRelic::Agent.agent.send(:harvest_and_send_error_event_data) @@ -131,8 +131,8 @@ def test_error_events_outside_txn_abide_by_custom_attributes_config end def generate_errors(num_errors = 1, options = {}) - in_transaction(:transaction_name => "Controller/blogs/index") do |t| - num_errors.times { t.notice_error(RuntimeError.new("Big Controller"), options) } + in_transaction(:transaction_name => 'Controller/blogs/index') do |t| + num_errors.times { t.notice_error(RuntimeError.new('Big Controller'), options) } end end diff --git a/test/multiverse/suites/agent_only/event_data_collection_test.rb b/test/multiverse/suites/agent_only/event_data_collection_test.rb index cf0c1f1430..73f2080f12 100644 --- a/test/multiverse/suites/agent_only/event_data_collection_test.rb +++ b/test/multiverse/suites/agent_only/event_data_collection_test.rb @@ -10,11 +10,11 @@ class EventDataCollectionTest < Minitest::Test def test_sends_all_event_capacities_on_connect expected = { 'harvest_limits' => { - "analytic_event_data" => 1200, - "custom_event_data" => 3000, - "error_event_data" => 100, - "span_event_data" => 2000, - "log_event_data" => 10000 + 'analytic_event_data' => 1200, + 'custom_event_data' => 3000, + 'error_event_data' => 100, + 'span_event_data' => 2000, + 'log_event_data' => 10000 } } @@ -25,14 +25,14 @@ def test_sends_all_event_capacities_on_connect def test_sets_event_report_period_on_connect_response connect_response = { - "agent_run_id" => 1, - "event_harvest_config" => { - "report_period_ms" => 5000, - "harvest_limits" => { - "analytic_event_data" => 1200, - "custom_event_data" => 3000, - "error_event_data" => 100, - "log_event_data" => 10000 + 'agent_run_id' => 1, + 'event_harvest_config' => { + 'report_period_ms' => 5000, + 'harvest_limits' => { + 'analytic_event_data' => 1200, + 'custom_event_data' => 3000, + 'error_event_data' => 100, + 'log_event_data' => 10000 } } } @@ -46,14 +46,14 @@ def test_sets_event_report_period_on_connect_response def test_resets_event_report_period_on_reconnect connect_response = { - "agent_run_id" => 1, - "event_harvest_config" => { - "report_period_ms" => 5000, - "harvest_limits" => { - "analytic_event_data" => 1200, - "custom_event_data" => 3000, - "error_event_data" => 100, - "log_event_data" => 10000 + 'agent_run_id' => 1, + 'event_harvest_config' => { + 'report_period_ms' => 5000, + 'harvest_limits' => { + 'analytic_event_data' => 1200, + 'custom_event_data' => 3000, + 'error_event_data' => 100, + 'log_event_data' => 10000 } } } diff --git a/test/multiverse/suites/agent_only/harvest_timestamps_test.rb b/test/multiverse/suites/agent_only/harvest_timestamps_test.rb index 378ac27228..a46528954e 100644 --- a/test/multiverse/suites/agent_only/harvest_timestamps_test.rb +++ b/test/multiverse/suites/agent_only/harvest_timestamps_test.rb @@ -56,6 +56,6 @@ def last_metric_data_post end def simulate_fork - NewRelic::Agent.instance.harvester.instance_variable_set(:@starting_pid, nil) + NewRelic::Agent.instance.instance_variable_get(:@harvester).instance_variable_set(:@starting_pid, nil) end end diff --git a/test/multiverse/suites/agent_only/labels_test.rb b/test/multiverse/suites/agent_only/labels_test.rb index f3e5282c77..09900d744d 100644 --- a/test/multiverse/suites/agent_only/labels_test.rb +++ b/test/multiverse/suites/agent_only/labels_test.rb @@ -20,7 +20,7 @@ def test_yaml_makes_it_to_the_collector end def test_labels_from_config_hash_make_it_to_the_collector - with_config("labels" => {"Server" => "East"}) do + with_config('labels' => {'Server' => 'East'}) do trigger_agent_reconnect assert_connect_had_labels(EXPECTED) @@ -28,13 +28,13 @@ def test_labels_from_config_hash_make_it_to_the_collector end def test_labels_from_manual_start_hash_make_it_to_the_collector - trigger_agent_reconnect(:labels => {"Server" => "East"}) + trigger_agent_reconnect(:labels => {'Server' => 'East'}) assert_connect_had_labels(EXPECTED) end def test_numeric_values_for_labels - trigger_agent_reconnect(:labels => {"Server" => 42}) + trigger_agent_reconnect(:labels => {'Server' => 42}) expected = [ {'label_type' => 'Server', 'label_value' => '42'} ] @@ -43,7 +43,7 @@ def test_numeric_values_for_labels end def test_boolean_values_for_labels - trigger_agent_reconnect(:labels => {"Server" => true}) + trigger_agent_reconnect(:labels => {'Server' => true}) expected = [ {'label_type' => 'Server', 'label_value' => 'true'} ] @@ -53,30 +53,30 @@ def test_boolean_values_for_labels # All testing of string parsed label pairs should go through the cross agent # test file for labels. Our dictionary passing is custom to Ruby, though. - load_cross_agent_test("labels").each do |testcase| + load_cross_agent_test('labels').each do |testcase| define_method("test_#{testcase['name']}_from_config_string") do - with_config("labels" => testcase["labelString"]) do + with_config('labels' => testcase['labelString']) do trigger_agent_reconnect - assert_connect_had_labels(testcase["expected"]) + assert_connect_had_labels(testcase['expected']) end end define_method("test_#{testcase['name']}_from_manual_start") do - trigger_agent_reconnect(:labels => testcase["labelString"]) + trigger_agent_reconnect(:labels => testcase['labelString']) - assert_connect_had_labels(testcase["expected"]) + assert_connect_had_labels(testcase['expected']) end define_method("test_#{testcase['name']}_from_env") do begin # Value must be here before reset for EnvironmentSource to see it - ENV['NEW_RELIC_LABELS'] = testcase["labelString"] + ENV['NEW_RELIC_LABELS'] = testcase['labelString'] NewRelic::Agent.config.reset_to_defaults trigger_agent_reconnect - assert_connect_had_labels(testcase["expected"]) + assert_connect_had_labels(testcase['expected']) ensure ENV['NEW_RELIC_LABELS'] = nil end diff --git a/test/multiverse/suites/agent_only/log_events_test.rb b/test/multiverse/suites/agent_only/log_events_test.rb index 24b4c20dbf..6abd994384 100644 --- a/test/multiverse/suites/agent_only/log_events_test.rb +++ b/test/multiverse/suites/agent_only/log_events_test.rb @@ -13,7 +13,7 @@ def test_log_event_data_sent_in_transaction with_config(:'application_logging.forwarding.enabled' => true) do in_transaction do |txn| NewRelic::Agent.agent.log_event_aggregator.reset! - NewRelic::Agent.agent.log_event_aggregator.record("Deadly", "FATAL") + NewRelic::Agent.agent.log_event_aggregator.record('Deadly', 'FATAL') trace_id = NewRelic::Agent::Tracer.current_trace_id span_id = NewRelic::Agent::Tracer.current_span_id end @@ -23,35 +23,35 @@ def test_log_event_data_sent_in_transaction last_log = last_log_event - assert_equal "Deadly", last_log["message"] - assert_equal "FATAL", last_log["level"] - assert_equal trace_id, last_log["trace.id"] - assert_equal span_id, last_log["span.id"] + assert_equal 'Deadly', last_log['message'] + assert_equal 'FATAL', last_log['level'] + assert_equal trace_id, last_log['trace.id'] + assert_equal span_id, last_log['span.id'] common = last_logs_common - assert_nil common["attributes"]["entity.type"] - assert_equal NewRelic::Agent::Hostname.get, common["attributes"]["hostname"] + assert_nil common['attributes']['entity.type'] + assert_equal NewRelic::Agent::Hostname.get, common['attributes']['hostname'] end def test_log_event_data_sent_no_transaction NewRelic::Agent.agent.log_event_aggregator.reset! with_config(:'application_logging.forwarding.enabled' => true) do - NewRelic::Agent.agent.log_event_aggregator.record("Deadly", "FATAL") + NewRelic::Agent.agent.log_event_aggregator.record('Deadly', 'FATAL') NewRelic::Agent.agent.send(:harvest_and_send_log_event_data) end last_log = last_log_event - assert_equal "Deadly", last_log["message"] - assert_equal "FATAL", last_log["level"] - assert_nil last_log["trace.id"] - assert_nil last_log["span.id"] + assert_equal 'Deadly', last_log['message'] + assert_equal 'FATAL', last_log['level'] + assert_nil last_log['trace.id'] + assert_nil last_log['span.id'] common = last_logs_common - assert_nil common["attributes"]["entity.type"] - assert_equal NewRelic::Agent::Hostname.get, common["attributes"]["hostname"] + assert_nil common['attributes']['entity.type'] + assert_equal NewRelic::Agent::Hostname.get, common['attributes']['hostname'] end def last_log_event diff --git a/test/multiverse/suites/agent_only/logging_test.rb b/test/multiverse/suites/agent_only/logging_test.rb index 2346a99e5b..4e057d83f3 100644 --- a/test/multiverse/suites/agent_only/logging_test.rb +++ b/test/multiverse/suites/agent_only/logging_test.rb @@ -23,20 +23,20 @@ def teardown def test_logs_app_name running_agent_writes_to_log( - {:app_name => "My App"}, - "Application: My App" + {:app_name => 'My App'}, + 'Application: My App' ) end def test_logs_error_with_bad_app_name running_agent_writes_to_log( {:app_name => false}, - "No application name configured." + 'No application name configured.' ) end def test_logs_dispatcher - dispatcher = "Y U NO SERVER WEBPAGE" + dispatcher = 'Y U NO SERVER WEBPAGE' running_agent_writes_to_log( {:dispatcher => dispatcher}, @@ -47,14 +47,14 @@ def test_logs_dispatcher def test_logs_missing_dispatcher running_agent_writes_to_log( {:dispatcher => ''}, - "No known dispatcher detected" + 'No known dispatcher detected' ) end def test_logs_raw_sql_warning running_agent_writes_to_log( {:'transaction_tracer.record_sql' => 'obfuscated'}, - "Agent is configured to send raw SQL to the service" + 'Agent is configured to send raw SQL to the service' ) do NewRelic::Agent.config.add_config_for_testing(:'transaction_tracer.record_sql' => 'raw') end @@ -63,7 +63,7 @@ def test_logs_raw_sql_warning def test_logs_if_sending_errors_on_change running_agent_writes_to_log( {:'error_collector.enabled' => false}, - "Error traces will be sent" + 'Error traces will be sent' ) do NewRelic::Agent.config.add_config_for_testing(:'error_collector.enabled' => true) end @@ -72,7 +72,7 @@ def test_logs_if_sending_errors_on_change def test_logs_if_not_sending_errors_on_change running_agent_writes_to_log( {:'error_collector.enabled' => true}, - "Error traces will not be sent" + 'Error traces will not be sent' ) do NewRelic::Agent.config.add_config_for_testing(:'error_collector.enabled' => false) end @@ -81,7 +81,7 @@ def test_logs_if_not_sending_errors_on_change def test_logs_transaction_tracing_disabled running_agent_writes_to_log( {:'transaction_tracer.enabled' => false}, - "Transaction traces will not be sent" + 'Transaction traces will not be sent' ) end @@ -90,7 +90,7 @@ def test_invalid_license_key collector.stub('connect', {}, 410) end - saw?("Agent received a ForceDisconnectException from the server") + saw?('Agent received a ForceDisconnectException from the server') teardown_agent end @@ -98,28 +98,28 @@ def test_invalid_license_key def test_logs_monitor_mode_disabled running_agent_writes_to_log( {:monitor_mode => false}, - "Agent configured not to send data in this environment." + 'Agent configured not to send data in this environment.' ) end def test_logs_missing_license_key running_agent_writes_to_log( {:license_key => false}, - "No license key found." + 'No license key found.' ) end def test_logs_blank_license_key running_agent_writes_to_log( {:license_key => ''}, - "No license key found." + 'No license key found.' ) end def test_logs_invalid_license_key running_agent_writes_to_log( {:license_key => 'a' * 30}, - "Invalid license key: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + 'Invalid license key: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' ) end @@ -137,7 +137,7 @@ def test_logs_unknown_config_setting_from_environment def test_logs_forking_workers running_agent_writes_to_log( {:dispatcher => :passenger}, - "Deferring startup of agent reporting thread" + 'Deferring startup of agent reporting thread' ) end diff --git a/test/multiverse/suites/agent_only/marshaling_test.rb b/test/multiverse/suites/agent_only/marshaling_test.rb index b0fb5c6c73..58de946446 100644 --- a/test/multiverse/suites/agent_only/marshaling_test.rb +++ b/test/multiverse/suites/agent_only/marshaling_test.rb @@ -70,7 +70,7 @@ def test_error_data_marshalling def test_sql_trace_data_marshalling in_transaction do - agent.sql_sampler.notice_sql("select * from test", "Database/test/select", + agent.sql_sampler.notice_sql('select * from test', 'Database/test/select', nil, 1.5) end diff --git a/test/multiverse/suites/agent_only/rename_rule_test.rb b/test/multiverse/suites/agent_only/rename_rule_test.rb index 0f3d4275da..519c05bab3 100644 --- a/test/multiverse/suites/agent_only/rename_rule_test.rb +++ b/test/multiverse/suites/agent_only/rename_rule_test.rb @@ -59,7 +59,7 @@ def test_metric_name_rules def test_transaction_segment_terms_do_not_apply_to_metrics in_transaction do - NewRelic::Agent.record_metric("other/qux/foo/bar", 42) + NewRelic::Agent.record_metric('other/qux/foo/bar', 42) end assert_metrics_recorded(['other/qux/foo/bar']) diff --git a/test/multiverse/suites/agent_only/rum_instrumentation_test.rb b/test/multiverse/suites/agent_only/rum_instrumentation_test.rb index ea2f32ac03..a84497b165 100644 --- a/test/multiverse/suites/agent_only/rum_instrumentation_test.rb +++ b/test/multiverse/suites/agent_only/rum_instrumentation_test.rb @@ -12,7 +12,7 @@ class RumAutoTest < Minitest::Test include Rack::Test::Methods include MultiverseHelpers - JS_AGENT_LOADER = "JS_AGENT_LOADER" + JS_AGENT_LOADER = 'JS_AGENT_LOADER' LOADER_REGEX = "\nJS_AGENT_LOADER" CONFIG_REGEX = "\n.*NREUM.info=.*" @@ -22,8 +22,8 @@ class RumAutoTest < Minitest::Test :browser_key => 'browserKey', :js_agent_loader => JS_AGENT_LOADER) do |collector| collector.stub('connect', { - 'transaction_name_rules' => [{"match_expression" => "ignored_transaction", - "ignore" => true}], + 'transaction_name_rules' => [{'match_expression' => 'ignored_transaction', + 'ignore' => true}], 'agent_run_id' => 1 }) end @@ -34,21 +34,21 @@ def after_setup end def test_autoinstrumentation_is_active - @inner_app.response = "W00t!

Hello World

" + @inner_app.response = 'W00t!

Hello World

' get('/') - assert_response_includes("#{CONFIG_REGEX}#{LOADER_REGEX}foo)) end def test_autoinstrumentation_with_body_only_puts_header_before_body - @inner_app.response = "

Hello World

" + @inner_app.response = '

Hello World

' get('/') assert_response_includes %Q(#{CONFIG_REGEX}#{LOADER_REGEX}) @@ -69,9 +69,9 @@ def test_autoinstrumentation_doesnt_run_for_crazy_shit_like_this end def test_content_length_is_correctly_set_if_present - @inner_app.response = "W00t!

Hello World

" + @inner_app.response = 'W00t!

Hello World

' content_length = @inner_app.response.length - @inner_app.headers["Content-Length"] = content_length + @inner_app.headers['Content-Length'] = content_length get('/') assert(last_response.headers['Content-Length'].to_i > content_length) @@ -79,16 +79,16 @@ def test_content_length_is_correctly_set_if_present end def test_xml_responses_arent_instrumented - body = "W00t!

Hello World

" + body = 'W00t!

Hello World

' @inner_app.response = body - @inner_app.headers["Content-Type"] = "text/xml" + @inner_app.headers['Content-Type'] = 'text/xml' get('/') assert_equal(last_response.body, body) end def test_rum_headers_are_not_injected_in_ignored_txn - body = "W00t!

Hello World

" + body = 'W00t!

Hello World

' @inner_app.response = body get('/', 'transaction_name' => 'ignored_transaction') diff --git a/test/multiverse/suites/agent_only/script/env_change.rb b/test/multiverse/suites/agent_only/script/env_change.rb index d85a836e95..10fb35f8b5 100644 --- a/test/multiverse/suites/agent_only/script/env_change.rb +++ b/test/multiverse/suites/agent_only/script/env_change.rb @@ -3,8 +3,8 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -ENV["NEW_RELIC_LOG_FILE_PATH"] = "STDOUT" +ENV['NEW_RELIC_LOG_FILE_PATH'] = 'STDOUT' require 'newrelic_rpm' -NewRelic::Agent.manual_start(:env => "production") +NewRelic::Agent.manual_start(:env => 'production') diff --git a/test/multiverse/suites/agent_only/script/loading.rb b/test/multiverse/suites/agent_only/script/loading.rb index 2c83c1d87b..aa74ed887e 100755 --- a/test/multiverse/suites/agent_only/script/loading.rb +++ b/test/multiverse/suites/agent_only/script/loading.rb @@ -3,13 +3,13 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -ENV["NEW_RELIC_LOG_FILE_PATH"] = "STDOUT" +ENV['NEW_RELIC_LOG_FILE_PATH'] = 'STDOUT' require 'newrelic_rpm' # Force all named items to re-enable enable_everyone = {} -DependencyDetection.items.each do |item| +DependencyDetection.instance_variable_get(:@items).each do |item| if item.name enable_everyone["disable_#{item.name}".to_sym] = false end diff --git a/test/multiverse/suites/agent_only/script/public_api_when_disabled.rb b/test/multiverse/suites/agent_only/script/public_api_when_disabled.rb index 112ec81640..f6f7c928c5 100644 --- a/test/multiverse/suites/agent_only/script/public_api_when_disabled.rb +++ b/test/multiverse/suites/agent_only/script/public_api_when_disabled.rb @@ -3,7 +3,7 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -ENV["NEW_RELIC_LOG_FILE_PATH"] = "STDOUT" +ENV['NEW_RELIC_LOG_FILE_PATH'] = 'STDOUT' # This file tries to require the minimum amount of the agent, and then call # public API methods on it to ensure that they don't raise exceptions. It is @@ -12,18 +12,18 @@ require 'new_relic/agent' -NewRelic::Agent.record_metric("Custom/Record", 1) -NewRelic::Agent.increment_metric("Custom/Increment", 1) +NewRelic::Agent.record_metric('Custom/Record', 1) +NewRelic::Agent.increment_metric('Custom/Increment', 1) NewRelic::Agent.require_test_helper -NewRelic::Agent.add_instrumentation("*_foobar.rb") +NewRelic::Agent.add_instrumentation('*_foobar.rb') NewRelic::Agent.ignore_error_filter do end -NewRelic::Agent.notice_error(StandardError.new("Always an option")) +NewRelic::Agent.notice_error(StandardError.new('Always an option')) -NewRelic::Agent.record_custom_event(:DontStart, :dont => "even") +NewRelic::Agent.record_custom_event(:DontStart, :dont => 'even') NewRelic::Agent.ignore_transaction NewRelic::Agent.ignore_apdex @@ -35,10 +35,10 @@ NewRelic::Agent.disable_sql_recording do end -NewRelic::Agent.set_transaction_name("Something/Different") +NewRelic::Agent.set_transaction_name('Something/Different') NewRelic::Agent.get_transaction_name -NewRelic::Agent.with_database_metric_name("Model", "Method") do +NewRelic::Agent.with_database_metric_name('Model', 'Method') do end NewRelic::Agent.set_sql_obfuscator do @@ -46,7 +46,7 @@ NewRelic::Agent.browser_timing_header -NewRelic::Agent.add_custom_attributes(:custom => "attributes") +NewRelic::Agent.add_custom_attributes(:custom => 'attributes') NewRelic::Agent.drop_buffered_data diff --git a/test/multiverse/suites/agent_only/script/symbol_env.rb b/test/multiverse/suites/agent_only/script/symbol_env.rb index ed8889125c..2dc08762d3 100755 --- a/test/multiverse/suites/agent_only/script/symbol_env.rb +++ b/test/multiverse/suites/agent_only/script/symbol_env.rb @@ -3,7 +3,7 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -ENV["NEW_RELIC_LOG_FILE_PATH"] = "STDOUT" +ENV['NEW_RELIC_LOG_FILE_PATH'] = 'STDOUT' require 'newrelic_rpm' diff --git a/test/multiverse/suites/agent_only/start_up_test.rb b/test/multiverse/suites/agent_only/start_up_test.rb index 35b5d24973..670a27ef43 100644 --- a/test/multiverse/suites/agent_only/start_up_test.rb +++ b/test/multiverse/suites/agent_only/start_up_test.rb @@ -41,21 +41,21 @@ def test_should_not_print_to_stdout_when_logging_available expected_noise << JRUBY_9000_NOISE if jruby_9000 - expected_noise.flatten.each { |noise| output.gsub!(noise, "") } + expected_noise.flatten.each { |noise| output.gsub!(noise, '') } assert_equal '', output.chomp end def test_instrumentation_loads_clean_even_without_dependencies - assert_runs_without_errors("bundle exec ruby script/loading.rb") + assert_runs_without_errors('bundle exec ruby script/loading.rb') end def test_manual_start_with_symbol_for_environment - assert_runs_without_errors("bundle exec ruby script/symbol_env.rb") + assert_runs_without_errors('bundle exec ruby script/symbol_env.rb') end def test_can_call_public_api_methods_when_agent_disabled - assert_runs_without_errors("bundle exec ruby script/public_api_when_disabled.rb") + assert_runs_without_errors('bundle exec ruby script/public_api_when_disabled.rb') end def test_manual_start_logs_about_mismatched_environment @@ -94,13 +94,13 @@ def test_after_fork_clears_existing_transactions NewRelic::Agent.manual_start(:app_name => 'my great app') - in_transaction("outer txn") do + in_transaction('outer txn') do pid = Process.fork do read.close NewRelic::Agent.after_fork txn = NewRelic::Agent::Tracer.current_transaction - txn_name = txn ? txn.best_name : nil + txn_name = txn&.best_name Marshal.dump(txn_name, write) end write.close @@ -124,7 +124,7 @@ def test_no_warnings expected_noise << JRUBY_9000_NOISE if jruby_9000 expected_noise << BUNDLER_NOISE if bundler_rubygem_conflicts? - expected_noise.flatten.each { |noise| output.gsub!(noise, "") } + expected_noise.flatten.each { |noise| output.gsub!(noise, '') } output.strip! assert_equal NewRelic::VERSION::STRING, output @@ -142,11 +142,11 @@ def assert_runs_without_errors(command) end def jruby_9000 - defined?(JRUBY_VERSION) && Gem::Version.new(JRUBY_VERSION) >= Gem::Version.new("9.0.0") + defined?(JRUBY_VERSION) && Gem::Version.new(JRUBY_VERSION) >= Gem::Version.new('9.0.0') end def bundler_rubygem_conflicts? - Gem::Version.new(Gem::VERSION) == Gem::Version.new("2.6.6") and - Gem::Version.new(Bundler::VERSION) == Gem::Version.new("1.12.5") + Gem::Version.new(Gem::VERSION) == Gem::Version.new('2.6.6') and + Gem::Version.new(Bundler::VERSION) == Gem::Version.new('1.12.5') end end diff --git a/test/multiverse/suites/agent_only/testing_app.rb b/test/multiverse/suites/agent_only/testing_app.rb index bd45b38502..19bbfaeb82 100644 --- a/test/multiverse/suites/agent_only/testing_app.rb +++ b/test/multiverse/suites/agent_only/testing_app.rb @@ -15,7 +15,7 @@ def call(env) request = Rack::Request.new(env) params = request.params if params['fail'] - raise "O_o" + raise 'O_o' end if params['transaction_name'] @@ -36,8 +36,8 @@ def call(env) end class TestingBackgroundJob - FIRST_NAME = "OtherTransaction/Custom/TestingBackgroundJob/first" - SECOND_NAME = "OtherTransaction/Custom/TestingBackgroundJob/second" + FIRST_NAME = 'OtherTransaction/Custom/TestingBackgroundJob/first' + SECOND_NAME = 'OtherTransaction/Custom/TestingBackgroundJob/second' def first(awhile = nil) job(FIRST_NAME, awhile) diff --git a/test/multiverse/suites/agent_only/thread_profiling_test.rb b/test/multiverse/suites/agent_only/thread_profiling_test.rb index bdb2a94fd8..6a9211620d 100644 --- a/test/multiverse/suites/agent_only/thread_profiling_test.rb +++ b/test/multiverse/suites/agent_only/thread_profiling_test.rb @@ -11,7 +11,7 @@ class ThreadProfilingTest < Minitest::Test include MultiverseHelpers setup_and_teardown_agent(:'thread_profiler.enabled' => true) do |collector| - collector.stub('connect', {"agent_run_id" => 666}) + collector.stub('connect', {'agent_run_id' => 666}) collector.stub('get_agent_commands', []) collector.stub('agent_command_results', []) end @@ -20,7 +20,7 @@ def after_setup agent.service.request_timeout = 0.5 agent.service.agent_id = 666 - @thread_profiler_session = agent.agent_command_router.thread_profiler_session + @thread_profiler_session = agent.instance_variable_get(:@agent_command_router).thread_profiler_session @threads = [] end @@ -30,22 +30,22 @@ def after_teardown end START_COMMAND = [[666, { - "name" => "start_profiler", - "arguments" => { - "profile_id" => -1, - "sample_period" => 0.01, - "duration" => 0.75, - "only_runnable_threads" => false, - "only_request_threads" => false, - "profile_agent_code" => true + 'name' => 'start_profiler', + 'arguments' => { + 'profile_id' => -1, + 'sample_period' => 0.01, + 'duration' => 0.75, + 'only_runnable_threads' => false, + 'only_request_threads' => false, + 'profile_agent_code' => true } }]] STOP_COMMAND = [[666, { - "name" => "stop_profiler", - "arguments" => { - "profile_id" => -1, - "report_data" => true + 'name' => 'stop_profiler', + 'arguments' => { + 'profile_id' => -1, + 'report_data' => true } }]] @@ -69,10 +69,10 @@ def test_thread_profiling assert_equal('666', profile_data.run_id, "Missing run_id, profile_data was #{profile_data.inspect}") assert(profile_data.poll_count >= 2, "Expected sample_count >= 2, but was #{profile_data.poll_count}") - assert_saw_traces(profile_data, "OTHER") - assert_saw_traces(profile_data, "AGENT") - assert_saw_traces(profile_data, "REQUEST") - assert_saw_traces(profile_data, "BACKGROUND") + assert_saw_traces(profile_data, 'OTHER') + assert_saw_traces(profile_data, 'AGENT') + assert_saw_traces(profile_data, 'REQUEST') + assert_saw_traces(profile_data, 'BACKGROUND') end def test_thread_profiling_can_stop @@ -115,11 +115,9 @@ def let_it_finish end def join_background_threads - if @threads - @threads.each do |thread| - thread.run - thread.join - end + @threads&.each do |thread| + thread.run + thread.join end end diff --git a/test/multiverse/suites/agent_only/transaction_events_test.rb b/test/multiverse/suites/agent_only/transaction_events_test.rb index 615bcce493..68efb30755 100644 --- a/test/multiverse/suites/agent_only/transaction_events_test.rb +++ b/test/multiverse/suites/agent_only/transaction_events_test.rb @@ -8,31 +8,31 @@ class TransactionEventsTest < Minitest::Test setup_and_teardown_agent def test_transaction_event_has_priority - in_transaction(:transaction_name => "Controller/blogs/index") {} + in_transaction(:transaction_name => 'Controller/blogs/index') {} NewRelic::Agent.agent.send(:harvest_and_send_analytic_event_data) intrinsics, _, _ = last_transaction_event - assert intrinsics["priority"].is_a?(Numeric), "Expected event to have priority" + assert intrinsics['priority'].is_a?(Numeric), 'Expected event to have priority' end def test_transaction_event_error_flag_is_set - in_transaction(:transaction_name => "Controller/blogs/index") do |t| - t.notice_error(RuntimeError.new("Big Controller")) + in_transaction(:transaction_name => 'Controller/blogs/index') do |t| + t.notice_error(RuntimeError.new('Big Controller')) end NewRelic::Agent.agent.send(:harvest_and_send_analytic_event_data) intrinsics, _, _ = last_transaction_event - assert intrinsics["error"], "Expected the error flag to be true" + assert intrinsics['error'], 'Expected the error flag to be true' end def test_transaction_events_abide_by_custom_attributes_config with_config(:'custom_attributes.enabled' => false) do - in_transaction(:transaction_name => "Controller/blogs/index") do |t| - t.add_custom_attributes(:foo => "bar") + in_transaction(:transaction_name => 'Controller/blogs/index') do |t| + t.add_custom_attributes(:foo => 'bar') end end diff --git a/test/multiverse/suites/agent_only/transaction_ignoring_test.rb b/test/multiverse/suites/agent_only/transaction_ignoring_test.rb index 7eb7eaf599..b667e995c3 100644 --- a/test/multiverse/suites/agent_only/transaction_ignoring_test.rb +++ b/test/multiverse/suites/agent_only/transaction_ignoring_test.rb @@ -21,8 +21,8 @@ def trigger_transaction_with_error(txn_name, error_msg) def trigger_transaction_with_slow_sql(txn_name) TestWidget.new.run_transaction(txn_name) do state = NewRelic::Agent::Tracer.state - NewRelic::Agent.instance.sql_sampler.notice_sql("select * from test", - "Database/test/select", + NewRelic::Agent.instance.sql_sampler.notice_sql('select * from test', + 'Database/test/select', nil, 1.5, state) end end diff --git a/test/multiverse/suites/agent_only/utilization_data_collection_test.rb b/test/multiverse/suites/agent_only/utilization_data_collection_test.rb index a1097f0e5f..e941f6dfb8 100644 --- a/test/multiverse/suites/agent_only/utilization_data_collection_test.rb +++ b/test/multiverse/suites/agent_only/utilization_data_collection_test.rb @@ -10,33 +10,33 @@ class UtilizationDataCollectionTest < Minitest::Test def test_sends_all_utilization_data_on_connect expected = { - "hostname" => "host", - "ip_address" => ["127.0.0.1"], - "metadata_version" => 5, - "logical_processors" => 5, - "total_ram_mib" => 128, - "vendors" => { - "aws" => { - "instanceId" => "i-08987cdeff7489fa7", - "instanceType" => "c4.2xlarge", - "availabilityZone" => "us-west-2c" + 'hostname' => 'host', + 'ip_address' => ['127.0.0.1'], + 'metadata_version' => 5, + 'logical_processors' => 5, + 'total_ram_mib' => 128, + 'vendors' => { + 'aws' => { + 'instanceId' => 'i-08987cdeff7489fa7', + 'instanceType' => 'c4.2xlarge', + 'availabilityZone' => 'us-west-2c' }, - "docker" => { - "id" => "47cbd16b77c50cbf71401" + 'docker' => { + 'id' => '47cbd16b77c50cbf71401' } } } - NewRelic::Agent::Hostname.stubs(:get).returns("host") + NewRelic::Agent::Hostname.stubs(:get).returns('host') NewRelic::Agent::Hostname.stubs(:get_fqdn).returns(nil) - NewRelic::Agent::SystemInfo.stubs(:docker_container_id).returns("47cbd16b77c50cbf71401") + NewRelic::Agent::SystemInfo.stubs(:docker_container_id).returns('47cbd16b77c50cbf71401') NewRelic::Agent::SystemInfo.stubs(:num_logical_processors).returns(5) NewRelic::Agent::SystemInfo.stubs(:ram_in_mib).returns(128) NewRelic::Agent::SystemInfo.stubs(:boot_id).returns(nil) - NewRelic::Agent::SystemInfo.stubs(:ip_addresses).returns(["127.0.0.1"]) + NewRelic::Agent::SystemInfo.stubs(:ip_addresses).returns(['127.0.0.1']) aws_fixture_path = File.expand_path('../../../../fixtures/utilization/aws', __FILE__) - fixture = File.read(File.join(aws_fixture_path, "valid.json")) + fixture = File.read(File.join(aws_fixture_path, 'valid.json')) with_fake_metadata_service do |service| NewRelic::Agent::Utilization::AWS.stubs(:imds_token).returns('J.R.R.') @@ -51,20 +51,20 @@ def test_sends_all_utilization_data_on_connect def test_omits_sending_vendor_data_on_connect_when_not_available expected = { - "hostname" => "host", - "ip_address" => ["127.0.0.1"], - "metadata_version" => 5, - "logical_processors" => 5, - "total_ram_mib" => 128 + 'hostname' => 'host', + 'ip_address' => ['127.0.0.1'], + 'metadata_version' => 5, + 'logical_processors' => 5, + 'total_ram_mib' => 128 } - NewRelic::Agent::Hostname.stubs(:get).returns("host") + NewRelic::Agent::Hostname.stubs(:get).returns('host') NewRelic::Agent::Hostname.stubs(:get_fqdn).returns(nil) NewRelic::Agent::SystemInfo.stubs(:num_logical_processors).returns(5) NewRelic::Agent::SystemInfo.stubs(:ram_in_mib).returns(128) NewRelic::Agent::SystemInfo.stubs(:docker_container_id).returns(nil) NewRelic::Agent::SystemInfo.stubs(:boot_id).returns(nil) - NewRelic::Agent::SystemInfo.stubs(:ip_addresses).returns(["127.0.0.1"]) + NewRelic::Agent::SystemInfo.stubs(:ip_addresses).returns(['127.0.0.1']) NewRelic::Agent::Utilization::AWS.any_instance.stubs(:detect).returns(false) NewRelic::Agent::Utilization::GCP.any_instance.stubs(:detect).returns(false) @@ -87,7 +87,7 @@ def with_fake_metadata_service yield(metadata_service) ensure - metadata_service.stop if metadata_service + metadata_service&.stop unredirect_link_local_address end diff --git a/test/multiverse/suites/bunny/bunny_test.rb b/test/multiverse/suites/bunny/bunny_test.rb index c266763d0f..86f5bb77d4 100644 --- a/test/multiverse/suites/bunny/bunny_test.rb +++ b/test/multiverse/suites/bunny/bunny_test.rb @@ -20,52 +20,52 @@ def teardown def test_metrics_recorded_for_produce_to_the_default_exchange with_queue do |queue| - in_transaction("test_txn") do - queue.publish("test_msg") + in_transaction('test_txn') do + queue.publish('test_msg') end assert_metrics_recorded [ - ["MessageBroker/RabbitMQ/Exchange/Produce/Named/Default", "test_txn"], - "MessageBroker/RabbitMQ/Exchange/Produce/Named/Default" + ['MessageBroker/RabbitMQ/Exchange/Produce/Named/Default', 'test_txn'], + 'MessageBroker/RabbitMQ/Exchange/Produce/Named/Default' ] end end def test_metrics_recorded_for_consume_from_the_default_exchange with_queue do |queue| - queue.publish("test_msg") + queue.publish('test_msg') - in_transaction("test_txn") do + in_transaction('test_txn') do queue.pop end assert_metrics_recorded [ - ["MessageBroker/RabbitMQ/Exchange/Consume/Named/Default", "test_txn"], - "MessageBroker/RabbitMQ/Exchange/Consume/Named/Default" + ['MessageBroker/RabbitMQ/Exchange/Consume/Named/Default', 'test_txn'], + 'MessageBroker/RabbitMQ/Exchange/Consume/Named/Default' ] end end def test_cat_headers_not_read_for_pop_by_default - cross_process_id = "321#123" + cross_process_id = '321#123' with_queue do |queue| - with_config(:"cross_application_tracer.enabled" => true, :cross_process_id => cross_process_id, :encoding_key => "abc") do - in_transaction("first_txn") do - queue.publish("test_msg") + with_config(:"cross_application_tracer.enabled" => true, :cross_process_id => cross_process_id, :encoding_key => 'abc') do + in_transaction('first_txn') do + queue.publish('test_msg') end - in_transaction("test_txn") do + in_transaction('test_txn') do queue.pop end event = last_transaction_event - refute event[0].has_key?("nr.guid"), "Event should not have key 'nr.guid'" - refute event[0].has_key?("nr.referringTransactionGuid"), "Event should not have key 'nr.referringTransactionGuid'" - refute event[0].has_key?("nr.tripId"), "Event should not have key 'nr.tripId'" - refute event[0].has_key?("nr.pathHash"), "Event should not have key 'nr.pathHash'" - refute event[0].has_key?("nr.referringPathHash"), "Event should not have key 'nr.referringPathHash'" + refute event[0].has_key?('nr.guid'), "Event should not have key 'nr.guid'" + refute event[0].has_key?('nr.referringTransactionGuid'), "Event should not have key 'nr.referringTransactionGuid'" + refute event[0].has_key?('nr.tripId'), "Event should not have key 'nr.tripId'" + refute event[0].has_key?('nr.pathHash'), "Event should not have key 'nr.pathHash'" + refute event[0].has_key?('nr.referringPathHash'), "Event should not have key 'nr.referringPathHash'" assert_metrics_not_recorded ["ClientApplication/#{cross_process_id}/all"] end @@ -73,72 +73,72 @@ def test_cat_headers_not_read_for_pop_by_default end def test_metrics_recorded_for_produce_to_a_named_exchange - x = Bunny::Exchange.new(@chan, :fanout, "activity.events") - in_transaction("test_txn") do - x.publish("hi") + x = Bunny::Exchange.new(@chan, :fanout, 'activity.events') + in_transaction('test_txn') do + x.publish('hi') end assert_metrics_recorded [ - ["MessageBroker/RabbitMQ/Exchange/Produce/Named/activity.events", "test_txn"], - "MessageBroker/RabbitMQ/Exchange/Produce/Named/activity.events" + ['MessageBroker/RabbitMQ/Exchange/Produce/Named/activity.events', 'test_txn'], + 'MessageBroker/RabbitMQ/Exchange/Produce/Named/activity.events' ] end def test_metrics_recorded_for_consume_from_a_named_exchange - x = @chan.fanout("activity.events") + x = @chan.fanout('activity.events') with_queue do |queue| queue.bind(x) - x.publish("howdy", { - routing_key: "red" + x.publish('howdy', { + routing_key: 'red' }) - in_transaction("test_txn") do + in_transaction('test_txn') do queue.pop end assert_metrics_recorded [ - ["MessageBroker/RabbitMQ/Exchange/Consume/Named/activity.events", "test_txn"], - "MessageBroker/RabbitMQ/Exchange/Consume/Named/activity.events" + ['MessageBroker/RabbitMQ/Exchange/Consume/Named/activity.events', 'test_txn'], + 'MessageBroker/RabbitMQ/Exchange/Consume/Named/activity.events' ] end end def test_segment_parameters_recorded_for_produce with_config(:'distributed_tracing.enabled' => false) do - x = @chan.fanout("activity.events") - headers = {foo: "bar"} - in_transaction("test_txn") do - x.publish("howdy", { - routing_key: "red", + x = @chan.fanout('activity.events') + headers = {foo: 'bar'} + in_transaction('test_txn') do + x.publish('howdy', { + routing_key: 'red', headers: headers, - reply_to: "blue", - correlation_id: "abc" + reply_to: 'blue', + correlation_id: 'abc' }) end node = find_node_with_name_matching(last_transaction_trace, /^MessageBroker\//) assert_equal :fanout, node.params[:exchange_type] - assert_equal "red", node.params[:routing_key] + assert_equal 'red', node.params[:routing_key] assert_equal headers, node.params[:headers] - assert_equal "blue", node.params[:reply_to] - assert_equal "abc", node.params[:correlation_id] + assert_equal 'blue', node.params[:reply_to] + assert_equal 'abc', node.params[:correlation_id] end end def test_segment_parameters_recorded_for_consume - headers = {foo: "bar"} + headers = {foo: 'bar'} with_queue do |queue| - queue.publish("howdy", { + queue.publish('howdy', { headers: headers, - reply_to: "blue", - correlation_id: "abc" + reply_to: 'blue', + correlation_id: 'abc' }) - in_transaction("test_txn") do + in_transaction('test_txn') do queue.pop end @@ -146,39 +146,39 @@ def test_segment_parameters_recorded_for_consume assert_equal :direct, node.params[:exchange_type] assert_equal queue.name, node.params[:routing_key] - assert_equal({"foo" => "bar"}, node.params[:headers]) - assert_equal "blue", node.params[:reply_to] - assert_equal "abc", node.params[:correlation_id] + assert_equal({'foo' => 'bar'}, node.params[:headers]) + assert_equal 'blue', node.params[:reply_to] + assert_equal 'abc', node.params[:correlation_id] end end def test_pop_returns_original_message with_queue do |queue| - queue.publish("howdy") + queue.publish('howdy') msg = queue.pop - assert Array === msg, "message was not an array" + assert Array === msg, 'message was not an array' assert Bunny::GetResponse === msg[0] assert Bunny::MessageProperties === msg[1] - assert_equal "howdy", msg[2] + assert_equal 'howdy', msg[2] end end def test_error_starting_amqp_segment_does_not_interfere_with_transaction - NewRelic::Agent::Messaging.stubs(:start_amqp_publish_segment).raises(StandardError.new("Boo")) + NewRelic::Agent::Messaging.stubs(:start_amqp_publish_segment).raises(StandardError.new('Boo')) with_queue do |queue| - in_transaction("test_txn") do + in_transaction('test_txn') do # our instrumentation should error here, but not interfere with bunny - queue.publish("test_msg") + queue.publish('test_msg') # this segment should be fine - segment = NewRelic::Agent::Tracer.start_segment(name: "Custom/blah/method") + segment = NewRelic::Agent::Tracer.start_segment(name: 'Custom/blah/method') ::NewRelic::Agent::Transaction::Segment.finish(segment) end - assert_metrics_recorded ["Custom/blah/method"] + assert_metrics_recorded ['Custom/blah/method'] refute_metrics_recorded [ - "MessageBroker/RabbitMQ/Exchange/Produce/Named/Default" + 'MessageBroker/RabbitMQ/Exchange/Produce/Named/Default' ] end end @@ -202,7 +202,7 @@ def test_transaction_implicitly_created_for_consume end lock.synchronize do - exchange.publish("hi", routing_key: 'some.key') + exchange.publish('hi', routing_key: 'some.key') cond.wait(lock) end @@ -218,40 +218,40 @@ def test_transaction_implicitly_created_for_consume cycles += 1 end - assert_equal "hi", msg + assert_equal 'hi', msg - refute_nil tt, "Did not expect tt to be nil. Something terrible has occurred." + refute_nil tt, 'Did not expect tt to be nil. Something terrible has occurred.' expected_destinations = NewRelic::Agent::AttributeFilter::DST_TRANSACTION_TRACER | NewRelic::Agent::AttributeFilter::DST_TRANSACTION_EVENTS | NewRelic::Agent::AttributeFilter::DST_ERROR_COLLECTOR - assert_equal({:"message.routingKey" => "some.key", + assert_equal({:"message.routingKey" => 'some.key', :"message.queueName" => queue.name, :"message.exchangeType" => :direct}, tt.attributes.agent_attributes_for(expected_destinations)) # metrics - assert_metrics_recorded ["OtherTransaction/Message/RabbitMQ/Exchange/Named/myDirectExchange"] + assert_metrics_recorded ['OtherTransaction/Message/RabbitMQ/Exchange/Named/myDirectExchange'] end end end def test_metrics_recorded_for_purge_with_server_named_queue with_queue do |queue| - in_transaction("test_txn") do - queue.publish("test") + in_transaction('test_txn') do + queue.publish('test') queue.purge end - assert_metrics_recorded "MessageBroker/RabbitMQ/Queue/Purge/Temp" + assert_metrics_recorded 'MessageBroker/RabbitMQ/Queue/Purge/Temp' end end def test_metrics_recorded_for_purge_with_named_queue with_queue(false) do |queue| - in_transaction("test_txn") do - queue.publish("test") + in_transaction('test_txn') do + queue.publish('test') queue.purge end @@ -263,10 +263,10 @@ def test_noticed_error_at_segment_and_txn_on_error txn = nil begin with_queue(false) do |queue| - Bunny::Channel.any_instance.stubs("basic_get").raises(Timeout::Error) + Bunny::Channel.any_instance.stubs('basic_get').raises(Timeout::Error) in_transaction do |msg_txn| txn = msg_txn - queue.publish("test") + queue.publish('test') queue.pop end end @@ -276,18 +276,18 @@ def test_noticed_error_at_segment_and_txn_on_error wait_until_not_nil(5) { txn } - assert_segment_noticed_error txn, /^MessageBroker\/RabbitMQ/, "Timeout::Error", /timeout/i - assert_transaction_noticed_error txn, "Timeout::Error" + assert_segment_noticed_error txn, /^MessageBroker\/RabbitMQ/, 'Timeout::Error', /timeout/i + assert_transaction_noticed_error txn, 'Timeout::Error' end def test_noticed_error_only_at_segment_on_error txn = nil with_queue(false) do |queue| - Bunny::Channel.any_instance.stubs("basic_get").raises(Timeout::Error) + Bunny::Channel.any_instance.stubs('basic_get').raises(Timeout::Error) in_transaction do |msg_txn| begin txn = msg_txn - queue.publish("test") + queue.publish('test') queue.pop rescue StandardError => e # NOP -- allowing ONLY span to notice error @@ -295,29 +295,29 @@ def test_noticed_error_only_at_segment_on_error end end - assert_segment_noticed_error txn, /^MessageBroker\/RabbitMQ/, "Timeout::Error", /timeout/i - refute_transaction_noticed_error txn, "Timeout::Error" + assert_segment_noticed_error txn, /^MessageBroker\/RabbitMQ/, 'Timeout::Error', /timeout/i + refute_transaction_noticed_error txn, 'Timeout::Error' end def test_error_starting_message_broker_segment_does_not_interfere_with_transaction with_queue do |queue| - NewRelic::Agent::Tracer.stubs(:start_message_broker_segment).raises(StandardError.new("Boo")) + NewRelic::Agent::Tracer.stubs(:start_message_broker_segment).raises(StandardError.new('Boo')) - in_transaction("test_txn") do + in_transaction('test_txn') do # This should error - queue.publish("test_msg") + queue.publish('test_msg') # this segment should be fine - segment = NewRelic::Agent::Tracer.start_segment(name: "Custom/blah/method") + segment = NewRelic::Agent::Tracer.start_segment(name: 'Custom/blah/method') segment.finish end msg = queue.pop - assert_equal "test_msg", msg[2] + assert_equal 'test_msg', msg[2] - assert_metrics_recorded ["Custom/blah/method"] - refute_metrics_recorded ["MessageBroker/RabbitMQ/Exchange/Produce/Named/Default"] + assert_metrics_recorded ['Custom/blah/method'] + refute_metrics_recorded ['MessageBroker/RabbitMQ/Exchange/Produce/Named/Default'] end end @@ -325,7 +325,7 @@ def test_pop_returning_no_message_doesnt_error NewRelic::Agent.stubs(:logger).returns(NewRelic::Agent::MemoryLogger.new) with_queue do |queue| - in_transaction("test_txn") do + in_transaction('test_txn') do queue.pop end @@ -339,24 +339,24 @@ def test_pop_returning_a_good_message_send_to_an_exchange_we_havent_accessed_doe with_queue do |queue| # publish in such a way that the exchange object does not end up in channel.exchanges channel = queue.channel - channel.basic_publish("test_msg", "", queue.name) + channel.basic_publish('test_msg', '', queue.name) assert_empty channel.exchanges - in_transaction("test_txn") do + in_transaction('test_txn') do msg = queue.pop - assert_equal "test_msg", msg[2] + assert_equal 'test_msg', msg[2] end assert_empty NewRelic::Agent.logger.messages - assert_metrics_recorded ["MessageBroker/RabbitMQ/Exchange/Consume/Named/Default"] + assert_metrics_recorded ['MessageBroker/RabbitMQ/Exchange/Consume/Named/Default'] end end def with_queue(temp = true, exclusive = true, &block) - queue_name = temp ? "" : random_string + queue_name = temp ? '' : random_string queue = @chan.queue(queue_name, exclusive: exclusive) yield(queue) if block @@ -373,6 +373,6 @@ def random_string def connection return Bunny.new unless docker? - Bunny.new("amqp://rabbitmq:5672") + Bunny.new('amqp://rabbitmq:5672') end end diff --git a/test/multiverse/suites/capistrano/deployment_test.rb b/test/multiverse/suites/capistrano/deployment_test.rb index b70dc2d0d1..27e04100b4 100644 --- a/test/multiverse/suites/capistrano/deployment_test.rb +++ b/test/multiverse/suites/capistrano/deployment_test.rb @@ -15,34 +15,34 @@ def setup def test_deploys_to_configured_application cap_it - assert_deployment_value("application_id", "test") + assert_deployment_value('application_id', 'test') end def test_deploys_with_commandline_parameter # Capistrano 3 doesn't provide built-in commandline params -> settings # We wire our own up via ENV to test setting out setting custom values env = { - 'NEWRELIC_CAPISTRANO_USER' => "Optimus Prime", - 'NEWRELIC_CAPISTRANO_APPNAME' => "Tesseract", - 'NEWRELIC_CAPISTRANO_REVISION' => "C-001", + 'NEWRELIC_CAPISTRANO_USER' => 'Optimus Prime', + 'NEWRELIC_CAPISTRANO_APPNAME' => 'Tesseract', + 'NEWRELIC_CAPISTRANO_REVISION' => 'C-001', 'NEWRELIC_CAPISTRANO_CHANGELOG' => "The greatest weakness of most humans is their hesitancy to tell others they love them while they're alive." } cap_it(env) - assert_deployment_value("user", "Optimus Prime") - assert_deployment_value("application_id", "Tesseract") - assert_deployment_value("revision", "C-001") - assert_deployment_value("changelog", "The greatest weakness of most humans is their hesitancy to tell others they love them while they're alive.") + assert_deployment_value('user', 'Optimus Prime') + assert_deployment_value('application_id', 'Tesseract') + assert_deployment_value('revision', 'C-001') + assert_deployment_value('changelog', "The greatest weakness of most humans is their hesitancy to tell others they love them while they're alive.") end def assert_deployment_value(key, value) assert_equal(1, @rpm_site.requests.count) - assert_equal(value, @rpm_site.requests.first["deployment"][key]) + assert_equal(value, @rpm_site.requests.first['deployment'][key]) end def cap_it(custom_env = {}) - cmd = "cap production newrelic:notice_deployment" + cmd = 'cap production newrelic:notice_deployment' default_env = {'FAKE_RPM_SITE_PORT' => @rpm_site.port.to_s} output = with_environment(default_env.merge(custom_env)) do `#{cmd}` diff --git a/test/multiverse/suites/capistrano2/config/deploy.rb b/test/multiverse/suites/capistrano2/config/deploy.rb index f55467b838..7a6b4638ba 100644 --- a/test/multiverse/suites/capistrano2/config/deploy.rb +++ b/test/multiverse/suites/capistrano2/config/deploy.rb @@ -4,16 +4,16 @@ require 'bundler/capistrano' -set :application, "new_relic_capistrano" -set :repository, "~/new_relic_capistrano" -set :current_path, "" -set :newrelic_license_key, "bootstrap_newrelic_admin_license_key_000" -set :newrelic_rails_env, "development" +set :application, 'new_relic_capistrano' +set :repository, '~/new_relic_capistrano' +set :current_path, '' +set :newrelic_license_key, 'bootstrap_newrelic_admin_license_key_000' +set :newrelic_rails_env, 'development' set :scm, :none -role :web, "localhost" -role :app, "localhost" -role :db, "localhost" +role :web, 'localhost' +role :app, 'localhost' +role :db, 'localhost' set :use_sudo, false diff --git a/test/multiverse/suites/capistrano2/deployment_test.rb b/test/multiverse/suites/capistrano2/deployment_test.rb index ec8c3979d0..b5b95e902a 100644 --- a/test/multiverse/suites/capistrano2/deployment_test.rb +++ b/test/multiverse/suites/capistrano2/deployment_test.rb @@ -14,22 +14,22 @@ def setup def test_deploys_to_configured_application cap_it - assert_deployment_value("application_id", "test") + assert_deployment_value('application_id', 'test') end def test_deploys_with_commandline_parameter - cap_it("-s newrelic_user=someone -s newrelic_appname=somewhere") + cap_it('-s newrelic_user=someone -s newrelic_appname=somewhere') - assert_deployment_value("user", "someone") - assert_deployment_value("application_id", "somewhere") + assert_deployment_value('user', 'someone') + assert_deployment_value('application_id', 'somewhere') end def assert_deployment_value(key, value) assert_equal(1, @rpm_site.requests.count) - assert_equal(value, @rpm_site.requests.first["deployment"][key]) + assert_equal(value, @rpm_site.requests.first['deployment'][key]) end - def cap_it(options = "") + def cap_it(options = '') cmd = "cap newrelic:notice_deployment #{options}" output = with_environment('FAKE_RPM_SITE_PORT' => @rpm_site.port.to_s) do `#{cmd}` diff --git a/test/multiverse/suites/config_file_loading/config_file_loading_test.rb b/test/multiverse/suites/config_file_loading/config_file_loading_test.rb index 984f5f94b7..15b18c5cd2 100644 --- a/test/multiverse/suites/config_file_loading/config_file_loading_test.rb +++ b/test/multiverse/suites/config_file_loading/config_file_loading_test.rb @@ -80,31 +80,31 @@ def setup_config(path, manual_config_options = {}, config_file_content = nil) def assert_config_read_from(path, manual_config_options = {}) setup_config(path, manual_config_options) - assert_equal("success!!", NewRelic::Agent.config[:foo], + assert_equal('success!!', NewRelic::Agent.config[:foo], "Failed to read yaml config from #{path.inspect[0..100]}\n\n#{NewRelic::Agent.config.inspect[0..100]}") end def assert_config_not_read_from(path) setup_config(path) - refute_equal NewRelic::Agent.config[:foo], "success!!", + refute_equal NewRelic::Agent.config[:foo], 'success!!', "Read yaml config from #{path.inspect}\n\n#{NewRelic::Agent.config.inspect}" end def test_config_loads_from_config_newrelic_yml - assert_config_read_from(File.join(@cwd, "config/newrelic.yml")) + assert_config_read_from(File.join(@cwd, 'config/newrelic.yml')) end def test_config_loads_from_newrelic_yml - assert_config_read_from(File.join(@cwd, "newrelic.yml")) + assert_config_read_from(File.join(@cwd, 'newrelic.yml')) end def test_config_loads_from_home_newrelic_yml - assert_config_read_from(ENV['HOME'] + "/newrelic.yml") + assert_config_read_from(ENV['HOME'] + '/newrelic.yml') end def test_config_loads_from_home_dot_newrelic_newrelic_yml - assert_config_read_from(ENV['HOME'] + "/.newrelic/newrelic.yml") + assert_config_read_from(ENV['HOME'] + '/.newrelic/newrelic.yml') end def test_config_loads_from_config_path_option_to_manual_start @@ -185,32 +185,32 @@ def test_exclude_commented_out_erb_lines log = with_array_logger { NewRelic::Agent.manual_start } - assert_equal "success!!", NewRelic::Agent.config[:foo] + assert_equal 'success!!', NewRelic::Agent.config[:foo] refute_log_contains(log, /ERROR.*Failed ERB processing/) refute_log_contains(log, /\(erb\)/) end def test_config_loads_from_env_NRCONFIG - ENV["NRCONFIG"] = "/tmp/foo/bar.yml" + ENV['NRCONFIG'] = '/tmp/foo/bar.yml' - assert_config_read_from("/tmp/foo/bar.yml") + assert_config_read_from('/tmp/foo/bar.yml') ensure - ENV["NRCONFIG"] = nil + ENV['NRCONFIG'] = nil end def test_config_isnt_loaded_from_somewhere_crazy - assert_config_not_read_from(File.join(@cwd, "somewhere/crazy/newrelic.yml")) + assert_config_not_read_from(File.join(@cwd, 'somewhere/crazy/newrelic.yml')) end def test_config_will_load_settings_for_environment_passed_manual_start - path = File.join(@cwd, "config/newrelic.yml") + path = File.join(@cwd, 'config/newrelic.yml') # pass an env key to NewRelic::Agent.manual_start which should cause it to # load that section of newrelic.yml setup_config(path, {:env => 'bazbangbarn'}) - assert_equal 'bazbangbarn', NewRelic::Agent.config[:i_am], "Agent.config did not load bazbangbarn config as requested" + assert_equal 'bazbangbarn', NewRelic::Agent.config[:i_am], 'Agent.config did not load bazbangbarn config as requested' end def test_parses_default_settings_correctly diff --git a/test/multiverse/suites/curb/curb_test.rb b/test/multiverse/suites/curb/curb_test.rb index 3d4b9d4cdb..41735351f7 100644 --- a/test/multiverse/suites/curb/curb_test.rb +++ b/test/multiverse/suites/curb/curb_test.rb @@ -34,7 +34,7 @@ def test_shouldnt_clobber_existing_completion_callback end end - assert completed, "completion block was never run" + assert completed, 'completion block was never run' end def test_get_works_with_the_shortcut_api @@ -92,7 +92,7 @@ def test_get_doesnt_destroy_ability_to_call_status end def test_doesnt_propagate_errors_in_instrumentation - NewRelic::Agent::CrossAppTracing.stubs(:cross_app_enabled?).raises("Booom") + NewRelic::Agent::CrossAppTracing.stubs(:cross_app_enabled?).raises('Booom') res = Curl::Easy.http_get(default_url) @@ -103,7 +103,7 @@ def test_works_with_parallel_fetches results = [] other_url = "http://localhost:#{$fake_server.port}/" - in_transaction("test") do + in_transaction('test') do Curl::Multi.get([default_url, other_url]) do |easy| results << easy.body_str end @@ -115,7 +115,7 @@ def test_works_with_parallel_fetches last_node = find_last_transaction_node() - assert_equal "External/Multiple/Curb::Multi/perform", last_node.metric_name + assert_equal 'External/Multiple/Curb::Multi/perform', last_node.metric_name end def test_block_passed_to_multi_perform_should_be_called @@ -123,7 +123,7 @@ def test_block_passed_to_multi_perform_should_be_called num_requests = 2 perform_block_called = false - in_transaction("test") do + in_transaction('test') do multi = Curl::Multi.new num_requests.times do |i| @@ -136,12 +136,12 @@ def test_block_passed_to_multi_perform_should_be_called multi.perform { perform_block_called = true } assert_equal(num_requests, successes) - assert(perform_block_called, "Block passed to Curl::Multi.perform should have been called") + assert(perform_block_called, 'Block passed to Curl::Multi.perform should have been called') end last_node = find_last_transaction_node() - assert_equal "External/Multiple/Curb::Multi/perform", last_node.metric_name + assert_equal 'External/Multiple/Curb::Multi/perform', last_node.metric_name end # https://github.com/newrelic/newrelic-ruby-agent/issues/1033 @@ -267,7 +267,7 @@ def multi.requests # def client_name - "Curb" + 'Curb' end def timeout_error_class @@ -275,7 +275,7 @@ def timeout_error_class end def simulate_error_response - get_response("http://localhost:666/evil") + get_response('http://localhost:666/evil') end def get_response(url = nil, headers = nil) @@ -314,11 +314,11 @@ def body(res) end def request_instance - NewRelic::Agent::HTTPClients::CurbRequest.new(Curl::Easy.new("http://localhost")) + NewRelic::Agent::HTTPClients::CurbRequest.new(Curl::Easy.new('http://localhost')) end def response_instance(headers = {}) - res = NewRelic::Agent::HTTPClients::CurbResponse.new(Curl::Easy.new("http://localhost")) + res = NewRelic::Agent::HTTPClients::CurbResponse.new(Curl::Easy.new('http://localhost')) headers.each do |hdr, val| res.append_header_data("#{hdr}: #{val}") end diff --git a/test/multiverse/suites/deferred_instrumentation/sinatra_test.rb b/test/multiverse/suites/deferred_instrumentation/sinatra_test.rb index a9e9cee429..42780bb1ab 100644 --- a/test/multiverse/suites/deferred_instrumentation/sinatra_test.rb +++ b/test/multiverse/suites/deferred_instrumentation/sinatra_test.rb @@ -24,11 +24,11 @@ class DeferredSinatraTestApp < Sinatra::Base end get '/' do - "root path" + 'root path' end get '/user/login' do - "please log in" + 'please log in' end # this action will always return 404 because of the condition. @@ -37,7 +37,7 @@ class DeferredSinatraTestApp < Sinatra::Base end get '/raise' do - raise "Uh-oh" + raise 'Uh-oh' end # check that pass works properly @@ -53,7 +53,7 @@ class DeferredSinatraTestApp < Sinatra::Base get('/error') {} condition do - raise "Boo" if $precondition_already_checked + raise 'Boo' if $precondition_already_checked $precondition_already_checked = true end @@ -82,7 +82,7 @@ class DeferredSinatraTestApp < Sinatra::Base end post '/files' do - "file uploaded" + 'file uploaded' end end diff --git a/test/multiverse/suites/delayed_job/Envfile b/test/multiverse/suites/delayed_job/Envfile index 0940ccfa44..0b7626b1e2 100644 --- a/test/multiverse/suites/delayed_job/Envfile +++ b/test/multiverse/suites/delayed_job/Envfile @@ -61,17 +61,6 @@ gemfile <<~RB #{boilerplate_gems} RB -if RUBY_VERSION < '2.4.0' - gemfile <<~RB - gem 'delayed_job', '~> 4.1.0' - gem 'delayed_job_active_record', '~> 4.1.1' - gem 'minitest', '~> 4.7.5' # required for Rails < 4.1 - gem 'activerecord', '~> 3.2.19' - gem 'i18n', '~> 0.6.11' - #{boilerplate_gems} - RB -end - if RUBY_VERSION < '2.5.0' && RUBY_PLATFORM != 'java' # delayed_job_active_record 4.1.2 drops support for Rails 3 gemfile <<~RB @@ -94,48 +83,3 @@ if RUBY_VERSION < '2.5.0' #{boilerplate_gems} RB end - -# delayed_job_active_record (and older baked into delayed_job) support -if RUBY_VERSION < '2.4.0' - dj4_with_active_record = <<~DJ - gem 'delayed_job', '~> 4.0.4' - gem 'delayed_job_active_record', '~> 4.0.2' - #{boilerplate_gems} - DJ -else - dj4_with_active_record = <<~DJ - gem 'delayed_job', '~> 4.0.4' - gem 'delayed_job_active_record', '= 4.0.2' - #{boilerplate_gems} - DJ -end - -dj3_with_active_record = <<~DJ - gem 'delayed_job', '~> 3.0.5' - gem 'delayed_job_active_record', '~> 0.4.4' - #{boilerplate_gems} -DJ - -if RUBY_VERSION < '2.4.0' - gemfile <<~RB - gem 'activerecord', '~> 4.2.0' - gem 'i18n', '~> 0.7.0' - #{dj4_with_active_record} - gem 'minitest', '~> 5.2.3' - RB - - gemfile <<~RB - gem 'activerecord', '~> 4.1.6' - gem 'i18n', '~> 0.6.11' - #{dj4_with_active_record} - gem 'minitest', '~> 5.2.3' - RB - - gemfile <<~RB - gem 'activerecord', '~> 4.0.10' - gem 'minitest', '~> 4.7.5' # required for Rails < 4.1 - gem 'i18n', '~> 0.6.11' - #{dj4_with_active_record} - RB -end - diff --git a/test/multiverse/suites/delayed_job/before_suite.rb b/test/multiverse/suites/delayed_job/before_suite.rb index 59acc1a6e9..c837dbb280 100644 --- a/test/multiverse/suites/delayed_job/before_suite.rb +++ b/test/multiverse/suites/delayed_job/before_suite.rb @@ -23,17 +23,17 @@ # required on others. Delayed::Worker.guess_backend -if Delayed::Worker.backend.to_s == "Delayed::Backend::ActiveRecord::Job" - $db_connection = ActiveRecord::Base.establish_connection(:adapter => "sqlite3", - :database => ":memory:") +if Delayed::Worker.backend.to_s == 'Delayed::Backend::ActiveRecord::Job' + $db_connection = ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', + :database => ':memory:') # Evaluate the delayed_job_active_record ERB template for database migration # This handles the case where ActiveRecord versions greater than or equal to 5.0 # have versioned migration classes (e.g. ActiveRecord::Migration[5.0]) and those # less than 5.0 do not. - dj_gem_spec = Bundler.rubygems.loaded_specs("delayed_job_active_record") || - Bundler.rubygems.loaded_specs("delayed_job") + dj_gem_spec = Bundler.rubygems.loaded_specs('delayed_job_active_record') || + Bundler.rubygems.loaded_specs('delayed_job') dj_gem_path = dj_gem_spec.full_gem_path diff --git a/test/multiverse/suites/delayed_job/delayed_job_instrumentation_test.rb b/test/multiverse/suites/delayed_job/delayed_job_instrumentation_test.rb index 3069ae9981..588d0e2b5b 100644 --- a/test/multiverse/suites/delayed_job/delayed_job_instrumentation_test.rb +++ b/test/multiverse/suites/delayed_job/delayed_job_instrumentation_test.rb @@ -24,11 +24,11 @@ class Pelican < ActiveRecord::Base self.table_name = :pelicans def quack - "quack..." + 'quack...' end def quack_later - "...quack" + '...quack' end handle_asynchronously :quack_later @@ -43,7 +43,7 @@ def after_setup # to install our instrumentation. Delayed::Workers are not initialized when running # tests inline so we have to manually instantiate one to install our instrumentation. # We also need to take care to only install the instrumentation once. - unless Delayed::Job.instance_methods.any? { |m| m == :invoke_job_without_new_relic || m == "invoke_job_without_new_relic" } + unless Delayed::Job.instance_methods.any? { |m| m == :invoke_job_without_new_relic || m == 'invoke_job_without_new_relic' } Delayed::Worker.new end end @@ -57,12 +57,12 @@ def after_teardown # We can only test methods using delay and handle_asynchronously on versions that run jobs via # the invoke_job method. def self.dj_invokes_job_inline? - Gem.loaded_specs["delayed_job"].version >= Gem::Version.new("3.0.0") + Gem.loaded_specs['delayed_job'].version >= Gem::Version.new('3.0.0') end if dj_invokes_job_inline? def test_delay_method - p = Pelican.create(:name => "Charlie") + p = Pelican.create(:name => 'Charlie') p.delay.quack assert_metrics_recorded [ @@ -73,7 +73,7 @@ def test_delay_method end def test_handle_asynchronously - p = Pelican.create(:name => "Charlieee") + p = Pelican.create(:name => 'Charlieee') p.quack_later assert_metrics_recorded [ diff --git a/test/multiverse/suites/delayed_job/delayed_job_sampler_test.rb b/test/multiverse/suites/delayed_job/delayed_job_sampler_test.rb index 41b8189000..66f6562c03 100644 --- a/test/multiverse/suites/delayed_job/delayed_job_sampler_test.rb +++ b/test/multiverse/suites/delayed_job/delayed_job_sampler_test.rb @@ -11,8 +11,8 @@ class DelayedJobSamplerTest < Minitest::Test TestWorker = Struct.new(:name, :read_ahead) setup_and_teardown_agent do - NewRelic::DelayedJobInjection.worker_name = "delayed" - @worker = TestWorker.new("delayed", 1) + NewRelic::DelayedJobInjection.worker_name = 'delayed' + @worker = TestWorker.new('delayed', 1) @sampler = NewRelic::Agent::Samplers::DelayedJobSampler.new end @@ -38,8 +38,8 @@ def test_sampler_no_failures_or_locks @sampler.poll assert_metrics_recorded( - "Workers/DelayedJob/failed_jobs" => {:total_call_time => 0}, - "Workers/DelayedJob/locked_jobs" => {:total_call_time => 0} + 'Workers/DelayedJob/failed_jobs' => {:total_call_time => 0}, + 'Workers/DelayedJob/locked_jobs' => {:total_call_time => 0} ) end @@ -53,7 +53,7 @@ def test_sampler_sees_failures @sampler.poll assert_metrics_recorded( - "Workers/DelayedJob/failed_jobs" => {:total_call_time => 1} + 'Workers/DelayedJob/failed_jobs' => {:total_call_time => 1} ) end @@ -64,7 +64,7 @@ def test_sampler_sees_locks @sampler.poll assert_metrics_recorded( - "Workers/DelayedJob/locked_jobs" => {:total_call_time => 1} + 'Workers/DelayedJob/locked_jobs' => {:total_call_time => 1} ) end @@ -74,8 +74,8 @@ def test_sampler_queue_depth_with_job @sampler.poll assert_metrics_recorded( - "Workers/DelayedJob/queue_length/priority/0" => {:total_call_time => 1}, - "Workers/DelayedJob/queue_length/all" => {:total_call_time => 1} + 'Workers/DelayedJob/queue_length/priority/0' => {:total_call_time => 1}, + 'Workers/DelayedJob/queue_length/all' => {:total_call_time => 1} ) end @@ -85,8 +85,8 @@ def test_sampler_queue_depth_with_alternate_priority @sampler.poll assert_metrics_recorded( - "Workers/DelayedJob/queue_length/priority/7" => {:total_call_time => 1}, - "Workers/DelayedJob/queue_length/all" => {:total_call_time => 1} + 'Workers/DelayedJob/queue_length/priority/7' => {:total_call_time => 1}, + 'Workers/DelayedJob/queue_length/all' => {:total_call_time => 1} ) end @@ -98,39 +98,39 @@ def test_sampler_queue_depth_with_default_queue @sampler.poll assert_metrics_recorded( - "Workers/DelayedJob/queue_length/name/default" => {:total_call_time => 1}, - "Workers/DelayedJob/queue_length/all" => {:total_call_time => 1} + 'Workers/DelayedJob/queue_length/name/default' => {:total_call_time => 1}, + 'Workers/DelayedJob/queue_length/all' => {:total_call_time => 1} ) end def test_sampler_queue_depth_with_alternate_queues return unless Delayed::Job.instance_methods.include?(:queue) - IWantToWait.new.delay(:queue => "cue").take_action - IWantToWait.new.delay(:queue => "cute").take_action + IWantToWait.new.delay(:queue => 'cue').take_action + IWantToWait.new.delay(:queue => 'cute').take_action @sampler.poll assert_metrics_recorded( - "Workers/DelayedJob/queue_length/name/cue" => {:total_call_time => 1}, - "Workers/DelayedJob/queue_length/name/cute" => {:total_call_time => 1}, - "Workers/DelayedJob/queue_length/all" => {:total_call_time => 2} + 'Workers/DelayedJob/queue_length/name/cue' => {:total_call_time => 1}, + 'Workers/DelayedJob/queue_length/name/cute' => {:total_call_time => 1}, + 'Workers/DelayedJob/queue_length/all' => {:total_call_time => 2} ) end def test_sampler_queue_depth_with_queues_and_priorities return unless Delayed::Job.instance_methods.include?(:queue) - IWantToWait.new.delay(:priority => 1, :queue => "cue").take_action - IWantToWait.new.delay(:priority => 1, :queue => "cute").take_action + IWantToWait.new.delay(:priority => 1, :queue => 'cue').take_action + IWantToWait.new.delay(:priority => 1, :queue => 'cute').take_action @sampler.poll assert_metrics_recorded( - "Workers/DelayedJob/queue_length/name/cue" => {:total_call_time => 1}, - "Workers/DelayedJob/queue_length/name/cute" => {:total_call_time => 1}, - "Workers/DelayedJob/queue_length/priority/1" => {:total_call_time => 2}, - "Workers/DelayedJob/queue_length/all" => {:total_call_time => 2} + 'Workers/DelayedJob/queue_length/name/cue' => {:total_call_time => 1}, + 'Workers/DelayedJob/queue_length/name/cute' => {:total_call_time => 1}, + 'Workers/DelayedJob/queue_length/priority/1' => {:total_call_time => 2}, + 'Workers/DelayedJob/queue_length/all' => {:total_call_time => 2} ) end end diff --git a/test/multiverse/suites/delayed_job/unsupported_backend_test.rb b/test/multiverse/suites/delayed_job/unsupported_backend_test.rb index 7a7a0cd612..516164ab04 100644 --- a/test/multiverse/suites/delayed_job/unsupported_backend_test.rb +++ b/test/multiverse/suites/delayed_job/unsupported_backend_test.rb @@ -9,7 +9,7 @@ class UnsupportedBackendTest < Minitest::Test include MultiverseHelpers setup_and_teardown_agent do - NewRelic::DelayedJobInjection.worker_name = "delayed" + NewRelic::DelayedJobInjection.worker_name = 'delayed' end def test_unsupported_raises_on_instantiation diff --git a/test/multiverse/suites/elasticsearch/elasticsearch_instrumentation_test.rb b/test/multiverse/suites/elasticsearch/elasticsearch_instrumentation_test.rb index 3bd1ad24b2..847070acb1 100644 --- a/test/multiverse/suites/elasticsearch/elasticsearch_instrumentation_test.rb +++ b/test/multiverse/suites/elasticsearch/elasticsearch_instrumentation_test.rb @@ -188,7 +188,7 @@ def simulate_transport_error end def transport_error_class - if ::Gem::Version.create(Elasticsearch::VERSION) < ::Gem::Version.create("8.0.0") + if ::Gem::Version.create(Elasticsearch::VERSION) < ::Gem::Version.create('8.0.0') ::Elasticsearch::Transport::Transport::Error else ::Elastic::Transport::Transport::Error @@ -196,7 +196,7 @@ def transport_error_class end def port - if ::Gem::Version.create(Elasticsearch::VERSION) < ::Gem::Version.create("8.0.0") + if ::Gem::Version.create(Elasticsearch::VERSION) < ::Gem::Version.create('8.0.0') 9200 # 9200 for elasticsearch 7 else 9250 # 9250 for elasticsearch 8 diff --git a/test/multiverse/suites/excon/Envfile b/test/multiverse/suites/excon/Envfile index eeb6b0e0cf..f417dc6628 100644 --- a/test/multiverse/suites/excon/Envfile +++ b/test/multiverse/suites/excon/Envfile @@ -4,8 +4,7 @@ excon_versions = [ [nil], - ['0.56.0'], - ['0.19.0', 2.4, 2.6] + ['0.56.0'] ] def gem_list(excon_version = nil) diff --git a/test/multiverse/suites/excon/excon_test.rb b/test/multiverse/suites/excon/excon_test.rb index f0254e1241..3debbe9c7e 100644 --- a/test/multiverse/suites/excon/excon_test.rb +++ b/test/multiverse/suites/excon/excon_test.rb @@ -2,15 +2,15 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -require "excon" -require "newrelic_rpm" -require "http_client_test_cases" +require 'excon' +require 'newrelic_rpm' +require 'http_client_test_cases' class ExconTest < Minitest::Test include HttpClientTestCases def client_name - "Excon" + 'Excon' end def new_timeout_error_class @@ -47,11 +47,11 @@ def head_response end def post_response - Excon.post(default_url, body: String.new) + Excon.post(default_url, body: +'') end def put_response - Excon.put(default_url, body: String.new) + Excon.put(default_url, body: +'') end def delete_response @@ -60,11 +60,11 @@ def delete_response def request_instance params = { - :method => "get", - :scheme => "http", - :host => "localhost", + :method => 'get', + :scheme => 'http', + :host => 'localhost', :port => 80, - :path => "", + :path => '', :headers => {} } NewRelic::Agent::HTTPClients::ExconHTTPRequest.new(params) @@ -87,7 +87,7 @@ def test_still_records_tt_node_when_request_fails_with_idempotent_set tt = last_transaction_trace node = tt.root_node.children.first.children.first - assert_equal("External/localhost/Excon/GET", node.metric_name) + assert_equal('External/localhost/Excon/GET', node.metric_name) assert_equal(target_url, node.params[:uri]) end @@ -103,6 +103,6 @@ def test_still_records_tt_node_when_request_expects_different_response_code last_node = find_last_transaction_node() - assert_equal("External/localhost/Excon/GET", last_node.metric_name) + assert_equal('External/localhost/Excon/GET', last_node.metric_name) end end diff --git a/test/multiverse/suites/grape/grape_test.rb b/test/multiverse/suites/grape/grape_test.rb index 0d3bef57bd..ae44521d90 100644 --- a/test/multiverse/suites/grape/grape_test.rb +++ b/test/multiverse/suites/grape/grape_test.rb @@ -2,8 +2,8 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -require "grape" -require "newrelic_rpm" +require 'grape' +require 'newrelic_rpm' require './grape_test_api' class GrapeTest < Minitest::Test @@ -93,7 +93,7 @@ def test_route_params_are_captured get('/grape_ape/10') expected = { - "request.parameters.id" => "10" + 'request.parameters.id' => '10' } assert_equal expected, last_transaction_trace_request_params @@ -115,7 +115,7 @@ def test_query_params_are_captured def test_post_body_params_are_captured with_config(:capture_params => true) do - post('/grape_ape', {'q' => '1234', 'foo' => 'bar'}.to_json, "CONTENT_TYPE" => "application/json") + post('/grape_ape', {'q' => '1234', 'foo' => 'bar'}.to_json, 'CONTENT_TYPE' => 'application/json') expected = { 'request.parameters.q' => '1234', @@ -129,7 +129,7 @@ def test_post_body_params_are_captured def test_post_body_params_are_captured_with_error with_config(:capture_params => true) do assert_raises(GrapeTestApiError) do - post('/grape_ape_fail', {'q' => '1234', 'foo' => 'fail'}.to_json, "CONTENT_TYPE" => "application/json") + post('/grape_ape_fail', {'q' => '1234', 'foo' => 'fail'}.to_json, 'CONTENT_TYPE' => 'application/json') end agent_attributes = attributes_for(last_traced_error, :agent) @@ -141,7 +141,7 @@ def test_post_body_params_are_captured_with_error def test_post_body_params_are_captured_with_rescue_from with_config(:capture_params => true) do - post('/grape_ape_fail_rescue', {'q' => '1234', 'foo' => 'fail'}.to_json, "CONTENT_TYPE" => "application/json") + post('/grape_ape_fail_rescue', {'q' => '1234', 'foo' => 'fail'}.to_json, 'CONTENT_TYPE' => 'application/json') agent_attributes = attributes_for(last_traced_error, :agent) @@ -152,12 +152,12 @@ def test_post_body_params_are_captured_with_rescue_from def test_post_body_with_nested_params_are_captured with_config(:capture_params => true) do - params = {"ape" => {"first_name" => "koko", "last_name" => "gorilla"}} - post('/grape_ape', params.to_json, "CONTENT_TYPE" => "application/json") + params = {'ape' => {'first_name' => 'koko', 'last_name' => 'gorilla'}} + post('/grape_ape', params.to_json, 'CONTENT_TYPE' => 'application/json') expected = { - "request.parameters.ape.first_name" => "koko", - "request.parameters.ape.last_name" => "gorilla" + 'request.parameters.ape.first_name' => 'koko', + 'request.parameters.ape.last_name' => 'gorilla' } assert_equal expected, last_transaction_trace_request_params @@ -167,14 +167,14 @@ def test_post_body_with_nested_params_are_captured def test_file_upload_params_are_filtered with_config(:capture_params => true) do params = { - :title => "blah", + :title => 'blah', :file => Rack::Test::UploadedFile.new(__FILE__, 'text/plain') } post('/grape_ape', params) expected = { - "request.parameters.title" => "blah", - "request.parameters.file" => "[FILE]" + 'request.parameters.title' => 'blah', + 'request.parameters.file' => '[FILE]' } assert_equal expected, last_transaction_trace_request_params @@ -183,7 +183,7 @@ def test_file_upload_params_are_filtered def test_404_with_params_does_not_capture_them with_config(:capture_params => true) do - post('/grape_catfish', {"foo" => "bar"}) + post('/grape_catfish', {'foo' => 'bar'}) expected = {} assert_equal expected, last_transaction_trace_request_params @@ -194,13 +194,13 @@ def test_params_are_captured_on_transaction_events with_config(:'attributes.include' => 'request.parameters.*', :'attributes.exclude' => ['request.*', 'response.*']) do json = { - :foo => "bar", - :bar => "baz" + :foo => 'bar', + :bar => 'baz' }.to_json - post('/grape_ape', json, {"CONTENT_TYPE" => "application/json"}) + post('/grape_ape', json, {'CONTENT_TYPE' => 'application/json'}) - expected = {"request.parameters.foo" => "bar", "request.parameters.bar" => "baz"} + expected = {'request.parameters.foo' => 'bar', 'request.parameters.bar' => 'baz'} actual = agent_attributes_for_single_event_posted_without_ignored_attributes assert_equal(expected, actual) @@ -211,20 +211,20 @@ def test_request_and_response_attributes_recorded_as_agent_attributes post('/grape_ape') expected = { - "response.headers.contentLength" => last_response.content_length.to_i, - "response.headers.contentType" => last_response.content_type, - "request.headers.contentLength" => last_request.content_length.to_i, - "request.headers.contentType" => last_request.content_type, - "request.headers.host" => last_request.host, - "request.method" => last_request.request_method + 'response.headers.contentLength' => last_response.content_length.to_i, + 'response.headers.contentType' => last_response.content_type, + 'request.headers.contentLength' => last_request.content_length.to_i, + 'request.headers.contentType' => last_request.content_type, + 'request.headers.host' => last_request.host, + 'request.method' => last_request.request_method } # Rack >= 2.1 changes how/when contentLength is computed and Grape >= 1.3 also changes to deal with this. # interactions with Rack < 2.1 and >= 2.1 differ on response.headers.contentLength calculations # so we remove it when it is zero since its not present in such cases. - if Gem::Version.new(::Grape::VERSION) >= Gem::Version.new("1.3.0") - if expected["response.headers.contentLength"] == 0 - expected.delete("response.headers.contentLength") + if Gem::Version.new(::Grape::VERSION) >= Gem::Version.new('1.3.0') + if expected['response.headers.contentLength'] == 0 + expected.delete('response.headers.contentLength') end end actual = agent_attributes_for_single_event_posted_without_ignored_attributes diff --git a/test/multiverse/suites/grape/grape_test_api.rb b/test/multiverse/suites/grape/grape_test_api.rb index b87461d8bb..89a5b2535f 100644 --- a/test/multiverse/suites/grape/grape_test_api.rb +++ b/test/multiverse/suites/grape/grape_test_api.rb @@ -20,7 +20,7 @@ class GrapeTestApi < Grape::API end get 'renamed' do - ::NewRelic::Agent.set_transaction_name("RenamedTxn") + ::NewRelic::Agent.set_transaction_name('RenamedTxn') 'Totally renamed it.' end diff --git a/test/multiverse/suites/grape/grape_versioning_test.rb b/test/multiverse/suites/grape/grape_versioning_test.rb index e2ec219a46..9c1dce5daf 100644 --- a/test/multiverse/suites/grape/grape_versioning_test.rb +++ b/test/multiverse/suites/grape/grape_versioning_test.rb @@ -109,9 +109,9 @@ def test_shared_version_block_in_transaction_names # def test_default_header_version_in_transaction_names @app_class = GrapeVersioning::DefaultHeaderApi - get("/fish", nil, 'HTTP_ACCEPT' => 'application/json') + get('/fish', nil, 'HTTP_ACCEPT' => 'application/json') - assert_metrics_recorded("Controller/Grape/GrapeVersioning::DefaultHeaderApi-v2|v3/fish (GET)") + assert_metrics_recorded('Controller/Grape/GrapeVersioning::DefaultHeaderApi-v2|v3/fish (GET)') end # :accept_version_header introduced in 0.5 @@ -121,9 +121,9 @@ def test_default_header_version_in_transaction_names if Gem::Version.new(Grape::VERSION) >= Gem::Version.new('0.5.0') def test_default_accept_version_header_version_in_transaction_names @app_class = GrapeVersioning::DefaultAcceptVersionHeaderApi - get("/fish", nil, 'HTTP_ACCEPT_VERSION' => '') + get('/fish', nil, 'HTTP_ACCEPT_VERSION' => '') - assert_metrics_recorded("Controller/Grape/GrapeVersioning::DefaultAcceptVersionHeaderApi-v2|v3/fish (GET)") + assert_metrics_recorded('Controller/Grape/GrapeVersioning::DefaultAcceptVersionHeaderApi-v2|v3/fish (GET)') end end end diff --git a/test/multiverse/suites/grape/grape_versioning_test_api.rb b/test/multiverse/suites/grape/grape_versioning_test_api.rb index 5c193ff0cc..4cc41f3760 100644 --- a/test/multiverse/suites/grape/grape_versioning_test_api.rb +++ b/test/multiverse/suites/grape/grape_versioning_test_api.rb @@ -10,12 +10,12 @@ class ApiV1 < Grape::API format :json get do - "root" + 'root' end resource :fish do get do - "api v1" + 'api v1' end end end @@ -27,19 +27,19 @@ class ApiV2 < Grape::API resource :fish do get do - "api v2" + 'api v2' end end end class ApiV3 < Grape::API - version 'v3', :using => :header, :vendor => "newrelic" + version 'v3', :using => :header, :vendor => 'newrelic' format :json resource :fish do get do - "api v3" + 'api v3' end end end @@ -54,7 +54,7 @@ class ApiV4 < Grape::API resource :fish do get do - "api v4" + 'api v4' end end end @@ -69,7 +69,7 @@ class CascadingAPI < Grape::API resource :fish do get do - "api v5" + 'api v5' end end @@ -81,7 +81,7 @@ class Unversioned < Grape::API resource :fish do get do - "api v5" + 'api v5' end end end @@ -91,7 +91,7 @@ class SharedApi < Grape::API version 'v1', 'v2', 'v3', 'v4' resource :fish do get do - "api v1-4" + 'api v1-4' end end end @@ -101,7 +101,7 @@ class SharedBlockApi < Grape::API version 'v1', 'v2', 'v3', 'v4' do resource :fish do get do - "api v1-4" + 'api v1-4' end end end @@ -109,10 +109,10 @@ class SharedBlockApi < Grape::API class DefaultHeaderApi < Grape::API format :json - version 'v2', 'v3', :using => :header, :vendor => "newrelic" + version 'v2', 'v3', :using => :header, :vendor => 'newrelic' resource :fish do get do - "api v1-4" + 'api v1-4' end end end @@ -122,7 +122,7 @@ class DefaultAcceptVersionHeaderApi < Grape::API version 'v2', 'v3', :using => :accept_version_header resource :fish do get do - "api v1-4" + 'api v1-4' end end end diff --git a/test/multiverse/suites/grape/unsupported_version_test.rb b/test/multiverse/suites/grape/unsupported_version_test.rb index 85f379faed..b84906d592 100644 --- a/test/multiverse/suites/grape/unsupported_version_test.rb +++ b/test/multiverse/suites/grape/unsupported_version_test.rb @@ -2,8 +2,8 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -require "grape" -require "newrelic_rpm" +require 'grape' +require 'newrelic_rpm' require './grape_test_api' class UnsupportedGrapeTest < Minitest::Test diff --git a/test/multiverse/suites/grpc/grpc_client_test.rb b/test/multiverse/suites/grpc/grpc_client_test.rb index 7af77c0ce8..e662885d38 100644 --- a/test/multiverse/suites/grpc/grpc_client_test.rb +++ b/test/multiverse/suites/grpc/grpc_client_test.rb @@ -130,6 +130,19 @@ def test_distributed_tracing_payload_created assert_distributed_tracing_payload_created_for_transaction(transaction) end + def test_distributed_tracing_payload_skipped_for_cat + metadata = {} + + with_config(:'distributed_tracing.enabled' => false, + :'cross_application_tracer.enabled' => true) do + transaction = NewRelic::Agent.instance.stub(:connected?, true) do + successful_grpc_client_issue_request_with_tracing(metadata) + end + end + + assert_predicate metadata, :empty? + end + def test_span_attributes_added successful_grpc_client_issue_request_with_tracing spans = harvest_span_events! diff --git a/test/multiverse/suites/grpc/grpc_server_test.rb b/test/multiverse/suites/grpc/grpc_server_test.rb index 6d74ce2cd2..e69d440aed 100644 --- a/test/multiverse/suites/grpc/grpc_server_test.rb +++ b/test/multiverse/suites/grpc/grpc_server_test.rb @@ -41,7 +41,7 @@ def method def current_segment t = MiniTest::Mock.new t.expect(:add_agent_attribute, nil, [:'request.headers', {}]) - t.expect(:add_agent_attribute, nil, [:'request.uri', "grpc://:/"]) + t.expect(:add_agent_attribute, nil, [:'request.uri', 'grpc://:/']) t.expect(:add_agent_attribute, nil, [:'request.method', nil]) t.expect(:add_agent_attribute, nil, [:'request.grpc_type', nil]) t @@ -54,7 +54,7 @@ def destinations def transaction t = MiniTest::Mock.new t.expect(:add_agent_attribute, nil, [:'request.headers', {}, destinations]) - t.expect(:add_agent_attribute, nil, [:'request.uri', "grpc://:/", destinations]) + t.expect(:add_agent_attribute, nil, [:'request.uri', 'grpc://:/', destinations]) t.expect(:add_agent_attribute, nil, [:'request.method', nil, destinations]) t.expect(:add_agent_attribute, nil, [:'request.grpc_type', nil, destinations]) t.expect(:current_segment, nil) # 4 existence checks diff --git a/test/multiverse/suites/high_security/high_security_test.rb b/test/multiverse/suites/high_security/high_security_test.rb index be1be526cb..df0f7db51e 100644 --- a/test/multiverse/suites/high_security/high_security_test.rb +++ b/test/multiverse/suites/high_security/high_security_test.rb @@ -14,34 +14,34 @@ class HighSecurityTest < Minitest::Test setup_and_teardown_agent do |collector| collector.use_ssl = true collector.stub('connect', { - "agent_run_id" => 1, - "agent_config" => { + 'agent_run_id' => 1, + 'agent_config' => { # Make sure that we take TT's all the time for testing purposes - "transaction_tracer.transaction_threshold" => -10, + 'transaction_tracer.transaction_threshold' => -10, # Really, really try to get us to allow things that we shouldn't when # in high security mode - "capture_params" => true, + 'capture_params' => true, - "transaction_tracer.capture_attributes" => true, - "error_collector.capture_attributes" => true, - "browser_monitoring.capture_attributes" => true, - "analytics_events.capture_attributes" => true, + 'transaction_tracer.capture_attributes' => true, + 'error_collector.capture_attributes' => true, + 'browser_monitoring.capture_attributes' => true, + 'analytics_events.capture_attributes' => true, - "attributes.enabled" => true, - "attributes.include" => ["*", "request.parameters.*"], + 'attributes.enabled' => true, + 'attributes.include' => ['*', 'request.parameters.*'], - "transaction_tracer.attributes.enabled" => true, - "transaction_tracer.attributes.include" => ["*", "request.parameters.*"], + 'transaction_tracer.attributes.enabled' => true, + 'transaction_tracer.attributes.include' => ['*', 'request.parameters.*'], - "transaction_events.attributes.enabled" => true, - "transaction_events.attributes.include" => ["*", "request.parameters.*"], + 'transaction_events.attributes.enabled' => true, + 'transaction_events.attributes.include' => ['*', 'request.parameters.*'], - "error_collector.attributes.enabled" => true, - "error_collector.attributes.include" => ["*", "request.parameters.*"], + 'error_collector.attributes.enabled' => true, + 'error_collector.attributes.include' => ['*', 'request.parameters.*'], - "browser_monitoring.attributes.enabled" => true, - "browser_monitoring.attributes.include" => ["*", "request.parameters.*"] + 'browser_monitoring.attributes.enabled' => true, + 'browser_monitoring.attributes.include' => ['*', 'request.parameters.*'] } }, 200) end @@ -59,14 +59,14 @@ def test_sends_high_security_flag_in_connect data = $collector.calls_for('connect') - assert data.first.body["high_security"] + assert data.first.body['high_security'] end # RUBY-2242 - helps with CSP adoptability def test_sends_high_security_flag_in_preconnect data = $collector.calls_for('preconnect') - assert data.first.body.first["high_security"] + assert data.first.body.first['high_security'] end def test_disallows_server_config_from_overriding_high_security @@ -76,7 +76,7 @@ def test_disallows_server_config_from_overriding_high_security def test_doesnt_capture_params_to_transaction_traces # TODO: stop the flapping/flaking skip 'Flaps too often with JRuby' if defined?(JRuby) - in_transaction(:filtered_params => {"loose" => "params"}) do + in_transaction(:filtered_params => {'loose' => 'params'}) do end run_harvest @@ -89,8 +89,8 @@ def test_doesnt_capture_params_to_transaction_traces def test_doesnt_capture_params_to_errors assert_raises(RuntimeError) do - in_transaction(:filtered_params => {"loose" => "params"}) do - raise "O_o" + in_transaction(:filtered_params => {'loose' => 'params'}) do + raise 'O_o' end end @@ -103,7 +103,7 @@ def test_doesnt_capture_params_to_errors end def test_doesnt_capture_params_to_events - in_transaction(:filtered_params => {"loose" => "params"}) do + in_transaction(:filtered_params => {'loose' => 'params'}) do end run_harvest @@ -115,7 +115,7 @@ def test_doesnt_capture_params_to_events end def test_doesnt_capture_params_to_browser - in_transaction(:filtered_params => {"loose" => "params"}) do + in_transaction(:filtered_params => {'loose' => 'params'}) do capture_js_data end @@ -126,7 +126,7 @@ def test_doesnt_capture_params_to_browser def test_disallows_custom_attributes_to_transaction_traces in_transaction do - NewRelic::Agent.add_custom_attributes(:not => "allowed") + NewRelic::Agent.add_custom_attributes(:not => 'allowed') end run_harvest @@ -140,8 +140,8 @@ def test_disallows_custom_attributes_to_transaction_traces def test_disallows_custom_attributes_on_errors assert_raises(RuntimeError) do in_transaction do - NewRelic::Agent.add_custom_attributes(:not => "allowed") - raise "O_o" + NewRelic::Agent.add_custom_attributes(:not => 'allowed') + raise 'O_o' end end @@ -155,7 +155,7 @@ def test_disallows_custom_attributes_on_errors def test_disallows_custom_attributes_on_events in_transaction do - NewRelic::Agent.add_custom_attributes(:not => "allowed") + NewRelic::Agent.add_custom_attributes(:not => 'allowed') end run_harvest @@ -168,7 +168,7 @@ def test_disallows_custom_attributes_on_events def test_disallows_custom_attributes_on_browser in_transaction do - NewRelic::Agent.add_custom_attributes(:not => "allowed") + NewRelic::Agent.add_custom_attributes(:not => 'allowed') capture_js_data end @@ -184,7 +184,7 @@ def test_doesnt_block_agent_attributes_to_transaction_traces run_harvest - expected = {"http.statusCode" => 200} + expected = {'http.statusCode' => 200} assert_equal expected, single_transaction_trace_posted.agent_attributes end @@ -193,13 +193,13 @@ def test_doesnt_block_agent_attributes_to_errors assert_raises(RuntimeError) do in_transaction do |txn| txn.http_response_code = 500 - raise "O_o" + raise 'O_o' end end run_harvest - expected = {"http.statusCode" => 500} + expected = {'http.statusCode' => 500} assert_equal expected, single_error_posted.agent_attributes end @@ -225,7 +225,7 @@ def test_doesnt_block_intrinsic_attributes_on_errors assert_raises(RuntimeError) do in_transaction do |txn| txn.distributed_tracer.is_cross_app_caller = true - raise "O_o" + raise 'O_o' end end @@ -240,10 +240,10 @@ def test_doesnt_block_intrinsic_attributes_on_errors end def test_blocks_log_capture - Logger.new(StringIO.new()).fatal("Oops") + Logger.new(StringIO.new()).fatal('Oops') run_harvest - assert_empty $collector.calls_for("log_event_data") + assert_empty $collector.calls_for('log_event_data') end end diff --git a/test/multiverse/suites/httpclient/Envfile b/test/multiverse/suites/httpclient/Envfile index 85b9156858..4ba6c67670 100644 --- a/test/multiverse/suites/httpclient/Envfile +++ b/test/multiverse/suites/httpclient/Envfile @@ -5,12 +5,7 @@ instrumentation_methods :chain, :prepend HTTPCLIENT_VERSIONS = [ [nil, 2.4], - ['2.8.3', 2.4], - ['2.6.0', 2.4, 3.0], - ['2.5.3', 2.4, 3.0], - ['2.4.0', 2.4, 3.0], - ['2.3.4', 2.4, 3.0], - ['2.2.0', 2.4, 3.0] + ['2.8.3', 2.4] ] def gem_list(httpclient_version = nil) diff --git a/test/multiverse/suites/httpclient/httpclient_test.rb b/test/multiverse/suites/httpclient/httpclient_test.rb index 3806a4b976..6facfd22e1 100644 --- a/test/multiverse/suites/httpclient/httpclient_test.rb +++ b/test/multiverse/suites/httpclient/httpclient_test.rb @@ -2,15 +2,15 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -require "httpclient" -require "newrelic_rpm" -require "http_client_test_cases" +require 'httpclient' +require 'newrelic_rpm' +require 'http_client_test_cases' class HTTPClientTest < Minitest::Test include HttpClientTestCases def client_name - "HTTPClient" + 'HTTPClient' end def timeout_error_class @@ -35,15 +35,15 @@ def head_response end def post_response - HTTPClient.post(default_url, :body => "") + HTTPClient.post(default_url, :body => '') end def put_response - HTTPClient.put(default_url, :body => "") + HTTPClient.put(default_url, :body => '') end def delete_response - HTTPClient.delete(default_url, :body => "") + HTTPClient.delete(default_url, :body => '') end def request_instance @@ -84,6 +84,6 @@ def new_push(request) last_node = find_last_transaction_node() - assert_equal("External/localhost/HTTPClient/GET", last_node.metric_name) + assert_equal('External/localhost/HTTPClient/GET', last_node.metric_name) end end diff --git a/test/multiverse/suites/httprb/httprb_test.rb b/test/multiverse/suites/httprb/httprb_test.rb index 7cd131550c..f0950790e6 100644 --- a/test/multiverse/suites/httprb/httprb_test.rb +++ b/test/multiverse/suites/httprb/httprb_test.rb @@ -2,15 +2,15 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -require "http" -require "newrelic_rpm" -require "http_client_test_cases" +require 'http' +require 'newrelic_rpm' +require 'http_client_test_cases' class HTTPTest < Minitest::Test include HttpClientTestCases def client_name - "http.rb" + 'http.rb' end def is_unsupported_1x? @@ -30,15 +30,15 @@ def head_response end def post_response - HTTP.post(default_url, :body => "") + HTTP.post(default_url, :body => '') end def put_response - HTTP.put(default_url, :body => "") + HTTP.put(default_url, :body => '') end def delete_response - HTTP.delete(default_url, :body => "") + HTTP.delete(default_url, :body => '') end # NOTE, some versions of HTTPrb gem implements body with @@ -70,7 +70,7 @@ def response_instance(headers = {}) version: '1.1', headers: headers, body: '', - request: HTTP::Request.new(uri: "http://newrelic.com", verb: :get) + request: HTTP::Request.new(uri: 'http://newrelic.com', verb: :get) } httprb_resp = is_unsupported_1x? ? HTTP::Response.new(*options.values) : HTTP::Response.new(options) diff --git a/test/multiverse/suites/infinite_tracing/infinite_tracing_test.rb b/test/multiverse/suites/infinite_tracing/infinite_tracing_test.rb index f6d4eb3447..ee3133222d 100644 --- a/test/multiverse/suites/infinite_tracing/infinite_tracing_test.rb +++ b/test/multiverse/suites/infinite_tracing/infinite_tracing_test.rb @@ -22,5 +22,5 @@ def self.load_test_files(pattern) end else - puts "Skipping tests in #{File.basename(__FILE__)} because Infinite Tracing is not configured to load" if ENV["VERBOSE_TEST_OUTPUT"] + puts "Skipping tests in #{File.basename(__FILE__)} because Infinite Tracing is not configured to load" if ENV['VERBOSE_TEST_OUTPUT'] end diff --git a/test/multiverse/suites/logger/logger_instrumentation_test.rb b/test/multiverse/suites/logger/logger_instrumentation_test.rb index c42990664c..3c1c5c84dd 100644 --- a/test/multiverse/suites/logger/logger_instrumentation_test.rb +++ b/test/multiverse/suites/logger/logger_instrumentation_test.rb @@ -34,7 +34,7 @@ def teardown LEVELS.each do |(name, level)| # logger#debug("message") define_method("test_records_#{name}") do - @logger.send(name, "A message") + @logger.send(name, 'A message') assert_equal(1, @written.string.lines.count) assert_match(/#{name.upcase}.*A message/, @written.string) @@ -42,8 +42,8 @@ def teardown end define_method("test_records_multiple_calls_#{name}") do - @logger.send(name, "A message") - @logger.send(name, "Another") + @logger.send(name, 'A message') + @logger.send(name, 'Another') assert_equal(2, @written.string.lines.count) assert_match(/#{name.upcase}.*A message/, @written.string) @@ -63,7 +63,7 @@ def teardown # logger#debug { "message" } define_method("test_records_with_block#{name}") do @logger.send(name) do - "A message" + 'A message' end assert_equal(1, @written.string.lines.count) @@ -73,7 +73,7 @@ def teardown # logger#log(Logger::DEBUG, "message") define_method("test_records_by_log_method_#{name}") do - @logger.log(level, "A message") + @logger.log(level, 'A message') assert_equal(1, @written.string.lines.count) assert_match(/#{name.upcase}.*A message/, @written.string) @@ -82,7 +82,7 @@ def teardown # logger#log(Logger::DEBUG} { "message" } define_method("test_records_by_log_method_with_block_#{name}") do - @logger.log(level) { "A message" } + @logger.log(level) { 'A message' } assert_equal(1, @written.string.lines.count) assert_match(/#{name.upcase}.*A message/, @written.string) @@ -91,7 +91,7 @@ def teardown # logger#log(Logger::DEBUG, "message", "progname") define_method("test_records_by_log_method_plus_progname_#{name}") do - @logger.log(level, "A message", "progname") + @logger.log(level, 'A message', 'progname') assert_equal(1, @written.string.lines.count) assert_match(/#{name.upcase}.*progname.*A message/, @written.string) @@ -100,7 +100,7 @@ def teardown define_method("test_decorates_message_when_enabled_#{name}") do with_config(:'application_logging.local_decorating.enabled' => true) do - @logger.log(level) { "A message" } + @logger.log(level) { 'A message' } assert_includes @written.string, 'NR-LINKING' end @@ -108,7 +108,7 @@ def teardown define_method("test_does_not_decorate_message_when_disabled_#{name}") do with_config(:'application_logging.local_decorating.enabled' => false) do - @logger.log(level) { "A message" } + @logger.log(level) { 'A message' } refute_includes @written.string, 'NR-LINKING' end @@ -124,40 +124,40 @@ def test_still_skips_levels end def test_unknown - @logger.unknown("A message") + @logger.unknown('A message') assert_equal(1, @written.string.lines.count) assert_match(/ANY.*A message/, @written.string) - assert_logging_instrumentation("ANY") + assert_logging_instrumentation('ANY') end def test_really_high_level - @logger.log(1_000_000, "A message") + @logger.log(1_000_000, 'A message') assert_equal(1, @written.string.lines.count) assert_match(/ANY.*A message/, @written.string) - assert_logging_instrumentation("ANY") + assert_logging_instrumentation('ANY') end def test_really_high_level_with_progname - @logger.log(1_000_000, "A message", "progname") + @logger.log(1_000_000, 'A message', 'progname') assert_equal(1, @written.string.lines.count) assert_match(/ANY.*progname.*A message/, @written.string) - assert_logging_instrumentation("ANY") + assert_logging_instrumentation('ANY') end def test_nil_severity - @logger.log(nil, "A message", "progname") + @logger.log(nil, 'A message', 'progname') assert_equal(1, @written.string.lines.count) assert_match(/ANY.*progname.*A message/, @written.string) - assert_logging_instrumentation("ANY") + assert_logging_instrumentation('ANY') end def test_skips_when_set @logger.mark_skip_instrumenting - @logger.log(1_000_000, "A message", "progname") + @logger.log(1_000_000, 'A message', 'progname') assert_equal(1, @written.string.lines.count) assert_match(/ANY.*progname.*A message/, @written.string) @@ -191,23 +191,23 @@ def test_dont_modify_frozen_logger NewRelic::Agent::Instrumentation::Logger.mark_skip_instrumenting(@logger) NewRelic::Agent::Instrumentation::Logger.clear_skip_instrumenting(@logger) - refute @logger.instance_variable_defined?(:@skip_instrumenting), "instance variable should not be defined" + refute @logger.instance_variable_defined?(:@skip_instrumenting), 'instance variable should not be defined' end def assert_logging_instrumentation(level, count = 1) # We count on Logger calls but actually write metrics on harvest to # minimize impact in the hot path _, logs = NewRelic::Agent.agent.log_event_aggregator.harvest! - logs_at_level = logs.select { |log| log.last["level"] == level } + logs_at_level = logs.select { |log| log.last['level'] == level } assert_equal count, logs_at_level.count assert_metrics_recorded_exclusive({ - "Logging/lines" => {:call_count => count}, + 'Logging/lines' => {:call_count => count}, "Logging/lines/#{level}" => {:call_count => count}, - "Logging/Forwarding/Dropped" => {}, - "Supportability/Logging/Forwarding/Seen" => {}, - "Supportability/Logging/Forwarding/Sent" => {} + 'Logging/Forwarding/Dropped' => {}, + 'Supportability/Logging/Forwarding/Seen' => {}, + 'Supportability/Logging/Forwarding/Sent' => {} }, :ignore_filter => %r{^Supportability/API/}) end diff --git a/test/multiverse/suites/memcache/dalli_test.rb b/test/multiverse/suites/memcache/dalli_test.rb index 8e7a3aecdd..d98f61564d 100644 --- a/test/multiverse/suites/memcache/dalli_test.rb +++ b/test/multiverse/suites/memcache/dalli_test.rb @@ -2,7 +2,7 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -require "./memcache_test_cases" +require './memcache_test_cases' if defined?(Dalli) @@ -21,7 +21,7 @@ def setup end def simulate_error - Dalli::Client.any_instance.stubs("perform").raises(simulated_error_class, "No server available") + Dalli::Client.any_instance.stubs('perform').raises(simulated_error_class, 'No server available') key = set_key_for_testcase @cache.get(key) end @@ -76,7 +76,7 @@ def test_assign_instance_to_when_exception_raised segment = mock('datastore_segment') segment.expects(:set_instance_info).with('unknown', 'unknown') server = DALLI_SERVER_PROTOCOL.new('/tmp/jonanfs.sock') - server.stubs(:hostname).raises("oops") + server.stubs(:hostname).raises('oops') DalliTracerHelper.assign_instance_to(segment, server) end diff --git a/test/multiverse/suites/memcache/memcache_client_test.rb b/test/multiverse/suites/memcache/memcache_client_test.rb index e77cbf013b..ebd6108392 100644 --- a/test/multiverse/suites/memcache/memcache_client_test.rb +++ b/test/multiverse/suites/memcache/memcache_client_test.rb @@ -2,7 +2,7 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -require "./memcache_test_cases" +require './memcache_test_cases' if defined?(MemCache) class MemcacheTest < Minitest::Test @@ -12,19 +12,19 @@ def setup @cache = MemCache.new("#{memcached_host}:11211") end - if MemCache::VERSION <= "1.5.0" + if MemCache::VERSION <= '1.5.0' undef_method :test_append_in_web, :test_prepend_in_web, :test_replace_in_web, :test_append_in_background, :test_prepend_in_background, :test_replace_in_background end - if MemCache::VERSION <= "1.7.0" + if MemCache::VERSION <= '1.7.0' undef_method :test_cas_in_web, :test_cas_in_background end def simulate_error - MemCache.any_instance.stubs("with_server").raises(simulated_error_class, "No server available") - MemCache.any_instance.stubs("request_setup").raises(simulated_error_class, "No server available") + MemCache.any_instance.stubs('with_server').raises(simulated_error_class, 'No server available') + MemCache.any_instance.stubs('request_setup').raises(simulated_error_class, 'No server available') key = set_key_for_testcase @cache.get(key) end diff --git a/test/multiverse/suites/memcache/memcache_test_cases.rb b/test/multiverse/suites/memcache/memcache_test_cases.rb index 1ad202ccec..b789e91b59 100644 --- a/test/multiverse/suites/memcache/memcache_test_cases.rb +++ b/test/multiverse/suites/memcache/memcache_test_cases.rb @@ -20,7 +20,7 @@ def randomized_key end end - def set_key_for_testcase(value = "value") + def set_key_for_testcase(value = 'value') randomized_key.tap do |key| @cache.set(key, value) NewRelic::Agent.drop_buffered_data @@ -29,22 +29,22 @@ def set_key_for_testcase(value = "value") def expected_web_metrics(command) [ - "Datastore/all", - "Datastore/Memcached/all", + 'Datastore/all', + 'Datastore/Memcached/all', "Datastore/operation/Memcached/#{command}", - "Datastore/allWeb", - "Datastore/Memcached/allWeb", + 'Datastore/allWeb', + 'Datastore/Memcached/allWeb', ["Datastore/operation/Memcached/#{command}", "Controller/#{self.class}/action"] ] end def expected_bg_metrics(command) [ - "Datastore/all", - "Datastore/Memcached/all", + 'Datastore/all', + 'Datastore/Memcached/all', "Datastore/operation/Memcached/#{command}", - "Datastore/allOther", - "Datastore/Memcached/allOther", + 'Datastore/allOther', + 'Datastore/Memcached/allOther', ["Datastore/operation/Memcached/#{command}", "OtherTransaction/Background/#{self.class}/bg_task"] ] end @@ -111,7 +111,7 @@ def test_set_in_web expected_metrics = expected_web_metrics(:set) in_web_transaction("Controller/#{self.class}/action") do - @cache.set(randomized_key, "value") + @cache.set(randomized_key, 'value') end assert_memcache_metrics_recorded expected_metrics @@ -121,7 +121,7 @@ def test_add_in_web expected_metrics = expected_web_metrics(:add) in_web_transaction("Controller/#{self.class}/action") do - @cache.add(randomized_key, "value") + @cache.add(randomized_key, 'value') end assert_memcache_metrics_recorded expected_metrics @@ -143,7 +143,7 @@ def test_incr_in_web expected_metrics = expected_web_metrics(:incr) in_web_transaction("Controller/#{self.class}/action") do - @cache.incr("incr_test", 0) + @cache.incr('incr_test', 0) end assert_memcache_metrics_recorded expected_metrics @@ -153,7 +153,7 @@ def test_decr_in_web expected_metrics = expected_web_metrics(:decr) in_web_transaction("Controller/#{self.class}/action") do - @cache.decr("decr_test", 1) + @cache.decr('decr_test', 1) end assert_memcache_metrics_recorded expected_metrics @@ -236,7 +236,7 @@ def test_set_in_background expected_metrics = expected_bg_metrics(:set) in_background_transaction("OtherTransaction/Background/#{self.class}/bg_task") do - @cache.set(randomized_key, "value") + @cache.set(randomized_key, 'value') end assert_memcache_metrics_recorded expected_metrics @@ -246,7 +246,7 @@ def test_add_in_background expected_metrics = expected_bg_metrics(:add) in_background_transaction("OtherTransaction/Background/#{self.class}/bg_task") do - @cache.add(randomized_key, "value") + @cache.add(randomized_key, 'value') end assert_memcache_metrics_recorded expected_metrics @@ -268,7 +268,7 @@ def test_incr_in_background expected_metrics = expected_bg_metrics(:incr) in_background_transaction("OtherTransaction/Background/#{self.class}/bg_task") do - @cache.incr("incr_test", 0) + @cache.incr('incr_test', 0) end assert_memcache_metrics_recorded expected_metrics @@ -278,7 +278,7 @@ def test_decr_in_background expected_metrics = expected_bg_metrics(:decr) in_background_transaction("OtherTransaction/Background/#{self.class}/bg_task") do - @cache.decr("decr_test", 0) + @cache.decr('decr_test', 0) end assert_memcache_metrics_recorded expected_metrics diff --git a/test/multiverse/suites/memcache/memcached_test.rb b/test/multiverse/suites/memcache/memcached_test.rb index 7c3d1f3e80..f7636d53a3 100644 --- a/test/multiverse/suites/memcache/memcached_test.rb +++ b/test/multiverse/suites/memcache/memcached_test.rb @@ -2,7 +2,7 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -require "./memcache_test_cases" +require './memcache_test_cases' if defined?(Memcached) class MemcachedTest < Minitest::Test @@ -13,7 +13,7 @@ def setup end def simulate_error - Memcached.any_instance.stubs("check_return_code").raises(simulated_error_class, "No server available") + Memcached.any_instance.stubs('check_return_code').raises(simulated_error_class, 'No server available') key = set_key_for_testcase @cache.get(key) end diff --git a/test/multiverse/suites/mongo/Envfile b/test/multiverse/suites/mongo/Envfile index 0600710f9d..35666715fb 100644 --- a/test/multiverse/suites/mongo/Envfile +++ b/test/multiverse/suites/mongo/Envfile @@ -19,20 +19,11 @@ end MONGO_VERSIONS_RUBY26 = ['2.17.0'] # Mongo versions to test with Ruby 2.5+ -MONGO_VERSIONS_RUBY25 = ['2.15.1', - '2.14.0', - '2.12.0'] +MONGO_VERSIONS_RUBY25 = ['2.15.1', '2.12.0'] # TODO: MAJOR VERSION - Stop testing mongo versions below 2.5.0 # Mongo versions to test with CRubies below 2.5.0 -MONGO_VERSIONS_OLDER_RUBIES = ['2.9.0', - '2.7.0', - '2.5.0', - '2.4.0', - '2.1.0', - '2.0.0', - '1.9.2', - '1.8.6'] +MONGO_VERSIONS_OLDER_RUBIES = ['2.9.0', '2.4.0'] # The highest Mongo server version to test 1.x gems against MAX_SERVER_VERSION_FOR_1X_GEMS = 2.6 diff --git a/test/multiverse/suites/mongo/helpers/mongo_helpers.rb b/test/multiverse/suites/mongo/helpers/mongo_helpers.rb index 6c9ebdfa39..bee769f0f6 100644 --- a/test/multiverse/suites/mongo/helpers/mongo_helpers.rb +++ b/test/multiverse/suites/mongo/helpers/mongo_helpers.rb @@ -5,7 +5,7 @@ module NewRelic module MongoHelpers def mongo_logger - if ENV["VERBOSE"] + if ENV['VERBOSE'] Mongo::Logger.Logger else filename = File.join(`pwd`.chomp, 'log', 'mongo_test.log') diff --git a/test/multiverse/suites/mongo/helpers/mongo_operation_tests.rb b/test/multiverse/suites/mongo/helpers/mongo_operation_tests.rb index 1a58e17fa9..368e4bbca2 100644 --- a/test/multiverse/suites/mongo/helpers/mongo_operation_tests.rb +++ b/test/multiverse/suites/mongo/helpers/mongo_operation_tests.rb @@ -117,9 +117,9 @@ def test_records_metrics_for_count def test_records_metrics_for_group begin in_transaction do - @collection.group({:key => "name", + @collection.group({:key => 'name', :initial => {:count => 0}, - :reduce => "function(k,v) { v.count += 1; }"}) + :reduce => 'function(k,v) { v.count += 1; }'}) end rescue Mongo::OperationFailure # We get occasional group failures, but should still record metrics @@ -338,23 +338,23 @@ def test_collstats end def test_web_scoped_metrics - in_web_transaction("webby") do + in_web_transaction('webby') do @collection.insert(@tribble) end metric = statement_metric(:insert) - assert_metrics_recorded([[metric, "webby"]]) + assert_metrics_recorded([[metric, 'webby']]) end def test_background_scoped_metrics - in_background_transaction("backed-up") do + in_background_transaction('backed-up') do @collection.insert(@tribble) end metric = statement_metric(:insert) - assert_metrics_recorded([[metric, "backed-up"]]) + assert_metrics_recorded([[metric, 'backed-up']]) end def test_notices_nosql @@ -539,7 +539,7 @@ def unique_field_name end def ensure_collection_exists - @collection.insert(:junk => "data") + @collection.insert(:junk => 'data') NewRelic::Agent.drop_buffered_data end @@ -552,6 +552,6 @@ def server_is_2_6_or_later? def statement_metric(action) metrics = build_test_metrics(action) - metrics.find { |m| m.start_with?("Datastore/statement") } + metrics.find { |m| m.start_with?('Datastore/statement') } end end diff --git a/test/multiverse/suites/mongo/helpers/mongo_server.rb b/test/multiverse/suites/mongo/helpers/mongo_server.rb index d9faca98f4..a5e9613b87 100644 --- a/test/multiverse/suites/mongo/helpers/mongo_server.rb +++ b/test/multiverse/suites/mongo/helpers/mongo_server.rb @@ -27,7 +27,7 @@ def self.count(type = :all) end def self.tmp_directory - ENV["MULTIVERSE_TMP"] || File.join(gem_root, 'tmp') + ENV['MULTIVERSE_TMP'] || File.join(gem_root, 'tmp') end def self.port_lock_directory @@ -53,7 +53,7 @@ def ping end def pingable? - ping == {"ok" => 1.0} + ping == {'ok' => 1.0} end def make_directories @@ -136,12 +136,12 @@ def mongod_path def startup_command pid_file = "--pidfilepath #{pid_path}" log_file = "--logpath #{log_path} " - fork = "--fork" + fork = '--fork' dbpath = "--dbpath #{db_path}" port_flag = "--port #{self.port}" small_mongo = "--oplogSize 128#{smallfiles_switch}" - repl_set = "--replSet multiverse" + repl_set = '--replSet multiverse' base = "#{port_flag} #{fork} #{pid_file} #{log_file} #{small_mongo} #{dbpath}" diff --git a/test/multiverse/suites/mongo/helpers/mongo_server_test.rb b/test/multiverse/suites/mongo/helpers/mongo_server_test.rb index 6b93be98aa..f41c95655e 100644 --- a/test/multiverse/suites/mongo/helpers/mongo_server_test.rb +++ b/test/multiverse/suites/mongo/helpers/mongo_server_test.rb @@ -102,7 +102,7 @@ def test_stop_deletes_pid_file end def test_pingable_returns_true_if_ping_is_ok - ok_status = {"ok" => 1.0} + ok_status = {'ok' => 1.0} @server.stubs(:ping).returns(ok_status) assert_predicate @server, :pingable? @@ -158,7 +158,7 @@ def test_starting_a_server_creates_a_client def test_ping_returns_ok_for_started_server @server.start - ok_status = {"ok" => 1.0} + ok_status = {'ok' => 1.0} assert_equal ok_status, @server.ping end diff --git a/test/multiverse/suites/mongo/mongo2_instrumentation_test.rb b/test/multiverse/suites/mongo/mongo2_instrumentation_test.rb index 4583a558a0..22496bdbf2 100644 --- a/test/multiverse/suites/mongo/mongo2_instrumentation_test.rb +++ b/test/multiverse/suites/mongo/mongo2_instrumentation_test.rb @@ -27,7 +27,7 @@ class Mongo2InstrumentationTest < Minitest::Test def setup Mongo::Logger.logger = mongo_logger - @database_name = "multiverse" + @database_name = 'multiverse' @client = Mongo::Client.new( ["#{$mongo.host}:#{$mongo.port}"], database: @database_name @@ -89,7 +89,7 @@ def test_noticed_error_only_at_segment_when_command_fails in_transaction do |db_txn| begin txn = db_txn - @database.collection("bogus").drop + @database.collection('bogus').drop rescue Mongo::Error::OperationFailure => e # NOP -- allowing ONLY span to notice error end @@ -168,7 +168,7 @@ def test_records_metrics_for_update_one NewRelic::Agent.drop_buffered_data in_transaction do - @collection.update_one(@tribbles[0], "$set" => @tribbles[1]) + @collection.update_one(@tribbles[0], '$set' => @tribbles[1]) end metrics = build_test_metrics(:update, true) @@ -182,7 +182,7 @@ def test_records_metrics_for_update_many NewRelic::Agent.drop_buffered_data in_transaction do - @collection.update_many(@tribbles[0], "$set" => @tribbles[1]) + @collection.update_many(@tribbles[0], '$set' => @tribbles[1]) end metrics = build_test_metrics(:update, true) @@ -238,7 +238,7 @@ def test_records_metrics_for_find_one_and_update NewRelic::Agent.drop_buffered_data in_transaction do - @collection.find_one_and_update(@tribbles[0], "$set" => @tribbles[1]) + @collection.find_one_and_update(@tribbles[0], '$set' => @tribbles[1]) end metrics = build_test_metrics(:findAndModify, true) @@ -272,7 +272,7 @@ def test_records_metrics_for_count def test_records_metrics_for_aggregate in_transaction do @collection.aggregate([ - {'$group' => {'_id' => "name", "max" => {'$max' => "$count"}}}, + {'$group' => {'_id' => 'name', 'max' => {'$max' => '$count'}}}, {'$match' => {'max' => {'$gte' => 1}}} ]).to_a end @@ -286,7 +286,7 @@ def test_records_metrics_for_aggregate def test_aggregate_pipeline_obfuscated_by_default in_transaction do @collection.aggregate([ - {'$group' => {'_id' => "name", "max" => {'$max' => "$count"}}}, + {'$group' => {'_id' => 'name', 'max' => {'$max' => '$count'}}}, {'$match' => {'max' => {'$gte' => 1}}} ]).to_a end @@ -296,25 +296,25 @@ def test_aggregate_pipeline_obfuscated_by_default node = find_node_with_name(sample, metric) expected = [ - {"$group" => {"_id" => "?", "max" => {"$max" => "?"}}}, - {"$match" => {"max" => {"$gte" => "?"}}} + {'$group' => {'_id' => '?', 'max' => {'$max' => '?'}}}, + {'$match' => {'max' => {'$gte' => '?'}}} ] - assert_equal expected, node[:statement]["pipeline"] + assert_equal expected, node[:statement]['pipeline'] end def test_filter_obfuscated_by_default in_transaction do - @collection.find("name" => "Wes Mantooth", "count" => {"$gte" => 1}).to_a + @collection.find('name' => 'Wes Mantooth', 'count' => {'$gte' => 1}).to_a end sample = last_transaction_trace metric = "Datastore/statement/MongoDB/#{@collection_name}/find" node = find_node_with_name(sample, metric) - expected = {"name" => "?", "count" => {"$gte" => "?"}} + expected = {'name' => '?', 'count' => {'$gte' => '?'}} - assert_equal expected, node[:statement]["filter"] + assert_equal expected, node[:statement]['filter'] end def test_batched_queries @@ -323,28 +323,28 @@ def test_batched_queries end NewRelic::Agent.drop_buffered_data - in_transaction("test_txn") do + in_transaction('test_txn') do @collection.find(:active => true).batch_size(10).to_a end expected = { - "test_txn" => {:call_count => 1}, - "OtherTransactionTotalTime" => {:call_count => 1}, - "OtherTransactionTotalTime/test_txn" => {:call_count => 1}, - ["Datastore/statement/MongoDB/#{@collection_name}/find", "test_txn"] => {:call_count => 1}, + 'test_txn' => {:call_count => 1}, + 'OtherTransactionTotalTime' => {:call_count => 1}, + 'OtherTransactionTotalTime/test_txn' => {:call_count => 1}, + ["Datastore/statement/MongoDB/#{@collection_name}/find", 'test_txn'] => {:call_count => 1}, "Datastore/statement/MongoDB/#{@collection_name}/find" => {:call_count => 1}, - ["Datastore/statement/MongoDB/#{@collection_name}/getMore", "test_txn"] => {:call_count => 2}, + ["Datastore/statement/MongoDB/#{@collection_name}/getMore", 'test_txn'] => {:call_count => 2}, "Datastore/statement/MongoDB/#{@collection_name}/getMore" => {:call_count => 2}, - "Datastore/operation/MongoDB/find" => {:call_count => 1}, - "Datastore/operation/MongoDB/getMore" => {:call_count => 2}, + 'Datastore/operation/MongoDB/find' => {:call_count => 1}, + 'Datastore/operation/MongoDB/getMore' => {:call_count => 2}, "Datastore/instance/MongoDB/#{mongo_host}/27017" => {:call_count => 3}, - "Datastore/MongoDB/allWeb" => {:call_count => 3}, - "Datastore/MongoDB/all" => {:call_count => 3}, - "Datastore/allWeb" => {:call_count => 3}, - "Datastore/all" => {:call_count => 3}, - "Supportability/API/drop_buffered_data" => {:call_count => 1}, - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all" => {:call_count => 1}, - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb" => {:call_count => 1} + 'Datastore/MongoDB/allWeb' => {:call_count => 3}, + 'Datastore/MongoDB/all' => {:call_count => 3}, + 'Datastore/allWeb' => {:call_count => 3}, + 'Datastore/all' => {:call_count => 3}, + 'Supportability/API/drop_buffered_data' => {:call_count => 1}, + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/all' => {:call_count => 1}, + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb' => {:call_count => 1} } assert_metrics_recorded_exclusive(expected, @@ -356,7 +356,7 @@ def test_batched_queries_have_node_per_query @collection.insert_one(:name => "test-#{i}", :active => true) end NewRelic::Agent.drop_buffered_data - in_transaction("webby") do + in_transaction('webby') do @collection.find(:active => true).batch_size(10).to_a end @@ -369,16 +369,16 @@ def test_batched_queries_have_node_per_query trace = last_transaction_trace actual = [] trace.each_node do |n| - actual << n.metric_name if n.metric_name.start_with?("Datastore/statement/MongoDB") + actual << n.metric_name if n.metric_name.start_with?('Datastore/statement/MongoDB') end assert_equal expected, actual end def test_trace_nodes_have_instance_attributes - @collection.insert_one(:name => "test", :active => true) + @collection.insert_one(:name => 'test', :active => true) NewRelic::Agent.drop_buffered_data - in_transaction("webby") do + in_transaction('webby') do @collection.find(:active => true).to_a end @@ -402,23 +402,23 @@ def test_drop_collection end def test_web_scoped_metrics - in_web_transaction("webby") do + in_web_transaction('webby') do @collection.insert_one(@tribbles.first) end metric = statement_metric(:insert) - assert_metrics_recorded([[metric, "webby"]]) + assert_metrics_recorded([[metric, 'webby']]) end def test_background_scoped_metrics - in_background_transaction("backed-up") do + in_background_transaction('backed-up') do @collection.insert_one(@tribbles.first) end metric = statement_metric(:insert) - assert_metrics_recorded([[metric, "backed-up"]]) + assert_metrics_recorded([[metric, 'backed-up']]) end def test_notices_nosql @@ -573,7 +573,7 @@ def test_other_requests_do_not_record_all_web_metric def statement_metric(action) metrics = build_test_metrics(action, true) - metrics.find { |m| m.start_with?("Datastore/statement") } + metrics.find { |m| m.start_with?('Datastore/statement') } end def assert_mongo_operation(expected_value, query) diff --git a/test/multiverse/suites/mongo/mongo_connection_test.rb b/test/multiverse/suites/mongo/mongo_connection_test.rb index a1172efd4b..ef66ab0042 100644 --- a/test/multiverse/suites/mongo/mongo_connection_test.rb +++ b/test/multiverse/suites/mongo/mongo_connection_test.rb @@ -20,7 +20,7 @@ class NewRelic::Agent::Instrumentation::MongoConnectionTest def setup @client = Mongo::Connection.new($mongo.host, $mongo.port) - @database_name = "multiverse" + @database_name = 'multiverse' @database = @client.db(@database_name) @collection_name = "tribbles-#{fake_guid(16)}" @collection = @database.collection(@collection_name) diff --git a/test/multiverse/suites/mongo/mongo_instrumentation_test.rb b/test/multiverse/suites/mongo/mongo_instrumentation_test.rb index fb94c9c4ba..5bf29a1f03 100644 --- a/test/multiverse/suites/mongo/mongo_instrumentation_test.rb +++ b/test/multiverse/suites/mongo/mongo_instrumentation_test.rb @@ -22,7 +22,7 @@ class NewRelic::Agent::Instrumentation::MongoInstrumentationTest < Minitest::Tes def setup @client = Mongo::MongoClient.new($mongo.host, $mongo.port, logger: mongo_logger) - @database_name = "multiverse" + @database_name = 'multiverse' @database = @client.db(@database_name) @collection_name = "tribbles-#{fake_guid(16)}" @collection = @database.collection(@collection_name) @@ -34,7 +34,7 @@ def setup end def test_noticed_error_at_segment_and_txn_when_violating_unique_constraints - expected_error_class = "Mongo::OperationFailure" + expected_error_class = 'Mongo::OperationFailure' txn = nil begin in_transaction do |db_txn| @@ -51,7 +51,7 @@ def test_noticed_error_at_segment_and_txn_when_violating_unique_constraints end def test_noticed_error_only_at_segment_when_violating_unique_constraints - expected_error_class = "Mongo::OperationFailure" + expected_error_class = 'Mongo::OperationFailure' txn = nil in_transaction do |db_txn| begin diff --git a/test/multiverse/suites/mongo/mongo_unsupported_version_test.rb b/test/multiverse/suites/mongo/mongo_unsupported_version_test.rb index 2cb20f9a5b..52d3231a65 100644 --- a/test/multiverse/suites/mongo/mongo_unsupported_version_test.rb +++ b/test/multiverse/suites/mongo/mongo_unsupported_version_test.rb @@ -14,7 +14,7 @@ class NewRelic::Agent::Instrumentation::MongoInstrumentationTest < Minitest::Tes include NewRelic::MongoHelpers def setup - @database_name = "multiverse" + @database_name = 'multiverse' @collection_name = "tribbles-#{fake_guid(16)}" @tribble = {'name' => 'soterios johnson'} @@ -31,7 +31,7 @@ def teardown def test_records_metrics_for_insert insert_to_collection - assert_metrics_not_recorded(["Datastore/all", "Datastore/allWeb", "Datastore/allOther"]) + assert_metrics_not_recorded(['Datastore/all', 'Datastore/allWeb', 'Datastore/allOther']) end # API changes between 1.x and 2.x that we need to work around to make diff --git a/test/multiverse/suites/net_http/net_http_test.rb b/test/multiverse/suites/net_http/net_http_test.rb index 5eb220765e..f27cb78e3e 100644 --- a/test/multiverse/suites/net_http/net_http_test.rb +++ b/test/multiverse/suites/net_http/net_http_test.rb @@ -2,7 +2,7 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -require "net_http_test_cases" +require 'net_http_test_cases' class NetHttpTest < Minitest::Test include NetHttpTestCases diff --git a/test/multiverse/suites/padrino/padrino_test.rb b/test/multiverse/suites/padrino/padrino_test.rb index 6143babd26..330b40cf6c 100644 --- a/test/multiverse/suites/padrino/padrino_test.rb +++ b/test/multiverse/suites/padrino/padrino_test.rb @@ -11,11 +11,11 @@ class PadrinoTestApp < Padrino::Application register Padrino::Helpers get '/user/login' do - "please log in" + 'please log in' end get(/\/regex.*/) do - "with extra regexes please!" + 'with extra regexes please!' end end @@ -52,8 +52,8 @@ def test_basic_route assert_equal 'please log in', last_response.body assert_metrics_recorded([ - "Controller/Sinatra/PadrinoTestApp/GET user/login", - "Apdex/Sinatra/PadrinoTestApp/GET user/login" + 'Controller/Sinatra/PadrinoTestApp/GET user/login', + 'Apdex/Sinatra/PadrinoTestApp/GET user/login' ]) end @@ -61,11 +61,11 @@ def test_regex_route get('/regexes') assert_equal 200, last_response.status - assert_equal "with extra regexes please!", last_response.body + assert_equal 'with extra regexes please!', last_response.body assert_metrics_recorded([ - "Controller/Sinatra/PadrinoTestApp/GET regex.*", - "Apdex/Sinatra/PadrinoTestApp/GET regex.*" + 'Controller/Sinatra/PadrinoTestApp/GET regex.*', + 'Apdex/Sinatra/PadrinoTestApp/GET regex.*' ]) end end diff --git a/test/multiverse/suites/rack/example_app.rb b/test/multiverse/suites/rack/example_app.rb index 7526975bbc..215f3234e8 100644 --- a/test/multiverse/suites/rack/example_app.rb +++ b/test/multiverse/suites/rack/example_app.rb @@ -132,7 +132,7 @@ def call(env) if req.params['override-content-type'] content_type = req.params['override-content-type'] - headers.update("Content-Type" => content_type) + headers.update('Content-Type' => content_type) end [status, headers, body] diff --git a/test/multiverse/suites/rack/nested_non_rack_app_test.rb b/test/multiverse/suites/rack/nested_non_rack_app_test.rb index cc957c0130..f8232e0ab1 100644 --- a/test/multiverse/suites/rack/nested_non_rack_app_test.rb +++ b/test/multiverse/suites/rack/nested_non_rack_app_test.rb @@ -45,20 +45,20 @@ def test_outermost_middleware_contributes_to_middleware_all_if_txn_name_is_non_r assert_metrics_recorded_exclusive( [ - "Apdex", - "ApdexAll", - "Apdex/NestedNonRackAppTest::RailsishApp/inner", - "Controller/NestedNonRackAppTest::RailsishApp/inner", - "HttpDispatcher", - "WebTransactionTotalTime", - "WebTransactionTotalTime/Controller/NestedNonRackAppTest::RailsishApp/inner", - "Middleware/all", - "Middleware/Rack/NestedNonRackAppTest::ExampleMiddleware/call", - ["Middleware/Rack/NestedNonRackAppTest::ExampleMiddleware/call", "Controller/NestedNonRackAppTest::RailsishApp/inner"], - "Nested/Controller/NestedNonRackAppTest::RailsishApp/inner", - ["Nested/Controller/NestedNonRackAppTest::RailsishApp/inner", "Controller/NestedNonRackAppTest::RailsishApp/inner"], - "Nested/Controller/Rack/NestedNonRackAppTest::RailsishApp/call", - ["Nested/Controller/Rack/NestedNonRackAppTest::RailsishApp/call", "Controller/NestedNonRackAppTest::RailsishApp/inner"], + 'Apdex', + 'ApdexAll', + 'Apdex/NestedNonRackAppTest::RailsishApp/inner', + 'Controller/NestedNonRackAppTest::RailsishApp/inner', + 'HttpDispatcher', + 'WebTransactionTotalTime', + 'WebTransactionTotalTime/Controller/NestedNonRackAppTest::RailsishApp/inner', + 'Middleware/all', + 'Middleware/Rack/NestedNonRackAppTest::ExampleMiddleware/call', + ['Middleware/Rack/NestedNonRackAppTest::ExampleMiddleware/call', 'Controller/NestedNonRackAppTest::RailsishApp/inner'], + 'Nested/Controller/NestedNonRackAppTest::RailsishApp/inner', + ['Nested/Controller/NestedNonRackAppTest::RailsishApp/inner', 'Controller/NestedNonRackAppTest::RailsishApp/inner'], + 'Nested/Controller/Rack/NestedNonRackAppTest::RailsishApp/call', + ['Nested/Controller/Rack/NestedNonRackAppTest::RailsishApp/call', 'Controller/NestedNonRackAppTest::RailsishApp/inner'], 'DurationByCaller/Unknown/Unknown/Unknown/HTTP/all', 'DurationByCaller/Unknown/Unknown/Unknown/HTTP/allWeb' ], diff --git a/test/multiverse/suites/rack/puma_rack_builder_test.rb b/test/multiverse/suites/rack/puma_rack_builder_test.rb index b3bca06e35..25770472d0 100644 --- a/test/multiverse/suites/rack/puma_rack_builder_test.rb +++ b/test/multiverse/suites/rack/puma_rack_builder_test.rb @@ -64,22 +64,22 @@ def test_puma_rack_builder_is_auto_instrumented assert_metrics_recorded_exclusive( [ - "Apdex", - "ApdexAll", - "HttpDispatcher", - "Middleware/all", - "Apdex/Rack/PumaRackBuilderTest::ExampleApp/call", - "Controller/Rack/PumaRackBuilderTest::ExampleApp/call", - "Middleware/Rack/PumaRackBuilderTest::MiddlewareOne/call", - "Middleware/Rack/PumaRackBuilderTest::MiddlewareTwo/call", - "Nested/Controller/Rack/PumaRackBuilderTest::ExampleApp/call", - "WebTransactionTotalTime", - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all", - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb", - "WebTransactionTotalTime/Controller/Rack/PumaRackBuilderTest::ExampleApp/call", - ["Middleware/Rack/PumaRackBuilderTest::MiddlewareOne/call", "Controller/Rack/PumaRackBuilderTest::ExampleApp/call"], - ["Middleware/Rack/PumaRackBuilderTest::MiddlewareTwo/call", "Controller/Rack/PumaRackBuilderTest::ExampleApp/call"], - ["Nested/Controller/Rack/PumaRackBuilderTest::ExampleApp/call", "Controller/Rack/PumaRackBuilderTest::ExampleApp/call"] + 'Apdex', + 'ApdexAll', + 'HttpDispatcher', + 'Middleware/all', + 'Apdex/Rack/PumaRackBuilderTest::ExampleApp/call', + 'Controller/Rack/PumaRackBuilderTest::ExampleApp/call', + 'Middleware/Rack/PumaRackBuilderTest::MiddlewareOne/call', + 'Middleware/Rack/PumaRackBuilderTest::MiddlewareTwo/call', + 'Nested/Controller/Rack/PumaRackBuilderTest::ExampleApp/call', + 'WebTransactionTotalTime', + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/all', + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb', + 'WebTransactionTotalTime/Controller/Rack/PumaRackBuilderTest::ExampleApp/call', + ['Middleware/Rack/PumaRackBuilderTest::MiddlewareOne/call', 'Controller/Rack/PumaRackBuilderTest::ExampleApp/call'], + ['Middleware/Rack/PumaRackBuilderTest::MiddlewareTwo/call', 'Controller/Rack/PumaRackBuilderTest::ExampleApp/call'], + ['Nested/Controller/Rack/PumaRackBuilderTest::ExampleApp/call', 'Controller/Rack/PumaRackBuilderTest::ExampleApp/call'] ], :ignore_filter => /^(Supportability|RubyVM|Memory|CPU|Logging)|(\/Rack\/Proc\/)/ ) diff --git a/test/multiverse/suites/rack/rack_auto_instrumentation_test.rb b/test/multiverse/suites/rack/rack_auto_instrumentation_test.rb index 28cb35878c..c042c36654 100644 --- a/test/multiverse/suites/rack/rack_auto_instrumentation_test.rb +++ b/test/multiverse/suites/rack/rack_auto_instrumentation_test.rb @@ -69,18 +69,18 @@ def test_non_agent_middlewares_do_not_record_metrics_if_disabled_by_config assert_metrics_recorded_exclusive( [ - "Apdex", - "ApdexAll", - "HttpDispatcher", - "Middleware/all", - "Apdex/Middleware/Rack/NewRelic::Rack::AgentHooks/call", - "Controller/Middleware/Rack/NewRelic::Rack::AgentHooks/call", - "Middleware/Rack/NewRelic::Rack::BrowserMonitoring/call", - "Middleware/Rack/NewRelic::Rack::AgentHooks/call", - "WebTransactionTotalTime", - "WebTransactionTotalTime/Controller/Middleware/Rack/NewRelic::Rack::AgentHooks/call", - ["Middleware/Rack/NewRelic::Rack::AgentHooks/call", "Controller/Middleware/Rack/NewRelic::Rack::AgentHooks/call"], - ["Middleware/Rack/NewRelic::Rack::BrowserMonitoring/call", "Controller/Middleware/Rack/NewRelic::Rack::AgentHooks/call"], + 'Apdex', + 'ApdexAll', + 'HttpDispatcher', + 'Middleware/all', + 'Apdex/Middleware/Rack/NewRelic::Rack::AgentHooks/call', + 'Controller/Middleware/Rack/NewRelic::Rack::AgentHooks/call', + 'Middleware/Rack/NewRelic::Rack::BrowserMonitoring/call', + 'Middleware/Rack/NewRelic::Rack::AgentHooks/call', + 'WebTransactionTotalTime', + 'WebTransactionTotalTime/Controller/Middleware/Rack/NewRelic::Rack::AgentHooks/call', + ['Middleware/Rack/NewRelic::Rack::AgentHooks/call', 'Controller/Middleware/Rack/NewRelic::Rack::AgentHooks/call'], + ['Middleware/Rack/NewRelic::Rack::BrowserMonitoring/call', 'Controller/Middleware/Rack/NewRelic::Rack::AgentHooks/call'], 'DurationByCaller/Unknown/Unknown/Unknown/HTTP/all', 'Supportability/API/recording_web_transaction?', 'DurationByCaller/Unknown/Unknown/Unknown/HTTP/allWeb' @@ -95,27 +95,27 @@ def test_middlewares_record_metrics assert_metrics_recorded_exclusive( [ - "Apdex", - "ApdexAll", - "HttpDispatcher", - "Middleware/all", - "Apdex/Rack/ExampleApp/call", - "Controller/Rack/ExampleApp/call", - "Middleware/Rack/MiddlewareOne/call", - "Middleware/Rack/MiddlewareTwo/call", - "Middleware/Rack/MiddlewareThree/call", - "Middleware/Rack/NewRelic::Rack::BrowserMonitoring/call", - "Middleware/Rack/NewRelic::Rack::AgentHooks/call", - "Nested/Controller/Rack/ExampleApp/call", - "Supportability/API/browser_timing_header", - "WebTransactionTotalTime", - "WebTransactionTotalTime/Controller/Rack/ExampleApp/call", - ["Middleware/Rack/NewRelic::Rack::BrowserMonitoring/call", "Controller/Rack/ExampleApp/call"], - ["Middleware/Rack/NewRelic::Rack::AgentHooks/call", "Controller/Rack/ExampleApp/call"], - ["Middleware/Rack/MiddlewareOne/call", "Controller/Rack/ExampleApp/call"], - ["Middleware/Rack/MiddlewareTwo/call", "Controller/Rack/ExampleApp/call"], - ["Middleware/Rack/MiddlewareThree/call", "Controller/Rack/ExampleApp/call"], - ["Nested/Controller/Rack/ExampleApp/call", "Controller/Rack/ExampleApp/call"], + 'Apdex', + 'ApdexAll', + 'HttpDispatcher', + 'Middleware/all', + 'Apdex/Rack/ExampleApp/call', + 'Controller/Rack/ExampleApp/call', + 'Middleware/Rack/MiddlewareOne/call', + 'Middleware/Rack/MiddlewareTwo/call', + 'Middleware/Rack/MiddlewareThree/call', + 'Middleware/Rack/NewRelic::Rack::BrowserMonitoring/call', + 'Middleware/Rack/NewRelic::Rack::AgentHooks/call', + 'Nested/Controller/Rack/ExampleApp/call', + 'Supportability/API/browser_timing_header', + 'WebTransactionTotalTime', + 'WebTransactionTotalTime/Controller/Rack/ExampleApp/call', + ['Middleware/Rack/NewRelic::Rack::BrowserMonitoring/call', 'Controller/Rack/ExampleApp/call'], + ['Middleware/Rack/NewRelic::Rack::AgentHooks/call', 'Controller/Rack/ExampleApp/call'], + ['Middleware/Rack/MiddlewareOne/call', 'Controller/Rack/ExampleApp/call'], + ['Middleware/Rack/MiddlewareTwo/call', 'Controller/Rack/ExampleApp/call'], + ['Middleware/Rack/MiddlewareThree/call', 'Controller/Rack/ExampleApp/call'], + ['Nested/Controller/Rack/ExampleApp/call', 'Controller/Rack/ExampleApp/call'], 'DurationByCaller/Unknown/Unknown/Unknown/HTTP/all', 'Supportability/API/recording_web_transaction?', 'DurationByCaller/Unknown/Unknown/Unknown/HTTP/allWeb' @@ -139,18 +139,18 @@ def test_middleware_that_returns_early_records_middleware_rollup_metric assert_metrics_recorded_exclusive( [ - "Apdex", - "ApdexAll", - "HttpDispatcher", - "Middleware/all", - "Apdex/Middleware/Rack/MiddlewareTwo/call", - "Controller/Middleware/Rack/MiddlewareTwo/call", - "Middleware/Rack/MiddlewareOne/call", - "Middleware/Rack/MiddlewareTwo/call", - "WebTransactionTotalTime", - "WebTransactionTotalTime/Controller/Middleware/Rack/MiddlewareTwo/call", - ["Middleware/Rack/MiddlewareOne/call", "Controller/Middleware/Rack/MiddlewareTwo/call"], - ["Middleware/Rack/MiddlewareTwo/call", "Controller/Middleware/Rack/MiddlewareTwo/call"], + 'Apdex', + 'ApdexAll', + 'HttpDispatcher', + 'Middleware/all', + 'Apdex/Middleware/Rack/MiddlewareTwo/call', + 'Controller/Middleware/Rack/MiddlewareTwo/call', + 'Middleware/Rack/MiddlewareOne/call', + 'Middleware/Rack/MiddlewareTwo/call', + 'WebTransactionTotalTime', + 'WebTransactionTotalTime/Controller/Middleware/Rack/MiddlewareTwo/call', + ['Middleware/Rack/MiddlewareOne/call', 'Controller/Middleware/Rack/MiddlewareTwo/call'], + ['Middleware/Rack/MiddlewareTwo/call', 'Controller/Middleware/Rack/MiddlewareTwo/call'], 'DurationByCaller/Unknown/Unknown/Unknown/HTTP/all', 'DurationByCaller/Unknown/Unknown/Unknown/HTTP/allWeb' ], diff --git a/test/multiverse/suites/rack/rack_parameter_filtering_test.rb b/test/multiverse/suites/rack/rack_parameter_filtering_test.rb index 355f6d265d..4cc496f1e6 100644 --- a/test/multiverse/suites/rack/rack_parameter_filtering_test.rb +++ b/test/multiverse/suites/rack/rack_parameter_filtering_test.rb @@ -20,14 +20,14 @@ def app def test_file_upload_params_are_filtered with_config(:capture_params => true) do params = { - :title => "blah", + :title => 'blah', :file => Rack::Test::UploadedFile.new(__FILE__, 'text/plain') } post('/', params) expected = { - "request.parameters.title" => "blah", - "request.parameters.file" => "[FILE]" + 'request.parameters.title' => 'blah', + 'request.parameters.file' => '[FILE]' } assert_equal expected, last_transaction_trace_request_params @@ -36,12 +36,12 @@ def test_file_upload_params_are_filtered def test_apply_filters_returns_params_when_rails_is_not_present with_config(:capture_params => true) do - params = {"name" => "name", "password" => "mypass"} + params = {'name' => 'name', 'password' => 'mypass'} post('/', params) expected = { - "request.parameters.name" => "name", - "request.parameters.password" => "mypass" + 'request.parameters.name' => 'name', + 'request.parameters.password' => 'mypass' } assert_equal expected, last_transaction_trace_request_params diff --git a/test/multiverse/suites/rack/url_map_test.rb b/test/multiverse/suites/rack/url_map_test.rb index ca9f66284a..fe93245181 100644 --- a/test/multiverse/suites/rack/url_map_test.rb +++ b/test/multiverse/suites/rack/url_map_test.rb @@ -159,9 +159,9 @@ def nested_controller_metric # revisit how we verify that def get(path) env = { - "REQUEST_METHOD" => "GET", - "PATH_INFO" => path, - "SCRIPT_NAME" => "" + 'REQUEST_METHOD' => 'GET', + 'PATH_INFO' => path, + 'SCRIPT_NAME' => '' } app.call(env) diff --git a/test/multiverse/suites/rails/action_cable_test.rb b/test/multiverse/suites/rails/action_cable_test.rb index 92ca434621..dca6b7524a 100644 --- a/test/multiverse/suites/rails/action_cable_test.rb +++ b/test/multiverse/suites/rails/action_cable_test.rb @@ -40,13 +40,13 @@ def test_action(data) end def boom(data) - raise StandardError.new("Boom!") + raise StandardError.new('Boom!') end end setup_and_teardown_agent do @connection = TestConnection.new - @channel = TestChannel.new(@connection, "{id: 1}") + @channel = TestChannel.new(@connection, '{id: 1}') end def test_creates_trace @@ -73,9 +73,9 @@ def test_action_with_error_is_noticed_by_agent error_trace = last_traced_error - assert_equal "StandardError", error_trace.exception_class_name - assert_equal "Boom!", error_trace.message - assert_equal "Controller/ActionCable/ActionCableTest::TestChannel/boom", error_trace.path + assert_equal 'StandardError', error_trace.exception_class_name + assert_equal 'Boom!', error_trace.message + assert_equal 'Controller/ActionCable/ActionCableTest::TestChannel/boom', error_trace.path end end diff --git a/test/multiverse/suites/rails/action_controller_live_rum_test.rb b/test/multiverse/suites/rails/action_controller_live_rum_test.rb index b7ae1aef55..948032e26e 100644 --- a/test/multiverse/suites/rails/action_controller_live_rum_test.rb +++ b/test/multiverse/suites/rails/action_controller_live_rum_test.rb @@ -7,7 +7,7 @@ if defined?(ActionController::Live) class UndeadController < ApplicationController - RESPONSE_BODY = "Brains!" + RESPONSE_BODY = 'Brains!' def brains render(:inline => RESPONSE_BODY) @@ -25,9 +25,9 @@ class LiveController < UndeadController class ActionControllerLiveRumTest < ActionDispatch::IntegrationTest include MultiverseHelpers - JS_LOADER = "JS LOADER IN DA HOUSE" + JS_LOADER = 'JS LOADER IN DA HOUSE' - setup_and_teardown_agent(:js_agent_loader => JS_LOADER, :beacon => "beacon", :browser_key => "key") + setup_and_teardown_agent(:js_agent_loader => JS_LOADER, :beacon => 'beacon', :browser_key => 'key') def test_rum_instrumentation_when_not_streaming get('/undead/brains') diff --git a/test/multiverse/suites/rails/action_controller_other_test.rb b/test/multiverse/suites/rails/action_controller_other_test.rb index 378d310ea2..3c03ac4d35 100644 --- a/test/multiverse/suites/rails/action_controller_other_test.rb +++ b/test/multiverse/suites/rails/action_controller_other_test.rb @@ -9,12 +9,12 @@ class DataController < ApplicationController # send_file def send_test_file - send_file(Rails.root + "../../../../README.md") + send_file(Rails.root + '../../../../README.md') end # send_data def send_test_data - send_data("wow its a adata") + send_data('wow its a adata') end # halted_callback @@ -23,7 +23,7 @@ def halt_my_callback; end # redirect_to def do_a_redirect - redirect_to("http://foo.bar/") + redirect_to('http://foo.bar/') end # unpermitted_parameters @@ -59,7 +59,7 @@ def test_halted_callback # depending on the rails version, the value will be either # "do_a_redirect" OR :do_a_redirect OR ":do_a_redirect" - assert_includes(tt_node.params[:filter].to_s, "do_a_redirect") + assert_includes(tt_node.params[:filter].to_s, 'do_a_redirect') assert_metrics_recorded(['Controller/data/halt_my_callback', 'Ruby/ActionController/halted_callback']) end @@ -108,5 +108,26 @@ def test_unpermitted_parameters assert_metrics_recorded(['Controller/data/not_allowed', segment_name]) end + + class TestClassActionController; end + def test_no_metric_naming_error + payloads = [ + {request: 'Not gonna respond to controller_class'}, + {request: Class.new do + def controller_class + 'not gonna respond to controller_path' + end + end}, + {context: {}}, + {context: {controller: TestClassActionController.name}}, + {}, + nil + ] + + payloads.each do |payload| + # make sure no error is raised + NewRelic::Agent::Instrumentation::ActionControllerOtherSubscriber.new.controller_name_for_metric(payload) + end + end end end diff --git a/test/multiverse/suites/rails/active_support_logger_test.rb b/test/multiverse/suites/rails/active_support_logger_test.rb index 1e26fa5a51..d0abc9d5dd 100644 --- a/test/multiverse/suites/rails/active_support_logger_test.rb +++ b/test/multiverse/suites/rails/active_support_logger_test.rb @@ -35,7 +35,7 @@ def test_logs_not_forwarded_by_broadcasted_logger # LogEventAggregator sees the log only once assert_equal 1, @aggregator.instance_variable_get(:@seen) - assert_equal({"DEBUG" => 1}, @aggregator.instance_variable_get(:@seen_by_severity)) + assert_equal({'DEBUG' => 1}, @aggregator.instance_variable_get(:@seen_by_severity)) end end end diff --git a/test/multiverse/suites/rails/activejob_test.rb b/test/multiverse/suites/rails/activejob_test.rb index 981eec28d9..5bc605d932 100644 --- a/test/multiverse/suites/rails/activejob_test.rb +++ b/test/multiverse/suites/rails/activejob_test.rb @@ -9,7 +9,7 @@ # ActiveJob is in Rails 4.2+, so make sure we're on an allowed version before # we try to load. -if Rails::VERSION::STRING >= "4.2.0" +if Rails::VERSION::STRING >= '4.2.0' require 'active_job' @@ -60,8 +60,8 @@ def after_teardown end end - ENQUEUE_PREFIX = "ActiveJob/Inline/Queue/Produce/Named" - PERFORM_PREFIX = "ActiveJob/Inline/Queue/Consume/Named" + ENQUEUE_PREFIX = 'ActiveJob/Inline/Queue/Produce/Named' + PERFORM_PREFIX = 'ActiveJob/Inline/Queue/Consume/Named' PERFORM_TRANSACTION_NAME = 'OtherTransaction/ActiveJob::Inline/MyJob/execute' PERFORM_TRANSACTION_ROLLUP = 'OtherTransaction/ActiveJob::Inline/all' @@ -165,7 +165,7 @@ def test_doesnt_nest_transactions_if_in_web end def test_doesnt_interfere_with_params_on_job - MyJobWithParams.perform_later("1", "2") + MyJobWithParams.perform_later('1', '2') assert_equal(%w[1 2], MyJobWithParams.last_params) end @@ -176,7 +176,7 @@ def test_captures_errors MyFailure.perform_later end - assert_metrics_recorded(["Errors/all"]) + assert_metrics_recorded(['Errors/all']) end end diff --git a/test/multiverse/suites/rails/bad_instrumentation_test.rb b/test/multiverse/suites/rails/bad_instrumentation_test.rb index 750cddd57a..c61cf77ae5 100644 --- a/test/multiverse/suites/rails/bad_instrumentation_test.rb +++ b/test/multiverse/suites/rails/bad_instrumentation_test.rb @@ -11,7 +11,7 @@ class BadInstrumentationController < ApplicationController # to fail. # https://newrelic.atlassian.net/browse/RUBY-1158 def failwhale - NewRelic::Agent::Tracer.start_segment(name: "Controller/BadInstrumentationController/failwhale") + NewRelic::Agent::Tracer.start_segment(name: 'Controller/BadInstrumentationController/failwhale') render(body: 'everything went great') end end diff --git a/test/multiverse/suites/rails/error_tracing_test.rb b/test/multiverse/suites/rails/error_tracing_test.rb index 3a866b2d11..3835127db4 100644 --- a/test/multiverse/suites/rails/error_tracing_test.rb +++ b/test/multiverse/suites/rails/error_tracing_test.rb @@ -45,19 +45,19 @@ def server_ignored_error end def frozen_error - e = RuntimeError.new("frozen errors make a refreshing treat on a hot summer day") + e = RuntimeError.new('frozen errors make a refreshing treat on a hot summer day') e.freeze raise e end def string_noticed_error - NewRelic::Agent.notice_error("trilobites died out millions of years ago") + NewRelic::Agent.notice_error('trilobites died out millions of years ago') render(body: 'trilobites') end def noticed_error NewRelic::Agent.notice_error(RuntimeError.new('this error should be noticed')) - render(body: "Shoulda noticed an error") + render(body: 'Shoulda noticed an error') end def middleware_error @@ -70,12 +70,12 @@ def error_with_custom_params end def noticed_error_with_trace_only - NewRelic::Agent.notice_error("Raise the gates!", :trace_only => true) + NewRelic::Agent.notice_error('Raise the gates!', :trace_only => true) render(body: 'Runner 5') end def noticed_error_with_expected_error - NewRelic::Agent.notice_error("Raise the gates!", :expected => true) + NewRelic::Agent.notice_error('Raise the gates!', :expected => true) render(body: 'Runner 5') end end @@ -92,7 +92,7 @@ class ErrorsWithoutSSCTest < ActionDispatch::IntegrationTest # Let base class override this without moving where we start the agent def setup_collector_mocks - $collector.stub('connect', {"agent_run_id" => 666}, 200) + $collector.stub('connect', {'agent_run_id' => 666}, 200) end def last_error @@ -126,7 +126,7 @@ def test_should_capture_errors_raised_in_middleware_after_call def test_should_capture_request_uri_and_params get('/error/controller_error?eat=static') - assert_equal('/error/controller_error', attributes_for_single_error_posted("agentAttributes")["request.uri"]) + assert_equal('/error/controller_error', attributes_for_single_error_posted('agentAttributes')['request.uri']) expected_params = { 'request.parameters.eat' => 'static', @@ -170,15 +170,15 @@ def test_should_capture_noticed_error_in_controller def test_should_capture_frozen_errors get('/error/frozen_error') - assert_error_reported_once("frozen errors make a refreshing treat on a hot summer day", - "Controller/error/frozen_error") + assert_error_reported_once('frozen errors make a refreshing treat on a hot summer day', + 'Controller/error/frozen_error') end def test_should_capture_string_noticed_errors get('/error/string_noticed_error') - assert_error_reported_once("trilobites died out millions of years ago", - "Controller/error/string_noticed_error") + assert_error_reported_once('trilobites died out millions of years ago', + 'Controller/error/string_noticed_error') end # Important choice of controller_error, since this goes through both the @@ -315,8 +315,8 @@ def test_should_not_increment_metrics_on_expected_error_errors 'Errors/Controller/error/noticed_error_with_expected_error' ]) - assert_metrics_recorded("Apdex" => {:apdex_s => 1}) - assert_metrics_recorded(["ErrorsExpected/all"]) + assert_metrics_recorded('Apdex' => {:apdex_s => 1}) + assert_metrics_recorded(['ErrorsExpected/all']) end protected @@ -332,11 +332,11 @@ def errors_with_message(message) def assert_errors_reported(message, queued_count, total_count = queued_count, txn_name = nil, apdex_f = 1) expected = {:call_count => total_count} - assert_metrics_recorded("Errors/all" => expected) + assert_metrics_recorded('Errors/all' => expected) assert_metrics_recorded("Errors/#{txn_name}" => expected) if txn_name unless apdex_f.nil? - assert_metrics_recorded("Apdex" => {:apdex_f => apdex_f}) + assert_metrics_recorded('Apdex' => {:apdex_f => apdex_f}) end assert_equal(queued_count, @@ -352,12 +352,12 @@ def assert_error_reported_once(message, txn_name = nil, apdex_f = 1) class ErrorsWithSSCTest < ErrorsWithoutSSCTest def setup_collector_mocks $collector.stub('connect', { - "agent_run_id" => 1, - "agent_config" => { - "error_collector.ignore_classes" => ['NewRelic::TestHelpers::Exceptions::IgnoredError', 'NewRelic::TestHelpers::Exceptions::ServerIgnoredError'], - "error_collector.enabled" => true + 'agent_run_id' => 1, + 'agent_config' => { + 'error_collector.ignore_classes' => ['NewRelic::TestHelpers::Exceptions::IgnoredError', 'NewRelic::TestHelpers::Exceptions::ServerIgnoredError'], + 'error_collector.enabled' => true }, - "collect_errors" => true + 'collect_errors' => true }, 200) end diff --git a/test/multiverse/suites/rails/gc_instrumentation_test.rb b/test/multiverse/suites/rails/gc_instrumentation_test.rb index 193524da2b..63fb6619a6 100644 --- a/test/multiverse/suites/rails/gc_instrumentation_test.rb +++ b/test/multiverse/suites/rails/gc_instrumentation_test.rb @@ -15,14 +15,14 @@ def gc_action Timeout.timeout(5) do until ::GC.count > initial_gc_count - long_string = "01234567" * 100_000 + long_string = '01234567' * 100_000 long_string = nil - another_long_string = "01234567" * 100_000 + another_long_string = '01234567' * 100_000 another_long_string = nil end end rescue Timeout::Error - puts "Timed out waiting for GC..." + puts 'Timed out waiting for GC...' end render(body: 'ha') diff --git a/test/multiverse/suites/rails/ignore_test.rb b/test/multiverse/suites/rails/ignore_test.rb index 17c60a06e8..1e12e027ef 100644 --- a/test/multiverse/suites/rails/ignore_test.rb +++ b/test/multiverse/suites/rails/ignore_test.rb @@ -11,15 +11,15 @@ class IgnoredController < ApplicationController newrelic_ignore_apdex :only => :action_to_ignore_apdex def action_to_ignore - render(body: "Ignore this") + render(body: 'Ignore this') end def action_to_ignore_apdex - render(body: "This too") + render(body: 'This too') end def action_not_ignored - render(body: "Not this!") + render(body: 'Not this!') end end @@ -40,7 +40,7 @@ def bar(*args); end class IgnoredActionsTest < ActionDispatch::IntegrationTest include MultiverseHelpers - setup_and_teardown_agent(:cross_process_id => "boo", + setup_and_teardown_agent(:cross_process_id => 'boo', :encoding_key => "\0", :trusted_account_ids => [1]) @@ -58,8 +58,8 @@ def test_metric__ignore def test_metric__ignore_apdex get('/ignored/action_to_ignore_apdex') - assert_metrics_recorded(["Controller/ignored/action_to_ignore_apdex"]) - assert_metrics_not_recorded(["Apdex"]) + assert_metrics_recorded(['Controller/ignored/action_to_ignore_apdex']) + assert_metrics_not_recorded(['Apdex']) end def test_ignored_transaction_traces_dont_leak @@ -75,14 +75,14 @@ def test_should_not_write_cat_response_headers_for_ignored_transactions get('/ignored/action_to_ignore', headers: {'X-NewRelic-ID' => Base64.encode64('1#234')}) - refute @response.headers["X-NewRelic-App-Data"] + refute @response.headers['X-NewRelic-App-Data'] end def test_apdex_ignored_if_ignored_in_parent_class get('/child/foo') get('/child/bar') - assert_metrics_not_recorded("Apdex") + assert_metrics_not_recorded('Apdex') end def test_ignored_transaction_does_not_record_span_events diff --git a/test/multiverse/suites/rails/middlewares.rb b/test/multiverse/suites/rails/middlewares.rb index 6e9101f613..55e4a25ce4 100644 --- a/test/multiverse/suites/rails/middlewares.rb +++ b/test/multiverse/suites/rails/middlewares.rb @@ -11,10 +11,10 @@ def initialize(app, options = {}) def call(env) path = ::Rack::Request.new(env).path_info - raise "middleware error" if path.include?('/middleware_error/before') + raise 'middleware error' if path.include?('/middleware_error/before') result = @app.call(env) - raise "middleware error" if path.include?('/middleware_error/after') + raise 'middleware error' if path.include?('/middleware_error/after') result end diff --git a/test/multiverse/suites/rails/parameter_capture_test.rb b/test/multiverse/suites/rails/parameter_capture_test.rb index 5d6005033e..364dd84e85 100644 --- a/test/multiverse/suites/rails/parameter_capture_test.rb +++ b/test/multiverse/suites/rails/parameter_capture_test.rb @@ -53,7 +53,7 @@ def test_uri_on_traced_errors_never_contains_query_string_without_capture_params with_config(:capture_params => false) do get('/parameter_capture/error?other=1234&secret=4567') - assert_equal('/parameter_capture/error', attributes_for_single_error_posted("agentAttributes")["request.uri"]) + assert_equal('/parameter_capture/error', attributes_for_single_error_posted('agentAttributes')['request.uri']) end end @@ -61,7 +61,7 @@ def test_uri_on_traced_errors_never_contains_query_string_with_capture_params with_config(:capture_params => true) do get('/parameter_capture/error?other=1234&secret=4567') - assert_equal('/parameter_capture/error', attributes_for_single_error_posted("agentAttributes")["request.uri"]) + assert_equal('/parameter_capture/error', attributes_for_single_error_posted('agentAttributes')['request.uri']) end end @@ -74,7 +74,7 @@ def test_referrer_on_traced_errors_never_contains_query_string_without_capture_p headers: {'HTTP_REFERER' => '/foo/bar?other=123&secret=456'}) attributes = agent_attributes_for_single_error_posted - assert_equal('/foo/bar', attributes["request.headers.referer"]) + assert_equal('/foo/bar', attributes['request.headers.referer']) end end @@ -84,7 +84,7 @@ def test_referrer_on_traced_errors_never_contains_query_string_even_with_capture headers: {'HTTP_REFERER' => '/foo/bar?other=123&secret=456'}) attributes = agent_attributes_for_single_error_posted - assert_equal('/foo/bar', attributes["request.headers.referer"]) + assert_equal('/foo/bar', attributes['request.headers.referer']) end end @@ -205,7 +205,7 @@ def test_uri_on_traced_error_should_not_contain_query_string_with_capture_params with_config(:capture_params => false) do get('/parameter_capture/error?param1=value1¶m2=value2') - assert_equal('/parameter_capture/error', attributes_for_single_error_posted("agentAttributes")["request.uri"]) + assert_equal('/parameter_capture/error', attributes_for_single_error_posted('agentAttributes')['request.uri']) end end @@ -216,7 +216,7 @@ def test_uri_on_traced_error_should_not_contain_query_string_with_capture_params with_config(:capture_params => true) do get('/parameter_capture/error?param1=value1¶m2=value2') - assert_equal('/parameter_capture/error', attributes_for_single_error_posted("agentAttributes")["request.uri"]) + assert_equal('/parameter_capture/error', attributes_for_single_error_posted('agentAttributes')['request.uri']) end end @@ -244,8 +244,8 @@ def test_parameters_attached_to_transaction_events_if_enabled actual = agent_attributes_for_single_event_posted_without_ignored_attributes - expected = {"request.parameters.param1" => "value1", - "request.parameters.param2" => "value2"} + expected = {'request.parameters.param1' => 'value1', + 'request.parameters.param2' => 'value2'} assert_equal expected, actual end @@ -254,56 +254,56 @@ def test_request_and_response_attributes_recorded_as_agent_attributes get('/parameter_capture/transaction') expected = { - "response.headers.contentType" => "#{response.content_type}; charset=#{response.charset}", - "request.headers.contentLength" => request.content_length.to_i, - "request.headers.host" => request.host, - "request.headers.accept" => request.accept + 'response.headers.contentType' => "#{response.content_type}; charset=#{response.charset}", + 'request.headers.contentLength' => request.content_length.to_i, + 'request.headers.host' => request.host, + 'request.headers.accept' => request.accept } if request.content_type - expected["request.headers.contentType"] = request.content_type + expected['request.headers.contentType'] = request.content_type end # ActionController::IntegrationTest sets this header whereas ActionDispatch::IntegrationTest # does not. Since we test using both we need to conditionally expect content_length to be set. unless defined?(ActionDispatch::IntegrationTest) - expected["response.headers.contentLength"] = response.content_length + expected['response.headers.contentLength'] = response.content_length end actual = agent_attributes_for_single_event_posted_without_ignored_attributes - assert_equal request.request_method.to_s.upcase, actual["request.method"] - assert_includes actual["response.headers.contentType"], response.content_type - assert_includes actual["response.headers.contentType"], response.charset + assert_equal request.request_method.to_s.upcase, actual['request.method'] + assert_includes actual['response.headers.contentType'], response.content_type + assert_includes actual['response.headers.contentType'], response.charset unless defined?(ActionDispatch::IntegrationTest) - assert_equal actual["response.headers.contentLength"], response.content_length + assert_equal actual['response.headers.contentLength'], response.content_length end end def test_params_tts_should_be_filtered_when_serviced_by_rack_app - params = {"secret" => "shhhhhhh", "name" => "name"} + params = {'secret' => 'shhhhhhh', 'name' => 'name'} with_config(:capture_params => true) do post('/filtering_test/', params: params) end expected = { - "request.parameters.secret" => "[FILTERED]", - "request.parameters.name" => "name" + 'request.parameters.secret' => '[FILTERED]', + 'request.parameters.name' => 'name' } assert_equal expected, last_transaction_trace_request_params end def test_params_on_errors_should_be_filtered_when_serviced_by_rack_app - params = {"secret" => "shhhhhhh", "name" => "name"} + params = {'secret' => 'shhhhhhh', 'name' => 'name'} with_config(:capture_params => true) do post('/filtering_test?raise=1', params: params) expected = { - "request.parameters.secret" => "[FILTERED]", - "request.parameters.name" => "name", - "request.parameters.raise" => "1" + 'request.parameters.secret' => '[FILTERED]', + 'request.parameters.name' => 'name', + 'request.parameters.raise' => '1' } attributes = agent_attributes_for_single_error_posted @@ -314,12 +314,12 @@ def test_params_on_errors_should_be_filtered_when_serviced_by_rack_app end def test_parameter_filtering_should_not_mutate_argument - input = {"foo" => "bar", "secret" => "baz"} - env = {"action_dispatch.parameter_filter" => ["secret"]} + input = {'foo' => 'bar', 'secret' => 'baz'} + env = {'action_dispatch.parameter_filter' => ['secret']} filtered = NewRelic::Agent::ParameterFiltering.apply_filters(env, input) - assert_equal({"foo" => "bar", "secret" => "[FILTERED]"}, filtered) - assert_equal({"foo" => "bar", "secret" => "baz"}, input) + assert_equal({'foo' => 'bar', 'secret' => '[FILTERED]'}, filtered) + assert_equal({'foo' => 'bar', 'secret' => 'baz'}, input) end if defined?(Sinatra) @@ -327,14 +327,14 @@ def test_params_tts_should_be_filtered_when_serviced_by_sinatra_app with_config(:capture_params => true) do get('/sinatra_app/', params: { - "secret" => "shhhhhhh", - "name" => "name" + 'secret' => 'shhhhhhh', + 'name' => 'name' }) end expected = { - "request.parameters.secret" => "[FILTERED]", - "request.parameters.name" => "name" + 'request.parameters.secret' => '[FILTERED]', + 'request.parameters.name' => 'name' } assert_equal expected, last_transaction_trace_request_params @@ -344,14 +344,14 @@ def test_params_on_errors_should_be_filtered_when_serviced_by_sinatra_app with_config(:capture_params => true) do get('/sinatra_app?raise=1', params: { - "secret" => "shhhhhhh", - "name" => "name" + 'secret' => 'shhhhhhh', + 'name' => 'name' }) attributes = agent_attributes_for_single_error_posted - assert_equal "[FILTERED]", attributes["request.parameters.secret"] - assert_equal "name", attributes["request.parameters.name"] - assert_equal "1", attributes["request.parameters.raise"] + assert_equal '[FILTERED]', attributes['request.parameters.secret'] + assert_equal 'name', attributes['request.parameters.name'] + assert_equal '1', attributes['request.parameters.raise'] end end @@ -366,7 +366,7 @@ def test_file_upload_params_are_replaced_with_placeholder result = single_transaction_trace_posted - assert_equal "#", result.agent_attributes["request.parameters.file"] + assert_equal '#', result.agent_attributes['request.parameters.file'] end end end diff --git a/test/multiverse/suites/rails/queue_time_test.rb b/test/multiverse/suites/rails/queue_time_test.rb index 7e78d5ddd3..f95c607ad4 100644 --- a/test/multiverse/suites/rails/queue_time_test.rb +++ b/test/multiverse/suites/rails/queue_time_test.rb @@ -9,7 +9,7 @@ class QueueController < ApplicationController def queued respond_to do |format| - format.html { render(body: "Queued") } + format.html { render(body: 'Queued') } end end @@ -28,7 +28,7 @@ class QueueTimeTest < ActionDispatch::IntegrationTest include MultiverseHelpers - setup_and_teardown_agent(:beacon => "beacon", :browser_key => "key", :js_agent_loader => "loader") + setup_and_teardown_agent(:beacon => 'beacon', :browser_key => 'key', :js_agent_loader => 'loader') def test_should_track_queue_time_metric t0 = nr_freeze_process_time diff --git a/test/multiverse/suites/rails/rails3_app/app_rails3_plus.rb b/test/multiverse/suites/rails/rails3_app/app_rails3_plus.rb index ffbc616173..c23d51c5bb 100644 --- a/test/multiverse/suites/rails/rails3_app/app_rails3_plus.rb +++ b/test/multiverse/suites/rails/rails3_app/app_rails3_plus.rb @@ -56,9 +56,9 @@ class Application < Base class SinatraTestApp < Sinatra::Base get '/' do - raise "Intentional error" if params["raise"] + raise 'Intentional error' if params['raise'] - "SinatraTestApp#index" + 'SinatraTestApp#index' end end end @@ -66,23 +66,23 @@ class SinatraTestApp < Sinatra::Base class MyApp < Rails::Application # We need a secret token for session, cookies, etc. config.active_support.deprecation = :log - config.secret_token = "49837489qkuweoiuoqwehisuakshdjksadhaisdy78o34y138974xyqp9rmye8yrpiokeuioqwzyoiuxftoyqiuxrhm3iou1hrzmjk" + config.secret_token = '49837489qkuweoiuoqwehisuakshdjksadhaisdy78o34y138974xyqp9rmye8yrpiokeuioqwzyoiuxftoyqiuxrhm3iou1hrzmjk' config.eager_load = false config.filter_parameters += [:secret] config.secret_key_base = fake_guid(64) - if Rails::VERSION::STRING >= "7.0.0" + if Rails::VERSION::STRING >= '7.0.0' config.action_controller.default_protect_from_forgery = true end if config.respond_to?(:hosts) - config.hosts << "www.example.com" + config.hosts << 'www.example.com' end - initializer "install_error_middleware" do + initializer 'install_error_middleware' do config.middleware.use(ErrorMiddleware) end - initializer "install_middleware_by_name" do + initializer 'install_middleware_by_name' do config.middleware.use(NamedMiddleware) end - initializer "install_middleware_instance" do + initializer 'install_middleware_instance' do config.middleware.use(InstanceMiddleware.new) end end @@ -115,7 +115,7 @@ class ApplicationController < ActionController::Base # With the patch below we can write our tests using render :body but have # that converted to render :text for Rails versions that do not support # render :body. - if Rails::VERSION::STRING < "4.1.0" + if Rails::VERSION::STRING < '4.1.0' def render(*args) options = args.first if Hash === options && options.key?(:body) diff --git a/test/multiverse/suites/rails/request_statistics_test.rb b/test/multiverse/suites/rails/request_statistics_test.rb index 001fd0d6e1..e8adc862c5 100644 --- a/test/multiverse/suites/rails/request_statistics_test.rb +++ b/test/multiverse/suites/rails/request_statistics_test.rb @@ -192,7 +192,7 @@ def assert_encoding(encname, string) return unless string.respond_to?(:encoding) expected_encoding = Encoding.find(encname) or raise "no such encoding #{encname.dump}" - msg = "Expected encoding of %p to be %p, but it was %p" % + msg = 'Expected encoding of %p to be %p, but it was %p' % [string, expected_encoding, string.encoding] assert_equal(expected_encoding, string.encoding, msg) diff --git a/test/multiverse/suites/rails/transaction_ignoring_test.rb b/test/multiverse/suites/rails/transaction_ignoring_test.rb index fef13c3723..98a4be87fa 100644 --- a/test/multiverse/suites/rails/transaction_ignoring_test.rb +++ b/test/multiverse/suites/rails/transaction_ignoring_test.rb @@ -11,8 +11,8 @@ def run_transaction NewRelic::Agent.set_transaction_name(params[:txn_name]) NewRelic::Agent.notice_error(params[:error_msg]) if params[:error_msg] if params[:slow_sql] - NewRelic::Agent.instance.sql_sampler.notice_sql("select * from test", - "Database/test/select", + NewRelic::Agent.instance.sql_sampler.notice_sql('select * from test', + 'Database/test/select', nil, 1.5, state) end render(body: 'some stuff') diff --git a/test/multiverse/suites/rails/view_instrumentation_test.rb b/test/multiverse/suites/rails/view_instrumentation_test.rb index 3a734cf9e2..487293d503 100644 --- a/test/multiverse/suites/rails/view_instrumentation_test.rb +++ b/test/multiverse/suites/rails/view_instrumentation_test.rb @@ -9,29 +9,29 @@ class ViewsController < ApplicationController def template_render_with_3_partial_renders - render(String.new('index')) + render((+'index')) end def render_with_delays nr_freeze_process_time @delay = 1 - render(String.new('index')) + render((+'index')) end def deep_partial_render - render(String.new('deep_partial')) + render((+'deep_partial')) end def text_render - render(body: "Yay") + render(body: 'Yay') end def json_render - render(:json => {"a" => "b"}) + render(:json => {'a' => 'b'}) end def xml_render - render(:xml => {"a" => "b"}) + render(:xml => {'a' => 'b'}) end def js_render @@ -41,7 +41,7 @@ def js_render def file_render # The choice of filename is significant here: we want a dot in the filename # in order to expose an issue on Rails 2. - file = File.expand_path(File.join(File.dirname(__FILE__), "dummy.txt")) + file = File.expand_path(File.join(File.dirname(__FILE__), 'dummy.txt')) render(:file => file, :content_type => 'text/plain', :layout => false) end @@ -50,11 +50,11 @@ def nothing_render end def inline_render - render(:inline => "<% Time.now %>

<%= Time.now %>

") + render(:inline => '<% Time.now %>

<%= Time.now %>

') end def haml_render - render(String.new('haml_view')) + render((+'haml_view')) end def no_template @@ -79,7 +79,7 @@ def each end def raise_render - raise "this is an uncaught RuntimeError" + raise 'this is an uncaught RuntimeError' end end @@ -106,7 +106,7 @@ class ViewInstrumentationTest < ActionDispatch::IntegrationTest end def test_should_allow_uncaught_exception_to_propagate - get("/views/raise_render") + get('/views/raise_render') assert_equal 500, status end @@ -126,7 +126,7 @@ def test_should_have_3_nodes_with_the_correct_metric_name sample = last_transaction_trace partial_nodes = find_all_nodes_with_name_matching(sample, 'View/views/_a_partial.html.erb/Partial') - assert_equal 3, partial_nodes.size, "sanity check" + assert_equal 3, partial_nodes.size, 'sanity check' assert_equal ['View/views/_a_partial.html.erb/Partial'], partial_nodes.map(&:metric_name).uniq end @@ -136,7 +136,7 @@ def test_should_create_a_metric_for_the_rendered_inline_template sample = last_transaction_trace text_node = find_node_with_name(sample, 'View/inline template/Rendering') - assert text_node, "Failed to find a node named View/inline template/Rendering" + assert text_node, 'Failed to find a node named View/inline template/Rendering' assert_metrics_recorded('View/inline template/Rendering') end @@ -155,7 +155,7 @@ def test_should_create_a_metric_for_the_rendered_text sample = last_transaction_trace text_node = find_node_with_name(sample, 'View/text template/Rendering') - assert text_node, "Failed to find a node named View/text template/Rendering" + assert text_node, 'Failed to find a node named View/text template/Rendering' assert_metrics_recorded('View/text template/Rendering') end end @@ -166,7 +166,7 @@ def test_should_create_a_metric_for_the_rendered_haml_template sample = last_transaction_trace text_node = find_node_with_name(sample, 'View/views/haml_view.html.haml/Rendering') - assert text_node, "Failed to find a node named View/views/haml_view.html.haml/Rendering" + assert text_node, 'Failed to find a node named View/views/haml_view.html.haml/Rendering' assert_metrics_recorded('View/views/haml_view.html.haml/Rendering') end @@ -189,7 +189,7 @@ def test_should_create_a_proper_metric_when_we_render_a_collection get('/views/collection_render') sample = last_transaction_trace - assert find_node_with_name(sample, "View/foos/_foo.html.haml/Partial") + assert find_node_with_name(sample, 'View/foos/_foo.html.haml/Partial') end RENDERING_OPTIONS.each do |action| diff --git a/test/multiverse/suites/rails_prepend/newrelic_prepender/lib/newrelic_prepender.rb b/test/multiverse/suites/rails_prepend/newrelic_prepender/lib/newrelic_prepender.rb index 5c2b165409..1724b1c150 100644 --- a/test/multiverse/suites/rails_prepend/newrelic_prepender/lib/newrelic_prepender.rb +++ b/test/multiverse/suites/rails_prepend/newrelic_prepender/lib/newrelic_prepender.rb @@ -2,7 +2,7 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -require "newrelic_prepender/version" +require 'newrelic_prepender/version' module NewRelic module Prepender diff --git a/test/multiverse/suites/rails_prepend/newrelic_prepender/lib/newrelic_prepender/version.rb b/test/multiverse/suites/rails_prepend/newrelic_prepender/lib/newrelic_prepender/version.rb index d7c256b532..0ef674e8da 100644 --- a/test/multiverse/suites/rails_prepend/newrelic_prepender/lib/newrelic_prepender/version.rb +++ b/test/multiverse/suites/rails_prepend/newrelic_prepender/lib/newrelic_prepender/version.rb @@ -3,5 +3,5 @@ # frozen_string_literal: true module NewRelicPrepender - VERSION = "0.1.0" + VERSION = '0.1.0' end diff --git a/test/multiverse/suites/rails_prepend/newrelic_prepender/newrelic_prepender.gemspec b/test/multiverse/suites/rails_prepend/newrelic_prepender/newrelic_prepender.gemspec index 57692b4d28..19e9446c40 100644 --- a/test/multiverse/suites/rails_prepend/newrelic_prepender/newrelic_prepender.gemspec +++ b/test/multiverse/suites/rails_prepend/newrelic_prepender/newrelic_prepender.gemspec @@ -1,17 +1,17 @@ # frozen_string_literal: true -lib = File.expand_path("../lib", __FILE__) +lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) -require "newrelic_prepender/version" +require 'newrelic_prepender/version' Gem::Specification.new do |spec| - spec.name = "newrelic_prepender" + spec.name = 'newrelic_prepender' spec.version = NewRelicPrepender::VERSION - spec.authors = ["Kenichi Nakamura"] - spec.email = ["knakamura@newrelic.com"] + spec.authors = ['Kenichi Nakamura'] + spec.email = ['knakamura@newrelic.com'] spec.summary = 'test module for prepend metrics' spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end - spec.require_paths = ["lib"] + spec.require_paths = ['lib'] spec.metadata['rubygems_mfa_required'] = 'true' end diff --git a/test/multiverse/suites/rails_prepend/prepended_supportability_test.rb b/test/multiverse/suites/rails_prepend/prepended_supportability_test.rb index 3d6e90eecc..6d6745cb12 100644 --- a/test/multiverse/suites/rails_prepend/prepended_supportability_test.rb +++ b/test/multiverse/suites/rails_prepend/prepended_supportability_test.rb @@ -14,16 +14,16 @@ def test_action_view_prepended_metrics # haml prepends a module on ActionView::Base # - "Supportability/PrependedModules/ActionView::Base" => metric_values_for(value_for_haml_version), + 'Supportability/PrependedModules/ActionView::Base' => metric_values_for(value_for_haml_version), - "Supportability/PrependedModules/ActionView::Template" => metric_values_for(1), - "Supportability/PrependedModules/ActionView::Renderer" => metric_values_for(1) + 'Supportability/PrependedModules/ActionView::Template' => metric_values_for(1), + 'Supportability/PrependedModules/ActionView::Renderer' => metric_values_for(1) }) end def test_action_controller_prepended_metrics - metrics = ["Supportability/PrependedModules/ActionController::Base"] - metrics << "Supportability/PrependedModules/ActionController::API" if ::Rails::VERSION::MAJOR.to_i == 5 + metrics = ['Supportability/PrependedModules/ActionController::Base'] + metrics << 'Supportability/PrependedModules/ActionController::API' if ::Rails::VERSION::MAJOR.to_i == 5 assert_metrics_recorded(metrics.reduce({}) { |h, m| h[m] = metric_values_for(1); h }) end @@ -31,13 +31,13 @@ def test_action_controller_prepended_metrics if ::Rails::VERSION::MAJOR.to_i == 5 def test_action_cable_prepended_metrics assert_metrics_recorded({ - "Supportability/PrependedModules/ActionCable::Engine" => metric_values_for(1), - "Supportability/PrependedModules/ActionCable::RemoteConnections" => metric_values_for(1) + 'Supportability/PrependedModules/ActionCable::Engine' => metric_values_for(1), + 'Supportability/PrependedModules/ActionCable::RemoteConnections' => metric_values_for(1) }) end def test_active_job_prepended_metrics - assert_metrics_recorded({"Supportability/PrependedModules/ActiveJob::Base" => metric_values_for(1)}) + assert_metrics_recorded({'Supportability/PrependedModules/ActiveJob::Base' => metric_values_for(1)}) end end @@ -48,8 +48,8 @@ def test_active_record_prepended_metrics val += 1 if ::Rails::VERSION::MAJOR.to_i == 5 and ::Rails::VERSION::MINOR.to_i == 0 assert_metrics_recorded({ - "Supportability/PrependedModules/ActiveRecord::Base" => metric_values_for(1), - "Supportability/PrependedModules/ActiveRecord::Relation" => metric_values_for(val) + 'Supportability/PrependedModules/ActiveRecord::Base' => metric_values_for(1), + 'Supportability/PrependedModules/ActiveRecord::Relation' => metric_values_for(val) }) end diff --git a/test/multiverse/suites/rake/Rakefile b/test/multiverse/suites/rake/Rakefile index 265baded0c..3a1035dc5a 100644 --- a/test/multiverse/suites/rake/Rakefile +++ b/test/multiverse/suites/rake/Rakefile @@ -3,34 +3,34 @@ # frozen_string_literal: true Bundler.require -require "tasks/newrelic" +require 'tasks/newrelic' task :default => [:before, :during, :after] do - puts "default" + puts 'default' end task :before do - puts "before" + puts 'before' end task :during do - puts "during" + puts 'during' end task :after do - puts "after" + puts 'after' end task :untraced do - puts "untraced" + puts 'untraced' end task :argument, [:who, :where] => [] do - puts "argument" + puts 'argument' end task :boom do - raise "a legitimate issue with the proposal." + raise 'a legitimate issue with the proposal.' end task :tree => [:branch1, :branch2] @@ -46,19 +46,19 @@ namespace :named do task :before do a = NewRelic::Agent::Tracer.start_segment(name: 'custom_before') - puts "named:before" + puts 'named:before' a.finish end task :during do a = NewRelic::Agent::Tracer.start_segment(name: 'custom_during') - puts "named:during" + puts 'named:during' a.finish end task :after do a = NewRelic::Agent::Tracer.start_segment(name: 'custom_after') - puts "named:after" + puts 'named:after' a.finish end end diff --git a/test/multiverse/suites/rake/multitask_test.rb b/test/multiverse/suites/rake/multitask_test.rb index 9de4efb691..7b770b76a3 100644 --- a/test/multiverse/suites/rake/multitask_test.rb +++ b/test/multiverse/suites/rake/multitask_test.rb @@ -12,32 +12,32 @@ class MultiTaskTest < Minitest::Test setup_and_teardown_agent def test_generate_scoped_metrics_for_children_if_always_multitask_set - with_tasks_traced("named:all") do - run_rake("named:all --multitask") - - assert_metric_names_posted "OtherTransaction/Rake/invoke/named:all", - "OtherTransaction/Rake/all", - "OtherTransaction/all", - "Rake/execute/multitask", - "Rake/execute/named:before", - "Rake/execute/named:during", - "Rake/execute/named:after" + with_tasks_traced('named:all') do + run_rake('named:all --multitask') + + assert_metric_names_posted 'OtherTransaction/Rake/invoke/named:all', + 'OtherTransaction/Rake/all', + 'OtherTransaction/all', + 'Rake/execute/multitask', + 'Rake/execute/named:before', + 'Rake/execute/named:during', + 'Rake/execute/named:after' end end def test_generate_transaction_trace_with_multitask - with_tasks_traced("named:all") do - run_rake("named:all --multitask") - - expected_nodes = ["ROOT", - "OtherTransaction/Rake/invoke/named:all", - "Rake/execute/multitask", - "Rake/execute/named:before", - "custom_before", - "Rake/execute/named:during", - "custom_during", - "Rake/execute/named:after", - "custom_after"] + with_tasks_traced('named:all') do + run_rake('named:all --multitask') + + expected_nodes = ['ROOT', + 'OtherTransaction/Rake/invoke/named:all', + 'Rake/execute/multitask', + 'Rake/execute/named:before', + 'custom_before', + 'Rake/execute/named:during', + 'custom_during', + 'Rake/execute/named:after', + 'custom_after'] actual_nodes = single_transaction_trace_posted.tree.nodes.flatten # check to make sure all expected nodes are inside of actual diff --git a/test/multiverse/suites/rake/rake_test.rb b/test/multiverse/suites/rake/rake_test.rb index 8cc9b8fb47..5d877fd1e5 100644 --- a/test/multiverse/suites/rake/rake_test.rb +++ b/test/multiverse/suites/rake/rake_test.rb @@ -12,8 +12,8 @@ class RakeTest < Minitest::Test setup_and_teardown_agent def test_disabling_rake_instrumentation - with_environment("NEW_RELIC_INSTRUMENTATION_RAKE" => "disabled", - "NEW_RELIC_SYNC_STARTUP" => "true") do + with_environment('NEW_RELIC_INSTRUMENTATION_RAKE' => 'disabled', + 'NEW_RELIC_SYNC_STARTUP' => 'true') do run_rake end @@ -21,13 +21,13 @@ def test_disabling_rake_instrumentation end def test_doesnt_trace_by_default - run_rake("untraced") + run_rake('untraced') refute_any_rake_metrics end def test_doesnt_trace_with_an_empty_list - with_tasks_traced("") do + with_tasks_traced('') do run_rake refute_any_rake_metrics @@ -37,14 +37,14 @@ def test_doesnt_trace_with_an_empty_list def test_timeout_on_connect $collector.stub_wait('connect', 5) - with_environment("NEW_RELIC_RAKE_CONNECT_TIMEOUT" => "0", - "NEW_RELIC_LOG" => "stdout", - "NEW_RELIC_SYNC_STARTUP" => "true") do + with_environment('NEW_RELIC_RAKE_CONNECT_TIMEOUT' => '0', + 'NEW_RELIC_LOG' => 'stdout', + 'NEW_RELIC_SYNC_STARTUP' => 'true') do run_rake end refute_any_rake_metrics - assert_includes @output, "ERROR : NewRelic::Agent::AgentHelpers::Connect::WaitOnConnectTimeout: Agent was unable to connect" + assert_includes @output, 'ERROR : NewRelic::Agent::AgentHelpers::Connect::WaitOnConnectTimeout: Agent was unable to connect' end def test_records_transaction_metrics @@ -53,12 +53,12 @@ def test_records_transaction_metrics run_rake - assert_metric_names_posted "OtherTransaction/Rake/invoke/default", - "OtherTransaction/Rake/all", - "OtherTransaction/all", - "Rake/execute/before", - "Rake/execute/during", - "Rake/execute/after" + assert_metric_names_posted 'OtherTransaction/Rake/invoke/default', + 'OtherTransaction/Rake/all', + 'OtherTransaction/all', + 'Rake/execute/before', + 'Rake/execute/during', + 'Rake/execute/after' end def test_records_transaction_trace @@ -69,13 +69,13 @@ def test_records_transaction_trace trace = single_transaction_trace_posted - assert_equal "OtherTransaction/Rake/invoke/default", trace.metric_name + assert_equal 'OtherTransaction/Rake/invoke/default', trace.metric_name - expected = ["ROOT", - ["OtherTransaction/Rake/invoke/default", - ["Rake/execute/before"], - ["Rake/execute/during"], - ["Rake/execute/after"]]] + expected = ['ROOT', + ['OtherTransaction/Rake/invoke/default', + ['Rake/execute/before'], + ['Rake/execute/during'], + ['Rake/execute/after']]] assert_equal expected, trace.tree.nodes end @@ -88,142 +88,142 @@ def test_records_transaction_events event = single_event_posted[0] - assert_equal "OtherTransaction/Rake/invoke/default", event["name"] + assert_equal 'OtherTransaction/Rake/invoke/default', event['name'] end def test_records_namespaced_tasks - with_tasks_traced("named:all") do - run_rake("named:all") - - assert_metric_names_posted "OtherTransaction/Rake/invoke/named:all", - "OtherTransaction/Rake/all", - "OtherTransaction/all", - "Rake/execute/named:before", - "Rake/execute/named:during", - "Rake/execute/named:after" + with_tasks_traced('named:all') do + run_rake('named:all') + + assert_metric_names_posted 'OtherTransaction/Rake/invoke/named:all', + 'OtherTransaction/Rake/all', + 'OtherTransaction/all', + 'Rake/execute/named:before', + 'Rake/execute/named:during', + 'Rake/execute/named:after' end end def test_matches_tasks_by_regex - with_tasks_traced(".*before") do - run_rake("before named:before during") + with_tasks_traced('.*before') do + run_rake('before named:before during') - assert_metric_names_posted "OtherTransaction/Rake/invoke/before", - "OtherTransaction/Rake/invoke/named:before" + assert_metric_names_posted 'OtherTransaction/Rake/invoke/before', + 'OtherTransaction/Rake/invoke/named:before' - refute_metric_names_posted "OtherTransaction/Rake/invoke/during" + refute_metric_names_posted 'OtherTransaction/Rake/invoke/during' end end def test_records_tree_of_prereqs - with_tasks_traced("tree") do - run_rake("tree") - - assert_metric_names_posted "OtherTransaction/Rake/invoke/tree", - "OtherTransaction/Rake/all", - "OtherTransaction/all", - "Rake/execute/branch1", - "Rake/execute/branch1a", - "Rake/execute/branch1b", - "Rake/execute/branch2", - "Rake/execute/branch2a", - "Rake/execute/branch2b" + with_tasks_traced('tree') do + run_rake('tree') + + assert_metric_names_posted 'OtherTransaction/Rake/invoke/tree', + 'OtherTransaction/Rake/all', + 'OtherTransaction/all', + 'Rake/execute/branch1', + 'Rake/execute/branch1a', + 'Rake/execute/branch1b', + 'Rake/execute/branch2', + 'Rake/execute/branch2a', + 'Rake/execute/branch2b' end end def test_traced_task_as_prereq_doesnt_get_transaction - with_tasks_traced("default", "before") do + with_tasks_traced('default', 'before') do run_rake - assert_metric_names_posted "OtherTransaction/Rake/invoke/default", - "OtherTransaction/Rake/all", - "OtherTransaction/all", - "Rake/execute/before", - "Rake/execute/during", - "Rake/execute/after" + assert_metric_names_posted 'OtherTransaction/Rake/invoke/default', + 'OtherTransaction/Rake/all', + 'OtherTransaction/all', + 'Rake/execute/before', + 'Rake/execute/during', + 'Rake/execute/after' - refute_metric_names_posted "OtherTransaction/Rake/invoke/before" + refute_metric_names_posted 'OtherTransaction/Rake/invoke/before' end end def test_error_during_task - with_tasks_traced("boom") do - run_rake("boom", true) + with_tasks_traced('boom') do + run_rake('boom', true) - expected = "OtherTransaction/Rake/invoke/boom" + expected = 'OtherTransaction/Rake/invoke/boom' assert_equal expected, single_error_posted.path end end def test_captures_task_arguments - with_tasks_traced("argument") do - run_rake("argument[someone,somewhere,vigorously]") + with_tasks_traced('argument') do + run_rake('argument[someone,somewhere,vigorously]') attributes = single_transaction_trace_posted.agent_attributes - assert_equal "someone", attributes["job.rake.args.who"] - assert_equal "somewhere", attributes["job.rake.args.where"] - assert_equal "vigorously", attributes["job.rake.args.2"] + assert_equal 'someone', attributes['job.rake.args.who'] + assert_equal 'somewhere', attributes['job.rake.args.where'] + assert_equal 'vigorously', attributes['job.rake.args.2'] end end def test_captures_task_arguments_with_too_few - with_tasks_traced("argument") do - run_rake("argument[someone]") + with_tasks_traced('argument') do + run_rake('argument[someone]') attributes = single_transaction_trace_posted.agent_attributes - assert_equal "someone", attributes["job.rake.args.who"] + assert_equal 'someone', attributes['job.rake.args.who'] - refute_includes attributes, "job.rake.args.where" - refute_includes attributes, "job.rake.args.2" + refute_includes attributes, 'job.rake.args.where' + refute_includes attributes, 'job.rake.args.2' end end def test_doesnt_capture_task_arguments_if_disabled_by_agent_attributes - with_tasks_traced("argument") do + with_tasks_traced('argument') do without_attributes do - run_rake("argument[someone,somewhere,vigorously]") + run_rake('argument[someone,somewhere,vigorously]') attributes = single_transaction_trace_posted.agent_attributes - refute_includes attributes, "job.rake.args.who" - refute_includes attributes, "job.rake.args.where" - refute_includes attributes, "job.rake.args.2" + refute_includes attributes, 'job.rake.args.who' + refute_includes attributes, 'job.rake.args.where' + refute_includes attributes, 'job.rake.args.2' end end end def test_doesnt_capture_completely_empty_args - with_tasks_traced("default") do - run_rake("default") + with_tasks_traced('default') do + run_rake('default') attributes = single_transaction_trace_posted.agent_attributes - refute attributes.keys.any? { |key| key.start_with?("job.rake.args") } + refute attributes.keys.any? { |key| key.start_with?('job.rake.args') } end end def test_captures_command_line - with_tasks_traced("default", "argument") do - run_rake("argument[someone] default") + with_tasks_traced('default', 'argument') do + run_rake('argument[someone] default') attributes = single_transaction_trace_posted.agent_attributes - assert_includes attributes["job.rake.command"], "argument[someone]" - assert_includes attributes["job.rake.command"], "default" + assert_includes attributes['job.rake.command'], 'argument[someone]' + assert_includes attributes['job.rake.command'], 'default' end end def test_doesnt_capture_command_line_if_disabled_by_agent_attributes - with_tasks_traced("default", "argument") do + with_tasks_traced('default', 'argument') do without_attributes do - run_rake("argument[someone] default") + run_rake('argument[someone] default') attributes = single_transaction_trace_posted.agent_attributes - refute_includes attributes, "job.rake.command" + refute_includes attributes, 'job.rake.command' end end end diff --git a/test/multiverse/suites/rake/rake_test_helper.rb b/test/multiverse/suites/rake/rake_test_helper.rb index a6446f2e48..fe461a799f 100644 --- a/test/multiverse/suites/rake/rake_test_helper.rb +++ b/test/multiverse/suites/rake/rake_test_helper.rb @@ -18,7 +18,7 @@ def after_teardown end end - def run_rake(commands = "", allow_failure = false) + def run_rake(commands = '', allow_failure = false) full_command = "bundle exec rake #{commands} 2>&1" @output = `#{full_command}` @@ -29,15 +29,15 @@ def run_rake(commands = "", allow_failure = false) def with_tasks_traced(*tasks) with_environment( - "NEW_RELIC_RAKE_TASKS" => tasks.join(","), - "NEW_RELIC_SYNC_STARTUP" => "true" + 'NEW_RELIC_RAKE_TASKS' => tasks.join(','), + 'NEW_RELIC_SYNC_STARTUP' => 'true' ) do yield end end def without_attributes(*tasks) - with_environment("NEW_RELIC_ATTRIBUTES_EXCLUDE" => "*") do + with_environment('NEW_RELIC_ATTRIBUTES_EXCLUDE' => '*') do yield end end @@ -62,7 +62,7 @@ def refute_any_rake_metrics end def all_metric_names_posted - $collector.calls_for("metric_data").map do |metric_post| + $collector.calls_for('metric_data').map do |metric_post| metric_post.metric_names end.flatten end diff --git a/test/multiverse/suites/redis/redis_instrumentation_test.rb b/test/multiverse/suites/redis/redis_instrumentation_test.rb index e9bedd4d70..35aacdd8c2 100644 --- a/test/multiverse/suites/redis/redis_instrumentation_test.rb +++ b/test/multiverse/suites/redis/redis_instrumentation_test.rb @@ -34,25 +34,25 @@ def after_teardown def test_records_metrics_for_connect redis = Redis.new - in_transaction("test_txn") do - redis.get("foo") + in_transaction('test_txn') do + redis.get('foo') end expected = { - "test_txn" => {:call_count => 1}, - "OtherTransactionTotalTime" => {:call_count => 1}, - "OtherTransactionTotalTime/test_txn" => {:call_count => 1}, - ["Datastore/operation/Redis/connect", "test_txn"] => {:call_count => 1}, - "Datastore/operation/Redis/connect" => {:call_count => 1}, - ["Datastore/operation/Redis/get", "test_txn"] => {:call_count => 1}, - "Datastore/operation/Redis/get" => {:call_count => 1}, - "Datastore/Redis/allOther" => {:call_count => 2}, - "Datastore/Redis/all" => {:call_count => 2}, - "Datastore/allOther" => {:call_count => 2}, - "Datastore/all" => {:call_count => 2}, + 'test_txn' => {:call_count => 1}, + 'OtherTransactionTotalTime' => {:call_count => 1}, + 'OtherTransactionTotalTime/test_txn' => {:call_count => 1}, + ['Datastore/operation/Redis/connect', 'test_txn'] => {:call_count => 1}, + 'Datastore/operation/Redis/connect' => {:call_count => 1}, + ['Datastore/operation/Redis/get', 'test_txn'] => {:call_count => 1}, + 'Datastore/operation/Redis/get' => {:call_count => 1}, + 'Datastore/Redis/allOther' => {:call_count => 2}, + 'Datastore/Redis/all' => {:call_count => 2}, + 'Datastore/allOther' => {:call_count => 2}, + 'Datastore/all' => {:call_count => 2}, "Datastore/instance/Redis/#{redis_host}/6379" => {:call_count => 2}, - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all" => {:call_count => 1}, - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allOther" => {:call_count => 1} + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/all' => {:call_count => 1}, + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/allOther' => {:call_count => 1} } assert_metrics_recorded_exclusive(expected, :ignore_filter => /Supportability/) @@ -61,7 +61,7 @@ def test_records_metrics_for_connect def test_records_connect_tt_node_within_call_that_triggered_it in_transaction do redis = Redis.new - redis.get("foo") + redis.get('foo') end tt = last_transaction_trace @@ -81,11 +81,11 @@ def test_records_metrics_for_set end expected = { - "Datastore/operation/Redis/set" => {:call_count => 1}, - "Datastore/Redis/allOther" => {:call_count => 1}, - "Datastore/Redis/all" => {:call_count => 1}, - "Datastore/allOther" => {:call_count => 1}, - "Datastore/all" => {:call_count => 1}, + 'Datastore/operation/Redis/set' => {:call_count => 1}, + 'Datastore/Redis/allOther' => {:call_count => 1}, + 'Datastore/Redis/all' => {:call_count => 1}, + 'Datastore/allOther' => {:call_count => 1}, + 'Datastore/all' => {:call_count => 1}, "Datastore/instance/Redis/#{redis_host}/6379" => {:call_count => 1} } @@ -98,11 +98,11 @@ def test_records_metrics_for_set_in_web_transaction end expected = { - "Datastore/operation/Redis/set" => {:call_count => 1}, - "Datastore/Redis/allWeb" => {:call_count => 1}, - "Datastore/Redis/all" => {:call_count => 1}, - "Datastore/allWeb" => {:call_count => 1}, - "Datastore/all" => {:call_count => 1}, + 'Datastore/operation/Redis/set' => {:call_count => 1}, + 'Datastore/Redis/allWeb' => {:call_count => 1}, + 'Datastore/Redis/all' => {:call_count => 1}, + 'Datastore/allWeb' => {:call_count => 1}, + 'Datastore/all' => {:call_count => 1}, "Datastore/instance/Redis/#{redis_host}/6379" => {:call_count => 1} } @@ -115,11 +115,11 @@ def test_records_metrics_for_get_in_background_txn end expected = { - "Datastore/operation/Redis/get" => {:call_count => 1}, - "Datastore/Redis/allOther" => {:call_count => 1}, - "Datastore/Redis/all" => {:call_count => 1}, - "Datastore/allOther" => {:call_count => 1}, - "Datastore/all" => {:call_count => 1}, + 'Datastore/operation/Redis/get' => {:call_count => 1}, + 'Datastore/Redis/allOther' => {:call_count => 1}, + 'Datastore/Redis/all' => {:call_count => 1}, + 'Datastore/allOther' => {:call_count => 1}, + 'Datastore/all' => {:call_count => 1}, "Datastore/instance/Redis/#{redis_host}/6379" => {:call_count => 1} } @@ -155,11 +155,11 @@ def test_records_metrics_for_get_in_web_transaction end expected = { - "Datastore/operation/Redis/get" => {:call_count => 1}, - "Datastore/Redis/allWeb" => {:call_count => 1}, - "Datastore/Redis/all" => {:call_count => 1}, - "Datastore/allWeb" => {:call_count => 1}, - "Datastore/all" => {:call_count => 1}, + 'Datastore/operation/Redis/get' => {:call_count => 1}, + 'Datastore/Redis/allWeb' => {:call_count => 1}, + 'Datastore/Redis/all' => {:call_count => 1}, + 'Datastore/allWeb' => {:call_count => 1}, + 'Datastore/all' => {:call_count => 1}, "Datastore/instance/Redis/#{redis_host}/6379" => {:call_count => 1} } @@ -175,18 +175,18 @@ def test_records_metrics_for_pipelined_commands end expected = { - "test_txn" => {:call_count => 1}, - "OtherTransactionTotalTime" => {:call_count => 1}, - "OtherTransactionTotalTime/test_txn" => {:call_count => 1}, - ["Datastore/operation/Redis/pipeline", "test_txn"] => {:call_count => 1}, - "Datastore/operation/Redis/pipeline" => {:call_count => 1}, - "Datastore/Redis/allOther" => {:call_count => 1}, - "Datastore/Redis/all" => {:call_count => 1}, - "Datastore/allOther" => {:call_count => 1}, - "Datastore/all" => {:call_count => 1}, + 'test_txn' => {:call_count => 1}, + 'OtherTransactionTotalTime' => {:call_count => 1}, + 'OtherTransactionTotalTime/test_txn' => {:call_count => 1}, + ['Datastore/operation/Redis/pipeline', 'test_txn'] => {:call_count => 1}, + 'Datastore/operation/Redis/pipeline' => {:call_count => 1}, + 'Datastore/Redis/allOther' => {:call_count => 1}, + 'Datastore/Redis/all' => {:call_count => 1}, + 'Datastore/allOther' => {:call_count => 1}, + 'Datastore/all' => {:call_count => 1}, "Datastore/instance/Redis/#{redis_host}/6379" => {:call_count => 1}, - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all" => {:call_count => 1}, - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allOther" => {:call_count => 1} + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/all' => {:call_count => 1}, + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/allOther' => {:call_count => 1} } assert_metrics_recorded_exclusive(expected, :ignore_filter => /Supportability/) @@ -215,18 +215,18 @@ def test_records_metrics_for_multi_blocks end expected = { - "test_txn" => {:call_count => 1}, - "OtherTransactionTotalTime" => {:call_count => 1}, - "OtherTransactionTotalTime/test_txn" => {:call_count => 1}, - ["Datastore/operation/Redis/multi", "test_txn"] => {:call_count => 1}, - "Datastore/operation/Redis/multi" => {:call_count => 1}, - "Datastore/Redis/allOther" => {:call_count => 1}, - "Datastore/Redis/all" => {:call_count => 1}, - "Datastore/allOther" => {:call_count => 1}, - "Datastore/all" => {:call_count => 1}, + 'test_txn' => {:call_count => 1}, + 'OtherTransactionTotalTime' => {:call_count => 1}, + 'OtherTransactionTotalTime/test_txn' => {:call_count => 1}, + ['Datastore/operation/Redis/multi', 'test_txn'] => {:call_count => 1}, + 'Datastore/operation/Redis/multi' => {:call_count => 1}, + 'Datastore/Redis/allOther' => {:call_count => 1}, + 'Datastore/Redis/all' => {:call_count => 1}, + 'Datastore/allOther' => {:call_count => 1}, + 'Datastore/all' => {:call_count => 1}, "Datastore/instance/Redis/#{redis_host}/6379" => {:call_count => 1}, - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all" => {:call_count => 1}, - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allOther" => {:call_count => 1} + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/all' => {:call_count => 1}, + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/allOther' => {:call_count => 1} } assert_metrics_recorded_exclusive(expected, :ignore_filter => /Supportability/) @@ -264,7 +264,7 @@ def test_records_commands_with_args_in_tt_node_for_multi_blocks def test_records_instance_parameters_on_tt_node_for_get in_transaction do - @redis.get("foo") + @redis.get('foo') end tt = last_transaction_trace @@ -281,7 +281,7 @@ def test_records_hostname_on_tt_node_for_get_with_unix_domain_socket redis.send(client).stubs(:path).returns('/tmp/redis.sock') in_transaction do - redis.get("foo") + redis.get('foo') end tt = last_transaction_trace @@ -295,7 +295,7 @@ def test_records_hostname_on_tt_node_for_get_with_unix_domain_socket def test_records_instance_parameters_on_tt_node_for_multi in_transaction do @redis.multi do |pipeline| - pipeline.get("foo") + pipeline.get('foo') end end @@ -314,7 +314,7 @@ def test_records_hostname_on_tt_node_for_multi_with_unix_domain_socket in_transaction do redis.multi do |pipeline| - pipeline.get("foo") + pipeline.get('foo') end end @@ -330,7 +330,7 @@ def test_records_unknown_unknown_metric_when_error_gathering_instance_data redis = Redis.new redis.send(client).stubs(:path).raises(StandardError.new) in_transaction do - redis.get("foo") + redis.get('foo') end assert_metrics_recorded('Datastore/instance/Redis/unknown/unknown') @@ -342,8 +342,8 @@ def simulated_error_class def simulate_read_error redis = Redis.new - redis.send(client).stubs("connect").raises(simulated_error_class, "Error connecting to Redis") - redis.get("foo") + redis.send(client).stubs('connect').raises(simulated_error_class, 'Error connecting to Redis') + redis.get('foo') ensure end diff --git a/test/multiverse/suites/resque/instrumentation_test.rb b/test/multiverse/suites/resque/instrumentation_test.rb index ebc9856270..8e4fd8959e 100644 --- a/test/multiverse/suites/resque/instrumentation_test.rb +++ b/test/multiverse/suites/resque/instrumentation_test.rb @@ -32,7 +32,7 @@ def self.perform(name, sleep_duration = 0) end def self.request(args) - "we are not amused" + 'we are not amused' end end @@ -49,7 +49,7 @@ def run_jobs with_config(:'transaction_tracer.transaction_threshold' => 0.0) do JOB_COUNT.times do |i| - Resque.enqueue(JobForTesting, "testing") + Resque.enqueue(JobForTesting, 'testing') end end @@ -109,7 +109,7 @@ def test_arguments_are_captured_on_transaction_and_span_events_when_enabled def assert_metric_and_call_count(name, expected_call_count) metric_data = $collector.calls_for('metric_data') - assert_equal(1, metric_data.size, "expected exactly one metric_data post from agent") + assert_equal(1, metric_data.size, 'expected exactly one metric_data post from agent') metric = metric_data.first.metrics.find { |m| m[0]['name'] == name } assert(metric, "could not find metric named #{name}") @@ -127,7 +127,7 @@ def assert_attributes_on_transaction_traces transaction_samples.each do |post| post.samples.each do |sample| assert_equal sample.metric_name, TRANSACTION_NAME, "Huh, that transaction shouldn't be in there!" - assert_equal 'testing', sample.agent_attributes["job.resque.args.0"] + assert_equal 'testing', sample.agent_attributes['job.resque.args.0'] end end end @@ -151,7 +151,7 @@ def assert_attributes_on_events events = transaction_event_posts + span_event_posts events.each do |event| - assert_includes event[2].keys, "job.resque.args.0" + assert_includes event[2].keys, 'job.resque.args.0' end end @@ -161,7 +161,7 @@ def refute_attributes_on_events events = transaction_event_posts + span_event_posts events.each do |event| - assert event[2].keys.none? { |k| k.start_with?("job.resque.args") }, "Found unexpected resque arguments" + assert event[2].keys.none? { |k| k.start_with?('job.resque.args') }, 'Found unexpected resque arguments' end end end diff --git a/test/multiverse/suites/sequel/sequel_extension_test.rb b/test/multiverse/suites/sequel/sequel_extension_test.rb index 352ec5e9bc..ddd01fbbd0 100644 --- a/test/multiverse/suites/sequel/sequel_extension_test.rb +++ b/test/multiverse/suites/sequel/sequel_extension_test.rb @@ -35,12 +35,12 @@ def teardown def expected_metrics_for_operation(operation) [ - ["Datastore/operation/#{product_name}/#{operation}", "dummy"], + ["Datastore/operation/#{product_name}/#{operation}", 'dummy'], "Datastore/operation/#{product_name}/#{operation}", "Datastore/#{product_name}/allWeb", - "Datastore/allWeb", + 'Datastore/allWeb', "Datastore/#{product_name}/all", - "Datastore/all" + 'Datastore/all' ] end @@ -142,5 +142,5 @@ def test_notices_sql_with_proper_metric_name end else - puts "Skipping tests in #{File.basename(__FILE__)} because unsupported Sequel version" if ENV["VERBOSE_TEST_OUTPUT"] + puts "Skipping tests in #{File.basename(__FILE__)} because unsupported Sequel version" if ENV['VERBOSE_TEST_OUTPUT'] end diff --git a/test/multiverse/suites/sequel/sequel_helpers.rb b/test/multiverse/suites/sequel/sequel_helpers.rb index fef0fff257..48faa023f9 100644 --- a/test/multiverse/suites/sequel/sequel_helpers.rb +++ b/test/multiverse/suites/sequel/sequel_helpers.rb @@ -50,10 +50,10 @@ def last_node(txn_sample) end def product_name - if defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby" - "JDBC" + if defined?(RUBY_ENGINE) && RUBY_ENGINE == 'jruby' + 'JDBC' else - "SQLite" + 'SQLite' end end diff --git a/test/multiverse/suites/sequel/sequel_plugin_test.rb b/test/multiverse/suites/sequel/sequel_plugin_test.rb index c09ef80d9b..739a290355 100644 --- a/test/multiverse/suites/sequel/sequel_plugin_test.rb +++ b/test/multiverse/suites/sequel/sequel_plugin_test.rb @@ -16,15 +16,15 @@ class SequelPluginTest < Minitest::Test def expected_metrics_for_operation(operation) [ - ["Datastore/statement/#{product_name}/Post/#{operation}", "dummy"], + ["Datastore/statement/#{product_name}/Post/#{operation}", 'dummy'], "Datastore/statement/#{product_name}/Post/#{operation}", "Datastore/operation/#{product_name}/#{operation}", "Datastore/#{product_name}/allWeb", - "Datastore/allWeb", + 'Datastore/allWeb', "Datastore/#{product_name}/all", - "Datastore/all", - "dummy", - "Apdex" + 'Datastore/all', + 'dummy', + 'Apdex' ] end @@ -195,7 +195,7 @@ def test_no_explain_plans_with_single_threaded_connection end assert_match %r{select \* from `posts` where `id` = 11}i, node.params[:sql] - assert_empty(node.params[:explain_plan], "Should not capture explain plan with single-threaded connection pool") + assert_empty(node.params[:explain_plan], 'Should not capture explain plan with single-threaded connection pool') end end @@ -230,5 +230,5 @@ def test_notices_sql_with_proper_metric_name_for_all end else - puts "Skipping tests in #{File.basename(__FILE__)} because unsupported Sequel version" if ENV["VERBOSE_TEST_OUTPUT"] + puts "Skipping tests in #{File.basename(__FILE__)} because unsupported Sequel version" if ENV['VERBOSE_TEST_OUTPUT'] end diff --git a/test/multiverse/suites/sidekiq/Envfile b/test/multiverse/suites/sidekiq/Envfile index 32b504aed4..a496701df9 100644 --- a/test/multiverse/suites/sidekiq/Envfile +++ b/test/multiverse/suites/sidekiq/Envfile @@ -9,8 +9,7 @@ end SIDEKIQ_VERSIONS = [ [nil, 2.7], ['6.4.0', 2.5], - ['5.0.3', 2.4], - ['4.2.0', 2.4] + ['5.0.3', 2.4] ] def gem_list(sidekiq_version = nil) diff --git a/test/multiverse/suites/sidekiq/sidekiq_instrumentation_test.rb b/test/multiverse/suites/sidekiq/sidekiq_instrumentation_test.rb index 377cf1bcfe..62a79c52cf 100644 --- a/test/multiverse/suites/sidekiq/sidekiq_instrumentation_test.rb +++ b/test/multiverse/suites/sidekiq/sidekiq_instrumentation_test.rb @@ -4,7 +4,7 @@ # https://newrelic.atlassian.net/browse/RUBY-775 -require File.join(File.dirname(__FILE__), "sidekiq_server") +require File.join(File.dirname(__FILE__), 'sidekiq_server') SidekiqServer.instance.run # Important to require after Sidekiq server starts for middleware to install @@ -14,8 +14,8 @@ require 'stringio' require 'fake_collector' -require File.join(File.dirname(__FILE__), "test_model") -require File.join(File.dirname(__FILE__), "test_worker") +require File.join(File.dirname(__FILE__), 'test_model') +require File.join(File.dirname(__FILE__), 'test_worker') class SidekiqTest < Minitest::Test JOB_COUNT = 5 @@ -46,7 +46,7 @@ def set_sidekiq_logger(logger) def teardown teardown_agent - if !passed? || ENV["VERBOSE"] + if !passed? || ENV['VERBOSE'] @sidekiq_log.rewind puts @sidekiq_log.read end @@ -83,7 +83,7 @@ def test_delayed end def test_delayed_with_malformed_yaml - YAML.stubs(:load).raises(RuntimeError.new("Ouch")) + YAML.stubs(:load).raises(RuntimeError.new('Ouch')) run_delayed assert_metric_and_call_count(ROLLUP_METRIC, JOB_COUNT) @@ -106,9 +106,9 @@ def test_all_jobs_ran def test_distributed_trace_instrumentation @config = { :'distributed_tracing.enabled' => true, - :account_id => "190", - :primary_application_id => "46954", - :trusted_account_key => "trust_this!" + :account_id => '190', + :primary_application_id => '46954', + :trusted_account_key => 'trust_this!' } NewRelic::Agent::DistributedTracePayload.stubs(:connected?).returns(true) NewRelic::Agent.config.add_config_for_testing(@config) @@ -117,8 +117,8 @@ def test_distributed_trace_instrumentation run_jobs end - assert_metric_and_call_count "Supportability/TraceContext/Accept/Success", JOB_COUNT # method for metrics created on server side - assert_metrics_recorded "Supportability/DistributedTrace/CreatePayload/Success" # method for metrics created on the client side + assert_metric_and_call_count 'Supportability/TraceContext/Accept/Success', JOB_COUNT # method for metrics created on server side + assert_metrics_recorded 'Supportability/DistributedTrace/CreatePayload/Success' # method for metrics created on the client side NewRelic::Agent.config.remove_config(@config) NewRelic::Agent.config.reset_to_defaults @@ -182,10 +182,18 @@ def test_captures_sidekiq_internal_errors Sidekiq::CLI.instance.handle_exception(exception) end + def test_accept_dt_headers_not_called_if_headers_nil + NewRelic::Agent::DistributedTracing.stubs(:insert_distributed_trace_headers) + NewRelic::Agent::DistributedTracing.expects(:accept_distributed_trace_headers).never + in_transaction do + run_jobs + end + end + def assert_metric_and_call_count(name, expected_call_count) metric_data = $collector.calls_for('metric_data') - assert_equal(1, metric_data.size, "expected exactly one metric_data post from agent") + assert_equal(1, metric_data.size, 'expected exactly one metric_data post from agent') metrics = metric_data.first.metrics metric = metrics.find { |m| m[0]['name'] == name } @@ -201,14 +209,14 @@ def assert_metric_and_call_count(name, expected_call_count) def assert_attributes_on_transaction_trace transaction_samples = $collector.calls_for('transaction_sample_data') - refute_empty transaction_samples, "Expected a transaction trace" + refute_empty transaction_samples, 'Expected a transaction trace' transaction_samples.each do |post| post.samples.each do |sample| assert_equal sample.metric_name, TRANSACTION_NAME, "Huh, that transaction shouldn't be in there!" actual = sample.agent_attributes.keys.to_set - expected = Set.new(["job.sidekiq.args.0", "job.sidekiq.args.1"]) + expected = Set.new(['job.sidekiq.args.0', 'job.sidekiq.args.1']) assert_equal expected, actual end @@ -233,8 +241,8 @@ def assert_attributes_on_events span_event_posts = $collector.calls_for('span_event_data')[0].events events = transaction_event_posts + span_event_posts events.each do |event| - assert_includes event[2].keys, "job.sidekiq.args.0" - assert_includes event[2].keys, "job.sidekiq.args.1" + assert_includes event[2].keys, 'job.sidekiq.args.0' + assert_includes event[2].keys, 'job.sidekiq.args.1' end end @@ -244,18 +252,18 @@ def refute_attributes_on_events events = transaction_event_posts + span_event_posts events.each do |event| - assert event[2].keys.none? { |k| k.start_with?("job.sidekiq.args") }, "Found unexpected sidekiq arguments" + assert event[2].keys.none? { |k| k.start_with?('job.sidekiq.args') }, 'Found unexpected sidekiq arguments' end end def assert_error_for_each_job(txn_name = TRANSACTION_NAME) - error_posts = $collector.calls_for("error_data") + error_posts = $collector.calls_for('error_data') - assert_equal 1, error_posts.length, "Wrong number of error posts!" + assert_equal 1, error_posts.length, 'Wrong number of error posts!' errors = error_posts.first - assert_equal JOB_COUNT, errors.errors.length, "Wrong number of errors noticed!" + assert_equal JOB_COUNT, errors.errors.length, 'Wrong number of errors noticed!' assert_metric_and_call_count('Errors/all', JOB_COUNT) if txn_name diff --git a/test/multiverse/suites/sidekiq/sidekiq_server.rb b/test/multiverse/suites/sidekiq/sidekiq_server.rb index c19f25356b..7f33ac403e 100644 --- a/test/multiverse/suites/sidekiq/sidekiq_server.rb +++ b/test/multiverse/suites/sidekiq/sidekiq_server.rb @@ -19,9 +19,9 @@ def initialize set_redis_host end - def run(file = "test_worker.rb") - @sidekiq.parse(["--require", File.join(File.dirname(__FILE__), file), - "--queue", "#{queue_name},1"]) + def run(file = 'test_worker.rb') + @sidekiq.parse(['--require', File.join(File.dirname(__FILE__), file), + '--queue', "#{queue_name},1"]) @cli_thread = Thread.new { @sidekiq.run } end @@ -29,7 +29,7 @@ def run(file = "test_worker.rb") # Launcher actor in Sidekiq to throw a fuss and exit with a failed code. def stop puts "Trying to stop Sidekiq gracefully from #{$$}" - Process.kill("INT", $$) + Process.kill('INT', $$) if @cli_thread.join(THREAD_JOIN_TIMEOUT).nil? puts "#{$$} Sidekiq::CLI thread timeout on exit" end diff --git a/test/multiverse/suites/sidekiq/sidekiq_with_redis_test.rb b/test/multiverse/suites/sidekiq/sidekiq_with_redis_test.rb index d6da28c754..73d1ebd721 100644 --- a/test/multiverse/suites/sidekiq/sidekiq_with_redis_test.rb +++ b/test/multiverse/suites/sidekiq/sidekiq_with_redis_test.rb @@ -34,6 +34,7 @@ class SidekiqWithRedisTest < MiniTest::Test # NOTE: Because Sidekiq v7.0+ can use `redis-client` without `redis`, this # test brings in the `redis` gem directly via `bundler/inline` def test_redis_client_pipelined_calls_work + skip 'The CI fails when trying to run this test because of a Bundler error' if RUBY_VERSION.match?(/^3\.1/) skip 'Testing conducted only using Sidekiq v7.0+ with redis not yet bundled' unless sidekiq_without_redis? gemfile do diff --git a/test/multiverse/suites/sidekiq/test_worker.rb b/test/multiverse/suites/sidekiq/test_worker.rb index aa97f9b0fb..bcafdf789c 100644 --- a/test/multiverse/suites/sidekiq/test_worker.rb +++ b/test/multiverse/suites/sidekiq/test_worker.rb @@ -2,7 +2,7 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -require_relative "sidekiq_server" +require_relative 'sidekiq_server' class TestWorker include Sidekiq::Worker @@ -70,7 +70,7 @@ def self.am_i_a_failure? def perform(key, val) if self.class.am_i_a_failure? - raise "Uh oh" + raise 'Uh oh' else TestWorker.record(key, val) end diff --git a/test/multiverse/suites/sinatra/Envfile b/test/multiverse/suites/sinatra/Envfile index 64dbbb277c..3bda2ac442 100644 --- a/test/multiverse/suites/sinatra/Envfile +++ b/test/multiverse/suites/sinatra/Envfile @@ -7,21 +7,13 @@ instrumentation_methods :chain, :prepend SINATRA_VERSIONS = [ [nil, 2.4], ['2.1.0', 2.4], - ['2.0.0', 2.4], - ['1.4.8', 2.4] + ['2.0.0', 2.4] ] -# sinatra v1.x needs rack v1.x, regardless of ruby version -def rack_version(sinatra_version) - return '~> 1.5' if sinatra_version.to_s =~ /^[^\d]*1/ - - '~> 2.2' -end - def gem_list(sinatra_version = nil) <<~RB gem 'sinatra'#{sinatra_version} - gem 'rack', '#{rack_version(sinatra_version)}' + gem 'rack', '~> 2.2' gem 'rack-test', '>= 0.8.0', :require => 'rack/test' RB diff --git a/test/multiverse/suites/sinatra/ignoring_test.rb b/test/multiverse/suites/sinatra/ignoring_test.rb index bddcc9a535..b589b914c7 100644 --- a/test/multiverse/suites/sinatra/ignoring_test.rb +++ b/test/multiverse/suites/sinatra/ignoring_test.rb @@ -45,7 +45,7 @@ class SinatraTestCase < Minitest::Test include ::NewRelic::Agent::Instrumentation::Sinatra include MultiverseHelpers - JS_AGENT_LOADER = "JS_AGENT_LOADER" + JS_AGENT_LOADER = 'JS_AGENT_LOADER' setup_and_teardown_agent(:application_id => 'appId', :beacon => 'beacon', @@ -186,7 +186,7 @@ def test_ignore_enduser def test_ignore_errors_in_ignored_transactions get('/ignored_erroring') - assert_metrics_not_recorded(["Errors/all"]) + assert_metrics_not_recorded(['Errors/all']) end def name_for_route(path) diff --git a/test/multiverse/suites/sinatra/nested_middleware_test.rb b/test/multiverse/suites/sinatra/nested_middleware_test.rb index e773374a14..4e30a5fa43 100644 --- a/test/multiverse/suites/sinatra/nested_middleware_test.rb +++ b/test/multiverse/suites/sinatra/nested_middleware_test.rb @@ -4,7 +4,7 @@ class MiddlewareApp < Sinatra::Base get '/middle' do - "From the middlewarez" + 'From the middlewarez' end end @@ -12,7 +12,7 @@ class MainApp < Sinatra::Base use MiddlewareApp get '/main' do - "mainly done" + 'mainly done' end end @@ -30,7 +30,7 @@ def test_inner_transaction get('/main') assert_metrics_recorded(["Controller/Sinatra/MainApp/#{name_for_route('main')}"]) - assert_metrics_not_recorded(["Controller/Sinatra/MiddlewareApp/GET (unknown)"]) + assert_metrics_not_recorded(['Controller/Sinatra/MiddlewareApp/GET (unknown)']) end def test_outer_transaction diff --git a/test/multiverse/suites/sinatra/sinatra_classic_test.rb b/test/multiverse/suites/sinatra/sinatra_classic_test.rb index 167660d21b..99f18c5013 100644 --- a/test/multiverse/suites/sinatra/sinatra_classic_test.rb +++ b/test/multiverse/suites/sinatra/sinatra_classic_test.rb @@ -22,11 +22,11 @@ end get '/' do - "root path" + 'root path' end get '/user/login' do - "please log in" + 'please log in' end # this action will always return 404 because of the condition. @@ -35,7 +35,7 @@ end get '/raise' do - raise "Uh-oh" + raise 'Uh-oh' end # check that pass works properly @@ -52,7 +52,7 @@ set(:precondition_check) do |_| condition do - raise "Boo" if $precondition_already_checked + raise 'Boo' if $precondition_already_checked $precondition_already_checked = true end diff --git a/test/multiverse/suites/sinatra/sinatra_metric_explosion_test.rb b/test/multiverse/suites/sinatra/sinatra_metric_explosion_test.rb index 5b0babeecc..e3ba387c9e 100644 --- a/test/multiverse/suites/sinatra/sinatra_metric_explosion_test.rb +++ b/test/multiverse/suites/sinatra/sinatra_metric_explosion_test.rb @@ -75,17 +75,17 @@ def test_transaction_name_does_not_explode metric_names = ::NewRelic::Agent.agent.stats_engine.to_h.keys.map(&:to_s) metric_names -= [ 'CPU/User Time', - "Middleware/all", - "WebFrontend/QueueTime", - "WebFrontend/WebServer/all" + 'Middleware/all', + 'WebFrontend/QueueTime', + 'WebFrontend/WebServer/all' ] name_beginnings_to_ignore = [ - "ApdexAll", - "Supportability", - "GC/Transaction", - "Nested/Controller", - "Middleware" + 'ApdexAll', + 'Supportability', + 'GC/Transaction', + 'Nested/Controller', + 'Middleware' ] metric_names.delete_if do |metric| name_beginnings_to_ignore.any? { |name| metric.start_with?(name) } diff --git a/test/multiverse/suites/sinatra/sinatra_modular_test.rb b/test/multiverse/suites/sinatra/sinatra_modular_test.rb index 9eca59c2ff..22ed09a640 100644 --- a/test/multiverse/suites/sinatra/sinatra_modular_test.rb +++ b/test/multiverse/suites/sinatra/sinatra_modular_test.rb @@ -22,11 +22,11 @@ class SinatraModularTestApp < Sinatra::Base end get '/' do - "root path" + 'root path' end get '/user/login' do - "please log in" + 'please log in' end # this action will always return 404 because of the condition. @@ -35,7 +35,7 @@ class SinatraModularTestApp < Sinatra::Base end get '/raise' do - raise "Uh-oh" + raise 'Uh-oh' end # check that pass works properly @@ -51,7 +51,7 @@ class SinatraModularTestApp < Sinatra::Base get('/error') {} condition do - raise "Boo" if $precondition_already_checked + raise 'Boo' if $precondition_already_checked $precondition_already_checked = true end diff --git a/test/multiverse/suites/sinatra/sinatra_parameter_capture_test.rb b/test/multiverse/suites/sinatra/sinatra_parameter_capture_test.rb index 8822e590a5..9133e27f27 100644 --- a/test/multiverse/suites/sinatra/sinatra_parameter_capture_test.rb +++ b/test/multiverse/suites/sinatra/sinatra_parameter_capture_test.rb @@ -3,12 +3,12 @@ # frozen_string_literal: true class SinatraParameterCaptureTestApp < Sinatra::Base - post "/capture_test" do - "capture test" + post '/capture_test' do + 'capture test' end post '/files' do - "file uploaded" + 'file uploaded' end end @@ -30,15 +30,15 @@ def test_request_params_are_captured_for_transaction_events with_config(:'attributes.include' => 'request.parameters.*', :'attributes.exclude' => ['request.*', 'response.*']) do params = { - :foo => "bar", - :bar => "baz" + :foo => 'bar', + :bar => 'baz' } post('/capture_test', params) end expected = { - "request.parameters.foo" => "bar", - "request.parameters.bar" => "baz" + 'request.parameters.foo' => 'bar', + 'request.parameters.bar' => 'baz' } actual = agent_attributes_for_single_event_posted_without_ignored_attributes @@ -49,14 +49,14 @@ def test_request_params_are_captured_for_transaction_events def test_file_upload_params_are_filtered with_config(:capture_params => true) do params = { - :title => "blah", + :title => 'blah', :file => Rack::Test::UploadedFile.new(__FILE__, 'text/plain') } post('/files', params) expected = { - "request.parameters.title" => "blah", - "request.parameters.file" => "[FILE]" + 'request.parameters.title' => 'blah', + 'request.parameters.file' => '[FILE]' } assert_equal(expected, last_transaction_trace_request_params) @@ -67,12 +67,12 @@ def test_request_and_response_attributes_recorded_as_agent_attributes post('/capture_test') expected = { - "response.headers.contentLength" => last_response.content_length.to_i, - "response.headers.contentType" => last_response.content_type, - "request.headers.contentLength" => last_request.content_length.to_i, - "request.headers.contentType" => last_request.content_type, - "request.headers.host" => last_request.host, - "request.method" => last_request.request_method + 'response.headers.contentLength' => last_response.content_length.to_i, + 'response.headers.contentType' => last_response.content_type, + 'request.headers.contentLength' => last_request.content_length.to_i, + 'request.headers.contentType' => last_request.content_type, + 'request.headers.host' => last_request.host, + 'request.method' => last_request.request_method } actual = agent_attributes_for_single_event_posted_without_ignored_attributes diff --git a/test/multiverse/suites/sinatra/sinatra_routes_test.rb b/test/multiverse/suites/sinatra/sinatra_routes_test.rb index 577e276c48..7359b169d8 100644 --- a/test/multiverse/suites/sinatra/sinatra_routes_test.rb +++ b/test/multiverse/suites/sinatra/sinatra_routes_test.rb @@ -14,7 +14,7 @@ class SinatraRouteTestApp < Sinatra::Base end get '/user/login' do - "please log in" + 'please log in' end # this action will always return 404 because of the condition. diff --git a/test/multiverse/suites/sinatra/sinatra_test_cases.rb b/test/multiverse/suites/sinatra/sinatra_test_cases.rb index 79a3da1e7e..c7a04e98fe 100644 --- a/test/multiverse/suites/sinatra/sinatra_test_cases.rb +++ b/test/multiverse/suites/sinatra/sinatra_test_cases.rb @@ -46,7 +46,7 @@ def ignored_segment include SinatraRouteNaming def app - raise "Must implement app on your test case" + raise 'Must implement app on your test case' end def app_name @@ -76,7 +76,7 @@ def test_conditions_are_applied_to_an_action_that_uses_them def test_queue_time_headers_are_passed_to_agent get('/user/login', {}, {'HTTP_X_REQUEST_START' => 't=1360973845'}) - assert_metrics_recorded(["WebFrontend/QueueTime"]) + assert_metrics_recorded(['WebFrontend/QueueTime']) end def test_shown_errors_get_caught @@ -97,7 +97,7 @@ def test_does_not_break_error_handling get('/error') assert_equal 200, last_response.status - assert_equal "nothing happened", last_response.body + assert_equal 'nothing happened', last_response.body end def test_sees_handled_error @@ -163,7 +163,7 @@ def test_rack_request_params_errors_are_swallowed def test_rack_request_params_errors_are_logged NewRelic::Agent.logger.stubs(:debug) - NewRelic::Agent.logger.expects(:debug).with("Failed to get params from Rack request.", kind_of(StandardError)).at_least_once + NewRelic::Agent.logger.expects(:debug).with('Failed to get params from Rack request.', kind_of(StandardError)).at_least_once trigger_error_on_params @@ -194,7 +194,7 @@ def test_doesnt_inject_already_existing_middleware def trigger_error_on_params Sinatra::Request.any_instance .stubs(:params).returns({}) - .then.raises(StandardError.new("Rack::Request#params error")) + .then.raises(StandardError.new('Rack::Request#params error')) end else def trigger_error_on_params diff --git a/test/multiverse/suites/sinatra_agent_disabled/shim_test.rb b/test/multiverse/suites/sinatra_agent_disabled/shim_test.rb index 94ac2cd3f2..f68f1a3f10 100644 --- a/test/multiverse/suites/sinatra_agent_disabled/shim_test.rb +++ b/test/multiverse/suites/sinatra_agent_disabled/shim_test.rb @@ -6,7 +6,7 @@ class MiddlewareApp < Sinatra::Base get '/middle' do - "From the middlewarez" + 'From the middlewarez' end end @@ -18,13 +18,13 @@ def teardown def assert_shims_defined # class method shim - assert_respond_to MiddlewareApp, :newrelic_ignore, "Class method newrelic_ignore not defined" - assert_respond_to MiddlewareApp, :newrelic_ignore_apdex, "Class method newrelic_ignore_apdex not defined" - assert_respond_to MiddlewareApp, :newrelic_ignore_enduser, "Class method newrelic_ignore_enduser not defined" + assert_respond_to MiddlewareApp, :newrelic_ignore, 'Class method newrelic_ignore not defined' + assert_respond_to MiddlewareApp, :newrelic_ignore_apdex, 'Class method newrelic_ignore_apdex not defined' + assert_respond_to MiddlewareApp, :newrelic_ignore_enduser, 'Class method newrelic_ignore_enduser not defined' # instance method shims - assert_includes(MiddlewareApp.instance_methods, :new_relic_trace_controller_action, "Instance method new_relic_trace_controller_action not defined") - assert_includes(MiddlewareApp.instance_methods, :perform_action_with_newrelic_trace, "Instance method perform_action_with_newrelic_trace not defined") + assert_includes(MiddlewareApp.instance_methods, :new_relic_trace_controller_action, 'Instance method new_relic_trace_controller_action not defined') + assert_includes(MiddlewareApp.instance_methods, :perform_action_with_newrelic_trace, 'Instance method perform_action_with_newrelic_trace not defined') end def test_shims_exist_when_agent_enabled_false diff --git a/test/multiverse/suites/tilt/Envfile b/test/multiverse/suites/tilt/Envfile index 59e8fe6389..8724e9eaeb 100644 --- a/test/multiverse/suites/tilt/Envfile +++ b/test/multiverse/suites/tilt/Envfile @@ -10,7 +10,7 @@ TILT_VERSIONS = [ ] def haml_version(tilt_version) - if tilt_version && (Gem::Version.new(tilt_version.match(/^\d+/)) < Gem::Version.new('2.0.0')) + if tilt_version && (Gem::Version.new(tilt_version.match(/[0-9\.]+/)) < Gem::Version.new('2.0.0')) add_version('5.2.2') end end diff --git a/test/multiverse/suites/typhoeus/Envfile b/test/multiverse/suites/typhoeus/Envfile index 3829ba9959..fa9dfd5ae6 100644 --- a/test/multiverse/suites/typhoeus/Envfile +++ b/test/multiverse/suites/typhoeus/Envfile @@ -4,9 +4,9 @@ # TODO: JRuby 9.3.7.0 crashes with Ubuntu 22 and JREs 8 and 11 suite_condition("Typhoeus is skipped for JRuby with Ubuntu 22") do - RUBY_PLATFORM != 'java' && + !(RUBY_PLATFORM == 'java' && File.exist?('/etc/lsb-release') && - File.read('/etc/lsb-release') =~ /DISTRIB_RELEASE=22\.04/ + File.read('/etc/lsb-release') =~ /DISTRIB_RELEASE=22\.04/) end instrumentation_methods :chain, :prepend @@ -15,7 +15,7 @@ TYPHOEUS_VERSIONS = [ nil, '1.4.0', '1.3.1', - '1.3.0', + '1.3.0' ] def gem_list(typhoeus_version = nil) @@ -23,7 +23,7 @@ def gem_list(typhoeus_version = nil) gem 'typhoeus'#{typhoeus_version} gem 'ethon' if RUBY_PLATFORM == 'java' gem 'rack' - + RB end diff --git a/test/multiverse/suites/typhoeus/typhoeus_test.rb b/test/multiverse/suites/typhoeus/typhoeus_test.rb index 0e582c8d6a..f4e916f4da 100644 --- a/test/multiverse/suites/typhoeus/typhoeus_test.rb +++ b/test/multiverse/suites/typhoeus/typhoeus_test.rb @@ -2,20 +2,20 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -require "typhoeus" -require "newrelic_rpm" -require "http_client_test_cases" +require 'typhoeus' +require 'newrelic_rpm' +require 'http_client_test_cases' if NewRelic::Agent::Instrumentation::Typhoeus.is_supported_version? class TyphoeusTest < Minitest::Test include HttpClientTestCases - USE_SSL_VERIFYPEER_VERSION = Gem::Version.new("0.5.0") + USE_SSL_VERIFYPEER_VERSION = Gem::Version.new('0.5.0') # Starting in version 0.6.4, Typhoeus supports passing URI instances instead # of String URLs. Make sure we don't break that. - SUPPORTS_URI_OBJECT_VERSION = Gem::Version.new("0.6.4") + SUPPORTS_URI_OBJECT_VERSION = Gem::Version.new('0.6.4') CURRENT_TYPHOEUS_VERSION = Gem::Version.new(Typhoeus::VERSION) @@ -28,7 +28,7 @@ def ssl_option end def client_name - "Typhoeus" + 'Typhoeus' end def timeout_error_class @@ -36,7 +36,7 @@ def timeout_error_class end def simulate_error_response - get_response("http://localhost:666/evil") + get_response('http://localhost:666/evil') end # We use the Typhoeus::Request rather than right on Typhoeus to support @@ -55,11 +55,11 @@ def head_response end def post_response - Typhoeus::Request.post(default_url, ssl_option.merge(:body => "")) + Typhoeus::Request.post(default_url, ssl_option.merge(:body => '')) end def put_response - Typhoeus::Request.put(default_url, ssl_option.merge(:body => "")) + Typhoeus::Request.put(default_url, ssl_option.merge(:body => '')) end def delete_response @@ -67,7 +67,7 @@ def delete_response end def request_instance - NewRelic::Agent::HTTPClients::TyphoeusHTTPRequest.new(Typhoeus::Request.new("http://newrelic.com")) + NewRelic::Agent::HTTPClients::TyphoeusHTTPRequest.new(Typhoeus::Request.new('http://newrelic.com')) end def response_instance(headers = {}) @@ -110,7 +110,7 @@ def test_maintains_on_complete_callback_ordering def test_tracing_succeeds_if_user_set_on_complete_callback_raises caught_exception = nil - in_transaction("test") do + in_transaction('test') do req = Typhoeus::Request.new(default_url, ssl_option) req.on_complete { |rsp| raise 'noodle' } @@ -130,21 +130,21 @@ def test_tracing_succeeds_if_user_set_on_complete_callback_raises last_node = find_last_transaction_node - assert_equal "External/localhost/Typhoeus/GET", last_node.metric_name + assert_equal 'External/localhost/Typhoeus/GET', last_node.metric_name end def test_request_succeeds_even_if_tracing_doesnt - in_transaction("test") do - ::NewRelic::Agent::CrossAppTracing.stubs(:cross_app_enabled?).raises("Booom") + in_transaction('test') do + ::NewRelic::Agent::CrossAppTracing.stubs(:cross_app_enabled?).raises('Booom') res = get_response assert_match %r{}i, body(res) - assert_metrics_not_recorded(["External/all"]) + assert_metrics_not_recorded(['External/all']) end end def test_hydra - in_transaction("test") do + in_transaction('test') do hydra = Typhoeus::Hydra.new 5.times { hydra.queue(Typhoeus::Request.new(default_url, ssl_option)) } hydra.run @@ -152,21 +152,21 @@ def test_hydra trace = last_transaction_trace - hydra = find_node_with_name(trace, "External/Multiple/Typhoeus::Hydra/run") + hydra = find_node_with_name(trace, 'External/Multiple/Typhoeus::Hydra/run') assert_equal 5, hydra.children.size hydra.children.each do |child| - assert_equal "External/localhost/Typhoeus/GET", child.metric_name + assert_equal 'External/localhost/Typhoeus/GET', child.metric_name end trace.each_node do |node| - next if node.metric_name == "ROOT" + next if node.metric_name == 'ROOT' - assert node.params.key?(:exclusive_duration_millis), "Expected all nodes (except ROOT) to have :exclusive_duration_millis" + assert node.params.key?(:exclusive_duration_millis), 'Expected all nodes (except ROOT) to have :exclusive_duration_millis' end - assert hydra.params[:exclusive_duration_millis] > 0, "Expected a positive exclusive duration" + assert hydra.params[:exclusive_duration_millis] > 0, 'Expected a positive exclusive duration' end def test_noticed_error_at_segment_and_txn_on_error_for_hydra @@ -175,7 +175,7 @@ def test_noticed_error_at_segment_and_txn_on_error_for_hydra in_transaction do |ext_txn| txn = ext_txn hydra = Typhoeus::Hydra.new - 5.times { hydra.queue(Typhoeus::Request.new("http://localhost:666/evil", ssl_option)) } + 5.times { hydra.queue(Typhoeus::Request.new('http://localhost:666/evil', ssl_option)) } hydra.run end rescue StandardError => e @@ -187,7 +187,7 @@ def test_noticed_error_at_segment_and_txn_on_error_for_hydra get_segments = txn.segments.select { |s| s.name =~ /GET$/ } assert_equal 5, get_segments.size - assert get_segments.all? { |s| s.noticed_error }, "Expected every GET to notice an error" + assert get_segments.all? { |s| s.noticed_error }, 'Expected every GET to notice an error' # Typhoeus doesn't raise errors, so transactions never see it, # which diverges from behavior of other HTTP client libraries @@ -200,7 +200,7 @@ def test_get_with_uri in_transaction { res = get_response(default_uri) } assert_match %r{}i, body(res) - assert_externals_recorded_for("localhost", "GET") + assert_externals_recorded_for('localhost', 'GET') end end end @@ -210,9 +210,9 @@ def test_get_with_uri class TyphoeusNotInstrumented < Minitest::Test def test_works_without_instrumentation # Typhoeus.get wasn't supported back before 0.5.x - Typhoeus::Request.get("http://localhost/not/there") + Typhoeus::Request.get('http://localhost/not/there') - assert_metrics_not_recorded(["External/all"]) + assert_metrics_not_recorded(['External/all']) end end diff --git a/test/multiverse/test/multiverse_test.rb b/test/multiverse/test/multiverse_test.rb index e2730d8bf5..40f3511ed9 100644 --- a/test/multiverse/test/multiverse_test.rb +++ b/test/multiverse/test/multiverse_test.rb @@ -43,7 +43,7 @@ def run_suite(suite) def test_suite_environments_are_isolated_from_each_other run = run_suite('one') - assert_equal 0, run.exit_status, "Test suite should demonstrate that " << + assert_equal 0, run.exit_status, 'Test suite should demonstrate that ' << "gems loaded in for one suite don't " << "persist in the next suite\n" # + run.output end @@ -51,14 +51,14 @@ def test_suite_environments_are_isolated_from_each_other def test_failed_tests_mean_unsuccessful_exit_code_in_parent_with_fork_execute_mode run = run_suite('two') - refute_equal 0, run.exit_status, "Failed test should mean unsuccessful " << + refute_equal 0, run.exit_status, 'Failed test should mean unsuccessful ' << "exit status in parent \n" # + run.output end def test_failed_tests_mean_unsuccessful_exit_code_in_parent_with_spawn_execute_mode run = run_suite('three') - refute_equal 0, run.exit_status, "Failed test in spawn mode should mean unsuccessful " << + refute_equal 0, run.exit_status, 'Failed test in spawn mode should mean unsuccessful ' << "exit status in parent \n" # + run.output end end diff --git a/test/multiverse/test/suite_examples/three/a/fail_test.rb b/test/multiverse/test/suite_examples/three/a/fail_test.rb index c028038f1b..6c4efc48dc 100644 --- a/test/multiverse/test/suite_examples/three/a/fail_test.rb +++ b/test/multiverse/test/suite_examples/three/a/fail_test.rb @@ -5,6 +5,6 @@ require 'test/unit' class ATest < Test::Unit::TestCase def test_failure - fail "This test is failing!!!" + fail 'This test is failing!!!' end end diff --git a/test/multiverse/test/suite_examples/three/b/win_test.rb b/test/multiverse/test/suite_examples/three/b/win_test.rb index 025be2452f..fd5ab49a22 100644 --- a/test/multiverse/test/suite_examples/three/b/win_test.rb +++ b/test/multiverse/test/suite_examples/three/b/win_test.rb @@ -5,6 +5,6 @@ require 'test/unit' class ATest < Test::Unit::TestCase def test_success - assert "This test is not failing!!!" + assert 'This test is not failing!!!' end end diff --git a/test/multiverse/test/suite_examples/two/a/fail_test.rb b/test/multiverse/test/suite_examples/two/a/fail_test.rb index c028038f1b..6c4efc48dc 100644 --- a/test/multiverse/test/suite_examples/two/a/fail_test.rb +++ b/test/multiverse/test/suite_examples/two/a/fail_test.rb @@ -5,6 +5,6 @@ require 'test/unit' class ATest < Test::Unit::TestCase def test_failure - fail "This test is failing!!!" + fail 'This test is failing!!!' end end diff --git a/test/new_relic/agent/agent/connect_test.rb b/test/new_relic/agent/agent/connect_test.rb index be39dd51f3..b879193e07 100644 --- a/test/new_relic/agent/agent/connect_test.rb +++ b/test/new_relic/agent/agent/connect_test.rb @@ -22,7 +22,7 @@ def setup @stats_engine = NewRelic::Agent::StatsEngine.new server = NewRelic::Control::Server.new('localhost', 30303) @service = NewRelic::Agent::NewRelicService.new('abcdef', server) - NewRelic::Agent.instance.service = @service + NewRelic::Agent.instance.instance_variable_set(:@service, @service) NewRelic::Agent.reset_config end @@ -40,22 +40,22 @@ def [](key) def test_should_connect_if_pending @connect_state = :pending - assert_predicate(self, :should_connect?, "should attempt to connect if pending") + assert_predicate(self, :should_connect?, 'should attempt to connect if pending') end def test_should_not_connect_if_disconnected @connect_state = :disconnected - refute should_connect?, "should not attempt to connect if force disconnected" + refute should_connect?, 'should not attempt to connect if force disconnected' end def test_should_connect_if_forced @connect_state = :disconnected - assert(should_connect?(true), "should connect if forced") + assert(should_connect?(true), 'should connect if forced') @connect_state = :connected - assert(should_connect?(true), "should connect if forced") + assert(should_connect?(true), 'should connect if forced') end def test_increment_retry_period @@ -74,17 +74,17 @@ def test_disconnect end def test_log_error - error = StandardError.new("message") + error = StandardError.new('message') expects_logging(:error, - includes("Error establishing connection with New Relic Service"), \ + includes('Error establishing connection with New Relic Service'), \ instance_of(StandardError)) log_error(error) end def test_handle_license_error - error = mock(:message => "error message") + error = mock(:message => 'error message') self.expects(:disconnect).once handle_license_error(error) end @@ -109,12 +109,6 @@ def test_configure_transaction_tracer_server_disabled end end - def test_apdex_f - with_config(:apdex_t => 10) do - assert_equal 40, apdex_f - end - end - def test_set_sql_recording_default with_config(:'transaction_tracer.record_sql' => 'obfuscated') do assert_equal(:obfuscated, NewRelic::Agent::Database.record_sql_method) @@ -147,9 +141,9 @@ def test_set_sql_recording_falsy def test_connect_gets_config NewRelic::Agent.manual_start - NewRelic::Agent.instance.service = default_service( + NewRelic::Agent.instance.instance_variable_set(:@service, default_service( :connect => {'agent_run_id' => 23, 'config' => 'a lot'} - ) + )) response = NewRelic::Agent.agent.connect_to_server @@ -196,12 +190,12 @@ def test_connect_memoizes_event_harvest_config def test_logging_collector_messages NewRelic::Agent.manual_start - NewRelic::Agent.instance.service = default_service( + NewRelic::Agent.instance.instance_variable_set(:@service, default_service( :connect => { 'messages' => [{'message' => 'beep boop', 'level' => 'INFO'}, {'message' => 'ha cha cha', 'level' => 'WARN'}] } - ) + )) expects_logging(:info, 'beep boop') expects_logging(:warn, 'ha cha cha') @@ -213,7 +207,7 @@ def test_logging_collector_messages def test_environment_for_connect assert environment_for_connect.detect { |(k, _)| k == 'Gems' - }, "expected connect_settings to include gems from environment" + }, 'expected connect_settings to include gems from environment' end def test_environment_for_connect_negative diff --git a/test/new_relic/agent/agent/start_test.rb b/test/new_relic/agent/agent/start_test.rb index 127a505c6a..1a6e025942 100644 --- a/test/new_relic/agent/agent/start_test.rb +++ b/test/new_relic/agent/agent/start_test.rb @@ -10,17 +10,17 @@ class NewRelic::Agent::Agent::StartTest < Minitest::Test include NewRelic::Agent::AgentHelpers::SpecialStartup def setup - @harvester = stub("dummy harvester") - @harvest_samplers = stub("dummy sampler collection") + @harvester = stub('dummy harvester') + @harvest_samplers = stub('dummy sampler collection') end def test_already_started_positive dummy_logger = mock - dummy_logger.expects(:error).with("Agent Started Already!") + dummy_logger.expects(:error).with('Agent Started Already!') NewRelic::Agent.stubs(:logger).returns(dummy_logger) self.expects(:started?).returns(true) - assert_predicate self, :already_started?, "should have already started" + assert_predicate self, :already_started?, 'should have already started' end def test_already_started_negative diff --git a/test/new_relic/agent/agent_logger_test.rb b/test/new_relic/agent/agent_logger_test.rb index 473ea2f79f..c805308ce5 100644 --- a/test/new_relic/agent/agent_logger_test.rb +++ b/test/new_relic/agent/agent_logger_test.rb @@ -11,8 +11,8 @@ class AgentLoggerTest < Minitest::Test def setup NewRelic::Agent.config.add_config_for_testing( - :log_file_path => "log/", - :log_file_name => "testlog.log", + :log_file_path => 'log/', + :log_file_name => 'testlog.log', :log_level => :info ) end @@ -40,7 +40,7 @@ def test_initializes_from_config def test_initializes_from_override override_logger = Logger.new('/dev/null') - logger = NewRelic::Agent::AgentLogger.new("", override_logger) + logger = NewRelic::Agent::AgentLogger.new('', override_logger) assert_equal override_logger, logger.instance_variable_get(:@log) end @@ -49,7 +49,7 @@ def test_forwards_calls_to_logger logger = create_basic_logger LEVELS.each do |level| - logger.send(level, "Boo!") + logger.send(level, 'Boo!') end assert_logged(/FATAL/, @@ -62,7 +62,7 @@ def test_forwards_calls_to_logger_with_multiple_arguments logger = create_basic_logger LEVELS.each do |level| - logger.send(level, "What", "up?") + logger.send(level, 'What', 'up?') end assert_logged(/FATAL/, /FATAL/, @@ -75,7 +75,7 @@ def test_forwards_calls_to_logger_once logger = create_basic_logger LEVELS.each do |level| - logger.send(:log_once, level, :special_key, "Special!") + logger.send(:log_once, level, :special_key, 'Special!') end assert_logged(/Special/) @@ -118,7 +118,7 @@ def test_maps_log_levels assert_equal Logger::INFO, NewRelic::Agent::AgentLogger.log_level_for(:info) assert_equal Logger::DEBUG, NewRelic::Agent::AgentLogger.log_level_for(:debug) - assert_equal Logger::INFO, NewRelic::Agent::AgentLogger.log_level_for("") + assert_equal Logger::INFO, NewRelic::Agent::AgentLogger.log_level_for('') assert_equal Logger::INFO, NewRelic::Agent::AgentLogger.log_level_for(:unknown) end @@ -127,7 +127,7 @@ def test_sets_log_level override_logger = Logger.new($stderr) override_logger.level = Logger::FATAL - NewRelic::Agent::AgentLogger.new("", override_logger) + NewRelic::Agent::AgentLogger.new('', override_logger) assert_equal Logger::DEBUG, override_logger.level end @@ -160,7 +160,7 @@ def test_log_to_stdout_based_on_config def test_startup_purges_memory_logger LEVELS.each do |level| - ::NewRelic::Agent::StartupLogger.instance.send(level, "boo!") + ::NewRelic::Agent::StartupLogger.instance.send(level, 'boo!') end create_basic_logger @@ -175,7 +175,7 @@ def test_passing_exceptions_only_logs_the_message_at_levels_higher_than_debug logger = create_basic_logger begin - raise "Something bad happened" + raise 'Something bad happened' rescue => err logger.error(err) end @@ -188,7 +188,7 @@ def test_passing_exceptions_logs_the_backtrace_at_debug_level logger = create_basic_logger begin - raise "Something bad happened" + raise 'Something bad happened' rescue => err logger.error(err) end @@ -202,7 +202,7 @@ def test_default_format_contains_full_year with_config(:log_level => :debug) do logger = create_basic_logger - logger.info("The nice thing about standards is that you have so many to choose from. -- ast") + logger.info('The nice thing about standards is that you have so many to choose from. -- ast') assert_logged(/#{Date.today.strftime("%Y-%m-%d")}/) end @@ -212,7 +212,7 @@ def test_format_message_allows_nil_backtrace with_config(:log_level => :debug) do logger = create_basic_logger - e = Exception.new("Look Ma, no backtrace!") + e = Exception.new('Look Ma, no backtrace!') assert_nil(e.backtrace) logger.error(e) @@ -225,7 +225,7 @@ def test_format_message_allows_nil_backtrace def test_log_exception_logs_backtrace_at_same_level_as_message_by_default logger = create_basic_logger - e = Exception.new("howdy") + e = Exception.new('howdy') e.set_backtrace(%w[wiggle wobble topple]) logger.log_exception(:info, e) @@ -237,7 +237,7 @@ def test_log_exception_logs_backtrace_at_same_level_as_message_by_default def test_log_exception_logs_backtrace_at_explicitly_specified_level logger = create_basic_logger - e = Exception.new("howdy") + e = Exception.new('howdy') e.set_backtrace(%w[wiggle wobble topple]) logger.log_exception(:warn, e, :info) @@ -297,7 +297,7 @@ def debug; end def test_should_cache_hostname NewRelic::Agent::Hostname.instance_variable_set(:@hostname, nil) - hostname = String.new('cachey-mccaherson') + hostname = +'cachey-mccaherson' Socket.expects(:gethostname).once.returns(hostname) logger = create_basic_logger logger.warn('one') @@ -323,7 +323,7 @@ def test_should_not_evaluate_blocks_unless_log_level_is_high_enough def test_should_allow_blocks_that_return_a_single_string logger = create_basic_logger - logger.warn { "Surely you jest!" } + logger.warn { 'Surely you jest!' } assert_logged(/WARN : Surely you jest!/) end @@ -331,7 +331,7 @@ def test_should_allow_blocks_that_return_a_single_string def test_should_allow_blocks_that_return_an_array logger = create_basic_logger logger.warn do - ["You must be joking!", "You can't be serious!"] + ['You must be joking!', "You can't be serious!"] end assert_logged( @@ -353,15 +353,15 @@ def test_can_overwrite_log_formatter def test_clear_already_logged logger = create_basic_logger - logger.log_once(:warn, :positive, "thoughts") - logger.log_once(:warn, :positive, "thoughts") + logger.log_once(:warn, :positive, 'thoughts') + logger.log_once(:warn, :positive, 'thoughts') - assert_logged "thoughts" + assert_logged 'thoughts' logger.clear_already_logged - logger.log_once(:warn, :positive, "thoughts") + logger.log_once(:warn, :positive, 'thoughts') - assert_logged "thoughts", "thoughts" + assert_logged 'thoughts', 'thoughts' end def test_doesnt_write_log_event_aggregator @@ -374,7 +374,7 @@ def test_doesnt_write_log_event_aggregator _, logs = NewRelic::Agent.agent.log_event_aggregator.harvest! - assert_empty logs.select { |log| log.last["message"].include?(message) } + assert_empty logs.select { |log| log.last['message'].include?(message) } end end @@ -388,7 +388,7 @@ def test_doesnt_write_log_event_aggregator_with_null_logger _, logs = NewRelic::Agent.agent.log_event_aggregator.harvest! - assert_empty logs.select { |log| log.last["message"].include?(message) } + assert_empty logs.select { |log| log.last['message'].include?(message) } end end @@ -403,7 +403,7 @@ def logged_lines def create_basic_logger @logdev = ArrayLogDevice.new override_logger = Logger.new(@logdev) - NewRelic::Agent::AgentLogger.new("", override_logger) + NewRelic::Agent::AgentLogger.new('', override_logger) end def with_squelched_stdout diff --git a/test/new_relic/agent/agent_test.rb b/test/new_relic/agent/agent_test.rb index a0de3fee8f..ca8c183341 100644 --- a/test/new_relic/agent/agent_test.rb +++ b/test/new_relic/agent/agent_test.rb @@ -15,11 +15,11 @@ def setup @agent = NewRelic::Agent::Agent.new NewRelic::Agent.agent = @agent - @agent.service = default_service - @agent.agent_command_router.stubs(:new_relic_service).returns(@agent.service) + @agent.instance_variable_set(:@service, default_service) + @agent.instance_variable_get(:@agent_command_router).stubs(:new_relic_service).returns(@agent.service) @agent.stubs(:start_worker_thread) - @config = {:license_key => "a" * 40} + @config = {:license_key => 'a' * 40} NewRelic::Agent.config.add_config_for_testing(@config) end @@ -48,7 +48,7 @@ def test_after_fork_should_not_collect_environment_report @agent.stubs(:in_resque_child_process?).returns(false) @agent.after_fork - refute_nil @agent.environment_report + refute_nil @agent.instance_variable_get(:@environment_report) end end @@ -81,7 +81,7 @@ def test_after_fork_should_replace_stats_engine @agent.after_fork(:report_to_channel => 123) - refute_equal old_engine, @agent.stats_engine, "Still got our old engine around!" + refute_equal old_engine, @agent.stats_engine, 'Still got our old engine around!' end end @@ -90,13 +90,13 @@ def test_after_fork_should_reset_errors_collected @agent.stubs(:connected?).returns(true) errors = [] - errors << NewRelic::NoticedError.new("", {}, Exception.new("boo")) + errors << NewRelic::NoticedError.new('', {}, Exception.new('boo')) @agent.merge_data_for_endpoint(:error_data, errors) @agent.after_fork(:report_to_channel => 123) errors = @agent.error_collector.error_trace_aggregator.harvest! - assert_equal 0, errors.length, "Still got errors collected in parent" + assert_equal 0, errors.length, 'Still got errors collected in parent' end end @@ -115,7 +115,7 @@ def test_after_fork_should_prevent_further_thread_restart_attempts @agent.disconnect @agent.after_fork - refute @agent.harvester.needs_restart? + refute @agent.instance_variable_get(:@harvester).needs_restart? end end @@ -128,7 +128,7 @@ def @agent.setup_and_start_agent(*_) # This is a hack to make the race condition that we're trying to test # for more likely for the purposes of this test. - harvester = @agent.harvester + harvester = @agent.instance_variable_get(:@harvester) def harvester.mark_started sleep(0.01) super @@ -190,7 +190,7 @@ def test_harvest_and_send_transaction_traces_merges_back_on_failure traces = [mock('tt1'), mock('tt2')] @agent.transaction_sampler.expects(:harvest!).returns(traces) - @agent.service.stubs(:transaction_sample_data).raises("wat") + @agent.service.stubs(:transaction_sample_data).raises('wat') @agent.transaction_sampler.expects(:merge!).with(traces) @agent.send(:harvest_and_send_transaction_traces) @@ -252,7 +252,7 @@ def test_check_for_and_handle_agent_commands_with_error def test_harvest_and_send_for_agent_commands @agent.service.expects(:profile_data).with(any_parameters) - @agent.agent_command_router.stubs(:harvest!).returns({:profile_data => [Object.new]}) + @agent.instance_variable_get(:@agent_command_router).stubs(:harvest!).returns({:profile_data => [Object.new]}) @agent.send(:harvest_and_send_for_agent_commands) end @@ -282,7 +282,7 @@ def test_merge_data_traces def test_merge_data_for_endpoint_abides_by_error_queue_limit errors = [] - 40.times { |i| errors << NewRelic::NoticedError.new("", {}, Exception.new("boo #{i}")) } + 40.times { |i| errors << NewRelic::NoticedError.new('', {}, Exception.new("boo #{i}")) } @agent.merge_data_for_endpoint(:error_data, errors) @@ -292,7 +292,7 @@ def test_merge_data_for_endpoint_abides_by_error_queue_limit # This method should NOT increment error counts, since that has already # been counted in the child - assert_metrics_not_recorded "Errors/all" + assert_metrics_not_recorded 'Errors/all' end def test_harvest_and_send_analytic_event_data_merges_in_samples_on_failure @@ -558,7 +558,7 @@ def test_defer_start_if_no_application_name_configured end logmsg = logdev.array.first.delete("\n") - refute @agent.started?, "agent was started" + refute @agent.started?, 'agent was started' assert_match(/No application name configured/i, logmsg) end @@ -696,7 +696,7 @@ def test_untraced_graceful_disconnect_logs_errors end def test_revert_to_default_configuration_removes_manual_and_server_source - manual_source = NewRelic::Agent::Configuration::ManualSource.new(:manual => "source") + manual_source = NewRelic::Agent::Configuration::ManualSource.new(:manual => 'source') Agent.config.replace_or_add_config(manual_source) server_config = NewRelic::Agent::Configuration::ServerSource.new({}) @@ -717,13 +717,13 @@ def test_revert_to_default_configuration_removes_manual_and_server_source def test_log_ignore_url_regexes with_config(:rules => {:ignore_url_regexes => %w[foo bar baz]}) do - expects_logging(:info, includes("/foo/, /bar/, /baz/")) + expects_logging(:info, includes('/foo/, /bar/, /baz/')) @agent.log_ignore_url_regexes end end def test_force_restart_logs_message - @agent.service = nil + @agent.instance_variable_set(:@service, nil) @agent.stubs(:sleep) log_results = with_array_logger(:debug) do @@ -737,7 +737,7 @@ def test_force_restart_logs_message end def test_force_disconnect_logs_message - @agent.service = nil + @agent.instance_variable_set(:@service, nil) @agent.stubs(:sleep) log_results = with_array_logger(:debug) do @@ -775,8 +775,8 @@ def test_exit_connecting_worker_thread # Write HTTP response with partial gzip content, leaving connection open. gzip = Zlib.gzip('Hello World!') headers = [ - "HTTP/1.1 200", - "Content-Encoding: gzip", + 'HTTP/1.1 200', + 'Content-Encoding: gzip', "Content-Length: #{gzip.length}", gzip.byteslice(0..-2) ].join("\r\n") @@ -785,10 +785,10 @@ def test_exit_connecting_worker_thread end @agent.unstub(:start_worker_thread) - @agent.service = NewRelic::Agent::NewRelicService.new( + @agent.instance_variable_set(:@service, NewRelic::Agent::NewRelicService.new( 'license-key', NewRelic::Control::Server.new('localhost', server.addr[1]) - ) + )) @agent.service.stubs(:setup_connection_for_ssl) @agent.setup_and_start_agent diff --git a/test/new_relic/agent/api_tests/datastore_api_test.rb b/test/new_relic/agent/api_tests/datastore_api_test.rb index 6f56484995..f6616f3739 100644 --- a/test/new_relic/agent/api_tests/datastore_api_test.rb +++ b/test/new_relic/agent/api_tests/datastore_api_test.rb @@ -31,7 +31,7 @@ def setup port_path_or_id: params['port_path_or_id'], database_name: params['database_name'] ) - segment.notice_sql("select * from foo") + segment.notice_sql('select * from foo') advance_process_time 2.0 segment.finish end diff --git a/test/new_relic/agent/attribute_filter_test.rb b/test/new_relic/agent/attribute_filter_test.rb index 796b221f69..0465500e97 100644 --- a/test/new_relic/agent/attribute_filter_test.rb +++ b/test/new_relic/agent/attribute_filter_test.rb @@ -9,9 +9,9 @@ module NewRelic::Agent class AttributeFilterTest < Minitest::Test - test_cases = load_cross_agent_test("attribute_configuration") + test_cases = load_cross_agent_test('attribute_configuration') test_cases.each do |test_case| - define_method("test_#{test_case['testname'].gsub(/\W/, "_")}") do + define_method("test_#{test_case['testname'].gsub(/\W/, '_')}") do with_config(test_case['config']) do filter = AttributeFilter.new(NewRelic::Agent.config) @@ -23,7 +23,7 @@ class AttributeFilterTest < Minitest::Test expected_destinations = to_bitfield(test_case['expected_destinations']) assert_equal(to_names(expected_destinations), to_names(actual_destinations), - PP.pp(test_case, String.new('')) + PP.pp(filter.rules, String.new(''))) + PP.pp(test_case, (+'')) + PP.pp(filter.rules, (+''))) end end end diff --git a/test/new_relic/agent/attribute_processing_test.rb b/test/new_relic/agent/attribute_processing_test.rb index 69862cc3bb..16a983af35 100644 --- a/test/new_relic/agent/attribute_processing_test.rb +++ b/test/new_relic/agent/attribute_processing_test.rb @@ -7,22 +7,22 @@ class AttributeProcessingTest < Minitest::Test def test_flatten_and_coerce_handles_nested_hashes - params = {"user" => - {"addresses" => + params = {'user' => + {'addresses' => [ - {"street" => "123 Street", "city" => "City", "state" => "ST", "zip" => "12345"}, - {"street" => "123 Blvd", "city" => "City2", "state" => "ST2", "zip" => "54321"} + {'street' => '123 Street', 'city' => 'City', 'state' => 'ST', 'zip' => '12345'}, + {'street' => '123 Blvd', 'city' => 'City2', 'state' => 'ST2', 'zip' => '54321'} ]}} expected = { - "request.parameters.user.addresses.0.street" => "123 Street", - "request.parameters.user.addresses.0.city" => "City", - "request.parameters.user.addresses.0.state" => "ST", - "request.parameters.user.addresses.0.zip" => "12345", - "request.parameters.user.addresses.1.street" => "123 Blvd", - "request.parameters.user.addresses.1.city" => "City2", - "request.parameters.user.addresses.1.state" => "ST2", - "request.parameters.user.addresses.1.zip" => "54321" + 'request.parameters.user.addresses.0.street' => '123 Street', + 'request.parameters.user.addresses.0.city' => 'City', + 'request.parameters.user.addresses.0.state' => 'ST', + 'request.parameters.user.addresses.0.zip' => '12345', + 'request.parameters.user.addresses.1.street' => '123 Blvd', + 'request.parameters.user.addresses.1.city' => 'City2', + 'request.parameters.user.addresses.1.state' => 'ST2', + 'request.parameters.user.addresses.1.zip' => '54321' } actual = NewRelic::Agent::AttributeProcessing.flatten_and_coerce(params, 'request.parameters') @@ -32,15 +32,15 @@ def test_flatten_and_coerce_handles_nested_hashes def test_flatten_and_coerce_coerces_values params = { - "v1" => Class.new, - "v2" => :symbol, - "v3" => 1.01 + 'v1' => Class.new, + 'v2' => :symbol, + 'v3' => 1.01 } expected = { - "request.parameters.v1" => "#", - "request.parameters.v2" => "symbol", - "request.parameters.v3" => 1.01 + 'request.parameters.v1' => '#', + 'request.parameters.v2' => 'symbol', + 'request.parameters.v3' => 1.01 } actual = NewRelic::Agent::AttributeProcessing.flatten_and_coerce(params, 'request.parameters') @@ -52,8 +52,8 @@ def test_prefix_optional_for_flatten_and_coerce params = {:foo => {:bar => %w[v1 v2]}} expected = { - "foo.bar.0" => "v1", - "foo.bar.1" => "v2" + 'foo.bar.0' => 'v1', + 'foo.bar.1' => 'v2' } actual = NewRelic::Agent::AttributeProcessing.flatten_and_coerce(params) @@ -65,8 +65,8 @@ def test_prefix_optional_for_flatten_and_coerce_with_initial_array_argument params = [:foo => {:bar => %w[v1 v2]}] expected = { - "0.foo.bar.0" => "v1", - "0.foo.bar.1" => "v2" + '0.foo.bar.0' => 'v1', + '0.foo.bar.1' => 'v2' } actual = NewRelic::Agent::AttributeProcessing.flatten_and_coerce(params) @@ -77,7 +77,7 @@ def test_prefix_optional_for_flatten_and_coerce_with_initial_array_argument def test_flatten_and_coerce_replaces_empty_hash_with_string_representation params = {:foo => {:bar => {}}} - expected = {"foo.bar" => "{}"} + expected = {'foo.bar' => '{}'} actual = NewRelic::Agent::AttributeProcessing.flatten_and_coerce(params) @@ -87,7 +87,7 @@ def test_flatten_and_coerce_replaces_empty_hash_with_string_representation def test_flatten_and_coerce_replaces_empty_array_with_string_representation params = {:foo => {:bar => []}} - expected = {"foo.bar" => "[]"} + expected = {'foo.bar' => '[]'} actual = NewRelic::Agent::AttributeProcessing.flatten_and_coerce(params) @@ -136,7 +136,7 @@ def test_flatten_and_coerce_turns_nan_or_infinity_into_null_and_then_dropped end def test_flatten_and_coerce_logs_warning_with_unexpected_arguments - expects_logging(:warn, all_of(includes("Unexpected object"), includes("flatten_and_coerce"))) + expects_logging(:warn, all_of(includes('Unexpected object'), includes('flatten_and_coerce'))) NewRelic::Agent::AttributeProcessing.flatten_and_coerce(Object.new) end @@ -146,7 +146,7 @@ def test_flatten_and_coerce_calls_a_block_key_and_value_when_provided NewRelic::Agent::AttributeProcessing.flatten_and_coerce(params) { |k, v| yielded[k] = v } - expected = {"foo.bar.0" => "qux", "foo.bar.1" => "quux"} + expected = {'foo.bar.0' => 'qux', 'foo.bar.1' => 'quux'} assert_equal expected, yielded end diff --git a/test/new_relic/agent/audit_logger_test.rb b/test/new_relic/agent/audit_logger_test.rb index 6c933aa37b..bc418e2d98 100644 --- a/test/new_relic/agent/audit_logger_test.rb +++ b/test/new_relic/agent/audit_logger_test.rb @@ -10,7 +10,7 @@ class AuditLoggerTest < Minitest::Test def setup NewRelic::Agent.config.add_config_for_testing(:'audit_log.enabled' => true) - @uri = "http://really.notreal" + @uri = 'http://really.notreal' @marshaller = NewRelic::Agent::NewRelicService::Marshaller.new @dummy_data = { 'foo' => [1, 2, 3], @@ -51,9 +51,9 @@ def read_log_body def test_never_setup_if_disabled with_config(:'audit_log.enabled' => false) do logger = NewRelic::Agent::AuditLogger.new - logger.log_request(@uri, "hi there", @marshaller) + logger.log_request(@uri, 'hi there', @marshaller) - refute logger.setup?, "Expected logger to not have been setup" + refute logger.setup?, 'Expected logger to not have been setup' end end @@ -62,13 +62,13 @@ def test_never_prepare_if_disabled logger = NewRelic::Agent::AuditLogger.new marshaller = NewRelic::Agent::NewRelicService::Marshaller.new marshaller.expects(:prepare).never - logger.log_request(@uri, "hi there", @marshaller) + logger.log_request(@uri, 'hi there', @marshaller) end end def test_log_formatter NewRelic::Agent::Hostname.instance_variable_set(:@hostname, nil) - Socket.stubs(:gethostname).returns(String.new('dummyhost')) + Socket.stubs(:gethostname).returns((+'dummyhost')) formatter = NewRelic::Agent::AuditLogger.new.create_log_formatter time = '2012-01-01 00:00:00' msg = 'hello' @@ -79,9 +79,9 @@ def test_log_formatter end def test_log_formatter_to_stdout - with_config(:'audit_log.path' => "STDOUT") do + with_config(:'audit_log.path' => 'STDOUT') do NewRelic::Agent::Hostname.instance_variable_set(:@hostname, nil) - Socket.stubs(:gethostname).returns(String.new('dummyhost')) + Socket.stubs(:gethostname).returns((+'dummyhost')) formatter = NewRelic::Agent::AuditLogger.new.create_log_formatter time = '2012-01-01 00:00:00' msg = 'hello' @@ -114,7 +114,7 @@ def test_setup_logger_creates_null_logger_when_ensure_path_fails def test_log_request_captures_system_call_errors logger = NewRelic::Agent::AuditLogger.new dummy_sink = StringIO.new - dummy_sink.stubs(:write).raises(SystemCallError, "nope") + dummy_sink.stubs(:write).raises(SystemCallError, 'nope') logger.stubs(:ensure_log_path).returns(dummy_sink) # In 1.9.2 and later, Logger::LogDevice#write captures any errors during @@ -164,7 +164,7 @@ def test_filters_endpoints def test_should_cache_hostname NewRelic::Agent::Hostname.instance_variable_set(:@hostname, nil) - hostname = String.new('cachey-mccaherson') + hostname = +'cachey-mccaherson' Socket.expects(:gethostname).once.returns(hostname) setup_fake_logger 3.times do @@ -177,7 +177,7 @@ def test_should_cache_hostname TRAPPABLE_ERRORS = [ StandardError.new, SystemStackError.new, - SystemCallError.new("Syscalls FTW") + SystemCallError.new('Syscalls FTW') ] TRAPPABLE_ERRORS.each do |error| @@ -223,7 +223,7 @@ def test_doesnt_write_log_event_aggregator logger.log_request(@uri, @dummy_data, @marshaller) _, logs = NewRelic::Agent.agent.log_event_aggregator.harvest! - audits = logs.select { |log| log.last["message"].include?("REQUEST") } + audits = logs.select { |log| log.last['message'].include?('REQUEST') } assert_empty audits end @@ -231,7 +231,7 @@ def test_doesnt_write_log_event_aggregator def capturing_stdout orig = $stdout.dup - output = String.new('') + output = +'' $stdout = StringIO.new(output) yield output diff --git a/test/new_relic/agent/autostart_test.rb b/test/new_relic/agent/autostart_test.rb index 1aadcea070..76e47191a2 100644 --- a/test/new_relic/agent/autostart_test.rb +++ b/test/new_relic/agent/autostart_test.rb @@ -20,7 +20,7 @@ def test_agent_wont_autostart_if_RAILS_CONSOLE_constant_is_defined Rails.send(:remove_const, :Console) end else - puts "Skipping `test_agent_wont_autostart_if_RAILS_CONSOLE_constant_is_defined` in #{File.basename(__FILE__)} because Rails is unavailable" if ENV["VERBOSE_TEST_OUTPUT"] + puts "Skipping `test_agent_wont_autostart_if_RAILS_CONSOLE_constant_is_defined` in #{File.basename(__FILE__)} because Rails is unavailable" if ENV['VERBOSE_TEST_OUTPUT'] end def test_agent_will_autostart_if_global_CONSOLE_constant_is_defined @@ -57,7 +57,7 @@ def test_agent_wont_start_if_dollar_0_is_irb MY_CONST = true def test_denylisted_constants_can_be_configured - with_config('autostart.denylisted_constants' => "IRB,::AutostartTest::MY_CONST") do + with_config('autostart.denylisted_constants' => 'IRB,::AutostartTest::MY_CONST') do refute ::NewRelic::Agent::Autostart.agent_should_start?, "Agent shouldn't autostart when environment contains denylisted constant" end end diff --git a/test/new_relic/agent/collector_hostname_test.rb b/test/new_relic/agent/collector_hostname_test.rb index 2cc3fbac7b..9538415d41 100644 --- a/test/new_relic/agent/collector_hostname_test.rb +++ b/test/new_relic/agent/collector_hostname_test.rb @@ -6,10 +6,10 @@ module NewRelic::Agent class CollectorHostname < Minitest::Test - test_cases = load_cross_agent_test("collector_hostname") + test_cases = load_cross_agent_test('collector_hostname') test_cases.each do |test_case| - define_method("test_#{test_case['name']}".tr(" ", "_")) do + define_method("test_#{test_case['name']}".tr(' ', '_')) do # The configuration manager checks the following places to # determine the collector host: # diff --git a/test/new_relic/agent/collector_response_code_test.rb b/test/new_relic/agent/collector_response_code_test.rb index b37e10a0d7..526ba8d542 100644 --- a/test/new_relic/agent/collector_response_code_test.rb +++ b/test/new_relic/agent/collector_response_code_test.rb @@ -14,7 +14,7 @@ def setup end def stub_service(response) - conn = stub("http_connection", request: response) + conn = stub('http_connection', request: response) @agent.service.stubs(:http_connection).returns(conn) end diff --git a/test/new_relic/agent/commands/agent_command_router_test.rb b/test/new_relic/agent/commands/agent_command_router_test.rb index e74fd7ae91..fa87b96a47 100644 --- a/test/new_relic/agent/commands/agent_command_router_test.rb +++ b/test/new_relic/agent/commands/agent_command_router_test.rb @@ -8,25 +8,25 @@ class AgentCommandRouterTest < Minitest::Test DEFAULT_ARGS = { - "profile_id" => 42 + 'profile_id' => 42 } BAZZLE_ID = 123 BAZZLE = [BAZZLE_ID, { - "name" => "bazzle", - "arguments" => DEFAULT_ARGS + 'name' => 'bazzle', + 'arguments' => DEFAULT_ARGS }] BOOM_ID = 666 BOOM = [BOOM_ID, { - "name" => "boom", - "arguments" => DEFAULT_ARGS + 'name' => 'boom', + 'arguments' => DEFAULT_ARGS }] UNRECOGNIZED_ID = 42 UNRECOGNIZED = [UNRECOGNIZED_ID, { - "name" => "JIBBERISH", - "arguments" => {} + 'name' => 'JIBBERISH', + 'arguments' => {} }] attr_reader :service, :agent_commands, :calls @@ -38,12 +38,12 @@ def setup @events = NewRelic::Agent::EventListener.new @agent_commands = NewRelic::Agent::Commands::AgentCommandRouter.new(@events) - @agent_commands.handlers["bazzle"] = proc { |args| handle_bazzle_command(args) } - @agent_commands.handlers["boom"] = proc { |args| handle_boom_command(args) } + @agent_commands.handlers['bazzle'] = proc { |args| handle_bazzle_command(args) } + @agent_commands.handlers['boom'] = proc { |args| handle_boom_command(args) } end def teardown - agent_commands.backtrace_service.worker_thread.join if agent_commands.backtrace_service.worker_thread + agent_commands.backtrace_service.worker_thread&.join end # Helpers for DataContainerTests @@ -59,7 +59,7 @@ def max_data_items def populate_container(container, n) start_profile('duration' => 1.0) advance_process_time(1.1) - agent_commands.backtrace_service.worker_thread.join if agent_commands.backtrace_service.worker_thread + agent_commands.backtrace_service.worker_thread&.join end # General command routing @@ -82,7 +82,7 @@ def test_check_for_and_handle_agent_commands_generates_results def test_check_for_and_handle_agent_commands_dispatches_with_error service.stubs(:get_agent_commands).returns([BOOM]) - service.expects(:agent_command_results).with({BOOM_ID.to_s => {"error" => "BOOOOOM"}}) + service.expects(:agent_command_results).with({BOOM_ID.to_s => {'error' => 'BOOOOOM'}}) agent_commands.check_for_and_handle_agent_commands end @@ -90,7 +90,7 @@ def test_check_for_and_handle_agent_commands_dispatches_with_error def test_check_for_and_handle_agent_commands_allows_multiple service.stubs(:get_agent_commands).returns([BAZZLE, BOOM]) service.expects(:agent_command_results).with({BAZZLE_ID.to_s => {}, - BOOM_ID.to_s => {"error" => "BOOOOOM"}}) + BOOM_ID.to_s => {'error' => 'BOOOOOM'}}) agent_commands.check_for_and_handle_agent_commands end @@ -184,7 +184,7 @@ def handle_bazzle_command(command) end def handle_boom_command(command) - raise NewRelic::Agent::Commands::AgentCommandRouter::AgentCommandError.new("BOOOOOM") + raise NewRelic::Agent::Commands::AgentCommandRouter::AgentCommandError.new('BOOOOOM') end def start_profile(args = {}) diff --git a/test/new_relic/agent/commands/agent_command_test.rb b/test/new_relic/agent/commands/agent_command_test.rb index b79eb61582..740cb161cb 100644 --- a/test/new_relic/agent/commands/agent_command_test.rb +++ b/test/new_relic/agent/commands/agent_command_test.rb @@ -9,11 +9,11 @@ module NewRelic::Agent::Commands class AgentCommandTest < Minitest::Test ID = 123 NAME = 'nuke_it_from_orbit' - ARGUMENTS = {"profile_id" => 42} + ARGUMENTS = {'profile_id' => 42} NUKE_IT_FROM_ORBIT = [ID, { - "name" => NAME, - "arguments" => ARGUMENTS + 'name' => NAME, + 'arguments' => ARGUMENTS }] def test_destructures_name_from_collector_command diff --git a/test/new_relic/agent/commands/thread_profiler_session_test.rb b/test/new_relic/agent/commands/thread_profiler_session_test.rb index e92690333b..ab17e2a784 100644 --- a/test/new_relic/agent/commands/thread_profiler_session_test.rb +++ b/test/new_relic/agent/commands/thread_profiler_session_test.rb @@ -13,22 +13,22 @@ module ThreadProfilerSessionTestHelpers START = { - "profile_id" => 42, - "sample_period" => 0.02, - "duration" => 0.025, - "only_runnable_threads" => false, - "only_request_threads" => false, - "profile_agent_code" => false + 'profile_id' => 42, + 'sample_period' => 0.02, + 'duration' => 0.025, + 'only_runnable_threads' => false, + 'only_request_threads' => false, + 'profile_agent_code' => false } STOP = { - "profile_id" => 42, - "report_data" => true + 'profile_id' => 42, + 'report_data' => true } STOP_AND_DISCARD = { - "profile_id" => 42, - "report_data" => false + 'profile_id' => 42, + 'report_data' => false } def start_command diff --git a/test/new_relic/agent/configuration/default_source_test.rb b/test/new_relic/agent/configuration/default_source_test.rb index 009ef7b0c4..8ba3d4c5e6 100644 --- a/test/new_relic/agent/configuration/default_source_test.rb +++ b/test/new_relic/agent/configuration/default_source_test.rb @@ -101,7 +101,7 @@ def test_transform_for_returns_nil_for_settings_that_do_not_have_a_transform end def test_convert_to_list - result = DefaultSource.convert_to_list("Foo,Bar,Baz") + result = DefaultSource.convert_to_list('Foo,Bar,Baz') assert_equal %w[Foo Bar Baz], result end @@ -125,17 +125,17 @@ def test_rules_ignore_converts_comma_delimited_string_to_array end def test_config_search_paths_with_home - with_environment("HOME" => "/home") do + with_environment('HOME' => '/home') do paths = DefaultSource.config_search_paths.call() - assert_includes paths, "/home/.newrelic/newrelic.yml" - assert_includes paths, "/home/newrelic.yml" + assert_includes paths, '/home/.newrelic/newrelic.yml' + assert_includes paths, '/home/newrelic.yml' end end def test_config_search_path_in_warbler - with_environment("GEM_HOME" => "/some/path.jar!") do - assert_includes DefaultSource.config_search_paths.call(), "/some/path.jar!/path/config/newrelic.yml" + with_environment('GEM_HOME' => '/some/path.jar!') do + assert_includes DefaultSource.config_search_paths.call(), '/some/path.jar!/path/config/newrelic.yml' end end @@ -214,28 +214,28 @@ def test_all_settings_specify_whether_they_are_allowed_from_server end def test_host_correct_when_license_key_matches_identifier - with_config(license_key: "eu01xx65c637a29c3982469a3fe8d1982d002c4b") do - assert_equal "collector.eu01.nr-data.net", DefaultSource.host.call + with_config(license_key: 'eu01xx65c637a29c3982469a3fe8d1982d002c4b') do + assert_equal 'collector.eu01.nr-data.net', DefaultSource.host.call end - with_config(license_key: "gov01x69c637a29c3982469a3fe8d1982d002c4c") do - assert_equal "collector.gov01.nr-data.net", DefaultSource.host.call + with_config(license_key: 'gov01x69c637a29c3982469a3fe8d1982d002c4c') do + assert_equal 'collector.gov01.nr-data.net', DefaultSource.host.call end end def test_host_correct_with_license_key_not_matching_identifer - with_config(license_key: "08a2ad66c637a29c3982469a3fe8d1982d002c4a") do - assert_equal "collector.newrelic.com", DefaultSource.host.call + with_config(license_key: '08a2ad66c637a29c3982469a3fe8d1982d002c4a') do + assert_equal 'collector.newrelic.com', DefaultSource.host.call end end def test_api_host_us - with_config(license_key: "08a2ad66c637a29c3982469a3fe8d1982d002c4a") do + with_config(license_key: '08a2ad66c637a29c3982469a3fe8d1982d002c4a') do assert_equal 'rpm.newrelic.com', DefaultSource.api_host.call end end def test_api_host_eu - with_config(license_key: "eu01xx65c637a29c3982469a3fe8d1982d002c4b") do + with_config(license_key: 'eu01xx65c637a29c3982469a3fe8d1982d002c4b') do assert_equal 'rpm.eu.newrelic.com', DefaultSource.api_host.call end end diff --git a/test/new_relic/agent/configuration/dotted_hash_test.rb b/test/new_relic/agent/configuration/dotted_hash_test.rb index dcd2a2c25b..60cf23ed0c 100644 --- a/test/new_relic/agent/configuration/dotted_hash_test.rb +++ b/test/new_relic/agent/configuration/dotted_hash_test.rb @@ -25,13 +25,13 @@ def test_with_multiple_layers_of_nesting end def test_turns_keys_to_symbols - hash = DottedHash.new({"turtle" => {"turtle" => {"turtle" => 1}}}) + hash = DottedHash.new({'turtle' => {'turtle' => {'turtle' => 1}}}) assert_equal({:'turtle.turtle.turtle' => 1}, hash) end def test_to_hash - dotted = DottedHash.new({"turtle" => {"turtle" => {"turtle" => 1}}}) + dotted = DottedHash.new({'turtle' => {'turtle' => {'turtle' => 1}}}) hash = dotted.to_hash assert_instance_of(Hash, hash) diff --git a/test/new_relic/agent/configuration/environment_source_test.rb b/test/new_relic/agent/configuration/environment_source_test.rb index 52b8980a23..f5df94fc4d 100644 --- a/test/new_relic/agent/configuration/environment_source_test.rb +++ b/test/new_relic/agent/configuration/environment_source_test.rb @@ -121,13 +121,13 @@ def test_set_values_from_new_relic_environment_variables end def test_set_values_from_new_relic_environment_variables_warns_unknowns - ENV['NEWRELIC_DOESNT_USE_THIS_VALUE'] = "true" - expects_logging(:info, includes("NEWRELIC_DOESNT_USE_THIS_VALUE")) + ENV['NEWRELIC_DOESNT_USE_THIS_VALUE'] = 'true' + expects_logging(:info, includes('NEWRELIC_DOESNT_USE_THIS_VALUE')) @environment_source.set_values_from_new_relic_environment_variables end def test_set_values_from_new_relic_environment_variables_ignores_NEW_RELIC_LOG - ENV['NEW_RELIC_LOG'] = "STDOUT" + ENV['NEW_RELIC_LOG'] = 'STDOUT' expects_no_logging(:info) @environment_source.set_values_from_new_relic_environment_variables end diff --git a/test/new_relic/agent/configuration/manager_test.rb b/test/new_relic/agent/configuration/manager_test.rb index 2b183ca1f0..c44f94e7a4 100644 --- a/test/new_relic/agent/configuration/manager_test.rb +++ b/test/new_relic/agent/configuration/manager_test.rb @@ -220,7 +220,7 @@ def test_callback_evals_procs @manager.register_callback(:test) do |value| actual = value end - @manager.add_config_for_testing(:test => proc { "value" }) + @manager.add_config_for_testing(:test => proc { 'value' }) refute_equal actual.class, Proc, 'Callback returned Proc' end @@ -240,7 +240,7 @@ def test_callback_not_called_if_no_change end def test_finished_configuring - @manager.add_config_for_testing(:layer => "yo") + @manager.add_config_for_testing(:layer => 'yo') refute @manager.finished_configuring? @@ -261,9 +261,9 @@ def test_doesnt_notify_unless_finished called = false NewRelic::Agent.instance.events.subscribe(:initial_configuration_complete) { called = true } - @manager.add_config_for_testing(:fake => "config") + @manager.add_config_for_testing(:fake => 'config') @manager.replace_or_add_config(ManualSource.new(:manual => true)) - @manager.replace_or_add_config(YamlSource.new("", "test")) + @manager.replace_or_add_config(YamlSource.new('', 'test')) refute called end @@ -282,7 +282,7 @@ def test_stripped_exceptions_allowlist_contains_only_valid_exception_classes def test_should_log_when_applying log = with_array_logger(:debug) do - @manager.add_config_for_testing(:test => "asdf") + @manager.add_config_for_testing(:test => 'asdf') end log_lines = log.array @@ -291,7 +291,7 @@ def test_should_log_when_applying end def test_should_log_when_removing - config = {:test => "asdf"} + config = {:test => 'asdf'} @manager.add_config_for_testing(config) log = with_array_logger(:debug) do @@ -321,15 +321,15 @@ def test_high_security_source_addable assert_includes(@manager.config_classes_for_testing, SecurityPolicySource) end - load_cross_agent_test("labels").each do |testcase| + load_cross_agent_test('labels').each do |testcase| define_method("test_#{testcase['name']}") do - @manager.add_config_for_testing(:labels => testcase["labelString"]) + @manager.add_config_for_testing(:labels => testcase['labelString']) - assert_warning if testcase["warning"] + assert_warning if testcase['warning'] - assert_equal(testcase["expected"].sort_by { |h| h["label_type"] }, - @manager.parse_labels_from_string.sort_by { |h| h["label_type"] }, - "failed on #{testcase["name"]}") + assert_equal(testcase['expected'].sort_by { |h| h['label_type'] }, + @manager.parse_labels_from_string.sort_by { |h| h['label_type'] }, + "failed on #{testcase['name']}") end end @@ -342,7 +342,7 @@ def test_parse_labels_from_dictionary_with_hard_failure end def test_parse_labels_from_string_with_hard_failure - bad_string = String.new('baaaad') + bad_string = +'baaaad' bad_string.stubs(:strip).raises('Booom') @manager.add_config_for_testing(:labels => bad_string) @@ -363,14 +363,14 @@ def test_parse_labels_from_dictionary_applies_length_limits @manager.add_config_for_testing(:labels => {'K' * 256 => 'V' * 256}) expected = [{'label_type' => 'K' * 255, 'label_value' => 'V' * 255}] - expects_logging(:warn, includes("truncated")) + expects_logging(:warn, includes('truncated')) assert_parsed_labels(expected) end def test_parse_labels_from_dictionary_disallows_further_nested_hashes @manager.add_config_for_testing(:labels => { - "More Nesting" => {"Hahaha" => "Ha"} + 'More Nesting' => {'Hahaha' => 'Ha'} }) assert_warning @@ -379,7 +379,7 @@ def test_parse_labels_from_dictionary_disallows_further_nested_hashes def test_parse_labels_from_dictionary_allows_numerics @manager.add_config_for_testing(:labels => { - "the answer" => 42 + 'the answer' => 42 }) expected = [{'label_type' => 'the answer', 'label_value' => '42'}] @@ -389,8 +389,8 @@ def test_parse_labels_from_dictionary_allows_numerics def test_parse_labels_from_dictionary_allows_booleans @manager.add_config_for_testing(:labels => { - "truthy" => true, - "falsy" => false + 'truthy' => true, + 'falsy' => false }) expected = [ @@ -433,7 +433,7 @@ def test_prepend_key_absent_to_instrumentation_value_of with_config({}) do result = @manager.fetch(:'instrumentation.net_http') - assert_equal "auto", result + assert_equal 'auto', result end end @@ -441,7 +441,7 @@ def test_prepend_key_true_to_instrumentation_value_of with_config(:prepend_net_instrumentation => true) do result = @manager.fetch(:'instrumentation.net_http') - assert_equal "auto", result + assert_equal 'auto', result end end @@ -475,7 +475,7 @@ def test_apply_transformations_logs_error_if_transformation_fails bomb = proc { raise StandardError.new } @manager.stubs(:transform_from_default).returns(bomb) - expects_logging(:error, includes("Error applying transformation"), any_parameters) + expects_logging(:error, includes('Error applying transformation'), any_parameters) assert_raises StandardError do @manager.apply_transformations(:test_key, 'test_value') diff --git a/test/new_relic/agent/configuration/manual_source_test.rb b/test/new_relic/agent/configuration/manual_source_test.rb index 464512a81f..28936cfe27 100644 --- a/test/new_relic/agent/configuration/manual_source_test.rb +++ b/test/new_relic/agent/configuration/manual_source_test.rb @@ -7,10 +7,10 @@ module NewRelic::Agent::Configuration class ManualSourceTest < Minitest::Test def test_prepopulates_nested_keys - source = ManualSource.new({:outer => {:inner => "stuff"}}) + source = ManualSource.new({:outer => {:inner => 'stuff'}}) expected = { - :outer => {:inner => "stuff"}, - :'outer.inner' => "stuff" + :outer => {:inner => 'stuff'}, + :'outer.inner' => 'stuff' } assert_equal(expected, source) diff --git a/test/new_relic/agent/configuration/orphan_configuration_test.rb b/test/new_relic/agent/configuration/orphan_configuration_test.rb index e5e5874e49..6b86fb1da7 100644 --- a/test/new_relic/agent/configuration/orphan_configuration_test.rb +++ b/test/new_relic/agent/configuration/orphan_configuration_test.rb @@ -47,7 +47,7 @@ def test_all_default_source_config_keys_are_used_in_the_agent def test_documented_all_named_instrumentation_files non_test_files.each do |file| - next unless file.include?("new_relic/agent/instrumentation") + next unless file.include?('new_relic/agent/instrumentation') lines_in(file).each_with_index do |line, index| dependency = line.match(NAMED_DEPENDENCY_PATTERN) @@ -56,8 +56,8 @@ def test_documented_all_named_instrumentation_files disable_key = "disable_#{name}".to_sym instrumentation_key = "instrumentation.#{name}".to_sym - has_disable_key = !!NewRelic::Agent::Configuration::DEFAULTS[disable_key] - has_instrumentation_key = !!NewRelic::Agent::Configuration::DEFAULTS[instrumentation_key] + has_disable_key = !NewRelic::Agent::Configuration::DEFAULTS[disable_key].nil? + has_instrumentation_key = !NewRelic::Agent::Configuration::DEFAULTS[instrumentation_key].nil? assert has_instrumentation_key || has_disable_key, "#{file}:#{index + 1} - Document key `#{instrumentation_key}` found as name for instrumentation.\n" diff --git a/test/new_relic/agent/configuration/security_policy_source_test.rb b/test/new_relic/agent/configuration/security_policy_source_test.rb index 49c547bca2..144f17260a 100644 --- a/test/new_relic/agent/configuration/security_policy_source_test.rb +++ b/test/new_relic/agent/configuration/security_policy_source_test.rb @@ -179,18 +179,18 @@ def test_message_parameters_disabled def generate_security_policies(default: false, enabled: [], disabled: [], required: []) policies = { - "record_sql" => {"enabled" => default, "required" => false, "position" => 0}, - "custom_events" => {"enabled" => default, "required" => false, "position" => 3}, - "custom_parameters" => {"enabled" => default, "required" => false, "position" => 4}, - "attributes_include" => {"enabled" => default, "required" => false, "position" => 1}, - "message_parameters" => {"enabled" => default, "required" => false, "position" => 6}, - "allow_raw_exception_messages" => {"enabled" => default, "required" => false, "position" => 2}, - "custom_instrumentation_editor" => {"enabled" => default, "required" => false, "position" => 5} + 'record_sql' => {'enabled' => default, 'required' => false, 'position' => 0}, + 'custom_events' => {'enabled' => default, 'required' => false, 'position' => 3}, + 'custom_parameters' => {'enabled' => default, 'required' => false, 'position' => 4}, + 'attributes_include' => {'enabled' => default, 'required' => false, 'position' => 1}, + 'message_parameters' => {'enabled' => default, 'required' => false, 'position' => 6}, + 'allow_raw_exception_messages' => {'enabled' => default, 'required' => false, 'position' => 2}, + 'custom_instrumentation_editor' => {'enabled' => default, 'required' => false, 'position' => 5} } - enabled.each { |name| policies[name]["enabled"] = true } - disabled.each { |name| policies[name]["enabled"] = false } - required.each { |name| policies[name]["required"] = true } + enabled.each { |name| policies[name]['enabled'] = true } + disabled.each { |name| policies[name]['enabled'] = false } + required.each { |name| policies[name]['required'] = true } policies end diff --git a/test/new_relic/agent/configuration/server_source_test.rb b/test/new_relic/agent/configuration/server_source_test.rb index e35e95af1b..8a10169671 100644 --- a/test/new_relic/agent/configuration/server_source_test.rb +++ b/test/new_relic/agent/configuration/server_source_test.rb @@ -102,37 +102,37 @@ def test_should_not_dot_the_web_transactions_apdex_hash def test_should_set_analytics_events_max_samples assert_equal 833, @source[:'transaction_events.max_samples_stored'] - assert_metrics_recorded({"Supportability/EventHarvest/AnalyticEventData/HarvestLimit" => {total_call_time: 833}}) + assert_metrics_recorded({'Supportability/EventHarvest/AnalyticEventData/HarvestLimit' => {total_call_time: 833}}) end def test_should_set_custom_events_max_samples assert_equal 833, @source[:'custom_insights_events.max_samples_stored'] - assert_metrics_recorded({"Supportability/EventHarvest/CustomEventData/HarvestLimit" => {total_call_time: 833}}) + assert_metrics_recorded({'Supportability/EventHarvest/CustomEventData/HarvestLimit' => {total_call_time: 833}}) end def test_should_set_error_events_max_samples assert_equal 8, @source[:'error_collector.max_event_samples_stored'] - assert_metrics_recorded({"Supportability/EventHarvest/ErrorEventData/HarvestLimit" => {total_call_time: 8}}) + assert_metrics_recorded({'Supportability/EventHarvest/ErrorEventData/HarvestLimit' => {total_call_time: 8}}) end def test_should_set_log_events_max_samples assert_equal 833, @source[:'application_logging.forwarding.max_samples_stored'] - assert_metrics_recorded({"Supportability/EventHarvest/LogEventData/HarvestLimit" => {total_call_time: 833}}) + assert_metrics_recorded({'Supportability/EventHarvest/LogEventData/HarvestLimit' => {total_call_time: 833}}) end def test_should_set_span_events_max_samples assert_equal 89, @source[:'span_events.max_samples_stored'] - assert_metrics_recorded({"Supportability/SpanEvent/Limit" => {total_call_time: 89}}) + assert_metrics_recorded({'Supportability/SpanEvent/Limit' => {total_call_time: 89}}) end def test_should_set_event_report_period assert_equal 5, @source[:'event_report_period'] - assert_metrics_recorded({"Supportability/EventHarvest/ReportPeriod" => {total_call_time: 5}}) + assert_metrics_recorded({'Supportability/EventHarvest/ReportPeriod' => {total_call_time: 5}}) end def test_should_set_span_event_report_period assert_equal 80000, @source[:'event_report_period.span_event_data'] - assert_metrics_recorded({"Supportability/SpanEvent/ReportPeriod" => {total_call_time: 80000}}) + assert_metrics_recorded({'Supportability/SpanEvent/ReportPeriod' => {total_call_time: 80000}}) end def test_should_correctly_handle_missing_event_type_from_event_harvest_config @@ -140,7 +140,7 @@ def test_should_correctly_handle_missing_event_type_from_event_harvest_config @source = ServerSource.new(@config) # Span events should fall back to default source - refute @source[:'span_events.max_samples_stored'], "Expected span events to be excluded from server source" + refute @source[:'span_events.max_samples_stored'], 'Expected span events to be excluded from server source' # The event report period and limits for other event types should still be in server source assert_equal 5, @source[:'event_report_period'] diff --git a/test/new_relic/agent/configuration/yaml_source_test.rb b/test/new_relic/agent/configuration/yaml_source_test.rb index 90b30af283..43ed697bdc 100644 --- a/test/new_relic/agent/configuration/yaml_source_test.rb +++ b/test/new_relic/agent/configuration/yaml_source_test.rb @@ -15,8 +15,8 @@ def setup end def test_should_load_hash_for_specified_configs - ignore_messages = {"RuntimeError" => ["test error3"]} - expected_messages = {"StandardError" => ["test error1", "test error2"]} + ignore_messages = {'RuntimeError' => ['test error3']} + expected_messages = {'StandardError' => ['test error1', 'test error2']} assert_equal ignore_messages, @source[:'error_collector.ignore_messages'] assert_equal expected_messages, @source[:'error_collector.expected_messages'] @@ -91,7 +91,7 @@ def test_should_not_fail_to_log_invalid_file_during_startup ::NewRelic::Agent::StartupLogger.any_instance.expects(:error) File.stubs(:exist?).returns(true) - File.stubs(:read).raises(StandardError.new("boo")) + File.stubs(:read).raises(StandardError.new('boo')) YamlSource.new('fake.yml', 'test') end @@ -99,7 +99,7 @@ def test_should_not_fail_to_log_invalid_file_during_startup def test_should_mark_error_on_read_as_failure File.stubs(:exist?).returns(true) - File.stubs(:read).raises(StandardError.new("boo")) + File.stubs(:read).raises(StandardError.new('boo')) source = YamlSource.new('fake.yml', 'test') @@ -107,7 +107,7 @@ def test_should_mark_error_on_read_as_failure end def test_should_mark_erb_error_as_failure - ERB.stubs(:new).raises(StandardError.new("boo")) + ERB.stubs(:new).raises(StandardError.new('boo')) source = YamlSource.new(@test_yml_path, 'test') diff --git a/test/new_relic/agent/connect/request_builder_test.rb b/test/new_relic/agent/connect/request_builder_test.rb index 05d8488fb2..75e874b231 100644 --- a/test/new_relic/agent/connect/request_builder_test.rb +++ b/test/new_relic/agent/connect/request_builder_test.rb @@ -33,7 +33,7 @@ def test_sanitize_environment_report_cannot_be_serialized end def test_connect_settings - with_config(:app_name => ["apps"]) do + with_config(:app_name => ['apps']) do keys = %w[pid host identifier display_host app_name language agent_version environment settings].map(&:to_sym) settings = @request_builder.connect_payload @@ -45,28 +45,28 @@ def test_connect_settings end def test_connect_settings_includes_correct_identifier - with_config(:app_name => "b;a;c") do + with_config(:app_name => 'b;a;c') do NewRelic::Agent::Connect::RequestBuilder.any_instance.stubs(:local_host).returns('lo-calhost') @environment_report = {} settings = @request_builder.connect_payload - assert_equal "ruby:lo-calhost:a,b,c", settings[:identifier] + assert_equal 'ruby:lo-calhost:a,b,c', settings[:identifier] end end def test_connect_settings_includes_labels_from_config with_config({:labels => {'Server' => 'East'}}) do - expected = [{"label_type" => "Server", "label_value" => "East"}] + expected = [{'label_type' => 'Server', 'label_value' => 'East'}] assert_equal expected, @request_builder.connect_payload[:labels] end end def test_connect_settings_includes_labels_from_semicolon_separated_config - with_config(:labels => "Server:East;Server:West;") do + with_config(:labels => 'Server:East;Server:West;') do expected = [ - {"label_type" => "Server", "label_value" => "West"} + {'label_type' => 'Server', 'label_value' => 'West'} ] assert_equal expected, @request_builder.connect_payload[:labels] diff --git a/test/new_relic/agent/connect/response_handler_test.rb b/test/new_relic/agent/connect/response_handler_test.rb index be34c9ed71..5e123ca1ec 100644 --- a/test/new_relic/agent/connect/response_handler_test.rb +++ b/test/new_relic/agent/connect/response_handler_test.rb @@ -9,7 +9,7 @@ class NewRelic::Agent::Agent::ResponseHandlerTest < Minitest::Test def setup server = NewRelic::Control::Server.new('localhost', 30303) @service = NewRelic::Agent::NewRelicService.new('abcdef', server) - NewRelic::Agent.instance.service = @service + NewRelic::Agent.instance.instance_variable_set(:@service, @service) @local_host = nil NewRelic::Agent.reset_config diff --git a/test/new_relic/agent/custom_event_aggregator_test.rb b/test/new_relic/agent/custom_event_aggregator_test.rb index de9def01c0..b11affce51 100644 --- a/test/new_relic/agent/custom_event_aggregator_test.rb +++ b/test/new_relic/agent/custom_event_aggregator_test.rb @@ -50,7 +50,7 @@ def aggregator end def name_for(event) - event[1]["name"] + event[1]['name'] end include NewRelic::CommonAggregatorTests @@ -123,9 +123,9 @@ def test_record_adds_type_and_timestamp def test_records_supportability_metrics_after_harvest with_config(:'custom_insights_events.max_samples_stored' => 5) do engine = NewRelic::Agent.instance.stats_engine - engine.expects(:tl_record_supportability_metric_count).with("Events/Customer/Seen", 9) - engine.expects(:tl_record_supportability_metric_count).with("Events/Customer/Sent", 5) - engine.expects(:tl_record_supportability_metric_count).with("Events/Customer/Dropped", 4) + engine.expects(:tl_record_supportability_metric_count).with('Events/Customer/Seen', 9) + engine.expects(:tl_record_supportability_metric_count).with('Events/Customer/Sent', 5) + engine.expects(:tl_record_supportability_metric_count).with('Events/Customer/Dropped', 4) 9.times { @aggregator.record(:t, :foo => :bar) } @aggregator.harvest! diff --git a/test/new_relic/agent/database/postgres_explain_obfuscator_test.rb b/test/new_relic/agent/database/postgres_explain_obfuscator_test.rb index 98aae1fd15..6ee99d3473 100644 --- a/test/new_relic/agent/database/postgres_explain_obfuscator_test.rb +++ b/test/new_relic/agent/database/postgres_explain_obfuscator_test.rb @@ -10,12 +10,12 @@ class PostgresExplainObfuscatorTest < Minitest::Test attr_reader :obfuscator def self.input_files - fixture_dir = File.join(cross_agent_tests_dir, "postgres_explain_obfuscation") + fixture_dir = File.join(cross_agent_tests_dir, 'postgres_explain_obfuscation') Dir["#{fixture_dir}/*.explain.txt"] end def self.name_for_input_file(input_file) - File.basename(input_file, ".explain.txt") + File.basename(input_file, '.explain.txt') end input_files.each do |input_file| @@ -29,7 +29,7 @@ def self.name_for_input_file(input_file) end def obfuscated_filename(query_file) - query_file.gsub(".explain.", ".colon_obfuscated.") + query_file.gsub('.explain.', '.colon_obfuscated.') end end end diff --git a/test/new_relic/agent/database/sql_obfuscation_test.rb b/test/new_relic/agent/database/sql_obfuscation_test.rb index 88c56b5434..580b20e8c1 100644 --- a/test/new_relic/agent/database/sql_obfuscation_test.rb +++ b/test/new_relic/agent/database/sql_obfuscation_test.rb @@ -13,7 +13,7 @@ def self.create_input_statements(raw_query, dialects) end def build_failure_message(statement, acceptable_outputs, actual_output) - msg = String.new("Failed to obfuscate #{statement.adapter} query correctly.\n") + msg = +"Failed to obfuscate #{statement.adapter} query correctly.\n" msg << "Input: #{statement.inspect}\n" if acceptable_outputs.size == 1 msg << "Expected: #{acceptable_outputs.first}\n" diff --git a/test/new_relic/agent/database_test.rb b/test/new_relic/agent/database_test.rb index ce28d8e554..0d8c133670 100644 --- a/test/new_relic/agent/database_test.rb +++ b/test/new_relic/agent/database_test.rb @@ -25,21 +25,21 @@ def test_adapter_from_config_symbol end def test_adapter_from_config_uri_jdbc_postgresql - config = {:uri => "jdbc:postgresql://host/database?user=postgres"} + config = {:uri => 'jdbc:postgresql://host/database?user=postgres'} statement = NewRelic::Agent::Database::Statement.new('some query', config) assert_equal(:postgres, statement.adapter) end def test_adapter_from_config_uri_jdbc_mysql - config = {:uri => "jdbc:mysql://host/database"} + config = {:uri => 'jdbc:mysql://host/database'} statement = NewRelic::Agent::Database::Statement.new('some query', config) assert_equal(:mysql, statement.adapter) end def test_adapter_from_config_uri_jdbc_sqlite - config = {:uri => "jdbc:sqlite::memory"} + config = {:uri => 'jdbc:sqlite::memory'} statement = NewRelic::Agent::Database::Statement.new('some query', config) assert_equal(:sqlite, statement.adapter) @@ -62,7 +62,7 @@ def test_explain_sql_with_mysql2_activerecord_result sql = 'SELECT * FROM spells where id=1' columns = %w[id select_type table type possible_keys key key_len ref rows Extra] - rows = [["1", "SIMPLE", "spells", "const", "PRIMARY", "PRIMARY", "4", "const", "1", ""]] + rows = [['1', 'SIMPLE', 'spells', 'const', 'PRIMARY', 'PRIMARY', '4', 'const', '1', '']] activerecord_result = ::ActiveRecord::Result.new(columns, rows) explainer = lambda { |statement| activerecord_result } @@ -78,18 +78,18 @@ def test_explain_sql_obfuscates_for_postgres_activerecord_result config = {:adapter => 'postgres'} sql = "SELECT * FROM blogs WHERE blogs.id=1234 AND blogs.title='sensitive text'" - columns = ["stuffs"] - rows = [[" Index Scan using blogs_pkey on blogs (cost=0.00..8.27 rows=1 width=540)"], - [" Index Cond: (id = 1234)"], + columns = ['stuffs'] + rows = [[' Index Scan using blogs_pkey on blogs (cost=0.00..8.27 rows=1 width=540)'], + [' Index Cond: (id = 1234)'], [" Filter: ((title)::text = 'sensitive text'::text)"]] activerecord_result = ::ActiveRecord::Result.new(columns, rows) explainer = lambda { |statement| activerecord_result } statement = NewRelic::Agent::Database::Statement.new(sql, config, explainer) expected_result = [['QUERY PLAN'], - [[" Index Scan using blogs_pkey on blogs (cost=0.00..8.27 rows=1 width=540)"], - [" Index Cond: ?"], - [" Filter: ?"]]] + [[' Index Scan using blogs_pkey on blogs (cost=0.00..8.27 rows=1 width=540)'], + [' Index Cond: ?'], + [' Filter: ?']]] with_config(:'transaction_tracer.record_sql' => 'obfuscated') do result = NewRelic::Agent::Database.explain_sql(statement) @@ -107,9 +107,9 @@ def test_explain_sql_select_with_mysql_explain_result sql = 'SELECT foo' plan = { - "select_type" => "SIMPLE", "key_len" => nil, "table" => "blogs", "id" => "1", - "possible_keys" => nil, "type" => "ALL", "Extra" => "", "rows" => "2", - "ref" => nil, "key" => nil + 'select_type' => 'SIMPLE', 'key_len' => nil, 'table' => 'blogs', 'id' => '1', + 'possible_keys' => nil, 'type' => 'ALL', 'Extra' => '', 'rows' => '2', + 'ref' => nil, 'key' => nil } explainer_result = mock('explain plan') explainer_result.expects(:each_hash).yields(plan) @@ -119,7 +119,7 @@ def test_explain_sql_select_with_mysql_explain_result result = NewRelic::Agent::Database.explain_sql(statement) expected_result = [%w[select_type key_len table id possible_keys type Extra rows ref key], - [["SIMPLE", nil, "blogs", "1", nil, "ALL", "", "2", nil, nil]]] + [['SIMPLE', nil, 'blogs', '1', nil, 'ALL', '', '2', nil, nil]]] assert_equal(expected_result[0].sort, result[0].sort, "Headers don't match") assert_equal(expected_result[1][0].compact.sort, result[1][0].compact.sort, "Values don't match") @@ -132,11 +132,11 @@ def test_explain_sql_select_with_sequel # Sequel returns explain plans to us as one giant preformatted string rather # than individual rows. plan_string = [ - "+--+-----------+-----+----+-------------+---+-------+---+----+-----+", - "|id|select_type|table|type|possible_keys|key|key_len|ref|rows|Extra|", - "+--+-----------+-----+----+-------------+---+-------+---+----+-----+", - "| 1|SIMPLE |items|ALL | | | | | 3| |", - "+--+-----------+-----+----+-------------+---+-------+---+----+-----+" + '+--+-----------+-----+----+-------------+---+-------+---+----+-----+', + '|id|select_type|table|type|possible_keys|key|key_len|ref|rows|Extra|', + '+--+-----------+-----+----+-------------+---+-------+---+----+-----+', + '| 1|SIMPLE |items|ALL | | | | | 3| |', + '+--+-----------+-----+----+-------------+---+-------+---+----+-----+' ].join("\n") explainer = lambda { |statement| plan_string } @@ -152,7 +152,7 @@ def test_explain_sql_select_with_mysql2_explain_result sql = 'SELECT foo' plan_fields = %w[select_type key_len table id possible_keys type Extra rows ref key] - plan_row = ["SIMPLE", nil, "blogs", "1", nil, "ALL", "", "2", nil, nil] + plan_row = ['SIMPLE', nil, 'blogs', '1', nil, 'ALL', '', '2', nil, nil] explainer_result = mock('explain plan') explainer_result.expects(:fields).returns(plan_fields) explainer_result.expects(:each).yields(plan_row) @@ -162,7 +162,7 @@ def test_explain_sql_select_with_mysql2_explain_result result = NewRelic::Agent::Database.explain_sql(statement) expected_result = [%w[select_type key_len table id possible_keys type Extra rows ref key], - [["SIMPLE", nil, "blogs", "1", nil, "ALL", "", "2", nil, nil]]] + [['SIMPLE', nil, 'blogs', '1', nil, 'ALL', '', '2', nil, nil]]] assert_equal(expected_result[0].sort, result[0].sort, "Headers don't match") assert_equal(expected_result[1][0].compact.sort, result[1][0].compact.sort, "Values don't match") @@ -172,17 +172,17 @@ def test_explain_sql_one_select_with_pg_explain_result config = {:adapter => 'postgresql'} sql = 'select count(id) from blogs limit 1' - plan = [{"QUERY PLAN" => "Limit (cost=11.75..11.76 rows=1 width=4)"}, - {"QUERY PLAN" => " -> Aggregate (cost=11.75..11.76 rows=1 width=4)"}, - {"QUERY PLAN" => " -> Seq Scan on blogs (cost=0.00..11.40 rows=140 width=4)"}] + plan = [{'QUERY PLAN' => 'Limit (cost=11.75..11.76 rows=1 width=4)'}, + {'QUERY PLAN' => ' -> Aggregate (cost=11.75..11.76 rows=1 width=4)'}, + {'QUERY PLAN' => ' -> Seq Scan on blogs (cost=0.00..11.40 rows=140 width=4)'}] explainer = lambda { |statement| plan } statement = NewRelic::Agent::Database::Statement.new(sql, config, explainer) result = NewRelic::Agent::Database.explain_sql(statement) expected_result = [['QUERY PLAN'], - [["Limit (cost=11.75..11.76 rows=1 width=4)"], - [" -> Aggregate (cost=11.75..11.76 rows=1 width=4)"], - [" -> Seq Scan on blogs (cost=0.00..11.40 rows=140 width=4)"]]] + [['Limit (cost=11.75..11.76 rows=1 width=4)'], + [' -> Aggregate (cost=11.75..11.76 rows=1 width=4)'], + [' -> Seq Scan on blogs (cost=0.00..11.40 rows=140 width=4)']]] assert_equal expected_result, result end @@ -191,17 +191,17 @@ def test_explain_sql_one_select_with_pg_explain_string_result config = {:adapter => 'postgresql'} sql = 'select count(id) from blogs limit 1' - plan = String.new("Limit (cost=11.75..11.76 rows=1 width=4) + plan = +"Limit (cost=11.75..11.76 rows=1 width=4) -> Aggregate (cost=11.75..11.76 rows=1 width=4) - -> Seq Scan on blogs (cost=0.00..11.40 rows=140 width=4)") + -> Seq Scan on blogs (cost=0.00..11.40 rows=140 width=4)" explainer = lambda { |statement| plan } statement = NewRelic::Agent::Database::Statement.new(sql, config, explainer) result = NewRelic::Agent::Database.explain_sql(statement) expected_result = [['QUERY PLAN'], - [["Limit (cost=11.75..11.76 rows=1 width=4)"], - [" -> Aggregate (cost=11.75..11.76 rows=1 width=4)"], - [" -> Seq Scan on blogs (cost=0.00..11.40 rows=140 width=4)"]]] + [['Limit (cost=11.75..11.76 rows=1 width=4)'], + [' -> Aggregate (cost=11.75..11.76 rows=1 width=4)'], + [' -> Seq Scan on blogs (cost=0.00..11.40 rows=140 width=4)']]] assert_equal expected_result, result end @@ -210,16 +210,16 @@ def test_explain_sql_obfuscates_for_postgres config = {:adapter => 'postgresql'} sql = "SELECT * FROM blogs WHERE blogs.id=1234 AND blogs.title='sensitive text'" - plan = [{"QUERY PLAN" => " Index Scan using blogs_pkey on blogs (cost=0.00..8.27 rows=1 width=540)"}, - {"QUERY PLAN" => " Index Cond: (id = 1234)"}, - {"QUERY PLAN" => " Filter: ((title)::text = 'sensitive text'::text)"}] + plan = [{'QUERY PLAN' => ' Index Scan using blogs_pkey on blogs (cost=0.00..8.27 rows=1 width=540)'}, + {'QUERY PLAN' => ' Index Cond: (id = 1234)'}, + {'QUERY PLAN' => " Filter: ((title)::text = 'sensitive text'::text)"}] explainer = lambda { |statement| plan } statement = NewRelic::Agent::Database::Statement.new(sql, config, explainer) expected_result = [['QUERY PLAN'], - [[" Index Scan using blogs_pkey on blogs (cost=0.00..8.27 rows=1 width=540)"], - [" Index Cond: ?"], - [" Filter: ?"]]] + [[' Index Scan using blogs_pkey on blogs (cost=0.00..8.27 rows=1 width=540)'], + [' Index Cond: ?'], + [' Filter: ?']]] with_config(:'transaction_tracer.record_sql' => 'obfuscated') do result = NewRelic::Agent::Database.explain_sql(statement) @@ -232,15 +232,15 @@ def test_explain_sql_does_not_obfuscate_if_record_sql_raw config = {:adapter => 'postgresql'} sql = "SELECT * FROM blogs WHERE blogs.id=1234 AND blogs.title='sensitive text'" - plan = [{"QUERY PLAN" => " Index Scan using blogs_pkey on blogs (cost=0.00..8.27 rows=1 width=540)"}, - {"QUERY PLAN" => " Index Cond: (id = 1234)"}, - {"QUERY PLAN" => " Filter: ((title)::text = 'sensitive text'::text)"}] + plan = [{'QUERY PLAN' => ' Index Scan using blogs_pkey on blogs (cost=0.00..8.27 rows=1 width=540)'}, + {'QUERY PLAN' => ' Index Cond: (id = 1234)'}, + {'QUERY PLAN' => " Filter: ((title)::text = 'sensitive text'::text)"}] explainer = lambda { |statement| plan } statement = NewRelic::Agent::Database::Statement.new(sql, config, explainer) expected_result = [['QUERY PLAN'], - [[" Index Scan using blogs_pkey on blogs (cost=0.00..8.27 rows=1 width=540)"], - [" Index Cond: (id = 1234)"], + [[' Index Scan using blogs_pkey on blogs (cost=0.00..8.27 rows=1 width=540)'], + [' Index Cond: (id = 1234)'], [" Filter: ((title)::text = 'sensitive text'::text)"]]] with_config(:'transaction_tracer.record_sql' => 'raw') do @@ -255,12 +255,12 @@ def test_explain_sql_select_with_sqlite_explain_string_result sql = 'SELECT foo' plan = [ - {"addr" => 0, "opcode" => "Trace", "p1" => 0, "p2" => 0, "p3" => 0, "p4" => "", "p5" => "00", "comment" => nil, 0 => 0, 1 => "Trace", 2 => 0, 3 => 0, 4 => 0, 5 => "", 6 => "00", 7 => nil}, - {"addr" => 1, "opcode" => "Goto", "p1" => 0, "p2" => 5, "p3" => 0, "p4" => "", "p5" => "00", "comment" => nil, 0 => 1, 1 => "Goto", 2 => 0, 3 => 5, 4 => 0, 5 => "", 6 => "00", 7 => nil}, - {"addr" => 2, "opcode" => "String8", "p1" => 0, "p2" => 1, "p3" => 0, "p4" => "foo", "p5" => "00", "comment" => nil, 0 => 2, 1 => "String8", 2 => 0, 3 => 1, 4 => 0, 5 => "foo", 6 => "00", 7 => nil}, - {"addr" => 3, "opcode" => "ResultRow", "p1" => 1, "p2" => 1, "p3" => 0, "p4" => "", "p5" => "00", "comment" => nil, 0 => 3, 1 => "ResultRow", 2 => 1, 3 => 1, 4 => 0, 5 => "", 6 => "00", 7 => nil}, - {"addr" => 4, "opcode" => "Halt", "p1" => 0, "p2" => 0, "p3" => 0, "p4" => "", "p5" => "00", "comment" => nil, 0 => 4, 1 => "Halt", 2 => 0, 3 => 0, 4 => 0, 5 => "", 6 => "00", 7 => nil}, - {"addr" => 5, "opcode" => "Goto", "p1" => 0, "p2" => 2, "p3" => 0, "p4" => "", "p5" => "00", "comment" => nil, 0 => 5, 1 => "Goto", 2 => 0, 3 => 2, 4 => 0, 5 => "", 6 => "00", 7 => nil} + {'addr' => 0, 'opcode' => 'Trace', 'p1' => 0, 'p2' => 0, 'p3' => 0, 'p4' => '', 'p5' => '00', 'comment' => nil, 0 => 0, 1 => 'Trace', 2 => 0, 3 => 0, 4 => 0, 5 => '', 6 => '00', 7 => nil}, + {'addr' => 1, 'opcode' => 'Goto', 'p1' => 0, 'p2' => 5, 'p3' => 0, 'p4' => '', 'p5' => '00', 'comment' => nil, 0 => 1, 1 => 'Goto', 2 => 0, 3 => 5, 4 => 0, 5 => '', 6 => '00', 7 => nil}, + {'addr' => 2, 'opcode' => 'String8', 'p1' => 0, 'p2' => 1, 'p3' => 0, 'p4' => 'foo', 'p5' => '00', 'comment' => nil, 0 => 2, 1 => 'String8', 2 => 0, 3 => 1, 4 => 0, 5 => 'foo', 6 => '00', 7 => nil}, + {'addr' => 3, 'opcode' => 'ResultRow', 'p1' => 1, 'p2' => 1, 'p3' => 0, 'p4' => '', 'p5' => '00', 'comment' => nil, 0 => 3, 1 => 'ResultRow', 2 => 1, 3 => 1, 4 => 0, 5 => '', 6 => '00', 7 => nil}, + {'addr' => 4, 'opcode' => 'Halt', 'p1' => 0, 'p2' => 0, 'p3' => 0, 'p4' => '', 'p5' => '00', 'comment' => nil, 0 => 4, 1 => 'Halt', 2 => 0, 3 => 0, 4 => 0, 5 => '', 6 => '00', 7 => nil}, + {'addr' => 5, 'opcode' => 'Goto', 'p1' => 0, 'p2' => 2, 'p3' => 0, 'p4' => '', 'p5' => '00', 'comment' => nil, 0 => 5, 1 => 'Goto', 2 => 0, 3 => 2, 4 => 0, 5 => '', 6 => '00', 7 => nil} ] explainer = lambda { |statement| plan } @@ -281,12 +281,12 @@ def test_explain_sql_select_with_sqlite3_explain_string_result sql = 'SELECT foo' plan = [ - {"addr" => 0, "opcode" => "Trace", "p1" => 0, "p2" => 0, "p3" => 0, "p4" => "", "p5" => "00", "comment" => nil, 0 => 0, 1 => "Trace", 2 => 0, 3 => 0, 4 => 0, 5 => "", 6 => "00", 7 => nil}, - {"addr" => 1, "opcode" => "Goto", "p1" => 0, "p2" => 5, "p3" => 0, "p4" => "", "p5" => "00", "comment" => nil, 0 => 1, 1 => "Goto", 2 => 0, 3 => 5, 4 => 0, 5 => "", 6 => "00", 7 => nil}, - {"addr" => 2, "opcode" => "String8", "p1" => 0, "p2" => 1, "p3" => 0, "p4" => "foo", "p5" => "00", "comment" => nil, 0 => 2, 1 => "String8", 2 => 0, 3 => 1, 4 => 0, 5 => "foo", 6 => "00", 7 => nil}, - {"addr" => 3, "opcode" => "ResultRow", "p1" => 1, "p2" => 1, "p3" => 0, "p4" => "", "p5" => "00", "comment" => nil, 0 => 3, 1 => "ResultRow", 2 => 1, 3 => 1, 4 => 0, 5 => "", 6 => "00", 7 => nil}, - {"addr" => 4, "opcode" => "Halt", "p1" => 0, "p2" => 0, "p3" => 0, "p4" => "", "p5" => "00", "comment" => nil, 0 => 4, 1 => "Halt", 2 => 0, 3 => 0, 4 => 0, 5 => "", 6 => "00", 7 => nil}, - {"addr" => 5, "opcode" => "Goto", "p1" => 0, "p2" => 2, "p3" => 0, "p4" => "", "p5" => "00", "comment" => nil, 0 => 5, 1 => "Goto", 2 => 0, 3 => 2, 4 => 0, 5 => "", 6 => "00", 7 => nil} + {'addr' => 0, 'opcode' => 'Trace', 'p1' => 0, 'p2' => 0, 'p3' => 0, 'p4' => '', 'p5' => '00', 'comment' => nil, 0 => 0, 1 => 'Trace', 2 => 0, 3 => 0, 4 => 0, 5 => '', 6 => '00', 7 => nil}, + {'addr' => 1, 'opcode' => 'Goto', 'p1' => 0, 'p2' => 5, 'p3' => 0, 'p4' => '', 'p5' => '00', 'comment' => nil, 0 => 1, 1 => 'Goto', 2 => 0, 3 => 5, 4 => 0, 5 => '', 6 => '00', 7 => nil}, + {'addr' => 2, 'opcode' => 'String8', 'p1' => 0, 'p2' => 1, 'p3' => 0, 'p4' => 'foo', 'p5' => '00', 'comment' => nil, 0 => 2, 1 => 'String8', 2 => 0, 3 => 1, 4 => 0, 5 => 'foo', 6 => '00', 7 => nil}, + {'addr' => 3, 'opcode' => 'ResultRow', 'p1' => 1, 'p2' => 1, 'p3' => 0, 'p4' => '', 'p5' => '00', 'comment' => nil, 0 => 3, 1 => 'ResultRow', 2 => 1, 3 => 1, 4 => 0, 5 => '', 6 => '00', 7 => nil}, + {'addr' => 4, 'opcode' => 'Halt', 'p1' => 0, 'p2' => 0, 'p3' => 0, 'p4' => '', 'p5' => '00', 'comment' => nil, 0 => 4, 1 => 'Halt', 2 => 0, 3 => 0, 4 => 0, 5 => '', 6 => '00', 7 => nil}, + {'addr' => 5, 'opcode' => 'Goto', 'p1' => 0, 'p2' => 2, 'p3' => 0, 'p4' => '', 'p5' => '00', 'comment' => nil, 0 => 5, 1 => 'Goto', 2 => 0, 3 => 2, 4 => 0, 5 => '', 6 => '00', 7 => nil} ] explainer = lambda { |statement| plan } @@ -337,11 +337,11 @@ def test_dont_collect_explain_for_parameterized_query def test_do_collect_explain_for_parameter_looking_literal config = {:adapter => 'postgresql'} sql = "SELECT * FROM table WHERE id = 'noise $11'" - plan = [{"QUERY PLAN" => "Some Jazz"}] + plan = [{'QUERY PLAN' => 'Some Jazz'}] explainer = lambda { |statement| plan } statement = NewRelic::Agent::Database::Statement.new(sql, config, explainer) - assert_equal([['QUERY PLAN'], [["Some Jazz"]]], + assert_equal([['QUERY PLAN'], [['Some Jazz']]], NewRelic::Agent::Database.explain_sql(statement)) end @@ -349,12 +349,12 @@ def test_do_collect_explain_for_parameterized_query_with_binds config = {:adapter => 'postgresql'} sql = 'SELECT * FROM table WHERE id = $1' # binds objects don't actually look like this, just need non-blank for test - binds = "values for the parameters" - plan = [{"QUERY PLAN" => "Some Jazz"}] + binds = 'values for the parameters' + plan = [{'QUERY PLAN' => 'Some Jazz'}] explainer = lambda { |statement| plan } statement = NewRelic::Agent::Database::Statement.new(sql, config, explainer, binds) - assert_equal([['QUERY PLAN'], [["Some Jazz"]]], + assert_equal([['QUERY PLAN'], [['Some Jazz']]], NewRelic::Agent::Database.explain_sql(statement)) end @@ -405,30 +405,30 @@ def test_explain_sql_one_select_no_connection def test_obfuscation_of_truncated_query insert = "INSERT INTO data (blah) VALUES ('abcdefg..." - assert_equal("Query too large (over 16k characters) to safely obfuscate", + assert_equal('Query too large (over 16k characters) to safely obfuscate', NewRelic::Agent::Database.obfuscate_sql(insert)) end def test_sql_obfuscation_filters NewRelic::Agent::Database.set_sql_obfuscator(:replace) do |string| - "1" + string + '1' + string end sql = "SELECT * FROM TABLE 123 'jim'" - assert_equal "1" + sql, NewRelic::Agent::Database.obfuscate_sql(sql) + assert_equal '1' + sql, NewRelic::Agent::Database.obfuscate_sql(sql) NewRelic::Agent::Database.set_sql_obfuscator(:before) do |string| - "2" + string + '2' + string end - assert_equal "12" + sql, NewRelic::Agent::Database.obfuscate_sql(sql) + assert_equal '12' + sql, NewRelic::Agent::Database.obfuscate_sql(sql) NewRelic::Agent::Database.set_sql_obfuscator(:after) do |string| - string + "3" + string + '3' end - assert_equal "12" + sql + "3", NewRelic::Agent::Database.obfuscate_sql(sql) + assert_equal '12' + sql + '3', NewRelic::Agent::Database.obfuscate_sql(sql) NewRelic::Agent::Database::Obfuscator.instance.reset end @@ -446,7 +446,7 @@ def test_close_connections_closes_all_held_db_connections end def test_manager_get_connection_does_not_log_configuration_details_on_error - config = "VOLDEMORT" + config = 'VOLDEMORT' connector = proc { raise } error_log = with_array_logger(:error) do NewRelic::Agent::Database::ConnectionManager.instance.get_connection(config, &connector) @@ -456,7 +456,7 @@ def test_manager_get_connection_does_not_log_configuration_details_on_error end def test_default_sql_obfuscator_obfuscates_double_quoted_literals_with_unknown_adapter - expected = "SELECT * FROM ? WHERE ? = ?" + expected = 'SELECT * FROM ? WHERE ? = ?' result = NewRelic::Agent::Database.obfuscate_sql("SELECT * FROM \"table\" WHERE \"col\" = 'value'") assert_equal expected, result @@ -481,7 +481,7 @@ def test_capture_query_long_query assert_equal('a' * (NewRelic::Agent::Database::MAX_QUERY_LENGTH - 3) + '...', truncated_query) end - INVALID_UTF8_STRING = String.new("select \x80").force_encoding('UTF-8') + INVALID_UTF8_STRING = (+"select \x80").force_encoding('UTF-8') def test_capture_query_mis_encoded query = INVALID_UTF8_STRING @@ -496,7 +496,7 @@ def test_capture_query_mis_encoded def test_parse_operation_from_query_mis_encoded query = INVALID_UTF8_STRING - expected = "select" + expected = 'select' parsed = NewRelic::Agent::Database.parse_operation_from_query(query) assert_equal(expected, parsed) @@ -536,15 +536,15 @@ def test_safe_sql_obfuscates_when_set NewRelic::Agent::Database.stubs(:record_sql_method).returns(:obfuscated) statement = NewRelic::Agent::Database::Statement.new("select * from mytable where name = '1337807';") - assert_equal "select * from mytable where name = ?;", statement.safe_sql + assert_equal 'select * from mytable where name = ?;', statement.safe_sql end def test_safe_sql_does_not_over_obfuscate_for_postgres NewRelic::Agent::Database.stubs(:record_sql_method).returns(:obfuscated) - conf = {:adapter => "postgresql", :encoding => "utf8", :pool => 10, :port => 5432, :prepared_statements => false, :ssl_mode => "require"} - sql = "SELECT \"users\".* FROM \"users\" WHERE \"users\".\"deleted_at\" IS NULL AND \"users\".\"id\" = 1602 LIMIT 1" - expected_sql = "SELECT \"users\".* FROM \"users\" WHERE \"users\".\"deleted_at\" IS ? AND \"users\".\"id\" = ? LIMIT ?" + conf = {:adapter => 'postgresql', :encoding => 'utf8', :pool => 10, :port => 5432, :prepared_statements => false, :ssl_mode => 'require'} + sql = 'SELECT "users".* FROM "users" WHERE "users"."deleted_at" IS NULL AND "users"."id" = 1602 LIMIT 1' + expected_sql = 'SELECT "users".* FROM "users" WHERE "users"."deleted_at" IS ? AND "users"."id" = ? LIMIT ?' stmt = NewRelic::Agent::Database::Statement.new(sql, conf) diff --git a/test/new_relic/agent/datastores/metric_helper_test.rb b/test/new_relic/agent/datastores/metric_helper_test.rb index dc6b899e49..039865738d 100644 --- a/test/new_relic/agent/datastores/metric_helper_test.rb +++ b/test/new_relic/agent/datastores/metric_helper_test.rb @@ -9,29 +9,29 @@ module NewRelic module Agent class Datastores::MetricHelperTest < Minitest::Test def setup - @product = "JonanDB" - @collection = "wiggles" - @operation = "select" + @product = 'JonanDB' + @collection = 'wiggles' + @operation = 'select' NewRelic::Agent::Harvester.any_instance.stubs(:harvest_thread_enabled?).returns(false) end def test_statement_metric_for - expected = "Datastore/statement/JonanDB/wiggles/select" + expected = 'Datastore/statement/JonanDB/wiggles/select' result = Datastores::MetricHelper.statement_metric_for(@product, @collection, @operation) assert_equal expected, result end def test_operation_metric_for - expected = "Datastore/operation/JonanDB/select" + expected = 'Datastore/operation/JonanDB/select' result = Datastores::MetricHelper.operation_metric_for(@product, @operation) assert_equal expected, result end def test_instance_metric_for - host = "localhost" - port = "1337807" + host = 'localhost' + port = '1337807' expected = "Datastore/instance/JonanDB/#{host}/#{port}" result = Datastores::MetricHelper.instance_metric_for(@product, host, port) @@ -41,12 +41,12 @@ def test_instance_metric_for def test_metrics_for_in_web_context Transaction.stubs(:recording_web_transaction?).returns(true) expected = [ - "Datastore/statement/JonanDB/wiggles/select", - "Datastore/operation/JonanDB/select", - "Datastore/JonanDB/allWeb", - "Datastore/JonanDB/all", - "Datastore/allWeb", - "Datastore/all" + 'Datastore/statement/JonanDB/wiggles/select', + 'Datastore/operation/JonanDB/select', + 'Datastore/JonanDB/allWeb', + 'Datastore/JonanDB/all', + 'Datastore/allWeb', + 'Datastore/all' ] result = Datastores::MetricHelper.metrics_for(@product, @operation, @collection) @@ -57,12 +57,12 @@ def test_metrics_for_in_web_context def test_metrics_for_outside_web_context Transaction.stubs(:recording_web_transaction?).returns(false) expected = [ - "Datastore/statement/JonanDB/wiggles/select", - "Datastore/operation/JonanDB/select", - "Datastore/JonanDB/allOther", - "Datastore/JonanDB/all", - "Datastore/allOther", - "Datastore/all" + 'Datastore/statement/JonanDB/wiggles/select', + 'Datastore/operation/JonanDB/select', + 'Datastore/JonanDB/allOther', + 'Datastore/JonanDB/all', + 'Datastore/allOther', + 'Datastore/all' ] result = Datastores::MetricHelper.metrics_for(@product, @operation, @collection) @@ -71,14 +71,14 @@ def test_metrics_for_outside_web_context end def test_scoped_metric_for_with_collection - expected = "Datastore/statement/JonanDB/wiggles/select" + expected = 'Datastore/statement/JonanDB/wiggles/select' result = Datastores::MetricHelper.scoped_metric_for(@product, @operation, @collection) assert_equal expected, result end def test_scoped_metric_for_without_collection - expected = "Datastore/operation/JonanDB/select" + expected = 'Datastore/operation/JonanDB/select' result = Datastores::MetricHelper.scoped_metric_for(@product, @operation) assert_equal expected, result @@ -87,11 +87,11 @@ def test_scoped_metric_for_without_collection def test_unscoped_metrics_for_in_web_context Transaction.stubs(:recording_web_transaction?).returns(true) expected = [ - "Datastore/operation/JonanDB/select", - "Datastore/JonanDB/allWeb", - "Datastore/JonanDB/all", - "Datastore/allWeb", - "Datastore/all" + 'Datastore/operation/JonanDB/select', + 'Datastore/JonanDB/allWeb', + 'Datastore/JonanDB/all', + 'Datastore/allWeb', + 'Datastore/all' ] result = Datastores::MetricHelper.unscoped_metrics_for(@product, @operation, @collection) @@ -102,11 +102,11 @@ def test_unscoped_metrics_for_in_web_context def test_unscoped_metrics_for_outside_web_context Transaction.stubs(:recording_web_transaction?).returns(false) expected = [ - "Datastore/operation/JonanDB/select", - "Datastore/JonanDB/allOther", - "Datastore/JonanDB/all", - "Datastore/allOther", - "Datastore/all" + 'Datastore/operation/JonanDB/select', + 'Datastore/JonanDB/allOther', + 'Datastore/JonanDB/all', + 'Datastore/allOther', + 'Datastore/all' ] result = Datastores::MetricHelper.unscoped_metrics_for(@product, @operation, @collection) @@ -117,10 +117,10 @@ def test_unscoped_metrics_for_outside_web_context def test_unscoped_metrics_for_without_collection Transaction.stubs(:recording_web_transaction?).returns(false) expected = [ - "Datastore/JonanDB/allOther", - "Datastore/JonanDB/all", - "Datastore/allOther", - "Datastore/all" + 'Datastore/JonanDB/allOther', + 'Datastore/JonanDB/all', + 'Datastore/allOther', + 'Datastore/all' ] result = Datastores::MetricHelper.unscoped_metrics_for(@product, @operation) @@ -131,14 +131,14 @@ def test_unscoped_metrics_for_without_collection def test_unscoped_metrics_for_with_instance_identifier Transaction.stubs(:recording_web_transaction?).returns(false) expected = [ - "Datastore/instance/JonanDB/localhost/1337807", - "Datastore/JonanDB/allOther", - "Datastore/JonanDB/all", - "Datastore/allOther", - "Datastore/all" + 'Datastore/instance/JonanDB/localhost/1337807', + 'Datastore/JonanDB/allOther', + 'Datastore/JonanDB/all', + 'Datastore/allOther', + 'Datastore/all' ] - result = Datastores::MetricHelper.unscoped_metrics_for(@product, @operation, nil, "localhost", "1337807") + result = Datastores::MetricHelper.unscoped_metrics_for(@product, @operation, nil, 'localhost', '1337807') assert_equal expected, result end @@ -147,13 +147,13 @@ def test_unscoped_metrics_for_with_instance_identifier_and_instance_reporting_di with_config(:'datastore_tracer.instance_reporting.enabled' => false) do Transaction.stubs(:recording_web_transaction?).returns(false) expected = [ - "Datastore/JonanDB/allOther", - "Datastore/JonanDB/all", - "Datastore/allOther", - "Datastore/all" + 'Datastore/JonanDB/allOther', + 'Datastore/JonanDB/all', + 'Datastore/allOther', + 'Datastore/all' ] - result = Datastores::MetricHelper.unscoped_metrics_for(@product, @operation, nil, "localhost/1337807") + result = Datastores::MetricHelper.unscoped_metrics_for(@product, @operation, nil, 'localhost/1337807') assert_equal expected, result end @@ -161,9 +161,9 @@ def test_unscoped_metrics_for_with_instance_identifier_and_instance_reporting_di def test_product_operation_collection_for_obeys_collection_and_operation_overrides in_transaction do - NewRelic::Agent.with_database_metric_name("Model", "new_method") do - result = Datastores::MetricHelper.product_operation_collection_for(@product, "original_method") - expected = [@product, "new_method", "Model"] + NewRelic::Agent.with_database_metric_name('Model', 'new_method') do + result = Datastores::MetricHelper.product_operation_collection_for(@product, 'original_method') + expected = [@product, 'new_method', 'Model'] assert_equal expected, result end @@ -172,9 +172,9 @@ def test_product_operation_collection_for_obeys_collection_and_operation_overrid def test_product_operation_collection_for_obeys_collection_override in_transaction do - NewRelic::Agent.with_database_metric_name("Model", nil) do - result = Datastores::MetricHelper.product_operation_collection_for(@product, "original_method") - expected = [@product, "original_method", "Model"] + NewRelic::Agent.with_database_metric_name('Model', nil) do + result = Datastores::MetricHelper.product_operation_collection_for(@product, 'original_method') + expected = [@product, 'original_method', 'Model'] assert_equal expected, result end @@ -183,9 +183,9 @@ def test_product_operation_collection_for_obeys_collection_override def test_product_operation_collection_for_ignore_overrides_for_other_products in_transaction do - NewRelic::Agent.with_database_metric_name("Model", "new_method", "FauxDB") do - result = Datastores::MetricHelper.product_operation_collection_for(@product, "original_method") - expected = [@product, "original_method", nil] + NewRelic::Agent.with_database_metric_name('Model', 'new_method', 'FauxDB') do + result = Datastores::MetricHelper.product_operation_collection_for(@product, 'original_method') + expected = [@product, 'original_method', nil] assert_equal expected, result end @@ -194,8 +194,8 @@ def test_product_operation_collection_for_ignore_overrides_for_other_products def test_product_operation_collection_for_applies_overrides_by_generic_product_name in_transaction do - NewRelic::Agent.with_database_metric_name("Model", "new_method") do - result = Datastores::MetricHelper.product_operation_collection_for("MoreSpecificDB", "original_method", nil, @product) + NewRelic::Agent.with_database_metric_name('Model', 'new_method') do + result = Datastores::MetricHelper.product_operation_collection_for('MoreSpecificDB', 'original_method', nil, @product) expected = %w[MoreSpecificDB new_method Model] assert_equal expected, result @@ -204,17 +204,17 @@ def test_product_operation_collection_for_applies_overrides_by_generic_product_n end def test_operation_from_sql - sql = "SELECT * FROM blogs where id = 5" + sql = 'SELECT * FROM blogs where id = 5' operation = Datastores::MetricHelper.operation_from_sql(sql) - assert_equal "select", operation + assert_equal 'select', operation end def test_operation_from_sql_returns_other_for_unrecognized_operation - sql = "DESCRIBE blogs" + sql = 'DESCRIBE blogs' operation = Datastores::MetricHelper.operation_from_sql(sql) - assert_equal "Other", operation + assert_equal 'Other', operation end end end diff --git a/test/new_relic/agent/datastores/mongo/event_formatter_test.rb b/test/new_relic/agent/datastores/mongo/event_formatter_test.rb index 3b8fad6bcc..d1933c9786 100644 --- a/test/new_relic/agent/datastores/mongo/event_formatter_test.rb +++ b/test/new_relic/agent/datastores/mongo/event_formatter_test.rb @@ -13,36 +13,36 @@ class EventFormatterTest < Minitest::Test DATABASE = 'multiverse'.freeze FIND_COMMAND = { - "find" => "tribbles", - "filter" => {"_id" => {"$gt" => 1}, "name" => "joe"}, - "sort" => {"_id" => 1}, - "limit" => 2, - "skip" => 2, - "comment" => "test", - "hint" => {"_id" => 1}, - "max" => {"_id" => 6}, - "maxScan" => 5000, - "maxTimeMS" => 6000, - "min" => {"_id" => 0}, - "readPreference" => {"mode" => "secondaryPreferred"}, - "returnKey" => false, - "showRecordId" => false, - "snapshot" => false + 'find' => 'tribbles', + 'filter' => {'_id' => {'$gt' => 1}, 'name' => 'joe'}, + 'sort' => {'_id' => 1}, + 'limit' => 2, + 'skip' => 2, + 'comment' => 'test', + 'hint' => {'_id' => 1}, + 'max' => {'_id' => 6}, + 'maxScan' => 5000, + 'maxTimeMS' => 6000, + 'min' => {'_id' => 0}, + 'readPreference' => {'mode' => 'secondaryPreferred'}, + 'returnKey' => false, + 'showRecordId' => false, + 'snapshot' => false }.freeze INSERT_COMMAND = { - "insert" => "tribbles", - "ordered" => true, - "documents" => [{:name => "test"}] + 'insert' => 'tribbles', + 'ordered' => true, + 'documents' => [{:name => 'test'}] }.freeze UPDATE_COMMAND = { - "update" => "tribbles", - "ordered" => true, - "updates" => [ + 'update' => 'tribbles', + 'ordered' => true, + 'updates' => [ { - :q => {:_id => {"$gt" => 1}}, - :u => {"$inc" => {:x => 1}}, + :q => {:_id => {'$gt' => 1}}, + :u => {'$inc' => {:x => 1}}, :multi => false, :upsert => false } @@ -50,16 +50,16 @@ class EventFormatterTest < Minitest::Test }.freeze DELETE_COMMAND = { - "delete" => "tribbles", - "ordered" => true, - "deletes" => [{:q => {:_id => {"$gt" => 1}}, :limit => 1}] + 'delete' => 'tribbles', + 'ordered' => true, + 'deletes' => [{:q => {:_id => {'$gt' => 1}}, :limit => 1}] }.freeze AGGREGATE_COMMAND = { - "aggregate" => "tribbles", - "pipeline" => [ - {"$group" => {"_id" => "name", "max" => {"$max" => "$count"}}}, - {"$match" => {"max" => {"$gte" => 1}}} + 'aggregate' => 'tribbles', + 'pipeline' => [ + {'$group' => {'_id' => 'name', 'max' => {'$max' => '$count'}}}, + {'$match' => {'max' => {'$gte' => 1}}} ] } @@ -81,22 +81,22 @@ def test_event_formatter_obfuscates_by_default expected = { :operation => :find, :database => DATABASE, - :collection => "tribbles", - "find" => "tribbles", - "filter" => {"_id" => {"$gt" => "?"}, "name" => "?"}, - "sort" => {"_id" => 1}, - "limit" => 2, - "skip" => 2, - "comment" => "test", - "hint" => {"_id" => 1}, - "max" => {"_id" => 6}, - "maxScan" => 5000, - "maxTimeMS" => 6000, - "min" => {"_id" => 0}, - "readPreference" => {"mode" => "secondaryPreferred"}, - "returnKey" => false, - "showRecordId" => false, - "snapshot" => false + :collection => 'tribbles', + 'find' => 'tribbles', + 'filter' => {'_id' => {'$gt' => '?'}, 'name' => '?'}, + 'sort' => {'_id' => 1}, + 'limit' => 2, + 'skip' => 2, + 'comment' => 'test', + 'hint' => {'_id' => 1}, + 'max' => {'_id' => 6}, + 'maxScan' => 5000, + 'maxTimeMS' => 6000, + 'min' => {'_id' => 0}, + 'readPreference' => {'mode' => 'secondaryPreferred'}, + 'returnKey' => false, + 'showRecordId' => false, + 'snapshot' => false } formatted = EventFormatter.format(:find, DATABASE, FIND_COMMAND) @@ -121,9 +121,9 @@ def test_event_formatter_whitelists_inserts expected = { :operation => :insert, :database => DATABASE, - :collection => "tribbles", - "insert" => "tribbles", - "ordered" => true + :collection => 'tribbles', + 'insert' => 'tribbles', + 'ordered' => true } formatted = EventFormatter.format(:insert, DATABASE, INSERT_COMMAND) @@ -135,9 +135,9 @@ def test_event_formatter_whitelists_updates expected = { :operation => :update, :database => DATABASE, - :collection => "tribbles", - "update" => "tribbles", - "ordered" => true + :collection => 'tribbles', + 'update' => 'tribbles', + 'ordered' => true } formatted = EventFormatter.format(:update, DATABASE, UPDATE_COMMAND) @@ -149,11 +149,11 @@ def test_event_formatter_obfuscates_pipeline expected = { :operation => :aggregate, :database => DATABASE, - :collection => "tribbles", - "aggregate" => "tribbles", - "pipeline" => [ - {"$group" => {"_id" => "?", "max" => {"$max" => "?"}}}, - {"$match" => {"max" => {"$gte" => "?"}}} + :collection => 'tribbles', + 'aggregate' => 'tribbles', + 'pipeline' => [ + {'$group' => {'_id' => '?', 'max' => {'$max' => '?'}}}, + {'$match' => {'max' => {'$gte' => '?'}}} ] } @@ -166,9 +166,9 @@ def test_event_formatter_whitelists_deletes expected = { :operation => :delete, :database => DATABASE, - :collection => "tribbles", - "delete" => "tribbles", - "ordered" => true + :collection => 'tribbles', + 'delete' => 'tribbles', + 'ordered' => true } formatted = EventFormatter.format(:delete, DATABASE, DELETE_COMMAND) diff --git a/test/new_relic/agent/datastores/mongo/metric_translator_test.rb b/test/new_relic/agent/datastores/mongo/metric_translator_test.rb index 5b6b3ebbfe..b9c2a8a4f0 100644 --- a/test/new_relic/agent/datastores/mongo/metric_translator_test.rb +++ b/test/new_relic/agent/datastores/mongo/metric_translator_test.rb @@ -20,7 +20,7 @@ def test_operation_and_collection_for_insert end def test_operation_and_collection_for_is_graceful_if_exceptions_are_raised - NewRelic::Agent::Datastores::Mongo::MetricTranslator.stubs(:find_one?).raises("Boom") + NewRelic::Agent::Datastores::Mongo::MetricTranslator.stubs(:find_one?).raises('Boom') result = NewRelic::Agent::Datastores::Mongo::MetricTranslator.operation_and_collection_for(:find, {}) assert_nil result @@ -29,7 +29,7 @@ def test_operation_and_collection_for_is_graceful_if_exceptions_are_raised def test_operation_and_collection_for_find payload = {:database => @database_name, :collection => @collection_name, - :selector => {"name" => "soterios johnson"}} + :selector => {'name' => 'soterios johnson'}} result = NewRelic::Agent::Datastores::Mongo::MetricTranslator.operation_and_collection_for(:find, payload) @@ -50,7 +50,7 @@ def test_operation_and_collection_for_find_one def test_operation_and_collection_for_remove payload = {:database => @database_name, :collection => @collection_name, - :selector => {"name" => "soterios johnson"}} + :selector => {'name' => 'soterios johnson'}} result = NewRelic::Agent::Datastores::Mongo::MetricTranslator.operation_and_collection_for(:remove, payload) @@ -60,8 +60,8 @@ def test_operation_and_collection_for_remove def test_operation_and_collection_for_update payload = {:database => @database_name, :collection => @collection_name, - :selector => {"name" => "soterios johnson"}, - :document => {"name" => "codemonkey"}} + :selector => {'name' => 'soterios johnson'}, + :document => {'name' => 'codemonkey'}} result = NewRelic::Agent::Datastores::Mongo::MetricTranslator.operation_and_collection_for(:update, payload) @@ -70,10 +70,10 @@ def test_operation_and_collection_for_update def test_operation_and_collection_for_distinct payload = {:database => @database_name, - :collection => "$cmd", + :collection => '$cmd', :limit => -1, :selector => {:distinct => @collection_name, - :key => "name", + :key => 'name', :query => nil}} result = NewRelic::Agent::Datastores::Mongo::MetricTranslator.operation_and_collection_for(:distinct, payload) @@ -83,11 +83,11 @@ def test_operation_and_collection_for_distinct def test_operation_and_collection_for_count payload = {:database => @database_name, - :collection => "$cmd", + :collection => '$cmd', :limit => -1, - :selector => {"count" => @collection_name, - "query" => {}, - "fields" => nil}} + :selector => {'count' => @collection_name, + 'query' => {}, + 'fields' => nil}} result = NewRelic::Agent::Datastores::Mongo::MetricTranslator.operation_and_collection_for(:find, payload) @@ -96,13 +96,13 @@ def test_operation_and_collection_for_count def test_operation_and_collection_for_group payload = {:database => @database_name, - :collection => "$cmd", + :collection => '$cmd', :limit => -1, - :selector => {"group" => {"ns" => @collection_name, - "$reduce" => stub("BSON::Code"), - "cond" => {}, - "initial" => {:count => 0}, - "key" => {"name" => 1}}}} + :selector => {'group' => {'ns' => @collection_name, + '$reduce' => stub('BSON::Code'), + 'cond' => {}, + 'initial' => {:count => 0}, + 'key' => {'name' => 1}}}} result = NewRelic::Agent::Datastores::Mongo::MetricTranslator.operation_and_collection_for(:find, payload) @@ -111,10 +111,10 @@ def test_operation_and_collection_for_group def test_operation_and_collection_for_aggregate payload = {:database => @database_name, - :collection => "$cmd", + :collection => '$cmd', :limit => -1, - :selector => {"aggregate" => @collection_name, - "pipeline" => [{"$group" => {:_id => "$says", :total => {"$sum" => 1}}}]}} + :selector => {'aggregate' => @collection_name, + 'pipeline' => [{'$group' => {:_id => '$says', :total => {'$sum' => 1}}}]}} result = NewRelic::Agent::Datastores::Mongo::MetricTranslator.operation_and_collection_for(:find, payload) @@ -123,12 +123,12 @@ def test_operation_and_collection_for_aggregate def test_operation_and_collection_for_mapreduce payload = {:database => @database_name, - :collection => "$cmd", + :collection => '$cmd', :limit => -1, - :selector => {"mapreduce" => @collection_name, - "map" => stub("BSON::Code"), - "reduce" => stub("BSON::Code"), - :out => "results"}} + :selector => {'mapreduce' => @collection_name, + 'map' => stub('BSON::Code'), + 'reduce' => stub('BSON::Code'), + :out => 'results'}} result = NewRelic::Agent::Datastores::Mongo::MetricTranslator.operation_and_collection_for(:find, payload) @@ -137,11 +137,11 @@ def test_operation_and_collection_for_mapreduce def test_operation_and_collection_for_find_and_modify payload = {:database => @database_name, - :collection => "$cmd", + :collection => '$cmd', :limit => -1, :selector => {:findandmodify => @collection_name, - :query => {"name" => "soterios johnson"}, - :update => {"name" => "codemonkey"}}} + :query => {'name' => 'soterios johnson'}, + :update => {'name' => 'codemonkey'}}} result = NewRelic::Agent::Datastores::Mongo::MetricTranslator.operation_and_collection_for(:find, payload) @@ -150,10 +150,10 @@ def test_operation_and_collection_for_find_and_modify def test_operation_and_collection_for_find_and_remove payload = {:database => @database_name, - :collection => "$cmd", + :collection => '$cmd', :limit => -1, :selector => {:findandmodify => @collection_name, - :query => {"name" => "soterios johnson"}, + :query => {'name' => 'soterios johnson'}, :remove => true}} result = NewRelic::Agent::Datastores::Mongo::MetricTranslator.operation_and_collection_for(:find, payload) @@ -163,10 +163,10 @@ def test_operation_and_collection_for_find_and_remove def test_operation_and_collection_for_create_index payload = {:database => @database_name, - :collection => "system.indexes", - :documents => [{:name => "name_1", + :collection => 'system.indexes', + :documents => [{:name => 'name_1', :ns => "#{@database_name}.#{@collection_name}", - :key => {"name" => 1}}]} + :key => {'name' => 1}}]} result = NewRelic::Agent::Datastores::Mongo::MetricTranslator.operation_and_collection_for(:insert, payload) @@ -175,10 +175,10 @@ def test_operation_and_collection_for_create_index def test_operation_and_collection_for_drop_indexes payload = {:database => @database_name, - :collection => "$cmd", + :collection => '$cmd', :limit => -1, :selector => {:deleteIndexes => @collection_name, - :index => "*"}} + :index => '*'}} result = NewRelic::Agent::Datastores::Mongo::MetricTranslator.operation_and_collection_for(:find, payload) @@ -187,10 +187,10 @@ def test_operation_and_collection_for_drop_indexes def test_operation_and_collection_for_drop_index payload = {:database => @database_name, - :collection => "$cmd", + :collection => '$cmd', :limit => -1, :selector => {:deleteIndexes => @collection_name, - :index => "name_1"}} + :index => 'name_1'}} result = NewRelic::Agent::Datastores::Mongo::MetricTranslator.operation_and_collection_for(:find, payload) @@ -199,7 +199,7 @@ def test_operation_and_collection_for_drop_index def test_operation_and_collection_for_reindex payload = {:database => @database_name, - :collection => "$cmd", + :collection => '$cmd', :limit => -1, :selector => {:reIndex => @collection_name}} @@ -210,7 +210,7 @@ def test_operation_and_collection_for_reindex def test_operation_and_collection_for_drop_collection payload = {:database => @database_name, - :collection => "$cmd", + :collection => '$cmd', :limit => -1, :selector => {:drop => @collection_name}} @@ -221,7 +221,7 @@ def test_operation_and_collection_for_drop_collection def test_operation_and_collection_for_rename_collection payload = {:database => @database_name, - :collection => "$cmd", + :collection => '$cmd', :limit => -1, :selector => {:renameCollection => "#{@database_name}.#{@collection_name}", :to => "#{@database_name}.renamed_#{@collection_name}"}} @@ -233,11 +233,11 @@ def test_operation_and_collection_for_rename_collection def test_operation_and_collection_for_ismaster payload = {:database => @database_name, - :collection => "$cmd", + :collection => '$cmd', :limit => -1, :selector => {:ismaster => 1}} - @collection_name = "$cmd" + @collection_name = '$cmd' result = NewRelic::Agent::Datastores::Mongo::MetricTranslator.operation_and_collection_for(:find, payload) @@ -246,7 +246,7 @@ def test_operation_and_collection_for_ismaster def test_operation_and_collection_for_collstats payload = {:database => @database_name, - :collection => "$cmd", + :collection => '$cmd', :limit => -1, :selector => {:collstats => @collection_name}} @@ -257,15 +257,15 @@ def test_operation_and_collection_for_collstats def test_operation_and_collection_for_unknown_command payload = {:database => @database_name, - :collection => "$cmd", + :collection => '$cmd', :limit => -1, :selector => {:mongomongomongo => @collection_name}} - @collection_name = "$cmd" + @collection_name = '$cmd' result = NewRelic::Agent::Datastores::Mongo::MetricTranslator.operation_and_collection_for(:find, payload) assert_equal ['mongomongomongo', @collection_name], result - assert_metrics_recorded(["Supportability/Mongo/UnknownCollection"]) + assert_metrics_recorded(['Supportability/Mongo/UnknownCollection']) end end diff --git a/test/new_relic/agent/datastores/nosql_obfuscator_test.rb b/test/new_relic/agent/datastores/nosql_obfuscator_test.rb index a28d3a6c0a..e01f8ea3b9 100644 --- a/test/new_relic/agent/datastores/nosql_obfuscator_test.rb +++ b/test/new_relic/agent/datastores/nosql_obfuscator_test.rb @@ -47,22 +47,22 @@ def test_obfuscate_selector_values_skips_allowed_keys def test_obfuscate_nested_hashes selector = { - "group" => { - "ns" => "tribbles", - "$reduce" => stub("BSON::Code"), - "cond" => {}, - "initial" => {:count => 0}, - "key" => {"name" => 1} + 'group' => { + 'ns' => 'tribbles', + '$reduce' => stub('BSON::Code'), + 'cond' => {}, + 'initial' => {:count => 0}, + 'key' => {'name' => 1} } } expected = { - "group" => { - "ns" => "?", - "$reduce" => "?", - "cond" => {}, - "initial" => {:count => "?"}, - "key" => {"name" => "?"} + 'group' => { + 'ns' => '?', + '$reduce' => '?', + 'cond' => {}, + 'initial' => {:count => '?'}, + 'key' => {'name' => '?'} } } @@ -72,8 +72,8 @@ def test_obfuscate_nested_hashes end def test_obfuscates_array_statement - statement = [{"$group" => {:_id => "$says", :total => {"$sum" => 1}}}] - expected = [{"$group" => {:_id => "?", :total => {"$sum" => "?"}}}] + statement = [{'$group' => {:_id => '$says', :total => {'$sum' => 1}}}] + expected = [{'$group' => {:_id => '?', :total => {'$sum' => '?'}}}] obfuscated = NosqlObfuscator.obfuscate_statement(statement) @@ -82,13 +82,13 @@ def test_obfuscates_array_statement def test_obfuscate_nested_arrays selector = { - "aggregate" => "mongeese", - "pipeline" => [{"$group" => {:_id => "$says", :total => {"$sum" => 1}}}] + 'aggregate' => 'mongeese', + 'pipeline' => [{'$group' => {:_id => '$says', :total => {'$sum' => 1}}}] } expected = { - "aggregate" => "?", - "pipeline" => [{"$group" => {:_id => "?", :total => {"$sum" => "?"}}}] + 'aggregate' => '?', + 'pipeline' => [{'$group' => {:_id => '?', :total => {'$sum' => '?'}}}] } obfuscated = NosqlObfuscator.obfuscate_statement(selector) diff --git a/test/new_relic/agent/datastores/redis_test.rb b/test/new_relic/agent/datastores/redis_test.rb index a05dd86673..fe134d5296 100644 --- a/test/new_relic/agent/datastores/redis_test.rb +++ b/test/new_relic/agent/datastores/redis_test.rb @@ -7,7 +7,7 @@ class NewRelic::Agent::Datastores::RedisTest < Minitest::Test def test_format_command - expected = "set \"foo\" \"bar\"" + expected = 'set "foo" "bar"' with_config(:'transaction_tracer.record_redis_arguments' => true) do result = NewRelic::Agent::Datastores::Redis.format_command([:set, 'foo', 'bar']) @@ -17,8 +17,8 @@ def test_format_command end def test_format_command_truncates_long_arguments - key = "namespace.other_namespace.different_namespace.why.would.you.do.this.key" - expected_key = "namespace.other_namespace.dif...ace.why.would.you.do.this.key" + key = 'namespace.other_namespace.different_namespace.why.would.you.do.this.key' + expected_key = 'namespace.other_namespace.dif...ace.why.would.you.do.this.key' expected = "set \"#{expected_key}\" \"redoctober\"" @@ -30,7 +30,7 @@ def test_format_command_truncates_long_arguments end def test_format_command_truncates_long_commands - key = "key" + key = 'key' command = [:set] + Array.new(NewRelic::Agent::Datastores::Redis::MAXIMUM_COMMAND_LENGTH, key) with_config(:'transaction_tracer.record_redis_arguments' => true) do @@ -49,7 +49,7 @@ def test_format_command_with_record_arguments_false end def test_format_command_in_pipeline - expected = "set \"foo\" \"bar\"" + expected = 'set "foo" "bar"' with_config(:'transaction_tracer.record_redis_arguments' => true) do result = NewRelic::Agent::Datastores::Redis.format_command([:set, 'foo', 'bar']) @@ -62,7 +62,7 @@ def test_append_command_in_pipeline_with_record_arguments_false expected = 'set ?' with_config(:'transaction_tracer.record_redis_arguments' => false) do - result = String.new('') + result = +'' NewRelic::Agent::Datastores::Redis.append_pipeline_command(result, [:set, 'foo', 'bar']) assert_equal expected, result @@ -73,7 +73,7 @@ def test_append_command_in_pipeline_with_record_arguments_and_no_args expected = 'multi' with_config(:'transaction_tracer.record_redis_arguments' => true) do - result = String.new('') + result = +'' NewRelic::Agent::Datastores::Redis.append_pipeline_command(result, [:multi]) assert_equal expected, result @@ -84,7 +84,7 @@ def test_append_command_in_pipeline_with_record_arguments_false_and_no_args expected = 'multi' with_config(:'transaction_tracer.record_redis_arguments' => false) do - result = String.new('') + result = +'' NewRelic::Agent::Datastores::Redis.append_pipeline_command(result, [:multi]) assert_equal expected, result @@ -93,19 +93,19 @@ def test_append_command_in_pipeline_with_record_arguments_false_and_no_args def test_format_pipeline_commands_truncates_long_commands pipeline = Array.new(NewRelic::Agent::Datastores::Redis::MAXIMUM_COMMAND_LENGTH) do - [:set, "0123456789"] + [:set, '0123456789'] end with_config(:'transaction_tracer.record_redis_arguments' => true) do result = NewRelic::Agent::Datastores::Redis.format_pipeline_commands(pipeline) assert_equal result.length, NewRelic::Agent::Datastores::Redis::MAXIMUM_COMMAND_LENGTH - assert result.end_with?("012345...") + assert result.end_with?('012345...') end end def test_format_command_with_non_string_argument - expected = "set \"key\" true" + expected = 'set "key" true' with_config(:'transaction_tracer.record_redis_arguments' => true) do result = NewRelic::Agent::Datastores::Redis.format_command([:set, 'key', true]) @@ -115,7 +115,7 @@ def test_format_command_with_non_string_argument end def test_format_command_handles_binary_strings - binary_string = (0..255).to_a.pack("c*") + binary_string = (0..255).to_a.pack('c*') expected = 'set "key" ' with_config(:'transaction_tracer.record_redis_arguments' => true) do @@ -126,7 +126,7 @@ def test_format_command_handles_binary_strings end def test_format_command_in_pipeline_handles_binary_strings - binary_string = (0..255).to_a.pack("c*") + binary_string = (0..255).to_a.pack('c*') expected = 'set "key" ' with_config(:'transaction_tracer.record_redis_arguments' => true) do diff --git a/test/new_relic/agent/datastores_test.rb b/test/new_relic/agent/datastores_test.rb index 16ddfe993e..123a50c04f 100644 --- a/test/new_relic/agent/datastores_test.rb +++ b/test/new_relic/agent/datastores_test.rb @@ -21,15 +21,15 @@ def internal private :internal - NewRelic::Agent::Datastores.trace(self, :find, "MyFirstDatabase") - NewRelic::Agent::Datastores.trace(self, :save, "MyFirstDatabase", "create") - NewRelic::Agent::Datastores.trace(self, :internal, "MyFirstDatabase") + NewRelic::Agent::Datastores.trace(self, :find, 'MyFirstDatabase') + NewRelic::Agent::Datastores.trace(self, :save, 'MyFirstDatabase', 'create') + NewRelic::Agent::Datastores.trace(self, :internal, 'MyFirstDatabase') def boom - raise "haha" + raise 'haha' end - NewRelic::Agent::Datastores.trace(self, :boom, "MyFirstDatabase", "boom") + NewRelic::Agent::Datastores.trace(self, :boom, 'MyFirstDatabase', 'boom') end def setup @@ -42,32 +42,32 @@ def test_still_calls_through end def test_in_web_transaction - in_web_transaction("txn") do + in_web_transaction('txn') do MyFirstDatabase.new.find end - assert_metrics("find", "Web") + assert_metrics('find', 'Web') end def test_in_other_transaction - in_background_transaction("txn") do + in_background_transaction('txn') do MyFirstDatabase.new.find end - assert_metrics("find", "Other") + assert_metrics('find', 'Other') end def test_separate_operation_name - in_background_transaction("txn") do + in_background_transaction('txn') do MyFirstDatabase.new.save end - assert_metrics("create", "Other") + assert_metrics('create', 'Other') end def test_safe_to_reinstrument MyFirstDatabase.class_eval do - NewRelic::Agent::Datastores.trace(self, :find, "MyFirstDatabase", "find") + NewRelic::Agent::Datastores.trace(self, :find, 'MyFirstDatabase', 'find') end assert_equal MyFirstDatabase::THE_OBJECT, MyFirstDatabase.new.find @@ -80,43 +80,43 @@ def test_method_retains_visibility end def test_wrap_doesnt_interfere - result = NewRelic::Agent::Datastores.wrap("MyFirstDatabase", "op") do - "yo" + result = NewRelic::Agent::Datastores.wrap('MyFirstDatabase', 'op') do + 'yo' end - assert_equal "yo", result + assert_equal 'yo', result end def test_wrap - in_background_transaction("txn") do - NewRelic::Agent::Datastores.wrap("MyFirstDatabase", "op", "coll") do + in_background_transaction('txn') do + NewRelic::Agent::Datastores.wrap('MyFirstDatabase', 'op', 'coll') do end end - assert_statement_metrics("op", "coll", "Other") + assert_statement_metrics('op', 'coll', 'Other') end def test_wrap_with_only_operation - in_background_transaction("txn") do - NewRelic::Agent::Datastores.wrap("MyFirstDatabase", "op") do + in_background_transaction('txn') do + NewRelic::Agent::Datastores.wrap('MyFirstDatabase', 'op') do end end - assert_metrics("op", "Other") + assert_metrics('op', 'Other') end def test_wrap_with_no_operation - in_background_transaction("txn") do - NewRelic::Agent::Datastores.wrap("MyFirstDatabase", nil) do + in_background_transaction('txn') do + NewRelic::Agent::Datastores.wrap('MyFirstDatabase', nil) do end end refute_metrics_recorded([ - "Datastore/operation/MyFirstDatabase/", - "Datastore/MyFirstDatabase/allOther", - "Datastore/MyFirstDatabase/all", - "Datastore/allOther", - "Datastore/all" + 'Datastore/operation/MyFirstDatabase/', + 'Datastore/MyFirstDatabase/allOther', + 'Datastore/MyFirstDatabase/all', + 'Datastore/allOther', + 'Datastore/all' ]) end @@ -126,28 +126,28 @@ def test_wrap_calls_notice noticed = args end - NewRelic::Agent::Datastores.wrap("MyFirstDatabase", "op", "coll", notice) do - "yo" + NewRelic::Agent::Datastores.wrap('MyFirstDatabase', 'op', 'coll', notice) do + 'yo' end result, scoped_metric, elapsed = noticed - assert_equal "yo", result - assert_equal "Datastore/statement/MyFirstDatabase/coll/op", scoped_metric + assert_equal 'yo', result + assert_equal 'Datastore/statement/MyFirstDatabase/coll/op', scoped_metric assert_instance_of Float, elapsed end def test_notice_sql - query = "SELECT * FROM SomeThings" - metric = "Datastore/statement/MyFirstDatabase/SomeThing/find" + query = 'SELECT * FROM SomeThings' + metric = 'Datastore/statement/MyFirstDatabase/SomeThing/find' elapsed = 1.0 in_transaction do |txn| nr_freeze_process_time segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "MyFirstDatabase", - operation: "find", - collection: "SomeThing" + product: 'MyFirstDatabase', + operation: 'find', + collection: 'SomeThing' ) NewRelic::Agent::Datastores.notice_sql(query, metric, elapsed) advance_process_time(elapsed) @@ -162,15 +162,15 @@ def test_notice_sql end def test_notice_statement - query = "key" + query = 'key' elapsed = 1.0 in_transaction do |txn| nr_freeze_process_time segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "MyFirstDatastore", - operation: "get", - collection: "key" + product: 'MyFirstDatastore', + operation: 'get', + collection: 'key' ) NewRelic::Agent::Datastores.notice_statement(query, elapsed) advance_process_time(elapsed) @@ -185,7 +185,7 @@ def test_notice_statement end def test_dont_notice_statement_based_on_record_sql_setting - query = "key" + query = 'key' elapsed = 1.0 agent = NewRelic::Agent.instance @@ -207,29 +207,29 @@ def test_node_created_when_exception_occurs rescue sample = last_transaction_trace - refute_nil find_node_with_name(sample, "Datastore/operation/MyFirstDatabase/boom") + refute_nil find_node_with_name(sample, 'Datastore/operation/MyFirstDatabase/boom') end def assert_statement_metrics(operation, collection, type) assert_metrics_recorded([ "Datastore/statement/MyFirstDatabase/#{collection}/#{operation}", - ["Datastore/statement/MyFirstDatabase/#{collection}/#{operation}", "txn"], + ["Datastore/statement/MyFirstDatabase/#{collection}/#{operation}", 'txn'], "Datastore/operation/MyFirstDatabase/#{operation}", "Datastore/MyFirstDatabase/all#{type}", - "Datastore/MyFirstDatabase/all", + 'Datastore/MyFirstDatabase/all', "Datastore/all#{type}", - "Datastore/all" + 'Datastore/all' ]) end def assert_metrics(operation, type) assert_metrics_recorded([ "Datastore/operation/MyFirstDatabase/#{operation}", - ["Datastore/operation/MyFirstDatabase/#{operation}", "txn"], + ["Datastore/operation/MyFirstDatabase/#{operation}", 'txn'], "Datastore/MyFirstDatabase/all#{type}", - "Datastore/MyFirstDatabase/all", + 'Datastore/MyFirstDatabase/all', "Datastore/all#{type}", - "Datastore/all" + 'Datastore/all' ]) end end diff --git a/test/new_relic/agent/deprecator_test.rb b/test/new_relic/agent/deprecator_test.rb index c0254dbffb..ae170d411d 100644 --- a/test/new_relic/agent/deprecator_test.rb +++ b/test/new_relic/agent/deprecator_test.rb @@ -9,7 +9,7 @@ class DeprecatorTest < Minitest::Test def setup @old_method = :foo @new_method = :bar - @version = "3.11.0" + @version = '3.11.0' end def teardown @@ -48,6 +48,6 @@ def test_deprecator_logs_the_version_if_given def test_deprecator_reports_a_supportability_metric NewRelic::Agent::Deprecator.deprecate(:deprecated_supportability_test) - assert_metrics_recorded("Supportability/Deprecated/deprecated_supportability_test") + assert_metrics_recorded('Supportability/Deprecated/deprecated_supportability_test') end end diff --git a/test/new_relic/agent/distributed_tracing/distributed_trace_metrics_test.rb b/test/new_relic/agent/distributed_tracing/distributed_trace_metrics_test.rb index 9d15881706..3c55bd4fbd 100644 --- a/test/new_relic/agent/distributed_tracing/distributed_trace_metrics_test.rb +++ b/test/new_relic/agent/distributed_tracing/distributed_trace_metrics_test.rb @@ -9,8 +9,8 @@ class DistributedTraceMetricsTest < Minitest::Test def setup nr_freeze_process_time @config = { - :account_id => "190", - :primary_application_id => "46954", + :account_id => '190', + :primary_application_id => '46954', :disable_harvest_thread => true, :"distributed_tracing.enabled" => true } @@ -24,7 +24,7 @@ def teardown end def in_controller_transaction(&blk) - in_transaction("controller_txn", :category => :controller) do |txn| + in_transaction('controller_txn', :category => :controller) do |txn| advance_process_time(1.0) yield(txn) end @@ -38,93 +38,93 @@ def valid_trace_context_headers end def test_transaction_type_suffix - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| txn.distributed_tracer.create_trace_state_payload - assert_equal "allOther", DistributedTraceMetrics.transaction_type_suffix + assert_equal 'allOther', DistributedTraceMetrics.transaction_type_suffix end - in_transaction("controller", :category => :controller) do |txn| - assert_equal "allWeb", DistributedTraceMetrics.transaction_type_suffix + in_transaction('controller', :category => :controller) do |txn| + assert_equal 'allWeb', DistributedTraceMetrics.transaction_type_suffix end end def test_prefix_for_metric - in_transaction("test_txn", :category => :controller) do |txn| + in_transaction('test_txn', :category => :controller) do |txn| payload = txn.distributed_tracer.create_trace_state_payload - assert payload, "payload should not be nil" + assert payload, 'payload should not be nil' - prefix = DistributedTraceMetrics.prefix_for_metric("Test", txn, payload) + prefix = DistributedTraceMetrics.prefix_for_metric('Test', txn, payload) - assert_equal "Test/App/190/46954/Unknown", prefix + assert_equal 'Test/App/190/46954/Unknown', prefix end end def test_record_metrics_for_transaction - in_transaction("test_txn", :category => :controller) do |txn| + in_transaction('test_txn', :category => :controller) do |txn| advance_process_time(1.0) payload = txn.distributed_tracer.create_trace_state_payload - assert payload, "payload should not be nil" + assert payload, 'payload should not be nil' DistributedTraceMetrics.record_metrics_for_transaction(txn) end assert_metrics_recorded([ - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all", - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb" + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/all', + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb' ]) end def test_record_metrics_for_transaction_with_payload - in_transaction("controller_txn", :category => :controller) do |txn| + in_transaction('controller_txn', :category => :controller) do |txn| advance_process_time(1.0) DistributedTracing.accept_distributed_trace_headers(valid_trace_context_headers, NewRelic::HTTP) DistributedTraceMetrics.record_metrics_for_transaction(txn) end assert_metrics_recorded([ - "DurationByCaller/Browser/212311/51424/HTTP/all", - "DurationByCaller/Browser/212311/51424/HTTP/allWeb", - "TransportDuration/Browser/212311/51424/HTTP/all", - "TransportDuration/Browser/212311/51424/HTTP/allWeb" + 'DurationByCaller/Browser/212311/51424/HTTP/all', + 'DurationByCaller/Browser/212311/51424/HTTP/allWeb', + 'TransportDuration/Browser/212311/51424/HTTP/all', + 'TransportDuration/Browser/212311/51424/HTTP/allWeb' ]) refute_metrics_recorded([ - "ErrorsByCaller/Browser/212311/51424/HTTP/all", - "ErrorsByCaller/Browser/212311/51424/HTTP/allWeb", - "ErrorsByCaller/Browser/212311/51424/Unknown/all", - "ErrorsByCaller/Browser/212311/51424/Unknown/allWeb" + 'ErrorsByCaller/Browser/212311/51424/HTTP/all', + 'ErrorsByCaller/Browser/212311/51424/HTTP/allWeb', + 'ErrorsByCaller/Browser/212311/51424/Unknown/all', + 'ErrorsByCaller/Browser/212311/51424/Unknown/allWeb' ]) end def test_record_metrics_for_transaction_with_garbage_transport_type - in_transaction("controller_txn", :category => :controller) do |txn| + in_transaction('controller_txn', :category => :controller) do |txn| advance_process_time(1.0) - DistributedTracing.accept_distributed_trace_headers(valid_trace_context_headers, "garbage") + DistributedTracing.accept_distributed_trace_headers(valid_trace_context_headers, 'garbage') DistributedTraceMetrics.record_metrics_for_transaction(txn) end assert_metrics_recorded([ - "DurationByCaller/Browser/212311/51424/Unknown/all", - "DurationByCaller/Browser/212311/51424/Unknown/allWeb", - "TransportDuration/Browser/212311/51424/Unknown/all", - "TransportDuration/Browser/212311/51424/Unknown/allWeb" + 'DurationByCaller/Browser/212311/51424/Unknown/all', + 'DurationByCaller/Browser/212311/51424/Unknown/allWeb', + 'TransportDuration/Browser/212311/51424/Unknown/all', + 'TransportDuration/Browser/212311/51424/Unknown/allWeb' ]) refute_metrics_recorded([ - "ErrorsByCaller/Browser/212311/51424/HTTP/all", - "ErrorsByCaller/Browser/212311/51424/HTTP/allWeb", - "ErrorsByCaller/Browser/212311/51424/Unknown/all", - "ErrorsByCaller/Browser/212311/51424/Unknown/allWeb" + 'ErrorsByCaller/Browser/212311/51424/HTTP/all', + 'ErrorsByCaller/Browser/212311/51424/HTTP/allWeb', + 'ErrorsByCaller/Browser/212311/51424/Unknown/all', + 'ErrorsByCaller/Browser/212311/51424/Unknown/allWeb' ]) end def test_record_metrics_for_transaction_with_exception_handling - in_transaction("controller_txn", :category => :controller) do |txn| + in_transaction('controller_txn', :category => :controller) do |txn| begin advance_process_time(1.0) DistributedTracing.accept_distributed_trace_headers(valid_trace_context_headers, NewRelic::HTTP) - raise "oops" + raise 'oops' rescue Exception => e Transaction.notice_error(e) DistributedTraceMetrics.record_metrics_for_transaction(txn) @@ -132,12 +132,12 @@ def test_record_metrics_for_transaction_with_exception_handling end assert_metrics_recorded([ - "DurationByCaller/Browser/212311/51424/HTTP/all", - "DurationByCaller/Browser/212311/51424/HTTP/allWeb", - "TransportDuration/Browser/212311/51424/HTTP/all", - "TransportDuration/Browser/212311/51424/HTTP/allWeb", - "ErrorsByCaller/Browser/212311/51424/HTTP/all", - "ErrorsByCaller/Browser/212311/51424/HTTP/allWeb" + 'DurationByCaller/Browser/212311/51424/HTTP/all', + 'DurationByCaller/Browser/212311/51424/HTTP/allWeb', + 'TransportDuration/Browser/212311/51424/HTTP/all', + 'TransportDuration/Browser/212311/51424/HTTP/allWeb', + 'ErrorsByCaller/Browser/212311/51424/HTTP/all', + 'ErrorsByCaller/Browser/212311/51424/HTTP/allWeb' ]) end end diff --git a/test/new_relic/agent/distributed_tracing/distributed_trace_payload_test.rb b/test/new_relic/agent/distributed_tracing/distributed_trace_payload_test.rb index 76d67352a5..2f7c32b5eb 100644 --- a/test/new_relic/agent/distributed_tracing/distributed_trace_payload_test.rb +++ b/test/new_relic/agent/distributed_tracing/distributed_trace_payload_test.rb @@ -12,9 +12,9 @@ def setup @config = { :'distributed_tracing.enabled' => true, - :account_id => "190", - :primary_application_id => "46954", - :trusted_account_key => "trust_this!" + :account_id => '190', + :primary_application_id => '46954', + :trusted_account_key => 'trust_this!' } NewRelic::Agent::DistributedTracePayload.stubs(:connected?).returns(true) NewRelic::Agent.config.add_config_for_testing(@config) @@ -30,36 +30,36 @@ def teardown def test_payload_is_created_if_connected created_at, payload = nil, nil - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| created_at = Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond) payload = DistributedTracePayload.for_transaction(txn) end - assert_equal "46954", payload.parent_app_id - assert_equal "190", payload.parent_account_id - assert_equal "trust_this!", payload.trusted_account_key + assert_equal '46954', payload.parent_app_id + assert_equal '190', payload.parent_account_id + assert_equal 'trust_this!', payload.trusted_account_key assert_equal DistributedTracePayload::VERSION, payload.version - assert_equal "App", payload.parent_type + assert_equal 'App', payload.parent_type assert_equal created_at, payload.timestamp end def test_trusted_account_id_present_if_different_than_account_id payload = nil - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| payload = DistributedTracePayload.for_transaction(txn) end - assert_equal "trust_this!", payload.trusted_account_key + assert_equal 'trust_this!', payload.trusted_account_key deserialized_payload = JSON.parse(payload.text) - assert_equal "trust_this!", deserialized_payload["d"]["tk"] + assert_equal 'trust_this!', deserialized_payload['d']['tk'] end def test_trusted_account_id_not_present_if_it_matches_account_id - with_config(:trusted_account_key => "190") do + with_config(:trusted_account_key => '190') do payload = nil - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| payload = DistributedTracePayload.for_transaction(txn) end @@ -67,14 +67,14 @@ def test_trusted_account_id_not_present_if_it_matches_account_id deserialized_payload = JSON.parse(payload.text) - refute deserialized_payload["d"].key?("tk") + refute deserialized_payload['d'].key?('tk') end end def test_attributes_are_copied_from_transaction payload = nil - transaction = in_transaction("test_txn") do |txn| + transaction = in_transaction('test_txn') do |txn| payload = DistributedTracePayload.for_transaction(txn) end @@ -85,14 +85,14 @@ def test_attributes_are_copied_from_transaction def test_sampled_flag_is_copied_from_transaction NewRelic::Agent.instance.adaptive_sampler.stubs(:sampled?).returns(false) - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| payload = DistributedTracePayload.for_transaction(txn) refute payload.sampled end NewRelic::Agent.instance.adaptive_sampler.stubs(:sampled?).returns(true) - in_transaction("test_txn2") do |txn| + in_transaction('test_txn2') do |txn| payload = DistributedTracePayload.for_transaction(txn) assert payload.sampled @@ -106,17 +106,17 @@ def test_payload_attributes_populated_from_serialized_version incoming_payload = nil - referring_transaction = in_transaction("test_txn") do |txn| + referring_transaction = in_transaction('test_txn') do |txn| incoming_payload = txn.distributed_tracer.create_distributed_trace_payload end payload = DistributedTracePayload.from_json(incoming_payload.text) assert_equal DistributedTracePayload::VERSION, payload.version - assert_equal "App", payload.parent_type - assert_equal "46954", payload.parent_app_id - assert_equal "190", payload.parent_account_id - assert_equal "trust_this!", payload.trusted_account_key + assert_equal 'App', payload.parent_type + assert_equal '46954', payload.parent_app_id + assert_equal '190', payload.parent_account_id + assert_equal 'trust_this!', payload.trusted_account_key assert_equal referring_transaction.initial_segment.guid, payload.id assert_equal referring_transaction.guid, payload.transaction_id assert_equal referring_transaction.trace_id, payload.trace_id @@ -132,17 +132,17 @@ def test_payload_attributes_populated_from_html_safe_version incoming_payload = nil - referring_transaction = in_transaction("test_txn") do |txn| + referring_transaction = in_transaction('test_txn') do |txn| incoming_payload = txn.distributed_tracer.create_distributed_trace_payload end payload = DistributedTracePayload.from_http_safe(incoming_payload.http_safe) assert_equal DistributedTracePayload::VERSION, payload.version - assert_equal "App", payload.parent_type - assert_equal "46954", payload.parent_app_id - assert_equal "190", payload.parent_account_id - assert_equal "trust_this!", payload.trusted_account_key + assert_equal 'App', payload.parent_type + assert_equal '46954', payload.parent_app_id + assert_equal '190', payload.parent_account_id + assert_equal 'trust_this!', payload.trusted_account_key assert_equal referring_transaction.initial_segment.guid, payload.id assert_equal referring_transaction.guid, payload.transaction_id assert_equal referring_transaction.trace_id, payload.trace_id @@ -155,18 +155,18 @@ def test_serialized_payload_has_expected_keys NewRelic::Agent.instance.adaptive_sampler.stubs(:sampled?).returns(true) payload = nil - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| payload = DistributedTracePayload.for_transaction(txn) end raw_payload = JSON.parse(payload.text) assert_equal_unordered %w[v d], raw_payload.keys - assert_equal_unordered %w[ty ac ap tk id tx tr pr sa ti], raw_payload["d"].keys + assert_equal_unordered %w[ty ac ap tk id tx tr pr sa ti], raw_payload['d'].keys end def test_to_json_and_from_json_are_inverse_operations - transaction = in_transaction("test_txn") {} + transaction = in_transaction('test_txn') {} payload1 = DistributedTracePayload.for_transaction(transaction) payload2 = DistributedTracePayload.from_json(payload1.text) diff --git a/test/new_relic/agent/distributed_tracing/distributed_tracing_cross_agent_test.rb b/test/new_relic/agent/distributed_tracing/distributed_tracing_cross_agent_test.rb index 3c144213de..34dbe37f0f 100644 --- a/test/new_relic/agent/distributed_tracing/distributed_tracing_cross_agent_test.rb +++ b/test/new_relic/agent/distributed_tracing/distributed_tracing_cross_agent_test.rb @@ -24,16 +24,16 @@ def self.focus_tests [] end - load_cross_agent_test("distributed_tracing/distributed_tracing").each do |test_case| - test_case['test_name'] = test_case['test_name'].tr(" ", "_") + load_cross_agent_test('distributed_tracing/distributed_tracing').each do |test_case| + test_case['test_name'] = test_case['test_name'].tr(' ', '_') if focus_tests.empty? || focus_tests.include?(test_case['test_name']) define_method("test_#{test_case['test_name']}") do - NewRelic::Agent.instance.adaptive_sampler.stubs(:sampled?).returns(test_case["force_sampled_true"]) + NewRelic::Agent.instance.adaptive_sampler.stubs(:sampled?).returns(test_case['force_sampled_true']) config = { :account_id => test_case['account_id'], - :primary_application_id => "2827902", + :primary_application_id => '2827902', :trusted_account_key => test_case['trusted_account_key'], :'span_events.enabled' => test_case['span_events_enabled'], :'distributed_tracing.enabled' => true @@ -46,7 +46,7 @@ def self.focus_tests end else define_method("test_#{test_case['test_name']}") do - skip("marked pending by exclusion from #only_tests") + skip('marked pending by exclusion from #only_tests') end end end @@ -55,8 +55,8 @@ def self.focus_tests def run_test_case(test_case) outbound_payloads = [] - if test_case['test_name'] =~ /^pending|^skip/ || test_case["pending"] || test_case["skip"] - skip("marked pending in trace_context.json") + if test_case['test_name'] =~ /^pending|^skip/ || test_case['pending'] || test_case['skip'] + skip('marked pending in trace_context.json') end in_transaction(in_transaction_options(test_case)) do |txn| accept_payloads(test_case, txn) @@ -76,7 +76,7 @@ def accept_payloads(test_case, txn) inbound_payloads = payloads_for(test_case) inbound_payloads.each do |payload| - carrier = {"HTTP_NEWRELIC" => payload} + carrier = {'HTTP_NEWRELIC' => payload} DistributedTracing.accept_distributed_trace_headers(carrier, test_case['transport_type']) end end diff --git a/test/new_relic/agent/distributed_tracing/trace_context_cross_agent_test.rb b/test/new_relic/agent/distributed_tracing/trace_context_cross_agent_test.rb index 8e2b908a20..c98c0c2fe6 100644 --- a/test/new_relic/agent/distributed_tracing/trace_context_cross_agent_test.rb +++ b/test/new_relic/agent/distributed_tracing/trace_context_cross_agent_test.rb @@ -37,18 +37,18 @@ def self.focus_tests [] end - load_cross_agent_test("distributed_tracing/trace_context").each do |test_case| - test_case['test_name'] = test_case['test_name'].tr(" ", "_") + load_cross_agent_test('distributed_tracing/trace_context').each do |test_case| + test_case['test_name'] = test_case['test_name'].tr(' ', '_') if focus_tests.empty? || focus_tests.include?(test_case['test_name']) define_method("test_#{test_case['test_name']}") do - NewRelic::Agent.instance.adaptive_sampler.stubs(:sampled?).returns(test_case["force_sampled_true"]) + NewRelic::Agent.instance.adaptive_sampler.stubs(:sampled?).returns(test_case['force_sampled_true']) config = { :'distributed_tracing.enabled' => true, :account_id => test_case['account_id'], - :primary_application_id => "2827902", + :primary_application_id => '2827902', :'transaction_events.enabled' => test_case.fetch('transaction_events_enabled', true), :trusted_account_key => test_case['trusted_account_key'], :'span_events.enabled' => test_case.fetch('span_events_enabled', true) @@ -60,7 +60,7 @@ def self.focus_tests end else define_method("test_#{test_case['test_name']}") do - skip("marked pending by exclusion from #focus_tests") + skip('marked pending by exclusion from #focus_tests') end end end @@ -69,8 +69,8 @@ def self.focus_tests def run_test_case(test_case) outbound_payloads = [] - if test_case['test_name'] =~ /^pending|^skip/ || test_case["pending"] || test_case["skip"] - skip("marked pending in trace_context.json") + if test_case['test_name'] =~ /^pending|^skip/ || test_case['pending'] || test_case['skip'] + skip('marked pending in trace_context.json') end in_transaction(in_transaction_options(test_case)) do |txn| accept_headers(test_case, txn) @@ -107,7 +107,7 @@ def create_newrelic_payloads(test_case, txn, w3c_payloads) outbound_payloads = [] if test_case['outbound_newrelic_payloads'] w3c_payloads.each do |w3c_payload| - if newrelic_header = w3c_payload["newrelic"] + if newrelic_header = w3c_payload['newrelic'] outbound_payloads << DistributedTracePayload.from_http_safe(newrelic_header) else outbound_payloads << nil @@ -133,11 +133,11 @@ def add_newrelic_entries(payload, newrelic_header) return unless newrelic_header return unless newrelic_payload = DistributedTracePayload.from_http_safe(newrelic_header) - payload["newrelic"] = { + payload['newrelic'] = { newrelic_key(:version) => newrelic_payload.version, newrelic_key(:data) => {} } - data_payload = payload["newrelic"][newrelic_key(:data)] + data_payload = payload['newrelic'][newrelic_key(:data)] assign_not_nil_value(data_payload, :parent_type, newrelic_payload.parent_type) assign_not_nil_value(data_payload, :parent_account_id, newrelic_payload.parent_account_id) assign_not_nil_value(data_payload, :parent_app, newrelic_payload.parent_app_id) @@ -223,10 +223,10 @@ def intrinsics_for_event(test_case, event_type) def verify_attributes(test_case_attributes, actual_attributes, event_type) if verbose_attributes? - puts "", "*" * 80 + puts '', '*' * 80 puts event_type pp(actual_attributes) - puts "*" * 80 + puts '*' * 80 end (test_case_attributes['exact'] || []).each do |k, v| @@ -291,7 +291,7 @@ def verify_span_intrinsics(test_case) harvested_events = NewRelic::Agent.agent.span_event_aggregator.harvest! last_span_events = harvested_events[1] - refute_empty last_span_events, "no span events harvested!" + refute_empty last_span_events, 'no span events harvested!' actual_intrinsics = last_span_events[0][0] @@ -305,7 +305,7 @@ def verify_outbound_payloads(test_case, actual_payloads) test_case_payloads.zip(actual_payloads).each do |test_case_data, actual| context_hash = trace_context_headers_to_hash(actual) - add_newrelic_entries(context_hash, actual["newrelic"]) + add_newrelic_entries(context_hash, actual['newrelic']) dotted_context_hash = NewRelic::Agent::Configuration::DottedHash.new(context_hash) stringified_hash = stringify_keys_in_object(dotted_context_hash) @@ -352,7 +352,7 @@ def trace_context_headers_to_hash(carrier) tracestate['span_id'] = tracestate_values[4] unless tracestate_values[4].empty? tracestate['transaction_id'] = tracestate_values[5] unless tracestate_values[5].empty? tracestate['sampled'] = tracestate_values[6] - tracestate['priority'] = tracestate_values[7].chomp("0") + tracestate['priority'] = tracestate_values[7].chomp('0') tracestate['timestamp'] = tracestate_values[8] tracestate['tracingVendors'] = header_data.trace_state_vendors else @@ -367,9 +367,9 @@ def trace_context_headers_to_hash(carrier) def rack_format(test_case, carrier) carrier ||= {} rack_headers = {} - rack_headers["HTTP_TRACEPARENT"] = carrier['traceparent'] if carrier['traceparent'] - rack_headers["HTTP_TRACESTATE"] = carrier['tracestate'] if carrier['tracestate'] - rack_headers["HTTP_NEWRELIC"] = carrier["newrelic"] if carrier["newrelic"] + rack_headers['HTTP_TRACEPARENT'] = carrier['traceparent'] if carrier['traceparent'] + rack_headers['HTTP_TRACESTATE'] = carrier['tracestate'] if carrier['tracestate'] + rack_headers['HTTP_NEWRELIC'] = carrier['newrelic'] if carrier['newrelic'] rack_headers end end diff --git a/test/new_relic/agent/distributed_tracing/trace_context_payload_test.rb b/test/new_relic/agent/distributed_tracing/trace_context_payload_test.rb index 8e764fdb58..043b1bcfc3 100644 --- a/test/new_relic/agent/distributed_tracing/trace_context_payload_test.rb +++ b/test/new_relic/agent/distributed_tracing/trace_context_payload_test.rb @@ -9,10 +9,10 @@ module Agent class TraceContextPayloadTest < Minitest::Test def test_to_s payload = TraceContextPayload.create( \ - parent_account_id: "12345", - parent_app_id: "6789", - id: "f85f42fd82a4cf1d", - transaction_id: "164d3b4b0d09cb05", + parent_account_id: '12345', + parent_app_id: '6789', + id: 'f85f42fd82a4cf1d', + transaction_id: '164d3b4b0d09cb05', sampled: true, priority: 0.123 ) @@ -25,9 +25,9 @@ def test_to_s_with_nil_id # and to_s should be able to deal with that. payload = TraceContextPayload.create( \ - parent_account_id: "12345", - parent_app_id: "6789", - transaction_id: "164d3b4b0d09cb05", + parent_account_id: '12345', + parent_app_id: '6789', + transaction_id: '164d3b4b0d09cb05', sampled: true, priority: 0.123 ) @@ -37,10 +37,10 @@ def test_to_s_with_nil_id def test_to_s_does_not_convert_to_scientific_notation payload = TraceContextPayload.create( \ - parent_account_id: "12345", - parent_app_id: "6789", - id: "f85f42fd82a4cf1d", - transaction_id: "164d3b4b0d09cb05", + parent_account_id: '12345', + parent_app_id: '6789', + id: 'f85f42fd82a4cf1d', + transaction_id: '164d3b4b0d09cb05', sampled: true, priority: 0.000012 ) @@ -56,11 +56,11 @@ def test_from_s assert_equal 0, payload.version assert_equal 0, payload.parent_type_id - assert_equal "App", payload.parent_type - assert_equal "12345", payload.parent_account_id - assert_equal "6789", payload.parent_app_id - assert_equal "f85f42fd82a4cf1d", payload.id - assert_equal "164d3b4b0d09cb05", payload.transaction_id + assert_equal 'App', payload.parent_type + assert_equal '12345', payload.parent_account_id + assert_equal '6789', payload.parent_app_id + assert_equal 'f85f42fd82a4cf1d', payload.id + assert_equal '164d3b4b0d09cb05', payload.transaction_id assert payload.sampled assert_in_delta(0.123, payload.priority) end @@ -71,7 +71,7 @@ def test_from_s_browser_payload_no_sampled_priority_or_transaction_id assert_equal 0, payload.version assert_equal 1, payload.parent_type_id - assert_equal "Browser", payload.parent_type + assert_equal 'Browser', payload.parent_type assert_equal '212311', payload.parent_account_id assert_equal '51424', payload.parent_app_id assert_equal '0996096a36a1cd29', payload.id @@ -89,22 +89,22 @@ def test_additional_attributes assert_equal 1, payload.version assert_equal 0, payload.parent_type_id - assert_equal "App", payload.parent_type - assert_equal "12345", payload.parent_account_id - assert_equal "6789", payload.parent_app_id - assert_equal "f85f42fd82a4cf1d", payload.id - assert_equal "164d3b4b0d09cb05", payload.transaction_id + assert_equal 'App', payload.parent_type + assert_equal '12345', payload.parent_account_id + assert_equal '6789', payload.parent_app_id + assert_equal 'f85f42fd82a4cf1d', payload.id + assert_equal '164d3b4b0d09cb05', payload.transaction_id assert payload.sampled assert_in_delta(0.123, payload.priority) end def test_valid valid_payloads = [ - "1-0-12345-6789-f85f42fd82a4cf1d-164d3b4b0d09cb05-1-0.123-1482959525577", - "1-0-12345-6789--164d3b4b0d09cb05-1-0.123-1482959525577", - "1-0-12345-6789-f85f42fd82a4cf1d--1-0.123-1482959525577", - "1-0-12345-6789-f85f42fd82a4cf1d-164d3b4b0d09cb05--0.123-1482959525577", - "1-0-12345-6789-f85f42fd82a4cf1d-164d3b4b0d09cb05---1482959525577" + '1-0-12345-6789-f85f42fd82a4cf1d-164d3b4b0d09cb05-1-0.123-1482959525577', + '1-0-12345-6789--164d3b4b0d09cb05-1-0.123-1482959525577', + '1-0-12345-6789-f85f42fd82a4cf1d--1-0.123-1482959525577', + '1-0-12345-6789-f85f42fd82a4cf1d-164d3b4b0d09cb05--0.123-1482959525577', + '1-0-12345-6789-f85f42fd82a4cf1d-164d3b4b0d09cb05---1482959525577' ] valid_payloads.each do |payload_str| @@ -114,11 +114,11 @@ def test_valid end invalid_payloads = [ - "-0-12345-6789-f85f42fd82a4cf1d-164d3b4b0d09cb05-1-0.123-1482959525577", - "1--12345-6789-f85f42fd82a4cf1d-164d3b4b0d09cb05-1-0.123-1482959525577", - "1-0--6789-f85f42fd82a4cf1d-164d3b4b0d09cb05-1-0.123-1482959525577", - "1-0-12345--f85f42fd82a4cf1d-164d3b4b0d09cb05-1-0.123-1482959525577", - "1-0-12345-6789-f85f42fd82a4cf1d-164d3b4b0d09cb05-1-0.123-" + '-0-12345-6789-f85f42fd82a4cf1d-164d3b4b0d09cb05-1-0.123-1482959525577', + '1--12345-6789-f85f42fd82a4cf1d-164d3b4b0d09cb05-1-0.123-1482959525577', + '1-0--6789-f85f42fd82a4cf1d-164d3b4b0d09cb05-1-0.123-1482959525577', + '1-0-12345--f85f42fd82a4cf1d-164d3b4b0d09cb05-1-0.123-1482959525577', + '1-0-12345-6789-f85f42fd82a4cf1d-164d3b4b0d09cb05-1-0.123-' ] invalid_payloads.each do |payload_str| diff --git a/test/new_relic/agent/distributed_tracing/trace_context_test.rb b/test/new_relic/agent/distributed_tracing/trace_context_test.rb index 7567715e31..8fb56abd51 100644 --- a/test/new_relic/agent/distributed_tracing/trace_context_test.rb +++ b/test/new_relic/agent/distributed_tracing/trace_context_test.rb @@ -8,8 +8,8 @@ module NewRelic::Agent::DistributedTracing class TraceContextTest < Minitest::Test def setup @config = { - :account_id => "190", - :primary_application_id => "46954", + :account_id => '190', + :primary_application_id => '46954', :disable_harvest_thread => true, :'distributed_tracing.enabled' => true } @@ -49,7 +49,7 @@ def test_parse_format_non_rack trace_context_header_data = TraceContext.parse(format: NewRelic::FORMAT_NON_RACK, carrier: carrier, - trace_state_entry_key: "190@nr") + trace_state_entry_key: '190@nr') trace_parent = trace_context_header_data.trace_parent @@ -72,7 +72,7 @@ def test_parse_format_rack trace_context_header_data = TraceContext.parse(format: NewRelic::FORMAT_RACK, carrier: carrier, - trace_state_entry_key: "190@nr") + trace_state_entry_key: '190@nr') trace_parent = trace_context_header_data.trace_parent @@ -95,7 +95,7 @@ def test_parse_with_nr_at_end trace_context_header_data = TraceContext.parse(format: NewRelic::FORMAT_NON_RACK, carrier: carrier, - trace_state_entry_key: "190@nr") + trace_state_entry_key: '190@nr') trace_parent = trace_context_header_data.trace_parent @@ -118,7 +118,7 @@ def test_parse_with_nr_middle trace_context_header_data = TraceContext.parse(format: NewRelic::FORMAT_NON_RACK, carrier: carrier, - trace_state_entry_key: "190@nr") + trace_state_entry_key: '190@nr') trace_parent = trace_context_header_data.trace_parent @@ -141,7 +141,7 @@ def test_parse_with_nr_middle_and_spaces trace_context_header_data = TraceContext.parse(format: NewRelic::FORMAT_NON_RACK, carrier: carrier, - trace_state_entry_key: "190@nr") + trace_state_entry_key: '190@nr') trace_parent = trace_context_header_data.trace_parent @@ -159,7 +159,7 @@ def test_parse_tracestate_no_other_entries carrier = make_inbound_carrier({'tracestate' => "190@nr=#{payload.to_s}"}) trace_context_header_data = TraceContext.parse(format: NewRelic::FORMAT_NON_RACK, carrier: carrier, - trace_state_entry_key: "190@nr") + trace_state_entry_key: '190@nr') assert_equal payload.to_s, trace_context_header_data.trace_state_payload.to_s assert_equal 'new=entry', trace_context_header_data.trace_state('new=entry') @@ -169,22 +169,22 @@ def test_parse_tracestate_no_nr_entry carrier = make_inbound_carrier trace_context_header_data = TraceContext.parse(format: NewRelic::FORMAT_NON_RACK, carrier: carrier, - trace_state_entry_key: "190@nr") + trace_state_entry_key: '190@nr') assert_nil trace_context_header_data.trace_state_payload assert_equal 'new=entry,other=asdf', trace_context_header_data.trace_state('new=entry') end def test_parse_tracestate_nr_entry_malformed - carrier = make_inbound_carrier({'tracestate' => "190@nr=somethingincorrect"}) + carrier = make_inbound_carrier({'tracestate' => '190@nr=somethingincorrect'}) trace_context_header_data = TraceContext.parse(format: NewRelic::FORMAT_NON_RACK, carrier: carrier, - trace_state_entry_key: "190@nr") + trace_state_entry_key: '190@nr') - refute trace_context_header_data.trace_state_payload, "no payload expected" + refute trace_context_header_data.trace_state_payload, 'no payload expected' assert_equal 'new=entry', trace_context_header_data.trace_state('new=entry') - assert_metrics_recorded "Supportability/TraceContext/Parse/Exception" - assert_metrics_recorded "Supportability/TraceContext/Parse/Exception" + assert_metrics_recorded 'Supportability/TraceContext/Parse/Exception' + assert_metrics_recorded 'Supportability/TraceContext/Parse/Exception' end def test_extract_trace_parent_nonzero_version @@ -289,12 +289,12 @@ def test_trace_parent_valid_future_version_with_extra_fields def make_inbound_carrier(options = {}) { NewRelic::TRACEPARENT_KEY => '00-a8e67265afe2773a3c611b94306ee5c2-fb1010463ea28a38-01', - NewRelic::TRACESTATE_KEY => "other=asdf" + NewRelic::TRACESTATE_KEY => 'other=asdf' }.update(options) end def make_payload - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| return txn.distributed_tracer.create_trace_state_payload end end diff --git a/test/new_relic/agent/distributed_tracing_test.rb b/test/new_relic/agent/distributed_tracing_test.rb index 4d95fbb176..6f4eb429f5 100644 --- a/test/new_relic/agent/distributed_tracing_test.rb +++ b/test/new_relic/agent/distributed_tracing_test.rb @@ -15,9 +15,9 @@ class DistributedTracingTest < Minitest::Test def setup @config = { :'distributed_tracing.enabled' => true, - :account_id => "190", - :primary_application_id => "46954", - :trusted_account_key => "190", + :account_id => '190', + :primary_application_id => '46954', + :trusted_account_key => '190', :disable_harvest_thread => true } NewRelic::Agent::DistributedTracePayload.stubs(:connected?).returns(true) @@ -33,23 +33,23 @@ def teardown def test_accept_distributed_trace_headers_api carrier = {'HTTP_TRACEPARENT' => 'pretend_this_is_valid'} - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| txn.distributed_tracer.expects(:accept_incoming_request) - DistributedTracing.accept_distributed_trace_headers(carrier, "HTTP") + DistributedTracing.accept_distributed_trace_headers(carrier, 'HTTP') end end def test_accept_distributed_trace_headers_api_with_non_rack carrier = {'tRaCePaReNt' => 'pretend_this_is_valid'} - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| txn.distributed_tracer.expects(:accept_trace_context_incoming_request) - DistributedTracing.accept_distributed_trace_headers(carrier, "Kafka") + DistributedTracing.accept_distributed_trace_headers(carrier, 'Kafka') end end def test_insert_distributed_trace_headers_api carrier = {} - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| txn.distributed_tracer.expects(:insert_headers) DistributedTracing.insert_distributed_trace_headers(carrier) end @@ -58,11 +58,11 @@ def test_insert_distributed_trace_headers_api def test_accept_distributed_trace_headers_api_case_insensitive carrier = { 'tRacEpArEnT' => '00-a8e67265afe2773a3c611b94306ee5c2-fb1010463ea28a38-01', - 'trAceSTatE' => "190@nr=0-0-190-2827902-7d3efb1b173fecfa-e8b91a159289ff74-1-1.23456-1518469636035" + 'trAceSTatE' => '190@nr=0-0-190-2827902-7d3efb1b173fecfa-e8b91a159289ff74-1-1.23456-1518469636035' } trace_context_header_data = nil - in_transaction("test_txn") do |txn| - DistributedTracing.accept_distributed_trace_headers(carrier, "Kafka") + in_transaction('test_txn') do |txn| + DistributedTracing.accept_distributed_trace_headers(carrier, 'Kafka') trace_context_header_data = txn.distributed_tracer.trace_context_header_data end diff --git a/test/new_relic/agent/encoding_normalizer_test.rb b/test/new_relic/agent/encoding_normalizer_test.rb index cd6eb4cba7..955c7de91f 100644 --- a/test/new_relic/agent/encoding_normalizer_test.rb +++ b/test/new_relic/agent/encoding_normalizer_test.rb @@ -27,7 +27,7 @@ def test_normalize_object_converts_rationals_to_floats end def test_normalize_string_returns_input_if_correctly_encoded_utf8 - string = "i want a pony" + string = 'i want a pony' result = EncodingNormalizer.normalize_string(string) assert_same(string, result) @@ -35,7 +35,7 @@ def test_normalize_string_returns_input_if_correctly_encoded_utf8 end def test_normalize_string_returns_munged_copy_if_ascii_8bit - string = (0..255).to_a.pack("C*") + string = (0..255).to_a.pack('C*') result = EncodingNormalizer.normalize_string(string) refute_same(string, result) @@ -44,7 +44,7 @@ def test_normalize_string_returns_munged_copy_if_ascii_8bit end def test_normalize_string_returns_munged_copy_if_invalid_utf8 - string = (0..255).to_a.pack("C*").force_encoding('UTF-8') + string = (0..255).to_a.pack('C*').force_encoding('UTF-8') result = EncodingNormalizer.normalize_string(string) refute_same(result, string) @@ -53,7 +53,7 @@ def test_normalize_string_returns_munged_copy_if_invalid_utf8 end def test_normalize_string_returns_munged_copy_if_other_convertible_encoding - string = "i want a pony".encode('UTF-16LE') + string = 'i want a pony'.encode('UTF-16LE') result = EncodingNormalizer.normalize_string(string) refute_same(result, string) @@ -66,7 +66,7 @@ def test_normalize_string_returns_munged_copy_if_other_non_convertible_encoding # Encoding::ConverterNotFoundError, which is what we're trying to # replicate for this test case. # The following UTF-7 string decodes to 'Jyväskylä', a city in Finland - string = String.new('Jyv+AOQ-skyl+AOQ-') + string = +'Jyv+AOQ-skyl+AOQ-' input = string.dup.force_encoding('UTF-7') assert_predicate input, :valid_encoding? diff --git a/test/new_relic/agent/error_collector_test.rb b/test/new_relic/agent/error_collector_test.rb index b6bbadba02..c499f464ff 100644 --- a/test/new_relic/agent/error_collector_test.rb +++ b/test/new_relic/agent/error_collector_test.rb @@ -54,9 +54,9 @@ def test_records_error_outside_of_transaction end def test_exclude - @error_collector.ignore(["IOError"]) + @error_collector.ignore(['IOError']) - @error_collector.notice_error(IOError.new("message"), :metric => 'path') + @error_collector.notice_error(IOError.new('message'), :metric => 'path') traces = harvest_error_traces events = harvest_error_events @@ -67,13 +67,13 @@ def test_exclude def test_exclude_later_config_changes in_transaction do - @error_collector.notice_error(IOError.new("message")) + @error_collector.notice_error(IOError.new('message')) end - NewRelic::Agent.config.add_config_for_testing(:'error_collector.ignore_classes' => ["IOError"]) + NewRelic::Agent.config.add_config_for_testing(:'error_collector.ignore_classes' => ['IOError']) in_transaction do - @error_collector.notice_error(IOError.new("message")) + @error_collector.notice_error(IOError.new('message')) end traces = harvest_error_traces @@ -87,8 +87,8 @@ def test_exclude_block @error_collector.class.ignore_error_filter = wrapped_filter_proc in_transaction do - @error_collector.notice_error(IOError.new("message"), :metric => 'path') - @error_collector.notice_error(StandardError.new("message"), :metric => 'path') + @error_collector.notice_error(IOError.new('message'), :metric => 'path') + @error_collector.notice_error(StandardError.new('message'), :metric => 'path') end traces = harvest_error_traces @@ -100,11 +100,11 @@ def test_exclude_block def test_failure_in_exclude_block @error_collector.class.ignore_error_filter = proc do - raise "HAHAHAHAH, error in the filter for ignoring errors!" + raise 'HAHAHAHAH, error in the filter for ignoring errors!' end in_transaction do - @error_collector.notice_error(StandardError.new("message")) + @error_collector.notice_error(StandardError.new('message')) end traces = harvest_error_traces @@ -121,19 +121,19 @@ def test_failure_block_assigned_with_different_instance end new_error_collector = NewRelic::Agent::ErrorCollector.new(NewRelic::Agent.instance.events) - new_error_collector.notice_error(StandardError.new("message")) + new_error_collector.notice_error(StandardError.new('message')) assert_empty new_error_collector.error_trace_aggregator.harvest! end def test_increments_count_on_errors - @error_collector.notice_error(StandardError.new("Boo")) + @error_collector.notice_error(StandardError.new('Boo')) assert_metrics_recorded( 'Errors/all' => {:call_count => 1} ) - @error_collector.notice_error(StandardError.new("Boo")) + @error_collector.notice_error(StandardError.new('Boo')) assert_metrics_recorded( 'Errors/all' => {:call_count => 2} @@ -311,7 +311,7 @@ def test_keeps_correct_frames_if_keep_frames_is_odd if defined?(Rails::VERSION::MAJOR) && Rails::VERSION::MAJOR < 5 def test_extract_stack_trace_from_original_exception - orig = mock('original', :backtrace => "STACK STACK STACK") + orig = mock('original', :backtrace => 'STACK STACK STACK') exception = mock('exception', :original_exception => orig) assert_equal('STACK STACK STACK', @error_collector.extract_stack_trace(exception)) @@ -492,18 +492,18 @@ def test_expected_error_not_recorded_as_custom_attribute event_attrs = events[0][1] - refute event_attrs.key?("expected"), "Unexpected attribute expected found in custom attributes" + refute event_attrs.key?('expected'), 'Unexpected attribute expected found in custom attributes' trace_attrs = traces[0].attributes_from_notice_error - refute trace_attrs.key?(:expected), "Unexpected attribute expected found in custom attributes" + refute trace_attrs.key?(:expected), 'Unexpected attribute expected found in custom attributes' end def test_segment_error_attributes with_segment do |segment| - @error_collector.notice_segment_error(segment, StandardError.new("Oops!")) + @error_collector.notice_segment_error(segment, StandardError.new('Oops!')) - assert segment.noticed_error, "expected segment.noticed_error to not be nil" + assert segment.noticed_error, 'expected segment.noticed_error to not be nil' # we defer building the error attributes until segments are turned into spans! assert_equal NewRelic::EMPTY_HASH, segment.noticed_error.attributes_from_notice_error @@ -513,8 +513,8 @@ def test_segment_error_attributes recorded_error_attributes = SpanEventPrimitive.error_attributes(segment) expected_error_attributes = { - "error.message" => "Oops!", - "error.class" => "StandardError" + 'error.message' => 'Oops!', + 'error.class' => 'StandardError' } assert_equal expected_error_attributes, segment.noticed_error.attributes_from_notice_error @@ -526,9 +526,9 @@ def test_segment_error_attributes def test_segment_error_attributes_for_expected_error with_segment do |segment| - @error_collector.notice_segment_error(segment, StandardError.new("Oops!"), {expected: true}) + @error_collector.notice_segment_error(segment, StandardError.new('Oops!'), {expected: true}) - assert segment.noticed_error, "expected segment.noticed_error to not be nil" + assert segment.noticed_error, 'expected segment.noticed_error to not be nil' # we defer building the error attributes until segments are turned into spans! assert_equal NewRelic::EMPTY_HASH, segment.noticed_error.attributes_from_notice_error @@ -538,9 +538,9 @@ def test_segment_error_attributes_for_expected_error recorded_error_attributes = SpanEventPrimitive.error_attributes(segment) expected_error_attributes = { - "error.message" => "Oops!", - "error.class" => "StandardError", - "error.expected" => true + 'error.message' => 'Oops!', + 'error.class' => 'StandardError', + 'error.expected' => true } assert_equal expected_error_attributes, segment.noticed_error.attributes_from_notice_error @@ -552,9 +552,9 @@ def test_segment_error_attributes_for_expected_error def test_segment_error_attributes_for_tx_notice_error_api_call with_segment do |segment| - NewRelic::Agent::Transaction.notice_error(StandardError.new("Oops!"), {expected: true}) + NewRelic::Agent::Transaction.notice_error(StandardError.new('Oops!'), {expected: true}) - assert segment.noticed_error, "expected segment.noticed_error to not be nil" + assert segment.noticed_error, 'expected segment.noticed_error to not be nil' # we defer building the error attributes until segments are turned into spans! assert_equal NewRelic::EMPTY_HASH, segment.noticed_error.attributes_from_notice_error @@ -564,9 +564,9 @@ def test_segment_error_attributes_for_tx_notice_error_api_call recorded_error_attributes = SpanEventPrimitive.error_attributes(segment) expected_error_attributes = { - "error.message" => "Oops!", - "error.class" => "StandardError", - "error.expected" => true + 'error.message' => 'Oops!', + 'error.class' => 'StandardError', + 'error.expected' => true } assert_equal expected_error_attributes, segment.noticed_error.attributes_from_notice_error @@ -579,9 +579,9 @@ def test_segment_error_attributes_for_tx_notice_error_api_call def test_segment_error_filtered with_config(:'error_collector.ignore_classes' => ['StandardError']) do with_segment do |segment| - @error_collector.notice_segment_error(segment, StandardError.new("Oops!")) + @error_collector.notice_segment_error(segment, StandardError.new('Oops!')) - refute segment.noticed_error, "expected segment.noticed_error to be nil" + refute segment.noticed_error, 'expected segment.noticed_error to be nil' end end @@ -592,14 +592,91 @@ def test_segment_error_exclude_block @error_collector.class.ignore_error_filter = wrapped_filter_proc with_segment do |segment| - @error_collector.notice_segment_error(segment, IOError.new("message")) + @error_collector.notice_segment_error(segment, IOError.new('message')) - refute segment.noticed_error, "expected segment.noticed_error to be nil" + refute segment.noticed_error, 'expected segment.noticed_error to be nil' end assert_nothing_harvested_for_segment_errors end + def test_build_customer_callback_hash + custom_attributes = {billie_eilish: :bored} + agent_attributes = {'http.statusCode': :bleachers__dont_take_the_money} + intrinsic_attributes = {'http.method': :walk_the_moon__anna_sun} + request_uri = :alternative_music + options = {taylor_swift: :maroon} + expected = true + error = StandardError.new + + noticed_error = NewRelic::NoticedError.new(:watermelon, error) + noticed_error.instance_variable_set(:@processed_attributes, + {NewRelic::NoticedError::USER_ATTRIBUTES => custom_attributes, + NewRelic::NoticedError::AGENT_ATTRIBUTES => agent_attributes, + NewRelic::NoticedError::INTRINSIC_ATTRIBUTES => intrinsic_attributes}) + noticed_error.request_uri = request_uri + noticed_error.expected = expected + hash = @error_collector.send(:build_customer_callback_hash, noticed_error, error, options) + + assert_equal hash[:error], error + assert_equal hash[:customAttributes], custom_attributes + assert_equal hash[:'request.uri'], request_uri + assert_equal hash[:'http.statusCode'], agent_attributes[:'http.statusCode'] + assert_equal hash[:'http.method'], intrinsic_attributes[:'http.method'] + assert_equal hash[:'error.expected'], expected + assert_equal hash[:options], options + end + + def test_update_error_group_name_returns_nil_unless_a_callback_has_been_registered + # because the build_customer_callback_hash method will call + # #custom_attributes on the noticed error object, and we're passing in + # nil for it, it would error out if the early return we're testing for + # did not return + @error_collector.stub(:error_group_callback, nil) do + assert_nil @error_collector.send(:update_error_group_name, nil, nil, nil) + end + end + + def test_update_error_group_name_updates_the_error_group_name + error = ArgumentError.new + error_group = 'lucky tiger' + noticed_error = NewRelic::NoticedError.new(:watermelon, error) + NewRelic::Agent.set_error_group_callback(proc { |hash| error_group if hash[:error].is_a?(ArgumentError) }) + @error_collector.send(:update_error_group_name, noticed_error, error, {}) + + assert_equal error_group, noticed_error.error_group + ensure + NewRelic::Agent.remove_instance_variable(:@error_group_callback) + end + + def test_update_error_group_logs_if_an_error_is_rescued + skip_unless_minitest5_or_above + + logger = MiniTest::Mock.new + # have #error return a phony value just for the purpose of being able + # to supply this test with at least 1 assertion. really, the #verify + # call to the mock should suffice, but it's nice to have assertions + phony_return = :yep_i_was_indeed_called + logger.expect :error, phony_return, [/Failed to obtain/] + @error_collector.stub(:error_group_callback, -> { raise 'kaboom' }) do + NewRelic::Agent.stub :logger, logger do + assert_equal phony_return, @error_collector.send(:update_error_group_name, nil, nil, nil) + end + end + logger.verify + end + + def test_noticed_errors_have_the_error_group_present_in_their_agent_attributes + error_group = 'blackcurrant tea' + exception = RuntimeError.new + NewRelic::Agent.set_error_group_callback(proc { |hash| error_group if hash[:error].is_a?(RuntimeError) }) + noticed_error = @error_collector.create_noticed_error(exception, {}) + + assert_equal error_group, noticed_error.agent_attributes[::NewRelic::NoticedError::AGENT_ATTRIBUTE_ERROR_GROUP] + ensure + NewRelic::Agent.remove_instance_variable(:@error_group_callback) + end + private # Segment errors utilize the error_collector's filtering for LASP diff --git a/test/new_relic/agent/error_event_aggregator_test.rb b/test/new_relic/agent/error_event_aggregator_test.rb index d0b76a77e1..02b1d791cd 100644 --- a/test/new_relic/agent/error_event_aggregator_test.rb +++ b/test/new_relic/agent/error_event_aggregator_test.rb @@ -33,7 +33,7 @@ def create_container def populate_container(sampler, n) n.times do - error = NewRelic::NoticedError.new("Controller/blogs/index", RuntimeError.new("Big Controller")) + error = NewRelic::NoticedError.new('Controller/blogs/index', RuntimeError.new('Big Controller')) payload = in_transaction {}.payload @error_event_aggregator.record(error, payload, @span_id) @@ -57,7 +57,7 @@ def aggregator end def name_for(event) - event[0]["transactionName"] + event[0]['transactionName'] end include NewRelic::CommonAggregatorTests @@ -71,8 +71,8 @@ def test_generates_event_without_payload assert_equal 'TransactionError', intrinsics['type'] assert_in_delta Process.clock_gettime(Process::CLOCK_REALTIME), intrinsics['timestamp'], 0.001 - assert_equal "RuntimeError", intrinsics['error.class'] - assert_equal "Big Controller!", intrinsics['error.message'] + assert_equal 'RuntimeError', intrinsics['error.class'] + assert_equal 'Big Controller!', intrinsics['error.message'] end def test_generates_event_from_error @@ -82,9 +82,9 @@ def test_generates_event_from_error assert_equal 'TransactionError', intrinsics['type'] assert_in_delta Process.clock_gettime(Process::CLOCK_REALTIME), intrinsics['timestamp'], 0.001 - assert_equal "RuntimeError", intrinsics['error.class'] - assert_equal "Big Controller!", intrinsics['error.message'] - assert_equal "Controller/blogs/index", intrinsics['transactionName'] + assert_equal 'RuntimeError', intrinsics['error.class'] + assert_equal 'Big Controller!', intrinsics['error.message'] + assert_equal 'Controller/blogs/index', intrinsics['transactionName'] assert_in_delta(0.1, intrinsics['duration']) assert_equal 80, intrinsics['port'] end @@ -146,9 +146,9 @@ def reset_error_event_buffer_state end def create_noticed_error(txn_name, options = {}) - exception = options.delete(:exception) || RuntimeError.new("Big Controller!") + exception = options.delete(:exception) || RuntimeError.new('Big Controller!') noticed_error = NewRelic::NoticedError.new(txn_name, exception) - noticed_error.request_uri = "http://site.com/blogs" + noticed_error.request_uri = 'http://site.com/blogs' noticed_error.request_port = 80 noticed_error.attributes = options.delete(:attributes) noticed_error.attributes_from_notice_error = options.delete(:custom_params) || {} diff --git a/test/new_relic/agent/error_trace_aggregator_test.rb b/test/new_relic/agent/error_trace_aggregator_test.rb index 03b9842b4f..942d03454f 100644 --- a/test/new_relic/agent/error_trace_aggregator_test.rb +++ b/test/new_relic/agent/error_trace_aggregator_test.rb @@ -25,7 +25,7 @@ def create_container def populate_container(aggregator, n) n.times do |i| - error = NewRelic::NoticedError.new(String.new('path'), String.new('yay errors')) + error = NewRelic::NoticedError.new((+'path'), (+'yay errors')) aggregator.add_to_error_queue(error) end end @@ -33,7 +33,7 @@ def populate_container(aggregator, n) include NewRelic::DataContainerTests def test_simple - notice_error(StandardError.new("message"), + notice_error(StandardError.new('message'), :uri => '/myurl/', :metric => 'path') @@ -56,13 +56,13 @@ def test_simple end def test_collect_failover - notice_error(StandardError.new("message"), :metric => 'first') + notice_error(StandardError.new('message'), :metric => 'first') errors = error_trace_aggregator.harvest! - notice_error(StandardError.new("message"), :metric => 'second') - notice_error(StandardError.new("message"), :metric => 'path') - notice_error(StandardError.new("message"), :metric => 'last') + notice_error(StandardError.new('message'), :metric => 'second') + notice_error(StandardError.new('message'), :metric => 'path') + notice_error(StandardError.new('message'), :metric => 'last') error_trace_aggregator.merge!(errors) errors = error_trace_aggregator.harvest! @@ -70,8 +70,8 @@ def test_collect_failover assert_equal 4, errors.length assert_equal_unordered(%w[first second path last], errors.map { |e| e.path }) - notice_error(StandardError.new("message"), :metric => 'first') - notice_error(StandardError.new("message"), :metric => 'last') + notice_error(StandardError.new('message'), :metric => 'first') + notice_error(StandardError.new('message'), :metric => 'last') errors = error_trace_aggregator.harvest! @@ -91,15 +91,15 @@ def test_supported_param_types [1.1, '1.1'], %w[hi hi], [:hi, 'hi'], - [StandardError.new("test"), "#"], - [TestClass.new, "#"]] + [StandardError.new('test'), '#'], + [TestClass.new, '#']] types.each do |test| - notice_error(StandardError.new("message"), + notice_error(StandardError.new('message'), :metric => 'path', :custom_params => {:x => test[0]}) error = error_trace_aggregator.harvest![0].to_collector_array - actual = error.last["userAttributes"]["x"] + actual = error.last['userAttributes']['x'] assert_equal test[1], actual end @@ -108,7 +108,7 @@ def test_supported_param_types def test_obfuscates_error_messages_when_high_security_is_set with_config(:high_security => true) do notice_error(StandardError.new("BAAAAD SQL: choose * out_of test where foo = 'bar'")) - notice_error(StandardError.new("BAAAAD SQL: choose * out_of test where foo in (1,2,3,4,5)")) + notice_error(StandardError.new('BAAAAD SQL: choose * out_of test where foo in (1,2,3,4,5)')) errors = error_trace_aggregator.harvest! @@ -124,7 +124,7 @@ def test_over_queue_limit_negative def test_over_queue_limit_positive expects_logging(:warn, includes('The error reporting queue has reached 20')) 21.times do - error = stub(:message => "", :is_internal => false) + error = stub(:message => '', :is_internal => false) error_trace_aggregator.add_to_error_queue(error) end @@ -137,7 +137,7 @@ def test_queue_overflow silence_stream(::STDOUT) do (max_q_length + 5).times do |n| notice_error(StandardError.new("exception #{n}"), - :metric => "path", + :metric => 'path', :custom_params => {:x => n}) end end @@ -147,7 +147,7 @@ def test_queue_overflow assert_equal(max_q_length, errors.length) errors.each_index do |i| error = errors.shift - actual = error.to_collector_array.last["userAttributes"]["x"] + actual = error.to_collector_array.last['userAttributes']['x'] assert_equal i.to_s, actual end @@ -199,7 +199,7 @@ def test_notice_agent_error_set_noticed_error_attributes errors = error_trace_aggregator.harvest! err = errors.first - assert_equal "NewRelic/AgentError", err.path + assert_equal 'NewRelic/AgentError', err.path refute_nil err.stack_trace end @@ -225,7 +225,7 @@ def test_notice_agent_error_uses_caller_if_no_exception_backtrace end def test_notice_agent_error_allows_an_error_past_queue_limit - 100.times { notice_error(StandardError.new("Ouch")) } + 100.times { notice_error(StandardError.new('Ouch')) } exception = DifficultToDebugAgentError.new error_trace_aggregator.notice_agent_error(exception) @@ -239,26 +239,26 @@ def test_notice_agent_error_doesnt_clog_up_the_queue_limit exception = DifficultToDebugAgentError.new error_trace_aggregator.notice_agent_error(exception) - 100.times { notice_error(StandardError.new("Ouch")) } + 100.times { notice_error(StandardError.new('Ouch')) } errors = error_trace_aggregator.harvest! assert_equal 21, errors.size end def test_notice_agent_error_adds_support_message - exception = DifficultToDebugAgentError.new("BOO") + exception = DifficultToDebugAgentError.new('BOO') error_trace_aggregator.notice_agent_error(exception) errors = error_trace_aggregator.harvest! err = errors.first assert_includes(err.message, exception.message) - assert_includes(err.message, "Ruby agent internal error") + assert_includes(err.message, 'Ruby agent internal error') end def test_errors_not_noticed_when_disabled with_config(:'error_collector.enabled' => false) do - notice_error(StandardError.new("Red hands")) + notice_error(StandardError.new('Red hands')) errors = error_trace_aggregator.harvest! assert_empty errors @@ -271,7 +271,7 @@ def test_errors_noticed_when_error_events_disabled :'error_collector.capture_events' => false } with_config(config) do - notice_error(StandardError.new("Red hands")) + notice_error(StandardError.new('Red hands')) errors = error_trace_aggregator.harvest! assert_equal 1, errors.size @@ -280,7 +280,7 @@ def test_errors_noticed_when_error_events_disabled def test_errors_not_harvested_when_changing_from_enabled_to_disabled with_config(:'error_collector.enabled' => true) do - notice_error(StandardError.new("Red hands")) + notice_error(StandardError.new('Red hands')) with_config(:'error_collector.enabled' => false) do errors = error_trace_aggregator.harvest! @@ -290,6 +290,24 @@ def test_errors_not_harvested_when_changing_from_enabled_to_disabled end end + def test_noticed_internal_errors_invoke_the_error_group_callback + message = 'ton up' + group = 'cafe racer' + proc = proc { |hash| group if hash[:error].message.match?(message) } + NewRelic::Agent.set_error_group_callback(proc) + + error = DifficultToDebugAgentError.new(message) + aggregator = NewRelic::Agent::ErrorTraceAggregator.new(1148) + aggregator.notice_agent_error(error) + noticed_error = aggregator.harvest!.first + + assert_equal group, noticed_error.error_group + ensure + NewRelic::Agent.remove_instance_variable(:@error_group_callback) + end + + private + def create_noticed_error(exception, options = {}) path = options.delete(:metric) noticed_error = NewRelic::NoticedError.new(path, exception) diff --git a/test/new_relic/agent/event_aggregator_test.rb b/test/new_relic/agent/event_aggregator_test.rb index d0d6e27fa2..a43ac62f8f 100644 --- a/test/new_relic/agent/event_aggregator_test.rb +++ b/test/new_relic/agent/event_aggregator_test.rb @@ -65,10 +65,10 @@ def test_it_has_a_name end def test_enabled_reflects_config_value - assert_predicate @aggregator, :enabled?, "Expected enabled? to be true" + assert_predicate @aggregator, :enabled?, 'Expected enabled? to be true' with_server_source(:enabled_key => false) do - refute @aggregator.enabled?, "Expected enabled? to be false" + refute @aggregator.enabled?, 'Expected enabled? to be false' end end @@ -92,7 +92,7 @@ def test_after_harvest_invoked_with_report end def test_notifies_full - expects_logging(:debug, includes("TestAggregator capacity of 5 reached")) + expects_logging(:debug, includes('TestAggregator capacity of 5 reached')) with_config(:cap_key => 5) do 5.times { |i| @aggregator.record(i) } end @@ -100,7 +100,7 @@ def test_notifies_full def test_notifies_full_only_once with_config(:cap_key => 5) do - msg = "TestAggregator capacity of 5 reached" + msg = 'TestAggregator capacity of 5 reached' # this will trigger a message to be logged 5.times { |i| @aggregator.record(i) } @@ -111,7 +111,7 @@ def test_notifies_full_only_once end def test_notifies_full_resets_after_harvest - msg = "TestAggregator capacity of 5 reached" + msg = 'TestAggregator capacity of 5 reached' expects_logging(:debug, includes(msg)) with_config(:cap_key => 5) do @@ -127,7 +127,7 @@ def test_notifies_full_resets_after_harvest end def test_notifies_full_resets_after_buffer_reset - msg = "TestAggregator capacity of 5 reached" + msg = 'TestAggregator capacity of 5 reached' expects_logging(:debug, includes(msg)) with_config(:cap_key => 5) do diff --git a/test/new_relic/agent/event_listener_test.rb b/test/new_relic/agent/event_listener_test.rb index 00ab8dfad4..419434df54 100644 --- a/test/new_relic/agent/event_listener_test.rb +++ b/test/new_relic/agent/event_listener_test.rb @@ -26,7 +26,7 @@ def assert_was_called end def assert_was_not_called - refute @called, "Event was called" + refute @called, 'Event was called' end # @@ -35,14 +35,14 @@ def assert_was_not_called def test_notifies @events.subscribe(:before_call, &@check_method) - @events.notify(:before_call, :env => "env") + @events.notify(:before_call, :env => 'env') assert_was_called - assert_equal([{:env => "env"}], @called_with) + assert_equal([{:env => 'env'}], @called_with) end def test_failure_during_notify_doesnt_block_other_hooks - @events.subscribe(:after_call) { raise "Boo!" } + @events.subscribe(:after_call) { raise 'Boo!' } @events.subscribe(:after_call, &@check_method) @events.notify(:after_call) @@ -52,7 +52,7 @@ def test_failure_during_notify_doesnt_block_other_hooks def test_runaway_events @events.runaway_threshold = 0 - expects_logging(:debug, includes("my_event")) + expects_logging(:debug, includes('my_event')) @events.subscribe(:my_event) {} end diff --git a/test/new_relic/agent/external_test.rb b/test/new_relic/agent/external_test.rb index 0047dc0722..e555f8ca3f 100644 --- a/test/new_relic/agent/external_test.rb +++ b/test/new_relic/agent/external_test.rb @@ -13,7 +13,7 @@ class ExternalTest < Minitest::Test def setup NewRelic::Agent::Harvester.any_instance.stubs(:harvest_thread_enabled?).returns(false) - @obfuscator = NewRelic::Agent::Obfuscator.new("jotorotoes") + @obfuscator = NewRelic::Agent::Obfuscator.new('jotorotoes') NewRelic::Agent::CrossAppTracing.stubs(:obfuscator).returns(@obfuscator) NewRelic::Agent::CrossAppTracing.stubs(:valid_encoding_key?).returns(true) end @@ -72,7 +72,7 @@ def test_process_request_metadata_not_in_transaction l = with_array_logger { NewRelic::Agent::External.process_request_metadata(rmd) } - assert_empty l.array, "process_request_metadata should not log errors without a current transaction" + assert_empty l.array, 'process_request_metadata should not log errors without a current transaction' refute Tracer.current_transaction end @@ -89,7 +89,7 @@ def test_process_request_metadata_with_invalid_id in_transaction do |txn| l = with_array_logger { NewRelic::Agent::External.process_request_metadata(rmd) } - refute_empty l.array, "process_request_metadata should log error on invalid ID" + refute_empty l.array, 'process_request_metadata should log error on invalid ID' assert_includes l.array.first, 'invalid/non-trusted ID' refute txn.distributed_tracer.cross_app_payload @@ -108,7 +108,7 @@ def test_process_request_metadata_with_non_trusted_id in_transaction do |txn| l = with_array_logger { NewRelic::Agent::External.process_request_metadata(rmd) } - refute_empty l.array, "process_request_metadata should log error on invalid ID" + refute_empty l.array, 'process_request_metadata should log error on invalid ID' assert_includes l.array.first, 'invalid/non-trusted ID' refute txn.distributed_tracer.cross_app_payload @@ -126,7 +126,7 @@ def test_process_request_metadata_cross_app_disabled in_transaction do |txn| l = with_array_logger { NewRelic::Agent::External.process_request_metadata(rmd) } - assert_empty l.array, "process_request_metadata should not log errors when cross app tracing is disabled" + assert_empty l.array, 'process_request_metadata should not log errors when cross app tracing is disabled' refute txn.distributed_tracer.cross_app_payload end @@ -185,7 +185,7 @@ def cat_config { :'cross_application_tracer.enabled' => true, :'distributed_tracing.enabled' => false, - :cross_process_id => "269975#22824", + :cross_process_id => '269975#22824', :trusted_account_ids => [1, 269975] } end diff --git a/test/new_relic/agent/hostname_test.rb b/test/new_relic/agent/hostname_test.rb index 586b606391..1a1cc2152f 100644 --- a/test/new_relic/agent/hostname_test.rb +++ b/test/new_relic/agent/hostname_test.rb @@ -10,7 +10,7 @@ module Agent class HostnameTest < Minitest::Test def setup NewRelic::Agent::Hostname.instance_variable_set(:@hostname, nil) - Socket.stubs(:gethostname).returns(String.new('Rivendell')) + Socket.stubs(:gethostname).returns((+'Rivendell')) end def teardown @@ -22,7 +22,7 @@ def test_get_returns_socket_hostname end def test_get_returns_socket_hostname_converted_to_utf8 - computer = String.new('Elronds’s-Computer') + computer = +'Elronds’s-Computer' Socket.stubs(:gethostname).returns(computer.force_encoding(Encoding::ASCII_8BIT)) assert_equal 'Elronds’s-Computer', NewRelic::Agent::Hostname.get @@ -48,7 +48,7 @@ def test_shortens_to_prefix_if_using_dyno_names_and_matches def test_does_not_shorten_if_not_using_dyno_names with_dyno_name('Imladris', :'heroku.use_dyno_names' => false, :'heroku.dyno_name_prefixes_to_shorten' => ['Rivendell']) do - Socket.stubs(:gethostname).returns(String.new('Rivendell.1')) + Socket.stubs(:gethostname).returns((+'Rivendell.1')) assert_equal 'Rivendell.1', NewRelic::Agent::Hostname.get end @@ -106,11 +106,11 @@ def test_localhost_predicate_false_when_host_nonlocal end def test_get_external_returns_host_for_localhost - assert_equal "Rivendell", NewRelic::Agent::Hostname.get_external("localhost") + assert_equal 'Rivendell', NewRelic::Agent::Hostname.get_external('localhost') end def test_get_external_returns_argument_for_nonlocalhost - assert_equal "drscheffler", NewRelic::Agent::Hostname.get_external("drscheffler") + assert_equal 'drscheffler', NewRelic::Agent::Hostname.get_external('drscheffler') end def with_dyno_name(dyno_name, config_options) @@ -133,7 +133,7 @@ def test_get_fqdn_no_stubs # 'hostname -f' succeeds def test_get_fqdn_hostname_f - stubbed = String.new('Rivendell.Eriador.MiddleEarth') + stubbed = +'Rivendell.Eriador.MiddleEarth' NewRelic::Helper.stubs('run_command').with('hostname -f').returns(stubbed) fqdn = NewRelic::Agent::Hostname.get_fqdn @@ -142,7 +142,7 @@ def test_get_fqdn_hostname_f # 'hostname -f' fails, 'hostname' succeeds def test_get_fqdn_hostname - stubbed = String.new('Lauterbrunnen.Switzerland.Earth') + stubbed = +'Lauterbrunnen.Switzerland.Earth' NewRelic::Helper.stubs('run_command').with('hostname -f').raises(NewRelic::CommandRunFailedError) NewRelic::Helper.stubs('run_command').with('hostname').returns(stubbed) fqdn = NewRelic::Agent::Hostname.get_fqdn diff --git a/test/new_relic/agent/http_clients/uri_util_test.rb b/test/new_relic/agent/http_clients/uri_util_test.rb index bb218ae833..059bc95d9d 100644 --- a/test/new_relic/agent/http_clients/uri_util_test.rb +++ b/test/new_relic/agent/http_clients/uri_util_test.rb @@ -7,58 +7,58 @@ class URIUtilTest < Minitest::Test def test_obfuscated - assert_obfuscated("http://foo.com/bar/baz", - "http://foo.com/bar/baz") + assert_obfuscated('http://foo.com/bar/baz', + 'http://foo.com/bar/baz') end def test_obfuscated_custom_port - assert_obfuscated("http://foo.com:1234/bar/baz", - "http://foo.com:1234/bar/baz") + assert_obfuscated('http://foo.com:1234/bar/baz', + 'http://foo.com:1234/bar/baz') end def test_obfuscated_omits_query_params - assert_obfuscated("http://foo.com/bar/baz?a=1&b=2", - "http://foo.com/bar/baz") + assert_obfuscated('http://foo.com/bar/baz?a=1&b=2', + 'http://foo.com/bar/baz') end def test_obfuscated_omits_fragment - assert_obfuscated("http://foo.com/bar/baz#fragment", - "http://foo.com/bar/baz") + assert_obfuscated('http://foo.com/bar/baz#fragment', + 'http://foo.com/bar/baz') end def test_obfuscated_omits_query_params_and_fragment - assert_obfuscated("http://foo.com/bar/baz?a=1&b=2#fragment", - "http://foo.com/bar/baz") + assert_obfuscated('http://foo.com/bar/baz?a=1&b=2#fragment', + 'http://foo.com/bar/baz') end def test_obfuscated_reflects_use_of_ssl - assert_obfuscated("https://foo.com/bar/baz", - "https://foo.com/bar/baz") + assert_obfuscated('https://foo.com/bar/baz', + 'https://foo.com/bar/baz') end def test_obfuscated_reflects_use_of_ssl_with_custom_port - assert_obfuscated("https://foo.com:9999/bar/baz", - "https://foo.com:9999/bar/baz") + assert_obfuscated('https://foo.com:9999/bar/baz', + 'https://foo.com:9999/bar/baz') end def test_obfuscated_with_full_uri_request_path - assert_obfuscated("http://foo.com/bar/baz?a=1&b=2#fragment", - "http://foo.com/bar/baz") + assert_obfuscated('http://foo.com/bar/baz?a=1&b=2#fragment', + 'http://foo.com/bar/baz') end def test_obfuscated_with_full_uri_request_path_https - assert_obfuscated("https://foo.com/bar/baz?a=1&b=2#fragment", - "https://foo.com/bar/baz") + assert_obfuscated('https://foo.com/bar/baz?a=1&b=2#fragment', + 'https://foo.com/bar/baz') end def test_strips_credentials_embedded_in_uri - assert_obfuscated("http://user:pass@foo.com/bar/baz", - "http://foo.com/bar/baz") + assert_obfuscated('http://user:pass@foo.com/bar/baz', + 'http://foo.com/bar/baz') end def test_invalid_url_normalization - assert_normalized("foobarbaz", - "foobarbaz") + assert_normalized('foobarbaz', + 'foobarbaz') end def assert_obfuscated(original, expected) @@ -71,8 +71,8 @@ def assert_normalized(original, expected) def test_obfuscate_should_not_modify_uri_input test_urls = [ - ::URI.parse("https://foo.com/bar/baz?a=1&b=2#fragment"), - "https://foo.com/bar/baz?a=1&b=2#fragment" + ::URI.parse('https://foo.com/bar/baz?a=1&b=2#fragment'), + 'https://foo.com/bar/baz?a=1&b=2#fragment' ] test_urls.each do |original| diff --git a/test/new_relic/agent/instrumentation/action_dispatch_subscriber_test.rb b/test/new_relic/agent/instrumentation/action_dispatch_subscriber_test.rb index 20a7b23af5..5c1f4e9c1d 100644 --- a/test/new_relic/agent/instrumentation/action_dispatch_subscriber_test.rb +++ b/test/new_relic/agent/instrumentation/action_dispatch_subscriber_test.rb @@ -12,5 +12,5 @@ ActionPack.gem_version >= Gem::Version.new('6.0.0') # notifications for dispatch added in Rails 6 require_relative 'rails/action_dispatch_subscriber' else - puts "Skipping tests in #{File.basename(__FILE__)} because ActionDispatch is unavailable or < 6.0" if ENV["VERBOSE_TEST_OUTPUT"] + puts "Skipping tests in #{File.basename(__FILE__)} because ActionDispatch is unavailable or < 6.0" if ENV['VERBOSE_TEST_OUTPUT'] end diff --git a/test/new_relic/agent/instrumentation/action_mailbox_subscriber_test.rb b/test/new_relic/agent/instrumentation/action_mailbox_subscriber_test.rb index 4207d528ca..9f6ae52948 100644 --- a/test/new_relic/agent/instrumentation/action_mailbox_subscriber_test.rb +++ b/test/new_relic/agent/instrumentation/action_mailbox_subscriber_test.rb @@ -10,5 +10,5 @@ ActionMailbox.gem_version >= Gem::Version.new('7.1.0.alpha') # notifications added in Rails 7.1 require_relative 'rails/action_mailbox_subscriber' else - puts "Skipping tests in #{File.basename(__FILE__)} because ActionMailbox is unavailable or < 7.1" if ENV["VERBOSE_TEST_OUTPUT"] + puts "Skipping tests in #{File.basename(__FILE__)} because ActionMailbox is unavailable or < 7.1" if ENV['VERBOSE_TEST_OUTPUT'] end diff --git a/test/new_relic/agent/instrumentation/action_mailer_subscriber_test.rb b/test/new_relic/agent/instrumentation/action_mailer_subscriber_test.rb index 40d5f42a65..48426e0d35 100644 --- a/test/new_relic/agent/instrumentation/action_mailer_subscriber_test.rb +++ b/test/new_relic/agent/instrumentation/action_mailer_subscriber_test.rb @@ -11,5 +11,5 @@ ActionMailer.gem_version >= Gem::Version.new('5.0') && RUBY_VERSION > '2.4.0' require_relative 'rails/action_mailer_subscriber' else - puts "Skipping tests in #{File.basename(__FILE__)} because ActionMailer is unavailable" if ENV["VERBOSE_TEST_OUTPUT"] + puts "Skipping tests in #{File.basename(__FILE__)} because ActionMailer is unavailable" if ENV['VERBOSE_TEST_OUTPUT'] end diff --git a/test/new_relic/agent/instrumentation/active_job_test.rb b/test/new_relic/agent/instrumentation/active_job_test.rb index fb6235ea9a..bab14a3c0f 100644 --- a/test/new_relic/agent/instrumentation/active_job_test.rb +++ b/test/new_relic/agent/instrumentation/active_job_test.rb @@ -8,15 +8,15 @@ module NewRelic::Agent::Instrumentation class ActiveJobHelperTest < Minitest::Test def test_rails_formatted_adapters_get_shortened - name = ActiveJobHelper.clean_adapter_name("ActiveJob::QueueAdapters::InlineAdapter") + name = ActiveJobHelper.clean_adapter_name('ActiveJob::QueueAdapters::InlineAdapter') - assert_equal "ActiveJob::Inline", name + assert_equal 'ActiveJob::Inline', name end def test_unexpected_name_format - name = ActiveJobHelper.clean_adapter_name("Not::AnExpected::Adapter") + name = ActiveJobHelper.clean_adapter_name('Not::AnExpected::Adapter') - assert_equal "Not::AnExpected::Adapter", name + assert_equal 'Not::AnExpected::Adapter', name end end end diff --git a/test/new_relic/agent/instrumentation/active_record_helper_test.rb b/test/new_relic/agent/instrumentation/active_record_helper_test.rb index ba39735f1c..a53a559766 100644 --- a/test/new_relic/agent/instrumentation/active_record_helper_test.rb +++ b/test/new_relic/agent/instrumentation/active_record_helper_test.rb @@ -10,64 +10,74 @@ class ActiveRecordHelperTest < Minitest::Test def test_product_operation_collection_for_find product, operation, collection = ActiveRecordHelper.product_operation_collection_for('Namespace::Model Load', nil, nil) - assert_equal "ActiveRecord", product - assert_equal "find", operation - assert_equal "Namespace::Model", collection + assert_equal 'ActiveRecord', product + assert_equal 'find', operation + assert_equal 'Namespace::Model', collection end def test_product_operation_collection_for_destroy product, operation, collection = ActiveRecordHelper.product_operation_collection_for('Model Destroy', nil, nil) - assert_equal "ActiveRecord", product - assert_equal "destroy", operation - assert_equal "Model", collection + assert_equal 'ActiveRecord', product + assert_equal 'destroy', operation + assert_equal 'Model', collection end def test_product_operation_collection_for_create product, operation, collection = ActiveRecordHelper.product_operation_collection_for('Model Create', nil, nil) - assert_equal "ActiveRecord", product - assert_equal "create", operation - assert_equal "Model", collection + assert_equal 'ActiveRecord', product + assert_equal 'create', operation + assert_equal 'Model', collection end def test_product_operation_collection_for_update product, operation, collection = ActiveRecordHelper.product_operation_collection_for('Model Update', nil, nil) - assert_equal "ActiveRecord", product - assert_equal "update", operation - assert_equal "Model", collection + assert_equal 'ActiveRecord', product + assert_equal 'update', operation + assert_equal 'Model', collection end def test_product_operation_collection_for_name_columns product, operation, collection = ActiveRecordHelper.product_operation_collection_for('Model Columns', nil, nil) - assert_equal "ActiveRecord", product - assert_equal "columns", operation - assert_equal "Model", collection + assert_equal 'ActiveRecord', product + assert_equal 'columns', operation + assert_equal 'Model', collection end def test_product_operation_collection_for_with_product_name_from_adapter - product, operation, collection = ActiveRecordHelper.product_operation_collection_for('Model Load', nil, "mysql") + product, operation, collection = ActiveRecordHelper.product_operation_collection_for('Model Load', nil, 'mysql') - assert_equal "MySQL", product - assert_equal "find", operation - assert_equal "Model", collection + assert_equal 'MySQL', product + assert_equal 'find', operation + assert_equal 'Model', collection end def test_product_operation_collection_for_from_sql - product, operation, collection = ActiveRecordHelper.product_operation_collection_for('invalid', "SELECT * FROM boo", nil) + product, operation, collection = ActiveRecordHelper.product_operation_collection_for('invalid', 'SELECT * FROM boo', nil) - assert_equal "ActiveRecord", product - assert_equal "select", operation + assert_equal 'ActiveRecord', product + assert_equal 'select', operation assert_nil collection end + def test_product_operation_collection_for_timestream_from_adapter + product, operation, collection = ActiveRecordHelper.product_operation_collection_for('Model Load', + nil, + 'amazon_timestream') + + assert_equal 'Timestream', product + assert_equal 'find', operation + assert_equal 'Model', collection + end + def test_product_operation_collection_for_name_with_integer_returns_nil product, operation, collection = ActiveRecordHelper.product_operation_collection_for(1, '', nil) - assert_equal "ActiveRecord", product - assert_equal "other", operation + assert_equal 'ActiveRecord', product + assert_equal 'other', operation assert_nil collection end diff --git a/test/new_relic/agent/instrumentation/active_storage_subscriber_test.rb b/test/new_relic/agent/instrumentation/active_storage_subscriber_test.rb index 1b1c7353a1..46127abc4a 100644 --- a/test/new_relic/agent/instrumentation/active_storage_subscriber_test.rb +++ b/test/new_relic/agent/instrumentation/active_storage_subscriber_test.rb @@ -13,5 +13,5 @@ def supported_active_storage_available? require_relative 'rails/active_storage_subscriber' else - puts "Skipping tests in #{File.basename(__FILE__)} because ActiveStorage is unavailable" if ENV["VERBOSE_TEST_OUTPUT"] + puts "Skipping tests in #{File.basename(__FILE__)} because ActiveStorage is unavailable" if ENV['VERBOSE_TEST_OUTPUT'] end diff --git a/test/new_relic/agent/instrumentation/active_support_subscriber_test.rb b/test/new_relic/agent/instrumentation/active_support_subscriber_test.rb index 6eb5d9f714..98a51822fb 100644 --- a/test/new_relic/agent/instrumentation/active_support_subscriber_test.rb +++ b/test/new_relic/agent/instrumentation/active_support_subscriber_test.rb @@ -8,5 +8,5 @@ if defined?(ActiveSupport) require_relative 'rails/active_support_subscriber' else - puts "Skipping tests in #{File.basename(__FILE__)} because Active Support is unavailable" if ENV["VERBOSE_TEST_OUTPUT"] + puts "Skipping tests in #{File.basename(__FILE__)} because Active Support is unavailable" if ENV['VERBOSE_TEST_OUTPUT'] end diff --git a/test/new_relic/agent/instrumentation/controller_instrumentation_test.rb b/test/new_relic/agent/instrumentation/controller_instrumentation_test.rb index 0536c7c799..8d0f1487a8 100644 --- a/test/new_relic/agent/instrumentation/controller_instrumentation_test.rb +++ b/test/new_relic/agent/instrumentation/controller_instrumentation_test.rb @@ -66,14 +66,14 @@ def teardown def test_apdex_recorded @object.public_transaction - assert_metrics_recorded("Apdex") + assert_metrics_recorded('Apdex') end def test_apdex_ignored @object.stubs(:ignore_apdex?).returns(true) @object.public_transaction - assert_metrics_not_recorded("Apdex") + assert_metrics_not_recorded('Apdex') end def test_apdex_ignored_if_ignored_in_parent_class @@ -82,7 +82,7 @@ def test_apdex_ignored_if_ignored_in_parent_class obj.foo obj.bar - assert_metrics_not_recorded("Apdex") + assert_metrics_not_recorded('Apdex') end def test_children_respect_parental_ignore_rules_with_only @@ -142,7 +142,7 @@ def test_ignore_allows_strings controller = Class.new do include ControllerInstrumentation - newrelic_ignore(:only => "foo") + newrelic_ignore(:only => 'foo') end key = ControllerInstrumentation::NR_DO_NOT_TRACE_KEY @@ -154,7 +154,7 @@ def test_ignore_allows_mixed_strings_and_symbols controller = Class.new do include ControllerInstrumentation - newrelic_ignore(:only => ["foo", :bar]) + newrelic_ignore(:only => ['foo', :bar]) end key = ControllerInstrumentation::NR_DO_NOT_TRACE_KEY @@ -252,19 +252,19 @@ def test_transaction_namer_determines_prefix def test_transaction_path_name result = @txn_namer.path_name(@object) - assert_equal("NewRelic::Agent::Instrumentation::ControllerInstrumentationTest::TestObject", result) + assert_equal('NewRelic::Agent::Instrumentation::ControllerInstrumentationTest::TestObject', result) end def test_transaction_path_name_with_name - result = @txn_namer.path_name(@object, :name => "test") + result = @txn_namer.path_name(@object, :name => 'test') - assert_equal("NewRelic::Agent::Instrumentation::ControllerInstrumentationTest::TestObject/test", result) + assert_equal('NewRelic::Agent::Instrumentation::ControllerInstrumentationTest::TestObject/test', result) end def test_transaction_path_name_with_overridden_class_name - result = @txn_namer.path_name(@object, :name => "perform", :class_name => 'Resque') + result = @txn_namer.path_name(@object, :name => 'perform', :class_name => 'Resque') - assert_equal("Resque/perform", result) + assert_equal('Resque/perform', result) end def test_add_transaction_tracer_should_not_double_instrument @@ -296,14 +296,14 @@ def test_parse_punctuation def test_argument_list options = {:foo => :bar, :params => '{ :account_name => args[0].name }', :far => 7} result = TestObject.generate_argument_list(options) - expected = [":far => \"7\"", ":foo => :bar", ":params => { :account_name => args[0].name }"] + expected = [':far => "7"', ':foo => :bar', ':params => { :account_name => args[0].name }'] assert_equal expected.sort, result.sort end def test_build_method_names result = TestObject.build_method_names('foo', '?') - expected = ["foo_with_newrelic_transaction_trace?", "foo_without_newrelic_transaction_trace?"] + expected = ['foo_with_newrelic_transaction_trace?', 'foo_without_newrelic_transaction_trace?'] assert_equal expected, result end diff --git a/test/new_relic/agent/instrumentation/instance_identification_test.rb b/test/new_relic/agent/instrumentation/instance_identification_test.rb index 24674c0e9f..b7529e0469 100644 --- a/test/new_relic/agent/instrumentation/instance_identification_test.rb +++ b/test/new_relic/agent/instrumentation/instance_identification_test.rb @@ -12,15 +12,15 @@ module ActiveRecordHelper class InstanceIdentificationTest < Minitest::Test def test_for_constructs_id_with_configured_host_and_port config = { - :host => "jonan.local", + :host => 'jonan.local', :port => 42 } host = InstanceIdentification.host(config) ppid = InstanceIdentification.port_path_or_id(config) - assert_equal "jonan.local", host - assert_equal "42", ppid + assert_equal 'jonan.local', host + assert_equal '42', ppid end def test_for_constructs_id_with_unspecified_configuration @@ -28,31 +28,31 @@ def test_for_constructs_id_with_unspecified_configuration host = InstanceIdentification.host(config) ppid = InstanceIdentification.port_path_or_id(config) - assert_equal "localhost", host - assert_equal "default", ppid + assert_equal 'localhost', host + assert_equal 'default', ppid end def test_for_constructs_id_with_weird_configs config = { - :host => "", - :port => "" + :host => '', + :port => '' } host = InstanceIdentification.host(config) ppid = InstanceIdentification.port_path_or_id(config) - assert_equal "unknown", host - assert_equal "unknown", ppid + assert_equal 'unknown', host + assert_equal 'unknown', ppid end def test_for_constructs_id_with_configured_host_without_port - config = {:host => "jonan.gummy_planet"} + config = {:host => 'jonan.gummy_planet'} host = InstanceIdentification.host(config) ppid = InstanceIdentification.port_path_or_id(config) - assert_equal "jonan.gummy_planet", host - assert_equal "default", ppid + assert_equal 'jonan.gummy_planet', host + assert_equal 'default', ppid end def test_for_constructs_id_with_port_without_host @@ -61,48 +61,48 @@ def test_for_constructs_id_with_port_without_host host = InstanceIdentification.host(config) ppid = InstanceIdentification.port_path_or_id(config) - assert_equal "localhost", host - assert_equal "1337", ppid + assert_equal 'localhost', host + assert_equal '1337', ppid end def test_for_constructs_id_with_default_port config = { - :adapter => "mysql", - :host => "jonan.gummy_planet" + :adapter => 'mysql', + :host => 'jonan.gummy_planet' } host = InstanceIdentification.host(config) ppid = InstanceIdentification.port_path_or_id(config) - assert_equal "jonan.gummy_planet", host - assert_equal "3306", ppid + assert_equal 'jonan.gummy_planet', host + assert_equal '3306', ppid end def test_for_constructs_id_with_postgres_directory config = { - :adapter => "postgresql", - :host => "/tmp" + :adapter => 'postgresql', + :host => '/tmp' } host = InstanceIdentification.host(config) ppid = InstanceIdentification.port_path_or_id(config) - assert_equal "localhost", host - assert_equal "default", ppid + assert_equal 'localhost', host + assert_equal 'default', ppid end def test_for_constructs_id_with_mysql_socket %w[ mysql mysql2 jdbcmysql ].each do |adapter| config = { :adapter => adapter, - :socket => "/var/run/mysqld.sock" + :socket => '/var/run/mysqld.sock' } host = InstanceIdentification.host(config) ppid = InstanceIdentification.port_path_or_id(config) - assert_equal "localhost", host - assert_equal "/var/run/mysqld.sock", ppid + assert_equal 'localhost', host + assert_equal '/var/run/mysqld.sock', ppid end end @@ -123,7 +123,7 @@ def test_supports_supported_adapters in_transaction do config = convert_test_case_to_config(test) - product, operation, collection = ActiveRecordHelper.product_operation_collection_for("Blog Find", nil, config[:adapter]) + product, operation, collection = ActiveRecordHelper.product_operation_collection_for('Blog Find', nil, config[:adapter]) host = ActiveRecordHelper::InstanceIdentification.host(config) port_path_or_id = ActiveRecordHelper::InstanceIdentification.port_path_or_id(config) @@ -142,10 +142,10 @@ def test_supports_supported_adapters end CONFIG_NAMES = { - "db_hostname" => :host, - "unix_socket" => :socket, - "port" => :port, - "product" => :adapter + 'db_hostname' => :host, + 'unix_socket' => :socket, + 'port' => :port, + 'product' => :adapter } def convert_test_case_to_config(test_case) @@ -160,9 +160,9 @@ def convert_test_case_to_config(test_case) end PRODUCT_TO_ADAPTER_NAMES = { - "Postgres" => "postgresql", - "MySQL" => "mysql", - "SQLite" => "sqlite3" + 'Postgres' => 'postgresql', + 'MySQL' => 'mysql', + 'SQLite' => 'sqlite3' } def convert_product_to_adapter(config) diff --git a/test/new_relic/agent/instrumentation/instrumentation_test.rb b/test/new_relic/agent/instrumentation/instrumentation_test.rb index 175949aa50..e1ea4b9cdf 100644 --- a/test/new_relic/agent/instrumentation/instrumentation_test.rb +++ b/test/new_relic/agent/instrumentation/instrumentation_test.rb @@ -6,8 +6,8 @@ class NewRelic::Agent::Instrumentation::InstrumentationTest < Minitest::Test Dir.glob('lib/new_relic/agent/instrumentation/**/*.rb') do |filename| - sub_folder = File.dirname(filename).split("/")[-1] - base_name = File.basename(filename).split(".")[0] + sub_folder = File.dirname(filename).split('/')[-1] + base_name = File.basename(filename).split('.')[0] # checking for syntax errors and unguarded code define_method("test_load_#{sub_folder}_#{base_name}") do diff --git a/test/new_relic/agent/instrumentation/middleware_proxy_test.rb b/test/new_relic/agent/instrumentation/middleware_proxy_test.rb index af325012cf..0047de0364 100644 --- a/test/new_relic/agent/instrumentation/middleware_proxy_test.rb +++ b/test/new_relic/agent/instrumentation/middleware_proxy_test.rb @@ -79,7 +79,7 @@ def test_anonymous_class_naming name = wrapped_instance.transaction_options[:transaction_name] - assert_equal("Middleware/Rack/AnonymousClass/call", name) + assert_equal('Middleware/Rack/AnonymousClass/call', name) end class BaseForAnonymous @@ -189,7 +189,7 @@ def test_should_start_transaction_if_none_is_running wrapped.call({}) - assert_metrics_recorded("HttpDispatcher") + assert_metrics_recorded('HttpDispatcher') end def test_should_respect_force_transaction_flag @@ -209,7 +209,7 @@ def test_should_respect_force_transaction_flag def test_should_get_the_right_name_when_target_is_a_class target_class = Class.new do def self.name - "GreatClass" + 'GreatClass' end def self.call(env) @@ -225,7 +225,7 @@ def self.call(env) end def test_should_emit_events_once - app = proc { |env| [200, {}, ["nothing"]] } + app = proc { |env| [200, {}, ['nothing']] } middleware = proc { |env| app.call(env) } wrapped_middleware = NewRelic::Agent::Instrumentation::MiddlewareProxy.wrap(middleware, true) @@ -242,7 +242,7 @@ def test_should_emit_events_once end def test_before_call_should_receive_rack_env_hash - app = proc { |env| [200, {}, ["nothing"]] } + app = proc { |env| [200, {}, ['nothing']] } wrapped_app = NewRelic::Agent::Instrumentation::MiddlewareProxy.wrap(app, true) original_env = {} @@ -256,7 +256,7 @@ def test_before_call_should_receive_rack_env_hash end def test_after_call_should_receive_rack_env_hash - app = proc { |env| [200, {}, ["nothing"]] } + app = proc { |env| [200, {}, ['nothing']] } wrapped_app = NewRelic::Agent::Instrumentation::MiddlewareProxy.wrap(app, true) original_env = {} diff --git a/test/new_relic/agent/instrumentation/mongodb_command_subscriber_test.rb b/test/new_relic/agent/instrumentation/mongodb_command_subscriber_test.rb index 5cb5229ae7..3d6b9b40b2 100644 --- a/test/new_relic/agent/instrumentation/mongodb_command_subscriber_test.rb +++ b/test/new_relic/agent/instrumentation/mongodb_command_subscriber_test.rb @@ -13,7 +13,7 @@ def setup @started_event.stubs(:command_name).returns('find') @started_event.stubs(:database_name).returns('mongodb-test') @started_event.stubs(:command).returns({'find' => 'users', 'filter' => {'name' => 'test'}}) - address = stub('address', :host => "127.0.0.1", :port => 27017) + address = stub('address', :host => '127.0.0.1', :port => 27017) @started_event.stubs(:address).returns(address) @succeeded_event = mock('succeeded event') @@ -22,7 +22,7 @@ def setup @subscriber = NewRelic::Agent::Instrumentation::MongodbCommandSubscriber.new - NewRelic::Agent::Hostname.stubs(:get).returns("nerd-server") + NewRelic::Agent::Hostname.stubs(:get).returns('nerd-server') @stats_engine = NewRelic::Agent.instance.stats_engine @stats_engine.clear_stats end @@ -76,7 +76,7 @@ def test_records_instance_metrics_for_tcp_connection end def test_records_instance_metrics_for_unix_domain_socket - address = stub('address', :host => "/tmp/mongodb-27017.sock", :port => nil) + address = stub('address', :host => '/tmp/mongodb-27017.sock', :port => nil) @started_event.stubs(:address).returns(address) in_transaction { simulate_query } @@ -103,7 +103,7 @@ def test_records_tt_segment_parameters_for_datastore_instance end def test_does_not_record_unknown_unknown_metric_when_data_empty - address = stub('address', :host => "", :port => "") + address = stub('address', :host => '', :port => '') @started_event.stubs(:address).returns(address) in_transaction { simulate_query } diff --git a/test/new_relic/agent/instrumentation/net_instrumentation_test.rb b/test/new_relic/agent/instrumentation/net_instrumentation_test.rb index cf9797b2e0..10387a0481 100644 --- a/test/new_relic/agent/instrumentation/net_instrumentation_test.rb +++ b/test/new_relic/agent/instrumentation/net_instrumentation_test.rb @@ -31,8 +31,8 @@ def test_scope_stack_integrity_maintained_on_request_failure @socket.stubs(:write).raises('fake network error') @socket.stubs(:write_nonblock).raises('fake network error') with_config(:"cross_application_tracer.enabled" => true) do - in_transaction("test") do - segment = NewRelic::Agent::Tracer.start_segment(name: "dummy") + in_transaction('test') do + segment = NewRelic::Agent::Tracer.start_segment(name: 'dummy') Net::HTTP.get(URI.parse('http://www.google.com/index.html')) rescue nil segment.finish end diff --git a/test/new_relic/agent/instrumentation/notification_subscriber_test.rb b/test/new_relic/agent/instrumentation/notification_subscriber_test.rb index 2237aa34cc..cbdc771f24 100644 --- a/test/new_relic/agent/instrumentation/notification_subscriber_test.rb +++ b/test/new_relic/agent/instrumentation/notification_subscriber_test.rb @@ -8,5 +8,5 @@ if defined?(ActiveSupport) require_relative 'rails/notifications_subscriber' else - puts "Skipping tests in #{File.basename(__FILE__)} because Active Support is unavailable" if ENV["VERBOSE_TEST_OUTPUT"] + puts "Skipping tests in #{File.basename(__FILE__)} because Active Support is unavailable" if ENV['VERBOSE_TEST_OUTPUT'] end diff --git a/test/new_relic/agent/instrumentation/rack_test.rb b/test/new_relic/agent/instrumentation/rack_test.rb index 8b6f23e4b9..3084ca7208 100644 --- a/test/new_relic/agent/instrumentation/rack_test.rb +++ b/test/new_relic/agent/instrumentation/rack_test.rb @@ -23,21 +23,21 @@ def generate_minimal_rack_app(mock_response) def test_basic_rack_app # should return what we send in, even when instrumented - x = generate_minimal_rack_app([200, {}, ["whee"]]) + x = generate_minimal_rack_app([200, {}, ['whee']]) - assert_equal [200, {}, ["whee"]], x.call({}) + assert_equal [200, {}, ['whee']], x.call({}) assert_metrics_recorded(['Controller/Middleware/Rack/MinimalRackApp/call']) end def test_basic_rack_app_404 - x = generate_minimal_rack_app([404, {}, ["whee"]]) + x = generate_minimal_rack_app([404, {}, ['whee']]) - assert_equal [404, {}, ["whee"]], x.call({}) + assert_equal [404, {}, ['whee']], x.call({}) assert_metrics_recorded(['Controller/Middleware/Rack/MinimalRackApp/call']) end def test_does_not_double_instrument_middlewares - x = generate_minimal_rack_app([200, {}, ["whee"]]) + x = generate_minimal_rack_app([200, {}, ['whee']]) wrapped_x = NewRelic::Agent::Instrumentation::MiddlewareProxy.wrap(x) assert_same(x, wrapped_x) diff --git a/test/new_relic/agent/instrumentation/rails/action_cable_subscriber.rb b/test/new_relic/agent/instrumentation/rails/action_cable_subscriber.rb index e902a94296..9319f4e538 100644 --- a/test/new_relic/agent/instrumentation/rails/action_cable_subscriber.rb +++ b/test/new_relic/agent/instrumentation/rails/action_cable_subscriber.rb @@ -114,7 +114,7 @@ def test_does_not_record_unscoped_metrics_nor_create_trace_for_transmit_outside_ sample = last_transaction_trace - assert_nil sample, "Did not expect a transaction to be created for transmit" + assert_nil sample, 'Did not expect a transaction to be created for transmit' refute_metrics_recorded ['Ruby/ActionCable/TestChannel/transmit'] end @@ -125,7 +125,7 @@ def test_does_not_record_unscoped_metrics_nor_create_trace_for_broadcast_outside sample = last_transaction_trace - assert_nil sample, "Did not expect a transaction to be created for broadcast" + assert_nil sample, 'Did not expect a transaction to be created for broadcast' refute_metrics_recorded ['Ruby/ActionCable/TestBroadcasting/broadcast'] end @@ -185,11 +185,11 @@ def test_actual_call_to_action_cable private def payload_for_perform_action(action = 'test_action') - {:channel_class => "TestChannel", :action => action.to_sym, :data => {"action" => "#{action}"}} + {:channel_class => 'TestChannel', :action => action.to_sym, :data => {'action' => "#{action}"}} end def payload_for_transmit(data = {}, via = nil) - {:channel_class => "TestChannel", :data => data, :via => via} + {:channel_class => 'TestChannel', :data => data, :via => via} end def payload_for_broadcast diff --git a/test/new_relic/agent/instrumentation/rails/action_controller_subscriber.rb b/test/new_relic/agent/instrumentation/rails/action_controller_subscriber.rb index 52bf2db9e4..1425d304e9 100644 --- a/test/new_relic/agent/instrumentation/rails/action_controller_subscriber.rb +++ b/test/new_relic/agent/instrumentation/rails/action_controller_subscriber.rb @@ -85,7 +85,7 @@ def test_record_apdex_metrics_with_error @subscriber.start('process_action.action_controller', :id, @entry_payload) advance_process_time(1.5) - error = StandardError.new("boo") + error = StandardError.new('boo') @exit_payload[:exception] = error NewRelic::Agent.notice_error(error) @@ -294,7 +294,7 @@ def test_records_request_params_in_txn end def test_records_filtered_request_params_in_txn - @request.env["action_dispatch.parameter_filter"] = [:password] + @request.env['action_dispatch.parameter_filter'] = [:password] with_config(:capture_params => true) do @entry_payload[:params]['password'] = 'secret' @subscriber.start('process_action.action_controller', :id, @entry_payload) @@ -318,7 +318,7 @@ def test_records_custom_parameters_in_txn def test_records_span_level_error exception_class = StandardError - exception_msg = "Natural 1" + exception_msg = 'Natural 1' exception = exception_class.new(msg = exception_msg) # :exception_object was added in Rails 5 and above params = {:exception_object => exception, :exception => [exception_class.name, exception_msg]} @@ -345,7 +345,7 @@ def test_records_code_level_metrics assert_equal __FILE__, attributes['code.filepath'] assert_equal 'index', attributes['code.function'] assert_equal TestController.instance_method(:index).source_location.last, attributes['code.lineno'] - assert_equal "NewRelic::Agent::Instrumentation::ActionControllerSubscriberTest::TestController", + assert_equal 'NewRelic::Agent::Instrumentation::ActionControllerSubscriberTest::TestController', attributes['code.namespace'] end end diff --git a/test/new_relic/agent/instrumentation/rails/action_view_subscriber.rb b/test/new_relic/agent/instrumentation/rails/action_view_subscriber.rb index 1d2c7d8171..52765b3305 100644 --- a/test/new_relic/agent/instrumentation/rails/action_view_subscriber.rb +++ b/test/new_relic/agent/instrumentation/rails/action_view_subscriber.rb @@ -162,7 +162,7 @@ def test_records_scoped_metric def test_records_span_level_error exception_class = StandardError - exception_msg = "Natural 1" + exception_msg = 'Natural 1' exception = exception_class.new(msg = exception_msg) # :exception_object was added in Rails 5 and above params = {:exception_object => exception, :exception => [exception_class.name, exception_msg]} diff --git a/test/new_relic/agent/instrumentation/rails/active_record_subscriber.rb b/test/new_relic/agent/instrumentation/rails/active_record_subscriber.rb index df7b4c5ed3..b7ec369041 100644 --- a/test/new_relic/agent/instrumentation/rails/active_record_subscriber.rb +++ b/test/new_relic/agent/instrumentation/rails/active_record_subscriber.rb @@ -47,7 +47,7 @@ def test_records_scoped_metrics end def test_records_datastore_instance_metric_for_supported_adapter - config = {:adapter => "mysql", :host => "jonan.gummy_planet", :port => 3306} + config = {:adapter => 'mysql', :host => 'jonan.gummy_planet', :port => 3306} @subscriber.stubs(:active_record_config).returns(config) in_transaction('test_txn') { simulate_query(2) } @@ -56,14 +56,14 @@ def test_records_datastore_instance_metric_for_supported_adapter end def test_records_datastore_instance_metric_with_one_datum_missing - config = {:adapter => "mysql", :host => "jonan.gummy_planet", :port => ""} + config = {:adapter => 'mysql', :host => 'jonan.gummy_planet', :port => ''} @subscriber.stubs(:active_record_config).returns(config) in_transaction('test_txn') { simulate_query(2) } assert_metrics_recorded('Datastore/instance/MySQL/jonan.gummy_planet/unknown') - config = {:adapter => "mysql", :host => "", :port => 3306} + config = {:adapter => 'mysql', :host => '', :port => 3306} @subscriber.stubs(:active_record_config).returns(config) in_transaction('test_txn') { simulate_query(2) } @@ -72,7 +72,7 @@ def test_records_datastore_instance_metric_with_one_datum_missing end def test_does_not_record_datastore_instance_metric_for_unsupported_adapter - config = {:adapter => "JonanDB", :host => "jonan.gummy_planet"} + config = {:adapter => 'JonanDB', :host => 'jonan.gummy_planet'} @subscriber.stubs(:active_record_config).returns(config) in_transaction('test_txn') { simulate_query(2) } @@ -82,7 +82,7 @@ def test_does_not_record_datastore_instance_metric_for_unsupported_adapter def test_does_not_record_datastore_instance_metric_if_disabled with_config('datastore_tracer.instance_reporting.enabled' => false) do - config = {:host => "jonan.gummy_planet"} + config = {:host => 'jonan.gummy_planet'} @subscriber.stubs(:active_record_config).returns(config) in_transaction('test_txn') { simulate_query(2) } @@ -92,7 +92,7 @@ def test_does_not_record_datastore_instance_metric_if_disabled end def test_does_not_record_datastore_instance_metric_if_both_are_empty - config = {:adapter => "", :host => ""} + config = {:adapter => '', :host => ''} @subscriber.stubs(:active_record_config).returns(config) in_transaction('test_txn') { simulate_query(2) } @@ -101,7 +101,7 @@ def test_does_not_record_datastore_instance_metric_if_both_are_empty end def test_does_not_record_database_name_if_disabled - config = {:host => "jonan.gummy_planet", :database => "pizza_cube"} + config = {:host => 'jonan.gummy_planet', :database => 'pizza_cube'} @subscriber.stubs(:active_record_config).returns(config) with_config('datastore_tracer.database_name_reporting.enabled' => false) do in_transaction { simulate_query(2) } @@ -116,12 +116,12 @@ def test_records_unknown_unknown_when_error_gathering_instance_data NewRelic::Agent::Instrumentation::ActiveRecordHelper::InstanceIdentification.stubs(:postgres_unix_domain_socket_case?).raises(StandardError.new) NewRelic::Agent::Instrumentation::ActiveRecordHelper::InstanceIdentification.stubs(:mysql_default_case?).raises(StandardError.new) - config = {:adapter => 'mysql', :host => "127.0.0.1"} + config = {:adapter => 'mysql', :host => '127.0.0.1'} @subscriber.stubs(:active_record_config).returns(config) in_transaction('test_txn') { simulate_query(2) } - assert_metrics_recorded("Datastore/instance/MySQL/unknown/unknown") + assert_metrics_recorded('Datastore/instance/MySQL/unknown/unknown') end def test_records_nothing_if_tracing_disabled diff --git a/test/new_relic/agent/instrumentation/rails/active_storage_subscriber.rb b/test/new_relic/agent/instrumentation/rails/active_storage_subscriber.rb index fee73202f2..2ff19397c2 100644 --- a/test/new_relic/agent/instrumentation/rails/active_storage_subscriber.rb +++ b/test/new_relic/agent/instrumentation/rails/active_storage_subscriber.rb @@ -22,13 +22,13 @@ def teardown def test_metrics_recorded_for_known_methods method_name_mapping = { - "service_upload.active_storage" => "upload".freeze, - "service_streaming_download.active_storage" => "streaming_download".freeze, - "service_download.active_storage" => "download".freeze, - "service_delete.active_storage" => "delete".freeze, - "service_delete_prefixed.active_storage" => "delete_prefixed".freeze, - "service_exist.active_storage" => "exist".freeze, - "service_url.active_storage" => "url".freeze + 'service_upload.active_storage' => 'upload'.freeze, + 'service_streaming_download.active_storage' => 'streaming_download'.freeze, + 'service_download.active_storage' => 'download'.freeze, + 'service_delete.active_storage' => 'delete'.freeze, + 'service_delete_prefixed.active_storage' => 'delete_prefixed'.freeze, + 'service_exist.active_storage' => 'exist'.freeze, + 'service_url.active_storage' => 'url'.freeze } in_transaction('test') do @@ -64,7 +64,7 @@ def test_key_recorded_as_attribute_on_traces end trace = last_transaction_trace - tt_node = find_node_with_name(trace, "Ruby/ActiveStorage/DiskService/upload") + tt_node = find_node_with_name(trace, 'Ruby/ActiveStorage/DiskService/upload') assert_equal 'mykey', tt_node.params[:key] end @@ -75,7 +75,7 @@ def test_exist_recorded_as_attribute_on_traces end trace = last_transaction_trace - tt_node = find_node_with_name(trace, "Ruby/ActiveStorage/DiskService/exist") + tt_node = find_node_with_name(trace, 'Ruby/ActiveStorage/DiskService/exist') assert tt_node.params.key?(:exist) refute tt_node.params[:exist] @@ -97,7 +97,7 @@ def test_segment_created def test_records_span_level_error exception_class = StandardError - exception_msg = "Natural 1" + exception_msg = 'Natural 1' exception = exception_class.new(msg = exception_msg) # :exception_object was added in Rails 5 and above params = {:exception_object => exception, :exception => [exception_class.name, exception_msg]} @@ -115,7 +115,7 @@ def test_records_span_level_error private def generate_event(event_name, attributes = {}) - defaults = {key: fake_guid(32), service: "Disk"} + defaults = {key: fake_guid(32), service: 'Disk'} payload = defaults.merge(attributes) @subscriber.start(event_name, @id, payload) yield if block_given? diff --git a/test/new_relic/agent/instrumentation/rails/active_support_subscriber.rb b/test/new_relic/agent/instrumentation/rails/active_support_subscriber.rb index 6ec574afe2..a38ee79eda 100644 --- a/test/new_relic/agent/instrumentation/rails/active_support_subscriber.rb +++ b/test/new_relic/agent/instrumentation/rails/active_support_subscriber.rb @@ -47,12 +47,12 @@ def test_finish_when_not_traced def test_metrics_recorded_for_known_methods method_name_mapping = { - "cache_read.active_support" => "read".freeze, - "cache_generate.active_support" => "generate".freeze, - "cache_fetch_hit.active_support" => "fetch_hit".freeze, - "cache_write.active_support" => "write".freeze, - "cache_delete.active_support" => "delete".freeze, - "cache_exist?.active_support" => "exist?".freeze + 'cache_read.active_support' => 'read'.freeze, + 'cache_generate.active_support' => 'generate'.freeze, + 'cache_fetch_hit.active_support' => 'fetch_hit'.freeze, + 'cache_write.active_support' => 'write'.freeze, + 'cache_delete.active_support' => 'delete'.freeze, + 'cache_exist?.active_support' => 'exist?'.freeze } in_transaction('test') do @@ -173,11 +173,11 @@ def test_an_actual_active_storage_cache_write assert_equal 2, txn.segments.size # the :store key is only in the payload for Rails 6.1+ - rails61 = Gem::Version.new(ActiveSupport::VERSION::STRING) >= Gem::Version.new("6.1.0") + rails61 = Gem::Version.new(ActiveSupport::VERSION::STRING) >= Gem::Version.new('6.1.0') segment_name = if rails61 "Ruby/ActiveSupport/#{store}/write" else - "Ruby/ActiveSupport/write" + 'Ruby/ActiveSupport/write' end assert_equal segment_name, segment.name diff --git a/test/new_relic/agent/instrumentation/rails/notifications_subscriber.rb b/test/new_relic/agent/instrumentation/rails/notifications_subscriber.rb index b623becb4a..d2a8c8618e 100644 --- a/test/new_relic/agent/instrumentation/rails/notifications_subscriber.rb +++ b/test/new_relic/agent/instrumentation/rails/notifications_subscriber.rb @@ -8,7 +8,7 @@ module NewRelic module Agent module Instrumentation class NotificationsSubscriberTest < Minitest::Test - DEFAULT_EVENT = "any.event" + DEFAULT_EVENT = 'any.event' def setup nr_freeze_process_time @@ -69,7 +69,7 @@ def test_segment_created_notsub name = "Ruby/#{DEFAULT_EVENT}" spans = harvest_span_events! - refute_empty(spans[1].select { |s| s[0]["name"] == name }) + refute_empty(spans[1].select { |s| s[0]['name'] == name }) end end end diff --git a/test/new_relic/agent/instrumentation/sequel_helper_test.rb b/test/new_relic/agent/instrumentation/sequel_helper_test.rb index e21d27577d..50a976eec7 100644 --- a/test/new_relic/agent/instrumentation/sequel_helper_test.rb +++ b/test/new_relic/agent/instrumentation/sequel_helper_test.rb @@ -9,26 +9,26 @@ module NewRelic module Agent class SequelHelperTest < Minitest::Test def test_product_name_from_adapter - expected_default = "Sequel" + expected_default = 'Sequel' default = Hash.new(expected_default) adapter_to_name = { - :ibmdb => "IBMDB2", - :firebird => "Firebird", - :informix => "Informix", - :jdbc => "JDBC", - :mysql => "MySQL", - :mysql2 => "MySQL", - :oracle => "Oracle", - :postgres => "Postgres", - :sqlite => "SQLite" + :ibmdb => 'IBMDB2', + :firebird => 'Firebird', + :informix => 'Informix', + :jdbc => 'JDBC', + :mysql => 'MySQL', + :mysql2 => 'MySQL', + :oracle => 'Oracle', + :postgres => 'Postgres', + :sqlite => 'SQLite' } default.merge(adapter_to_name).each do |adapter, name| assert_equal name, NewRelic::Agent::Instrumentation::SequelHelper.product_name_from_adapter(adapter) end - default_result = NewRelic::Agent::Instrumentation::SequelHelper.product_name_from_adapter("YouDontKnowThisAdapter") + default_result = NewRelic::Agent::Instrumentation::SequelHelper.product_name_from_adapter('YouDontKnowThisAdapter') assert_equal expected_default, default_result end diff --git a/test/new_relic/agent/instrumentation/sinatra/transaction_namer_test.rb b/test/new_relic/agent/instrumentation/sinatra/transaction_namer_test.rb index 755d846423..ad59c30a08 100644 --- a/test/new_relic/agent/instrumentation/sinatra/transaction_namer_test.rb +++ b/test/new_relic/agent/instrumentation/sinatra/transaction_namer_test.rb @@ -11,28 +11,28 @@ module Instrumentation module Sinatra class TransactionNamerTest < Minitest::Test def test_transaction_name_for_route - env = {"newrelic.last_route" => /^\/the_route$/} - request = stub(:request_method => "GET") + env = {'newrelic.last_route' => /^\/the_route$/} + request = stub(:request_method => 'GET') result = TransactionNamer.transaction_name_for_route(env, request) - assert_equal "GET the_route", result + assert_equal 'GET the_route', result end def test_transaction_name_for_route_padrino env = {} - route = stub(:original_path => "/path/:id") - request = stub(:route_obj => route, :request_method => "GET") + route = stub(:original_path => '/path/:id') + request = stub(:route_obj => route, :request_method => 'GET') result = TransactionNamer.transaction_name_for_route(env, request) - assert_equal "GET path/:id", result + assert_equal 'GET path/:id', result end def test_transaction_name_for_root_route - env = {"newrelic.last_route" => /\A\/\z/} - request = stub(:request_method => "GET") + env = {'newrelic.last_route' => /\A\/\z/} + request = stub(:request_method => 'GET') result = TransactionNamer.transaction_name_for_route(env, request) - assert_equal "GET /", result + assert_equal 'GET /', result end def test_transaction_name_for_route_without_routes @@ -40,15 +40,15 @@ def test_transaction_name_for_route_without_routes end def test_basic_sinatra_naming - assert_transaction_name "(unknown)", "(unknown)" + assert_transaction_name '(unknown)', '(unknown)' # Sinatra < 1.4 style regexes - assert_transaction_name "will_boom", "^/will_boom$" - assert_transaction_name "hello/([^/?#]+)", "^/hello/([^/?#]+)$" + assert_transaction_name 'will_boom', '^/will_boom$' + assert_transaction_name 'hello/([^/?#]+)', '^/hello/([^/?#]+)$' # Sinatra 1.4 style regexs - assert_transaction_name "will_boom", "\A/will_boom\z" - assert_transaction_name "hello/([^/?#]+)", "\A/hello/([^/?#]+)\z" + assert_transaction_name 'will_boom', "\A/will_boom\z" + assert_transaction_name 'hello/([^/?#]+)', "\A/hello/([^/?#]+)\z" end def assert_transaction_name(expected, original) diff --git a/test/new_relic/agent/instrumentation/sinatra_test.rb b/test/new_relic/agent/instrumentation/sinatra_test.rb index 12d08fb6b7..1250a8e898 100644 --- a/test/new_relic/agent/instrumentation/sinatra_test.rb +++ b/test/new_relic/agent/instrumentation/sinatra_test.rb @@ -33,7 +33,7 @@ def test_newrelic_request_headers end def test_process_route_with_bad_arguments - @app.stubs(:env).raises("Boo") + @app.stubs(:env).raises('Boo') yielded = false @app.process_route_with_tracing do yielded = true @@ -43,7 +43,7 @@ def test_process_route_with_bad_arguments end def test_route_eval_with_bad_params - @app.stubs(:env).raises("Boo") + @app.stubs(:env).raises('Boo') yielded = false @app.route_eval_with_tracing do yielded = true diff --git a/test/new_relic/agent/instrumentation/task_instrumentation_test.rb b/test/new_relic/agent/instrumentation/task_instrumentation_test.rb index c54de8b991..b97f2b9c82 100644 --- a/test/new_relic/agent/instrumentation/task_instrumentation_test.rb +++ b/test/new_relic/agent/instrumentation/task_instrumentation_test.rb @@ -20,11 +20,11 @@ def run_task_outer(n = 0) def run_task_exception NewRelic::Agent.add_custom_attributes(:custom_one => 'one custom val') - raise "This is an error" + raise 'This is an error' end def run_background_job - "This is a background job" + 'This is a background job' end add_transaction_tracer :run_task_exception @@ -178,12 +178,12 @@ def test_error_collector_captures_custom_params error = errors.first - assert_equal("Controller/NewRelic::Agent::Instrumentation::TaskInstrumentationTest/run_task_exception", error.path) + assert_equal('Controller/NewRelic::Agent::Instrumentation::TaskInstrumentationTest/run_task_exception', error.path) refute_nil(error.stack_trace) result = error.attributes.custom_attributes_for(NewRelic::Agent::AttributeFilter::DST_TRANSACTION_TRACER) - refute_nil(result["custom_one"]) + refute_nil(result['custom_one']) end def test_instrument_background_job diff --git a/test/new_relic/agent/javascript_instrumentor_test.rb b/test/new_relic/agent/javascript_instrumentor_test.rb index 67422941d0..f56d318e5d 100644 --- a/test/new_relic/agent/javascript_instrumentor_test.rb +++ b/test/new_relic/agent/javascript_instrumentor_test.rb @@ -3,8 +3,8 @@ # frozen_string_literal: true require_relative '../../test_helper' -require "new_relic/agent/javascript_instrumentor" -require "base64" +require 'new_relic/agent/javascript_instrumentor' +require 'base64' class NewRelic::Agent::JavaScriptInstrumentorTest < Minitest::Test attr_reader :instrumentor @@ -35,7 +35,7 @@ def teardown end def test_default_loader - assert_equal "rum", NewRelic::Agent.config[:'browser_monitoring.loader'] + assert_equal 'rum', NewRelic::Agent.config[:'browser_monitoring.loader'] end def test_auto_instrumentation_config_defaults_to_enabled @@ -43,13 +43,13 @@ def test_auto_instrumentation_config_defaults_to_enabled end def test_browser_timing_header_outside_transaction - assert_equal "", instrumentor.browser_timing_header + assert_equal '', instrumentor.browser_timing_header end def test_browser_timing_scripts_with_rum_enabled_false with_config(:'rum.enabled' => false) do in_transaction do - assert_equal "", instrumentor.browser_timing_header + assert_equal '', instrumentor.browser_timing_header end end end @@ -57,7 +57,7 @@ def test_browser_timing_scripts_with_rum_enabled_false def test_browser_timing_header_disable_all_tracing in_transaction do NewRelic::Agent.disable_all_tracing do - assert_equal "", instrumentor.browser_timing_header + assert_equal '', instrumentor.browser_timing_header end end end @@ -65,7 +65,7 @@ def test_browser_timing_header_disable_all_tracing def test_browser_timing_header_without_loader with_config(:js_agent_loader => '') do in_transaction do - assert_equal "", instrumentor.browser_timing_header + assert_equal '', instrumentor.browser_timing_header end end end @@ -73,7 +73,7 @@ def test_browser_timing_header_without_loader def test_browser_timing_header_without_beacon with_config(:beacon => '') do in_transaction do - assert_equal "", instrumentor.browser_timing_header + assert_equal '', instrumentor.browser_timing_header end end end @@ -81,7 +81,7 @@ def test_browser_timing_header_without_beacon def test_browser_timing_header_without_browser_key with_config(:browser_key => '') do in_transaction do - assert_equal "", instrumentor.browser_timing_header + assert_equal '', instrumentor.browser_timing_header end end end @@ -90,7 +90,7 @@ def test_browser_timing_header_with_ignored_enduser in_transaction do |txn| txn.ignore_enduser! - assert_equal "", instrumentor.browser_timing_header + assert_equal '', instrumentor.browser_timing_header end end @@ -106,7 +106,7 @@ def test_browser_timing_header_with_default_settings def test_browser_timing_header_with_nonce in_transaction do - header = instrumentor.browser_timing_header("NONCE_TEST") + header = instrumentor.browser_timing_header('NONCE_TEST') assert_has_js_agent_loader_with_nonce(header) assert_has_text(BEGINNING_OF_FOOTER_WITH_NONCE, header) @@ -117,9 +117,9 @@ def test_browser_timing_header_with_nonce def test_browser_timing_header_safe_when_insert_js_fails in_transaction do begin - NewRelic::Agent.stubs(:config).raises("Hahahaha") + NewRelic::Agent.stubs(:config).raises('Hahahaha') - assert_equal "", instrumentor.browser_timing_header + assert_equal '', instrumentor.browser_timing_header ensure # stopping the transaction touches config, so we need to ensure we # clean up after ourselves here. @@ -130,17 +130,17 @@ def test_browser_timing_header_safe_when_insert_js_fails def test_browser_timing_header_safe_when_loader_generation_fails in_transaction do - instrumentor.stubs(:html_safe_if_needed).raises("Hahahaha") + instrumentor.stubs(:html_safe_if_needed).raises('Hahahaha') - assert_equal "", instrumentor.browser_timing_header + assert_equal '', instrumentor.browser_timing_header end end def test_browser_timing_header_safe_when_json_dump_fails in_transaction do - ::JSON.stubs(:dump).raises("Serialize? Hahahaha") + ::JSON.stubs(:dump).raises('Serialize? Hahahaha') - assert_equal "", instrumentor.browser_timing_header + assert_equal '', instrumentor.browser_timing_header end end @@ -157,14 +157,14 @@ def test_config_data_for_js_agent data = instrumentor.data_for_js_agent(txn) expected = { - "beacon" => "beacon", - "errorBeacon" => "", - "licenseKey" => "browserKey", - "applicationID" => "5, 6", - "transactionName" => pack("most recent transaction"), - "queueTime" => 0, - "applicationTime" => 10000, - "agent" => "" + 'beacon' => 'beacon', + 'errorBeacon' => '', + 'licenseKey' => 'browserKey', + 'applicationID' => '5, 6', + 'transactionName' => pack('most recent transaction'), + 'queueTime' => 0, + 'applicationTime' => 10000, + 'agent' => '' } js = instrumentor.browser_timing_config(state) @@ -180,16 +180,16 @@ def test_config_data_for_js_agent_attributes nr_freeze_process_time with_config(ATTRIBUTES_ENABLED => true) do in_transaction('most recent transaction') do |txn| - NewRelic::Agent.add_custom_attributes(:user => "user") - NewRelic::Agent::Transaction.add_agent_attribute(:agent, "attribute", NewRelic::Agent::AttributeFilter::DST_ALL) + NewRelic::Agent.add_custom_attributes(:user => 'user') + NewRelic::Agent::Transaction.add_agent_attribute(:agent, 'attribute', NewRelic::Agent::AttributeFilter::DST_ALL) data = instrumentor.data_for_js_agent(txn) # Handle packed atts key specially since it's obfuscated - actual = unpack_to_object(data["atts"]) + actual = unpack_to_object(data['atts']) expected = { - "u" => {"user" => "user"}, - "a" => {"agent" => "attribute"} + 'u' => {'user' => 'user'}, + 'a' => {'agent' => 'attribute'} } assert_equal expected, actual @@ -201,7 +201,7 @@ def test_ssl_for_http_not_included_by_default in_transaction do |txn| data = instrumentor.data_for_js_agent(txn) - assert_not_includes data, "sslForHttp" + assert_not_includes data, 'sslForHttp' end end @@ -210,7 +210,7 @@ def test_ssl_for_http_enabled in_transaction do |txn| data = instrumentor.data_for_js_agent(txn) - assert data["sslForHttp"] + assert data['sslForHttp'] end end end @@ -220,7 +220,7 @@ def test_ssl_for_http_disabled in_transaction do |txn| data = instrumentor.data_for_js_agent(txn) - assert_false data["sslForHttp"] + assert_false data['sslForHttp'] end end end @@ -230,7 +230,7 @@ def test_ssl_for_http_disabled def test_data_for_js_agent_doesnt_get_custom_attributes_by_default with_config({}) do in_transaction do - NewRelic::Agent.add_custom_attributes({:boo => "hoo"}) + NewRelic::Agent.add_custom_attributes({:boo => 'hoo'}) assert_attributes_missing end @@ -239,7 +239,7 @@ def test_data_for_js_agent_doesnt_get_custom_attributes_by_default def test_data_for_js_agent_doesnt_get_custom_attributes_outside_transaction with_config(ATTRIBUTES_ENABLED => true) do - NewRelic::Agent.add_custom_attributes({:boo => "hoo"}) + NewRelic::Agent.add_custom_attributes({:boo => 'hoo'}) assert_attributes_missing end @@ -248,7 +248,7 @@ def test_data_for_js_agent_doesnt_get_custom_attributes_outside_transaction def test_data_for_js_agent_gets_custom_attributes_with_old_config with_config(ATTRIBUTES_ENABLED => true) do in_transaction do - NewRelic::Agent.add_custom_attributes({:boo => "hoo"}) + NewRelic::Agent.add_custom_attributes({:boo => 'hoo'}) assert_attributes_are('{"u":{"boo":"hoo"}}') end @@ -258,17 +258,51 @@ def test_data_for_js_agent_gets_custom_attributes_with_old_config def test_data_for_js_agent_gets_custom_attributes_when_configured with_config(ATTRIBUTES_ENABLED => true) do in_transaction do - NewRelic::Agent.add_custom_attributes({:boo => "hoo"}) + NewRelic::Agent.add_custom_attributes({:boo => 'hoo'}) assert_attributes_are('{"u":{"boo":"hoo"}}') end end end + def test_data_for_js_agent_produced_a_log_statement_for_custom_attributes + logger = Object.new + logger.instance_variable_set(:@seen, false) + def logger.debug(msg); @seen = true if msg.match?(/Appending the following.*\["pather_panchali"\]/); end + with_config(ATTRIBUTES_ENABLED => true) do + in_transaction do + NewRelic::Agent.stub :logger, logger do + NewRelic::Agent.add_custom_attributes(pather_panchali: :apu) + + assert_attributes_are('{"u":{"pather_panchali":"apu"}}') + end + end + + assert logger.instance_variable_get(:@seen), 'Expected log statement was not seen' + end + end + + def test_data_for_js_agent_produced_a_log_statement_for_empty_custom_attributes + logger = Object.new + logger.instance_variable_set(:@seen, false) + def logger.debug(msg); @seen = true if msg.include?('No custom attributes found'); end + with_config(ATTRIBUTES_ENABLED => false) do + in_transaction do + NewRelic::Agent.stub :logger, logger do + NewRelic::Agent.add_custom_attributes(pather_panchali: :subir) + + assert_attributes_missing + end + end + + assert logger.instance_variable_get(:@seen), 'Expected log statement was not seen' + end + end + def test_data_for_js_agent_ignores_custom_attributes_by_config with_config(ATTRIBUTES_ENABLED => false) do in_transaction do - NewRelic::Agent.add_custom_attributes({:boo => "hoo"}) + NewRelic::Agent.add_custom_attributes({:boo => 'hoo'}) assert_attributes_missing end @@ -322,7 +356,7 @@ def assert_attributes_are(expected) in_transaction do |txn| data = instrumentor.data_for_js_agent(txn) - assert_equal pack(expected), data["atts"] + assert_equal pack(expected), data['atts'] end end @@ -330,12 +364,12 @@ def assert_attributes_missing in_transaction do |txn| data = instrumentor.data_for_js_agent(txn) - assert_not_includes data, "atts" + assert_not_includes data, 'atts' end end def pack(text) - [text].pack("m0").delete("\n") + [text].pack('m0').delete("\n") end def unpack_to_object(text) @@ -348,7 +382,7 @@ def formatted_for_matching(value) when String %Q("#{value}") when NilClass - "null" + 'null' else value end diff --git a/test/new_relic/agent/linking_metadata_test.rb b/test/new_relic/agent/linking_metadata_test.rb index 83ba97c7ca..c142497c77 100644 --- a/test/new_relic/agent/linking_metadata_test.rb +++ b/test/new_relic/agent/linking_metadata_test.rb @@ -10,7 +10,7 @@ module LinkingMetadata class LinkingMetadataTest < Minitest::Test def setup @config = nil - Hostname.stubs(:get).returns("localhost") + Hostname.stubs(:get).returns('localhost') reset_buffers_and_caches end @@ -28,16 +28,16 @@ def test_service_metadata_requires_hash def test_service_metadata_without_guid apply_config({ - :app_name => ["Test app", "Another name"] + :app_name => ['Test app', 'Another name'] }) result = Hash.new LinkingMetadata.append_service_linking_metadata(result) expected = { - "entity.name" => "Test app", - "entity.type" => "SERVICE", - "hostname" => "localhost" + 'entity.name' => 'Test app', + 'entity.type' => 'SERVICE', + 'hostname' => 'localhost' } assert_equal(expected, result) @@ -45,18 +45,18 @@ def test_service_metadata_without_guid def test_service_metadata_with_guid apply_config({ - :app_name => ["Test app", "Another name"], - :entity_guid => "GUID" + :app_name => ['Test app', 'Another name'], + :entity_guid => 'GUID' }) result = Hash.new LinkingMetadata.append_service_linking_metadata(result) expected = { - "entity.guid" => "GUID", - "entity.name" => "Test app", - "entity.type" => "SERVICE", - "hostname" => "localhost" + 'entity.guid' => 'GUID', + 'entity.name' => 'Test app', + 'entity.type' => 'SERVICE', + 'hostname' => 'localhost' } assert_equal(expected, result) @@ -76,15 +76,15 @@ def test_trace_metadata_empty end def test_trace_metadata_with_ids - Tracer.stubs(:current_trace_id).returns("trace_id") - Tracer.stubs(:current_span_id).returns("span_id") + Tracer.stubs(:current_trace_id).returns('trace_id') + Tracer.stubs(:current_span_id).returns('span_id') result = Hash.new LinkingMetadata.append_trace_linking_metadata(result) expected = { - "trace.id" => "trace_id", - "span.id" => "span_id" + 'trace.id' => 'trace_id', + 'span.id' => 'span_id' } assert_equal(expected, result) diff --git a/test/new_relic/agent/local_log_decorator_test.rb b/test/new_relic/agent/local_log_decorator_test.rb index e33a22df5d..c0b44cdbfd 100644 --- a/test/new_relic/agent/local_log_decorator_test.rb +++ b/test/new_relic/agent/local_log_decorator_test.rb @@ -84,10 +84,10 @@ def test_decorate_puts_metadata_at_end_of_first_newline end def test_URI_encodes_entity_name - with_config(app_name: "My App | Production") do + with_config(app_name: 'My App | Production') do decorated_message = LocalLogDecorator.decorate(MESSAGE) - assert_includes decorated_message, "My%20App%20%7C%20Production" + assert_includes decorated_message, 'My%20App%20%7C%20Production' end end diff --git a/test/new_relic/agent/log_event_aggregator_test.rb b/test/new_relic/agent/log_event_aggregator_test.rb index b8ed14cfa9..ef19caed4d 100644 --- a/test/new_relic/agent/log_event_aggregator_test.rb +++ b/test/new_relic/agent/log_event_aggregator_test.rb @@ -40,7 +40,7 @@ def create_container def populate_container(container, n) n.times do |i| - container.record("A log message", ::Logger::Severity.constants.sample.to_s) + container.record('A log message', ::Logger::Severity.constants.sample.to_s) end end @@ -56,10 +56,10 @@ def test_records_enabled_metrics_on_startup NewRelic::Agent.config.notify_server_source_added assert_metrics_recorded_exclusive({ - "Supportability/Logging/Ruby/Logger/enabled" => {:call_count => 1}, - "Supportability/Logging/Metrics/Ruby/enabled" => {:call_count => 1}, - "Supportability/Logging/Forwarding/Ruby/enabled" => {:call_count => 1}, - "Supportability/Logging/LocalDecorating/Ruby/enabled" => {:call_count => 1} + 'Supportability/Logging/Ruby/Logger/enabled' => {:call_count => 1}, + 'Supportability/Logging/Metrics/Ruby/enabled' => {:call_count => 1}, + 'Supportability/Logging/Forwarding/Ruby/enabled' => {:call_count => 1}, + 'Supportability/Logging/LocalDecorating/Ruby/enabled' => {:call_count => 1} }, :ignore_filter => %r{^Supportability/API/}) end @@ -75,10 +75,10 @@ def test_records_disabled_metrics_on_startup NewRelic::Agent.config.notify_server_source_added assert_metrics_recorded_exclusive({ - "Supportability/Logging/Ruby/Logger/disabled" => {:call_count => 1}, - "Supportability/Logging/Metrics/Ruby/disabled" => {:call_count => 1}, - "Supportability/Logging/Forwarding/Ruby/disabled" => {:call_count => 1}, - "Supportability/Logging/LocalDecorating/Ruby/disabled" => {:call_count => 1} + 'Supportability/Logging/Ruby/Logger/disabled' => {:call_count => 1}, + 'Supportability/Logging/Metrics/Ruby/disabled' => {:call_count => 1}, + 'Supportability/Logging/Forwarding/Ruby/disabled' => {:call_count => 1}, + 'Supportability/Logging/LocalDecorating/Ruby/disabled' => {:call_count => 1} }, :ignore_filter => %r{^Supportability/API/}) end @@ -86,13 +86,13 @@ def test_records_disabled_metrics_on_startup def test_records_customer_metrics_when_enabled with_config(LogEventAggregator::METRICS_ENABLED_KEY => true) do - 2.times { @aggregator.record("Are you counting this?", "DEBUG") } + 2.times { @aggregator.record('Are you counting this?', 'DEBUG') } @aggregator.harvest! end assert_metrics_recorded({ - "Logging/lines" => {:call_count => 2}, - "Logging/lines/DEBUG" => {:call_count => 2} + 'Logging/lines' => {:call_count => 2}, + 'Logging/lines/DEBUG' => {:call_count => 2} }) end @@ -103,25 +103,25 @@ def test_doesnt_record_customer_metrics_when_overall_disabled_and_metrics_enable ) do NewRelic::Agent.config.notify_server_source_added - @aggregator.record("Are you counting this?", "DEBUG") + @aggregator.record('Are you counting this?', 'DEBUG') @aggregator.harvest! end assert_metrics_not_recorded([ - "Logging/lines", - "Logging/lines/DEBUG" + 'Logging/lines', + 'Logging/lines/DEBUG' ]) end def test_doesnt_record_customer_metrics_when_disabled with_config(LogEventAggregator::METRICS_ENABLED_KEY => false) do - @aggregator.record("Are you counting this?", "DEBUG") + @aggregator.record('Are you counting this?', 'DEBUG') @aggregator.harvest! end assert_metrics_not_recorded([ - "Logging/lines", - "Logging/lines/DEBUG" + 'Logging/lines', + 'Logging/lines/DEBUG' ]) end @@ -129,9 +129,9 @@ def test_logs_with_nil_severity_use_unknown @aggregator.record('Chocolate chips are great', nil) _, events = @aggregator.harvest! - assert_equal 'UNKNOWN', events[0][1]["level"] + assert_equal 'UNKNOWN', events[0][1]['level'] assert_metrics_recorded([ - "Logging/lines/UNKNOWN" + 'Logging/lines/UNKNOWN' ]) end @@ -139,9 +139,9 @@ def test_logs_with_empty_severity_use_unknown @aggregator.record('Chocolate chips are great', '') _, events = @aggregator.harvest! - assert_equal 'UNKNOWN', events[0][1]["level"] + assert_equal 'UNKNOWN', events[0][1]['level'] assert_metrics_recorded([ - "Logging/lines/UNKNOWN" + 'Logging/lines/UNKNOWN' ]) end @@ -152,14 +152,14 @@ def test_does_not_record_if_overall_disabled_and_forwarding_enabled ) do NewRelic::Agent.config.notify_server_source_added - @aggregator.record('Hello world!', "DEBUG") + @aggregator.record('Hello world!', 'DEBUG') _, events = @aggregator.harvest! assert_empty events assert_metrics_recorded({ - "Supportability/Logging/Ruby/Logger/disabled" => {:call_count => 1}, - "Supportability/Logging/Forwarding/Ruby/disabled" => {:call_count => 1} + 'Supportability/Logging/Ruby/Logger/disabled' => {:call_count => 1}, + 'Supportability/Logging/Forwarding/Ruby/disabled' => {:call_count => 1} }) end end @@ -169,7 +169,7 @@ def test_record_applies_limits with_config(CAPACITY_KEY => max_samples) do n = max_samples + 1 n.times do |i| - @aggregator.record("Take it to the limit", "FATAL") + @aggregator.record('Take it to the limit', 'FATAL') end metadata, results = @aggregator.harvest! @@ -186,7 +186,7 @@ def test_record_in_transaction n = max_samples + 1 n.times do |i| in_transaction do - @aggregator.record("Take it to the limit", "FATAL") + @aggregator.record('Take it to the limit', 'FATAL') end end @@ -203,12 +203,12 @@ def test_record_in_transaction_prioritizes_sampling with_config(CAPACITY_KEY => 1) do in_transaction do |txn| txn.sampled = false - @aggregator.record("Deadly", "FATAL") + @aggregator.record('Deadly', 'FATAL') end in_transaction do |txn| txn.sampled = true - @aggregator.record("Buggy", "DEBUG") + @aggregator.record('Buggy', 'DEBUG') end metadata, results = @aggregator.harvest! @@ -216,7 +216,7 @@ def test_record_in_transaction_prioritizes_sampling assert_equal(2, metadata[:events_seen]) assert_equal(1, metadata[:reservoir_size]) assert_equal(1, results.size) - assert_equal("Buggy", results.first.last["message"], "Favor sampled") + assert_equal('Buggy', results.first.last['message'], 'Favor sampled') end end @@ -225,12 +225,12 @@ def test_record_in_transaction_prioritizes with_config(CAPACITY_KEY => 1) do in_transaction do |txn| txn.priority = 0.5 - @aggregator.record("Deadly", "FATAL") + @aggregator.record('Deadly', 'FATAL') end in_transaction do |txn| txn.priority = 0.9 - @aggregator.record("Buggy", "DEBUG") + @aggregator.record('Buggy', 'DEBUG') end metadata, results = @aggregator.harvest! @@ -238,7 +238,7 @@ def test_record_in_transaction_prioritizes assert_equal(2, metadata[:events_seen]) assert_equal(1, metadata[:reservoir_size]) assert_equal(1, results.size) - assert_equal("Buggy", results.first.last["message"]) + assert_equal('Buggy', results.first.last['message']) end end @@ -246,17 +246,17 @@ def test_record_without_transaction_randomizes # There can be only one with_config(CAPACITY_KEY => 1) do LogPriority.stubs(:rand).returns(0.9) - @aggregator.record("Buggy", "DEBUG") + @aggregator.record('Buggy', 'DEBUG') LogPriority.stubs(:rand).returns(0.1) - @aggregator.record("Deadly", "FATAL") + @aggregator.record('Deadly', 'FATAL') metadata, results = @aggregator.harvest! assert_equal(2, metadata[:events_seen]) assert_equal(1, metadata[:reservoir_size]) assert_equal(1, results.size) - assert_equal("Buggy", results.first.last["message"]) + assert_equal('Buggy', results.first.last['message']) end end @@ -264,7 +264,7 @@ def test_lowering_limit_truncates_buffer original_count = 100 with_config(CAPACITY_KEY => original_count) do original_count.times do |i| - @aggregator.record("Truncation happens", "WARN") + @aggregator.record('Truncation happens', 'WARN') end end @@ -281,7 +281,7 @@ def test_lowering_limit_truncates_buffer def test_record_adds_timestamp t0 = Process.clock_gettime(Process::CLOCK_REALTIME) * 1000 message = "Time keeps slippin' away" - @aggregator.record(message, "INFO") + @aggregator.record(message, 'INFO') _, events = @aggregator.harvest! @@ -289,7 +289,7 @@ def test_record_adds_timestamp event = events.first assert_equal({ - 'level' => "INFO", + 'level' => 'INFO', 'message' => message, 'timestamp' => t0 }, @@ -298,15 +298,15 @@ def test_record_adds_timestamp def test_records_metrics_on_harvest with_config(CAPACITY_KEY => 5) do - 9.times { @aggregator.record("Are you counting this?", "DEBUG") } + 9.times { @aggregator.record('Are you counting this?', 'DEBUG') } @aggregator.harvest! assert_metrics_recorded_exclusive({ - "Logging/lines" => {:call_count => 9}, - "Logging/lines/DEBUG" => {:call_count => 9}, - "Logging/Forwarding/Dropped" => {:call_count => 4}, - "Supportability/Logging/Forwarding/Seen" => {:call_count => 9}, - "Supportability/Logging/Forwarding/Sent" => {:call_count => 5} + 'Logging/lines' => {:call_count => 9}, + 'Logging/lines/DEBUG' => {:call_count => 9}, + 'Logging/Forwarding/Dropped' => {:call_count => 4}, + 'Supportability/Logging/Forwarding/Seen' => {:call_count => 9}, + 'Supportability/Logging/Forwarding/Sent' => {:call_count => 5} }, :ignore_filter => %r{^Supportability/API/}) end @@ -317,7 +317,7 @@ def test_high_security_mode # We refresh the high security setting on this notification NewRelic::Agent.config.notify_server_source_added - 9.times { @aggregator.record("Are you counting this?", "DEBUG") } + 9.times { @aggregator.record('Are you counting this?', 'DEBUG') } _, items = @aggregator.harvest! # Never aggregate logs @@ -325,12 +325,12 @@ def test_high_security_mode # We are fine to count them, though.... assert_metrics_recorded_exclusive({ - "Logging/lines" => {:call_count => 9}, - "Logging/lines/DEBUG" => {:call_count => 9}, - "Supportability/Logging/Ruby/Logger/enabled" => {:call_count => 1}, - "Supportability/Logging/Metrics/Ruby/enabled" => {:call_count => 1}, - "Supportability/Logging/Forwarding/Ruby/enabled" => {:call_count => 1}, - "Supportability/Logging/LocalDecorating/Ruby/disabled" => {:call_count => 1} + 'Logging/lines' => {:call_count => 9}, + 'Logging/lines/DEBUG' => {:call_count => 9}, + 'Supportability/Logging/Ruby/Logger/enabled' => {:call_count => 1}, + 'Supportability/Logging/Metrics/Ruby/enabled' => {:call_count => 1}, + 'Supportability/Logging/Forwarding/Ruby/enabled' => {:call_count => 1}, + 'Supportability/Logging/LocalDecorating/Ruby/disabled' => {:call_count => 1} }, :ignore_filter => %r{^Supportability/API/}) end @@ -341,7 +341,7 @@ def test_overall_disabled # Refresh the value of @enabled on the LogEventAggregator NewRelic::Agent.config.notify_server_source_added - @aggregator.record('', "DEBUG") + @aggregator.record('', 'DEBUG') _, events = @aggregator.harvest! # Record no events @@ -349,10 +349,10 @@ def test_overall_disabled # All settings should report as disabled regardless of config option assert_metrics_recorded_exclusive({ - "Supportability/Logging/Ruby/Logger/disabled" => {:call_count => 1}, - "Supportability/Logging/Metrics/Ruby/disabled" => {:call_count => 1}, - "Supportability/Logging/Forwarding/Ruby/disabled" => {:call_count => 1}, - "Supportability/Logging/LocalDecorating/Ruby/disabled" => {:call_count => 1} + 'Supportability/Logging/Ruby/Logger/disabled' => {:call_count => 1}, + 'Supportability/Logging/Metrics/Ruby/disabled' => {:call_count => 1}, + 'Supportability/Logging/Forwarding/Ruby/disabled' => {:call_count => 1}, + 'Supportability/Logging/LocalDecorating/Ruby/disabled' => {:call_count => 1} }, :ignore_filter => %r{^Supportability/API/}) end @@ -367,17 +367,17 @@ def test_overall_disabled_in_high_security_mode # We refresh the high security setting on this notification NewRelic::Agent.config.notify_server_source_added - 9.times { @aggregator.record("Are you counting this?", "DEBUG") } + 9.times { @aggregator.record('Are you counting this?', 'DEBUG') } _, items = @aggregator.harvest! # Never aggregate logs assert_empty items assert_metrics_recorded_exclusive({ - "Supportability/Logging/Ruby/Logger/disabled" => {:call_count => 1}, - "Supportability/Logging/Metrics/Ruby/disabled" => {:call_count => 1}, - "Supportability/Logging/Forwarding/Ruby/disabled" => {:call_count => 1}, - "Supportability/Logging/LocalDecorating/Ruby/disabled" => {:call_count => 1} + 'Supportability/Logging/Ruby/Logger/disabled' => {:call_count => 1}, + 'Supportability/Logging/Metrics/Ruby/disabled' => {:call_count => 1}, + 'Supportability/Logging/Forwarding/Ruby/disabled' => {:call_count => 1}, + 'Supportability/Logging/LocalDecorating/Ruby/disabled' => {:call_count => 1} }, :ignore_filter => %r{^Supportability/API/}) end @@ -385,8 +385,8 @@ def test_overall_disabled_in_high_security_mode def test_basic_conversion_to_melt_format LinkingMetadata.stubs(:append_service_linking_metadata).returns({ - "entity.guid" => "GUID", - "entity.name" => "Hola" + 'entity.guid' => 'GUID', + 'entity.name' => 'Hola' }) log_data = [ @@ -395,14 +395,14 @@ def test_basic_conversion_to_melt_format reservoir_size: 0 }, [ - [{"priority": 1}, {"message": "This is a mess"}] + [{"priority": 1}, {"message": 'This is a mess'}] ] ] payload, size = LogEventAggregator.payload_to_melt_format(log_data) expected = [{ - common: {attributes: {"entity.guid" => "GUID", "entity.name" => "Hola"}}, - logs: [{"message": "This is a mess"}] + common: {attributes: {'entity.guid' => 'GUID', 'entity.name' => 'Hola'}}, + logs: [{"message": 'This is a mess'}] }] assert_equal 1, size @@ -410,36 +410,36 @@ def test_basic_conversion_to_melt_format end def test_create_event_truncates_message_when_exceeding_max_bytes - right_size_message = String.new("a" * LogEventAggregator::MAX_BYTES) + right_size_message = String.new('a' * LogEventAggregator::MAX_BYTES) message = right_size_message + 'b' event = @aggregator.create_event(1, message, 'INFO') - assert_equal(right_size_message, event[1]["message"]) + assert_equal(right_size_message, event[1]['message']) end def test_create_event_doesnt_truncate_message_when_at_max_bytes - message = String.new("a" * LogEventAggregator::MAX_BYTES) + message = String.new('a' * LogEventAggregator::MAX_BYTES) event = @aggregator.create_event(1, message, 'INFO') - assert_equal(message, event[1]["message"]) + assert_equal(message, event[1]['message']) end def test_create_event_doesnt_truncate_message_when_below_max_bytes - message = String.new("a" * (LogEventAggregator::MAX_BYTES - 1)) + message = String.new('a' * (LogEventAggregator::MAX_BYTES - 1)) event = @aggregator.create_event(1, message, 'INFO') - assert_equal(message, event[1]["message"]) + assert_equal(message, event[1]['message']) end def test_does_not_record_if_message_is_nil - @aggregator.record(nil, "DEBUG") + @aggregator.record(nil, 'DEBUG') _, events = @aggregator.harvest! assert_empty events end def test_does_not_record_if_message_empty_string - @aggregator.record('', "DEBUG") + @aggregator.record('', 'DEBUG') _, events = @aggregator.harvest! assert_empty events diff --git a/test/new_relic/agent/logging_test.rb b/test/new_relic/agent/logging_test.rb index 59e07e79a0..d5493889fa 100644 --- a/test/new_relic/agent/logging_test.rb +++ b/test/new_relic/agent/logging_test.rb @@ -71,14 +71,14 @@ def test_constructor_arguments_shift_age messages_to_escape = { 'quote' => 'message with a quote "', 'escaped_quote' => 'message with an escaped quote \"', - 'backslash' => "message with a backslash \ ", - 'forward_slash' => "message with a forward slash / ", + 'backslash' => "message with a backslash \ ", # rubocop:disable Style/RedundantStringEscape + 'forward_slash' => 'message with a forward slash / ', 'backspace' => 'message with a backspace \b ', 'form_feed' => "message with a form feed \f ", 'newline' => "message with a newline \n ", 'carriage_return' => "message with a carriage return \r", 'tab' => "message with a tab \t ", - 'unicode' => "message with a unicode snowman ☃ ", + 'unicode' => 'message with a unicode snowman ☃ ', 'unicode_hex' => "message with a unicode snowman \u2603 " } messages_to_escape.each do |name, message| @@ -103,7 +103,7 @@ def test_to_replace_non_utf_8_chars def test_to_replace_ascii_8bit_chars message = 'message with an ASCII-8BIT character' - char = String.new('č') + char = +'č' input = "#{message} #{char.force_encoding(Encoding::ASCII_8BIT)}" expectation = "#{message} #{DecoratingFormatter::REPLACEMENT_CHAR}#{DecoratingFormatter::REPLACEMENT_CHAR}" logger = DecoratingLogger.new(@output) diff --git a/test/new_relic/agent/memory_logger_test.rb b/test/new_relic/agent/memory_logger_test.rb index 8364a1c018..0f8978b543 100644 --- a/test/new_relic/agent/memory_logger_test.rb +++ b/test/new_relic/agent/memory_logger_test.rb @@ -23,11 +23,11 @@ def test_proxies_messages_to_real_logger_on_dump # work with old versions of Mocha. def real_logger.warn(*); end - real_logger.expects(:fatal).with("message at fatal") - real_logger.expects(:error).with("message at error") - real_logger.expects(:warn).with("message at warn") - real_logger.expects(:info).with("message at info") - real_logger.expects(:debug).with("message at debug") + real_logger.expects(:fatal).with('message at fatal') + real_logger.expects(:error).with('message at error') + real_logger.expects(:warn).with('message at warn') + real_logger.expects(:info).with('message at info') + real_logger.expects(:debug).with('message at debug') @logger.dump(real_logger) end @@ -67,8 +67,8 @@ def test_proxies_through_calls_to_log_exception end def test_log_once - @logger.log_once(:debug, :once, "Once") - @logger.log_once(:debug, :once, "Twice?") + @logger.log_once(:debug, :once, 'Once') + @logger.log_once(:debug, :once, 'Twice?') real_logger = stub real_logger.expects(:debug).once diff --git a/test/new_relic/agent/messaging_test.rb b/test/new_relic/agent/messaging_test.rb index 2275da2fe5..b53cab78d8 100644 --- a/test/new_relic/agent/messaging_test.rb +++ b/test/new_relic/agent/messaging_test.rb @@ -18,27 +18,27 @@ def teardown end def test_metrics_recorded_for_amqp_publish - in_transaction("test_txn") do + in_transaction('test_txn') do segment = NewRelic::Agent::Messaging.start_amqp_publish_segment( - library: "RabbitMQ", - destination_name: "Default", - headers: {foo: "bar"} + library: 'RabbitMQ', + destination_name: 'Default', + headers: {foo: 'bar'} ) segment.finish end assert_metrics_recorded [ - ["MessageBroker/RabbitMQ/Exchange/Produce/Named/Default", "test_txn"], - "MessageBroker/RabbitMQ/Exchange/Produce/Named/Default" + ['MessageBroker/RabbitMQ/Exchange/Produce/Named/Default', 'test_txn'], + 'MessageBroker/RabbitMQ/Exchange/Produce/Named/Default' ] end def test_metrics_recorded_for_amqp_consume - in_transaction("test_txn") do + in_transaction('test_txn') do segment = NewRelic::Agent::Messaging.start_amqp_consume_segment( - library: "RabbitMQ", - destination_name: "Default", - delivery_info: {routing_key: "foo", exchange_name: "bar"}, + library: 'RabbitMQ', + destination_name: 'Default', + delivery_info: {routing_key: 'foo', exchange_name: 'bar'}, message_properties: {headers: {}} ) @@ -46,98 +46,98 @@ def test_metrics_recorded_for_amqp_consume end assert_metrics_recorded [ - ["MessageBroker/RabbitMQ/Exchange/Consume/Named/Default", "test_txn"], - "MessageBroker/RabbitMQ/Exchange/Consume/Named/Default" + ['MessageBroker/RabbitMQ/Exchange/Consume/Named/Default', 'test_txn'], + 'MessageBroker/RabbitMQ/Exchange/Consume/Named/Default' ] end def test_segment_parameters_recorded_for_publish - in_transaction("test_txn") do - headers = {foo: "bar"} + in_transaction('test_txn') do + headers = {foo: 'bar'} segment = NewRelic::Agent::Messaging.start_amqp_publish_segment( - library: "RabbitMQ", - destination_name: "Default", + library: 'RabbitMQ', + destination_name: 'Default', headers: headers, - routing_key: "red", - reply_to: "blue", - correlation_id: "abc", - exchange_type: "direct" + routing_key: 'red', + reply_to: 'blue', + correlation_id: 'abc', + exchange_type: 'direct' ) - assert_equal "red", segment.params[:routing_key] + assert_equal 'red', segment.params[:routing_key] assert_equal headers, segment.params[:headers] - assert_equal "blue", segment.params[:reply_to] - assert_equal "abc", segment.params[:correlation_id] - assert_equal "direct", segment.params[:exchange_type] + assert_equal 'blue', segment.params[:reply_to] + assert_equal 'abc', segment.params[:correlation_id] + assert_equal 'direct', segment.params[:exchange_type] end end def test_segment_params_not_recorded_for_publish_with_segment_params_disabled with_config(:'message_tracer.segment_parameters.enabled' => false) do - in_transaction("test_txn") do - headers = {foo: "bar"} + in_transaction('test_txn') do + headers = {foo: 'bar'} segment = NewRelic::Agent::Messaging.start_amqp_publish_segment( - library: "RabbitMQ", - destination_name: "Default", + library: 'RabbitMQ', + destination_name: 'Default', headers: headers, - routing_key: "red", - reply_to: "blue", - correlation_id: "abc", - exchange_type: "direct" + routing_key: 'red', + reply_to: 'blue', + correlation_id: 'abc', + exchange_type: 'direct' ) - refute segment.params.has_key?(:routing_key), "Params should not have key :routing_key" - refute segment.params.has_key?(:headers), "Params should not have key :headers" - refute segment.params.has_key?(:reply_to), "Params should not have key :reply_to" - refute segment.params.has_key?(:correlation_id), "Params should not have key :correlation_id" - refute segment.params.has_key?(:exchange_type), "Params should not have key :exchange_type" + refute segment.params.has_key?(:routing_key), 'Params should not have key :routing_key' + refute segment.params.has_key?(:headers), 'Params should not have key :headers' + refute segment.params.has_key?(:reply_to), 'Params should not have key :reply_to' + refute segment.params.has_key?(:correlation_id), 'Params should not have key :correlation_id' + refute segment.params.has_key?(:exchange_type), 'Params should not have key :exchange_type' end end end def test_segment_parameters_recorded_for_consume - in_transaction("test_txn") do - message_properties = {headers: {foo: "bar"}, reply_to: "blue", correlation_id: "abc"} - delivery_info = {routing_key: "red", exchange_name: "foobar"} + in_transaction('test_txn') do + message_properties = {headers: {foo: 'bar'}, reply_to: 'blue', correlation_id: 'abc'} + delivery_info = {routing_key: 'red', exchange_name: 'foobar'} segment = NewRelic::Agent::Messaging.start_amqp_consume_segment( - library: "RabbitMQ", - destination_name: "Default", + library: 'RabbitMQ', + destination_name: 'Default', delivery_info: delivery_info, message_properties: message_properties, - queue_name: "yellow", - exchange_type: "direct" + queue_name: 'yellow', + exchange_type: 'direct' ) - assert_equal("red", segment.params[:routing_key]) - assert_equal({foo: "bar"}, segment.params[:headers]) - assert_equal("blue", segment.params[:reply_to]) - assert_equal("abc", segment.params[:correlation_id]) - assert_equal("direct", segment.params[:exchange_type]) - assert_equal("yellow", segment.params[:queue_name]) + assert_equal('red', segment.params[:routing_key]) + assert_equal({foo: 'bar'}, segment.params[:headers]) + assert_equal('blue', segment.params[:reply_to]) + assert_equal('abc', segment.params[:correlation_id]) + assert_equal('direct', segment.params[:exchange_type]) + assert_equal('yellow', segment.params[:queue_name]) end end def test_segment_params_not_recorded_for_consume_with_segment_params_disabled with_config(:'message_tracer.segment_parameters.enabled' => false) do - in_transaction("test_txn") do - message_properties = {headers: {foo: "bar"}, reply_to: "blue", correlation_id: "abc"} - delivery_info = {routing_key: "red", exchange_name: "foobar"} + in_transaction('test_txn') do + message_properties = {headers: {foo: 'bar'}, reply_to: 'blue', correlation_id: 'abc'} + delivery_info = {routing_key: 'red', exchange_name: 'foobar'} segment = NewRelic::Agent::Messaging.start_amqp_consume_segment( - library: "RabbitMQ", - destination_name: "Default", + library: 'RabbitMQ', + destination_name: 'Default', delivery_info: delivery_info, message_properties: message_properties, - queue_name: "yellow", - exchange_type: "direct" + queue_name: 'yellow', + exchange_type: 'direct' ) - refute segment.params.has_key?(:routing_key), "Params should not have key :routing_key" - refute segment.params.has_key?(:headers), "Params should not have key :headers" - refute segment.params.has_key?(:reply_to), "Params should not have key :reply_to" - refute segment.params.has_key?(:correlation_id), "Params should not have key :correlation_id" - refute segment.params.has_key?(:exchange_type), "Params should not have key :exchange_type" + refute segment.params.has_key?(:routing_key), 'Params should not have key :routing_key' + refute segment.params.has_key?(:headers), 'Params should not have key :headers' + refute segment.params.has_key?(:reply_to), 'Params should not have key :reply_to' + refute segment.params.has_key?(:correlation_id), 'Params should not have key :correlation_id' + refute segment.params.has_key?(:exchange_type), 'Params should not have key :exchange_type' end end end @@ -147,10 +147,10 @@ def test_wrap_message_broker_consume_transaction tap.expects(:tap) NewRelic::Agent::Messaging.wrap_message_broker_consume_transaction( - library: "AwesomeBunniez", + library: 'AwesomeBunniez', destination_type: :exchange, - destination_name: "Default", - routing_key: "red" + destination_name: 'Default', + routing_key: 'red' ) do txn = NewRelic::Agent::Tracer.current_transaction @@ -160,7 +160,7 @@ def test_wrap_message_broker_consume_transaction txn = last_transaction_trace - assert txn.finished, "Expected transaction to be finished" + assert txn.finished, 'Expected transaction to be finished' end def test_agent_attributes_assigned_for_generic_wrap_consume_transaction @@ -171,10 +171,10 @@ def test_agent_attributes_assigned_for_generic_wrap_consume_transaction tap.expects(:tap) NewRelic::Agent::Messaging.wrap_message_broker_consume_transaction( - library: "RabbitMQ", + library: 'RabbitMQ', destination_type: :exchange, - destination_name: "Default", - routing_key: "red" + destination_name: 'Default', + routing_key: 'red' ) { tap.tap } transaction_event = last_transaction_event @@ -185,49 +185,49 @@ def test_agent_attributes_assigned_for_generic_wrap_consume_transaction assert transaction_event.all? { |e| Hash === e }, "expected Array of 3 hashes, actual: [#{transaction_event.map(&:class).join(',')}]" # rubocop:enable Performance/RedundantEqualityComparisonBlock assert transaction_event[2].key?(:'message.routingKey'), "expected transaction event attributes to have key :'message.routingKey', actual: #{transaction_event[2].keys.join(',')}" - assert_equal "red", transaction_event[2][:'message.routingKey'] + assert_equal 'red', transaction_event[2][:'message.routingKey'] span_event = last_span_event assert span_event[2].key?(:'message.routingKey'), "expected span event attributes to have key :'message.routingKey', actual: #{span_event[2].keys.join(',')}" - assert_equal "red", span_event[2][:'message.routingKey'] + assert_equal 'red', span_event[2][:'message.routingKey'] end def test_header_attributes_assigned_for_generic_wrap_consume_transaction - with_config(:"attributes.include" => "message.headers.*") do + with_config(:"attributes.include" => 'message.headers.*') do tap = mock('tap') tap.expects(:tap) NewRelic::Agent::Messaging.wrap_message_broker_consume_transaction( - library: "RabbitMQ", + library: 'RabbitMQ', destination_type: :exchange, - destination_name: "Default", - routing_key: "red", - headers: {token: "foo"} + destination_name: 'Default', + routing_key: 'red', + headers: {token: 'foo'} ) { tap.tap } event = last_transaction_event - assert_equal "foo", event[2][:"message.headers.token"], "Expected header attributes to be added, actual attributes: #{event[2]}" + assert_equal 'foo', event[2][:"message.headers.token"], "Expected header attributes to be added, actual attributes: #{event[2]}" end end def test_cat_headers_removed_when_headers_assigned_as_attributes - with_config(:"attributes.include" => "message.headers.*") do + with_config(:"attributes.include" => 'message.headers.*') do tap = mock('tap') tap.expects(:tap) NewRelic::Agent::Messaging.wrap_message_broker_consume_transaction( - library: "RabbitMQ", + library: 'RabbitMQ', destination_type: :exchange, - destination_name: "Default", - routing_key: "red", - headers: {"token" => "foo", "NewRelicID" => "bar"} + destination_name: 'Default', + routing_key: 'red', + headers: {'token' => 'foo', 'NewRelicID' => 'bar'} ) { tap.tap } event = last_transaction_event - refute event[2].has_key?(:"message.headers.NewRelicID"), "Expected CAT headers to be omitted from message attributes" + refute event[2].has_key?(:"message.headers.NewRelicID"), 'Expected CAT headers to be omitted from message attributes' end end @@ -236,33 +236,33 @@ def test_header_attributes_not_assigned_when_headers_not_included_in_consume_tra tap.expects(:tap) NewRelic::Agent::Messaging.wrap_message_broker_consume_transaction( - library: "RabbitMQ", + library: 'RabbitMQ', destination_type: :exchange, - destination_name: "Default", - routing_key: "red", - headers: {token: "foo"} + destination_name: 'Default', + routing_key: 'red', + headers: {token: 'foo'} ) { tap.tap } event = last_transaction_event - refute event[2].has_key?(:"message.headers.token"), "Expected header attributes not to be added" + refute event[2].has_key?(:"message.headers.token"), 'Expected header attributes not to be added' end def test_agent_attributes_not_assigned_when_in_transaction_but_not_subscribed NewRelic::Agent::Transaction.any_instance.stubs(:sampled?).returns(true) NewRelic::Agent.instance.span_event_aggregator.stubs(:enabled?).returns(true) - in_transaction("test_txn") do - message_properties = {headers: {foo: "bar"}, reply_to: "blue", correlation_id: "abc"} - delivery_info = {routing_key: "red", exchange_name: "foobar"} + in_transaction('test_txn') do + message_properties = {headers: {foo: 'bar'}, reply_to: 'blue', correlation_id: 'abc'} + delivery_info = {routing_key: 'red', exchange_name: 'foobar'} segment = NewRelic::Agent::Messaging.start_amqp_consume_segment( - library: "RabbitMQ", - destination_name: "Default", + library: 'RabbitMQ', + destination_name: 'Default', delivery_info: delivery_info, message_properties: message_properties, - queue_name: "yellow", - exchange_type: "direct" + queue_name: 'yellow', + exchange_type: 'direct' ) segment.finish @@ -278,16 +278,16 @@ def test_agent_attributes_not_assigned_when_in_transaction_but_not_subscribed end def test_agent_attributes_not_assigned_when_not_subscribed_nor_in_transaction - message_properties = {headers: {foo: "bar"}, reply_to: "blue", correlation_id: "abc"} - delivery_info = {routing_key: "red", exchange_name: "foobar"} + message_properties = {headers: {foo: 'bar'}, reply_to: 'blue', correlation_id: 'abc'} + delivery_info = {routing_key: 'red', exchange_name: 'foobar'} segment = NewRelic::Agent::Messaging.start_amqp_consume_segment( - library: "RabbitMQ", - destination_name: "Default", + library: 'RabbitMQ', + destination_name: 'Default', delivery_info: delivery_info, message_properties: message_properties, - queue_name: "yellow", - exchange_type: "direct" + queue_name: 'yellow', + exchange_type: 'direct' ) refute segment.transaction, "expected nil segment.transaction, actual: #{segment.transaction}" @@ -295,16 +295,16 @@ def test_agent_attributes_not_assigned_when_not_subscribed_nor_in_transaction end def test_consume_api_passes_message_properties_headers_to_underlying_api - message_properties = {headers: {foo: "bar"}, reply_to: "blue", correlation_id: "abc"} - delivery_info = {routing_key: "red", exchange_name: "foobar"} + message_properties = {headers: {foo: 'bar'}, reply_to: 'blue', correlation_id: 'abc'} + delivery_info = {routing_key: 'red', exchange_name: 'foobar'} segment = NewRelic::Agent::Messaging.start_amqp_consume_segment( - library: "RabbitMQ", - destination_name: "Default", + library: 'RabbitMQ', + destination_name: 'Default', delivery_info: delivery_info, message_properties: message_properties, - queue_name: "yellow", - exchange_type: "direct" + queue_name: 'yellow', + exchange_type: 'direct' ) assert NewRelic::Agent::Transaction::MessageBrokerSegment === segment @@ -314,137 +314,137 @@ def test_consume_api_passes_message_properties_headers_to_underlying_api def test_start_message_broker_segments_returns_properly_constructed_segment segment = NewRelic::Agent::Tracer.start_message_broker_segment( action: :produce, - library: "RabbitMQ", + library: 'RabbitMQ', destination_type: :exchange, - destination_name: "QQ" + destination_name: 'QQ' ) assert NewRelic::Agent::Transaction::MessageBrokerSegment === segment - assert_equal "MessageBroker/RabbitMQ/Exchange/Produce/Named/QQ", segment.name + assert_equal 'MessageBroker/RabbitMQ/Exchange/Produce/Named/QQ', segment.name assert_equal :produce, segment.action - assert_equal "RabbitMQ", segment.library + assert_equal 'RabbitMQ', segment.library assert_equal :exchange, segment.destination_type - assert_equal "QQ", segment.destination_name + assert_equal 'QQ', segment.destination_name end def test_headers_not_attached_to_segment_if_empty_on_produce segment = NewRelic::Agent::Messaging.start_amqp_publish_segment( - library: "RabbitMQ", - destination_name: "Default", + library: 'RabbitMQ', + destination_name: 'Default', headers: {} ) - refute segment.params[:headers], "expected no :headers key in segment params" + refute segment.params[:headers], 'expected no :headers key in segment params' end def test_headers_not_attached_to_segment_if_empty_on_consume segment = NewRelic::Agent::Messaging.start_amqp_consume_segment( - library: "RabbitMQ", - destination_name: "Default", - delivery_info: {routing_key: "foo", exchange_name: "bar"}, + library: 'RabbitMQ', + destination_name: 'Default', + delivery_info: {routing_key: 'foo', exchange_name: 'bar'}, message_properties: {headers: {}} ) - refute segment.params[:headers], "expected no :headers key in segment params" + refute segment.params[:headers], 'expected no :headers key in segment params' end def test_consume_segments_filter_out_CAT_headers_from_parameters segment = NewRelic::Agent::Messaging.start_amqp_consume_segment( - library: "RabbitMQ", - destination_name: "Default", - delivery_info: {routing_key: "foo", exchange_name: "bar"}, + library: 'RabbitMQ', + destination_name: 'Default', + delivery_info: {routing_key: 'foo', exchange_name: 'bar'}, message_properties: {headers: {'hi' => 'there', 'NewRelicID' => '123#456', 'NewRelicTransaction' => 'abcdef'}} ) refute segment.params[:headers].key?('NewRelicID'), "expected segment params to not have CAT header 'NewRelicID'" refute segment.params[:headers].key?('NewRelicTransaction'), "expected segment params to not have CAT header 'NewRelicTransaction'" - assert segment.params[:headers].key?('hi'), "expected segment params to have application defined headers" + assert segment.params[:headers].key?('hi'), 'expected segment params to have application defined headers' assert_equal 'there', segment.params[:headers]['hi'] end def test_consume_segments_filter_out_synthetics_headers_from_parameters segment = NewRelic::Agent::Messaging.start_amqp_consume_segment( - library: "RabbitMQ", - destination_name: "Default", - delivery_info: {routing_key: "foo", exchange_name: "bar"}, + library: 'RabbitMQ', + destination_name: 'Default', + delivery_info: {routing_key: 'foo', exchange_name: 'bar'}, message_properties: {headers: {'hi' => 'there', 'NewRelicSynthetics' => 'abcdef12345'}} ) - refute segment.params[:headers].key?('NewRelicSynthetics'), "expected segment params to not have Synthetics header" - assert segment.params[:headers].key?('hi'), "expected segment params to have application defined headers" + refute segment.params[:headers].key?('NewRelicSynthetics'), 'expected segment params to not have Synthetics header' + assert segment.params[:headers].key?('hi'), 'expected segment params to have application defined headers' assert_equal 'there', segment.params[:headers]['hi'] end def test_consume_segments_do_not_attach_empty_after_filtering_headers segment = NewRelic::Agent::Messaging.start_amqp_consume_segment( - library: "RabbitMQ", - destination_name: "Default", - delivery_info: {routing_key: "foo", exchange_name: "bar"}, + library: 'RabbitMQ', + destination_name: 'Default', + delivery_info: {routing_key: 'foo', exchange_name: 'bar'}, message_properties: {headers: {'NewRelicID' => '123#456', 'NewRelicTransaction' => 'abcdef', 'NewRelicSynthetics' => 'qwerasdfzxcv'}} ) - refute segment.params[:headers], "expected no :headers key in segment params" + refute segment.params[:headers], 'expected no :headers key in segment params' end def test_agent_attributes_assigned_for_amqp_wrap_consume_transaction NewRelic::Agent::Transaction.any_instance.stubs(:sampled?).returns(true) NewRelic::Agent.instance.span_event_aggregator.stubs(:enabled?).returns(true) - with_config(:"attributes.include" => ["message.headers.*", "message.replyTo", "message.correlationId", "message.exchangeType"]) do + with_config(:"attributes.include" => ['message.headers.*', 'message.replyTo', 'message.correlationId', 'message.exchangeType']) do tap = mock('tap') tap.expects(:tap) NewRelic::Agent::Messaging.wrap_amqp_consume_transaction( - library: "AwesomeBunniez", - destination_name: "MyExchange", + library: 'AwesomeBunniez', + destination_name: 'MyExchange', delivery_info: {routing_key: 'blue'}, - message_properties: {reply_to: 'reply.key', correlation_id: 'correlate', headers: {"foo" => "bar", "NewRelicID" => "baz"}}, + message_properties: {reply_to: 'reply.key', correlation_id: 'correlate', headers: {'foo' => 'bar', 'NewRelicID' => 'baz'}}, exchange_type: :fanout, queue_name: 'some.queue' ) { tap.tap } transaction_event = last_transaction_event - assert_equal "blue", transaction_event[2][:'message.routingKey'] - assert_equal "reply.key", transaction_event[2][:'message.replyTo'] - assert_equal "correlate", transaction_event[2][:'message.correlationId'] + assert_equal 'blue', transaction_event[2][:'message.routingKey'] + assert_equal 'reply.key', transaction_event[2][:'message.replyTo'] + assert_equal 'correlate', transaction_event[2][:'message.correlationId'] assert_equal :fanout, transaction_event[2][:'message.exchangeType'] - assert_equal "some.queue", transaction_event[2][:'message.queueName'] - assert_equal "bar", transaction_event[2][:'message.headers.foo'] + assert_equal 'some.queue', transaction_event[2][:'message.queueName'] + assert_equal 'bar', transaction_event[2][:'message.headers.foo'] refute transaction_event[2].has_key?(:'message.headers.NewRelicID') span_event = last_span_event - assert_equal "blue", span_event[2][:'message.routingKey'] - assert_equal "reply.key", span_event[2][:'message.replyTo'] - assert_equal "correlate", span_event[2][:'message.correlationId'] + assert_equal 'blue', span_event[2][:'message.routingKey'] + assert_equal 'reply.key', span_event[2][:'message.replyTo'] + assert_equal 'correlate', span_event[2][:'message.correlationId'] assert_equal :fanout, span_event[2][:'message.exchangeType'] - assert_equal "some.queue", span_event[2][:'message.queueName'] - assert_equal "bar", span_event[2][:'message.headers.foo'] + assert_equal 'some.queue', span_event[2][:'message.queueName'] + assert_equal 'bar', span_event[2][:'message.headers.foo'] refute span_event[2].has_key?(:'message.headers.NewRelicID') end end def test_segment_records_proper_metrics_for_consume - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| segment = NewRelic::Agent::Messaging.start_message_broker_segment( action: :consume, - library: "RabbitMQ", + library: 'RabbitMQ', destination_type: :exchange, - destination_name: "Default" + destination_name: 'Default' ) segment.finish end assert_metrics_recorded [ - ["MessageBroker/RabbitMQ/Exchange/Consume/Named/Default", "test_txn"], - "MessageBroker/RabbitMQ/Exchange/Consume/Named/Default" + ['MessageBroker/RabbitMQ/Exchange/Consume/Named/Default', 'test_txn'], + 'MessageBroker/RabbitMQ/Exchange/Consume/Named/Default' ] end def test_wrap_message_broker_consume_transaction_reads_cat_headers - guid = "BEC1BC64675138B9" - cross_process_id = "321#123" + guid = 'BEC1BC64675138B9' + cross_process_id = '321#123' intrinsic_attributes = {client_cross_process_id: cross_process_id, referring_transaction_guid: guid} obfuscated_id = nil raw_txn_info = nil @@ -457,7 +457,7 @@ def test_wrap_message_broker_consume_transaction_reads_cat_headers :cross_process_id => cross_process_id, :'distributed_tracing.enabled' => false, :trusted_account_ids => [321], - :encoding_key => "abc") do + :encoding_key => 'abc') do in_transaction do |txn| obfuscated_id = obfuscator.obfuscate(cross_process_id) raw_txn_info = [guid, false, guid, txn.distributed_tracer.cat_path_hash] @@ -465,10 +465,10 @@ def test_wrap_message_broker_consume_transaction_reads_cat_headers end NewRelic::Agent::Messaging.wrap_message_broker_consume_transaction( - library: "RabbitMQ", + library: 'RabbitMQ', destination_type: :exchange, destination_name: 'Default', - headers: {"NewRelicID" => obfuscated_id, "NewRelicTransaction" => obfuscated_txn_info} + headers: {'NewRelicID' => obfuscated_id, 'NewRelicTransaction' => obfuscated_txn_info} ) do txn = NewRelic::Agent::Tracer.current_transaction payload = txn.distributed_tracer.cross_app_payload @@ -484,8 +484,8 @@ def test_wrap_message_broker_consume_transaction_reads_cat_headers end def test_wrap_message_broker_consume_transaction_records_proper_metrics_with_cat - guid = "BEC1BC64675138B9" - cross_process_id = "321#123" + guid = 'BEC1BC64675138B9' + cross_process_id = '321#123' obfuscated_id = nil raw_txn_info = nil obfuscated_txn_info = nil @@ -497,18 +497,18 @@ def test_wrap_message_broker_consume_transaction_records_proper_metrics_with_cat :cross_process_id => cross_process_id, :'distributed_tracing.enabled' => false, :trusted_account_ids => [321], - :encoding_key => "abc") do - in_transaction("test_txn") do |txn| + :encoding_key => 'abc') do + in_transaction('test_txn') do |txn| obfuscated_id = obfuscator.obfuscate(cross_process_id) raw_txn_info = [guid, false, guid, txn.distributed_tracer.cat_path_hash] obfuscated_txn_info = obfuscator.obfuscate(raw_txn_info.to_json) end Messaging.wrap_message_broker_consume_transaction( - library: "RabbitMQ", + library: 'RabbitMQ', destination_type: :exchange, - destination_name: "Default", - headers: {"NewRelicID" => obfuscated_id, "NewRelicTransaction" => obfuscated_txn_info} + destination_name: 'Default', + headers: {'NewRelicID' => obfuscated_id, 'NewRelicTransaction' => obfuscated_txn_info} ) do tap.tap end diff --git a/test/new_relic/agent/method_interrobang_test.rb b/test/new_relic/agent/method_interrobang_test.rb index 17c5376b05..d690058e57 100644 --- a/test/new_relic/agent/method_interrobang_test.rb +++ b/test/new_relic/agent/method_interrobang_test.rb @@ -9,11 +9,11 @@ class MethodInterrobangTest < Minitest::Test include NewRelic::Agent::MethodTracer def interrogate? - "say what?" + 'say what?' end def mutate! - "oh yeah!" + 'oh yeah!' end add_method_tracer :interrogate? @@ -21,11 +21,11 @@ def mutate! def test_alias_method_ending_in_question_mark assert_respond_to self, :interrogate? - assert_equal "say what?", interrogate? + assert_equal 'say what?', interrogate? end def test_alias_method_ending_in_exclamation_mark assert_respond_to self, :mutate! - assert_equal "oh yeah!", mutate! + assert_equal 'oh yeah!', mutate! end end diff --git a/test/new_relic/agent/method_tracer_helpers_test.rb b/test/new_relic/agent/method_tracer_helpers_test.rb index f0b8e73052..b3179f46eb 100644 --- a/test/new_relic/agent/method_tracer_helpers_test.rb +++ b/test/new_relic/agent/method_tracer_helpers_test.rb @@ -91,7 +91,7 @@ def test_provides_accurate_info_for_an_instance_method end end - def test_provides_accurate_info_for_an_instance_method + def test_provides_accurate_info_for_a_private_instance_method with_config(:'code_level_metrics.enabled' => true) do info = NewRelic::Agent::MethodTracerHelpers.code_information(::The::Example, :private_method) diff --git a/test/new_relic/agent/method_tracer_params_test.rb b/test/new_relic/agent/method_tracer_params_test.rb index b417558b6c..5311c49e30 100644 --- a/test/new_relic/agent/method_tracer_params_test.rb +++ b/test/new_relic/agent/method_tracer_params_test.rb @@ -5,8 +5,8 @@ require_relative '../../test_helper' class NewRelic::Agent::MethodTracerParamsTest < Minitest::Test - METRIC = "metric" - KEYWORD_DEPRECATED_WARNING = "Using the last argument as keyword parameters is deprecated" + METRIC = 'metric' + KEYWORD_DEPRECATED_WARNING = 'Using the last argument as keyword parameters is deprecated' def setup NewRelic::Agent::Tracer.clear_state @@ -29,11 +29,11 @@ def teardown class UntracedMethods def expect_deprecation_warnings? - RUBY_VERSION >= "2.7.0" && RUBY_VERSION < "3.0.0" + RUBY_VERSION >= '2.7.0' && RUBY_VERSION < '3.0.0' end def no_args - {foo: {bar: "foobar"}} + {foo: {bar: 'foobar'}} end def last_arg_expects_a_hash(foo, bar = {}) @@ -127,50 +127,50 @@ def assert_common_tracing_behavior(traced_class) call_expecting_warning_after_ruby_26(traced_class) end - [["untraced_methods", UntracedMethods], - ["traced_methods", TracedMethods], - ["traced_metric_methods", TracedMetricMethods], - ["traced_metric_methods_unscoped", TracedMetricMethodsUnscoped]].each do |traced_class_name, traced_class| + [['untraced_methods', UntracedMethods], + ['traced_methods', TracedMethods], + ['traced_metric_methods', TracedMetricMethods], + ['traced_metric_methods_unscoped', TracedMetricMethodsUnscoped]].each do |traced_class_name, traced_class| # We're doing it all in one big super test because order of invocation matters! # When many small test scenarios, if the tests for deprecation warnings emitted # by the compiler are not invoked first, then we miss our chance to capture # that output and assert/refute reliably. # This very large run ensures order of calls always happen in predictable order. define_method "test_expected_results_#{traced_class_name}" do - expected = {foo: {bar: "foobar"}} + expected = {foo: {bar: 'foobar'}} expected369 = {1 => 3, 2 => 6, 3 => 9} instance = traced_class.new # Test deprecation warnings first! refute_deprecation_warning { instance.no_args } - refute_deprecation_warning { instance.last_arg_expects_a_hash(:foo, {bar: "foobar"}) } - refute_deprecation_warning { instance.last_arg_expects_a_hash(:foo, bar: "foobar") } + refute_deprecation_warning { instance.last_arg_expects_a_hash(:foo, {bar: 'foobar'}) } + refute_deprecation_warning { instance.last_arg_expects_a_hash(:foo, bar: 'foobar') } - refute_deprecation_warning { instance.wildcard_args(:foo, bar: "foobar") } - refute_deprecation_warning { instance.wildcard_args(:foo, {bar: "foobar"}) } + refute_deprecation_warning { instance.wildcard_args(:foo, bar: 'foobar') } + refute_deprecation_warning { instance.wildcard_args(:foo, {bar: 'foobar'}) } - refute_deprecation_warning { instance.last_arg_is_a_keyword(:foo, bar: "foobar") } - refute_deprecation_warning { instance.all_args_are_keywords(foo: :foo, bar: {bar: "foobar"}) } - refute_deprecation_warning { instance.args_and_kwargs(:foo, bar: "foobar") } - if RUBY_VERSION < "2.7.0" - refute_deprecation_warning { instance.last_arg_is_a_keyword(:foo, {bar: "foobar"}) } - refute_deprecation_warning { instance.args_and_kwargs(:foo, {bar: "foobar"}) } + refute_deprecation_warning { instance.last_arg_is_a_keyword(:foo, bar: 'foobar') } + refute_deprecation_warning { instance.all_args_are_keywords(foo: :foo, bar: {bar: 'foobar'}) } + refute_deprecation_warning { instance.args_and_kwargs(:foo, bar: 'foobar') } + if RUBY_VERSION < '2.7.0' + refute_deprecation_warning { instance.last_arg_is_a_keyword(:foo, {bar: 'foobar'}) } + refute_deprecation_warning { instance.args_and_kwargs(:foo, {bar: 'foobar'}) } end # ensure behavior doesn't change by tracing methods! assert_equal expected, instance.no_args - assert_equal expected, instance.last_arg_expects_a_hash(:foo, {bar: "foobar"}) - assert_equal expected, instance.last_arg_expects_a_hash(:foo, bar: "foobar") - assert_equal expected, instance.wildcard_args(:foo, {bar: "foobar"}) - assert_equal expected, instance.wildcard_args(:foo, bar: "foobar") - assert_equal expected, instance.args_and_kwargs(:foo, bar: "foobar") + assert_equal expected, instance.last_arg_expects_a_hash(:foo, {bar: 'foobar'}) + assert_equal expected, instance.last_arg_expects_a_hash(:foo, bar: 'foobar') + assert_equal expected, instance.wildcard_args(:foo, {bar: 'foobar'}) + assert_equal expected, instance.wildcard_args(:foo, bar: 'foobar') + assert_equal expected, instance.args_and_kwargs(:foo, bar: 'foobar') assert_equal expected369, instance.modifies_hash # This is what changes in 3.0! - version_specific_expected = RUBY_VERSION >= "3.0.0" ? {foo: {}} : expected + version_specific_expected = RUBY_VERSION >= '3.0.0' ? {foo: {}} : expected - silence_expected_warnings { assert_equal version_specific_expected, instance.args_and_kwargs(:foo, {bar: "foobar"}) } + silence_expected_warnings { assert_equal version_specific_expected, instance.args_and_kwargs(:foo, {bar: 'foobar'}) } end end end diff --git a/test/new_relic/agent/method_tracer_test.rb b/test/new_relic/agent/method_tracer_test.rb index 4ea19ace49..cc58a7d3c4 100644 --- a/test/new_relic/agent/method_tracer_test.rb +++ b/test/new_relic/agent/method_tracer_test.rb @@ -18,7 +18,7 @@ def thrower(level) # don't use a real sampler because we can't instantiate one # NewRelic::Agent::TransactionSampler.new(NewRelic::Agent.instance) begin - fail "This should not have worked." + fail 'This should not have worked.' rescue end else @@ -40,7 +40,7 @@ module TestModuleWithLog class << self def other_method # just here to be traced - log("12345") + log('12345') end def log(msg) @@ -78,7 +78,7 @@ class MyProxyClass < BasicObject include ::NewRelic::Agent::MethodTracer def hello - "hello" + 'hello' end add_method_tracer :hello, 'Custom/proxy/hello' @@ -115,7 +115,7 @@ def test_preserve_logging end def test_trace_execution_scoped_records_metric_data - metric = "hello" + metric = 'hello' in_transaction do self.class.trace_execution_scoped(metric) do @@ -144,7 +144,7 @@ def test_trace_execution_scoped_pushes_transaction_scope assert_metrics_recorded 'yeap' => {:call_count => 1} end - METRIC = "metric" + METRIC = 'metric' def test_add_method_tracer @metric_name = METRIC @@ -179,7 +179,7 @@ def test_add_class_method_tracer MyClass.class_method end - metric = "Custom/MyClass/Class/class_method" + metric = 'Custom/MyClass/Class/class_method' assert_metrics_recorded metric => {:call_count => 1} end @@ -202,7 +202,7 @@ def test_add_module_method_tracer MyModule.module_method end - metric = "Custom/MyModule/Class/module_method" + metric = 'Custom/MyModule/Class/module_method' assert_metrics_recorded metric => {:call_count => 1} end @@ -237,7 +237,7 @@ def test_add_anonymous_class_method_tracer cls.new.instance_method end - metric = "Custom/AnonymousClass/instance_method" + metric = 'Custom/AnonymousClass/instance_method' assert_metrics_recorded metric => {:call_count => 1} end @@ -297,9 +297,9 @@ def test_method_traced? end def test_tt_only - self.class.add_method_tracer(:method_c1, "c1", :push_scope => true) - self.class.add_method_tracer(:method_c2, "c2", :metric => false) - self.class.add_method_tracer(:method_c3, "c3", :push_scope => false) + self.class.add_method_tracer(:method_c1, 'c1', :push_scope => true) + self.class.add_method_tracer(:method_c2, 'c2', :metric => false) + self.class.add_method_tracer(:method_c3, 'c3', :push_scope => false) in_transaction do method_c1 @@ -310,8 +310,8 @@ def test_tt_only end def test_nested_scope_tracer - Insider.add_method_tracer(:catcher, "catcher", :push_scope => true) - Insider.add_method_tracer(:thrower, "thrower", :push_scope => true) + Insider.add_method_tracer(:catcher, 'catcher', :push_scope => true) + Insider.add_method_tracer(:thrower, 'thrower', :push_scope => true) mock = Insider.new(@stats_engine) @@ -321,8 +321,8 @@ def test_nested_scope_tracer end assert_metrics_recorded({ - "catcher" => {:call_count => 2}, - "thrower" => {:call_count => 6} + 'catcher' => {:call_count => 2}, + 'thrower' => {:call_count => 6} }) sample = last_transaction_trace @@ -351,7 +351,7 @@ def test_add_same_tracer_twice def test_add_tracer_with_dynamic_metric metric_code = -> (*args) { "#{args[0]}.#{args[1]}" } @metric_name = metric_code - expected_metric = "1.2" + expected_metric = '1.2' self.class.add_method_tracer(:method_to_be_traced, metric_code) in_transaction do @@ -417,7 +417,7 @@ def test_multiple_metrics__unscoped def test_exception begin - metric = "hey" + metric = 'hey' in_transaction do self.class.trace_execution_scoped(metric) do raise StandardError.new diff --git a/test/new_relic/agent/monitors/cross_app_monitor_test.rb b/test/new_relic/agent/monitors/cross_app_monitor_test.rb index 96776c0970..c52b7ff255 100644 --- a/test/new_relic/agent/monitors/cross_app_monitor_test.rb +++ b/test/new_relic/agent/monitors/cross_app_monitor_test.rb @@ -8,10 +8,10 @@ module NewRelic::Agent class CrossAppMonitorTest < Minitest::Test NEWRELIC_ID_HEADER = DistributedTracing::CrossAppMonitor::NEWRELIC_ID_HEADER_KEY NEWRELIC_TXN_HEADER = DistributedTracing::CrossAppMonitor::NEWRELIC_TXN_HEADER_KEY - CONTENT_LENGTH_KEY = "HTTP_CONTENT_LENGTH" + CONTENT_LENGTH_KEY = 'HTTP_CONTENT_LENGTH' - AGENT_CROSS_APP_ID = "qwerty" - REQUEST_CROSS_APP_ID = "42#1234" + AGENT_CROSS_APP_ID = 'qwerty' + REQUEST_CROSS_APP_ID = '42#1234' TRANSACTION_GUID = '941B0E8001E444E8' REF_TRANSACTION_GUID = '830092CDE59421D4' @@ -78,13 +78,13 @@ def test_doesnt_write_response_header_if_id_blank end def test_doesnt_write_response_header_if_untrusted_id - when_request_runs(for_id("4#1234")) + when_request_runs(for_id('4#1234')) assert_nil response_app_data end def test_doesnt_write_response_header_if_improperly_formatted_id - when_request_runs(for_id("42")) + when_request_runs(for_id('42')) assert_nil response_app_data end @@ -213,11 +213,11 @@ def test_path_hash h3 = @monitor.path_hash('step3', h2.to_i(16)) h4 = @monitor.path_hash('step4', h3.to_i(16)) - assert_equal("eaaec1df", h0) - assert_equal("2e9a0b02", h1) - assert_equal("01d3f0eb", h2) - assert_equal("9a1b45e5", h3) - assert_equal("e9eecfee", h4) + assert_equal('eaaec1df', h0) + assert_equal('2e9a0b02', h1) + assert_equal('01d3f0eb', h2) + assert_equal('9a1b45e5', h3) + assert_equal('e9eecfee', h4) end end @@ -239,7 +239,7 @@ def when_request_runs(request = for_id(REQUEST_CROSS_APP_ID), name = 'transactio end def for_id(id) - encoded_id = id == "" ? "" : Base64.encode64(id) + encoded_id = id == '' ? '' : Base64.encode64(id) encoded_txn_info = json_dump_and_encode([REF_TRANSACTION_GUID, false]) return { diff --git a/test/new_relic/agent/monitors/distributed_trace_monitor_test.rb b/test/new_relic/agent/monitors/distributed_trace_monitor_test.rb index e5f75d6e39..034de8c93d 100644 --- a/test/new_relic/agent/monitors/distributed_trace_monitor_test.rb +++ b/test/new_relic/agent/monitors/distributed_trace_monitor_test.rb @@ -18,9 +18,9 @@ def setup :'cross_application_tracer.enabled' => false, :'distributed_tracing.enabled' => true, :encoding_key => "\0", - :account_id => "190", - :primary_application_id => "46954", - :trusted_account_key => "trust_this!" + :account_id => '190', + :primary_application_id => '46954', + :trusted_account_key => 'trust_this!' } DistributedTracePayload.stubs(:connected?).returns(true) @@ -35,14 +35,14 @@ def teardown def after_notify_event(rack_scheme = nil) payload = nil - in_transaction("referring_txn") do |txn| + in_transaction('referring_txn') do |txn| payload = txn.distributed_tracer.create_distributed_trace_payload end env = {NEWRELIC_TRACE_KEY => payload.http_safe} env['rack.url_scheme'] = rack_scheme if rack_scheme - in_transaction("receiving_txn") do |txn| + in_transaction('receiving_txn') do |txn| @events.notify(:before_call, env) yield(txn) end diff --git a/test/new_relic/agent/monitors/distributed_tracing_monitor_test.rb b/test/new_relic/agent/monitors/distributed_tracing_monitor_test.rb index 4af5ca42f1..9978188383 100644 --- a/test/new_relic/agent/monitors/distributed_tracing_monitor_test.rb +++ b/test/new_relic/agent/monitors/distributed_tracing_monitor_test.rb @@ -46,7 +46,7 @@ def distributed_tracing_disabled def test_invokes_accept_incoming_request with_notify_after_config(distributed_tracing_enabled) do - in_transaction("receiving_txn") do |receiving_txn| + in_transaction('receiving_txn') do |receiving_txn| receiving_txn.distributed_tracer.expects(:accept_incoming_request).at_least_once @events.notify(:before_call, {}) end @@ -55,7 +55,7 @@ def test_invokes_accept_incoming_request def test_invokes_accept_incoming_request_when_cat_enabled_too with_notify_after_config(cat_and_distributed_tracing_enabled) do - in_transaction("receiving_txn") do |receiving_txn| + in_transaction('receiving_txn') do |receiving_txn| receiving_txn.distributed_tracer.expects(:accept_incoming_request).at_least_once @events.notify(:before_call, {}) end @@ -64,7 +64,7 @@ def test_invokes_accept_incoming_request_when_cat_enabled_too def test_skips_accept_incoming_request with_notify_after_config(distributed_tracing_disabled) do - in_transaction("receiving_txn") do |receiving_txn| + in_transaction('receiving_txn') do |receiving_txn| receiving_txn.distributed_tracer.expects(:accept_incoming_request).never @events.notify(:before_call, {}) end diff --git a/test/new_relic/agent/monitors/inbound_request_monitor_test.rb b/test/new_relic/agent/monitors/inbound_request_monitor_test.rb index eaeccde6bf..41df0a35df 100644 --- a/test/new_relic/agent/monitors/inbound_request_monitor_test.rb +++ b/test/new_relic/agent/monitors/inbound_request_monitor_test.rb @@ -28,23 +28,23 @@ def teardown end def test_deserialize - payload = @monitor.obfuscator.obfuscate("[1,2,3]") + payload = @monitor.obfuscator.obfuscate('[1,2,3]') - assert_equal [1, 2, 3], @monitor.deserialize_header(payload, "the_key") + assert_equal [1, 2, 3], @monitor.deserialize_header(payload, 'the_key') end def test_deserialize_nonsense - expects_logging(:debug, includes("the_key")) + expects_logging(:debug, includes('the_key')) - assert_nil @monitor.deserialize_header("asdf", "the_key") + assert_nil @monitor.deserialize_header('asdf', 'the_key') end def test_deserialize_with_invalid_json - payload = @monitor.obfuscator.obfuscate("[1,2,3") + payload = @monitor.obfuscator.obfuscate('[1,2,3') - expects_logging(:debug, includes("the_key")) + expects_logging(:debug, includes('the_key')) - assert_nil @monitor.deserialize_header(payload, "the_key") + assert_nil @monitor.deserialize_header(payload, 'the_key') end end end diff --git a/test/new_relic/agent/monitors/trace_context_request_monitor_test.rb b/test/new_relic/agent/monitors/trace_context_request_monitor_test.rb index 98f2d772f8..867fdbd15b 100644 --- a/test/new_relic/agent/monitors/trace_context_request_monitor_test.rb +++ b/test/new_relic/agent/monitors/trace_context_request_monitor_test.rb @@ -14,9 +14,9 @@ def setup :'cross_application_tracer.enabled' => false, :'distributed_tracing.enabled' => true, :encoding_key => "\0", - :account_id => "190", - :primary_application_id => "46954", - :trusted_account_key => "99999" + :account_id => '190', + :primary_application_id => '46954', + :trusted_account_key => '99999' } NewRelic::Agent.config.add_config_for_testing(@config, true) @@ -30,7 +30,7 @@ def teardown def test_accepts_trace_context parent_txn, carrier = build_parent_transaction_headers - child_txn = in_transaction("receiving_txn") do |txn| + child_txn = in_transaction('receiving_txn') do |txn| @events.notify(:before_call, carrier) end @@ -41,7 +41,7 @@ def test_accepts_trace_context def test_accepts_trace_context_with_trace_parent_and_no_trace_state carrier = {'HTTP_TRACEPARENT' => '00-12345678901234567890123456789012-1234567890123456-01'} - txn = in_transaction("receiving_txn") do + txn = in_transaction('receiving_txn') do @events.notify(:before_call, carrier) end @@ -53,7 +53,7 @@ def test_accepts_trace_context_with_empty_trace_state 'HTTP_TRACEPARENT' => '00-12345678901234567890123456789012-1234567890123456-00', 'HTTP_TRACESTATE' => '' } - txn = in_transaction("receiving_txn") do + txn = in_transaction('receiving_txn') do @events.notify(:before_call, carrier) end @@ -65,7 +65,7 @@ def test_restarts_trace_on_all_zero_trace_id 'HTTP_TRACEPARENT' => '00-00000000000000000000000000000000-1234567890123456-00', 'HTTP_TRACESTATE' => '' } - txn = in_transaction("receiving_txn") do + txn = in_transaction('receiving_txn') do @events.notify(:before_call, carrier) end diff --git a/test/new_relic/agent/new_relic_service/security_policy_settings_test.rb b/test/new_relic/agent/new_relic_service/security_policy_settings_test.rb index adc3e96515..ec7d76475b 100644 --- a/test/new_relic/agent/new_relic_service/security_policy_settings_test.rb +++ b/test/new_relic/agent/new_relic_service/security_policy_settings_test.rb @@ -11,24 +11,24 @@ class NewRelicService class SecurityPolicySettingsTest < Minitest::Test def test_preliminary_settings policies = { - "record_sql" => {"enabled" => false, "required" => false, "position" => 0}, - "custom_events" => {"enabled" => false, "required" => false, "position" => 3}, - "custom_parameters" => {"enabled" => false, "required" => false, "position" => 4}, - "attributes_include" => {"enabled" => false, "required" => false, "position" => 1}, - "message_parameters" => {"enabled" => false, "required" => false, "position" => 6}, - "allow_raw_exception_messages" => {"enabled" => false, "required" => false, "position" => 2}, - "custom_instrumentation_editor" => {"enabled" => false, "required" => false, "position" => 5} + 'record_sql' => {'enabled' => false, 'required' => false, 'position' => 0}, + 'custom_events' => {'enabled' => false, 'required' => false, 'position' => 3}, + 'custom_parameters' => {'enabled' => false, 'required' => false, 'position' => 4}, + 'attributes_include' => {'enabled' => false, 'required' => false, 'position' => 1}, + 'message_parameters' => {'enabled' => false, 'required' => false, 'position' => 6}, + 'allow_raw_exception_messages' => {'enabled' => false, 'required' => false, 'position' => 2}, + 'custom_instrumentation_editor' => {'enabled' => false, 'required' => false, 'position' => 5} } expected = { - "security_policies" => { - "record_sql" => {"enabled" => false}, - "custom_events" => {"enabled" => false}, - "custom_parameters" => {"enabled" => false}, - "attributes_include" => {"enabled" => false}, - "message_parameters" => {"enabled" => false}, - "allow_raw_exception_messages" => {"enabled" => false}, - "custom_instrumentation_editor" => {"enabled" => false} + 'security_policies' => { + 'record_sql' => {'enabled' => false}, + 'custom_events' => {'enabled' => false}, + 'custom_parameters' => {'enabled' => false}, + 'attributes_include' => {'enabled' => false}, + 'message_parameters' => {'enabled' => false}, + 'allow_raw_exception_messages' => {'enabled' => false}, + 'custom_instrumentation_editor' => {'enabled' => false} } } @@ -37,8 +37,8 @@ def test_preliminary_settings assert_equal expected, settings end - load_cross_agent_test("language_agents_security_policies").each do |test_case| - define_method("test_#{test_case['name']}".tr(" ", "_")) do + load_cross_agent_test('language_agents_security_policies').each do |test_case| + define_method("test_#{test_case['name']}".tr(' ', '_')) do with_redefined_policies(test_case['required_features']) do policies = test_case['security_policies'] validator = SecurityPolicySettings::Validator.new(test_case) diff --git a/test/new_relic/agent/new_relic_service_test.rb b/test/new_relic/agent/new_relic_service_test.rb index e0b15ef26b..1619afeec8 100644 --- a/test/new_relic/agent/new_relic_service_test.rb +++ b/test/new_relic/agent/new_relic_service_test.rb @@ -41,7 +41,7 @@ def test_session_handles_timeouts_opening_connection_gracefully end end - refute block_ran, "Expected block passed to #session to have not run" + refute block_ran, 'Expected block passed to #session to have not run' end def test_session_block_reuses_http_handle_with_aggressive_keepalive_off @@ -225,7 +225,7 @@ def test_initialize_uses_license_key_from_config def test_initialize_uses_license_key_from_manual_start service = NewRelic::Agent::NewRelicService.new - NewRelic::Agent.manual_start(:license_key => "geronimo") + NewRelic::Agent.manual_start(:license_key => 'geronimo') assert_equal 'geronimo', service.send(:license_key) NewRelic::Agent.shutdown @@ -514,7 +514,7 @@ def test_profile_data @http_handle.respond_to(:profile_data, 'profile' => 123) response = @service.profile_data([]) - assert_equal({"profile" => 123}, response) + assert_equal({'profile' => 123}, response) end def test_profile_data_does_not_normalize_encodings @@ -616,7 +616,7 @@ def test_supportability_metrics_for_http_error_responses end assert_metrics_recorded( - "Supportability/Agent/Collector/HTTPError/400" => {:call_count => 1} + 'Supportability/Agent/Collector/HTTPError/400' => {:call_count => 1} ) end @@ -629,7 +629,7 @@ def test_supportability_metrics_for_endpoint_response_time @service.send(:invoke_remote, :foobar, payload) assert_metrics_recorded( - "Supportability/Agent/Collector/foobar/Duration" => {:call_count => 1} + 'Supportability/Agent/Collector/foobar/Duration' => {:call_count => 1} ) end @@ -644,7 +644,7 @@ def test_supportability_metrics_for_unsuccessful_endpoint_attempts end assert_metrics_recorded( - "Supportability/Agent/Collector/metric_data/Attempts" => {:call_count => 1} + 'Supportability/Agent/Collector/metric_data/Attempts' => {:call_count => 1} ) end @@ -692,7 +692,7 @@ def test_skips_normalization_if_configured_to end def test_json_marshaller_handles_binary_strings - input_string = (0..255).to_a.pack("C*") + input_string = (0..255).to_a.pack('C*') roundtripped_string = roundtrip_data(input_string) assert_equal(Encoding.find('ASCII-8BIT'), input_string.encoding) @@ -702,7 +702,7 @@ def test_json_marshaller_handles_binary_strings end def test_json_marshaller_handles_strings_with_incorrect_encoding - input_string = (0..255).to_a.pack("C*").force_encoding("UTF-8") + input_string = (0..255).to_a.pack('C*').force_encoding('UTF-8') roundtripped_string = roundtrip_data(input_string) assert_equal(Encoding.find('UTF-8'), input_string.encoding) @@ -712,7 +712,7 @@ def test_json_marshaller_handles_strings_with_incorrect_encoding end def test_json_marshaller_failure_when_not_normalizing - input_string = (0..255).to_a.pack("C*") + input_string = (0..255).to_a.pack('C*') assert_raises(NewRelic::Agent::SerializationError) do roundtrip_data(input_string, false) end @@ -854,7 +854,7 @@ def test_valid_to_marshal end def test_not_valid_to_marshal - @service.marshaller.stubs(:dump).raises(StandardError.new("Failed to marshal")) + @service.marshaller.stubs(:dump).raises(StandardError.new('Failed to marshal')) refute @service.valid_to_marshal?({}) end @@ -921,7 +921,7 @@ def test_max_payload_size_enforced end assert_metrics_recorded( - "Supportability/Ruby/Collector/foobar/MaxPayloadSizeLimit" => {:call_count => 1} + 'Supportability/Ruby/Collector/foobar/MaxPayloadSizeLimit' => {:call_count => 1} ) end @@ -1048,7 +1048,7 @@ def generate_random_byte_sequence(length = 255, encoding = nil) meth = alphabet.respond_to?(:sample) ? :sample : :choice length.times { bytes << alphabet.send(meth) } - string = bytes.pack("C*") + string = bytes.pack('C*') string.force_encoding(encoding) if encoding string end @@ -1220,7 +1220,7 @@ def reset end def last_request_payload - return nil unless @last_request && @last_request.body + return nil unless @last_request&.body content_encoding = @last_request['Content-Encoding'] body = if content_encoding == 'deflate' diff --git a/test/new_relic/agent/obfuscator_test.rb b/test/new_relic/agent/obfuscator_test.rb index cc83cdda83..b7169f14a9 100644 --- a/test/new_relic/agent/obfuscator_test.rb +++ b/test/new_relic/agent/obfuscator_test.rb @@ -3,7 +3,7 @@ # frozen_string_literal: true require_relative '../../test_helper' -require "new_relic/agent/obfuscator" +require 'new_relic/agent/obfuscator' class NewRelic::Agent::ObfuscatorTest < Minitest::Test OBFUSCATION_KEY = (1..40).to_a.pack('c*') @@ -37,26 +37,26 @@ def test_obfuscate_long_string def test_obfuscate_utf8 assert_encoded(RUM_KEY_LENGTH, - "foooooééoooo - blah", - "Z21sa2ppxKHKo2RjYm4iLiRnamZg") + 'foooooééoooo - blah', + 'Z21sa2ppxKHKo2RjYm4iLiRnamZg') end def test_decoding_blank obfuscator = NewRelic::Agent::Obfuscator.new('query') - assert_equal "", obfuscator.deobfuscate("") + assert_equal '', obfuscator.deobfuscate('') end def test_decoding_empty_key - obfuscator = NewRelic::Agent::Obfuscator.new("") + obfuscator = NewRelic::Agent::Obfuscator.new('') - assert_equal "query", obfuscator.encode('query') + assert_equal 'query', obfuscator.encode('query') end def test_encode_with_nil_uses_empty_key obfuscator = NewRelic::Agent::Obfuscator.new(nil) - assert_equal "query", obfuscator.encode('query') + assert_equal 'query', obfuscator.encode('query') end def test_encoding_functions_can_roundtrip_utf8_text diff --git a/test/new_relic/agent/parameter_filtering_test.rb b/test/new_relic/agent/parameter_filtering_test.rb index b6dba00940..379dc323ec 100644 --- a/test/new_relic/agent/parameter_filtering_test.rb +++ b/test/new_relic/agent/parameter_filtering_test.rb @@ -11,7 +11,7 @@ class ParameterFilteringTest < Minitest::Test def test_apply_filters_returns_params_when_rails_is_not_present undefine_constant(:"ActionDispatch::Http::ParameterFilter") do undefine_constant(:"ActiveSupport::ParameterFilter") do - params = {"password" => "mypass"} + params = {'password' => 'mypass'} result = ParameterFiltering.apply_filters({}, params) assert_equal params, result @@ -20,22 +20,22 @@ def test_apply_filters_returns_params_when_rails_is_not_present end def test_apply_filters_replaces_file_uploads_with_placeholder - env = {"CONTENT_TYPE" => "multipart/form-data"} + env = {'CONTENT_TYPE' => 'multipart/form-data'} params = { - :name => "name", + :name => 'name', :file => { - :filename => "data.jpg", - :tempfile => "file_data" + :filename => 'data.jpg', + :tempfile => 'file_data' } } - expected = {:name => "name", :file => "[FILE]"} + expected = {:name => 'name', :file => '[FILE]'} result = ParameterFiltering.apply_filters(env, params) assert_equal expected, result # argument should not be mutated - assert_equal({:filename => "data.jpg", :tempfile => "file_data"}, params[:file]) + assert_equal({:filename => 'data.jpg', :tempfile => 'file_data'}, params[:file]) end def test_app_works_constant_not_set diff --git a/test/new_relic/agent/pipe_channel_manager_test.rb b/test/new_relic/agent/pipe_channel_manager_test.rb index 2385051007..aea75633ea 100644 --- a/test/new_relic/agent/pipe_channel_manager_test.rb +++ b/test/new_relic/agent/pipe_channel_manager_test.rb @@ -80,7 +80,7 @@ def test_listener_merges_transaction_traces def test_listener_merges_error_traces sampler = NewRelic::Agent.agent.error_collector - sampler.notice_error(Exception.new("message"), :uri => '/myurl/', + sampler.notice_error(Exception.new('message'), :uri => '/myurl/', :metric => 'path', :referer => 'test_referer', :request_params => {:x => 'y'}) NewRelic::Agent.agent.merge_data_for_endpoint(:error_data, sampler.error_trace_aggregator.harvest!) @@ -94,7 +94,7 @@ def test_listener_merges_error_traces run_child(668) do NewRelic::Agent.after_fork new_sampler = NewRelic::Agent::ErrorCollector.new(NewRelic::Agent.instance.events) - new_sampler.notice_error(Exception.new("new message"), :uri => '/myurl/', + new_sampler.notice_error(Exception.new('new message'), :uri => '/myurl/', :metric => 'path', :referer => 'test_referer', :request_params => {:x => 'y'}) service = NewRelic::Agent::PipeService.new(668) @@ -134,7 +134,7 @@ def test_listener_merges_error_events reset_lifetime_counts!(error_event_aggregator) sampler = NewRelic::Agent.agent.error_collector - sampler.notice_error(Exception.new("message"), :uri => '/myurl/', + sampler.notice_error(Exception.new('message'), :uri => '/myurl/', :metric => 'path', :referer => 'test_referer', :request_params => {:x => 'y'}) @@ -143,7 +143,7 @@ def test_listener_merges_error_events run_child(668) do NewRelic::Agent.after_fork new_sampler = NewRelic::Agent::ErrorCollector.new(NewRelic::Agent.instance.events) - new_sampler.notice_error(Exception.new("new message"), :uri => '/myurl/', + new_sampler.notice_error(Exception.new('new message'), :uri => '/myurl/', :metric => 'path', :referer => 'test_referer', :request_params => {:x => 'y'}) service = NewRelic::Agent::PipeService.new(668) @@ -226,7 +226,7 @@ def assert_pipe_finished(id) def create_sql_sample(sampler) state = NewRelic::Agent::Tracer.state sampler.on_start_transaction(state) - sampler.notice_sql("SELECT * FROM table", "ActiveRecord/Widgets/find", nil, 100, state) + sampler.notice_sql('SELECT * FROM table', 'ActiveRecord/Widgets/find', nil, 100, state) sampler.on_finishing_transaction(state, 'noodles') end end @@ -243,11 +243,11 @@ def test_pipe_read_length_failure # If we only read three bytes, it isn't valid. # We can't tell whether any four bytes or more are a "good" length or not. - read_pipe = stub(:read => "jrc") + read_pipe = stub(:read => 'jrc') IO.stubs(:pipe).returns([read_pipe, write_pipe]) # Includes the failed bytes - expects_logging(:error, includes("[6a 72 63]")) + expects_logging(:error, includes('[6a 72 63]')) pipe = NewRelic::Agent::PipeChannelManager::Pipe.new @@ -317,7 +317,7 @@ def test_blocking_error_rescued wake_mock = MiniTest::Mock.new out_mock = MiniTest::Mock.new 4.times { wake_mock.expect(:out, out_mock) } - error_stub = proc { |msg| desired_error_messages_seen += 1 if msg =~ /^(?:Issue while|Ready pipes)/ } + error_stub = proc { |msg| desired_error_messages_seen += 1 if /^(?:Issue while|Ready pipes)/.match?(msg) } ready_pipes_mock = MiniTest::Mock.new ::IO.stub(:select, [ready_pipes_mock]) do diff --git a/test/new_relic/agent/pipe_service_test.rb b/test/new_relic/agent/pipe_service_test.rb index d472c17ed2..ea19970119 100644 --- a/test/new_relic/agent/pipe_service_test.rb +++ b/test/new_relic/agent/pipe_service_test.rb @@ -114,7 +114,7 @@ def test_transaction_sample_data_with_newlines end def test_log_event_data - payload = [{}, [[{"priority" => 1}, {"message" => "yo"}]]] + payload = [{}, [[{'priority' => 1}, {'message' => 'yo'}]]] received_data = data_from_forked_process do @service.log_event_data(payload) end diff --git a/test/new_relic/agent/priority_sampled_buffer_test.rb b/test/new_relic/agent/priority_sampled_buffer_test.rb index df567bc119..20798e5efc 100644 --- a/test/new_relic/agent/priority_sampled_buffer_test.rb +++ b/test/new_relic/agent/priority_sampled_buffer_test.rb @@ -24,7 +24,7 @@ def test_block_is_evaluated_based_on_priority events = create_events(5..9) events.each { |e| buffer.append(event: e) } - buffer.append(event: create_event(priority: 4)) { raise "This should not be evaluated" } + buffer.append(event: create_event(priority: 4)) { raise 'This should not be evaluated' } assert_equal(5, buffer.size) assert_equal_unordered(events, buffer.to_a) @@ -73,7 +73,7 @@ def test_to_a_returns_copy_of_items_array events.each { |e| buffer.append(event: e) } items = buffer.to_a - items << create_event(priority: "blarg") + items << create_event(priority: 'blarg') assert_equal(events, buffer.to_a) end @@ -95,13 +95,13 @@ def test_buffer_full_works_properly 4.times do |i| buffer.append(event: create_event(priority: i)) - refute buffer.full?, "#PrioritySampledBuffer#append should return false until buffer is full" + refute buffer.full?, '#PrioritySampledBuffer#append should return false until buffer is full' end 4.times do |i| buffer.append(event: create_event(priority: i)) - assert_predicate(buffer, :full?, "#PrioritySampledBuffer#append should return true once buffer is full") + assert_predicate(buffer, :full?, '#PrioritySampledBuffer#append should return true once buffer is full') end end @@ -249,7 +249,7 @@ def test_sample_rate_lifetime # for this test file. def create_event(priority: nil, name: nil) name ||= "event_#{priority}" - [{"priority" => priority, "name" => name}, {}, {}] + [{'priority' => priority, 'name' => name}, {}, {}] end def create_events(priorities) diff --git a/test/new_relic/agent/rpm_agent_test.rb b/test/new_relic/agent/rpm_agent_test.rb index c8edb5de56..feeedb1d42 100644 --- a/test/new_relic/agent/rpm_agent_test.rb +++ b/test/new_relic/agent/rpm_agent_test.rb @@ -27,7 +27,7 @@ def test_public_apis nil end with_ignore_error_filter(filter) do - NewRelic::Agent.notice_error(StandardError.new("message"), :request_params => {:x => "y"}) + NewRelic::Agent.notice_error(StandardError.new('message'), :request_params => {:x => 'y'}) end assert(ignore_called) @@ -61,17 +61,17 @@ def test_post_fork_handler end def test_manual_overrides - NewRelic::Agent.manual_start(:app_name => "testjobs") + NewRelic::Agent.manual_start(:app_name => 'testjobs') - assert_equal "testjobs", NewRelic::Agent.config[:app_name][0] + assert_equal 'testjobs', NewRelic::Agent.config[:app_name][0] NewRelic::Agent.shutdown end def test_agent_restart - NewRelic::Agent.manual_start(:app_name => "noapp") - NewRelic::Agent.manual_start(:app_name => "testjobs") + NewRelic::Agent.manual_start(:app_name => 'noapp') + NewRelic::Agent.manual_start(:app_name => 'testjobs') - assert_equal "testjobs", NewRelic::Agent.config[:app_name][0] + assert_equal 'testjobs', NewRelic::Agent.config[:app_name][0] NewRelic::Agent.shutdown end diff --git a/test/new_relic/agent/rules_engine_test.rb b/test/new_relic/agent/rules_engine_test.rb index 4e977787b6..cac3ee1c97 100644 --- a/test/new_relic/agent/rules_engine_test.rb +++ b/test/new_relic/agent/rules_engine_test.rb @@ -119,11 +119,11 @@ def create_rule(spec) define_method("test_#{testcase['testname']}") do engine = NewRelic::Agent::RulesEngine.create_metric_rules('metric_name_rules' => testcase['rules']) - testcase["tests"].each do |test| - if test["expected"].nil? - assert_nil engine.rename(test["input"]), "Input: #{test['input'].inspect}" + testcase['tests'].each do |test| + if test['expected'].nil? + assert_nil engine.rename(test['input']), "Input: #{test['input'].inspect}" else - assert_equal test["expected"], engine.rename(test["input"]), "Input: #{test['input'].inspect}" + assert_equal test['expected'], engine.rename(test['input']), "Input: #{test['input'].inspect}" end end end @@ -134,7 +134,7 @@ def create_rule(spec) engine = NewRelic::Agent::RulesEngine.create_transaction_rules(testcase) testcase['tests'].each do |test| - assert_equal(test["expected"], engine.rename(test["input"]), "Input: #{test['input'].inspect}") + assert_equal(test['expected'], engine.rename(test['input']), "Input: #{test['input'].inspect}") end end end diff --git a/test/new_relic/agent/samplers/cpu_sampler_test.rb b/test/new_relic/agent/samplers/cpu_sampler_test.rb index e8f932c0bb..eef51980ee 100644 --- a/test/new_relic/agent/samplers/cpu_sampler_test.rb +++ b/test/new_relic/agent/samplers/cpu_sampler_test.rb @@ -39,11 +39,11 @@ def test_correctly_detecting_jruby_support_for_correct_cpu_sampling # def assert_supported_on_platform - assert_predicate NewRelic::Agent::Samplers::CpuSampler, :supported_on_this_platform?, "should be supported on this platform" + assert_predicate NewRelic::Agent::Samplers::CpuSampler, :supported_on_this_platform?, 'should be supported on this platform' end def refute_supported_on_platform - refute NewRelic::Agent::Samplers::CpuSampler.supported_on_this_platform?, "should not be supported on this platform" + refute NewRelic::Agent::Samplers::CpuSampler.supported_on_this_platform?, 'should not be supported on this platform' end def set_jruby_version_constant(string) diff --git a/test/new_relic/agent/samplers/memory_sampler_test.rb b/test/new_relic/agent/samplers/memory_sampler_test.rb index 71b880ce75..4b046d3954 100644 --- a/test/new_relic/agent/samplers/memory_sampler_test.rb +++ b/test/new_relic/agent/samplers/memory_sampler_test.rb @@ -19,7 +19,7 @@ def test_memory__default s.poll s.poll - assert_metrics_recorded "Memory/Physical" => {:call_count => 3, :total_call_time => 999} + assert_metrics_recorded 'Memory/Physical' => {:call_count => 3, :total_call_time => 999} end def test_memory__linux @@ -32,7 +32,7 @@ def test_memory__linux s.poll s.poll - assert_metrics_recorded "Memory/Physical" => {:call_count => 3, :total_call_time => 999} + assert_metrics_recorded 'Memory/Physical' => {:call_count => 3, :total_call_time => 999} end def test_memory__solaris @@ -43,7 +43,7 @@ def test_memory__solaris s = NewRelic::Agent::Samplers::MemorySampler.new s.poll - assert_metrics_recorded "Memory/Physical" => {:call_count => 1, :total_call_time => 999} + assert_metrics_recorded 'Memory/Physical' => {:call_count => 1, :total_call_time => 999} end def test_memory__windows diff --git a/test/new_relic/agent/span_event_aggregator_test.rb b/test/new_relic/agent/span_event_aggregator_test.rb index 65ae5e6351..fd73834174 100644 --- a/test/new_relic/agent/span_event_aggregator_test.rb +++ b/test/new_relic/agent/span_event_aggregator_test.rb @@ -70,7 +70,7 @@ def aggregator end def name_for(event) - event[0]["name"] + event[0]['name'] end def enabled_key diff --git a/test/new_relic/agent/span_event_primitive_test.rb b/test/new_relic/agent/span_event_primitive_test.rb index 8a8e44d0c3..0379f463b1 100644 --- a/test/new_relic/agent/span_event_primitive_test.rb +++ b/test/new_relic/agent/span_event_primitive_test.rb @@ -24,8 +24,8 @@ def test_error_attributes_returns_nil_when_no_error with_segment do |segment| eh = SpanEventPrimitive::error_attributes(segment) - refute segment.noticed_error, "segment.noticed_error expected to be nil!" - refute eh, "expected nil when no error present on segment" + refute segment.noticed_error, 'segment.noticed_error expected to be nil!' + refute eh, 'expected nil when no error present on segment' end end @@ -34,10 +34,10 @@ def test_error_attributes_returns_populated_attributes_when_error_present eh = SpanEventPrimitive::error_attributes(segment) - assert segment.noticed_error, "segment.noticed_error should NOT be nil!" - assert eh.is_a?(Hash), "expected a Hash when error present on segment" - assert_equal "oops!", eh["error.message"] - assert_equal "RuntimeError", eh["error.class"] + assert segment.noticed_error, 'segment.noticed_error should NOT be nil!' + assert eh.is_a?(Hash), 'expected a Hash when error present on segment' + assert_equal 'oops!', eh['error.message'] + assert_equal 'RuntimeError', eh['error.class'] end def test_error_attributes_are_merged_with_agent_attributes_when_error_present @@ -45,10 +45,10 @@ def test_error_attributes_are_merged_with_agent_attributes_when_error_present segment.attributes.stubs(:agent_attributes_for).returns(NewRelic::EMPTY_HASH) _, _, attrs = SpanEventPrimitive.for_segment(segment) - assert segment.noticed_error, "segment.noticed_error should NOT be nil!" - assert attrs.is_a?(Hash), "expected a Hash when error present on segment" - assert_equal "oops!", attrs["error.message"] - assert_equal "RuntimeError", attrs["error.class"] + assert segment.noticed_error, 'segment.noticed_error should NOT be nil!' + assert attrs.is_a?(Hash), 'expected a Hash when error present on segment' + assert_equal 'oops!', attrs['error.message'] + assert_equal 'RuntimeError', attrs['error.class'] end def test_does_not_add_error_attributes_in_high_security @@ -57,8 +57,8 @@ def test_does_not_add_error_attributes_in_high_security eh = SpanEventPrimitive::error_attributes(segment) - refute segment.noticed_error, "segment.noticed_error should be nil!" - refute eh, "expected nil when error present on segment and high_security is enabled" + refute segment.noticed_error, 'segment.noticed_error should be nil!' + refute eh, 'expected nil when error present on segment and high_security is enabled' end end @@ -68,10 +68,10 @@ def test_does_not_add_error_message_when_strip_message_enabled eh = SpanEventPrimitive::error_attributes(segment) - assert segment.noticed_error, "segment.noticed_error should NOT be nil!" - assert eh.is_a?(Hash), "expected a Hash when error present on segment" - assert eh["error.message"].start_with?("Message removed by") - assert_equal "RuntimeError", eh["error.class"] + assert segment.noticed_error, 'segment.noticed_error should NOT be nil!' + assert eh.is_a?(Hash), 'expected a Hash when error present on segment' + assert eh['error.message'].start_with?('Message removed by') + assert_equal 'RuntimeError', eh['error.class'] end end @@ -86,7 +86,7 @@ def test_root_span_gets_transaction_name_attribute root_span_event = SpanEventPrimitive.for_segment(root_segment) # There should be a transaction.name attribute on the root span equal to the final txn name - assert_equal txn.best_name, root_span_event[0]["transaction.name"] + assert_equal txn.best_name, root_span_event[0]['transaction.name'] end def test_root_span_gets_dt_parent_attributes @@ -96,9 +96,9 @@ def test_root_span_gets_dt_parent_attributes @config = { :'distributed_tracing.enabled' => true, - :account_id => "190", - :primary_application_id => "46954", - :trusted_account_key => "trust_this!" + :account_id => '190', + :primary_application_id => '46954', + :trusted_account_key => 'trust_this!' } NewRelic::Agent.config.add_config_for_testing(@config) @@ -106,9 +106,9 @@ def test_root_span_gets_dt_parent_attributes payload = nil in_transaction('test_txn') do |txn| NewRelic::Agent::Tracer \ - .start_external_request_segment(library: "net/http", - uri: "http://docs.newrelic.com", - procedure: "GET") + .start_external_request_segment(library: 'net/http', + uri: 'http://docs.newrelic.com', + procedure: 'GET') payload = txn.distributed_tracer.create_distributed_trace_payload end @@ -119,24 +119,24 @@ def test_root_span_gets_dt_parent_attributes last_span_event = NewRelic::Agent.agent.span_event_aggregator.harvest![-1][-1] - assert last_span_event[2]["parent.type"], "Expected parent.type in agent attributes" - assert last_span_event[2]["parent.app"], "Expected parent.app in agent attributes" - assert last_span_event[2]["parent.account"], "Expected parent.account in agent attributes" - assert last_span_event[2]["parent.transportType"], "Expected parent.transportType in agent attributes" - assert last_span_event[2]["parent.transportDuration"], "Expected parent.transportDuration in agent attributes" + assert last_span_event[2]['parent.type'], 'Expected parent.type in agent attributes' + assert last_span_event[2]['parent.app'], 'Expected parent.app in agent attributes' + assert last_span_event[2]['parent.account'], 'Expected parent.account in agent attributes' + assert last_span_event[2]['parent.transportType'], 'Expected parent.transportType in agent attributes' + assert last_span_event[2]['parent.transportDuration'], 'Expected parent.transportDuration in agent attributes' end def test_empty_error_message_can_override_previous_error_message_attribute begin with_segment do |segment| - segment.notice_error(RuntimeError.new("oops!")) + segment.notice_error(RuntimeError.new('oops!')) segment.notice_error(StandardError.new) error_attributes = SpanEventPrimitive::error_attributes(segment) - assert segment.noticed_error, "segment.noticed_error should NOT be nil!" - assert_equal "StandardError", error_attributes["error.class"] + assert segment.noticed_error, 'segment.noticed_error should NOT be nil!' + assert_equal 'StandardError', error_attributes['error.class'] # If no message given, we should see the class name as the new error message - assert_equal "StandardError", error_attributes["error.message"] + assert_equal 'StandardError', error_attributes['error.message'] end end end @@ -183,7 +183,7 @@ def test_custom_span_attributes_not_added_to_transaction_events attributes = NewRelic::Agent::Attributes.new(filter) payload = { - :name => "Controller/whatever", + :name => 'Controller/whatever', :type => :controller, :start_timestamp => Process.clock_gettime(Process::CLOCK_REALTIME), :duration => 0.1, @@ -206,14 +206,14 @@ def test_attribute_exclusion in_transaction('test_txn') do |t| t.stubs(:sampled?).returns(true) external_segment = Tracer.start_external_request_segment(library: 'Net::HTTP', - uri: "https://docs.newrelic.com", - procedure: "GET") + uri: 'https://docs.newrelic.com', + procedure: 'GET') external_segment.finish end end last_span_events = NewRelic::Agent.agent.span_event_aggregator.harvest![1] - _, optional_attrs, _ = last_span_events.detect { |ev| ev[0]["name"] == external_segment.name } + _, optional_attrs, _ = last_span_events.detect { |ev| ev[0]['name'] == external_segment.name } assert_empty optional_attrs end @@ -221,14 +221,14 @@ def test_attribute_exclusion def test_transaction_level_custom_attributes_added_to_span_events with_config(:'span_events.attributes.enabled' => true) do with_segment do |segment| - NewRelic::Agent.add_custom_attributes(:foo => "bar") + NewRelic::Agent.add_custom_attributes(:foo => 'bar') txn = NewRelic::Agent::Tracer.current_transaction span_event = SpanEventPrimitive.for_segment(segment) transaction_custom_attributes = txn.attributes.custom_attributes_for(NewRelic::Agent::AttributeFilter::DST_TRANSACTION_EVENTS) span_custom_attributes = span_event[1] - assert_equal({"foo" => "bar"}, span_custom_attributes) + assert_equal({'foo' => 'bar'}, span_custom_attributes) assert_equal transaction_custom_attributes, span_custom_attributes end end @@ -238,8 +238,8 @@ def test_span_level_custom_attributes_always_override_transaction_level_custom_a with_config(:'span_events.attributes.enabled' => true) do # Attributes added via add_custom_span_attributes should override those added via add_custom_attributes with_segment do |segment| - NewRelic::Agent.add_custom_attributes(:foo => "bar") - NewRelic::Agent.add_custom_span_attributes(:foo => "baz") + NewRelic::Agent.add_custom_attributes(:foo => 'bar') + NewRelic::Agent.add_custom_span_attributes(:foo => 'baz') txn = NewRelic::Agent::Tracer.current_transaction span_event = SpanEventPrimitive.for_segment(segment) @@ -247,14 +247,14 @@ def test_span_level_custom_attributes_always_override_transaction_level_custom_a transaction_custom_attributes = txn.attributes.custom_attributes_for(NewRelic::Agent::AttributeFilter::DST_TRANSACTION_EVENTS) span_custom_attributes = span_event[1] - assert_equal({"foo" => "baz"}, span_custom_attributes) + assert_equal({'foo' => 'baz'}, span_custom_attributes) refute_equal transaction_custom_attributes, span_custom_attributes end # Span attributes should still be preferred even if add_custom_span_attributes is called before add_custom_attributes with_segment do |segment| - NewRelic::Agent.add_custom_span_attributes(:foo => "baz") - NewRelic::Agent.add_custom_attributes(:foo => "bar") + NewRelic::Agent.add_custom_span_attributes(:foo => 'baz') + NewRelic::Agent.add_custom_attributes(:foo => 'bar') txn = NewRelic::Agent::Tracer.current_transaction span_event = SpanEventPrimitive.for_segment(segment) @@ -262,7 +262,7 @@ def test_span_level_custom_attributes_always_override_transaction_level_custom_a transaction_custom_attributes = txn.attributes.custom_attributes_for(NewRelic::Agent::AttributeFilter::DST_TRANSACTION_EVENTS) span_custom_attributes = span_event[1] - assert_equal({"foo" => "baz"}, span_custom_attributes) + assert_equal({'foo' => 'baz'}, span_custom_attributes) refute_equal transaction_custom_attributes, span_custom_attributes end end @@ -274,14 +274,14 @@ def test_transaction_level_agent_attributes_added_to_span_events with_config(:'span_events.attributes.enabled' => true) do _segment, transaction = with_segment do |segment| txn = NewRelic::Agent::Tracer.current_transaction - txn.add_agent_attribute(:foo, "bar", AttributeFilter::DST_ALL) + txn.add_agent_attribute(:foo, 'bar', AttributeFilter::DST_ALL) span_event = SpanEventPrimitive.for_segment(segment) end transaction_agent_attributes = transaction.attributes.agent_attributes_for(NewRelic::Agent::AttributeFilter::DST_TRANSACTION_EVENTS) span_agent_attributes = span_event[2] - assert_equal({:foo => "bar"}, span_agent_attributes) + assert_equal({:foo => 'bar'}, span_agent_attributes) assert_equal transaction_agent_attributes, span_agent_attributes end end diff --git a/test/new_relic/agent/span_events_test.rb b/test/new_relic/agent/span_events_test.rb index c8a8f3e155..928c33a064 100644 --- a/test/new_relic/agent/span_events_test.rb +++ b/test/new_relic/agent/span_events_test.rb @@ -11,9 +11,9 @@ class SpanEventsTest < Minitest::Test def setup @config = { :'distributed_tracing.enabled' => true, - :account_id => "190", - :primary_application_id => "46954", - :trusted_account_key => "trust_this!" + :account_id => '190', + :primary_application_id => '46954', + :trusted_account_key => 'trust_this!' } NewRelic::Agent.config.add_config_for_testing(@config) @@ -33,9 +33,9 @@ def test_span_ids_passed_in_payload_when_span_events_enabled external_segment = nil transaction = in_transaction('test_txn') do |txn| external_segment = NewRelic::Agent::Tracer \ - .start_external_request_segment(library: "net/http", - uri: "http://docs.newrelic.com", - procedure: "GET") + .start_external_request_segment(library: 'net/http', + uri: 'http://docs.newrelic.com', + procedure: 'GET') payload = txn.distributed_tracer.create_distributed_trace_payload end @@ -50,9 +50,9 @@ def test_parent_span_id_propagated_cross_process external_segment = nil in_transaction('test_txn') do |txn| external_segment = NewRelic::Agent::Tracer \ - .start_external_request_segment(library: "net/http", - uri: "http://docs.newrelic.com", - procedure: "GET") + .start_external_request_segment(library: 'net/http', + uri: 'http://docs.newrelic.com', + procedure: 'GET') payload = txn.distributed_tracer.create_distributed_trace_payload end @@ -61,9 +61,9 @@ def test_parent_span_id_propagated_cross_process end last_span_events = NewRelic::Agent.agent.span_event_aggregator.harvest![1] - txn2_entry_span = last_span_events.detect { |ev| ev[0]["name"] == "test_txn2" } + txn2_entry_span = last_span_events.detect { |ev| ev[0]['name'] == 'test_txn2' } - assert_equal external_segment.guid, txn2_entry_span[0]["parentId"] + assert_equal external_segment.guid, txn2_entry_span[0]['parentId'] end def test_span_event_parenting @@ -81,20 +81,20 @@ def test_span_event_parenting last_span_events = NewRelic::Agent.agent.span_event_aggregator.harvest![1] - txn_segment_event, _, _ = last_span_events.detect { |ev| ev[0]["name"] == "test_txn" } + txn_segment_event, _, _ = last_span_events.detect { |ev| ev[0]['name'] == 'test_txn' } - assert_equal txn.guid, txn_segment_event["transactionId"] - assert_nil txn_segment_event["parentId"] + assert_equal txn.guid, txn_segment_event['transactionId'] + assert_nil txn_segment_event['parentId'] - segment_event_a, _, _ = last_span_events.detect { |ev| ev[0]["name"] == "segment_a" } + segment_event_a, _, _ = last_span_events.detect { |ev| ev[0]['name'] == 'segment_a' } - assert_equal txn.guid, segment_event_a["transactionId"] - assert_equal txn_segment.guid, segment_event_a["parentId"] + assert_equal txn.guid, segment_event_a['transactionId'] + assert_equal txn_segment.guid, segment_event_a['parentId'] - segment_event_b, _, _ = last_span_events.detect { |ev| ev[0]["name"] == "segment_b" } + segment_event_b, _, _ = last_span_events.detect { |ev| ev[0]['name'] == 'segment_b' } - assert_equal txn.guid, segment_event_b["transactionId"] - assert_equal segment_a.guid, segment_event_b["parentId"] + assert_equal txn.guid, segment_event_b['transactionId'] + assert_equal segment_a.guid, segment_event_b['parentId'] end def test_entrypoint_attribute_added_to_first_span_only @@ -106,9 +106,9 @@ def test_entrypoint_attribute_added_to_first_span_only last_span_events = NewRelic::Agent.agent.span_event_aggregator.harvest![1] - txn_segment_event, _, _ = last_span_events.detect { |ev| ev[0]["name"] == "test_txn" } + txn_segment_event, _, _ = last_span_events.detect { |ev| ev[0]['name'] == 'test_txn' } - segment_event_a, _, _ = last_span_events.detect { |ev| ev[0]["name"] == "segment_a" } + segment_event_a, _, _ = last_span_events.detect { |ev| ev[0]['name'] == 'segment_a' } assert txn_segment_event.key?('nr.entryPoint') assert txn_segment_event.fetch('nr.entryPoint') diff --git a/test/new_relic/agent/sql_sampler_test.rb b/test/new_relic/agent/sql_sampler_test.rb index 4c2bb60ed2..bbcbec497f 100644 --- a/test/new_relic/agent/sql_sampler_test.rb +++ b/test/new_relic/agent/sql_sampler_test.rb @@ -31,7 +31,7 @@ def create_container def populate_container(sampler, n) n.times do |i| sampler.on_start_transaction(@state) - sampler.notice_sql("SELECT * FROM test#{i}", "Database/test/select", {}, 1, @state) + sampler.notice_sql("SELECT * FROM test#{i}", 'Database/test/select', {}, 1, @state) sampler.on_finishing_transaction(@state, 'txn') end end @@ -53,15 +53,15 @@ def test_on_start_transaction def test_notice_sql_no_transaction assert_nil @sampler.tl_transaction_data - @sampler.notice_sql("select * from test", "Database/test/select", nil, 10, @state) + @sampler.notice_sql('select * from test', 'Database/test/select', nil, 10, @state) end def test_notice_sql @sampler.on_start_transaction(@state) - @sampler.notice_sql("select * from test", "Database/test/select", nil, 1.5, @state) - @sampler.notice_sql("select * from test2", "Database/test2/select", nil, 1.3, @state) + @sampler.notice_sql('select * from test', 'Database/test/select', nil, 1.5, @state) + @sampler.notice_sql('select * from test2', 'Database/test2/select', nil, 1.3, @state) # this sql will not be captured - @sampler.notice_sql("select * from test", "Database/test/select", nil, 0, @state) + @sampler.notice_sql('select * from test', 'Database/test/select', nil, 0, @state) refute_nil @sampler.tl_transaction_data assert_equal 2, @sampler.tl_transaction_data.sql_data.size @@ -70,8 +70,8 @@ def test_notice_sql def test_notice_sql_statement @sampler.on_start_transaction(@state) - sql = "select * from test" - metric_name = "Database/test/select" + sql = 'select * from test' + metric_name = 'Database/test/select' statement = NewRelic::Agent::Database::Statement.new(sql, {:adapter => :mysql}) @sampler.notice_sql_statement(statement, metric_name, 1.5) @@ -85,19 +85,19 @@ def test_notice_sql_statement def test_notice_sql_truncates_query @sampler.on_start_transaction(@state) message = 'a' * 17_000 - @sampler.notice_sql(message, "Database/test/select", nil, 1.5, @state) + @sampler.notice_sql(message, 'Database/test/select', nil, 1.5, @state) assert_equal('a' * 16_381 + '...', @sampler.tl_transaction_data.sql_data[0].sql) end def test_save_slow_sql data = NewRelic::Agent::TransactionSqlData.new - data.set_transaction_info("/c/a", 'guid') - data.set_transaction_name("WebTransaction/Controller/c/a") + data.set_transaction_info('/c/a', 'guid') + data.set_transaction_name('WebTransaction/Controller/c/a') data.sql_data.concat([ - NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test"), "Database/test/select", 1.5), - NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test"), "Database/test/select", 1.2), - NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test2"), "Database/test2/select", 1.1) + NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new('select * from test'), 'Database/test/select', 1.5), + NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new('select * from test'), 'Database/test/select', 1.2), + NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new('select * from test2'), 'Database/test2/select', 1.1) ]) @sampler.save_slow_sql(data) @@ -105,27 +105,27 @@ def test_save_slow_sql end def test_sql_aggregation - query = "select * from test" - slow_sql = NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new(query), "Database/test/select", 1.2) + query = 'select * from test' + slow_sql = NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new(query), 'Database/test/select', 1.2) - sql_trace = NewRelic::Agent::SqlTrace.new(query, slow_sql, "tx_name", "uri") + sql_trace = NewRelic::Agent::SqlTrace.new(query, slow_sql, 'tx_name', 'uri') - sql_trace.aggregate(NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new(query), "Database/test/select", 1.5), "slowest_tx_name", "slow_uri") - sql_trace.aggregate(NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new(query), "Database/test/select", 1.1), "other_tx_name", "uri2") + sql_trace.aggregate(NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new(query), 'Database/test/select', 1.5), 'slowest_tx_name', 'slow_uri') + sql_trace.aggregate(NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new(query), 'Database/test/select', 1.1), 'other_tx_name', 'uri2') assert_equal 3, sql_trace.call_count - assert_equal "slowest_tx_name", sql_trace.path - assert_equal "slow_uri", sql_trace.url + assert_equal 'slowest_tx_name', sql_trace.path + assert_equal 'slow_uri', sql_trace.url assert_in_delta(1.5, sql_trace.max_call_time) end def test_harvest data = NewRelic::Agent::TransactionSqlData.new - data.set_transaction_info("/c/a", 'guid') - data.set_transaction_name("WebTransaction/Controller/c/a") - data.sql_data.concat([NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test"), "Database/test/select", 1.5), - NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test"), "Database/test/select", 1.2), - NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test2"), "Database/test2/select", 1.1)]) + data.set_transaction_info('/c/a', 'guid') + data.set_transaction_name('WebTransaction/Controller/c/a') + data.sql_data.concat([NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new('select * from test'), 'Database/test/select', 1.5), + NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new('select * from test'), 'Database/test/select', 1.2), + NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new('select * from test2'), 'Database/test2/select', 1.1)]) @sampler.save_slow_sql(data) sql_traces = @sampler.harvest! @@ -135,8 +135,8 @@ def test_harvest def test_harvest_should_not_take_more_than_10 data = NewRelic::Agent::TransactionSqlData.new - data.set_transaction_info("/c/a", 'guid') - data.set_transaction_name("WebTransaction/Controller/c/a") + data.set_transaction_info('/c/a', 'guid') + data.set_transaction_name('WebTransaction/Controller/c/a') 15.times do |i| statement = NewRelic::Agent::Database::Statement.new("select * from test#{(i + 97).chr}") data.sql_data << NewRelic::Agent::SlowSql.new(statement, "Database/test#{(i + 97).chr}/select", i) @@ -151,12 +151,12 @@ def test_harvest_should_not_take_more_than_10 def test_harvest_should_aggregate_similar_queries data = NewRelic::Agent::TransactionSqlData.new - data.set_transaction_info("/c/a", 'guid') - data.set_transaction_name("WebTransaction/Controller/c/a") + data.set_transaction_info('/c/a', 'guid') + data.set_transaction_name('WebTransaction/Controller/c/a') queries = [ - NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test where foo in (1, 2) "), "Database/test/select", 1.5), - NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test where foo in (1,2, 3 ,4, 5,6, 'snausage')"), "Database/test/select", 1.2), - NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test2 where foo in (1,2)"), "Database/test2/select", 1.1) + NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new('select * from test where foo in (1, 2) '), 'Database/test/select', 1.5), + NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test where foo in (1,2, 3 ,4, 5,6, 'snausage')"), 'Database/test/select', 1.2), + NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new('select * from test2 where foo in (1,2)'), 'Database/test2/select', 1.1) ] data.sql_data.concat(queries) @sampler.save_slow_sql(data) @@ -167,23 +167,23 @@ def test_harvest_should_aggregate_similar_queries end def test_harvest_should_collect_explain_plans - @connection.expects(:execute).with("EXPLAIN select * from test") \ - .returns(dummy_mysql_explain_result({"header0" => 'foo0', "header1" => 'foo1', "header2" => 'foo2'})) - @connection.expects(:execute).with("EXPLAIN select * from test2") \ - .returns(dummy_mysql_explain_result({"header0" => 'bar0', "header1" => 'bar1', "header2" => 'bar2'})) + @connection.expects(:execute).with('EXPLAIN select * from test') \ + .returns(dummy_mysql_explain_result({'header0' => 'foo0', 'header1' => 'foo1', 'header2' => 'foo2'})) + @connection.expects(:execute).with('EXPLAIN select * from test2') \ + .returns(dummy_mysql_explain_result({'header0' => 'bar0', 'header1' => 'bar1', 'header2' => 'bar2'})) data = NewRelic::Agent::TransactionSqlData.new - data.set_transaction_info("/c/a", 'guid') - data.set_transaction_name("WebTransaction/Controller/c/a") + data.set_transaction_info('/c/a', 'guid') + data.set_transaction_name('WebTransaction/Controller/c/a') explainer = NewRelic::Agent::Instrumentation::ActiveRecord::EXPLAINER config = {:adapter => 'mysql'} queries = [ - NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test", config, explainer), - "Database/test/select", 1.5), - NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test", config, explainer), - "Database/test/select", 1.2), - NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test2", config, explainer), - "Database/test2/select", 1.1) + NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new('select * from test', config, explainer), + 'Database/test/select', 1.5), + NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new('select * from test', config, explainer), + 'Database/test/select', 1.2), + NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new('select * from test2', config, explainer), + 'Database/test2/select', 1.1) ] data.sql_data.concat(queries) @sampler.save_slow_sql(data) @@ -208,11 +208,11 @@ def test_sql_trace_should_include_transaction_guid def test_should_not_collect_explain_plans_when_disabled with_config(:'transaction_tracer.explain_enabled' => false) do data = NewRelic::Agent::TransactionSqlData.new - data.set_transaction_info("/c/a", 'guid') - data.set_transaction_name("WebTransaction/Controller/c/a") + data.set_transaction_info('/c/a', 'guid') + data.set_transaction_name('WebTransaction/Controller/c/a') queries = [ - NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test"), - "Database/test/select", 1.5) + NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new('select * from test'), + 'Database/test/select', 1.5) ] data.sql_data.concat(queries) @sampler.save_slow_sql(data) @@ -232,8 +232,8 @@ def test_should_not_collect_anything_when_record_sql_is_off with_config(settings) do in_transaction do - sql = "SELECT * FROM test" - metric_name = "Database/test/select" + sql = 'SELECT * FROM test' + metric_name = 'Database/test/select' sampler.notice_sql(sql, metric_name, {}, 10) end end @@ -244,25 +244,25 @@ def test_should_not_collect_anything_when_record_sql_is_off end def test_sql_id_fits_in_a_mysql_int_11 - statement = NewRelic::Agent::Database::Statement.new("select * from test") - sql_trace = NewRelic::Agent::SqlTrace.new("select * from test", + statement = NewRelic::Agent::Database::Statement.new('select * from test') + sql_trace = NewRelic::Agent::SqlTrace.new('select * from test', NewRelic::Agent::SlowSql.new(statement, - "Database/test/select", 1.2), - "tx_name", "uri") + 'Database/test/select', 1.2), + 'tx_name', 'uri') - assert(-2147483648 <= sql_trace.sql_id, "sql_id too small") - assert(2147483647 >= sql_trace.sql_id, "sql_id too large") + assert(-2147483648 <= sql_trace.sql_id, 'sql_id too small') + assert(2147483647 >= sql_trace.sql_id, 'sql_id too large') end def test_sends_obfuscated_queries_when_configured with_config(:'transaction_tracer.record_sql' => 'obfuscated') do data = NewRelic::Agent::TransactionSqlData.new - data.set_transaction_info("/c/a", 'guid') - data.set_transaction_name("WebTransaction/Controller/c/a") + data.set_transaction_info('/c/a', 'guid') + data.set_transaction_name('WebTransaction/Controller/c/a') data.sql_data.concat([NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test where foo = 'bar'"), - "Database/test/select", 1.5), - NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test where foo in (1,2,3,4,5)"), - "Database/test/select", 1.2)]) + 'Database/test/select', 1.5), + NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new('select * from test where foo in (1,2,3,4,5)'), + 'Database/test/select', 1.2)]) @sampler.save_slow_sql(data) sql_traces = @sampler.harvest!.sort_by(&:total_call_time).reverse @@ -278,12 +278,12 @@ def test_sends_obfuscated_queries_when_configured_via_slow_sql_settings } with_config(settings) do data = NewRelic::Agent::TransactionSqlData.new - data.set_transaction_info("/c/a", 'guid') - data.set_transaction_name("WebTransaction/Controller/c/a") + data.set_transaction_info('/c/a', 'guid') + data.set_transaction_name('WebTransaction/Controller/c/a') data.sql_data.concat([NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test where foo = 'bar'"), - "Database/test/select", 1.5), - NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test where foo in (1,2,3,4,5)"), - "Database/test/select", 1.2)]) + 'Database/test/select', 1.5), + NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new('select * from test where foo in (1,2,3,4,5)'), + 'Database/test/select', 1.2)]) @sampler.save_slow_sql(data) sql_traces = @sampler.harvest!.sort_by(&:total_call_time).reverse @@ -298,7 +298,7 @@ def test_does_not_over_obfuscate_queries_for_postgres in_transaction do sql = %Q[INSERT INTO "items" ("name", "price") VALUES ('continuum transfunctioner', 100000) RETURNING "id"] - sampler.notice_sql(sql, "Database/test/insert", {:adapter => "postgres"}, 1.23) + sampler.notice_sql(sql, 'Database/test/insert', {:adapter => 'postgres'}, 1.23) end sql_traces = sampler.harvest! @@ -308,8 +308,8 @@ def test_does_not_over_obfuscate_queries_for_postgres def test_takes_slowest_samples data = NewRelic::Agent::TransactionSqlData.new - data.set_transaction_info("/c/a", 'guid') - data.set_transaction_name("WebTransaction/Controller/c/a") + data.set_transaction_info('/c/a', 'guid') + data.set_transaction_name('WebTransaction/Controller/c/a') count = NewRelic::Agent::SqlSampler::MAX_SAMPLES * 2 durations = (0...count).to_a.shuffle @@ -330,8 +330,8 @@ def test_can_directly_marshal_traces_for_pipe_transmittal with_config(:'transaction_tracer.explain_enabled' => false) do data = NewRelic::Agent::TransactionSqlData.new explainer = NewRelic::Agent::Instrumentation::ActiveRecord::EXPLAINER - data.sql_data.concat([NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test", {}, explainer), - "Database/test/select", 1.5)]) + data.sql_data.concat([NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new('select * from test', {}, explainer), + 'Database/test/select', 1.5)]) @sampler.save_slow_sql(data) sql_traces = @sampler.harvest! @@ -342,10 +342,10 @@ def test_can_directly_marshal_traces_for_pipe_transmittal def test_to_collector_array with_config(:'transaction_tracer.explain_enabled' => false) do data = NewRelic::Agent::TransactionSqlData.new - data.set_transaction_info("/c/a", 'guid') - data.set_transaction_name("WebTransaction/Controller/c/a") - data.sql_data.concat([NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new("select * from test"), - "Database/test/select", 1.5)]) + data.set_transaction_info('/c/a', 'guid') + data.set_transaction_name('WebTransaction/Controller/c/a') + data.sql_data.concat([NewRelic::Agent::SlowSql.new(NewRelic::Agent::Database::Statement.new('select * from test'), + 'Database/test/select', 1.5)]) @sampler.save_slow_sql(data) sql_traces = @sampler.harvest! @@ -361,69 +361,69 @@ def test_to_collector_array end def test_to_collector_array_with_bad_values - statement = NewRelic::Agent::Database::Statement.new("query") - slow = NewRelic::Agent::SlowSql.new(statement, "transaction", Rational(12, 1)) - trace = NewRelic::Agent::SqlTrace.new("query", slow, "path", "uri") + statement = NewRelic::Agent::Database::Statement.new('query') + slow = NewRelic::Agent::SlowSql.new(statement, 'transaction', Rational(12, 1)) + trace = NewRelic::Agent::SqlTrace.new('query', slow, 'path', 'uri') trace.call_count = Rational(10, 1) - trace.instance_variable_set(:@sql_id, "1234") + trace.instance_variable_set(:@sql_id, '1234') marshaller = NewRelic::Agent::NewRelicService::JsonMarshaller.new params = "eJyrrgUAAXUA+Q==\n" - expected = ["path", "uri", 1234, "query", "transaction", + expected = ['path', 'uri', 1234, 'query', 'transaction', 10, 12000, 12000, 12000, params] assert_equal expected, trace.to_collector_array(marshaller.default_encoder) end def test_to_collector_array_with_database_instance_params - statement = NewRelic::Agent::Database::Statement.new("query", nil, nil, nil, nil, "jonan.gummy_planet", "1337", "pizza_cube") - slow = NewRelic::Agent::SlowSql.new(statement, "transaction", 1.0) - trace = NewRelic::Agent::SqlTrace.new("query", slow, "path", "uri") + statement = NewRelic::Agent::Database::Statement.new('query', nil, nil, nil, nil, 'jonan.gummy_planet', '1337', 'pizza_cube') + slow = NewRelic::Agent::SlowSql.new(statement, 'transaction', 1.0) + trace = NewRelic::Agent::SqlTrace.new('query', slow, 'path', 'uri') encoder = NewRelic::Agent::NewRelicService::Encoders::Identity params = trace.to_collector_array(encoder).last - assert_equal "jonan.gummy_planet", params[:host] - assert_equal "1337", params[:port_path_or_id] - assert_equal "pizza_cube", params[:database_name] + assert_equal 'jonan.gummy_planet', params[:host] + assert_equal '1337', params[:port_path_or_id] + assert_equal 'pizza_cube', params[:database_name] end def test_to_collector_array_with_instance_reporting_disabled with_config(:'datastore_tracer.instance_reporting.enabled' => false) do - statement = NewRelic::Agent::Database::Statement.new("query", nil, nil, nil, nil, "jonan.gummy_planet", "1337", "pizza_cube") - slow = NewRelic::Agent::SlowSql.new(statement, "transaction", 1.0) - trace = NewRelic::Agent::SqlTrace.new("query", slow, "path", "uri") + statement = NewRelic::Agent::Database::Statement.new('query', nil, nil, nil, nil, 'jonan.gummy_planet', '1337', 'pizza_cube') + slow = NewRelic::Agent::SlowSql.new(statement, 'transaction', 1.0) + trace = NewRelic::Agent::SqlTrace.new('query', slow, 'path', 'uri') encoder = NewRelic::Agent::NewRelicService::Encoders::Identity params = trace.to_collector_array(encoder).last refute params.key?(:host) refute params.key?(:port_path_or_id) - assert_equal "pizza_cube", params[:database_name] + assert_equal 'pizza_cube', params[:database_name] end end def test_to_collector_array_with_database_name_reporting_disabled with_config(:'datastore_tracer.database_name_reporting.enabled' => false) do - statement = NewRelic::Agent::Database::Statement.new("query", nil, nil, nil, nil, "jonan.gummy_planet", "1337", "pizza_cube") - slow = NewRelic::Agent::SlowSql.new(statement, "transaction", 1.0) - trace = NewRelic::Agent::SqlTrace.new("query", slow, "path", "uri") + statement = NewRelic::Agent::Database::Statement.new('query', nil, nil, nil, nil, 'jonan.gummy_planet', '1337', 'pizza_cube') + slow = NewRelic::Agent::SlowSql.new(statement, 'transaction', 1.0) + trace = NewRelic::Agent::SqlTrace.new('query', slow, 'path', 'uri') encoder = NewRelic::Agent::NewRelicService::Encoders::Identity params = trace.to_collector_array(encoder).last - assert_equal "jonan.gummy_planet", params[:host] - assert_equal "1337", params[:port_path_or_id] + assert_equal 'jonan.gummy_planet', params[:host] + assert_equal '1337', params[:port_path_or_id] refute params.key?(:database_name) end end def test_merge_without_existing_trace - query = "select * from test" + query = 'select * from test' statement = NewRelic::Agent::Database::Statement.new(query, {}) - slow_sql = NewRelic::Agent::SlowSql.new(statement, "Database/test/select", 1) - trace = NewRelic::Agent::SqlTrace.new(query, slow_sql, "txn_name", "uri") + slow_sql = NewRelic::Agent::SlowSql.new(statement, 'Database/test/select', 1) + trace = NewRelic::Agent::SqlTrace.new(query, slow_sql, 'txn_name', 'uri') @sampler.merge!([trace]) @@ -431,13 +431,13 @@ def test_merge_without_existing_trace end def test_merge_with_existing_trace - query = "select * from test" + query = 'select * from test' statement = NewRelic::Agent::Database::Statement.new(query, {}) - slow_sql0 = NewRelic::Agent::SlowSql.new(statement, "Database/test/select", 1) - slow_sql1 = NewRelic::Agent::SlowSql.new(statement, "Database/test/select", 2) + slow_sql0 = NewRelic::Agent::SlowSql.new(statement, 'Database/test/select', 1) + slow_sql1 = NewRelic::Agent::SlowSql.new(statement, 'Database/test/select', 2) - trace0 = NewRelic::Agent::SqlTrace.new(query, slow_sql0, "txn_name", "uri") - trace1 = NewRelic::Agent::SqlTrace.new(query, slow_sql1, "txn_name", "uri") + trace0 = NewRelic::Agent::SqlTrace.new(query, slow_sql0, 'txn_name', 'uri') + trace1 = NewRelic::Agent::SqlTrace.new(query, slow_sql1, 'txn_name', 'uri') @sampler.merge!([trace0]) @sampler.merge!([trace1]) @@ -450,13 +450,13 @@ def test_merge_with_existing_trace def test_on_finishing_transaction_with_busted_transaction_state_does_not_crash state = NewRelic::Agent::Tracer.state - @sampler.on_finishing_transaction(state, "whatever") + @sampler.on_finishing_transaction(state, 'whatever') end def test_caps_collection_of_unique_statements data = NewRelic::Agent::TransactionSqlData.new - data.set_transaction_info("/c/a", 'guid') - data.set_transaction_name("WebTransaction/Controller/c/a") + data.set_transaction_info('/c/a', 'guid') + data.set_transaction_name('WebTransaction/Controller/c/a') count = NewRelic::Agent::SqlSampler::MAX_SAMPLES + 1 count.times do |i| @@ -473,7 +473,7 @@ def test_record_intrinsics_on_slow_sql payload = nil NewRelic::Agent::DistributedTracePayload.stubs(:connected?).returns(true) with_config({:'distributed_tracing.enabled' => true, - :primary_application_id => "46954", + :primary_application_id => '46954', :trusted_account_key => 'trust_this!', :account_id => 190, :'slow_sql.explain_threshold' => -1}) do @@ -493,16 +493,16 @@ def test_record_intrinsics_on_slow_sql segment = nil txn = nil sampled = nil - txn = in_web_transaction("test_txn") do |t| + txn = in_web_transaction('test_txn') do |t| t.sampled = true t.distributed_tracer.accept_distributed_trace_payload(payload.text) sampled = t.sampled? segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "insert", - collection: "Blog" + product: 'SQLite', + operation: 'insert', + collection: 'Blog' ) - segment.notice_sql("SELECT * FROM Blog") + segment.notice_sql('SELECT * FROM Blog') segment.finish end diff --git a/test/new_relic/agent/stats_engine/gc_profiler_test.rb b/test/new_relic/agent/stats_engine/gc_profiler_test.rb index af4fb3ad86..9a8918f185 100644 --- a/test/new_relic/agent/stats_engine/gc_profiler_test.rb +++ b/test/new_relic/agent/stats_engine/gc_profiler_test.rb @@ -78,7 +78,7 @@ def test_gc_profiler_clear_does_not_reset_count GC::Profiler.enable count_before_allocations = GC.count - 100000.times { String.new } + 100000.times { +'' } GC.start count_after_allocations = GC.count GC::Profiler.clear diff --git a/test/new_relic/agent/stats_engine_test.rb b/test/new_relic/agent/stats_engine_test.rb index e60bdec965..98276fa955 100644 --- a/test/new_relic/agent/stats_engine_test.rb +++ b/test/new_relic/agent/stats_engine_test.rb @@ -270,13 +270,13 @@ def test_record_scoped_and_unscoped_metrics_records_unscoped_if_not_in_txn def test_harvest @engine.clear_stats - @engine.tl_record_unscoped_metrics("a", 10) - @engine.tl_record_unscoped_metrics("c", 1) - @engine.tl_record_unscoped_metrics("c", 3) + @engine.tl_record_unscoped_metrics('a', 10) + @engine.tl_record_unscoped_metrics('c', 1) + @engine.tl_record_unscoped_metrics('c', 3) assert_metrics_recorded({ - "a" => {:call_count => 1, :total_call_time => 10}, - "c" => {:call_count => 2, :total_call_time => 4} + 'a' => {:call_count => 1, :total_call_time => 10}, + 'c' => {:call_count => 2, :total_call_time => 4} }) harvested = @engine.harvest!.to_h @@ -333,30 +333,30 @@ def test_apply_rules_to_metric_data_respects_ignore_rules end def test_harvest_with_merge - @engine.tl_record_unscoped_metrics("a", 1) + @engine.tl_record_unscoped_metrics('a', 1) - assert_metrics_recorded "a" => {:call_count => 1, :total_call_time => 1} + assert_metrics_recorded 'a' => {:call_count => 1, :total_call_time => 1} harvest = @engine.harvest! - assert_metrics_not_recorded "a" + assert_metrics_not_recorded 'a' - @engine.tl_record_unscoped_metrics("a", 2) + @engine.tl_record_unscoped_metrics('a', 2) - assert_metrics_recorded "a" => {:call_count => 1, :total_call_time => 2} + assert_metrics_recorded 'a' => {:call_count => 1, :total_call_time => 2} # this should merge the contents of the previous harvest, # so the stats for metric "a" should have 2 data points @engine.merge!(harvest) harvest = @engine.harvest! - stats = harvest[NewRelic::MetricSpec.new("a")] + stats = harvest[NewRelic::MetricSpec.new('a')] assert_equal 2, stats.call_count assert_equal 3, stats.total_call_time end def test_merge_merges - @engine.tl_record_unscoped_metrics("foo", 1) + @engine.tl_record_unscoped_metrics('foo', 1) other_stats_hash = NewRelic::Agent::StatsHash.new() other_stats_hash.record(NewRelic::MetricSpec.new('foo'), 1) diff --git a/test/new_relic/agent/stats_test.rb b/test/new_relic/agent/stats_test.rb index c1f9f706a4..fb1d578f73 100644 --- a/test/new_relic/agent/stats_test.rb +++ b/test/new_relic/agent/stats_test.rb @@ -64,7 +64,7 @@ def test_to_s s1 = NewRelic::Agent::Stats.new s1.trace_call(10) - assert_equal("[ 1 calls 10.0000s / 10.0000s ex]", s1.to_s) + assert_equal('[ 1 calls 10.0000s / 10.0000s ex]', s1.to_s) end def test_apdex_recording @@ -161,7 +161,7 @@ def test_sum_of_squares_merge s3 = s1.merge(s2) assert_equal(s1.sum_of_squares, 4 * 4 + 7 * 7) - assert_equal(s3.sum_of_squares, 4 * 4 + 7 * 7 + 13 * 13 + 16 * 16, "check sum of squares") + assert_equal(s3.sum_of_squares, 4 * 4 + 7 * 7 + 13 * 13 + 16 * 16, 'check sum of squares') end def test_to_json_enforces_float_values diff --git a/test/new_relic/agent/synthetics_event_aggregator_test.rb b/test/new_relic/agent/synthetics_event_aggregator_test.rb index 952aab6531..c563beb07f 100644 --- a/test/new_relic/agent/synthetics_event_aggregator_test.rb +++ b/test/new_relic/agent/synthetics_event_aggregator_test.rb @@ -49,13 +49,13 @@ def aggregator end def name_for(event) - event[0]["name"] + event[0]['name'] end include NewRelic::CommonAggregatorTests def test_includes_custom_attributes - attrs = {"user" => "Wes Mantooth", "channel" => 9} + attrs = {'user' => 'Wes Mantooth', 'channel' => 9} attributes.merge_custom_attributes(attrs) @@ -109,14 +109,14 @@ def test_lower_priority_events_discarded_in_favor_higher_priority_events end def test_includes_agent_attributes - attributes.add_agent_attribute(:'request.headers.referer', "http://blog.site/home", AttributeFilter::DST_TRANSACTION_EVENTS) + attributes.add_agent_attribute(:'request.headers.referer', 'http://blog.site/home', AttributeFilter::DST_TRANSACTION_EVENTS) attributes.add_agent_attribute(:'http.statusCode', 200, AttributeFilter::DST_TRANSACTION_EVENTS) generate_request _, _, agent_attrs = last_synthetics_event - expected = {:"request.headers.referer" => "http://blog.site/home", :'http.statusCode' => 200} + expected = {:"request.headers.referer" => 'http://blog.site/home', :'http.statusCode' => 200} assert_equal expected, agent_attrs end @@ -127,7 +127,7 @@ def test_aggregator_defers_synthetics_event_creation aggregator.expects(:create_event).never payload = { - :name => "Doesnt/matter", + :name => 'Doesnt/matter', :synthetics_resource_id => 100, :priority => 0.123 } diff --git a/test/new_relic/agent/system_info_test.rb b/test/new_relic/agent/system_info_test.rb index 64521a26d9..150afdf76e 100644 --- a/test/new_relic/agent/system_info_test.rb +++ b/test/new_relic/agent/system_info_test.rb @@ -12,7 +12,7 @@ def setup @sysinfo.clear_processor_info end - each_cross_agent_test :dir => 'proc_cpuinfo', :pattern => "*.txt" do |file| + each_cross_agent_test :dir => 'proc_cpuinfo', :pattern => '*.txt' do |file| if File.basename(file) =~ /^((\d+|X)pack_(\d+|X)core_(\d+|X)logical).txt$/ test_name = "test_#{$1}" @@ -82,7 +82,7 @@ def setup if test_case['expectedMetrics'] assert_metrics_recorded test_case['expectedMetrics'] else - refute_metrics_recorded "Supportability/utilization/docker/error" + refute_metrics_recorded 'Supportability/utilization/docker/error' end end end @@ -106,14 +106,14 @@ def setup end def test_proc_meminfo_unparsable - assert_nil @sysinfo.parse_linux_meminfo_in_mib("") + assert_nil @sysinfo.parse_linux_meminfo_in_mib('') end def test_ram_in_mb_nil_when_proc_meminfo_unreadable - NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns("linux") + NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns('linux') NewRelic::Agent::SystemInfo.expects(:proc_try_read).with('/proc/meminfo').returns(nil) - assert_nil NewRelic::Agent::SystemInfo.ram_in_mib, "Expected ram_in_mib to be nil" + assert_nil NewRelic::Agent::SystemInfo.ram_in_mib, 'Expected ram_in_mib to be nil' end def test_processor_info_returns_if_set @@ -214,18 +214,18 @@ def test_processor_info_darwin_fallback_logicalcpu end def test_processor_info_linux_is_cpuinfo - NewRelic::Agent::SystemInfo.stub(:proc_try_read, "T. Rex") do - NewRelic::Agent::SystemInfo.stub(:parse_cpuinfo, "Rawr") do + NewRelic::Agent::SystemInfo.stub(:proc_try_read, 'T. Rex') do + NewRelic::Agent::SystemInfo.stub(:parse_cpuinfo, 'Rawr') do NewRelic::Agent::SystemInfo.processor_info_linux - assert_equal "Rawr", NewRelic::Agent::SystemInfo.instance_variable_get(:@processor_info) + assert_equal 'Rawr', NewRelic::Agent::SystemInfo.instance_variable_get(:@processor_info) end end end def test_processor_info_linux_is_empty NewRelic::Agent::SystemInfo.stub(:proc_try_read, nil) do - NewRelic::Agent::SystemInfo.stub(:parse_cpuinfo, "Rawr") do + NewRelic::Agent::SystemInfo.stub(:parse_cpuinfo, 'Rawr') do NewRelic::Agent::SystemInfo.processor_info_linux assert_equal NewRelic::EMPTY_HASH, NewRelic::Agent::SystemInfo.instance_variable_get(:@processor_info) @@ -265,37 +265,37 @@ def test_processor_info_os_unknown end def test_system_info_darwin_predicate - NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns("darwin13") + NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns('darwin13') - assert_predicate NewRelic::Agent::SystemInfo, :darwin?, "Expected OS to match darwin" + assert_predicate NewRelic::Agent::SystemInfo, :darwin?, 'Expected OS to match darwin' - NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns("linux") + NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns('linux') - refute NewRelic::Agent::SystemInfo.darwin?, "Did not expect OS to match darwin" + refute NewRelic::Agent::SystemInfo.darwin?, 'Did not expect OS to match darwin' end def test_system_info_linux_predicate - NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns("linux") + NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns('linux') - assert_predicate NewRelic::Agent::SystemInfo, :linux?, "Expected OS to match linux" + assert_predicate NewRelic::Agent::SystemInfo, :linux?, 'Expected OS to match linux' - NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns("darwin13") + NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns('darwin13') - refute NewRelic::Agent::SystemInfo.linux?, "Did not expect OS to match linux" + refute NewRelic::Agent::SystemInfo.linux?, 'Did not expect OS to match linux' end def test_system_info_bsd_predicate - NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns("freebsd") + NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns('freebsd') - assert_predicate NewRelic::Agent::SystemInfo, :bsd?, "Expected OS to match bsd" + assert_predicate NewRelic::Agent::SystemInfo, :bsd?, 'Expected OS to match bsd' - NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns("darwin13") + NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns('darwin13') - refute NewRelic::Agent::SystemInfo.bsd?, "Did not expect OS to match bsd" + refute NewRelic::Agent::SystemInfo.bsd?, 'Did not expect OS to match bsd' end def test_supportability_metric_recorded_when_docker_id_unavailable - NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns("linux") + NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns('linux') cgroup_info = File.read(File.join(cross_agent_tests_dir, 'docker_container_id', 'invalid-length.txt')) NewRelic::Agent::SystemInfo.expects(:proc_try_read).with('/proc/self/cgroup').returns(cgroup_info) @@ -303,68 +303,68 @@ def test_supportability_metric_recorded_when_docker_id_unavailable assert_nil NewRelic::Agent::SystemInfo.docker_container_id end - assert_metrics_recorded "Supportability/utilization/docker/error" + assert_metrics_recorded 'Supportability/utilization/docker/error' end - VALID_UUID = String.new('eb26a240-5535-0135-e727-745c89b5accd') + VALID_UUID = +'eb26a240-5535-0135-e727-745c89b5accd' def test_valid_boot_id - NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns("linux") + NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns('linux') NewRelic::Agent::SystemInfo.expects(:proc_try_read).with('/proc/sys/kernel/random/boot_id').returns(VALID_UUID) assert_equal VALID_UUID, NewRelic::Agent::SystemInfo.boot_id - assert_metrics_not_recorded "Supportability/utilization/boot_id/error" + assert_metrics_not_recorded 'Supportability/utilization/boot_id/error' end def test_invalid_length_ascii_boot_id - NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns("linux") + NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns('linux') test_boot_id = VALID_UUID * 2 NewRelic::Agent::SystemInfo.expects(:proc_try_read).with('/proc/sys/kernel/random/boot_id').returns(test_boot_id) assert_equal test_boot_id, NewRelic::Agent::SystemInfo.boot_id - assert_metrics_recorded "Supportability/utilization/boot_id/error" + assert_metrics_recorded 'Supportability/utilization/boot_id/error' end def test_truncated_invalid_length_ascii_boot_id - NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns("linux") + NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns('linux') test_boot_id = VALID_UUID * 8 NewRelic::Agent::SystemInfo.expects(:proc_try_read).with('/proc/sys/kernel/random/boot_id').returns(test_boot_id) assert_equal test_boot_id[0, 128], NewRelic::Agent::SystemInfo.boot_id - assert_metrics_recorded "Supportability/utilization/boot_id/error" + assert_metrics_recorded 'Supportability/utilization/boot_id/error' end def test_non_ascii_boot_id - NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns("linux") - panda = String.new('🐼') + NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns('linux') + panda = +'🐼' NewRelic::Agent::SystemInfo.expects(:proc_try_read).with('/proc/sys/kernel/random/boot_id').returns(panda) assert_nil NewRelic::Agent::SystemInfo.boot_id - assert_metrics_recorded "Supportability/utilization/boot_id/error" + assert_metrics_recorded 'Supportability/utilization/boot_id/error' end def test_empty_boot_id - NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns("linux") - empty = String.new('') + NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns('linux') + empty = +'' NewRelic::Agent::SystemInfo.expects(:proc_try_read).with('/proc/sys/kernel/random/boot_id').returns(empty) assert_nil NewRelic::Agent::SystemInfo.boot_id - assert_metrics_recorded "Supportability/utilization/boot_id/error" + assert_metrics_recorded 'Supportability/utilization/boot_id/error' end def test_nil_boot_id_on_not_linux - NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns("darwin13") + NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns('darwin13') assert_nil NewRelic::Agent::SystemInfo.boot_id - NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns("freebsd") + NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns('freebsd') assert_nil NewRelic::Agent::SystemInfo.boot_id - NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns("solaris") + NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns('solaris') assert_nil NewRelic::Agent::SystemInfo.boot_id - assert_metrics_not_recorded "Supportability/utilization/boot_id/error" + assert_metrics_not_recorded 'Supportability/utilization/boot_id/error' end end diff --git a/test/new_relic/agent/threading/agent_thread_test.rb b/test/new_relic/agent/threading/agent_thread_test.rb index 5c78385184..54110dc1a2 100644 --- a/test/new_relic/agent/threading/agent_thread_test.rb +++ b/test/new_relic/agent/threading/agent_thread_test.rb @@ -8,21 +8,21 @@ module NewRelic::Agent::Threading class AgentThreadTest < Minitest::Test def test_sets_label - t = AgentThread.create("labelled") {} + t = AgentThread.create('labelled') {} - assert_equal "labelled", t[:newrelic_label] + assert_equal 'labelled', t[:newrelic_label] t.join end def test_bucket_thread_as_agent_when_profiling - t = AgentThread.create("labelled") {} + t = AgentThread.create('labelled') {} assert_equal :agent, AgentThread.bucket_thread(t, true) t.join end def test_bucket_thread_as_agent_when_not_profiling - t = AgentThread.create("labelled") {} + t = AgentThread.create('labelled') {} assert_equal :ignore, AgentThread.bucket_thread(t, false) t.join @@ -86,16 +86,16 @@ def test_bucket_thread_as_other def test_runs_block called = false - t = AgentThread.create("labelled") { called = true } + t = AgentThread.create('labelled') { called = true } t.join assert called end def test_standard_error_is_caught - expects_logging(:error, includes("exited"), any_parameters) + expects_logging(:error, includes('exited'), any_parameters) - t = AgentThread.create("fail") { raise "O_o" } + t = AgentThread.create('fail') { raise 'O_o' } t.join assert_thread_completed(t) @@ -103,11 +103,11 @@ def test_standard_error_is_caught def test_exception_is_reraised with_thread_report_on_exception_disabled do - expects_logging(:error, includes("exited"), any_parameters) + expects_logging(:error, includes('exited'), any_parameters) assert_raises(Exception) do begin - t = AgentThread.create("fail") { raise Exception.new } + t = AgentThread.create('fail') { raise Exception.new } t.join ensure assert_thread_died_from_exception(t) @@ -168,8 +168,8 @@ def test_scrub_backtrace_handles_nil_backtrace def test_agent_thread_creation_ignores_current_transaction with_config(:'instrumentation.thread.tracing' => true) do in_transaction do |txn| - t = AgentThread.create("label") do - refute ::Thread.current[:newrelic_tracer_state] && ::Thread.current[:newrelic_tracer_state].current_transaction, "Agent thread should not contain a current transaction" + t = AgentThread.create('label') do + refute ::Thread.current[:newrelic_tracer_state] && ::Thread.current[:newrelic_tracer_state].current_transaction, 'Agent thread should not contain a current transaction' end t.join end diff --git a/test/new_relic/agent/threading/backtrace_node_test.rb b/test/new_relic/agent/threading/backtrace_node_test.rb index 159583db35..4ac31c90df 100644 --- a/test/new_relic/agent/threading/backtrace_node_test.rb +++ b/test/new_relic/agent/threading/backtrace_node_test.rb @@ -19,7 +19,7 @@ def setup end def assert_backtrace_trees_equal(a, b, original_a = a, original_b = b) - message = String.new("Thread profiles did not match.\n\n") + message = +"Thread profiles did not match.\n\n" message << "Expected tree:\n#{original_a.dump_string}\n\n" message << "Actual tree:\n#{original_b.dump_string}\n" @@ -32,7 +32,7 @@ def assert_backtrace_trees_equal(a, b, original_a = a, original_b = b) def create_node(frame, parent = nil, runnable_count = 0) node = BacktraceNode.new(frame) - parent.add_child_unless_present(node) if parent + parent&.add_child_unless_present(node) node.runnable_count = runnable_count node end @@ -48,7 +48,7 @@ def test_single_node_converts_to_array convert_nodes_to_array([node]) assert_equal([ - ["irb.rb", "catch", 69], + ['irb.rb', 'catch', 69], 0, 0, [] ], @@ -63,7 +63,7 @@ def test_multiple_nodes_converts_to_array convert_nodes_to_array([node, child_node]) assert_equal([ - ["irb.rb", "catch", 69], + ['irb.rb', 'catch', 69], 0, 0, [ [ @@ -82,7 +82,7 @@ def test_nodes_without_line_numbers convert_nodes_to_array([node]) assert_equal([ - ["transaction_sample_buffer.rb", "visit_node", -1], + ['transaction_sample_buffer.rb', 'visit_node', -1], 0, 0, [] ], @@ -91,12 +91,12 @@ def test_nodes_without_line_numbers def test_gracefully_handle_bad_values_in_to_array node = BacktraceNode.new(SINGLE_LINE) - node.stubs(:parse_backtrace_frame).returns(["irb.rb", "catch", "blarg"]) + node.stubs(:parse_backtrace_frame).returns(['irb.rb', 'catch', 'blarg']) node.runnable_count = Rational(10, 1) convert_nodes_to_array([node]) assert_equal([ - ["irb.rb", "catch", 0], + ['irb.rb', 'catch', 0], 10, 0, [] ], diff --git a/test/new_relic/agent/threading/backtrace_service_test.rb b/test/new_relic/agent/threading/backtrace_service_test.rb index 51090b6bfa..e372df25e4 100644 --- a/test/new_relic/agent/threading/backtrace_service_test.rb +++ b/test/new_relic/agent/threading/backtrace_service_test.rb @@ -138,7 +138,7 @@ def test_harvest_returns_nil_if_never_subscribed def test_poll_forwards_backtraces_to_subscribed_profiles fake_worker_loop(@service) - bt0, bt1 = ["bt0"], ["bt1"] + bt0, bt1 = ['bt0'], ['bt1'] thread0 = fake_thread(:request, bt0) thread1 = fake_thread(:differenter_request, bt1) @@ -165,7 +165,7 @@ def test_poll_scrubs_backtraces_before_forwarding_to_profiles fake_worker_loop(@service) scrubbed_backtrace = [] - thread = fake_thread(:agent, ["trace"]) + thread = fake_thread(:agent, ['trace']) AgentThread.stubs(:scrub_backtrace) .with(thread, any_parameters) @@ -457,7 +457,7 @@ def test_buffer_backtrace_for_thread_should_limit_buffer_size @service.buffer_backtrace_for_thread(thread, Process.clock_gettime(Process::CLOCK_REALTIME), stub, :request) assert_equal BacktraceService::MAX_BUFFER_LENGTH, @service.buffer[thread].length - assert_metrics_recorded(["Supportability/ThreadProfiler/DroppedBacktraces"]) + assert_metrics_recorded(['Supportability/ThreadProfiler/DroppedBacktraces']) end def test_dynamically_adjusts_worker_loop_period diff --git a/test/new_relic/agent/tracer_test.rb b/test/new_relic/agent/tracer_test.rb index 9a6e8b0211..b8b3321cac 100644 --- a/test/new_relic/agent/tracer_test.rb +++ b/test/new_relic/agent/tracer_test.rb @@ -111,7 +111,7 @@ def test_in_transaction_missing_category def test_in_transaction_with_early_failure yielded = false - NewRelic::Agent::Transaction.any_instance.stubs(:start).raises("Boom") + NewRelic::Agent::Transaction.any_instance.stubs(:start).raises('Boom') NewRelic::Agent::Tracer.in_transaction(name: 'test', category: :other) do yielded = true end @@ -123,7 +123,7 @@ def test_in_transaction_with_early_failure def test_in_transaction_with_late_failure yielded = false - NewRelic::Agent::Transaction.any_instance.stubs(:commit!).raises("Boom") + NewRelic::Agent::Transaction.any_instance.stubs(:commit!).raises('Boom') NewRelic::Agent::Tracer.in_transaction(name: 'test', category: :other) do yielded = true end @@ -135,17 +135,17 @@ def test_in_transaction_with_late_failure def test_in_transaction_notices_errors assert_raises RuntimeError do NewRelic::Agent::Tracer.in_transaction(name: 'test', category: :other) do - raise "O_o" + raise 'O_o' end end - assert_metrics_recorded(["Errors/all"]) + assert_metrics_recorded(['Errors/all']) end def test_start_transaction_without_one_already_existing assert_nil Tracer.current_transaction - txn = Tracer.start_transaction(name: "Controller/Blogs/index", + txn = Tracer.start_transaction(name: 'Controller/Blogs/index', category: :controller) assert_equal txn, Tracer.current_transaction @@ -159,7 +159,7 @@ def test_start_transaction_returns_current_if_already_in_progress in_transaction do |txn1| refute_nil Tracer.current_transaction - txn2 = Tracer.start_transaction(name: "Controller/Blogs/index", + txn2 = Tracer.start_transaction(name: 'Controller/Blogs/index', category: :controller) assert_equal txn2, txn1 @@ -171,7 +171,7 @@ def test_start_transaction_or_segment_without_active_txn assert_nil Tracer.current_transaction finishable = Tracer.start_transaction_or_segment( - name: "Controller/Blogs/index", + name: 'Controller/Blogs/index', category: :controller ) @@ -185,7 +185,7 @@ def test_start_transaction_or_segment_without_active_txn def test_start_transaction_or_segment_with_active_txn in_transaction do |txn| finishable = Tracer.start_transaction_or_segment( - name: "Middleware/Rack/MyMiddleWare/call", + name: 'Middleware/Rack/MyMiddleWare/call', category: :middleware ) @@ -202,21 +202,21 @@ def test_start_transaction_or_segment_with_active_txn def test_start_transaction_or_segment_multiple_calls f1 = Tracer.start_transaction_or_segment( - name: "Controller/Rack/Test::App/call", + name: 'Controller/Rack/Test::App/call', category: :rack ) f2 = Tracer.start_transaction_or_segment( - name: "Middleware/Rack/MyMiddleware/call", + name: 'Middleware/Rack/MyMiddleware/call', category: :middleware ) f3 = Tracer.start_transaction_or_segment( - name: "Controller/blogs/index", + name: 'Controller/blogs/index', category: :controller ) - f4 = Tracer.start_segment(name: "Custom/MyClass/my_meth") + f4 = Tracer.start_segment(name: 'Custom/MyClass/my_meth') f4.finish f3.finish @@ -224,31 +224,31 @@ def test_start_transaction_or_segment_multiple_calls f1.finish assert_metrics_recorded [ - ["Nested/Controller/Rack/Test::App/call", "Controller/blogs/index"], - ["Middleware/Rack/MyMiddleware/call", "Controller/blogs/index"], - ["Nested/Controller/blogs/index", "Controller/blogs/index"], - ["Custom/MyClass/my_meth", "Controller/blogs/index"], - "Controller/blogs/index", - "Nested/Controller/Rack/Test::App/call", - "Middleware/Rack/MyMiddleware/call", - "Nested/Controller/blogs/index", - "Custom/MyClass/my_meth" + ['Nested/Controller/Rack/Test::App/call', 'Controller/blogs/index'], + ['Middleware/Rack/MyMiddleware/call', 'Controller/blogs/index'], + ['Nested/Controller/blogs/index', 'Controller/blogs/index'], + ['Custom/MyClass/my_meth', 'Controller/blogs/index'], + 'Controller/blogs/index', + 'Nested/Controller/Rack/Test::App/call', + 'Middleware/Rack/MyMiddleware/call', + 'Nested/Controller/blogs/index', + 'Custom/MyClass/my_meth' ] end def test_start_transaction_or_segment_multiple_calls_with_partial_name f1 = Tracer.start_transaction_or_segment( - partial_name: "Test::App/call", + partial_name: 'Test::App/call', category: :rack ) f2 = Tracer.start_transaction_or_segment( - partial_name: "MyMiddleware/call", + partial_name: 'MyMiddleware/call', category: :middleware ) f3 = Tracer.start_transaction_or_segment( - partial_name: "blogs/index", + partial_name: 'blogs/index', category: :controller ) @@ -257,35 +257,35 @@ def test_start_transaction_or_segment_multiple_calls_with_partial_name f1.finish assert_metrics_recorded [ - ["Nested/Controller/Rack/Test::App/call", "Controller/blogs/index"], - ["Middleware/Rack/MyMiddleware/call", "Controller/blogs/index"], - ["Nested/Controller/blogs/index", "Controller/blogs/index"], - "Controller/blogs/index", - "Nested/Controller/Rack/Test::App/call", - "Middleware/Rack/MyMiddleware/call", - "Nested/Controller/blogs/index" + ['Nested/Controller/Rack/Test::App/call', 'Controller/blogs/index'], + ['Middleware/Rack/MyMiddleware/call', 'Controller/blogs/index'], + ['Nested/Controller/blogs/index', 'Controller/blogs/index'], + 'Controller/blogs/index', + 'Nested/Controller/Rack/Test::App/call', + 'Middleware/Rack/MyMiddleware/call', + 'Nested/Controller/blogs/index' ] end def test_start_transaction_with_partial_name txn = Tracer.start_transaction( - partial_name: "Test::App/call", + partial_name: 'Test::App/call', category: :rack ) txn.finish - assert_metrics_recorded ["Controller/Rack/Test::App/call"] + assert_metrics_recorded ['Controller/Rack/Test::App/call'] end def test_current_segment_with_transaction assert_nil Tracer.current_segment - txn = Tracer.start_transaction(name: "Controller/blogs/index", category: :controller) + txn = Tracer.start_transaction(name: 'Controller/blogs/index', category: :controller) assert_equal txn.initial_segment, Tracer.current_segment - segment = Tracer.start_segment(name: "Custom/MyClass/myoperation") + segment = Tracer.start_segment(name: 'Custom/MyClass/myoperation') assert_equal segment, Tracer.current_segment @@ -296,7 +296,7 @@ def test_current_segment_with_transaction def test_current_segment_without_transaction assert_nil Tracer.current_segment - Tracer.start_segment(name: "Custom/MyClass/myoperation") + Tracer.start_segment(name: 'Custom/MyClass/myoperation') assert_nil Tracer.current_segment end @@ -304,18 +304,18 @@ def test_current_segment_without_transaction def test_current_segment_in_nested_threads_with_traced_thread assert_nil Tracer.current_segment - txn = Tracer.start_transaction(name: "Controller/blogs/index", category: :controller) + txn = Tracer.start_transaction(name: 'Controller/blogs/index', category: :controller) assert_equal txn.initial_segment, Tracer.current_segment threads = [] threads << ::NewRelic::TracedThread.new do - segment = Tracer.start_segment(name: "Custom/MyClass/myoperation") + segment = Tracer.start_segment(name: 'Custom/MyClass/myoperation') assert_equal segment, Tracer.current_segment threads << ::NewRelic::TracedThread.new do - segment2 = Tracer.start_segment(name: "Custom/MyClass/myoperation2") + segment2 = Tracer.start_segment(name: 'Custom/MyClass/myoperation2') assert_equal segment2, Tracer.current_segment segment2.finish @@ -337,18 +337,18 @@ def test_current_segment_in_nested_threads_auto with_config(:'instrumentation.thread.tracing' => true) do assert_nil Tracer.current_segment - txn = Tracer.start_transaction(name: "Controller/blogs/index", category: :controller) + txn = Tracer.start_transaction(name: 'Controller/blogs/index', category: :controller) assert_equal txn.initial_segment, Tracer.current_segment threads = [] threads << ::Thread.new do - segment = Tracer.start_segment(name: "Custom/MyClass/myoperation") + segment = Tracer.start_segment(name: 'Custom/MyClass/myoperation') assert_equal segment, Tracer.current_segment threads << Thread.new do - segment2 = Tracer.start_segment(name: "Custom/MyClass/myoperation2") + segment2 = Tracer.start_segment(name: 'Custom/MyClass/myoperation2') assert_equal segment2, Tracer.current_segment segment2.finish @@ -364,7 +364,7 @@ def test_current_segment_in_nested_threads_auto threads.each(&:join) txn.finish - assert_equal 2, txn.segments.count { |s| s.name == "Ruby/Thread" } + assert_equal 2, txn.segments.count { |s| s.name == 'Ruby/Thread' } assert_nil Tracer.current_segment end end @@ -373,7 +373,7 @@ def test_current_segment_in_nested_threads_disabled with_config(:'instrumentation.thread.tracing' => false) do assert_nil Tracer.current_segment - txn = Tracer.start_transaction(name: "Controller/blogs/index", category: :controller) + txn = Tracer.start_transaction(name: 'Controller/blogs/index', category: :controller) assert_equal txn.initial_segment, Tracer.current_segment threads = [] @@ -386,7 +386,7 @@ def test_current_segment_in_nested_threads_disabled threads.each(&:join) txn.finish - assert_equal 0, txn.segments.count { |s| s.name == "Ruby/Thread" } + assert_equal 0, txn.segments.count { |s| s.name == 'Ruby/Thread' } assert_nil Tracer.current_segment end end @@ -400,7 +400,7 @@ def test_thread_ids_included_when_enabled Thread.new { 'woof' }.join end - assert_match /Ruby\/Thread\/Thread\d+\/Fiber\d+/, txn.segments.last.name + assert_match %r{Ruby/Thread/Thread\d+/Fiber\d+}, txn.segments.last.name end end @@ -413,17 +413,17 @@ def test_thread_ids_absent_when_disabled Thread.new { 'woof' }.join end - assert_match /Ruby\/Thread$/, txn.segments.last.name + assert_match %r{Ruby/Thread$}, txn.segments.last.name end end def test_start_segment - name = "Custom/MyClass/myoperation" + name = 'Custom/MyClass/myoperation' unscoped_metrics = [ - "Custom/Segment/something/all", - "Custom/Segment/something/allWeb" + 'Custom/Segment/something/all', + 'Custom/Segment/something/allWeb' ] - parent = Transaction::Segment.new("parent") + parent = Transaction::Segment.new('parent') start_time = Process.clock_gettime(Process::CLOCK_REALTIME) in_transaction('test') do @@ -441,14 +441,14 @@ def test_start_segment end def test_start_datastore_segment - product = "MySQL" - operation = "INSERT" - collection = "blogs" - host = "localhost" - port_path_or_id = "3306" - database_name = "blog_app" + product = 'MySQL' + operation = 'INSERT' + collection = 'blogs' + host = 'localhost' + port_path_or_id = '3306' + database_name = 'blog_app' start_time = Process.clock_gettime(Process::CLOCK_REALTIME) - parent = Transaction::Segment.new("parent") + parent = Transaction::Segment.new('parent') in_transaction('test') do segment = Tracer.start_datastore_segment( @@ -469,11 +469,11 @@ def test_start_datastore_segment end def test_start_external_request_segment - library = "Net::HTTP" - uri = "https://docs.newrelic.com" - procedure = "GET" + library = 'Net::HTTP' + uri = 'https://docs.newrelic.com' + procedure = 'GET' start_time = Process.clock_gettime(Process::CLOCK_REALTIME) - parent = Transaction::Segment.new("parent") + parent = Transaction::Segment.new('parent') in_transaction('test') do segment = Tracer.start_external_request_segment( diff --git a/test/new_relic/agent/transaction/attributes_test.rb b/test/new_relic/agent/transaction/attributes_test.rb index 636f81cb6d..a201597f0d 100644 --- a/test/new_relic/agent/transaction/attributes_test.rb +++ b/test/new_relic/agent/transaction/attributes_test.rb @@ -18,15 +18,15 @@ def setup def test_adds_custom_attribute attributes = create_attributes - attributes.merge_custom_attributes(:foo => "bar") + attributes.merge_custom_attributes(:foo => 'bar') - assert_equal({"foo" => "bar"}, attributes.custom_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER)) + assert_equal({'foo' => 'bar'}, attributes.custom_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER)) end def test_disable_custom_attributes with_config({:'transaction_tracer.attributes.enabled' => false}) do attributes = create_attributes - attributes.merge_custom_attributes(:foo => "bar") + attributes.merge_custom_attributes(:foo => 'bar') assert_empty attributes.custom_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER) end @@ -35,7 +35,7 @@ def test_disable_custom_attributes def test_disable_custom_attributes_in_high_security_mode with_config(:high_security => true) do attributes = create_attributes - attributes.merge_custom_attributes(:foo => "bar") + attributes.merge_custom_attributes(:foo => 'bar') assert_empty attributes.custom_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER) end @@ -44,7 +44,7 @@ def test_disable_custom_attributes_in_high_security_mode def test_disable_merging_custom_attributes_in_high_security_mode with_config(:high_security => true) do attributes = create_attributes - attributes.merge_custom_attributes(:foo => "bar") + attributes.merge_custom_attributes(:foo => 'bar') assert_empty attributes.custom_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER) end @@ -52,23 +52,23 @@ def test_disable_merging_custom_attributes_in_high_security_mode def test_merge_custom_attributes attributes = create_attributes - params = {:foo => {:bar => "baz"}} + params = {:foo => {:bar => 'baz'}} attributes.merge_custom_attributes(params) - assert_equal({"foo.bar" => "baz"}, attributes.custom_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER)) + assert_equal({'foo.bar' => 'baz'}, attributes.custom_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER)) end def test_adds_agent_attribute attributes = create_attributes - attributes.add_agent_attribute(:foo, "bar", AttributeFilter::DST_ALL) + attributes.add_agent_attribute(:foo, 'bar', AttributeFilter::DST_ALL) - assert_equal({:foo => "bar"}, attributes.agent_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER)) + assert_equal({:foo => 'bar'}, attributes.agent_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER)) end def test_disable_agent_attributes with_config({:'transaction_tracer.attributes.enabled' => false}) do attributes = create_attributes - attributes.add_agent_attribute(:foo, "bar", AttributeFilter::DST_ALL) + attributes.add_agent_attribute(:foo, 'bar', AttributeFilter::DST_ALL) assert_empty attributes.agent_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER) end @@ -76,16 +76,16 @@ def test_disable_agent_attributes def test_agent_attributes_obey_default_destinations attributes = create_attributes - attributes.add_agent_attribute(:foo, "bar", AttributeFilter::DST_ERROR_COLLECTOR) + attributes.add_agent_attribute(:foo, 'bar', AttributeFilter::DST_ERROR_COLLECTOR) assert_empty attributes.agent_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER) end def test_adds_intrinsic_attribute_to_only_traces_and_errors attributes = create_attributes - attributes.add_intrinsic_attribute(:foo, "bar") + attributes.add_intrinsic_attribute(:foo, 'bar') - expected = {:foo => "bar"} + expected = {:foo => 'bar'} assert_equal(expected, attributes.intrinsic_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER)) assert_equal(expected, attributes.intrinsic_attributes_for(AttributeFilter::DST_ERROR_COLLECTOR)) @@ -97,9 +97,9 @@ def test_adds_intrinsic_attribute_to_only_traces_and_errors def test_intrinsic_attributes_arent_disabled_for_traces_and_errors with_config({:'transaction_tracer.attributes.enabled' => false}) do attributes = create_attributes - attributes.add_intrinsic_attribute(:foo, "bar") + attributes.add_intrinsic_attribute(:foo, 'bar') - expected = {:foo => "bar"} + expected = {:foo => 'bar'} assert_equal(expected, attributes.intrinsic_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER)) assert_equal(expected, attributes.intrinsic_attributes_for(AttributeFilter::DST_ERROR_COLLECTOR)) @@ -109,17 +109,17 @@ def test_intrinsic_attributes_arent_disabled_for_traces_and_errors end end - MULTIBYTE_CHARACTER = "七" + MULTIBYTE_CHARACTER = '七' def test_truncates_multibyte_string # Leading single byte character makes byteslice yield invalid string - value = "j" + MULTIBYTE_CHARACTER * 1000 + value = 'j' + MULTIBYTE_CHARACTER * 1000 attributes = create_attributes attributes.merge_custom_attributes(:key => value) custom_attributes = attributes.custom_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER) - result = custom_attributes["key"] + result = custom_attributes['key'] assert_predicate result, :valid_encoding? assert result.bytesize < NewRelic::Agent::Attributes::VALUE_LIMIT @@ -127,24 +127,24 @@ def test_truncates_multibyte_string def test_truncates_multibyte_symbol # Leading single byte character makes byteslice yield invalid string - value = ("j" + MULTIBYTE_CHARACTER * 1000).to_sym + value = ('j' + MULTIBYTE_CHARACTER * 1000).to_sym attributes = create_attributes attributes.merge_custom_attributes(:key => value) custom_attributes = attributes.custom_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER) - result = custom_attributes["key"] + result = custom_attributes['key'] assert_predicate result, :valid_encoding? assert result.bytesize < NewRelic::Agent::Attributes::VALUE_LIMIT end def test_limits_key_length - key = "x" * (Attributes::KEY_LIMIT + 1) + key = 'x' * (Attributes::KEY_LIMIT + 1) expects_logging(:warn, includes(key)) attributes = create_attributes - attributes.merge_custom_attributes(key => "") + attributes.merge_custom_attributes(key => '') assert_custom_attributes_empty(attributes) end @@ -154,61 +154,61 @@ def test_limits_key_length_by_bytes expects_logging(:warn, includes(key)) attributes = create_attributes - attributes.merge_custom_attributes(key => "") + attributes.merge_custom_attributes(key => '') assert_custom_attributes_empty(attributes) end def test_limits_key_length_symbol - key = ("x" * (Attributes::KEY_LIMIT + 1)).to_sym + key = ('x' * (Attributes::KEY_LIMIT + 1)).to_sym expects_logging(:warn, includes(key.to_s)) attributes = create_attributes - attributes.merge_custom_attributes(key => "") + attributes.merge_custom_attributes(key => '') assert_custom_attributes_empty(attributes) end def test_limits_key_length_on_merge_custom_attributes - key = ("x" * (Attributes::KEY_LIMIT + 1)).to_sym + key = ('x' * (Attributes::KEY_LIMIT + 1)).to_sym expects_logging(:warn, includes(key.to_s)) attributes = create_attributes - attributes.merge_custom_attributes(key => "") + attributes.merge_custom_attributes(key => '') assert_custom_attributes_empty(attributes) end def test_allows_non_string_key_type attributes = create_attributes - attributes.merge_custom_attributes(1 => "value") + attributes.merge_custom_attributes(1 => 'value') - assert_equal "value", custom_attributes(attributes)["1"] + assert_equal 'value', custom_attributes(attributes)['1'] end def test_truncates_string_values - value = "x" * 1000 + value = 'x' * 1000 attributes = create_attributes attributes.merge_custom_attributes(:key => value) - assert_equal Attributes::VALUE_LIMIT, custom_attributes(attributes)["key"].length + assert_equal Attributes::VALUE_LIMIT, custom_attributes(attributes)['key'].length end def test_truncates_symbol_values - value = ("x" * 1000).to_sym + value = ('x' * 1000).to_sym attributes = create_attributes attributes.merge_custom_attributes(:key => value) - assert_equal Attributes::VALUE_LIMIT, custom_attributes(attributes)["key"].length + assert_equal Attributes::VALUE_LIMIT, custom_attributes(attributes)['key'].length end def test_leaves_numbers_alone attributes = create_attributes attributes.merge_custom_attributes(:key => 42) - assert_equal 42, custom_attributes(attributes)["key"] + assert_equal 42, custom_attributes(attributes)['key'] end def test_limits_attribute_count @@ -223,32 +223,32 @@ def test_limits_attribute_count end def test_merge_untrusted_agent_attributes - with_config(:'attributes.include' => "request.parameters.*") do + with_config(:'attributes.include' => 'request.parameters.*') do attributes = create_attributes - params = {:foo => {:bar => "baz"}} + params = {:foo => {:bar => 'baz'}} attributes.merge_untrusted_agent_attributes(params, 'request.parameters', AttributeFilter::DST_NONE) - assert_equal({"request.parameters.foo.bar" => "baz"}, agent_attributes(attributes)) + assert_equal({'request.parameters.foo.bar' => 'baz'}, agent_attributes(attributes)) end end def test_merge_untrusted_agent_attributes_drops_long_keys - with_config(:'attributes.include' => "request.parameters.*") do + with_config(:'attributes.include' => 'request.parameters.*') do attributes = create_attributes params = { - "a" * 256 => "too long", - "foo" => "bar" + 'a' * 256 => 'too long', + 'foo' => 'bar' } attributes.merge_untrusted_agent_attributes(params, 'request.parameters', AttributeFilter::DST_NONE) - assert_equal({"request.parameters.foo" => "bar"}, agent_attributes(attributes)) + assert_equal({'request.parameters.foo' => 'bar'}, agent_attributes(attributes)) end end def test_merge_untrusted_agent_attributes_disallowed_in_high_security - with_config(:high_security => true, :'attributes.include' => "request.parameters.*") do + with_config(:high_security => true, :'attributes.include' => 'request.parameters.*') do attributes = create_attributes - params = {"sneaky" => "code"} + params = {'sneaky' => 'code'} attributes.merge_untrusted_agent_attributes('request.parameters', params, AttributeFilter::DST_NONE) diff --git a/test/new_relic/agent/transaction/datastore_segment_test.rb b/test/new_relic/agent/transaction/datastore_segment_test.rb index b9027a9df8..0f44251ab0 100644 --- a/test/new_relic/agent/transaction/datastore_segment_test.rb +++ b/test/new_relic/agent/transaction/datastore_segment_test.rb @@ -23,39 +23,39 @@ def teardown end def test_datastore_segment_name_with_collection - segment = DatastoreSegment.new("SQLite", "insert", "Blog") + segment = DatastoreSegment.new('SQLite', 'insert', 'Blog') - assert_equal "Datastore/statement/SQLite/Blog/insert", segment.name + assert_equal 'Datastore/statement/SQLite/Blog/insert', segment.name end def test_datastore_segment_name_with_operation - segment = DatastoreSegment.new("SQLite", "select") + segment = DatastoreSegment.new('SQLite', 'select') - assert_equal "Datastore/operation/SQLite/select", segment.name + assert_equal 'Datastore/operation/SQLite/select', segment.name end def test_segment_does_not_record_metrics_outside_of_txn - segment = DatastoreSegment.new("SQLite", "insert", "Blog") + segment = DatastoreSegment.new('SQLite', 'insert', 'Blog') segment.start advance_process_time(1) segment.finish refute_metrics_recorded [ - "Datastore/statement/SQLite/Blog/insert", - "Datastore/operation/SQLite/insert", - "Datastore/SQLite/allWeb", - "Datastore/SQLite/all", - "Datastore/allWeb", - "Datastore/all" + 'Datastore/statement/SQLite/Blog/insert', + 'Datastore/operation/SQLite/insert', + 'Datastore/SQLite/allWeb', + 'Datastore/SQLite/all', + 'Datastore/allWeb', + 'Datastore/all' ] end def test_segment_records_expected_metrics - in_web_transaction("text_txn") do + in_web_transaction('text_txn') do segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "insert", - collection: "Blog" + product: 'SQLite', + operation: 'insert', + collection: 'Blog' ) segment.start advance_process_time(1) @@ -63,20 +63,20 @@ def test_segment_records_expected_metrics end assert_metrics_recorded [ - "Datastore/statement/SQLite/Blog/insert", - "Datastore/operation/SQLite/insert", - "Datastore/SQLite/allWeb", - "Datastore/SQLite/all", - "Datastore/allWeb", - "Datastore/all" + 'Datastore/statement/SQLite/Blog/insert', + 'Datastore/operation/SQLite/insert', + 'Datastore/SQLite/allWeb', + 'Datastore/SQLite/all', + 'Datastore/allWeb', + 'Datastore/all' ] end def test_segment_records_expected_metrics_without_collection - in_web_transaction("text_txn") do + in_web_transaction('text_txn') do segment = Tracer.start_datastore_segment( - product: "SQLite", - operation: "select" + product: 'SQLite', + operation: 'select' ) segment.start advance_process_time(1) @@ -84,21 +84,21 @@ def test_segment_records_expected_metrics_without_collection end assert_metrics_recorded [ - "Datastore/operation/SQLite/select", - "Datastore/SQLite/allWeb", - "Datastore/SQLite/all", - "Datastore/allWeb", - "Datastore/all" + 'Datastore/operation/SQLite/select', + 'Datastore/SQLite/allWeb', + 'Datastore/SQLite/all', + 'Datastore/allWeb', + 'Datastore/all' ] end def test_segment_records_expected_metrics_with_instance_identifier - in_web_transaction("text_txn") do + in_web_transaction('text_txn') do segment = Tracer.start_datastore_segment( - product: "SQLite", - operation: "select", - host: "jonan-01", - port_path_or_id: "1337807" + product: 'SQLite', + operation: 'select', + host: 'jonan-01', + port_path_or_id: '1337807' ) segment.start advance_process_time(1) @@ -106,21 +106,21 @@ def test_segment_records_expected_metrics_with_instance_identifier end assert_metrics_recorded [ - "Datastore/instance/SQLite/jonan-01/1337807", - "Datastore/operation/SQLite/select", - "Datastore/SQLite/allWeb", - "Datastore/SQLite/all", - "Datastore/allWeb", - "Datastore/all" + 'Datastore/instance/SQLite/jonan-01/1337807', + 'Datastore/operation/SQLite/select', + 'Datastore/SQLite/allWeb', + 'Datastore/SQLite/all', + 'Datastore/allWeb', + 'Datastore/all' ] end def test_segment_records_expected_metrics_with_instance_identifier_host_only - in_web_transaction("text_txn") do + in_web_transaction('text_txn') do segment = Tracer.start_datastore_segment( - product: "SQLite", - operation: "select", - host: "jonan-01" + product: 'SQLite', + operation: 'select', + host: 'jonan-01' ) segment.start advance_process_time(1) @@ -128,20 +128,20 @@ def test_segment_records_expected_metrics_with_instance_identifier_host_only end assert_metrics_recorded [ - "Datastore/instance/SQLite/jonan-01/unknown", - "Datastore/operation/SQLite/select", - "Datastore/SQLite/allWeb", - "Datastore/SQLite/all", - "Datastore/allWeb", - "Datastore/all" + 'Datastore/instance/SQLite/jonan-01/unknown', + 'Datastore/operation/SQLite/select', + 'Datastore/SQLite/allWeb', + 'Datastore/SQLite/all', + 'Datastore/allWeb', + 'Datastore/all' ] end def test_segment_records_expected_metrics_with_instance_identifier_port_only - in_web_transaction("text_txn") do + in_web_transaction('text_txn') do segment = Tracer.start_datastore_segment( - product: "SQLite", - operation: "select", + product: 'SQLite', + operation: 'select', port_path_or_id: 1337807 ) segment.start @@ -150,44 +150,44 @@ def test_segment_records_expected_metrics_with_instance_identifier_port_only end assert_metrics_recorded [ - "Datastore/instance/SQLite/unknown/1337807", - "Datastore/operation/SQLite/select", - "Datastore/SQLite/allWeb", - "Datastore/SQLite/all", - "Datastore/allWeb", - "Datastore/all" + 'Datastore/instance/SQLite/unknown/1337807', + 'Datastore/operation/SQLite/select', + 'Datastore/SQLite/allWeb', + 'Datastore/SQLite/all', + 'Datastore/allWeb', + 'Datastore/all' ] end def test_segment_does_not_record_expected_metrics_with_empty_data - in_web_transaction("text_txn") do + in_web_transaction('text_txn') do segment = Tracer.start_datastore_segment( - product: "SQLite", - operation: "select" + product: 'SQLite', + operation: 'select' ) segment.start advance_process_time(1) segment.finish end - assert_metrics_not_recorded "Datastore/instance/SQLite/unknown/unknown" + assert_metrics_not_recorded 'Datastore/instance/SQLite/unknown/unknown' end def test_segment_does_not_record_instance_id_metrics_when_disabled with_config(:'datastore_tracer.instance_reporting.enabled' => false) do - in_web_transaction("text_txn") do + in_web_transaction('text_txn') do segment = Tracer.start_datastore_segment( - product: "SQLite", - operation: "select", - collection: "jonan-01", - port_path_or_id: "1337807" + product: 'SQLite', + operation: 'select', + collection: 'jonan-01', + port_path_or_id: '1337807' ) segment.start advance_process_time(1) segment.finish end - assert_metrics_not_recorded "Datastore/instance/SQLite/jonan-01/1337807" + assert_metrics_not_recorded 'Datastore/instance/SQLite/jonan-01/1337807' end end @@ -196,8 +196,8 @@ def test_non_sampled_segment_does_not_record_span_event txn.stubs(:sampled?).returns(false) segment = Tracer.start_datastore_segment( - product: "SQLite", - operation: "select", + product: 'SQLite', + operation: 'select', port_path_or_id: 1337807 ) @@ -216,8 +216,8 @@ def test_ignored_transaction_does_not_record_span_event txn.stubs(:ignore?).returns(true) segment = Tracer.start_datastore_segment( - product: "SQLite", - operation: "select", + product: 'SQLite', + operation: 'select', port_path_or_id: 1337807 ) @@ -237,18 +237,18 @@ def test_sampled_segment_records_span_event sampled = nil priority = nil timestamp = nil - sql_statement = "select * from table" + sql_statement = 'select * from table' in_web_transaction('wat') do |txn| txn.stubs(:sampled?).returns(true) segment = Tracer.start_datastore_segment( - product: "SQLite", - collection: "Blahg", - operation: "select", - host: "rachel.foo", + product: 'SQLite', + collection: 'Blahg', + operation: 'select', + host: 'rachel.foo', port_path_or_id: 1337807, - database_name: "calzone_zone" + database_name: 'calzone_zone' ) segment.notice_sql(sql_statement) @@ -293,18 +293,18 @@ def test_sampled_segment_records_span_event end def test_sql_statement_not_added_to_span_event_if_disabled - with_config(:'transaction_tracer.record_sql' => "off") do - sql = "SELECT * FROM mytable WHERE super_secret=1" + with_config(:'transaction_tracer.record_sql' => 'off') do + sql = 'SELECT * FROM mytable WHERE super_secret=1' in_web_transaction('wat') do |txn| txn.stubs(:sampled?).returns(true) segment = Tracer.start_datastore_segment( - product: "SQLite", - collection: "Blahg", - operation: "select", + product: 'SQLite', + collection: 'Blahg', + operation: 'select', port_path_or_id: 1337807, - database_name: "calzone_zone" + database_name: 'calzone_zone' ) segment.notice_sql(sql) @@ -317,23 +317,23 @@ def test_sql_statement_not_added_to_span_event_if_disabled assert_equal 2, last_span_events.size event = last_span_events[0][0] - refute event.key("db.statement") + refute event.key('db.statement') end end def test_verify_sql_statement_obfuscated_on_span_event - with_config(:'transaction_tracer.record_sql' => "obfuscated") do - sql = "SELECT * FROM mytable WHERE super_secret=1" + with_config(:'transaction_tracer.record_sql' => 'obfuscated') do + sql = 'SELECT * FROM mytable WHERE super_secret=1' in_web_transaction('wat') do |txn| txn.stubs(:sampled?).returns(true) segment = Tracer.start_datastore_segment( - product: "SQLite", - collection: "Blahg", - operation: "select", + product: 'SQLite', + collection: 'Blahg', + operation: 'select', port_path_or_id: 1337807, - database_name: "calzone_zone" + database_name: 'calzone_zone' ) segment.notice_sql(sql) @@ -346,24 +346,24 @@ def test_verify_sql_statement_obfuscated_on_span_event assert_equal 2, last_span_events.size _, _, agent_attributes = last_span_events[0] - obfuscated_sql = "SELECT * FROM mytable WHERE super_secret=?" + obfuscated_sql = 'SELECT * FROM mytable WHERE super_secret=?' - assert_equal obfuscated_sql, agent_attributes["db.statement"] + assert_equal obfuscated_sql, agent_attributes['db.statement'] end end def test_nosql_statement_added_to_span_event_if_present - nosql_statement = "get MY_KEY " + nosql_statement = 'get MY_KEY ' in_web_transaction('wat') do |txn| txn.stubs(:sampled?).returns(true) segment = Tracer.start_datastore_segment( - product: "SQLite", - collection: "Blahg", - operation: "select", + product: 'SQLite', + collection: 'Blahg', + operation: 'select', port_path_or_id: 1337807, - database_name: "calzone_zone" + database_name: 'calzone_zone' ) segment.notice_nosql_statement(nosql_statement) @@ -376,7 +376,7 @@ def test_nosql_statement_added_to_span_event_if_present assert_equal 2, last_span_events.size _, _, agent_attributes = last_span_events[0] - assert_equal nosql_statement, agent_attributes["db.statement"] + assert_equal nosql_statement, agent_attributes['db.statement'] end def test_span_event_truncates_long_sql_statement @@ -385,8 +385,8 @@ def test_span_event_truncates_long_sql_statement txn.stubs(:sampled?).returns(true) segment = Tracer.start_datastore_segment( - product: "SQLite", - operation: "select" + product: 'SQLite', + operation: 'select' ) sql_statement = "select * from #{'a' * 2500}" @@ -408,8 +408,8 @@ def test_span_event_truncates_long_nosql_statement txn.stubs(:sampled?).returns(true) segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "Redis", - operation: "set" + product: 'Redis', + operation: 'set' ) statement = "set mykey #{'a' * 2500}" @@ -429,11 +429,11 @@ def test_span_event_truncates_long_attributes txn.stubs(:sampled?).returns(true) segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "select", + product: 'SQLite', + operation: 'select', host: "localhost#{'t' * 300}", database_name: "foo#{'o' * 300}", - port_path_or_id: "blah" + port_path_or_id: 'blah' ) segment.finish @@ -457,8 +457,8 @@ def test_span_event_omits_optional_attributes txn.stubs(:sampled?).returns(true) segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "select" + product: 'SQLite', + operation: 'select' ) segment.finish @@ -477,10 +477,10 @@ def test_add_instance_identifier_segment_parameter in_transaction do segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "select", - host: "jonan-01", - port_path_or_id: "1337807" + product: 'SQLite', + operation: 'select', + host: 'jonan-01', + port_path_or_id: '1337807' ) advance_process_time(1) segment.finish @@ -489,24 +489,24 @@ def test_add_instance_identifier_segment_parameter sample = last_transaction_trace node = find_node_with_name(sample, segment.name) - assert_equal "jonan-01", node.params[:host] - assert_equal "1337807", node.params[:port_path_or_id] + assert_equal 'jonan-01', node.params[:host] + assert_equal '1337807', node.params[:port_path_or_id] end def test_localhost_replaced_by_system_hostname - NewRelic::Agent::Hostname.stubs(:get).returns("jonan.gummy_planet") + NewRelic::Agent::Hostname.stubs(:get).returns('jonan.gummy_planet') %w[localhost 0.0.0.0 127.0.0.1 0:0:0:0:0:0:0:1 0:0:0:0:0:0:0:0 ::1 ::].each do |host| segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "select", - collection: "blogs", + product: 'SQLite', + operation: 'select', + collection: 'blogs', host: host, - port_path_or_id: "1337" + port_path_or_id: '1337' ) segment.finish - assert_equal "jonan.gummy_planet", segment.host + assert_equal 'jonan.gummy_planet', segment.host end end @@ -515,9 +515,9 @@ def test_add_database_name_segment_parameter in_transaction do segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "select", - database_name: "pizza_cube" + product: 'SQLite', + operation: 'select', + database_name: 'pizza_cube' ) advance_process_time(1) segment.finish @@ -526,7 +526,7 @@ def test_add_database_name_segment_parameter sample = last_transaction_trace node = find_node_with_name(sample, segment.name) - assert_equal "pizza_cube", node.params[:database_name] + assert_equal 'pizza_cube', node.params[:database_name] end def test_does_not_add_database_name_segment_parameter_when_disabled @@ -535,9 +535,9 @@ def test_does_not_add_database_name_segment_parameter_when_disabled in_transaction do segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "select", - database_name: "pizza_cube" + product: 'SQLite', + operation: 'select', + database_name: 'pizza_cube' ) advance_process_time(1) segment.finish @@ -553,10 +553,10 @@ def test_does_not_add_database_name_segment_parameter_when_disabled def test_notice_sql in_transaction do segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "select" + product: 'SQLite', + operation: 'select' ) - segment.notice_sql("select * from blogs") + segment.notice_sql('select * from blogs') advance_process_time(2.0) Agent.instance.sql_sampler.expects(:notice_sql_statement) do |statement, name, duration| assert_equal segment.sql_statement.sql, statement.sql_statement @@ -565,7 +565,7 @@ def test_notice_sql end segment.finish - assert_equal("select * from blogs", segment.params[:sql].sql) + assert_equal('select * from blogs', segment.params[:sql].sql) end end @@ -574,10 +574,10 @@ def test_notice_sql_not_recording state.record_sql = false in_transaction do segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "select" + product: 'SQLite', + operation: 'select' ) - segment.notice_sql("select * from blogs") + segment.notice_sql('select * from blogs') assert_nil segment.sql_statement segment.finish @@ -588,11 +588,11 @@ def test_notice_sql_not_recording def test_notice_sql_can_be_disabled_with_record_sql in_transaction do |txn| segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "select" + product: 'SQLite', + operation: 'select' ) segment.record_sql = false - segment.notice_sql("select * from blogs") + segment.notice_sql('select * from blogs') assert_nil segment.sql_statement segment.finish @@ -602,40 +602,40 @@ def test_notice_sql_can_be_disabled_with_record_sql def test_notice_sql_creates_database_statement_with_identifier in_transaction do segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "select", - host: "jonan.gummy_planet", - port_path_or_id: "1337" + product: 'SQLite', + operation: 'select', + host: 'jonan.gummy_planet', + port_path_or_id: '1337' ) - segment.notice_sql("select * from blogs") + segment.notice_sql('select * from blogs') segment.finish - assert_equal "jonan.gummy_planet", segment.sql_statement.host - assert_equal "1337", segment.sql_statement.port_path_or_id + assert_equal 'jonan.gummy_planet', segment.sql_statement.host + assert_equal '1337', segment.sql_statement.port_path_or_id end end def test_notice_sql_creates_database_statement_with_database_name in_transaction do segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "select", - database_name: "pizza_cube" + product: 'SQLite', + operation: 'select', + database_name: 'pizza_cube' ) - segment.notice_sql("select * from blogs") + segment.notice_sql('select * from blogs') segment.finish - assert_equal "pizza_cube", segment.sql_statement.database_name + assert_equal 'pizza_cube', segment.sql_statement.database_name end end def test_notice_sql_truncates_long_queries in_transaction do segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "select" + product: 'SQLite', + operation: 'select' ) - segment.notice_sql("select * from blogs where " + ("something is nothing" * 16_384)) + segment.notice_sql('select * from blogs where ' + ('something is nothing' * 16_384)) segment.finish assert_equal(16_384, segment.params[:sql].sql.length) @@ -646,10 +646,10 @@ def test_internal_notice_sql explainer = stub(explainer: nil) in_transaction do segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "select" + product: 'SQLite', + operation: 'select' ) - segment._notice_sql("select * from blogs", {:adapter => :sqlite}, explainer) + segment._notice_sql('select * from blogs', {:adapter => :sqlite}, explainer) advance_process_time(2.0) Agent.instance.sql_sampler.expects(:notice_sql_statement) do |statement, name, duration| assert_equal segment.sql_statement.sql, statement.sql_statement @@ -658,16 +658,16 @@ def test_internal_notice_sql end segment.finish - assert_equal("select * from blogs", segment.params[:sql].sql) + assert_equal('select * from blogs', segment.params[:sql].sql) end end def test_notice_nosql_statement - statement = "set mykey 123" + statement = 'set mykey 123' in_transaction do segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "Redis", - operation: "set" + product: 'Redis', + operation: 'set' ) segment.notice_nosql_statement(statement) advance_process_time(2.0) @@ -683,10 +683,10 @@ def test_notice_nosql_statement_not_recording state.record_sql = false in_transaction do segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "select" + product: 'SQLite', + operation: 'select' ) - segment.notice_nosql_statement("hgetall somehash") + segment.notice_nosql_statement('hgetall somehash') assert_nil segment.nosql_statement segment.finish @@ -695,7 +695,7 @@ def test_notice_nosql_statement_not_recording end def test_set_instance_info_with_valid_data - segment = DatastoreSegment.new("SQLite", "select", nil) + segment = DatastoreSegment.new('SQLite', 'select', nil) segment.set_instance_info('jonan.gummy_planet', 1337807) assert_equal 'jonan.gummy_planet', segment.host @@ -703,7 +703,7 @@ def test_set_instance_info_with_valid_data end def test_set_instance_info_with_empty_host - segment = DatastoreSegment.new("SQLite", "select", nil) + segment = DatastoreSegment.new('SQLite', 'select', nil) segment.set_instance_info(nil, 1337807) assert_equal 'unknown', segment.host @@ -711,7 +711,7 @@ def test_set_instance_info_with_empty_host end def test_set_instance_info_with_empty_port_path_or_id - segment = DatastoreSegment.new("SQLite", "select", nil) + segment = DatastoreSegment.new('SQLite', 'select', nil) segment.set_instance_info('jonan.gummy_planet', nil) assert_equal 'jonan.gummy_planet', segment.host @@ -719,7 +719,7 @@ def test_set_instance_info_with_empty_port_path_or_id end def test_set_instance_info_with_empty_data - segment = DatastoreSegment.new("SQLite", "select", nil) + segment = DatastoreSegment.new('SQLite', 'select', nil) segment.set_instance_info(nil, nil) assert_nil segment.host @@ -734,11 +734,11 @@ def test_set_instance_info_with_empty_data def test_backtrace_not_appended_if_not_over_duration segment = nil with_config(:'transaction_tracer.stack_trace_threshold' => 2.0) do - in_web_transaction("test_txn") do + in_web_transaction('test_txn') do segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "insert", - collection: "Blog" + product: 'SQLite', + operation: 'insert', + collection: 'Blog' ) segment.start advance_process_time(1.0) @@ -757,11 +757,11 @@ def test_backtrace_not_appended_if_not_over_duration def test_backtrace_appended_when_over_duration segment = nil with_config(:'transaction_tracer.stack_trace_threshold' => 1.0) do - in_web_transaction("test_txn") do + in_web_transaction('test_txn') do segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "insert", - collection: "Blog" + product: 'SQLite', + operation: 'insert', + collection: 'Blog' ) segment.start advance_process_time(2.0) @@ -778,7 +778,7 @@ def test_backtrace_appended_when_over_duration end def test_node_obfuscated - orig_sql = "SELECT * from Jim where id=66" + orig_sql = 'SELECT * from Jim where id=66' in_transaction do s = NewRelic::Agent::Tracer.start_datastore_segment @@ -788,7 +788,7 @@ def test_node_obfuscated node = find_last_transaction_node(last_transaction_trace) assert_equal orig_sql, node[:sql].sql - assert_equal "SELECT * from Jim where id=?", node.obfuscated_sql + assert_equal 'SELECT * from Jim where id=?', node.obfuscated_sql end def test_sets_start_time_from_api @@ -796,9 +796,9 @@ def test_sets_start_time_from_api in_transaction do |txn| segment = Tracer.start_datastore_segment( - product: "SQLite", - operation: "insert", - collection: "Blog", + product: 'SQLite', + operation: 'insert', + collection: 'Blog', start_time: t ) segment.finish diff --git a/test/new_relic/agent/transaction/distributed_tracer_test.rb b/test/new_relic/agent/transaction/distributed_tracer_test.rb index ca46f50727..edec042205 100644 --- a/test/new_relic/agent/transaction/distributed_tracer_test.rb +++ b/test/new_relic/agent/transaction/distributed_tracer_test.rb @@ -17,9 +17,9 @@ def distributed_tracing_enabled { :'cross_application_tracer.enabled' => false, :'distributed_tracing.enabled' => true, - :account_id => "190", - :primary_application_id => "46954", - :trusted_account_key => "trust_this!" + :account_id => '190', + :primary_application_id => '46954', + :trusted_account_key => 'trust_this!' } end @@ -37,10 +37,10 @@ def build_distributed_trace_header(env = {}) begin NewRelic::Agent::DistributedTracePayload.stubs(:connected?).returns(true) with_config(distributed_tracing_enabled) do - in_transaction("referring_txn") do |txn| + in_transaction('referring_txn') do |txn| payload = txn.distributed_tracer.create_distributed_trace_payload - assert payload, "failed to build a distributed_trace payload!" + assert payload, 'failed to build a distributed_trace payload!' env['HTTP_NEWRELIC'] = payload.http_safe end end @@ -60,8 +60,8 @@ def tests_accepts_trace_context_header in_transaction do |txn| txn.distributed_tracer.accept_incoming_request(env) - assert txn.distributed_tracer.trace_context_header_data, "Expected to accept trace context headers" - refute txn.distributed_tracer.distributed_trace_payload, "Did not expect to accept a distributed trace payload" + assert txn.distributed_tracer.trace_context_header_data, 'Expected to accept trace context headers' + refute txn.distributed_tracer.distributed_trace_payload, 'Did not expect to accept a distributed trace payload' end end end @@ -76,8 +76,8 @@ def tests_accepts_distributed_trace_header in_transaction do |txn| txn.distributed_tracer.accept_incoming_request(env) - refute txn.distributed_tracer.trace_context_header_data, "Did not expect to accept trace context headers" - assert txn.distributed_tracer.distributed_trace_payload, "Expected to accept a distributed trace payload" + refute txn.distributed_tracer.trace_context_header_data, 'Did not expect to accept trace context headers' + assert txn.distributed_tracer.distributed_trace_payload, 'Expected to accept a distributed trace payload' end end end @@ -92,8 +92,8 @@ def tests_ignores_distributed_trace_header_when_context_trace_header_present in_transaction do |txn| txn.distributed_tracer.accept_incoming_request(env) - assert txn.distributed_tracer.trace_context_header_data, "Expected to accept trace context headers" - refute txn.distributed_tracer.distributed_trace_payload, "Did not expect to accept a distributed trace payload" + assert txn.distributed_tracer.trace_context_header_data, 'Expected to accept trace context headers' + refute txn.distributed_tracer.distributed_trace_payload, 'Did not expect to accept a distributed trace payload' end end end @@ -166,6 +166,37 @@ def tests_outbound_distributed_trace_headers_omitted_when_exclude_is_true end end end + + def test_log_request_headers_with_hash_argument + test_header = {'Snow' => 'Day'} + log = with_array_logger(level = :debug) do + in_transaction do |txn| + txn.distributed_tracer.log_request_headers(test_header) + end + end + + assert_log_contains(log, /REQUEST HEADERS: #{test_header}/) + end + + def test_log_request_headers_with_request_argument + skip_unless_minitest5_or_above + + test_header = {'Test' => 'Header'} + request = MiniTest::Mock.new + + request.expect :headers, test_header + request.expect :is_a?, true, [NewRelic::Agent::HTTPClients::AbstractRequest] + + log = with_array_logger(level = :debug) do + in_transaction do |txn| + txn.distributed_tracer.log_request_headers(request) + end + end + + assert_log_contains(log, /REQUEST HEADERS: #{test_header}/) + + request.verify + end end end end diff --git a/test/new_relic/agent/transaction/distributed_tracing_test.rb b/test/new_relic/agent/transaction/distributed_tracing_test.rb index c3fd709ebe..e54e720810 100644 --- a/test/new_relic/agent/transaction/distributed_tracing_test.rb +++ b/test/new_relic/agent/transaction/distributed_tracing_test.rb @@ -16,9 +16,9 @@ class DistributedTracingTest < Minitest::Test def setup @config = { :'distributed_tracing.enabled' => true, - :account_id => "190", - :primary_application_id => "46954", - :trusted_account_key => "trust_this!" + :account_id => '190', + :primary_application_id => '46954', + :trusted_account_key => 'trust_this!' } NewRelic::Agent::DistributedTracePayload.stubs(:connected?).returns(true) NewRelic::Agent.config.add_config_for_testing(@config) @@ -36,15 +36,15 @@ def test_create_distributed_trace_payload_returns_payload created_at = Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond) payload = nil - transaction = in_transaction("test_txn") do |t| + transaction = in_transaction('test_txn') do |t| payload = t.distributed_tracer.create_distributed_trace_payload end - assert_equal "46954", payload.parent_app_id - assert_equal "190", payload.parent_account_id - assert_equal "trust_this!", payload.trusted_account_key + assert_equal '46954', payload.parent_app_id + assert_equal '190', payload.parent_account_id + assert_equal 'trust_this!', payload.trusted_account_key assert_equal DistributedTracePayload::VERSION, payload.version - assert_equal "App", payload.parent_type + assert_equal 'App', payload.parent_type assert_equal transaction.initial_segment.guid, payload.id assert_equal transaction.guid, payload.transaction_id assert_equal transaction.trace_id, payload.trace_id @@ -58,7 +58,7 @@ def test_create_distributed_trace_payload_while_disconnected_returns_nil NewRelic::Agent::DistributedTracePayload.stubs(:connected?).returns(false) - in_transaction("test_txn") do |t| + in_transaction('test_txn') do |t| payload = t.distributed_tracer.create_distributed_trace_payload end @@ -68,7 +68,7 @@ def test_create_distributed_trace_payload_while_disconnected_returns_nil def test_accept_distributed_trace_payload_assigns_json_payload payload = create_distributed_trace_payload - transaction = in_transaction("test_txn") do |txn| + transaction = in_transaction('test_txn') do |txn| txn.distributed_tracer.accept_distributed_trace_payload(payload.text) end @@ -80,7 +80,7 @@ def test_accept_distributed_trace_payload_assigns_json_payload def test_accept_distributed_trace_payload_assigns_http_safe_payload payload = create_distributed_trace_payload - transaction = in_transaction("test_txn") do |txn| + transaction = in_transaction('test_txn') do |txn| txn.distributed_tracer.accept_distributed_trace_payload(payload.http_safe) end @@ -95,8 +95,8 @@ def test_accept_distributed_trace_payload_rejects_untrusted_account_with_trusted transaction = nil accepted = nil - with_config(trusted_account_key: "somekey") do - transaction = in_transaction("test_txn") do |txn| + with_config(trusted_account_key: 'somekey') do + transaction = in_transaction('test_txn') do |txn| accepted = txn.distributed_tracer.accept_distributed_trace_payload(payload.http_safe) end end @@ -114,8 +114,8 @@ def test_accept_distributed_trace_payload_rejects_untrusted_account_without_trus transaction = nil accepted = nil - with_config(trusted_account_key: "somekey") do - transaction = in_transaction("test_txn") do |txn| + with_config(trusted_account_key: 'somekey') do + transaction = in_transaction('test_txn') do |txn| accepted = txn.distributed_tracer.accept_distributed_trace_payload(payload.http_safe) end end @@ -128,13 +128,13 @@ def test_accept_distributed_trace_payload_rejects_untrusted_account_without_trus def test_accept_distributed_trace_payload_accepts_payload_when_account_id_matches_trusted_key payload = create_distributed_trace_payload payload.trusted_account_key = nil - payload.parent_account_id = "500" + payload.parent_account_id = '500' transaction = nil accepted = nil - with_config(trusted_account_key: "500") do - transaction = in_transaction("test_txn") do |txn| + with_config(trusted_account_key: '500') do + transaction = in_transaction('test_txn') do |txn| accepted = txn.distributed_tracer.accept_distributed_trace_payload(payload.http_safe) end end @@ -146,7 +146,7 @@ def test_accept_distributed_trace_payload_accepts_payload_when_account_id_matche def test_accept_distributed_trace_payload_records_duration_metrics payload = create_distributed_trace_payload - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| txn.distributed_tracer.accept_distributed_trace_payload(payload.text) end @@ -163,9 +163,9 @@ def test_accept_distributed_trace_payload_records_duration_metrics def test_accept_distributed_trace_payload_with_error_records_error_metrics payload = create_distributed_trace_payload - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| txn.distributed_tracer.accept_distributed_trace_payload(payload.text) - NewRelic::Agent.notice_error(StandardError.new("Nooo!")) + NewRelic::Agent.notice_error(StandardError.new('Nooo!')) end assert_metrics_recorded ['ErrorsByCaller/App/190/46954/Unknown/all', @@ -177,7 +177,7 @@ def test_sampled_flag_propagated_when_true_in_incoming_payload NewRelic::Agent.instance.adaptive_sampler.stubs(:sampled?).returns(false) - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| refute txn.sampled? txn.distributed_tracer.accept_distributed_trace_payload(payload.text) @@ -190,7 +190,7 @@ def test_sampled_flag_respects_upstreams_decision_when_sampled_is_false NewRelic::Agent.instance.adaptive_sampler.stubs(:sampled?).returns(true) - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| assert_predicate txn, :sampled? txn.distributed_tracer.accept_distributed_trace_payload(payload.text) @@ -222,13 +222,13 @@ def test_initial_legacy_cat_request_trace_id_overwritten_by_first_distributed_tr NewRelic::Agent.instance.adaptive_sampler.stubs(:sampled?).returns(true) transaction = nil - transaction = in_transaction("test_txn") do |txn| + transaction = in_transaction('test_txn') do |txn| # simulate legacy cat referring_txn_info = [ - "b854df4feb2b1f06", + 'b854df4feb2b1f06', false, - "7e249074f277923d", - "5d2957be" + '7e249074f277923d', + '5d2957be' ] payload = CrossAppPayload.new('1#666', txn, referring_txn_info) @@ -256,18 +256,18 @@ def test_intrinsics_assigned_to_transaction_event_from_distributed_trace inbound_payload = child_transaction.distributed_tracer.distributed_trace_payload - assert_equal inbound_payload.parent_type, child_intrinsics["parent.type"] - assert_equal "Unknown", child_intrinsics["parent.transportType"] - assert_equal inbound_payload.parent_app_id, child_intrinsics["parent.app"] - assert_equal inbound_payload.parent_account_id, child_intrinsics["parent.account"] + assert_equal inbound_payload.parent_type, child_intrinsics['parent.type'] + assert_equal 'Unknown', child_intrinsics['parent.transportType'] + assert_equal inbound_payload.parent_app_id, child_intrinsics['parent.app'] + assert_equal inbound_payload.parent_account_id, child_intrinsics['parent.account'] - assert_equal inbound_payload.trace_id, child_intrinsics["traceId"] - assert_equal inbound_payload.id, child_intrinsics["parentSpanId"] - assert_equal child_transaction.guid, child_intrinsics["guid"] - assert child_intrinsics["sampled"] + assert_equal inbound_payload.trace_id, child_intrinsics['traceId'] + assert_equal inbound_payload.id, child_intrinsics['parentSpanId'] + assert_equal child_transaction.guid, child_intrinsics['guid'] + assert child_intrinsics['sampled'] - assert child_intrinsics["parentId"] - assert_equal parent_transaction.guid, child_intrinsics["parentId"] + assert child_intrinsics['parentId'] + assert_equal parent_transaction.guid, child_intrinsics['parentId'] # Make sure the parent / grandparent links are connected all # the way up. @@ -277,9 +277,9 @@ def test_intrinsics_assigned_to_transaction_event_from_distributed_trace def test_assign_distributed_trace_attributes_properly_assigned_on_receiving_dt payload = create_distributed_trace_payload(sampled: false) - payload.id = "abc123" + payload.id = 'abc123' - txn = in_transaction("test_txn") do |t| + txn = in_transaction('test_txn') do |t| t.distributed_tracer.accept_distributed_trace_payload(payload.text) end @@ -293,7 +293,7 @@ def test_assign_distributed_trace_attributes_properly_assigned_on_receiving_dt def test_assign_distributed_trace_attributes_properly_assigned_on_initial_trace payload = create_distributed_trace_payload(sampled: false) - txn = in_transaction("test_txn") do |t| + txn = in_transaction('test_txn') do |t| t.distributed_tracer.accept_distributed_trace_payload(payload.text) end @@ -309,17 +309,17 @@ def test_assign_distributed_trace_attributes_properly_assigned_on_initial_trace def test_sampled_is_false_in_transaction_event_when_indicated_by_upstream payload = create_distributed_trace_payload(sampled: false) - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| txn.distributed_tracer.accept_distributed_trace_payload(payload.text) end intrinsics, _, _ = last_transaction_event - refute intrinsics["sampled"] + refute intrinsics['sampled'] end def test_agent_attributes_always_recorded_when_distributed_tracing_enabled - in_transaction("test_txn") {} + in_transaction('test_txn') {} intrinsics, _, _ = last_transaction_event @@ -334,14 +334,14 @@ def test_intrinsics_assigned_to_error_event_from_distributed_trace payload = nil referring_transaction = nil - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| referring_transaction = txn payload = referring_transaction.distributed_tracer.create_distributed_trace_payload end - transaction = in_transaction("text_txn2") do |txn| + transaction = in_transaction('text_txn2') do |txn| txn.distributed_tracer.accept_distributed_trace_payload(payload.text) - NewRelic::Agent.notice_error(StandardError.new("Nooo!")) + NewRelic::Agent.notice_error(StandardError.new('Nooo!')) end intrinsics, _, _ = last_error_event @@ -350,16 +350,16 @@ def test_intrinsics_assigned_to_error_event_from_distributed_trace transport_type = transaction.distributed_tracer.caller_transport_type - assert_equal inbound_payload.parent_type, intrinsics["parent.type"] - assert_equal transport_type, intrinsics["parent.transportType"] - assert_equal inbound_payload.parent_app_id, intrinsics["parent.app"] - assert_equal inbound_payload.parent_account_id, intrinsics["parent.account"] + assert_equal inbound_payload.parent_type, intrinsics['parent.type'] + assert_equal transport_type, intrinsics['parent.transportType'] + assert_equal inbound_payload.parent_app_id, intrinsics['parent.app'] + assert_equal inbound_payload.parent_account_id, intrinsics['parent.account'] assert_equal inbound_payload.transaction_id, referring_transaction.guid - assert_equal transaction.guid, intrinsics["guid"] - assert_equal inbound_payload.trace_id, intrinsics["traceId"] - assert intrinsics["sampled"] - assert intrinsics["parentId"], "Child should be linked to parent transaction" - assert_equal inbound_payload.transaction_id, intrinsics["parentId"] + assert_equal transaction.guid, intrinsics['guid'] + assert_equal inbound_payload.trace_id, intrinsics['traceId'] + assert intrinsics['sampled'] + assert intrinsics['parentId'], 'Child should be linked to parent transaction' + assert_equal inbound_payload.transaction_id, intrinsics['parentId'] end def test_sampled_is_false_in_error_event_when_indicated_by_upstream @@ -367,14 +367,14 @@ def test_sampled_is_false_in_error_event_when_indicated_by_upstream NewRelic::Agent.instance.adaptive_sampler.stubs(:sampled?).returns(true) - in_transaction("text_txn") do |txn| + in_transaction('text_txn') do |txn| txn.distributed_tracer.accept_distributed_trace_payload(payload.text) - NewRelic::Agent.notice_error(StandardError.new("Nooo!")) + NewRelic::Agent.notice_error(StandardError.new('Nooo!')) end intrinsics, _, _ = last_error_event - refute intrinsics["sampled"] + refute intrinsics['sampled'] end def test_distributed_trace_does_not_propagate_nil_sampled_flags @@ -383,50 +383,50 @@ def test_distributed_trace_does_not_propagate_nil_sampled_flags NewRelic::Agent.instance.adaptive_sampler.stubs(:sampled?).returns(true) - transaction = in_transaction("test_txn") do |txn| + transaction = in_transaction('test_txn') do |txn| txn.distributed_tracer.accept_distributed_trace_payload(payload.text) end intrinsics, _, _ = last_transaction_event assert_predicate transaction, :sampled? - assert intrinsics["sampled"] + assert intrinsics['sampled'] end def test_sampled_flag_added_to_intrinsics_without_distributed_trace_when_true NewRelic::Agent.instance.adaptive_sampler.stubs(:sampled?).returns(true) - transaction = in_transaction("test_txn") do - NewRelic::Agent.notice_error(StandardError.new("Sorry!")) + transaction = in_transaction('test_txn') do + NewRelic::Agent.notice_error(StandardError.new('Sorry!')) end txn_intrinsics, _, _ = last_transaction_event err_intrinsics, _, _ = last_error_event assert_predicate transaction, :sampled? - assert txn_intrinsics["sampled"] - assert err_intrinsics["sampled"] + assert txn_intrinsics['sampled'] + assert err_intrinsics['sampled'] end def test_sampled_flag_added_to_intrinsics_without_distributed_trace_when_false NewRelic::Agent.instance.adaptive_sampler.stubs(:sampled?).returns(false) - transaction = in_transaction("test_txn") do - NewRelic::Agent.notice_error(StandardError.new("Sorry!")) + transaction = in_transaction('test_txn') do + NewRelic::Agent.notice_error(StandardError.new('Sorry!')) end txn_intrinsics, _, _ = last_transaction_event err_intrinsics, _, _ = last_error_event refute transaction.sampled? - refute txn_intrinsics["sampled"] - refute err_intrinsics["sampled"] + refute txn_intrinsics['sampled'] + refute err_intrinsics['sampled'] end def test_transaction_inherits_priority_from_distributed_trace_payload payload = create_distributed_trace_payload(sampled: true) - transaction = in_transaction("test_txn") do |txn| + transaction = in_transaction('test_txn') do |txn| txn.distributed_tracer.accept_distributed_trace_payload(payload.text) end @@ -439,7 +439,7 @@ def test_transaction_doesnt_inherit_priority_from_distributed_trace_payload_when payload.priority = nil priority = nil - transaction = in_transaction("test_txn2") do |txn| + transaction = in_transaction('test_txn2') do |txn| priority = txn.priority txn.distributed_tracer.accept_distributed_trace_payload(payload.text) end @@ -457,7 +457,7 @@ def test_transaction_doesnt_inherit_priority_from_distributed_without_sampled_fl payload.sampled = nil priority = nil - transaction = in_transaction("test_txn2") do |txn| + transaction = in_transaction('test_txn2') do |txn| priority = txn.priority txn.distributed_tracer.accept_distributed_trace_payload(payload.text) end @@ -470,7 +470,7 @@ def test_payload_ignored_when_nil refute txn.distributed_tracer.accept_distributed_trace_payload(nil) end - assert_metrics_recorded "Supportability/DistributedTrace/AcceptPayload/Ignored/Null" + assert_metrics_recorded 'Supportability/DistributedTrace/AcceptPayload/Ignored/Null' end def test_multiple_payload_accepts_ignored @@ -482,7 +482,7 @@ def test_multiple_payload_accepts_ignored refute txn.distributed_tracer.accept_distributed_trace_payload(payload2) end - assert_metrics_recorded "Supportability/DistributedTrace/AcceptPayload/Ignored/Multiple" + assert_metrics_recorded 'Supportability/DistributedTrace/AcceptPayload/Ignored/Multiple' end def test_payload_rejected_when_accept_is_called_after_create @@ -494,17 +494,17 @@ def test_payload_rejected_when_accept_is_called_after_create refute txn.distributed_tracer.accept_distributed_trace_payload(payload) end - assert_metrics_recorded "Supportability/DistributedTrace/AcceptPayload/Ignored/CreateBeforeAccept" + assert_metrics_recorded 'Supportability/DistributedTrace/AcceptPayload/Ignored/CreateBeforeAccept' end def test_supportability_metric_recorded_when_error_parsing_payload - payload = "{thisisnotvalidjson" + payload = '{thisisnotvalidjson' in_transaction do |txn| refute txn.distributed_tracer.accept_distributed_trace_payload(payload) end - assert_metrics_recorded "Supportability/DistributedTrace/AcceptPayload/ParseException" + assert_metrics_recorded 'Supportability/DistributedTrace/AcceptPayload/ParseException' end def test_supportability_metric_recorded_on_major_version_mismatch @@ -517,7 +517,7 @@ def test_supportability_metric_recorded_on_major_version_mismatch refute txn2.distributed_tracer.accept_distributed_trace_payload(payload.text) end - assert_metrics_recorded "Supportability/DistributedTrace/AcceptPayload/Ignored/MajorVersion" + assert_metrics_recorded 'Supportability/DistributedTrace/AcceptPayload/Ignored/MajorVersion' end def test_supportability_metric_recorded_accept_successful @@ -527,19 +527,19 @@ def test_supportability_metric_recorded_accept_successful assert txn.distributed_tracer.accept_distributed_trace_payload(payload) end - assert_metrics_recorded "Supportability/DistributedTrace/AcceptPayload/Success" + assert_metrics_recorded 'Supportability/DistributedTrace/AcceptPayload/Success' end def test_supportability_metric_recorded_on_exception_during_accept payload = create_distributed_trace_payload.text in_transaction do |txn| - txn.distributed_tracer.stubs(:check_valid_version).raises(ArgumentError.new("oops!")) + txn.distributed_tracer.stubs(:check_valid_version).raises(ArgumentError.new('oops!')) refute txn.distributed_tracer.accept_distributed_trace_payload(payload) end - assert_metrics_recorded "Supportability/DistributedTrace/AcceptPayload/Exception" + assert_metrics_recorded 'Supportability/DistributedTrace/AcceptPayload/Exception' end def test_supportability_metric_recorded_when_payload_creation_successful @@ -549,17 +549,17 @@ def test_supportability_metric_recorded_when_payload_creation_successful refute_nil payload end - assert_metrics_recorded "Supportability/DistributedTrace/CreatePayload/Success" + assert_metrics_recorded 'Supportability/DistributedTrace/CreatePayload/Success' end def test_supportability_metric_recorded_when_payload_creation_fails in_transaction do |txn| - DistributedTracePayload.stubs(:for_transaction).raises(StandardError.new("oops!")) + DistributedTracePayload.stubs(:for_transaction).raises(StandardError.new('oops!')) txn.distributed_tracer.create_distributed_trace_payload end - assert_metrics_recorded "Supportability/DistributedTrace/CreatePayload/Exception" - refute_metrics_recorded "Supportability/DistributedTrace/CreatePayload/Success" + assert_metrics_recorded 'Supportability/DistributedTrace/CreatePayload/Exception' + refute_metrics_recorded 'Supportability/DistributedTrace/CreatePayload/Success' end def test_sampled_and_priority_inherited_when_accepting_distributed_trace_payload @@ -615,14 +615,14 @@ def create_distributed_trace_payload(sampled: nil) def create_distributed_transactions result = {} - result[:grandparent_transaction] = in_transaction("test_txn") do |txn| + result[:grandparent_transaction] = in_transaction('test_txn') do |txn| result[:grandparent_payload] = txn.distributed_tracer.create_distributed_trace_payload end result[:grandparent_intrinsics], _, _ = last_transaction_event - result[:parent_transaction] = in_transaction("text_txn2") do |txn| + result[:parent_transaction] = in_transaction('text_txn2') do |txn| txn.distributed_tracer.accept_distributed_trace_payload( result[:grandparent_payload].text ) @@ -633,7 +633,7 @@ def create_distributed_transactions result[:parent_intrinsics], _, _ = last_transaction_event - result[:child_transaction] = in_transaction("text_txn3") do |txn| + result[:child_transaction] = in_transaction('text_txn3') do |txn| txn.distributed_tracer.accept_distributed_trace_payload( result[:parent_payload].text ) diff --git a/test/new_relic/agent/transaction/external_request_segment_test.rb b/test/new_relic/agent/transaction/external_request_segment_test.rb index 8687ecfcce..72fcbc1e65 100644 --- a/test/new_relic/agent/transaction/external_request_segment_test.rb +++ b/test/new_relic/agent/transaction/external_request_segment_test.rb @@ -36,7 +36,7 @@ def to_s TRANSACTION_GUID = 'BEC1BC64675138B9' def setup - @obfuscator = NewRelic::Agent::Obfuscator.new("jotorotoes") + @obfuscator = NewRelic::Agent::Obfuscator.new('jotorotoes') NewRelic::Agent.agent.stubs(:connected?).returns(true) NewRelic::Agent::CrossAppTracing.stubs(:obfuscator).returns(@obfuscator) @@ -50,51 +50,51 @@ def teardown end def test_generates_expected_name - segment = ExternalRequestSegment.new("Typhoeus", "http://remotehost.com/blogs/index", "GET") + segment = ExternalRequestSegment.new('Typhoeus', 'http://remotehost.com/blogs/index', 'GET') - assert_equal "External/remotehost.com/Typhoeus/GET", segment.name + assert_equal 'External/remotehost.com/Typhoeus/GET', segment.name end def test_downcases_hostname - segment = ExternalRequestSegment.new("Typhoeus", "http://ReMoTeHoSt.Com/blogs/index", "GET") + segment = ExternalRequestSegment.new('Typhoeus', 'http://ReMoTeHoSt.Com/blogs/index', 'GET') - assert_equal "External/remotehost.com/Typhoeus/GET", segment.name + assert_equal 'External/remotehost.com/Typhoeus/GET', segment.name end def test_segment_does_not_record_metrics_outside_of_txn - segment = ExternalRequestSegment.new("Net::HTTP", "http://remotehost.com/blogs/index", "GET") + segment = ExternalRequestSegment.new('Net::HTTP', 'http://remotehost.com/blogs/index', 'GET') segment.finish refute_metrics_recorded [ - "External/remotehost.com/Net::HTTP/GET", - "External/all", - "External/remotehost.com/all", - "External/allWeb", - ["External/remotehost.com/Net::HTTP/GET", "test"] + 'External/remotehost.com/Net::HTTP/GET', + 'External/all', + 'External/remotehost.com/all', + 'External/allWeb', + ['External/remotehost.com/Net::HTTP/GET', 'test'] ] end def test_segment_records_expected_metrics_for_non_cat_txn - in_transaction("test", :category => :controller) do + in_transaction('test', :category => :controller) do segment = Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET' ) segment.finish end expected_metrics = [ - "External/remotehost.com/Net::HTTP/GET", - "External/all", - "External/remotehost.com/all", - "External/allWeb", - ["External/remotehost.com/Net::HTTP/GET", "test"] + 'External/remotehost.com/Net::HTTP/GET', + 'External/all', + 'External/remotehost.com/all', + 'External/allWeb', + ['External/remotehost.com/Net::HTTP/GET', 'test'] ] if Agent.config[:'distributed_tracing.enabled'] - expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all" - expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb" + expected_metrics << 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/all' + expected_metrics << 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb' end assert_metrics_recorded expected_metrics @@ -103,15 +103,15 @@ def test_segment_records_expected_metrics_for_non_cat_txn def test_segment_records_noncat_metrics_when_cat_disabled request = RequestWrapper.new response = { - 'X-NewRelic-App-Data' => make_app_data_payload("1#1884", "txn-name", 2, 8, 0, TRANSACTION_GUID) + 'X-NewRelic-App-Data' => make_app_data_payload('1#1884', 'txn-name', 2, 8, 0, TRANSACTION_GUID) } with_config(cat_config.merge({:"cross_application_tracer.enabled" => false})) do - in_transaction("test", :category => :controller) do + in_transaction('test', :category => :controller) do segment = Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET' ) segment.add_request_headers(request) segment.process_response_headers(response) @@ -119,16 +119,16 @@ def test_segment_records_noncat_metrics_when_cat_disabled end expected_metrics = [ - "External/remotehost.com/Net::HTTP/GET", - "External/all", - "External/remotehost.com/all", - "External/allWeb", - ["External/remotehost.com/Net::HTTP/GET", "test"] + 'External/remotehost.com/Net::HTTP/GET', + 'External/all', + 'External/remotehost.com/all', + 'External/allWeb', + ['External/remotehost.com/Net::HTTP/GET', 'test'] ] if Agent.config[:'distributed_tracing.enabled'] - expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all" - expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb" + expected_metrics << 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/all' + expected_metrics << 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb' end assert_metrics_recorded expected_metrics @@ -138,15 +138,15 @@ def test_segment_records_noncat_metrics_when_cat_disabled def test_segment_records_noncat_metrics_without_valid_cross_process_id request = RequestWrapper.new response = { - 'X-NewRelic-App-Data' => make_app_data_payload("1#1884", "txn-name", 2, 8, 0, TRANSACTION_GUID) + 'X-NewRelic-App-Data' => make_app_data_payload('1#1884', 'txn-name', 2, 8, 0, TRANSACTION_GUID) } with_config(cat_config.merge({:cross_process_id => ''})) do - in_transaction("test", :category => :controller) do + in_transaction('test', :category => :controller) do segment = Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET' ) segment.add_request_headers(request) segment.process_response_headers(response) @@ -154,16 +154,16 @@ def test_segment_records_noncat_metrics_without_valid_cross_process_id end expected_metrics = [ - "External/remotehost.com/Net::HTTP/GET", - "External/all", - "External/remotehost.com/all", - "External/allWeb", - ["External/remotehost.com/Net::HTTP/GET", "test"] + 'External/remotehost.com/Net::HTTP/GET', + 'External/all', + 'External/remotehost.com/all', + 'External/allWeb', + ['External/remotehost.com/Net::HTTP/GET', 'test'] ] if Agent.config[:'distributed_tracing.enabled'] - expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all" - expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb" + expected_metrics << 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/all' + expected_metrics << 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb' end assert_metrics_recorded expected_metrics @@ -174,15 +174,15 @@ def test_segment_records_noncat_metrics_without_valid_encoding_key CrossAppTracing.unstub(:valid_encoding_key?) request = RequestWrapper.new response = { - 'X-NewRelic-App-Data' => make_app_data_payload("1#1884", "txn-name", 2, 8, 0, TRANSACTION_GUID) + 'X-NewRelic-App-Data' => make_app_data_payload('1#1884', 'txn-name', 2, 8, 0, TRANSACTION_GUID) } with_config(cat_config.merge({:encoding_key => ''})) do - in_transaction("test", :category => :controller) do + in_transaction('test', :category => :controller) do segment = Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET' ) segment.add_request_headers(request) segment.process_response_headers(response) @@ -190,16 +190,16 @@ def test_segment_records_noncat_metrics_without_valid_encoding_key end expected_metrics = [ - "External/remotehost.com/Net::HTTP/GET", - "External/all", - "External/remotehost.com/all", - "External/allWeb", - ["External/remotehost.com/Net::HTTP/GET", "test"] + 'External/remotehost.com/Net::HTTP/GET', + 'External/all', + 'External/remotehost.com/all', + 'External/allWeb', + ['External/remotehost.com/Net::HTTP/GET', 'test'] ] if Agent.config[:'distributed_tracing.enabled'] - expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all" - expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb" + expected_metrics << 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/all' + expected_metrics << 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb' end assert_metrics_recorded expected_metrics @@ -208,32 +208,32 @@ def test_segment_records_noncat_metrics_without_valid_encoding_key def test_segment_records_expected_metrics_for_cat_transaction response = { - 'X-NewRelic-App-Data' => make_app_data_payload("1#1884", "txn-name", 2, 8, 0, TRANSACTION_GUID) + 'X-NewRelic-App-Data' => make_app_data_payload('1#1884', 'txn-name', 2, 8, 0, TRANSACTION_GUID) } with_config(cat_config) do - in_transaction("test", :category => :controller) do |txn| + in_transaction('test', :category => :controller) do |txn| segment = Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://newrelic.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://newrelic.com/blogs/index', + procedure: 'GET' ) segment.process_response_headers(response) segment.finish end expected_metrics = [ - "ExternalTransaction/newrelic.com/1#1884/txn-name", - "ExternalApp/newrelic.com/1#1884/all", - "External/all", - "External/newrelic.com/all", - "External/allWeb", - ["ExternalTransaction/newrelic.com/1#1884/txn-name", "test"] + 'ExternalTransaction/newrelic.com/1#1884/txn-name', + 'ExternalApp/newrelic.com/1#1884/all', + 'External/all', + 'External/newrelic.com/all', + 'External/allWeb', + ['ExternalTransaction/newrelic.com/1#1884/txn-name', 'test'] ] if Agent.config[:'distributed_tracing.enabled'] - expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all" - expected_metrics << "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb" + expected_metrics << 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/all' + expected_metrics << 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb' end assert_metrics_recorded expected_metrics @@ -246,7 +246,7 @@ def test_proper_metrics_recorded_for_distributed_trace_on_receiver request = RequestWrapper.new payload = nil - with_config(account_id: "190", primary_application_id: "46954") do + with_config(account_id: '190', primary_application_id: '46954') do in_transaction do |txn| payload = txn.distributed_tracer.create_distributed_trace_payload end @@ -255,12 +255,12 @@ def test_proper_metrics_recorded_for_distributed_trace_on_receiver NewRelic::Agent.drop_buffered_data transport_type = nil - in_transaction("test_txn2", :category => :controller) do |txn| + in_transaction('test_txn2', :category => :controller) do |txn| txn.distributed_tracer.accept_distributed_trace_payload(payload.text) segment = Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://newrelic.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://newrelic.com/blogs/index', + procedure: 'GET' ) transport_type = txn.distributed_tracer.caller_transport_type segment.add_request_headers(request) @@ -268,14 +268,14 @@ def test_proper_metrics_recorded_for_distributed_trace_on_receiver end expected_metrics = [ - "External/all", - "External/newrelic.com/all", - "External/allWeb", + 'External/all', + 'External/newrelic.com/all', + 'External/allWeb', "DurationByCaller/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/all", "DurationByCaller/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/allWeb", "TransportDuration/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/all", "TransportDuration/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/allWeb", - ["External/newrelic.com/Net::HTTP/GET", "test_txn2"] + ['External/newrelic.com/Net::HTTP/GET', 'test_txn2'] ] assert_metrics_recorded expected_metrics @@ -290,7 +290,7 @@ def test_proper_metrics_recorded_for_distributed_trace_on_receiver_when_error_oc request = RequestWrapper.new payload = nil - with_config(account_id: "190", primary_application_id: "46954") do + with_config(account_id: '190', primary_application_id: '46954') do in_transaction do |txn| payload = txn.distributed_tracer.create_distributed_trace_payload end @@ -299,30 +299,30 @@ def test_proper_metrics_recorded_for_distributed_trace_on_receiver_when_error_oc NewRelic::Agent.drop_buffered_data transport_type = nil - in_transaction("test_txn2", :category => :controller) do |txn| + in_transaction('test_txn2', :category => :controller) do |txn| txn.distributed_tracer.accept_distributed_trace_payload(payload.text) segment = Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://newrelic.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://newrelic.com/blogs/index', + procedure: 'GET' ) transport_type = txn.distributed_tracer.caller_transport_type segment.add_request_headers(request) segment.finish - NewRelic::Agent.notice_error(StandardError.new("Sorry!")) + NewRelic::Agent.notice_error(StandardError.new('Sorry!')) end expected_metrics = [ - "External/all", - "External/newrelic.com/all", - "External/allWeb", + 'External/all', + 'External/newrelic.com/all', + 'External/allWeb', "DurationByCaller/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/all", "DurationByCaller/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/allWeb", "TransportDuration/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/all", "TransportDuration/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/allWeb", "ErrorsByCaller/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/all", "ErrorsByCaller/#{payload.parent_type}/#{payload.parent_account_id}/#{payload.parent_app_id}/#{transport_type}/allWeb", - ["External/newrelic.com/Net::HTTP/GET", "test_txn2"] + ['External/newrelic.com/Net::HTTP/GET', 'test_txn2'] ] assert_metrics_recorded expected_metrics @@ -334,17 +334,17 @@ def test_segment_writes_outbound_request_headers with_config(cat_config) do in_transaction(:category => :controller) do segment = Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET' ) segment.add_request_headers(request) segment.finish end end - assert request.headers.key?("X-NewRelic-ID"), "Expected to find X-NewRelic-ID header" - assert request.headers.key?("X-NewRelic-Transaction"), "Expected to find X-NewRelic-Transaction header" + assert request.headers.key?('X-NewRelic-ID'), 'Expected to find X-NewRelic-ID header' + assert request.headers.key?('X-NewRelic-Transaction'), 'Expected to find X-NewRelic-Transaction header' end def test_segment_writes_outbound_request_headers_for_trace_context @@ -352,17 +352,17 @@ def test_segment_writes_outbound_request_headers_for_trace_context with_config(trace_context_config) do in_transaction(:category => :controller) do segment = Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET' ) segment.add_request_headers(request) segment.finish end end - assert request.headers.key?("traceparent"), "Expected to find traceparent header" - assert request.headers.key?("tracestate"), "Expected to find tracestate header" + assert request.headers.key?('traceparent'), 'Expected to find traceparent header' + assert request.headers.key?('tracestate'), 'Expected to find tracestate header' end def test_segment_writes_synthetics_header_for_synthetics_txn @@ -371,32 +371,32 @@ def test_segment_writes_synthetics_header_for_synthetics_txn in_transaction(:category => :controller) do |txn| txn.raw_synthetics_header = json_dump_and_encode([1, 42, 100, 200, 300]) segment = Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET' ) segment.add_request_headers(request) segment.finish end end - assert request.headers.key?("X-NewRelic-Synthetics"), "Expected to find X-NewRelic-Synthetics header" + assert request.headers.key?('X-NewRelic-Synthetics'), 'Expected to find X-NewRelic-Synthetics header' end def test_add_request_headers_renames_segment_based_on_host_header - request = RequestWrapper.new({"host" => "anotherhost.local"}) + request = RequestWrapper.new({'host' => 'anotherhost.local'}) with_config(cat_config) do in_transaction(:category => :controller) do segment = Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET' ) - assert_equal "External/remotehost.com/Net::HTTP/GET", segment.name + assert_equal 'External/remotehost.com/Net::HTTP/GET', segment.name segment.add_request_headers(request) - assert_equal "External/anotherhost.local/Net::HTTP/GET", segment.name + assert_equal 'External/anotherhost.local/Net::HTTP/GET', segment.name segment.finish end end @@ -404,23 +404,23 @@ def test_add_request_headers_renames_segment_based_on_host_header def test_read_response_headers_decodes_valid_appdata response = { - 'X-NewRelic-App-Data' => make_app_data_payload("1#1884", "txn-name", 2, 8, 0, TRANSACTION_GUID) + 'X-NewRelic-App-Data' => make_app_data_payload('1#1884', 'txn-name', 2, 8, 0, TRANSACTION_GUID) } with_config(cat_config) do in_transaction(:category => :controller) do |txn| segment = Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET' ) segment.process_response_headers(response) segment.finish assert_predicate segment, :cross_app_request? - assert_equal "1#1884", segment.cross_process_id - assert_equal "txn-name", segment.cross_process_transaction_name - assert_equal "BEC1BC64675138B9", segment.transaction_guid + assert_equal '1#1884', segment.cross_process_id + assert_equal 'txn-name', segment.cross_process_transaction_name + assert_equal 'BEC1BC64675138B9', segment.transaction_guid end end end @@ -445,12 +445,12 @@ def with_external_segment(headers, config, segment_params) def test_read_response_headers_ignores_invalid_appdata headers = { - 'X-NewRelic-App-Data' => "this#is#not#valid#appdata" + 'X-NewRelic-App-Data' => 'this#is#not#valid#appdata' } segment_params = { - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET' } segment, _http_response = with_external_segment(headers, cat_config, segment_params) @@ -463,42 +463,42 @@ def test_read_response_headers_ignores_invalid_appdata def test_sets_http_status_code_ok headers = { - 'X-NewRelic-App-Data' => "this#is#not#valid#appdata", + 'X-NewRelic-App-Data' => 'this#is#not#valid#appdata', 'status_code' => 200 } segment_params = { - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET' } segment, _http_response = with_external_segment(headers, cat_config, segment_params) assert_equal 200, segment.http_status_code - refute_metrics_recorded "External/remotehost.com/Net::HTTP/GET/Error" + refute_metrics_recorded 'External/remotehost.com/Net::HTTP/GET/Error' end def test_unknown_response_records_supportability_metric response = { - 'X-NewRelic-App-Data' => make_app_data_payload("1#1884", "txn-name", 2, 8, 0, TRANSACTION_GUID) + 'X-NewRelic-App-Data' => make_app_data_payload('1#1884', 'txn-name', 2, 8, 0, TRANSACTION_GUID) } with_config(trace_context_config) do in_transaction(:category => :controller) do |txn| segment = Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET' ) segment.process_response_headers(response) segment.finish refute segment.cross_app_request? - refute segment.http_status_code, "No http_status_code expected!" + refute segment.http_status_code, 'No http_status_code expected!' end end expected_metrics = [ - "External/remotehost.com/Net::HTTP/GET/MissingHTTPStatusCode", - "External/remotehost.com/Net::HTTP/GET", - "External/allWeb" + 'External/remotehost.com/Net::HTTP/GET/MissingHTTPStatusCode', + 'External/remotehost.com/Net::HTTP/GET', + 'External/allWeb' ] assert_metrics_recorded expected_metrics @@ -506,32 +506,32 @@ def test_unknown_response_records_supportability_metric def test_sets_http_status_code_not_found headers = { - 'X-NewRelic-App-Data' => "this#is#not#valid#appdata", + 'X-NewRelic-App-Data' => 'this#is#not#valid#appdata', 'status_code' => 404 } segment_params = { - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET' } segment, _http_response = with_external_segment(headers, cat_config, segment_params) assert_equal 404, segment.http_status_code - refute_metrics_recorded "External/remotehost.com/Net::HTTP/GET/MissingHTTPStatusCode" + refute_metrics_recorded 'External/remotehost.com/Net::HTTP/GET/MissingHTTPStatusCode' end def test_read_response_headers_ignores_invalid_cross_app_id response = { - 'X-NewRelic-App-Data' => make_app_data_payload("not_an_ID", "txn-name", 2, 8, 0, TRANSACTION_GUID) + 'X-NewRelic-App-Data' => make_app_data_payload('not_an_ID', 'txn-name', 2, 8, 0, TRANSACTION_GUID) } with_config(cat_config) do in_transaction(:category => :controller) do |txn| segment = Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET' ) segment.process_response_headers(response) segment.finish @@ -546,13 +546,13 @@ def test_read_response_headers_ignores_invalid_cross_app_id def test_uri_recorded_as_tt_attribute segment = nil - uri = "http://newrelic.com/blogs/index" + uri = 'http://newrelic.com/blogs/index' in_transaction(:category => :controller) do segment = Tracer.start_external_request_segment( - library: "Net::HTTP", + library: 'Net::HTTP', uri: uri, - procedure: "GET" + procedure: 'GET' ) segment.finish end @@ -567,15 +567,15 @@ def test_guid_recorded_as_tt_attribute_for_cat_txn segment = nil response = { - 'X-NewRelic-App-Data' => make_app_data_payload("1#1884", "txn-name", 2, 8, 0, TRANSACTION_GUID) + 'X-NewRelic-App-Data' => make_app_data_payload('1#1884', 'txn-name', 2, 8, 0, TRANSACTION_GUID) } with_config(cat_config) do in_transaction(:category => :controller) do segment = Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET' ) segment.process_response_headers(response) segment.finish @@ -622,7 +622,7 @@ def test_get_request_metadata_with_cross_app_tracing_disabled in_transaction do |txn| rmd = external_request_segment { |s| s.get_request_metadata } - refute rmd, "`get_request_metadata` should return nil with cross app tracing disabled" + refute rmd, '`get_request_metadata` should return nil with cross app tracing disabled' end end end @@ -709,7 +709,7 @@ def test_process_response_metadata_with_invalid_cross_app_id segment = external_request_segment { |s| s.process_response_metadata(rmd); s } end - refute_empty l.array, "process_response_metadata should log error on invalid ID" + refute_empty l.array, 'process_response_metadata should log error on invalid ID' assert_includes l.array.first, 'invalid/non-trusted ID' assert_equal 'External/example.com/foo/get', segment.name @@ -736,7 +736,7 @@ def test_process_response_metadata_with_untrusted_cross_app_id segment = external_request_segment { |s| s.process_response_metadata(rmd); s } end - refute_empty l.array, "process_response_metadata should log error on invalid ID" + refute_empty l.array, 'process_response_metadata should log error on invalid ID' assert_includes l.array.first, 'invalid/non-trusted ID' assert_equal 'External/example.com/foo/get', segment.name @@ -750,8 +750,8 @@ def test_segment_adds_distributed_trace_header distributed_tracing_config = { :'distributed_tracing.enabled' => true, :'cross_application_tracer.enabled' => false, - :account_id => "190", - :primary_application_id => "46954" + :account_id => '190', + :primary_application_id => '46954' } with_config(distributed_tracing_config) do @@ -759,16 +759,16 @@ def test_segment_adds_distributed_trace_header with_config(cat_config.merge(distributed_tracing_config)) do in_transaction(:category => :controller) do |txn| segment = Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET' ) segment.add_request_headers(request) segment.finish end end - assert request.headers.key?("newrelic"), "Expected to find newrelic header" + assert request.headers.key?('newrelic'), 'Expected to find newrelic header' end end @@ -777,9 +777,9 @@ def test_sets_start_time_from_api in_transaction do |txn| segment = Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET", + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET', start_time: t ) segment.finish @@ -800,9 +800,9 @@ def test_sampled_external_records_span_event in_transaction('wat') do |txn| txn.stubs(:sampled?).returns(true) - segment = ExternalRequestSegment.new("Typhoeus", - "http://remotehost.com/blogs/index", - "GET") + segment = ExternalRequestSegment.new('Typhoeus', + 'http://remotehost.com/blogs/index', + 'GET') txn.add_segment(segment) segment.start advance_process_time(1.0) @@ -845,14 +845,14 @@ def test_sampled_external_records_span_event def test_urls_are_filtered with_config(distributed_tracing_config) do segment = nil - filtered_url = "https://remotehost.com/bar/baz" + filtered_url = 'https://remotehost.com/bar/baz' in_transaction('wat') do |txn| txn.stubs(:sampled?).returns(true) - segment = ExternalRequestSegment.new("Typhoeus", + segment = ExternalRequestSegment.new('Typhoeus', "#{filtered_url}?a=1&b=2#fragment", - "GET") + 'GET') txn.add_segment(segment) segment.start advance_process_time(1.0) @@ -873,9 +873,9 @@ def test_non_sampled_segment_does_not_record_span_event in_transaction('wat') do |txn| txn.stubs(:sampled?).returns(false) - segment = ExternalRequestSegment.new("Typhoeus", - "http://remotehost.com/blogs/index", - "GET") + segment = ExternalRequestSegment.new('Typhoeus', + 'http://remotehost.com/blogs/index', + 'GET') txn.add_segment(segment) segment.start advance_process_time(1.0) @@ -891,9 +891,9 @@ def test_ignored_segment_does_not_record_span_event in_transaction('wat') do |txn| txn.stubs(:ignore?).returns(true) - segment = ExternalRequestSegment.new("Typhoeus", - "http://remotehost.com/blogs/index", - "GET") + segment = ExternalRequestSegment.new('Typhoeus', + 'http://remotehost.com/blogs/index', + 'GET') txn.add_segment(segment) segment.start advance_process_time(1.0) @@ -910,9 +910,9 @@ def test_span_event_truncates_long_value in_transaction('wat') do |txn| txn.stubs(:sampled?).returns(true) segment = NewRelic::Agent::Tracer.start_external_request_segment( \ - library: "Typhoeus", + library: 'Typhoeus', uri: "http://#{'a' * 300}.com", - procedure: "GET" + procedure: 'GET' ) segment.finish end @@ -942,7 +942,7 @@ def test_record_agent_attributes_can_be_enabled def cat_config { - :cross_process_id => "269975#22824", + :cross_process_id => '269975#22824', :trusted_account_ids => [1, 269975], :'cross_application_tracer.enabled' => true, :'distributed_tracing.enabled' => false @@ -961,9 +961,9 @@ def trace_context_config { :'distributed_tracing.enabled' => true, :'cross_application_tracer.enabled' => false, - :account_id => "190", - :primary_application_id => "46954", - :trusted_account_key => "trust_this!" + :account_id => '190', + :primary_application_id => '46954', + :trusted_account_key => 'trust_this!' } end diff --git a/test/new_relic/agent/transaction/message_broker_segment_test.rb b/test/new_relic/agent/transaction/message_broker_segment_test.rb index c2c6d19ec0..0984d236b2 100644 --- a/test/new_relic/agent/transaction/message_broker_segment_test.rb +++ b/test/new_relic/agent/transaction/message_broker_segment_test.rb @@ -14,102 +14,102 @@ def teardown end def test_metrics_recorded_for_produce - in_transaction("test_txn") do + in_transaction('test_txn') do segment = NewRelic::Agent::Tracer.start_message_broker_segment( action: :produce, - library: "RabbitMQ", + library: 'RabbitMQ', destination_type: :exchange, - destination_name: "Default" + destination_name: 'Default' ) segment.finish end assert_metrics_recorded [ - ["MessageBroker/RabbitMQ/Exchange/Produce/Named/Default", "test_txn"], - "MessageBroker/RabbitMQ/Exchange/Produce/Named/Default" + ['MessageBroker/RabbitMQ/Exchange/Produce/Named/Default', 'test_txn'], + 'MessageBroker/RabbitMQ/Exchange/Produce/Named/Default' ] end def test_metrics_recorded_for_consume - in_transaction("test_txn") do + in_transaction('test_txn') do segment = NewRelic::Agent::Tracer.start_message_broker_segment( action: :consume, - library: "RabbitMQ", + library: 'RabbitMQ', destination_type: :exchange, - destination_name: "Default" + destination_name: 'Default' ) segment.finish end assert_metrics_recorded [ - ["MessageBroker/RabbitMQ/Exchange/Consume/Named/Default", "test_txn"], - "MessageBroker/RabbitMQ/Exchange/Consume/Named/Default" + ['MessageBroker/RabbitMQ/Exchange/Consume/Named/Default', 'test_txn'], + 'MessageBroker/RabbitMQ/Exchange/Consume/Named/Default' ] end def test_segment_copies_parameters - in_transaction("test_txn") do + in_transaction('test_txn') do segment = NewRelic::Agent::Tracer.start_message_broker_segment( action: :produce, - library: "RabbitMQ", + library: 'RabbitMQ', destination_type: :exchange, - destination_name: "Default", - parameters: {routing_key: "my.key", correlation_id: "123"} + destination_name: 'Default', + parameters: {routing_key: 'my.key', correlation_id: '123'} ) - assert_equal "my.key", segment.params[:routing_key] - assert_equal "123", segment.params[:correlation_id] + assert_equal 'my.key', segment.params[:routing_key] + assert_equal '123', segment.params[:correlation_id] end end def test_allows_symbol_exchange_names - in_transaction("test_txn") do + in_transaction('test_txn') do segment = NewRelic::Agent::Tracer.start_message_broker_segment( action: :produce, - library: "RabbitMQ", + library: 'RabbitMQ', destination_type: :exchange, destination_name: :this_is_totally_a_symbol, - parameters: {routing_key: "my.key", correlation_id: "123"} + parameters: {routing_key: 'my.key', correlation_id: '123'} ) - assert_equal "MessageBroker/RabbitMQ/Exchange/Produce/Named/this_is_totally_a_symbol", + assert_equal 'MessageBroker/RabbitMQ/Exchange/Produce/Named/this_is_totally_a_symbol', segment.name end end def test_segment_adds_cat_headers_to_message_properties_for_produce - with_config(:"cross_application_tracer.enabled" => true, :"distributed_tracing.enabled" => false, :cross_process_id => "321#123", :encoding_key => "abc") do - in_transaction("test_txn") do + with_config(:"cross_application_tracer.enabled" => true, :"distributed_tracing.enabled" => false, :cross_process_id => '321#123', :encoding_key => 'abc') do + in_transaction('test_txn') do segment = NewRelic::Agent::Tracer.start_message_broker_segment( action: :produce, - library: "RabbitMQ", + library: 'RabbitMQ', destination_type: :exchange, - destination_name: "Default", + destination_name: 'Default', headers: {} ) - assert segment.headers.key?("NewRelicID"), "Expected message_properties to contain: NewRelicId" - assert segment.headers.key?("NewRelicTransaction"), "Expected message_properties to contain: NewRelicTransaction" - refute segment.headers.key?("NewRelicSynthetics") + assert segment.headers.key?('NewRelicID'), 'Expected message_properties to contain: NewRelicId' + assert segment.headers.key?('NewRelicTransaction'), 'Expected message_properties to contain: NewRelicTransaction' + refute segment.headers.key?('NewRelicSynthetics') end end end def test_segment_adds_synthetics_and_cat_headers_to_message_properties_for_produce - with_config(:"cross_application_tracer.enabled" => true, :"distributed_tracing.enabled" => false, :cross_process_id => "321#123", :encoding_key => "abc") do - in_transaction("test_txn") do |txn| - txn.raw_synthetics_header = "boo" + with_config(:"cross_application_tracer.enabled" => true, :"distributed_tracing.enabled" => false, :cross_process_id => '321#123', :encoding_key => 'abc') do + in_transaction('test_txn') do |txn| + txn.raw_synthetics_header = 'boo' segment = NewRelic::Agent::Tracer.start_message_broker_segment( action: :produce, - library: "RabbitMQ", + library: 'RabbitMQ', destination_type: :exchange, - destination_name: "Default", + destination_name: 'Default', headers: {} ) - assert segment.headers.key?("NewRelicID"), "Expected message_properties to contain: NewRelicId" - assert segment.headers.key?("NewRelicTransaction"), "Expected message_properties to contain: NewRelicTransaction" - assert segment.headers.key?("NewRelicSynthetics"), "Expected message_properties to contain: NewRelicSynthetics" + assert segment.headers.key?('NewRelicID'), 'Expected message_properties to contain: NewRelicId' + assert segment.headers.key?('NewRelicTransaction'), 'Expected message_properties to contain: NewRelicTransaction' + assert segment.headers.key?('NewRelicSynthetics'), 'Expected message_properties to contain: NewRelicSynthetics' end end end @@ -117,18 +117,18 @@ def test_segment_adds_synthetics_and_cat_headers_to_message_properties_for_produ def test_segment_adds_distributed_trace_headers_to_message_properties_for_produce NewRelic::Agent::DistributedTracePayload.stubs(:connected?).returns(true) with_config(:"distributed_tracing.enabled" => true, - :account_id => "190", - :primary_application_id => "46954") do - transaction = in_transaction("test_txn") do |txn| + :account_id => '190', + :primary_application_id => '46954') do + transaction = in_transaction('test_txn') do |txn| segment = NewRelic::Agent::Tracer.start_message_broker_segment( action: :produce, - library: "RabbitMQ", + library: 'RabbitMQ', destination_type: :exchange, - destination_name: "Default", + destination_name: 'Default', headers: {} ) - assert segment.headers.key?("newrelic"), "Expected message_properties to contain: newrelic" + assert segment.headers.key?('newrelic'), 'Expected message_properties to contain: newrelic' end intrinsics, _, _ = last_transaction_event @@ -141,17 +141,17 @@ def test_sets_start_time_from_constructor t = Process.clock_gettime(Process::CLOCK_REALTIME) segment = MessageBrokerSegment.new(action: :produce, - library: "RabbitMQ", + library: 'RabbitMQ', destination_type: :exchange, - destination_name: "Default", + destination_name: 'Default', start_time: t) assert_equal t, segment.start_time segment = NewRelic::Agent::Tracer.start_message_broker_segment(action: :produce, - library: "RabbitMQ", + library: 'RabbitMQ', destination_type: :exchange, - destination_name: "Default", + destination_name: 'Default', start_time: t) assert_equal t, segment.start_time diff --git a/test/new_relic/agent/transaction/request_attributes_test.rb b/test/new_relic/agent/transaction/request_attributes_test.rb index c07443adc0..90f3898936 100644 --- a/test/new_relic/agent/transaction/request_attributes_test.rb +++ b/test/new_relic/agent/transaction/request_attributes_test.rb @@ -13,7 +13,7 @@ def test_tolerates_request_without_desired_methods request = stub('request') attrs = RequestAttributes.new(request) - assert_equal "/", attrs.request_path + assert_equal '/', attrs.request_path assert_nil attrs.referer assert_nil attrs.content_length assert_nil attrs.content_type @@ -23,59 +23,59 @@ def test_tolerates_request_without_desired_methods end def test_sets_referer_from_request - request = stub('request', :referer => "http://site.com/page") + request = stub('request', :referer => 'http://site.com/page') attrs = RequestAttributes.new(request) - assert_equal "http://site.com/page", attrs.referer + assert_equal 'http://site.com/page', attrs.referer end def test_sets_accept_from_request_headers - request = stub('request', :env => {"HTTP_ACCEPT" => "application/json"}) + request = stub('request', :env => {'HTTP_ACCEPT' => 'application/json'}) attrs = RequestAttributes.new(request) - assert_equal "application/json", attrs.accept + assert_equal 'application/json', attrs.accept end def test_sets_content_length_from_request - request = stub('request', :content_length => "111") + request = stub('request', :content_length => '111') attrs = RequestAttributes.new(request) assert_equal 111, attrs.content_length end def test_sets_content_type_from_request - request = stub('request', :content_type => "application/json") + request = stub('request', :content_type => 'application/json') attrs = RequestAttributes.new(request) - assert_equal "application/json", attrs.content_type + assert_equal 'application/json', attrs.content_type end def test_sets_host_from_request - request = stub('request', :host => "localhost") + request = stub('request', :host => 'localhost') attrs = RequestAttributes.new(request) - assert_equal "localhost", attrs.host + assert_equal 'localhost', attrs.host end def test_sets_port_from_request - request = stub('request', :port => "3000") + request = stub('request', :port => '3000') attrs = RequestAttributes.new(request) assert_equal 3000, attrs.port end def test_sets_user_agent_from_request - request = stub('request', :user_agent => "use this!") + request = stub('request', :user_agent => 'use this!') attrs = RequestAttributes.new(request) - assert_equal "use this!", attrs.user_agent + assert_equal 'use this!', attrs.user_agent end def test_sets_method_from_request - request = stub('request', :request_method => "POST") + request = stub('request', :request_method => 'POST') attrs = RequestAttributes.new(request) - assert_equal "POST", attrs.request_method + assert_equal 'POST', attrs.request_method end end end diff --git a/test/new_relic/agent/transaction/segment_test.rb b/test/new_relic/agent/transaction/segment_test.rb index bf54246021..62229d85dd 100644 --- a/test/new_relic/agent/transaction/segment_test.rb +++ b/test/new_relic/agent/transaction/segment_test.rb @@ -22,7 +22,7 @@ def teardown end def test_logs_warning_if_a_non_hash_arg_is_passed_to_add_custom_span_attributes - expects_logging(:warn, includes("add_custom_span_attributes")) + expects_logging(:warn, includes('add_custom_span_attributes')) in_transaction do NewRelic::Agent.add_custom_span_attributes('fooz') end @@ -31,7 +31,7 @@ def test_logs_warning_if_a_non_hash_arg_is_passed_to_add_custom_span_attributes def test_ignores_custom_attributes_when_in_high_security with_config(:high_security => true) do with_segment do |segment| - NewRelic::Agent.add_custom_span_attributes(:failure => "is an option") + NewRelic::Agent.add_custom_span_attributes(:failure => 'is an option') assert_empty attributes_for(segment, :custom) end @@ -42,16 +42,16 @@ def test_records_error_attributes_on_segment test_segment, _error = capture_segment_with_error current_noticed_error = test_segment.noticed_error - assert current_noticed_error, "expected noticed_error to not be nil" + assert current_noticed_error, 'expected noticed_error to not be nil' test_segment.noticed_error.build_error_attributes attributes = test_segment.noticed_error_attributes - assert attributes, "expected noticed_error_attributes to not be nil" + assert attributes, 'expected noticed_error_attributes to not be nil' refute_empty attributes - assert_equal "oops!", attributes["error.message"] - assert_equal "RuntimeError", attributes["error.class"] + assert_equal 'oops!', attributes['error.message'] + assert_equal 'RuntimeError', attributes['error.class'] end def test_segment_with_no_error_does_not_produce_error_attributes @@ -81,47 +81,47 @@ def test_ignores_error_attributes_when_in_high_security agent_attributes = attributes_for(segment, :agent) # No error attributes - assert_equal({"parent.transportType" => "Unknown"}, agent_attributes) + assert_equal({'parent.transportType' => 'Unknown'}, agent_attributes) end end def test_adding_custom_attributes with_config(:'span_events.attributes.enabled' => true) do with_segment do |segment| - NewRelic::Agent.add_custom_span_attributes(:foo => "bar") + NewRelic::Agent.add_custom_span_attributes(:foo => 'bar') actual = segment.attributes.custom_attributes_for(NewRelic::Agent::AttributeFilter::DST_SPAN_EVENTS) - assert_equal({"foo" => "bar"}, actual) + assert_equal({'foo' => 'bar'}, actual) end end end def test_assigns_unscoped_metrics - segment = Segment.new("Custom/simple/segment", "Segment/all") + segment = Segment.new('Custom/simple/segment', 'Segment/all') - assert_equal "Custom/simple/segment", segment.name - assert_equal "Segment/all", segment.unscoped_metrics + assert_equal 'Custom/simple/segment', segment.name + assert_equal 'Segment/all', segment.unscoped_metrics end def test_assigns_unscoped_metrics_as_array - segment = Segment.new("Custom/simple/segment", ["Segment/all", "Other/all"]) + segment = Segment.new('Custom/simple/segment', ['Segment/all', 'Other/all']) - assert_equal "Custom/simple/segment", segment.name - assert_equal ["Segment/all", "Other/all"], segment.unscoped_metrics + assert_equal 'Custom/simple/segment', segment.name + assert_equal ['Segment/all', 'Other/all'], segment.unscoped_metrics end def test_segment_does_not_record_metrics_outside_of_txn - segment = Segment.new("Custom/simple/segment", "Segment/all") + segment = Segment.new('Custom/simple/segment', 'Segment/all') segment.start advance_process_time(1.0) segment.finish - refute_metrics_recorded ["Custom/simple/segment", "Segment/all"] + refute_metrics_recorded ['Custom/simple/segment', 'Segment/all'] end def test_segment_records_metrics - in_transaction("test") do |txn| - segment = Segment.new("Custom/simple/segment", "Segment/all") + in_transaction('test') do |txn| + segment = Segment.new('Custom/simple/segment', 'Segment/all') txn.add_segment(segment) segment.start advance_process_time(1.0) @@ -129,33 +129,33 @@ def test_segment_records_metrics end assert_metrics_recorded [ - "test", - ["Custom/simple/segment", "test"], - "Custom/simple/segment", - "Segment/all", - "OtherTransactionTotalTime", - "OtherTransactionTotalTime/test", - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all", - "Supportability/API/recording_web_transaction?", - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allOther" + 'test', + ['Custom/simple/segment', 'test'], + 'Custom/simple/segment', + 'Segment/all', + 'OtherTransactionTotalTime', + 'OtherTransactionTotalTime/test', + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/all', + 'Supportability/API/recording_web_transaction?', + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/allOther' ] end def test_segment_records_metrics_when_given_as_array in_transaction do |txn| - segment = Segment.new("Custom/simple/segment", ["Segment/all", "Other/all"]) + segment = Segment.new('Custom/simple/segment', ['Segment/all', 'Other/all']) txn.add_segment(segment) segment.start advance_process_time(1.0) segment.finish end - assert_metrics_recorded ["Custom/simple/segment", "Segment/all", "Other/all"] + assert_metrics_recorded ['Custom/simple/segment', 'Segment/all', 'Other/all'] end def test_segment_can_disable_scoped_metric_recording in_transaction('test') do |txn| - segment = Segment.new("Custom/simple/segment", "Segment/all") + segment = Segment.new('Custom/simple/segment', 'Segment/all') segment.record_scoped_metric = false txn.add_segment(segment) segment.start @@ -164,21 +164,21 @@ def test_segment_can_disable_scoped_metric_recording end assert_metrics_recorded_exclusive [ - "test", - "Custom/simple/segment", - "Segment/all", - "Supportability/API/drop_buffered_data", - "OtherTransactionTotalTime", - "OtherTransactionTotalTime/test", - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all", - "Supportability/API/recording_web_transaction?", - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allOther" + 'test', + 'Custom/simple/segment', + 'Segment/all', + 'Supportability/API/drop_buffered_data', + 'OtherTransactionTotalTime', + 'OtherTransactionTotalTime/test', + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/all', + 'Supportability/API/recording_web_transaction?', + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/allOther' ], :ignore_filter => %r{^(Supportability/Logging|Supportability/API)} end def test_segment_can_disable_scoped_metric_recording_with_unscoped_as_frozen_array in_transaction('test') do |txn| - segment = Segment.new("Custom/simple/segment", ["Segment/all", "Segment/allOther"].freeze) + segment = Segment.new('Custom/simple/segment', ['Segment/all', 'Segment/allOther'].freeze) segment.record_scoped_metric = false txn.add_segment(segment) segment.start @@ -187,15 +187,15 @@ def test_segment_can_disable_scoped_metric_recording_with_unscoped_as_frozen_arr end assert_metrics_recorded [ - "test", - "Custom/simple/segment", - "Segment/all", - "Segment/allOther", - "OtherTransactionTotalTime", - "OtherTransactionTotalTime/test", - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all", - "Supportability/API/recording_web_transaction?", - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allOther" + 'test', + 'Custom/simple/segment', + 'Segment/all', + 'Segment/allOther', + 'OtherTransactionTotalTime', + 'OtherTransactionTotalTime/test', + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/all', + 'Supportability/API/recording_web_transaction?', + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/allOther' ] end @@ -284,38 +284,38 @@ def test_sets_start_time_from_constructor def test_adding_agent_attributes in_transaction do |txn| - txn.add_agent_attribute(:foo, "bar", AttributeFilter::DST_ALL) + txn.add_agent_attribute(:foo, 'bar', AttributeFilter::DST_ALL) segment = NewRelic::Agent::Tracer.current_segment actual = segment.attributes.agent_attributes_for(AttributeFilter::DST_SPAN_EVENTS) - assert_equal({:foo => "bar"}, actual) + assert_equal({:foo => 'bar'}, actual) end end def test_request_attributes_in_agent_attributes request_attributes = { - :referer => "/referred", - :path => "/", + :referer => '/referred', + :path => '/', :content_length => 0, - :content_type => "application/json", - :host => "foo.foo", - :user_agent => "Use This!", - :request_method => "GET" + :content_type => 'application/json', + :host => 'foo.foo', + :user_agent => 'Use This!', + :request_method => 'GET' } - request = stub("request", request_attributes) + request = stub('request', request_attributes) txn = in_transaction(:request => request) do end segment = txn.segments[0] actual = segment.attributes.agent_attributes_for(AttributeFilter::DST_SPAN_EVENTS) - assert_equal "/referred", actual[:'request.headers.referer'] - assert_equal "/", actual[:'request.uri'] + assert_equal '/referred', actual[:'request.headers.referer'] + assert_equal '/', actual[:'request.uri'] assert_equal 0, actual[:'request.headers.contentLength'] - assert_equal "application/json", actual[:"request.headers.contentType"] - assert_equal "foo.foo", actual[:'request.headers.host'] - assert_equal "Use This!", actual[:'request.headers.userAgent'] - assert_equal "GET", actual[:'request.method'] + assert_equal 'application/json', actual[:"request.headers.contentType"] + assert_equal 'foo.foo', actual[:'request.headers.host'] + assert_equal 'Use This!', actual[:'request.headers.userAgent'] + assert_equal 'GET', actual[:'request.method'] end def test_transaction_response_attributes_included_in_agent_attributes @@ -330,19 +330,19 @@ def test_transaction_response_attributes_included_in_agent_attributes assert_equal 418, actual[:"http.statusCode"] assert_equal 100, actual[:"response.headers.contentLength"] - assert_equal "application/json", actual[:"response.headers.contentType"] + assert_equal 'application/json', actual[:"response.headers.contentType"] end def test_referer_in_agent_attributes segment = nil - request = stub('request', :referer => "/referred", :path => "/") + request = stub('request', :referer => '/referred', :path => '/') txn = in_transaction(:request => request) do end segment = txn.segments[0] actual = segment.attributes.agent_attributes_for(AttributeFilter::DST_SPAN_EVENTS) - assert_equal "/referred", actual[:'request.headers.referer'] + assert_equal '/referred', actual[:'request.headers.referer'] end def test_self_finish_returns_early @@ -377,13 +377,13 @@ def capture_nested_segment_with_error parent_segment = nil with_segment do |segment| parent_segment = segment - segment_with_error = Tracer.start_segment(name: "nested_test", parent: segment) - raise "oops!" + segment_with_error = Tracer.start_segment(name: 'nested_test', parent: segment) + raise 'oops!' end rescue Exception => exception segment_with_error.finish - assert segment_with_error, "expected to have a segment_with_error" + assert segment_with_error, 'expected to have a segment_with_error' build_deferred_error_attributes(segment_with_error) refute_equal parent_segment, segment_with_error diff --git a/test/new_relic/agent/transaction/trace_builder_test.rb b/test/new_relic/agent/transaction/trace_builder_test.rb index 5a921df5fb..e8aa7e8862 100644 --- a/test/new_relic/agent/transaction/trace_builder_test.rb +++ b/test/new_relic/agent/transaction/trace_builder_test.rb @@ -16,16 +16,16 @@ def setup def test_builds_trace_for_transaction txn = nil state = Tracer.state - Tracer.in_transaction(name: "test_txn", category: :controller) do + Tracer.in_transaction(name: 'test_txn', category: :controller) do txn = state.current_transaction advance_process_time(1) - segment_a = Tracer.start_segment(name: "segment_a") - segment_a.params[:foo] = "bar" + segment_a = Tracer.start_segment(name: 'segment_a') + segment_a.params[:foo] = 'bar' advance_process_time(1) - segment_b = Tracer.start_segment(name: "segment_b") + segment_b = Tracer.start_segment(name: 'segment_b') advance_process_time(2) segment_b.finish - segment_c = Tracer.start_segment(name: "segment_c") + segment_c = Tracer.start_segment(name: 'segment_c') advance_process_time(3) segment_c.finish segment_a.finish @@ -35,32 +35,32 @@ def test_builds_trace_for_transaction root = trace.root_node - assert_equal "ROOT", root.metric_name + assert_equal 'ROOT', root.metric_name assert_in_delta(0.0, root.entry_timestamp) assert_in_delta(7.0, root.exit_timestamp) txn_segment = root.children[0] - assert_equal "test_txn", txn_segment.metric_name + assert_equal 'test_txn', txn_segment.metric_name assert_in_delta(0.0, txn_segment.entry_timestamp) assert_in_delta(7.0, txn_segment.exit_timestamp) segment_a = txn_segment.children[0] - assert_equal "segment_a", segment_a.metric_name + assert_equal 'segment_a', segment_a.metric_name assert_in_delta(1.0, segment_a.entry_timestamp) assert_in_delta(7.0, segment_a.exit_timestamp) - assert_equal "bar", segment_a.params[:foo] + assert_equal 'bar', segment_a.params[:foo] segment_b = segment_a.children[0] - assert_equal "segment_b", segment_b.metric_name + assert_equal 'segment_b', segment_b.metric_name assert_in_delta(2.0, segment_b.entry_timestamp) assert_in_delta(4.0, segment_b.exit_timestamp) segment_c = segment_a.children[1] - assert_equal "segment_c", segment_c.metric_name + assert_equal 'segment_c', segment_c.metric_name assert_in_delta(4.0, segment_c.entry_timestamp) assert_in_delta(7.0, segment_c.exit_timestamp) end @@ -68,10 +68,10 @@ def test_builds_trace_for_transaction def test_trace_built_if_segment_left_unfinished txn = nil state = Tracer.state - Tracer.in_transaction(name: "test_txn", category: :controller) do + Tracer.in_transaction(name: 'test_txn', category: :controller) do txn = state.current_transaction advance_process_time(1) - Tracer.start_segment(name: "segment_a") + Tracer.start_segment(name: 'segment_a') advance_process_time(1) end @@ -79,19 +79,19 @@ def test_trace_built_if_segment_left_unfinished root = trace.root_node - assert_equal "ROOT", root.metric_name + assert_equal 'ROOT', root.metric_name assert_in_delta(0.0, root.entry_timestamp) assert_in_delta(2.0, root.exit_timestamp) txn_segment = root.children[0] - assert_equal "test_txn", txn_segment.metric_name + assert_equal 'test_txn', txn_segment.metric_name assert_in_delta(0.0, txn_segment.entry_timestamp) assert_in_delta(2.0, txn_segment.exit_timestamp) segment_a = txn_segment.children[0] - assert_equal "segment_a", segment_a.metric_name + assert_equal 'segment_a', segment_a.metric_name assert_in_delta(1.0, segment_a.entry_timestamp) assert_in_delta(2.0, segment_a.exit_timestamp) end diff --git a/test/new_relic/agent/transaction/trace_context_test.rb b/test/new_relic/agent/transaction/trace_context_test.rb index 78083ed89f..10aa80c0b6 100644 --- a/test/new_relic/agent/transaction/trace_context_test.rb +++ b/test/new_relic/agent/transaction/trace_context_test.rb @@ -14,9 +14,9 @@ def setup @config = { :'distributed_tracing.enabled' => true, :'span_events.enabled' => true, - :account_id => "190", - :primary_application_id => "46954", - :trusted_account_key => "999999", + :account_id => '190', + :primary_application_id => '46954', + :trusted_account_key => '999999', :disable_harvest_thread => true } NewRelic::Agent.agent.stubs(:connected?).returns(true) @@ -55,7 +55,7 @@ def test_insert_trace_context_header assert_equal trace_state, carrier['tracestate'] - assert_metrics_recorded "Supportability/TraceContext/Create/Success" + assert_metrics_recorded 'Supportability/TraceContext/Create/Success' end def test_insert_trace_context_non_root @@ -285,11 +285,11 @@ def test_do_not_accept_trace_context_if_trace_context_already_accepted trace_state_payload = txn.distributed_tracer.create_trace_state_payload trace_context_header_data = make_trace_context_header_data(trace_state_payload: trace_state_payload) - assert txn.distributed_tracer.accept_trace_context(trace_context_header_data), "Expected first trace context to be accepted" - refute txn.distributed_tracer.accept_trace_context(trace_context_header_data), "Expected second trace context not to be accepted" + assert txn.distributed_tracer.accept_trace_context(trace_context_header_data), 'Expected first trace context to be accepted' + refute txn.distributed_tracer.accept_trace_context(trace_context_header_data), 'Expected second trace context not to be accepted' end - assert_metrics_recorded "Supportability/TraceContext/Accept/Ignored/Multiple" + assert_metrics_recorded 'Supportability/TraceContext/Accept/Ignored/Multiple' end def test_records_a_no_nr_entry_trace_state_metric @@ -308,7 +308,7 @@ def test_records_a_no_nr_entry_trace_state_metric child.distributed_tracer.insert_trace_context_header(carrier) end - assert_metrics_recorded "Supportability/TraceContext/TraceState/NoNrEntry" + assert_metrics_recorded 'Supportability/TraceContext/TraceState/NoNrEntry' end def test_records_an_invalid_trace_state_metric @@ -318,10 +318,10 @@ def test_records_an_invalid_trace_state_metric trace_context_header_data = make_trace_context_header_data(trace_state_payload: trace_state_payload) trace_state_payload.stubs(:valid?).returns(false) - refute txn.distributed_tracer.accept_trace_context(trace_context_header_data), "Expected trace context to be rejected" + refute txn.distributed_tracer.accept_trace_context(trace_context_header_data), 'Expected trace context to be rejected' end - assert_metrics_recorded "Supportability/TraceContext/TraceState/InvalidNrEntry" + assert_metrics_recorded 'Supportability/TraceContext/TraceState/InvalidNrEntry' end def test_do_not_accept_trace_context_if_txn_has_already_generated_trace_context @@ -335,7 +335,7 @@ def test_do_not_accept_trace_context_if_txn_has_already_generated_trace_context refute txn.distributed_tracer.accept_trace_context(trace_context_header_data) end - assert_metrics_recorded "Supportability/TraceContext/Accept/Ignored/CreateBeforeAccept" + assert_metrics_recorded 'Supportability/TraceContext/Accept/Ignored/CreateBeforeAccept' end def test_creates_trace_context_payload @@ -450,9 +450,9 @@ def make_trace_parent(options) }.update(options) end - def make_trace_context_header_data(trace_parent: "00-a8e67265afe2773a3c611b94306ee5c2-fb1010463ea28a38-01", + def make_trace_context_header_data(trace_parent: '00-a8e67265afe2773a3c611b94306ee5c2-fb1010463ea28a38-01', trace_state_payload: nil, - trace_state: ["other=asdf"], + trace_state: ['other=asdf'], trace_state_vendors: '') NewRelic::Agent::DistributedTracing::TraceContext::HeaderData.new(trace_parent, trace_state_payload, trace_state, 10, trace_state_vendors) end diff --git a/test/new_relic/agent/transaction/trace_node_test.rb b/test/new_relic/agent/transaction/trace_node_test.rb index 5b4124abb9..3fa8c8b2ee 100644 --- a/test/new_relic/agent/transaction/trace_node_test.rb +++ b/test/new_relic/agent/transaction/trace_node_test.rb @@ -53,7 +53,7 @@ def test_to_array def test_to_array_with_bad_values node = NewRelic::Agent::Transaction::TraceNode.new(nil, nil) node.end_trace(Rational(10, 1)) - expected = [0, 10_000.0, "", {}, []] + expected = [0, 10_000.0, '', {}, []] assert_equal(expected, node.to_array) end @@ -61,26 +61,26 @@ def test_to_array_with_bad_values def test_path_string s = NewRelic::Agent::Transaction::TraceNode.new('Custom/test/metric', Process.clock_gettime(Process::CLOCK_REALTIME)) - assert_equal("Custom/test/metric[]", s.path_string) + assert_equal('Custom/test/metric[]', s.path_string) fake_node = mock('node') fake_node.expects(:path_string).returns('Custom/other/metric[]') s.children << fake_node - assert_equal("Custom/test/metric[Custom/other/metric[]]", s.path_string) + assert_equal('Custom/test/metric[Custom/other/metric[]]', s.path_string) end def test_to_s_compact s = NewRelic::Agent::Transaction::TraceNode.new('Custom/test/metric', Process.clock_gettime(Process::CLOCK_REALTIME)) - assert_equal("Custom/test/metric", s.to_s_compact) + assert_equal('Custom/test/metric', s.to_s_compact) fake_node = mock('node') fake_node.expects(:to_s_compact).returns('Custom/other/metric') s.children << fake_node - assert_equal("Custom/test/metric{Custom/other/metric}", s.to_s_compact) + assert_equal('Custom/test/metric{Custom/other/metric}', s.to_s_compact) end def test_to_debug_str_basic @@ -105,7 +105,7 @@ def test_to_debug_str_closed def test_to_debug_str_closed_with_nonnumeric s = NewRelic::Agent::Transaction::TraceNode.new('Custom/test/metric', 0.0) - s.end_trace("0.1") + s.end_trace('0.1') assert_equal(">> 0 ms [TraceNode] Custom/test/metric \n<< 0.1 Custom/test/metric\n", s.to_debug_str(0)) end @@ -295,25 +295,25 @@ def test_explain_sql_raising_an_error statement.config = config statement.explainer = NewRelic::Agent::Instrumentation::ActiveRecord::EXPLAINER s.params = {:sql => statement} - NewRelic::Agent::Database.expects(:get_connection).with(config).raises(RuntimeError.new("whee")) + NewRelic::Agent::Database.expects(:get_connection).with(config).raises(RuntimeError.new('whee')) s.explain_sql end def test_explain_sql_can_handle_missing_config # If TT node came over from Resque child, might not be a Statement s = NewRelic::Agent::Transaction::TraceNode.new('Custom/test/metric', Process.clock_gettime(Process::CLOCK_REALTIME)) - s.params = {:sql => "SELECT * FROM galaxy"} + s.params = {:sql => 'SELECT * FROM galaxy'} s.explain_sql end def test_explain_sql_can_use_already_existing_plan s = NewRelic::Agent::Transaction::TraceNode.new('Custom/test/metric', Process.clock_gettime(Process::CLOCK_REALTIME)) s.params = { - :sql => "SELECT * FROM galaxy", - :explain_plan => "EXPLAIN IT!" + :sql => 'SELECT * FROM galaxy', + :explain_plan => 'EXPLAIN IT!' } - assert_equal("EXPLAIN IT!", s.explain_sql) + assert_equal('EXPLAIN IT!', s.explain_sql) end def test_params_equal diff --git a/test/new_relic/agent/transaction/trace_test.rb b/test/new_relic/agent/transaction/trace_test.rb index 60c9510287..71d8894f8e 100644 --- a/test/new_relic/agent/transaction/trace_test.rb +++ b/test/new_relic/agent/transaction/trace_test.rb @@ -63,7 +63,7 @@ def test_collector_array_contains_start_time def test_root_node assert_in_delta(0.0, @trace.root_node.entry_timestamp) - assert_equal "ROOT", @trace.root_node.metric_name + assert_equal 'ROOT', @trace.root_node.metric_name end def test_prepare_to_send_returns_self @@ -108,7 +108,7 @@ def test_prepare_to_send_collects_explain_plans node = @trace.create_node(0.0, 'has_sql') node.stubs(:duration).returns(2) node.stubs(:explain_sql).returns('') - node[:sql] = NewRelic::Agent::Database::Statement.new("select * from pelicans") + node[:sql] = NewRelic::Agent::Database::Statement.new('select * from pelicans') @trace.root_node.children << node @@ -129,7 +129,7 @@ def test_prepare_to_send_prepares_sql_for_transmission @trace.prepare_to_send! - assert_equal "select * from pelicans where name = ?;", node[:sql] + assert_equal 'select * from pelicans where name = ?;', node[:sql] end def test_prepare_to_send_strips_sql @@ -216,7 +216,7 @@ def test_prepare_sql_for_transmission_obfuscates_sql_if_record_sql_method_is_obf @trace.prepare_sql_for_transmission! - assert_equal "select * from pelicans where name = ?;", node[:sql] + assert_equal 'select * from pelicans where name = ?;', node[:sql] end def test_prepare_sql_for_transmission_does_not_modify_sql_if_record_sql_method_is_raw @@ -354,7 +354,7 @@ def test_trace_tree_contains_attributes expected = { 'agentAttributes' => {:foo => 'bar'}, - 'userAttributes' => {"foo" => 'bar'}, + 'userAttributes' => {'foo' => 'bar'}, 'intrinsics' => {:foo => 'bar'} } diff --git a/test/new_relic/agent/transaction/tracing_test.rb b/test/new_relic/agent/transaction/tracing_test.rb index b69eb6542d..c159e310d0 100644 --- a/test/new_relic/agent/transaction/tracing_test.rb +++ b/test/new_relic/agent/transaction/tracing_test.rb @@ -20,26 +20,26 @@ def teardown end def test_segment_bound_to_transaction_records_metrics - in_transaction("test_txn") do + in_transaction('test_txn') do segment = Tracer.start_segment( - name: "Custom/simple/segment", - unscoped_metrics: "Segment/all" + name: 'Custom/simple/segment', + unscoped_metrics: 'Segment/all' ) segment.start advance_process_time(1.0) segment.finish - refute_metrics_recorded ["Custom/simple/segment", "Segment/all"] + refute_metrics_recorded ['Custom/simple/segment', 'Segment/all'] end - assert_metrics_recorded ["Custom/simple/segment", "Segment/all"] + assert_metrics_recorded ['Custom/simple/segment', 'Segment/all'] end def test_segment_bound_to_transaction_invokes_complete_callback_when_finished - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| segment = Tracer.start_segment( - name: "Custom/simple/segment", - unscoped_metrics: "Segment/all" + name: 'Custom/simple/segment', + unscoped_metrics: 'Segment/all' ) txn.expects(:segment_complete).with(segment) segment.start @@ -54,11 +54,11 @@ def test_segment_bound_to_transaction_invokes_complete_callback_when_finished def test_segment_data_is_copied_to_trace segment = nil - segment_name = "Custom/simple/segment" - in_transaction("test_txn") do + segment_name = 'Custom/simple/segment' + in_transaction('test_txn') do segment = Tracer.start_segment( name: segment_name, - unscoped_metrics: "Segment/all" + unscoped_metrics: 'Segment/all' ) segment.start advance_process_time(1.0) @@ -73,8 +73,8 @@ def test_segment_data_is_copied_to_trace end def test_start_segment - in_transaction("test_txn") do |txn| - segment = Tracer.start_segment(name: "Custom/segment/method") + in_transaction('test_txn') do |txn| + segment = Tracer.start_segment(name: 'Custom/segment/method') assert_equal Process.clock_gettime(Process::CLOCK_REALTIME), segment.start_time assert_equal txn, segment.transaction @@ -90,9 +90,9 @@ def test_start_segment_with_time_override start_time = Process.clock_gettime(Process::CLOCK_REALTIME) advance_process_time(2) - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| segment = Tracer.start_segment( - name: "Custom/segment/method", + name: 'Custom/segment/method', start_time: start_time ) @@ -104,11 +104,11 @@ def test_start_segment_with_time_override end def test_start_datastore_segment - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| segment = Tracer.start_datastore_segment( - product: "SQLite", - operation: "insert", - collection: "Blog" + product: 'SQLite', + operation: 'insert', + collection: 'Blog' ) assert_equal Process.clock_gettime(Process::CLOCK_REALTIME), segment.start_time @@ -125,60 +125,60 @@ def test_start_datastore_segment_provides_defaults_without_params segment = Tracer.start_datastore_segment segment.finish - assert_equal "Datastore/operation/Unknown/other", segment.name - assert_equal "Unknown", segment.product - assert_equal "other", segment.operation + assert_equal 'Datastore/operation/Unknown/other', segment.name + assert_equal 'Unknown', segment.product + assert_equal 'other', segment.operation end def test_start_datastore_segment_does_not_record_metrics_outside_of_txn segment = Tracer.start_datastore_segment( - product: "SQLite", - operation: "insert", - collection: "Blog" + product: 'SQLite', + operation: 'insert', + collection: 'Blog' ) segment.start advance_process_time(1) segment.finish refute_metrics_recorded [ - "Datastore/statement/SQLite/Blog/insert", - "Datastore/operation/SQLite/insert", - "Datastore/SQLite/allWeb", - "Datastore/SQLite/all", - "Datastore/allWeb", - "Datastore/all" + 'Datastore/statement/SQLite/Blog/insert', + 'Datastore/operation/SQLite/insert', + 'Datastore/SQLite/allWeb', + 'Datastore/SQLite/all', + 'Datastore/allWeb', + 'Datastore/all' ] end def test_start_segment_with_tracing_disabled_in_transaction segment = nil - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| NewRelic::Agent.disable_all_tracing do segment = Tracer.start_segment( - name: "Custom/segment/method", - unscoped_metrics: "Custom/all" + name: 'Custom/segment/method', + unscoped_metrics: 'Custom/all' ) advance_process_time(1) segment.finish end end - assert_nil segment.transaction, "Did not expect segment to associated with a transaction" - refute_metrics_recorded ["Custom/segment/method", "Custom/all"] + assert_nil segment.transaction, 'Did not expect segment to associated with a transaction' + refute_metrics_recorded ['Custom/segment/method', 'Custom/all'] end def test_current_segment_in_transaction - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| assert_equal txn.initial_segment, txn.current_segment ds_segment = Tracer.start_datastore_segment( - product: "SQLite", - operation: "insert", - collection: "Blog" + product: 'SQLite', + operation: 'insert', + collection: 'Blog' ) assert_equal ds_segment, txn.current_segment - segment = Tracer.start_segment(name: "Custom/basic/segment") + segment = Tracer.start_segment(name: 'Custom/basic/segment') assert_equal segment, txn.current_segment @@ -193,18 +193,18 @@ def test_current_segment_in_transaction end def test_segments_are_properly_parented - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| assert_nil txn.initial_segment.parent ds_segment = Tracer.start_datastore_segment( - product: "SQLite", - operation: "insert", - collection: "Blog" + product: 'SQLite', + operation: 'insert', + collection: 'Blog' ) assert_equal txn.initial_segment, ds_segment.parent - segment = Tracer.start_segment(name: "Custom/basic/segment") + segment = Tracer.start_segment(name: 'Custom/basic/segment') assert_equal ds_segment, segment.parent @@ -215,29 +215,29 @@ def test_segments_are_properly_parented def test_segment_started_outside_txn_does_not_record_metrics segment = Tracer.start_segment( - name: "Custom/segment/method", - unscoped_metrics: "Custom/all" + name: 'Custom/segment/method', + unscoped_metrics: 'Custom/all' ) advance_process_time(1) segment.finish - assert_nil segment.transaction, "Did not expect segment to associated with a transaction" - refute_metrics_recorded ["Custom/segment/method", "Custom/all"] + assert_nil segment.transaction, 'Did not expect segment to associated with a transaction' + refute_metrics_recorded ['Custom/segment/method', 'Custom/all'] end def test_start_external_request_segment - in_transaction("test_txn") do |txn| + in_transaction('test_txn') do |txn| segment = Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://site.com/endpoint", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://site.com/endpoint', + procedure: 'GET' ) assert_equal Process.clock_gettime(Process::CLOCK_REALTIME), segment.start_time assert_equal txn, segment.transaction - assert_equal "Net::HTTP", segment.library - assert_equal "http://site.com/endpoint", segment.uri.to_s - assert_equal "GET", segment.procedure + assert_equal 'Net::HTTP', segment.library + assert_equal 'http://site.com/endpoint', segment.uri.to_s + assert_equal 'GET', segment.procedure advance_process_time(1) segment.finish @@ -248,38 +248,38 @@ def test_start_external_request_segment def test_segment_does_not_record_metrics_outside_of_txn segment = Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET' ) segment.finish refute_metrics_recorded [ - "External/remotehost.com/Net::HTTP/GET", - "External/all", - "External/remotehost.com/all", - "External/allWeb", - ["External/remotehost.com/Net::HTTP/GET", "test"] + 'External/remotehost.com/Net::HTTP/GET', + 'External/all', + 'External/remotehost.com/all', + 'External/allWeb', + ['External/remotehost.com/Net::HTTP/GET', 'test'] ] end def test_children_time segment_a, segment_b, segment_c, segment_d = nil, nil, nil, nil - in_transaction("test") do - segment_a = NewRelic::Agent::Tracer.start_segment(name: "metric a") + in_transaction('test') do + segment_a = NewRelic::Agent::Tracer.start_segment(name: 'metric a') advance_process_time(0.001) - segment_b = NewRelic::Agent::Tracer.start_segment(name: "metric b") + segment_b = NewRelic::Agent::Tracer.start_segment(name: 'metric b') advance_process_time(0.002) - segment_c = NewRelic::Agent::Tracer.start_segment(name: "metric c") + segment_c = NewRelic::Agent::Tracer.start_segment(name: 'metric c') advance_process_time(0.003) segment_c.finish advance_process_time(0.001) - segment_d = NewRelic::Agent::Tracer.start_segment(name: "metric d") + segment_d = NewRelic::Agent::Tracer.start_segment(name: 'metric d') advance_process_time(0.002) segment_d.finish @@ -441,7 +441,7 @@ def test_txn_not_recorded_when_tracing_is_disabled def test_trace_should_log_segment_limit_reached_once with_config(:'transaction_tracer.limit_segments' => 3) do in_transaction do |txn| - expects_logging(:debug, includes("Segment limit")) + expects_logging(:debug, includes('Segment limit')) 8.times { |i| NewRelic::Agent::Tracer.start_segment(name: "segment_#{i}") } end end @@ -461,7 +461,7 @@ def test_sets_start_time_from_api in_transaction do |txn| segment = NewRelic::Agent::Tracer.start_segment( - name: "segment_a", + name: 'segment_a', start_time: t ) segment.finish @@ -499,9 +499,9 @@ def test_flexible_parenting_datastore_segment segment_a = NewRelic::Agent::Tracer.start_segment(name: 'segment_a') segment_b = NewRelic::Agent::Tracer.start_segment(name: 'segment_b') segment_c = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "Select", - collection: "blogs", + product: 'SQLite', + operation: 'Select', + collection: 'blogs', parent: segment_a ) segment_c.finish @@ -518,9 +518,9 @@ def test_flexible_parenting_external_request_segment segment_a = NewRelic::Agent::Tracer.start_segment(name: 'segment_a') segment_b = NewRelic::Agent::Tracer.start_segment(name: 'segment_b') segment_c = NewRelic::Agent::Tracer.start_external_request_segment( - library: "MyLib", - uri: "https://blog.newrelic.com", - procedure: "GET", + library: 'MyLib', + uri: 'https://blog.newrelic.com', + procedure: 'GET', parent: segment_a ) segment_c.finish @@ -538,9 +538,9 @@ def test_flexible_parenting_message_broker_segment segment_b = NewRelic::Agent::Tracer.start_segment(name: 'segment_b') segment_c = NewRelic::Agent::Tracer.start_message_broker_segment( action: :produce, - library: "RabbitMQ", + library: 'RabbitMQ', destination_type: :exchange, - destination_name: "Default", + destination_name: 'Default', parent: segment_a ) segment_c.finish @@ -603,22 +603,22 @@ def test_parent_identifies_concurrent_children def test_concurrent_durations segment_a, segment_b, segment_c, segment_d = nil, nil, nil, nil - in_transaction("test") do - segment_a = NewRelic::Agent::Tracer.start_segment(name: "metric a") + in_transaction('test') do + segment_a = NewRelic::Agent::Tracer.start_segment(name: 'metric a') advance_process_time(2) - segment_b = NewRelic::Agent::Tracer.start_segment(name: "metric b") + segment_b = NewRelic::Agent::Tracer.start_segment(name: 'metric b') advance_process_time(1) segment_c = NewRelic::Agent::Tracer.start_segment( - name: "metric c", + name: 'metric c', parent: segment_a ) advance_process_time(1) segment_d = NewRelic::Agent::Tracer.start_segment( - name: "metric d", + name: 'metric d', parent: segment_a ) @@ -659,15 +659,15 @@ def test_concurrent_durations def test_child_segment_ends_after_parent_durations_correct segment_a, segment_b, segment_c = nil, nil, nil - in_transaction("test") do - segment_a = NewRelic::Agent::Tracer.start_segment(name: "metric a") + in_transaction('test') do + segment_a = NewRelic::Agent::Tracer.start_segment(name: 'metric a') advance_process_time(1) - segment_b = NewRelic::Agent::Tracer.start_segment(name: "metric b") + segment_b = NewRelic::Agent::Tracer.start_segment(name: 'metric b') advance_process_time(2) segment_b.finish - segment_c = NewRelic::Agent::Tracer.start_segment(name: "metric c") + segment_c = NewRelic::Agent::Tracer.start_segment(name: 'metric c') advance_process_time(3) segment_a.finish @@ -701,19 +701,19 @@ def test_child_segment_ends_after_parent_durations_correct def test_durations_correct_with_sync_child_followed_by_concurrent_children segment_a, segment_b, segment_c, segment_d = nil, nil, nil, nil - in_transaction("test") do - segment_a = NewRelic::Agent::Tracer.start_segment(name: "metric a") + in_transaction('test') do + segment_a = NewRelic::Agent::Tracer.start_segment(name: 'metric a') advance_process_time(1) - segment_b = NewRelic::Agent::Tracer.start_segment(name: "metric b") + segment_b = NewRelic::Agent::Tracer.start_segment(name: 'metric b') advance_process_time(2) segment_b.finish - segment_c = NewRelic::Agent::Tracer.start_segment(name: "metric c") + segment_c = NewRelic::Agent::Tracer.start_segment(name: 'metric c') advance_process_time(1) segment_d = NewRelic::Agent::Tracer.start_segment( - name: "metric d", + name: 'metric d', parent: segment_a ) @@ -741,17 +741,17 @@ def test_durations_correct_with_sync_child_followed_by_concurrent_children def test_transaction_detects_async_when_there_are_concurrent_children segment_a, segment_b, segment_c = nil, nil, nil - in_transaction("test") do |txn| - segment_a = NewRelic::Agent::Tracer.start_segment(name: "metric a") + in_transaction('test') do |txn| + segment_a = NewRelic::Agent::Tracer.start_segment(name: 'metric a') advance_process_time(2) - segment_b = NewRelic::Agent::Tracer.start_segment(name: "metric b") + segment_b = NewRelic::Agent::Tracer.start_segment(name: 'metric b') advance_process_time(1) refute txn.async? segment_c = NewRelic::Agent::Tracer.start_segment( - name: "metric c", + name: 'metric c', parent: segment_a ) @@ -771,18 +771,18 @@ def test_transaction_detects_async_when_there_are_concurrent_children def test_transaction_detects_async_when_child_ends_after_parent segment_a, segment_b, segment_c = nil, nil, nil - in_transaction("test") do |txn| - segment_a = NewRelic::Agent::Tracer.start_segment(name: "metric a") + in_transaction('test') do |txn| + segment_a = NewRelic::Agent::Tracer.start_segment(name: 'metric a') advance_process_time(1) - segment_b = NewRelic::Agent::Tracer.start_segment(name: "metric b") + segment_b = NewRelic::Agent::Tracer.start_segment(name: 'metric b') advance_process_time(2) segment_b.finish - refute txn.async?, "Expected transaction not to be asynchronous" + refute txn.async?, 'Expected transaction not to be asynchronous' - segment_c = NewRelic::Agent::Tracer.start_segment(name: "metric c") + segment_c = NewRelic::Agent::Tracer.start_segment(name: 'metric c') advance_process_time(3) segment_a.finish @@ -790,22 +790,22 @@ def test_transaction_detects_async_when_child_ends_after_parent advance_process_time(4) segment_c.finish - assert_predicate txn, :async?, "Expected transaction to be asynchronous" + assert_predicate txn, :async?, 'Expected transaction to be asynchronous' end end def test_transaction_records_exclusive_duration_millis_segment_param_when_transaction_async segment_a, segment_b, segment_c = nil, nil, nil - in_transaction("test") do - segment_a = NewRelic::Agent::Tracer.start_segment(name: "metric a") + in_transaction('test') do + segment_a = NewRelic::Agent::Tracer.start_segment(name: 'metric a') advance_process_time(2) - segment_b = NewRelic::Agent::Tracer.start_segment(name: "metric b") + segment_b = NewRelic::Agent::Tracer.start_segment(name: 'metric b') advance_process_time(1) segment_c = NewRelic::Agent::Tracer.start_segment( - name: "metric c", + name: 'metric c', parent: segment_a ) @@ -837,19 +837,19 @@ def test_transaction_records_exclusive_duration_millis_segment_param_when_transa def test_total_time_metrics_async_sync_children_non_web segment_a, segment_b, segment_c, segment_d = nil, nil, nil, nil - transaction = in_transaction("test") do - segment_a = NewRelic::Agent::Tracer.start_segment(name: "metric a") + transaction = in_transaction('test') do + segment_a = NewRelic::Agent::Tracer.start_segment(name: 'metric a') advance_process_time(1) - segment_b = NewRelic::Agent::Tracer.start_segment(name: "metric b") + segment_b = NewRelic::Agent::Tracer.start_segment(name: 'metric b') advance_process_time(2) segment_b.finish - segment_c = NewRelic::Agent::Tracer.start_segment(name: "metric c") + segment_c = NewRelic::Agent::Tracer.start_segment(name: 'metric c') advance_process_time(1) segment_d = NewRelic::Agent::Tracer.start_segment( - name: "metric d", + name: 'metric d', parent: segment_a ) @@ -865,13 +865,13 @@ def test_total_time_metrics_async_sync_children_non_web assert_in_delta(9.0, transaction.total_time) assert_metrics_recorded( - "OtherTransactionTotalTime" => + 'OtherTransactionTotalTime' => { :call_count => 1, :total_call_time => 9.0, :total_exclusive_time => 9.0 }, - "OtherTransactionTotalTime/test" => + 'OtherTransactionTotalTime/test' => { :call_count => 1, :total_call_time => 9.0, @@ -883,19 +883,19 @@ def test_total_time_metrics_async_sync_children_non_web def test_total_time_metrics_async_sync_children_web segment_a, segment_b, segment_c, segment_d = nil, nil, nil, nil - transaction = in_web_transaction("test") do - segment_a = NewRelic::Agent::Tracer.start_segment(name: "metric a") + transaction = in_web_transaction('test') do + segment_a = NewRelic::Agent::Tracer.start_segment(name: 'metric a') advance_process_time(1) - segment_b = NewRelic::Agent::Tracer.start_segment(name: "metric b") + segment_b = NewRelic::Agent::Tracer.start_segment(name: 'metric b') advance_process_time(2) segment_b.finish - segment_c = NewRelic::Agent::Tracer.start_segment(name: "metric c") + segment_c = NewRelic::Agent::Tracer.start_segment(name: 'metric c') advance_process_time(1) segment_d = NewRelic::Agent::Tracer.start_segment( - name: "metric d", + name: 'metric d', parent: segment_a ) @@ -911,13 +911,13 @@ def test_total_time_metrics_async_sync_children_web assert_in_delta(9.0, transaction.total_time) assert_metrics_recorded( - "WebTransactionTotalTime" => + 'WebTransactionTotalTime' => { :call_count => 1, :total_call_time => 9.0, :total_exclusive_time => 9.0 }, - "WebTransactionTotalTime/test" => + 'WebTransactionTotalTime/test' => { :call_count => 1, :total_call_time => 9.0, @@ -945,19 +945,19 @@ def test_total_time_metrics_async_sync_children_web def test_times_accurate_when_child_finishes_after_parent segment_a, segment_b, segment_c, segment_d = nil, nil, nil, nil - txn = in_transaction("test") do - segment_a = NewRelic::Agent::Tracer.start_segment(name: "metric a") + txn = in_transaction('test') do + segment_a = NewRelic::Agent::Tracer.start_segment(name: 'metric a') advance_process_time(1) - segment_b = NewRelic::Agent::Tracer.start_segment(name: "metric b") + segment_b = NewRelic::Agent::Tracer.start_segment(name: 'metric b') advance_process_time(2) segment_b.finish - segment_c = NewRelic::Agent::Tracer.start_segment(name: "metric c") + segment_c = NewRelic::Agent::Tracer.start_segment(name: 'metric c') advance_process_time(1) segment_d = NewRelic::Agent::Tracer.start_segment( - name: "metric d", + name: 'metric d', parent: segment_a ) @@ -1011,21 +1011,21 @@ def test_times_accurate_when_child_finishes_after_parent def test_times_accurate_when_child_finishes_after_parent_more_nesting segment_a, segment_b, segment_c, segment_d, segment_e = nil, nil, nil, nil, nil - txn = in_transaction("test") do - segment_a = NewRelic::Agent::Tracer.start_segment(name: "metric a") + txn = in_transaction('test') do + segment_a = NewRelic::Agent::Tracer.start_segment(name: 'metric a') advance_process_time(1) - segment_b = NewRelic::Agent::Tracer.start_segment(name: "metric b") + segment_b = NewRelic::Agent::Tracer.start_segment(name: 'metric b') - segment_c = NewRelic::Agent::Tracer.start_segment(name: "metric c") + segment_c = NewRelic::Agent::Tracer.start_segment(name: 'metric c') advance_process_time(2) segment_c.finish - segment_d = NewRelic::Agent::Tracer.start_segment(name: "metric d") + segment_d = NewRelic::Agent::Tracer.start_segment(name: 'metric d') advance_process_time(1) segment_e = NewRelic::Agent::Tracer.start_segment( - name: "metric e", + name: 'metric e', parent: segment_b ) diff --git a/test/new_relic/agent/transaction_error_primitive_test.rb b/test/new_relic/agent/transaction_error_primitive_test.rb index 51f5636ba5..e598c1d5e6 100644 --- a/test/new_relic/agent/transaction_error_primitive_test.rb +++ b/test/new_relic/agent/transaction_error_primitive_test.rb @@ -21,10 +21,10 @@ def test_event_includes_expected_intrinsics assert_equal 'TransactionError', intrinsics['type'] assert_in_delta Process.clock_gettime(Process::CLOCK_REALTIME), intrinsics['timestamp'], 0.001 - assert_equal "RuntimeError", intrinsics['error.class'] - assert_equal "Big Controller!", intrinsics['error.message'] + assert_equal 'RuntimeError', intrinsics['error.class'] + assert_equal 'Big Controller!', intrinsics['error.message'] refute intrinsics['error.expected'] - assert_equal "Controller/blogs/index", intrinsics['transactionName'] + assert_equal 'Controller/blogs/index', intrinsics['transactionName'] assert_in_delta(0.1, intrinsics['duration']) assert_equal 80, intrinsics['port'] assert_equal @span_id, intrinsics['spanId'] @@ -59,23 +59,23 @@ def test_includes_mapped_metrics intrinsics, *_ = create_event(:payload_options => {:metrics => metrics}) - assert_in_delta(10.0, intrinsics["databaseDuration"]) - assert_equal 1, intrinsics["databaseCallCount"] - assert_in_delta(11.0, intrinsics["gcCumulative"]) - assert_in_delta(12.0, intrinsics["queueDuration"]) - assert_in_delta(13.0, intrinsics["externalDuration"]) - assert_equal 1, intrinsics["externalCallCount"] + assert_in_delta(10.0, intrinsics['databaseDuration']) + assert_equal 1, intrinsics['databaseCallCount'] + assert_in_delta(11.0, intrinsics['gcCumulative']) + assert_in_delta(12.0, intrinsics['queueDuration']) + assert_in_delta(13.0, intrinsics['externalDuration']) + assert_equal 1, intrinsics['externalCallCount'] end def test_includes_cat_attributes - intrinsics, *_ = create_event(:payload_options => {:guid => "GUID", :referring_transaction_guid => "REFERRING_GUID"}) + intrinsics, *_ = create_event(:payload_options => {:guid => 'GUID', :referring_transaction_guid => 'REFERRING_GUID'}) - assert_equal "GUID", intrinsics["nr.transactionGuid"] - assert_equal "REFERRING_GUID", intrinsics["nr.referringTransactionGuid"] + assert_equal 'GUID', intrinsics['nr.transactionGuid'] + assert_equal 'REFERRING_GUID', intrinsics['nr.referringTransactionGuid'] end def test_includes_custom_attributes - attrs = {"user" => "Wes Mantooth", "channel" => 9} + attrs = {'user' => 'Wes Mantooth', 'channel' => 9} attributes = Attributes.new(NewRelic::Agent.instance.attribute_filter) attributes.merge_custom_attributes(attrs) @@ -87,12 +87,12 @@ def test_includes_custom_attributes def test_includes_agent_attributes attributes = Attributes.new(NewRelic::Agent.instance.attribute_filter) - attributes.add_agent_attribute(:'request.headers.referer', "http://blog.site/home", AttributeFilter::DST_ERROR_COLLECTOR) + attributes.add_agent_attribute(:'request.headers.referer', 'http://blog.site/home', AttributeFilter::DST_ERROR_COLLECTOR) attributes.add_agent_attribute(:'http.statusCode', 200, AttributeFilter::DST_ERROR_COLLECTOR) _, _, agent_attrs = create_event(:error_options => {:attributes => attributes}) - expected = {:"request.headers.referer" => "http://blog.site/home", :'http.statusCode' => 200} + expected = {:"request.headers.referer" => 'http://blog.site/home', :'http.statusCode' => 200} assert_equal expected, agent_attrs end @@ -105,7 +105,7 @@ def create_event(options = {}) def generate_payload(options = {}) { - :name => "Controller/blogs/index", + :name => 'Controller/blogs/index', :type => :controller, :start_timestamp => Process.clock_gettime(Process::CLOCK_REALTIME), :duration => 0.1 @@ -113,11 +113,11 @@ def generate_payload(options = {}) end def create_noticed_error(options = {}) - exception = options.delete(:exception) || RuntimeError.new("Big Controller!") + exception = options.delete(:exception) || RuntimeError.new('Big Controller!') expected = options.fetch(:expected, false) - txn_name = "Controller/blogs/index" + txn_name = 'Controller/blogs/index' noticed_error = NewRelic::NoticedError.new(txn_name, exception) - noticed_error.request_uri = "http://site.com/blogs" + noticed_error.request_uri = 'http://site.com/blogs' noticed_error.request_port = 80 noticed_error.expected = expected noticed_error.attributes = options.delete(:attributes) diff --git a/test/new_relic/agent/transaction_event_aggregator_test.rb b/test/new_relic/agent/transaction_event_aggregator_test.rb index 8679b142e2..07fe0778c8 100644 --- a/test/new_relic/agent/transaction_event_aggregator_test.rb +++ b/test/new_relic/agent/transaction_event_aggregator_test.rb @@ -50,7 +50,7 @@ def aggregator end def name_for(event) - event[0]["name"] + event[0]['name'] end include NewRelic::CommonAggregatorTests @@ -76,7 +76,7 @@ def test_block_is_not_executed_unless_buffer_admits_event end end - assert_nil event, "Did not expect block to be executed" + assert_nil event, 'Did not expect block to be executed' refute_includes last_transaction_events, event end diff --git a/test/new_relic/agent/transaction_event_primitive_test.rb b/test/new_relic/agent/transaction_event_primitive_test.rb index a927da471f..86c4f0001c 100644 --- a/test/new_relic/agent/transaction_event_primitive_test.rb +++ b/test/new_relic/agent/transaction_event_primitive_test.rb @@ -17,12 +17,12 @@ def setup def test_creates_intrinsics intrinsics, *_ = TransactionEventPrimitive.create(generate_payload) - assert_equal "Transaction", intrinsics['type'] + assert_equal 'Transaction', intrinsics['type'] assert_in_delta Process.clock_gettime(Process::CLOCK_REALTIME), intrinsics['timestamp'], 0.001 - assert_equal "Controller/whatever", intrinsics['name'] + assert_equal 'Controller/whatever', intrinsics['name'] refute intrinsics['error'] assert_in_delta(0.1, intrinsics['duration']) - assert intrinsics["priority"].is_a?(Numeric) + assert intrinsics['priority'].is_a?(Numeric) end def test_event_includes_synthetics @@ -115,33 +115,33 @@ def test_samples_on_transaction_finished_event_includes_expected_web_metrics txn_metrics.record_unscoped('WebFrontend/QueueTime', 13) txn_metrics.record_unscoped('External/allWeb', 14) txn_metrics.record_unscoped('Datastore/all', 15) - txn_metrics.record_unscoped("GC/Transaction/all", 16) + txn_metrics.record_unscoped('GC/Transaction/all', 16) event_data, *_ = TransactionEventPrimitive.create(generate_payload('name', :metrics => txn_metrics)) - assert_equal 13, event_data["queueDuration"] - assert_equal 14, event_data["externalDuration"] - assert_equal 15, event_data["databaseDuration"] - assert_equal 16, event_data["gcCumulative"] + assert_equal 13, event_data['queueDuration'] + assert_equal 14, event_data['externalDuration'] + assert_equal 15, event_data['databaseDuration'] + assert_equal 16, event_data['gcCumulative'] - assert_equal 1, event_data["externalCallCount"] - assert_equal 1, event_data["databaseCallCount"] + assert_equal 1, event_data['externalCallCount'] + assert_equal 1, event_data['databaseCallCount'] end def test_samples_on_transaction_finished_includes_expected_background_metrics txn_metrics = NewRelic::Agent::TransactionMetrics.new txn_metrics.record_unscoped('External/allOther', 12) txn_metrics.record_unscoped('Datastore/all', 13) - txn_metrics.record_unscoped("GC/Transaction/all", 14) + txn_metrics.record_unscoped('GC/Transaction/all', 14) event_data, *_ = TransactionEventPrimitive.create(generate_payload('name', :metrics => txn_metrics)) - assert_equal 12, event_data["externalDuration"] - assert_equal 13, event_data["databaseDuration"] - assert_equal 14, event_data["gcCumulative"] + assert_equal 12, event_data['externalDuration'] + assert_equal 13, event_data['databaseDuration'] + assert_equal 14, event_data['gcCumulative'] - assert_equal 1, event_data["databaseCallCount"] - assert_equal 1, event_data["externalCallCount"] + assert_equal 1, event_data['databaseCallCount'] + assert_equal 1, event_data['externalCallCount'] end def test_samples_on_transaction_finished_event_include_apdex_perf_zone @@ -151,15 +151,15 @@ def test_samples_on_transaction_finished_event_include_apdex_perf_zone end def test_samples_on_transaction_finished_event_includes_guid - event_data, *_ = TransactionEventPrimitive.create(generate_payload('name', :guid => "GUID")) + event_data, *_ = TransactionEventPrimitive.create(generate_payload('name', :guid => 'GUID')) - assert_equal "GUID", event_data["nr.guid"] + assert_equal 'GUID', event_data['nr.guid'] end def test_samples_on_transaction_finished_event_includes_referring_transaction_guid - event_data, *_ = TransactionEventPrimitive.create(generate_payload('name', :referring_transaction_guid => "REFER")) + event_data, *_ = TransactionEventPrimitive.create(generate_payload('name', :referring_transaction_guid => 'REFER')) - assert_equal "REFER", event_data["nr.referringTransactionGuid"] + assert_equal 'REFER', event_data['nr.referringTransactionGuid'] end def generate_payload(name = 'whatever', options = {}) diff --git a/test/new_relic/agent/transaction_event_recorder_test.rb b/test/new_relic/agent/transaction_event_recorder_test.rb index 535f20805c..9bff587d70 100644 --- a/test/new_relic/agent/transaction_event_recorder_test.rb +++ b/test/new_relic/agent/transaction_event_recorder_test.rb @@ -34,13 +34,13 @@ def test_synthetics_events_timestamp_bumps_go_to_main_buffer generate_request("syn_#{i}", :timestamp => i + 10, :synthetics_resource_id => 100) end - generate_request("syn_10", :timestamp => 20, :synthetics_resource_id => 100) + generate_request('syn_10', :timestamp => 20, :synthetics_resource_id => 100) _, txn_events = harvest_transaction_events! _, syn_events = harvest_synthetics_events! assert_equal 10, syn_events.size - assert_equal_unordered (10..19).map(&:to_f), syn_events.map { |e| e[0]["timestamp"] } + assert_equal_unordered (10..19).map(&:to_f), syn_events.map { |e| e[0]['timestamp'] } assert_equal 1, txn_events.size end end @@ -54,7 +54,7 @@ def test_normal_events_discarded_in_favor_sampled_events expected = (0..4).map { |i| "Controller/sampled_#{i}" } - assert_equal_unordered expected, events.map { |e| e[0]["name"] } + assert_equal_unordered expected, events.map { |e| e[0]['name'] } end end @@ -67,7 +67,7 @@ def test_sampled_events_not_discarded_in_favor_of_normal_events expected = (0..4).map { |i| "Controller/sampled_#{i}" } - assert_equal_unordered expected, events.map { |e| e[0]["name"] } + assert_equal_unordered expected, events.map { |e| e[0]['name'] } end end diff --git a/test/new_relic/agent/transaction_interrobang_test.rb b/test/new_relic/agent/transaction_interrobang_test.rb index cbb40e9df8..7aacd237f9 100644 --- a/test/new_relic/agent/transaction_interrobang_test.rb +++ b/test/new_relic/agent/transaction_interrobang_test.rb @@ -9,11 +9,11 @@ class TransactionInterrobangTest < Minitest::Test include NewRelic::Agent::Instrumentation::ControllerInstrumentation def interrogate? - "say what?" + 'say what?' end def mutate! - "oh yeah!" + 'oh yeah!' end add_transaction_tracer :interrogate? @@ -22,12 +22,12 @@ def mutate! def test_alias_method_ending_in_question_mark assert_respond_to self, :interrogate? assert_respond_to self, :interrogate_with_newrelic_transaction_trace? - assert_equal "say what?", interrogate? + assert_equal 'say what?', interrogate? end def test_alias_method_ending_in_exclamation_mark assert_respond_to self, :mutate! assert_respond_to self, :mutate_with_newrelic_transaction_trace! - assert_equal "oh yeah!", mutate! + assert_equal 'oh yeah!', mutate! end end diff --git a/test/new_relic/agent/transaction_sampler_test.rb b/test/new_relic/agent/transaction_sampler_test.rb index 465b08eb6c..567dab1c22 100644 --- a/test/new_relic/agent/transaction_sampler_test.rb +++ b/test/new_relic/agent/transaction_sampler_test.rb @@ -10,7 +10,7 @@ class TransactionSamplerTest < Minitest::Test module MockGCStats def time return 0 if @@values.empty? - raise "too many calls" if @@index >= @@values.size + raise 'too many calls' if @@index >= @@values.size @@curtime ||= 0 @@curtime += (@@values[@@index] * 1e09).to_i @@ -203,18 +203,18 @@ def test_sample__gc_stats with_config(:'transaction_tracer.transaction_threshold' => 0.0) do in_transaction('a') do - segment_b = Tracer.start_segment(name: "b") + segment_b = Tracer.start_segment(name: 'b') segment_b.finish - segment_c = Tracer.start_segment(name: "c") - segment_d = Tracer.start_segment(name: "d") + segment_c = Tracer.start_segment(name: 'c') + segment_d = Tracer.start_segment(name: 'd') segment_d.finish segment_c.finish end sample = last_transaction_trace - assert_equal "ROOT{a{b,c{d}}}", sample.to_s_compact + assert_equal 'ROOT{a{b,c{d}}}', sample.to_s_compact end ensure MockGCStats.mock_values = [] @@ -281,7 +281,7 @@ def test_harvest_slowest @sampler.merge!([slowest]) new_slowest = @sampler.harvest![0] - assert((new_slowest != slowest), "Should not harvest the same trace since the new one should be slower") + assert((new_slowest != slowest), 'Should not harvest the same trace since the new one should be slower') assert_equal(10, new_slowest.duration.round, "Slowest duration must be = 10, but was: #{new_slowest.duration.inspect}") end nr_unfreeze_process_time @@ -377,7 +377,7 @@ def test_synthetics_parameters_not_included_if_not_valid_synthetics_request def test_synthetics_parameters_included in_transaction do |txn| - txn.raw_synthetics_header = "" + txn.raw_synthetics_header = '' txn.synthetics_payload = [1, 1, 100, 200, 300] end @@ -457,11 +457,11 @@ def run_sample_trace(state = @state) @sampler.notice_push_frame(state) @sampler.notice_sql("SELECT * FROM sandwiches WHERE bread = 'white'", {}, 0, state) yield if block_given? - @sampler.notice_pop_frame(state, "ab") + @sampler.notice_pop_frame(state, 'ab') @sampler.notice_push_frame(state) @sampler.notice_sql("SELECT * FROM sandwiches WHERE bread = 'french'", {}, 0, state) - @sampler.notice_pop_frame(state, "ac") - @sampler.notice_pop_frame(state, "a") + @sampler.notice_pop_frame(state, 'ac') + @sampler.notice_pop_frame(state, 'a') @sampler.on_finishing_transaction(state, @txn) end diff --git a/test/new_relic/agent/transaction_test.rb b/test/new_relic/agent/transaction_test.rb index f8f5b651da..eefce403ac 100644 --- a/test/new_relic/agent/transaction_test.rb +++ b/test/new_relic/agent/transaction_test.rb @@ -37,23 +37,23 @@ def test_request_with_path_with_query_string request = stub(:path => '/path?hello=bob#none') in_transaction(:request => request) do |txn| - assert_equal "/path", txn.request_path + assert_equal '/path', txn.request_path end end def test_request_parsing_referer - request = stub(:referer => 'https://www.yahoo.com:8080/path/hello?bob=none&foo=bar', :path => "/") + request = stub(:referer => 'https://www.yahoo.com:8080/path/hello?bob=none&foo=bar', :path => '/') in_transaction(:request => request) do |txn| - assert_equal "https://www.yahoo.com:8080/path/hello", txn.referer + assert_equal 'https://www.yahoo.com:8080/path/hello', txn.referer end end def test_strips_query_string_from_path_and_referer request = stub(:path => '/path?hello=bob#none', :referer => '/path/hello?bob=none&foo=bar') in_transaction(:request => request) do |txn| - assert_equal "/path", txn.request_path - assert_equal "/path/hello", txn.referer + assert_equal '/path', txn.request_path + assert_equal '/path/hello', txn.referer end end @@ -68,7 +68,7 @@ def test_transaction_referer_nil_if_request_referer_nil def test_request_with_normal_path request = stub(:path => '/blogs') in_transaction(:request => request) do |txn| - assert_equal "/blogs", txn.request_path + assert_equal '/blogs', txn.request_path assert_nil txn.referer end end @@ -76,7 +76,7 @@ def test_request_with_normal_path def test_request_with_empty_path request = stub(:path => '') in_transaction(:request => request) do |txn| - assert_equal "/", txn.request_path + assert_equal '/', txn.request_path assert_nil txn.referer end end @@ -84,7 +84,7 @@ def test_request_with_empty_path def test_request_to_root_path request = stub(:path => '/') in_transaction(:request => request) do |txn| - assert_equal "/", txn.request_path + assert_equal '/', txn.request_path assert_nil txn.referer end end @@ -92,7 +92,7 @@ def test_request_to_root_path def test_request_with_empty_path_with_query_string request = stub(:path => '?k=v') in_transaction(:request => request) do |txn| - assert_equal "/", txn.request_path + assert_equal '/', txn.request_path assert_nil txn.referer end end @@ -361,7 +361,7 @@ def test_set_default_transaction_name_without_category in_transaction('foo', :category => :controller) do |txn| Transaction.set_default_transaction_name('bar') - assert_equal("Controller/bar", txn.best_name) + assert_equal('Controller/bar', txn.best_name) end end @@ -369,7 +369,7 @@ def test_set_default_transaction_name_with_category in_transaction('foo', :category => :controller) do |txn| Transaction.set_default_transaction_name('bar', :rack) - assert_equal("Controller/Rack/bar", txn.best_name) + assert_equal('Controller/Rack/bar', txn.best_name) end end @@ -424,7 +424,7 @@ def test_end_fires_a_transaction_finished_event_with_overview_metrics end in_web_transaction('Controller/foo/1/bar/22') do - NewRelic::Agent.record_metric("HttpDispatcher", 2.1) + NewRelic::Agent.record_metric('HttpDispatcher', 2.1) end assert_in_delta(2.1, options['HttpDispatcher'].total_call_time) @@ -477,7 +477,7 @@ def test_end_fires_a_transaction_finished_event_with_guid_if_referring_transacti with_config(:apdex_t => 2.0) do in_transaction do |txn| - referring_txn_info = ["another"] + referring_txn_info = ['another'] cross_app_payload = CrossAppPayload.new('1#666', txn, referring_txn_info) txn.distributed_tracer.cross_app_payload = cross_app_payload end @@ -493,12 +493,12 @@ def test_end_fires_a_transaction_finished_event_with_referring_transaction_guid end in_transaction do |txn| - referring_txn_info = ["GUID"] + referring_txn_info = ['GUID'] payload = CrossAppPayload.new('1#666', txn, referring_txn_info) txn.distributed_tracer.cross_app_payload = payload end - assert_equal "GUID", referring_guid + assert_equal 'GUID', referring_guid end def test_end_fires_a_transaction_finished_event_without_referring_guid_if_not_present @@ -630,7 +630,7 @@ def test_cross_app_fields_not_in_finish_event_payload_if_no_cross_app_calls def test_is_not_synthetic_request_without_payload in_transaction do |txn| - txn.raw_synthetics_header = "" + txn.raw_synthetics_header = '' refute txn.is_synthetics_request? end @@ -646,7 +646,7 @@ def test_is_not_synthetic_request_without_header def test_is_synthetic_request in_transaction do |txn| - txn.raw_synthetics_header = "" + txn.raw_synthetics_header = '' txn.synthetics_payload = [1, 2, 3, 4, 5] assert_predicate txn, :is_synthetics_request? @@ -674,7 +674,7 @@ def test_synthetics_fields_in_finish_event_payload end in_transaction do |txn| - txn.raw_synthetics_header = "something" + txn.raw_synthetics_header = 'something' txn.synthetics_payload = [1, 1, 100, 200, 300] end @@ -700,7 +700,7 @@ def test_synthetics_fields_not_in_finish_event_payload_if_no_cross_app_calls end def test_logs_warning_if_a_non_hash_arg_is_passed_to_add_custom_attributes - expects_logging(:warn, includes("add_custom_attributes")) + expects_logging(:warn, includes('add_custom_attributes')) in_transaction do NewRelic::Agent.add_custom_attributes('fooz') end @@ -709,7 +709,7 @@ def test_logs_warning_if_a_non_hash_arg_is_passed_to_add_custom_attributes def test_ignores_custom_attributes_when_in_high_security with_config(:high_security => true) do in_transaction do |txn| - NewRelic::Agent.add_custom_attributes(:failure => "is an option") + NewRelic::Agent.add_custom_attributes(:failure => 'is an option') assert_empty attributes_for(txn, :custom) end @@ -718,7 +718,7 @@ def test_ignores_custom_attributes_when_in_high_security def test_notice_error_in_current_transaction_saves_it_for_finishing in_transaction('failing') do |txn| - Transaction.notice_error("") + Transaction.notice_error('') assert_equal 1, txn.exceptions.count end @@ -726,7 +726,7 @@ def test_notice_error_in_current_transaction_saves_it_for_finishing def test_notice_error_in_transaction_sends_attributes_along txn = in_transaction('oops') do - Transaction.notice_error("wat?") + Transaction.notice_error('wat?') end errors = harvest_error_traces! error = errors.first @@ -738,7 +738,7 @@ def test_notice_error_after_current_transaction_notifies_error_collector in_transaction('failing') do # no-op end - Transaction.notice_error("") + Transaction.notice_error('') errors = harvest_error_traces! assert_equal 1, errors.count @@ -746,16 +746,16 @@ def test_notice_error_after_current_transaction_notifies_error_collector def test_notice_error_without_transaction_notifies_error_collector cleanup_transaction - Transaction.notice_error("") + Transaction.notice_error('') errors = harvest_error_traces! assert_equal 1, errors.count end def test_notice_error_sends_uri_and_referer_from_request - request = stub(:path => "/here") + request = stub(:path => '/here') in_transaction(:request => request) do |txn| - Transaction.notice_error("wat") + Transaction.notice_error('wat') end errors = harvest_error_traces! @@ -764,14 +764,14 @@ def test_notice_error_sends_uri_and_referer_from_request error = errors.first - assert_equal "/here", error.request_uri + assert_equal '/here', error.request_uri end def test_notice_error_sets_expected_attribute Transaction.notice_error(RuntimeError.new, expected: true) errors = harvest_error_traces! - assert errors.first.expected, "Error should have had expected attribute set" + assert errors.first.expected, 'Error should have had expected attribute set' end def test_notice_error_sets_expected_attribute_in_transaction @@ -781,7 +781,7 @@ def test_notice_error_sets_expected_attribute_in_transaction errors = harvest_error_traces! - assert errors.first.expected, "Error should have had expected attribute set" + assert errors.first.expected, 'Error should have had expected attribute set' end def test_notice_error_does_not_set_span_id_attribute_on_error_event_outside_transaction @@ -789,7 +789,7 @@ def test_notice_error_does_not_set_span_id_attribute_on_error_event_outside_tran error_event = last_error_event - refute error_event[0].has_key?("spanId"), "Did not expect spanId intrinsic attribute" + refute error_event[0].has_key?('spanId'), 'Did not expect spanId intrinsic attribute' end def test_notice_error_sets_span_id_attribute_on_error_event_in_transaction @@ -801,7 +801,7 @@ def test_notice_error_sets_span_id_attribute_on_error_event_in_transaction error_event = last_error_event - assert_equal span_id, error_event[0]["spanId"] + assert_equal span_id, error_event[0]['spanId'] end def test_transport_duration_returned_in_seconds_when_positive @@ -939,7 +939,7 @@ def test_jruby_cpu_time_logs_errors_once_at_warn bean.stubs(:getCurrentThreadUserTime).raises(StandardError, 'Error calculating JRuby CPU Time') ::Java::JavaLangManagement::ManagementFactory.stubs(:getThreadMXBean).returns(bean) - expects_logging(:warn, includes("Error calculating JRuby CPU Time"), any_parameters) + expects_logging(:warn, includes('Error calculating JRuby CPU Time'), any_parameters) txn.send(:jruby_cpu_time) expects_no_logging(:warn) txn.send(:jruby_cpu_time) @@ -955,9 +955,9 @@ def test_jruby_cpu_time_always_logs_errors_at_debug bean.stubs(:getCurrentThreadUserTime).raises(StandardError, 'Error calculating JRuby CPU Time') ::Java::JavaLangManagement::ManagementFactory.stubs(:getThreadMXBean).returns(bean) - expects_logging(:warn, includes("Error calculating JRuby CPU Time"), any_parameters) + expects_logging(:warn, includes('Error calculating JRuby CPU Time'), any_parameters) txn.send(:jruby_cpu_time) - expects_logging(:debug, includes("Error calculating JRuby CPU Time"), any_parameters) + expects_logging(:debug, includes('Error calculating JRuby CPU Time'), any_parameters) txn.send(:jruby_cpu_time) end end @@ -1126,13 +1126,13 @@ def test_nested_other_transaction def test_failure_during_ignore_error_filter_doesnt_prevent_transaction filter = proc do |*_| - raise "HAHAHAHAH, error in the filter for ignoring errors!" + raise 'HAHAHAHAH, error in the filter for ignoring errors!' end with_ignore_error_filter(filter) do - expects_logging(:error, includes("HAHAHAHAH"), any_parameters) + expects_logging(:error, includes('HAHAHAHAH'), any_parameters) - in_transaction("Controller/boom") do + in_transaction('Controller/boom') do Transaction.notice_error(SillyError.new) end @@ -1160,10 +1160,10 @@ def ==(other) end def test_start_safe_from_exceptions - Transaction.any_instance.stubs(:start).raises("Haha") + Transaction.any_instance.stubs(:start).raises('Haha') expects_logging(:error, any_parameters) - in_transaction("Controller/boom") do + in_transaction('Controller/boom') do # nope end @@ -1183,10 +1183,10 @@ def test_start_ignores_transactions_from_ignored_paths end def test_finish_safe_from_exceptions - Transaction.any_instance.stubs(:commit!).raises("Haha") + Transaction.any_instance.stubs(:commit!).raises('Haha') expects_logging(:error, any_parameters) - in_transaction("Controller/boom") do + in_transaction('Controller/boom') do # nope end @@ -1216,7 +1216,7 @@ def test_user_defined_rules_ignore_returns_false_if_cannot_parse_uri end def test_finish_resets_the_transaction_state_if_there_is_an_error - txn = Tracer.start_transaction(name: "test", category: :controller) + txn = Tracer.start_transaction(name: 'test', category: :controller) state = Tracer.state state.expects(:reset) txn.stubs(:commit!).raises(StandardError, 'StandardError') @@ -1321,10 +1321,10 @@ def test_instrumentation_state def test_adding_custom_attributes with_config(:'transaction_tracer.attributes.enabled' => true) do in_transaction do |txn| - NewRelic::Agent.add_custom_attributes(:foo => "bar") + NewRelic::Agent.add_custom_attributes(:foo => 'bar') actual = txn.attributes.custom_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER) - assert_equal({"foo" => "bar"}, actual) + assert_equal({'foo' => 'bar'}, actual) end end end @@ -1332,10 +1332,10 @@ def test_adding_custom_attributes def test_adding_agent_attributes with_config(:'transaction_tracer.attributes.enabled' => true) do in_transaction do |txn| - txn.add_agent_attribute(:foo, "bar", AttributeFilter::DST_ALL) + txn.add_agent_attribute(:foo, 'bar', AttributeFilter::DST_ALL) actual = txn.attributes.agent_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER) - assert_equal({:foo => "bar"}, actual) + assert_equal({:foo => 'bar'}, actual) end end end @@ -1343,32 +1343,32 @@ def test_adding_agent_attributes def test_adding_agent_attributes_via_class with_config(:'transaction_tracer.attributes.enabled' => true) do in_transaction do |txn| - Transaction.add_agent_attribute(:foo, "bar", AttributeFilter::DST_ALL) + Transaction.add_agent_attribute(:foo, 'bar', AttributeFilter::DST_ALL) actual = txn.attributes.agent_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER) - assert_equal({:foo => "bar"}, actual) + assert_equal({:foo => 'bar'}, actual) end end end def test_adding_agent_attributes_via_class_outside_of_txn_is_safe - expects_logging(:debug, includes("foo")) - Transaction.add_agent_attribute(:foo, "bar", AttributeFilter::DST_ALL) + expects_logging(:debug, includes('foo')) + Transaction.add_agent_attribute(:foo, 'bar', AttributeFilter::DST_ALL) end def test_adding_intrinsic_attributes in_transaction do |txn| - txn.attributes.add_intrinsic_attribute(:foo, "bar") + txn.attributes.add_intrinsic_attribute(:foo, 'bar') actual = txn.attributes.intrinsic_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER) - assert_equal({:foo => "bar"}, actual) + assert_equal({:foo => 'bar'}, actual) end end def test_assigns_synthetics_to_intrinsic_attributes txn = in_transaction do |t| - t.raw_synthetics_header = "" + t.raw_synthetics_header = '' t.synthetics_payload = [1, 1, 100, 200, 300] t end @@ -1472,35 +1472,35 @@ def test_intrinsic_attributes_include_cpu_time def test_request_params_included_in_agent_attributes txn = with_config(:capture_params => true) do - in_transaction(:filtered_params => {:foo => "bar"}) do + in_transaction(:filtered_params => {:foo => 'bar'}) do end end actual = txn.attributes.agent_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER) - assert_equal "bar", actual['request.parameters.foo'] + assert_equal 'bar', actual['request.parameters.foo'] end def test_request_params_included_in_agent_attributes_in_nested_txn txn = with_config(:capture_params => true) do - in_transaction(:filtered_params => {:foo => "bar", :bar => "baz"}) do - in_transaction(:filtered_params => {:bar => "qux"}) do + in_transaction(:filtered_params => {:foo => 'bar', :bar => 'baz'}) do + in_transaction(:filtered_params => {:bar => 'qux'}) do end end end actual = txn.attributes.agent_attributes_for(AttributeFilter::DST_TRANSACTION_TRACER) - assert_equal "bar", actual['request.parameters.foo'] - assert_equal "qux", actual['request.parameters.bar'] + assert_equal 'bar', actual['request.parameters.foo'] + assert_equal 'qux', actual['request.parameters.bar'] end def test_request_params_get_key_length_limits - key = "x" * 1000 + key = 'x' * 1000 expects_logging(:debug, includes(key)) txn = with_config(:capture_params => true) do - in_transaction(:filtered_params => {key => "bar"}) do + in_transaction(:filtered_params => {key => 'bar'}) do end end @@ -1527,17 +1527,17 @@ def test_trace_id end def test_referer_in_agent_attributes - request = stub('request', :referer => "/referred", :path => "/") + request = stub('request', :referer => '/referred', :path => '/') txn = in_transaction(:request => request) do end actual = txn.attributes.agent_attributes_for(AttributeFilter::DST_ERROR_COLLECTOR) - assert_equal "/referred", actual[:'request.headers.referer'] + assert_equal '/referred', actual[:'request.headers.referer'] end def test_referer_omitted_if_not_on_request - request = stub('request', :path => "/") + request = stub('request', :path => '/') txn = in_transaction(:request => request) do end @@ -1550,44 +1550,44 @@ def test_error_recorded_predicate_false_by_default txn = in_transaction do end - refute txn.payload[:error], "Did not expected error to be recorded" + refute txn.payload[:error], 'Did not expected error to be recorded' end def test_error_recorded_predicate_true_when_error_recorded txn = in_transaction do |t| - t.notice_error(StandardError.new("Sorry!")) + t.notice_error(StandardError.new('Sorry!')) end - assert txn.payload[:error], "Expected error to be recorded" + assert txn.payload[:error], 'Expected error to be recorded' end def test_error_recorded_predicate_abides_by_ignore_filter filter = proc do |error| - error.message == "Sorry!" ? nil : error + error.message == 'Sorry!' ? nil : error end with_ignore_error_filter(filter) do txn = in_transaction do |t| - t.notice_error(StandardError.new("Sorry!")) + t.notice_error(StandardError.new('Sorry!')) end - refute txn.payload[:error], "Expected error to be apologetic" + refute txn.payload[:error], 'Expected error to be apologetic' end end def test_error_recorded_with_ignore_filter_and_multiple_errors filter = proc do |error| - error.message == "Sorry!" ? nil : error + error.message == 'Sorry!' ? nil : error end with_ignore_error_filter(filter) do txn = in_transaction do |t| - t.notice_error(StandardError.new("Sorry!")) - t.notice_error(StandardError.new("Not Sorry!")) - t.notice_error(StandardError.new("Sorry!")) + t.notice_error(StandardError.new('Sorry!')) + t.notice_error(StandardError.new('Not Sorry!')) + t.notice_error(StandardError.new('Sorry!')) end - assert txn.payload[:error], "Expected error to be recorded" + assert txn.payload[:error], 'Expected error to be recorded' end end @@ -1606,36 +1606,36 @@ def test_nesting_max_depth_increments end def test_set_transaction_name_for_nested_transactions - in_web_transaction("Controller/Framework/webby") do |t| - in_web_transaction("Controller/Framework/inner_1") do - in_web_transaction("Controller/Framework/inner_2") do - segment = Tracer.start_segment(name: "Ruby/my_lib/my_meth") - NewRelic::Agent.set_transaction_name("RackFramework/action") + in_web_transaction('Controller/Framework/webby') do |t| + in_web_transaction('Controller/Framework/inner_1') do + in_web_transaction('Controller/Framework/inner_2') do + segment = Tracer.start_segment(name: 'Ruby/my_lib/my_meth') + NewRelic::Agent.set_transaction_name('RackFramework/action') segment.finish end end end assert_metrics_recorded_exclusive [ - "Controller/RackFramework/action", - "HttpDispatcher", - "Apdex", - "ApdexAll", - "Apdex/RackFramework/action", - "Nested/Controller/Framework/webby", - "Nested/Controller/Framework/inner_1", - "Nested/Controller/Framework/inner_2", - "Ruby/my_lib/my_meth", - "Supportability/API/set_transaction_name", - "WebTransactionTotalTime", - "WebTransactionTotalTime/Controller/RackFramework/action", - ["Nested/Controller/Framework/webby", "Controller/RackFramework/action"], - ["Nested/Controller/Framework/inner_1", "Controller/RackFramework/action"], - ["Nested/Controller/Framework/inner_2", "Controller/RackFramework/action"], - ["Ruby/my_lib/my_meth", "Controller/RackFramework/action"], - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/all", - "Supportability/API/recording_web_transaction?", - "DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb" + 'Controller/RackFramework/action', + 'HttpDispatcher', + 'Apdex', + 'ApdexAll', + 'Apdex/RackFramework/action', + 'Nested/Controller/Framework/webby', + 'Nested/Controller/Framework/inner_1', + 'Nested/Controller/Framework/inner_2', + 'Ruby/my_lib/my_meth', + 'Supportability/API/set_transaction_name', + 'WebTransactionTotalTime', + 'WebTransactionTotalTime/Controller/RackFramework/action', + ['Nested/Controller/Framework/webby', 'Controller/RackFramework/action'], + ['Nested/Controller/Framework/inner_1', 'Controller/RackFramework/action'], + ['Nested/Controller/Framework/inner_2', 'Controller/RackFramework/action'], + ['Ruby/my_lib/my_meth', 'Controller/RackFramework/action'], + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/all', + 'Supportability/API/recording_web_transaction?', + 'DurationByCaller/Unknown/Unknown/Unknown/Unknown/allWeb' ] end @@ -1687,7 +1687,7 @@ def test_batches_logs_during_transaction ) do NewRelic::Agent.config.notify_server_source_added in_transaction do - NewRelic::Agent.agent.log_event_aggregator.record("A message", "FATAL") + NewRelic::Agent.agent.log_event_aggregator.record('A message', 'FATAL') assert_equal 1, Transaction.tl_current.logs.size end @@ -1704,7 +1704,7 @@ def test_ignores_logs_when_transaction_ignored txn.ignore! NewRelic::Agent.agent.log_event_aggregator.reset! - NewRelic::Agent.agent.log_event_aggregator.record("A message", "FATAL") + NewRelic::Agent.agent.log_event_aggregator.record('A message', 'FATAL') assert_equal 1, Transaction.tl_current.logs.size end @@ -1725,7 +1725,7 @@ def test_limits_batched_logs_during_transaction NewRelic::Agent.config.notify_server_source_added in_transaction do 100.times do - NewRelic::Agent.agent.log_event_aggregator.record("A message", "FATAL") + NewRelic::Agent.agent.log_event_aggregator.record('A message', 'FATAL') end assert_equal limit, Transaction.tl_current.logs.size diff --git a/test/new_relic/agent/transaction_time_aggregator_test.rb b/test/new_relic/agent/transaction_time_aggregator_test.rb index a08de4fe0a..848d568181 100644 --- a/test/new_relic/agent/transaction_time_aggregator_test.rb +++ b/test/new_relic/agent/transaction_time_aggregator_test.rb @@ -101,7 +101,7 @@ def test_metrics NewRelic::Agent::TransactionTimeAggregator.harvest! - spec = NewRelic::MetricSpec.new("Instance/Busy") + spec = NewRelic::MetricSpec.new('Instance/Busy') stats = NewRelic::Agent.instance.stats_engine.to_h[spec] refute_nil stats diff --git a/test/new_relic/agent/utilization/aws_test.rb b/test/new_relic/agent/utilization/aws_test.rb index 902453c593..0f37deaa43 100644 --- a/test/new_relic/agent/utilization/aws_test.rb +++ b/test/new_relic/agent/utilization/aws_test.rb @@ -20,15 +20,15 @@ def teardown # --- def test_generates_expected_collector_hash_for_valid_response - fixture = File.read(File.join(aws_fixture_path, "valid.json")) + fixture = File.read(File.join(aws_fixture_path, 'valid.json')) mock_response = mock(code: '200', body: fixture) @vendor.stubs(:request_metadata).returns(mock_response) expected = { - :instanceId => "i-08987cdeff7489fa7", - :instanceType => "c4.2xlarge", - :availabilityZone => "us-west-2c" + :instanceId => 'i-08987cdeff7489fa7', + :instanceType => 'c4.2xlarge', + :availabilityZone => 'us-west-2c' } assert @vendor.detect @@ -36,33 +36,33 @@ def test_generates_expected_collector_hash_for_valid_response end def test_fails_when_response_contains_invalid_chars - fixture = File.read(File.join(aws_fixture_path, "invalid_chars.json")) + fixture = File.read(File.join(aws_fixture_path, 'invalid_chars.json')) mock_response = mock(code: '200', body: fixture) @vendor.stubs(:request_metadata).returns(mock_response) refute @vendor.detect - assert_metrics_recorded "Supportability/utilization/aws/error" => {:call_count => 1} + assert_metrics_recorded 'Supportability/utilization/aws/error' => {:call_count => 1} end def test_fails_when_response_is_missing_required_value - fixture = File.read(File.join(aws_fixture_path, "missing_value.json")) + fixture = File.read(File.join(aws_fixture_path, 'missing_value.json')) mock_response = mock(code: '200', body: fixture) @vendor.stubs(:request_metadata).returns(mock_response) refute @vendor.detect - assert_metrics_recorded "Supportability/utilization/aws/error" => {:call_count => 1} + assert_metrics_recorded 'Supportability/utilization/aws/error' => {:call_count => 1} end def test_fails_based_on_response_code - fixture = File.read(File.join(aws_fixture_path, "valid.json")) + fixture = File.read(File.join(aws_fixture_path, 'valid.json')) mock_response = stub(code: '404', body: fixture) @vendor.stubs(:request_metadata).returns(mock_response) refute @vendor.detect - refute_metrics_recorded "Supportability/utilization/aws/error" + refute_metrics_recorded 'Supportability/utilization/aws/error' end def test_that_the_headers_lambda_is_processed_properly @@ -70,7 +70,7 @@ def test_that_the_headers_lambda_is_processed_properly mock_response = mock(code: '200', body: phony_imds_token) Net::HTTP.any_instance.stubs(:send_request).returns(mock_response) - assert_equal @vendor.headers, "X-aws-ec2-metadata-token" => phony_imds_token + assert_equal @vendor.headers, 'X-aws-ec2-metadata-token' => phony_imds_token end # --- @@ -81,10 +81,10 @@ def aws_fixture_path # --- - load_cross_agent_test("utilization_vendor_specific/aws").each do |test_case| + load_cross_agent_test('utilization_vendor_specific/aws').each do |test_case| test_case = symbolize_keys_in_object(test_case) - define_method("test_#{test_case[:testname]}".tr(" ", "_")) do + define_method("test_#{test_case[:testname]}".tr(' ', '_')) do NewRelic::Agent::Utilization::AWS.stubs(:imds_token).returns('John Howe') uri_obj_key = test_case[:uri].keys.detect do |key| key =~ %r{http://169.254.169.254/(?:2016-09-02|latest)/dynamic/instance-identity/document} @@ -106,20 +106,18 @@ def aws_fixture_path assert_equal expected, {aws: @vendor.metadata} - if test_case[:expected_metrics] - test_case[:expected_metrics].each do |metric, v| - if v[:call_count] == 0 - if uri_obj[:timeout] - refute detection, '@vendor.detect should have returned false' - else - assert detection, '@vendor.detect should have returned truthy' - end - - assert_metrics_not_recorded [metric.to_s] - else + test_case[:expected_metrics]&.each do |metric, v| + if v[:call_count] == 0 + if uri_obj[:timeout] refute detection, '@vendor.detect should have returned false' - assert_metrics_recorded [metric.to_s] + else + assert detection, '@vendor.detect should have returned truthy' end + + assert_metrics_not_recorded [metric.to_s] + else + refute detection, '@vendor.detect should have returned false' + assert_metrics_recorded [metric.to_s] end end end diff --git a/test/new_relic/agent/utilization/azure_test.rb b/test/new_relic/agent/utilization/azure_test.rb index d3816b1a3d..b34a313596 100644 --- a/test/new_relic/agent/utilization/azure_test.rb +++ b/test/new_relic/agent/utilization/azure_test.rb @@ -20,16 +20,16 @@ def teardown # --- def test_generates_expected_collector_hash_for_valid_response - fixture = File.read(File.join(azure_fixture_path, "valid.json")) + fixture = File.read(File.join(azure_fixture_path, 'valid.json')) stubbed_response = stub(code: '200', body: fixture) @vendor.stubs(:request_metadata).returns(stubbed_response) expected = { - :vmId => "c84ffaa7-1b0a-4aa6-9f5c-0912655d9870", - :name => "rubytest", - :vmSize => "Standard_DS1_v2", - :location => "eastus" + :vmId => 'c84ffaa7-1b0a-4aa6-9f5c-0912655d9870', + :name => 'rubytest', + :vmSize => 'Standard_DS1_v2', + :location => 'eastus' } assert @vendor.detect @@ -37,33 +37,33 @@ def test_generates_expected_collector_hash_for_valid_response end def test_fails_when_response_contains_invalid_chars - fixture = File.read(File.join(azure_fixture_path, "invalid_chars.json")) + fixture = File.read(File.join(azure_fixture_path, 'invalid_chars.json')) stubbed_response = stub(code: '200', body: fixture) @vendor.stubs(:request_metadata).returns(stubbed_response) refute @vendor.detect - assert_metrics_recorded "Supportability/utilization/azure/error" => {:call_count => 1} + assert_metrics_recorded 'Supportability/utilization/azure/error' => {:call_count => 1} end def test_fails_when_response_is_missing_required_value - fixture = File.read(File.join(azure_fixture_path, "missing_value.json")) + fixture = File.read(File.join(azure_fixture_path, 'missing_value.json')) stubbed_response = stub(code: '200', body: fixture) @vendor.stubs(:request_metadata).returns(stubbed_response) refute @vendor.detect - assert_metrics_recorded "Supportability/utilization/azure/error" => {:call_count => 1} + assert_metrics_recorded 'Supportability/utilization/azure/error' => {:call_count => 1} end def test_fails_based_on_response_code - fixture = File.read(File.join(azure_fixture_path, "valid.json")) + fixture = File.read(File.join(azure_fixture_path, 'valid.json')) stubbed_response = stub(code: '404', body: fixture) @vendor.stubs(:request_metadata).returns(stubbed_response) refute @vendor.detect - refute_metrics_recorded "Supportability/utilization/azure/error" + refute_metrics_recorded 'Supportability/utilization/azure/error' end # --- @@ -74,10 +74,10 @@ def azure_fixture_path # --- - load_cross_agent_test("utilization_vendor_specific/azure").each do |test_case| + load_cross_agent_test('utilization_vendor_specific/azure').each do |test_case| test_case = symbolize_keys_in_object(test_case) - define_method("test_#{test_case[:testname]}".tr(" ", "_")) do + define_method("test_#{test_case[:testname]}".tr(' ', '_')) do uri_obj = test_case[:uri][:'http://169.254.169.254/metadata/instance/compute?api-version=2017-03-01'] if uri_obj[:timeout] @vendor.stubs(:request_metadata).returns(nil) @@ -95,20 +95,18 @@ def azure_fixture_path assert_equal expected, {azure: @vendor.metadata} - if test_case[:expected_metrics] - test_case[:expected_metrics].each do |metric, v| - if v[:call_count] == 0 - if uri_obj[:timeout] - refute detection, '@vendor.detect should have returned false' - else - assert detection, '@vendor.detect should have returned truthy' - end - - assert_metrics_not_recorded [metric.to_s] - else + test_case[:expected_metrics]&.each do |metric, v| + if v[:call_count] == 0 + if uri_obj[:timeout] refute detection, '@vendor.detect should have returned false' - assert_metrics_recorded [metric.to_s] + else + assert detection, '@vendor.detect should have returned truthy' end + + assert_metrics_not_recorded [metric.to_s] + else + refute detection, '@vendor.detect should have returned false' + assert_metrics_recorded [metric.to_s] end end end diff --git a/test/new_relic/agent/utilization/gcp_test.rb b/test/new_relic/agent/utilization/gcp_test.rb index 289c4cb3aa..33928158d3 100644 --- a/test/new_relic/agent/utilization/gcp_test.rb +++ b/test/new_relic/agent/utilization/gcp_test.rb @@ -20,16 +20,16 @@ def teardown # --- def test_generates_expected_collector_hash_for_valid_response - fixture = File.read(File.join(gcp_fixture_path, "valid.json")) + fixture = File.read(File.join(gcp_fixture_path, 'valid.json')) stubbed_response = stub(code: '200', body: fixture) @vendor.stubs(:request_metadata).returns(stubbed_response) expected = { - :id => "4332984205593314925", - :machineType => "custom-1-1024", - :name => "aef-default-20170714t143150-1q67", - :zone => "us-central1-b" + :id => '4332984205593314925', + :machineType => 'custom-1-1024', + :name => 'aef-default-20170714t143150-1q67', + :zone => 'us-central1-b' } assert @vendor.detect @@ -37,33 +37,33 @@ def test_generates_expected_collector_hash_for_valid_response end def test_fails_when_response_contains_invalid_chars - fixture = File.read(File.join(gcp_fixture_path, "invalid_chars.json")) + fixture = File.read(File.join(gcp_fixture_path, 'invalid_chars.json')) stubbed_response = stub(code: '200', body: fixture) @vendor.stubs(:request_metadata).returns(stubbed_response) refute @vendor.detect - assert_metrics_recorded "Supportability/utilization/gcp/error" => {:call_count => 1} + assert_metrics_recorded 'Supportability/utilization/gcp/error' => {:call_count => 1} end def test_fails_when_response_is_missing_required_value - fixture = File.read(File.join(gcp_fixture_path, "missing_value.json")) + fixture = File.read(File.join(gcp_fixture_path, 'missing_value.json')) stubbed_response = stub(code: '200', body: fixture) @vendor.stubs(:request_metadata).returns(stubbed_response) refute @vendor.detect - assert_metrics_recorded "Supportability/utilization/gcp/error" => {:call_count => 1} + assert_metrics_recorded 'Supportability/utilization/gcp/error' => {:call_count => 1} end def test_fails_based_on_response_code - fixture = File.read(File.join(gcp_fixture_path, "valid.json")) + fixture = File.read(File.join(gcp_fixture_path, 'valid.json')) stubbed_response = stub(code: '404', body: fixture) @vendor.stubs(:request_metadata).returns(stubbed_response) refute @vendor.detect - refute_metrics_recorded "Supportability/utilization/gcp/error" + refute_metrics_recorded 'Supportability/utilization/gcp/error' end # --- @@ -74,10 +74,10 @@ def gcp_fixture_path # --- - load_cross_agent_test("utilization_vendor_specific/gcp").each do |test_case| + load_cross_agent_test('utilization_vendor_specific/gcp').each do |test_case| test_case = symbolize_keys_in_object(test_case) - define_method("test_#{test_case[:testname]}".tr(" ", "_")) do + define_method("test_#{test_case[:testname]}".tr(' ', '_')) do uri_obj = test_case[:uri][:'http://metadata.google.internal/computeMetadata/v1/instance/?recursive=true'] if uri_obj[:timeout] @vendor.stubs(:request_metadata).returns(nil) @@ -95,20 +95,18 @@ def gcp_fixture_path assert_equal expected, {gcp: @vendor.metadata} - if test_case[:expected_metrics] - test_case[:expected_metrics].each do |metric, v| - if v[:call_count] == 0 - if uri_obj[:timeout] - refute detection, '@vendor.detect should have returned false' - else - assert detection, '@vendor.detect should have returned truthy' - end - - assert_metrics_not_recorded [metric.to_s] - else + test_case[:expected_metrics]&.each do |metric, v| + if v[:call_count] == 0 + if uri_obj[:timeout] refute detection, '@vendor.detect should have returned false' - assert_metrics_recorded [metric.to_s] + else + assert detection, '@vendor.detect should have returned truthy' end + + assert_metrics_not_recorded [metric.to_s] + else + refute detection, '@vendor.detect should have returned false' + assert_metrics_recorded [metric.to_s] end end end diff --git a/test/new_relic/agent/utilization/pcf_test.rb b/test/new_relic/agent/utilization/pcf_test.rb index f11c6e8d5a..31ffe1e3b0 100644 --- a/test/new_relic/agent/utilization/pcf_test.rb +++ b/test/new_relic/agent/utilization/pcf_test.rb @@ -20,13 +20,13 @@ def teardown # --- def test_generate_expected_vendors_hash_when_expected_env_vars_present - with_pcf_env("CF_INSTANCE_GUID" => "fd326c0e-847e-47a1-65cc-45f6", - "CF_INSTANCE_IP" => "10.10.149.48", - "MEMORY_LIMIT" => "1024m") do + with_pcf_env('CF_INSTANCE_GUID' => 'fd326c0e-847e-47a1-65cc-45f6', + 'CF_INSTANCE_IP' => '10.10.149.48', + 'MEMORY_LIMIT' => '1024m') do expected = { - :cf_instance_guid => "fd326c0e-847e-47a1-65cc-45f6", - :cf_instance_ip => "10.10.149.48", - :memory_limit => "1024m" + :cf_instance_guid => 'fd326c0e-847e-47a1-65cc-45f6', + :cf_instance_ip => '10.10.149.48', + :memory_limit => '1024m' } assert @vendor.detect @@ -35,16 +35,16 @@ def test_generate_expected_vendors_hash_when_expected_env_vars_present end def test_fails_when_expected_value_has_invalid_chars - with_pcf_env("CF_INSTANCE_GUID" => "**fd326c0e-847e-47a1-65cc-45f6**", - "CF_INSTANCE_IP" => "10.10.149.48", - "MEMORY_LIMIT" => "1024m") do + with_pcf_env('CF_INSTANCE_GUID' => '**fd326c0e-847e-47a1-65cc-45f6**', + 'CF_INSTANCE_IP' => '10.10.149.48', + 'MEMORY_LIMIT' => '1024m') do refute @vendor.detect end end def test_fails_when_required_value_is_missing - with_pcf_env("CF_INSTANCE_GUID" => "fd326c0e-847e-47a1-65cc-45f6", - "CF_INSTANCE_IP" => "10.10.149.48") do + with_pcf_env('CF_INSTANCE_GUID' => 'fd326c0e-847e-47a1-65cc-45f6', + 'CF_INSTANCE_IP' => '10.10.149.48') do refute @vendor.detect end end @@ -59,10 +59,10 @@ def with_pcf_env(vars, &blk) # --- - load_cross_agent_test("utilization_vendor_specific/pcf").each do |test_case| + load_cross_agent_test('utilization_vendor_specific/pcf').each do |test_case| test_case = symbolize_keys_in_object(test_case) - define_method("test_#{test_case[:testname]}".tr(" ", "_")) do + define_method("test_#{test_case[:testname]}".tr(' ', '_')) do timeout = false pcf_env = test_case[:env_vars].reduce({}) do |h, (k, v)| h[k.to_s] = v[:response] if v[:response] @@ -80,20 +80,18 @@ def with_pcf_env(vars, &blk) assert_equal expected, {pcf: @vendor.metadata} - if test_case[:expected_metrics] - test_case[:expected_metrics].each do |metric, v| - if v[:call_count] == 0 - if timeout - refute detection, '@vendor.detect should have returned false' - else - assert detection, '@vendor.detect should have returned truthy' - end - - assert_metrics_not_recorded [metric.to_s] - else + test_case[:expected_metrics]&.each do |metric, v| + if v[:call_count] == 0 + if timeout refute detection, '@vendor.detect should have returned false' - assert_metrics_recorded [metric.to_s] + else + assert detection, '@vendor.detect should have returned truthy' end + + assert_metrics_not_recorded [metric.to_s] + else + refute detection, '@vendor.detect should have returned false' + assert_metrics_recorded [metric.to_s] end end end diff --git a/test/new_relic/agent/utilization/vendor_test.rb b/test/new_relic/agent/utilization/vendor_test.rb index 5943ea1734..2666006915 100644 --- a/test/new_relic/agent/utilization/vendor_test.rb +++ b/test/new_relic/agent/utilization/vendor_test.rb @@ -10,15 +10,15 @@ module Agent module Utilization class VendorTest < Minitest::Test class ExampleVendor < Vendor - vendor_name "example" - endpoint "http://169.254.169.254/metadata" - headers "meta" => "yes" + vendor_name 'example' + endpoint 'http://169.254.169.254/metadata' + headers 'meta' => 'yes' keys %w[vm_type vm_id vm_zone] key_transforms :to_sym end class LambdaVendor < Vendor - headers "river" => -> { "phoenix".upcase } + headers 'river' => -> { 'phoenix'.upcase } end def setup @@ -30,21 +30,21 @@ def teardown end def test_has_name - assert_equal "example", @vendor.vendor_name + assert_equal 'example', @vendor.vendor_name end def test_has_endpoint - assert_equal URI("http://169.254.169.254/metadata"), @vendor.endpoint + assert_equal URI('http://169.254.169.254/metadata'), @vendor.endpoint end def test_has_headers - expected = {"meta" => "yes"} + expected = {'meta' => 'yes'} assert_equal expected, @vendor.headers end def test_headers_with_lambda_values - assert_equal "PHOENIX", LambdaVendor.new.headers["river"] + assert_equal 'PHOENIX', LambdaVendor.new.headers['river'] end def test_assigns_expected_keys @@ -54,9 +54,9 @@ def test_assigns_expected_keys assert @vendor.detect expected = { - :vm_type => "large", - :vm_id => "x123", - :vm_zone => "danger_zone" + :vm_type => 'large', + :vm_id => 'x123', + :vm_zone => 'danger_zone' } assert_equal expected, @vendor.metadata @@ -67,7 +67,7 @@ def test_detect_fails_when_expected_field_is_null @vendor.stubs(:request_metadata).returns(stubbed_response) refute @vendor.detect - assert_metrics_recorded "Supportability/utilization/example/error" => {:call_count => 1} + assert_metrics_recorded 'Supportability/utilization/example/error' => {:call_count => 1} end def test_detect_fails_when_expected_field_has_invalid_chars @@ -75,7 +75,7 @@ def test_detect_fails_when_expected_field_has_invalid_chars @vendor.stubs(:request_metadata).returns(stubbed_response) refute @vendor.detect - assert_metrics_recorded "Supportability/utilization/example/error" => {:call_count => 1} + assert_metrics_recorded 'Supportability/utilization/example/error' => {:call_count => 1} end end end diff --git a/test/new_relic/agent/utilization_data_test.rb b/test/new_relic/agent/utilization_data_test.rb index 5415dd7236..eb04e15c18 100644 --- a/test/new_relic/agent/utilization_data_test.rb +++ b/test/new_relic/agent/utilization_data_test.rb @@ -25,9 +25,9 @@ def test_aws_information_is_included_when_available utilization_data = UtilizationData.new expected = { - :instanceId => "i-08987cdeff7489fa7", - :instanceType => "c4.2xlarge", - :availabilityZone => "us-west-2c" + :instanceId => 'i-08987cdeff7489fa7', + :instanceType => 'c4.2xlarge', + :availabilityZone => 'us-west-2c' } assert_equal expected, utilization_data.to_collector_hash[:vendors][:aws] @@ -48,10 +48,10 @@ def test_azure_information_is_included_when_available utilization_data = UtilizationData.new expected = { - :vmId => "c84ffaa7-1b0a-4aa6-9f5c-0912655d9870", - :name => "rubytest", - :vmSize => "Standard_DS1_v2", - :location => "eastus" + :vmId => 'c84ffaa7-1b0a-4aa6-9f5c-0912655d9870', + :name => 'rubytest', + :vmSize => 'Standard_DS1_v2', + :location => 'eastus' } assert_equal expected, utilization_data.to_collector_hash[:vendors][:azure] @@ -72,10 +72,10 @@ def test_gcp_information_is_included_when_available utilization_data = UtilizationData.new expected = { - :id => "4332984205593314925", - :machineType => "custom-1-1024", - :name => "aef-default-20170714t143150-1q67", - :zone => "us-central1-b" + :id => '4332984205593314925', + :machineType => 'custom-1-1024', + :name => 'aef-default-20170714t143150-1q67', + :zone => 'us-central1-b' } assert_equal expected, utilization_data.to_collector_hash[:vendors][:gcp] @@ -94,13 +94,13 @@ def test_gcp_information_is_omitted_when_available_but_disabled_by_config def test_pcf_information_is_included_when_available utilization_data = UtilizationData.new - with_pcf_env("CF_INSTANCE_GUID" => "ab326c0e-123e-47a1-65cc-45f6", - "CF_INSTANCE_IP" => "101.1.149.48", - "MEMORY_LIMIT" => "2048m") do + with_pcf_env('CF_INSTANCE_GUID' => 'ab326c0e-123e-47a1-65cc-45f6', + 'CF_INSTANCE_IP' => '101.1.149.48', + 'MEMORY_LIMIT' => '2048m') do expected = { - :cf_instance_guid => "ab326c0e-123e-47a1-65cc-45f6", - :cf_instance_ip => "101.1.149.48", - :memory_limit => "2048m" + :cf_instance_guid => 'ab326c0e-123e-47a1-65cc-45f6', + :cf_instance_ip => '101.1.149.48', + :memory_limit => '2048m' } assert_equal expected, utilization_data.to_collector_hash[:vendors][:pcf] @@ -111,22 +111,22 @@ def test_pcf_information_is_omitted_when_available_but_disabled_by_config with_config(:'utilization.detect_pcf' => false, :'utilization.detect_docker' => false) do utilization_data = UtilizationData.new - with_pcf_env("CF_INSTANCE_GUID" => "ab326c0e-123e-47a1-65cc-45f6", - "CF_INSTANCE_IP" => "101.1.149.48", - "MEMORY_LIMIT" => "2048m") do + with_pcf_env('CF_INSTANCE_GUID' => 'ab326c0e-123e-47a1-65cc-45f6', + 'CF_INSTANCE_IP' => '101.1.149.48', + 'MEMORY_LIMIT' => '2048m') do assert_nil utilization_data.to_collector_hash[:vendors] end end end def test_docker_information_is_included_when_available - NewRelic::Agent::SystemInfo.stubs(:docker_container_id).returns("47cbd16b77c50cbf71401") + NewRelic::Agent::SystemInfo.stubs(:docker_container_id).returns('47cbd16b77c50cbf71401') utilization_data = UtilizationData.new expected = { :docker => { - :id => "47cbd16b77c50cbf71401" + :id => '47cbd16b77c50cbf71401' } } @@ -134,7 +134,7 @@ def test_docker_information_is_included_when_available end def test_docker_information_is_omitted_when_available_but_disabled_by_config - NewRelic::Agent::SystemInfo.stubs(:docker_container_id).returns("47cbd16b77c50cbf71401") + NewRelic::Agent::SystemInfo.stubs(:docker_container_id).returns('47cbd16b77c50cbf71401') with_config(:'utilization.detect_docker' => false) do utilization_data = UtilizationData.new @@ -145,10 +145,10 @@ def test_docker_information_is_omitted_when_available_but_disabled_by_config def test_logged_when_docker_container_id_is_unrecognized NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns('linux') NewRelic::Agent::SystemInfo.stubs(:ram_in_mib).returns(128) - NewRelic::Agent::SystemInfo.stubs(:proc_try_read).returns(String.new('whatever')) - NewRelic::Agent::SystemInfo.stubs(:parse_cgroup_ids).returns('cpu' => "*****YOLO*******") + NewRelic::Agent::SystemInfo.stubs(:proc_try_read).returns((+'whatever')) + NewRelic::Agent::SystemInfo.stubs(:parse_cgroup_ids).returns('cpu' => '*****YOLO*******') - expects_logging(:debug, includes("YOLO")) + expects_logging(:debug, includes('YOLO')) utilization_data = UtilizationData.new assert_nil utilization_data.to_collector_hash[:vendors] @@ -157,17 +157,17 @@ def test_logged_when_docker_container_id_is_unrecognized def test_aws_and_docker_information_is_included_when_both_available stub_aws_info - NewRelic::Agent::SystemInfo.stubs(:docker_container_id).returns("47cbd16b77c50cbf71401") + NewRelic::Agent::SystemInfo.stubs(:docker_container_id).returns('47cbd16b77c50cbf71401') utilization_data = UtilizationData.new expected = { :aws => { - :instanceId => "i-08987cdeff7489fa7", - :instanceType => "c4.2xlarge", - :availabilityZone => "us-west-2c" + :instanceId => 'i-08987cdeff7489fa7', + :instanceType => 'c4.2xlarge', + :availabilityZone => 'us-west-2c' }, :docker => { - :id => "47cbd16b77c50cbf71401" + :id => '47cbd16b77c50cbf71401' } } @@ -183,11 +183,11 @@ def test_vendor_information_is_omitted_if_unavailable end def test_hostname_is_present_in_collector_hash - NewRelic::Agent::Hostname.stubs(:get).returns("host") + NewRelic::Agent::Hostname.stubs(:get).returns('host') utilization_data = UtilizationData.new - assert_equal "host", utilization_data.to_collector_hash[:hostname] + assert_equal 'host', utilization_data.to_collector_hash[:hostname] end def test_ip_is_present_in_collector_hash @@ -199,15 +199,15 @@ def test_ip_is_present_in_collector_hash end def test_full_hostname_is_present_in_collector_hash - NewRelic::Agent::Hostname.stubs(:get_fqdn).returns("foobar.baz.com") + NewRelic::Agent::Hostname.stubs(:get_fqdn).returns('foobar.baz.com') utilization_data = UtilizationData.new - assert_equal "foobar.baz.com", utilization_data.to_collector_hash[:full_hostname] + assert_equal 'foobar.baz.com', utilization_data.to_collector_hash[:full_hostname] end def test_full_hostname_omitted_if_empty_or_nil - [nil, ""].each do |return_value| + [nil, ''].each do |return_value| NewRelic::Agent::Hostname.stubs(:get_fqdn).returns(return_value) utilization_data = UtilizationData.new @@ -233,12 +233,12 @@ def test_memory_is_present_in_collector_hash end def test_memory_is_nil_when_proc_meminfo_is_unreadable - NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns("linux") + NewRelic::Agent::SystemInfo.stubs(:ruby_os_identifier).returns('linux') NewRelic::Agent::SystemInfo.stubs(:proc_try_read).returns(nil) utilization_data = UtilizationData.new - assert_nil utilization_data.to_collector_hash[:total_ram_mib], "Expected total_ram_mib to be nil" + assert_nil utilization_data.to_collector_hash[:total_ram_mib], 'Expected total_ram_mib to be nil' end def test_metadata_version_is_present_in_collector_hash @@ -272,11 +272,11 @@ def test_configured_total_ram_mib_added_to_config_hash end def test_boot_id_is_present_in_collector_hash - NewRelic::Agent::SystemInfo.stubs(:boot_id).returns("boot-id") + NewRelic::Agent::SystemInfo.stubs(:boot_id).returns('boot-id') utilization_data = UtilizationData.new - assert_equal "boot-id", utilization_data.to_collector_hash[:boot_id] + assert_equal 'boot-id', utilization_data.to_collector_hash[:boot_id] end def test_kubernetes_information_is_present_if_available @@ -311,7 +311,7 @@ def stub_aws_info(response_code: '200', response_body: default_aws_response) def default_aws_response aws_fixture_path = File.expand_path('../../../fixtures/utilization/aws', __FILE__) - File.read(File.join(aws_fixture_path, "valid.json")) + File.read(File.join(aws_fixture_path, 'valid.json')) end def stub_azure_info(response_code: '200', response_body: default_azure_response) @@ -331,7 +331,7 @@ def stub_gcp_info(response_code: '200', response_body: default_gcp_response) def default_gcp_response aws_fixture_path = File.expand_path('../../../fixtures/utilization/gcp', __FILE__) - File.read(File.join(aws_fixture_path, "valid.json")) + File.read(File.join(aws_fixture_path, 'valid.json')) end def with_pcf_env(vars, &blk) @@ -342,10 +342,10 @@ def with_pcf_env(vars, &blk) # --- - load_cross_agent_test("utilization/utilization_json").each do |test_case| + load_cross_agent_test('utilization/utilization_json').each do |test_case| test_case = symbolize_keys_in_object(test_case) - define_method("test_#{test_case[:testname]}".tr(" ", "_")) do + define_method("test_#{test_case[:testname]}".tr(' ', '_')) do setup_cross_agent_test_stubs test_case env = non_config_environment_variables(test_case) diff --git a/test/new_relic/agent/worker_loop_test.rb b/test/new_relic/agent/worker_loop_test.rb index f4e0689bbe..e924881c60 100644 --- a/test/new_relic/agent/worker_loop_test.rb +++ b/test/new_relic/agent/worker_loop_test.rb @@ -61,7 +61,7 @@ def test_task_error__standard @worker_loop.run(0) do @worker_loop.stop done = true - raise "Standard Error Test" + raise 'Standard Error Test' end assert done @@ -71,7 +71,7 @@ def test_task_error__exception expects_logging(:error, any_parameters) @worker_loop.run(0) do @worker_loop.stop - raise NewRelic::TestHelper::Exception::TestError, "oops" + raise NewRelic::TestHelper::Exception::TestError, 'oops' end end diff --git a/test/new_relic/agent_test.rb b/test/new_relic/agent_test.rb index 8069c27702..7760c7f4a5 100644 --- a/test/new_relic/agent_test.rb +++ b/test/new_relic/agent_test.rb @@ -34,7 +34,7 @@ def test_shutdown end def test_shutdown_removes_manual_startup_config - NewRelic::Agent.manual_start(:monitor_mode => true, :license_key => "a" * 40, :some_absurd_setting => true) + NewRelic::Agent.manual_start(:monitor_mode => true, :license_key => 'a' * 40, :some_absurd_setting => true) assert NewRelic::Agent.config[:some_absurd_setting] NewRelic::Agent.shutdown @@ -43,7 +43,7 @@ def test_shutdown_removes_manual_startup_config end def test_shutdown_removes_server_config - NewRelic::Agent.manual_start(:monitor_mode => true, :license_key => "a" * 40) + NewRelic::Agent.manual_start(:monitor_mode => true, :license_key => 'a' * 40) response_handler = ::NewRelic::Agent::Connect::ResponseHandler.new( NewRelic::Agent.instance, NewRelic::Agent.config ) @@ -73,6 +73,9 @@ def test_configure_agent_applied_server_side_config refute NewRelic::Agent.config[:'transaction_tracer.enabled'] refute NewRelic::Agent.config[:'error_collector.enabled'] end + + # resets the SSC to empty + NewRelic::Agent.config.replace_or_add_config(NewRelic::Agent::Configuration::ServerSource.new({})) end def test_after_fork @@ -105,7 +108,7 @@ def test_manual_start_starts_channel_listener end def test_manual_start_kicks_dependency_check_again - with_config(:monitor_mode => true, :license_key => "a" * 40, :sync_startup => true) do + with_config(:monitor_mode => true, :license_key => 'a' * 40, :sync_startup => true) do NewRelic::Agent.manual_start assert_predicate NewRelic::Agent.instance, :started? @@ -135,7 +138,7 @@ def test_agent_when_started old_agent = NewRelic::Agent.agent NewRelic::Agent.instance_eval { @agent = 'not nil' } - assert_equal('not nil', NewRelic::Agent.agent, "should return the value from @agent") + assert_equal('not nil', NewRelic::Agent.agent, 'should return the value from @agent') NewRelic::Agent.instance_eval { @agent = old_agent } end @@ -187,7 +190,7 @@ def test_instance NewRelic::Agent.manual_start assert_equal(NewRelic::Agent.agent, NewRelic::Agent.instance, - "should return the same agent for both identical methods") + 'should return the same agent for both identical methods') NewRelic::Agent.shutdown end @@ -317,7 +320,7 @@ def test_get_txn_name_and_set_txn_name_preserves_category engine.reset! Transactor.new.txn do NewRelic::Agent.set_transaction_name('a_new_name', :category => :task) - new_name = NewRelic::Agent.get_transaction_name + "2" + new_name = NewRelic::Agent.get_transaction_name + '2' NewRelic::Agent.set_transaction_name(new_name) end @@ -458,7 +461,7 @@ def test_linking_metadata_no_transaction # unexpectedly get a noticed error Hash returned from their methods. def test_notice_error_returns_nil begin - raise "WTF" + raise 'WTF' rescue => e assert_nil ::NewRelic::Agent.notice_error(e) end @@ -529,6 +532,83 @@ def test_modules_and_classes_return_name_properly end end + def test_set_error_group_callback + lambda = -> { 'Hello, World!' } + NewRelic::Agent.set_error_group_callback(lambda) + + assert_equal lambda, + NewRelic::Agent.instance_variable_get(:@error_group_callback), + 'Supplied error group callback proc was not found to be set.' + end + + def test_set_error_group_callback_can_be_called_multiple_times + procs = [proc { 'one' }, proc { 'two' }, proc { 'three' }] + procs.each { |proc| NewRelic::Agent.set_error_group_callback(proc) } + + assert_equal procs.last, + NewRelic::Agent.instance_variable_get(:@error_group_callback), + 'Supplied error group callback proc was not found to be set.' + end + + def test_set_error_group_callback_rejects_non_proc + skip_unless_minitest5_or_above + + NewRelic::Agent.instance_variable_set(:@error_group_callback, nil) + + mock_logger = MiniTest::Mock.new + mock_logger.expect :error, nil, [/expected an argument of type Proc/] + + NewRelic::Agent.stub(:logger, mock_logger) do + NewRelic::Agent.set_error_group_callback([]) + end + + mock_logger.verify + assert_nil NewRelic::Agent.instance_variable_get(:@error_group_callback) + end + + def test_error_group_callback_is_exposed + callback = 'lucky tiger' + NewRelic::Agent.instance_variable_set(:@error_group_callback, callback) + + assert_equal callback, NewRelic::Agent.error_group_callback + ensure + NewRelic::Agent.remove_instance_variable(:@error_group_callback) + end + + def test_successful_set_error_group_callback_api_invocation_produces_supportability_metrics + called = false + verification_proc = proc { |name| called = true if name == :set_error_group_callback } + NewRelic::Agent.stub :record_api_supportability_metric, verification_proc do + NewRelic::Agent.set_error_group_callback(proc {}) + end + assert called + end + + def test_set_user_id_attribute + test_user = 'test_user_id' + + in_transaction do |txn| + NewRelic::Agent.set_user_id(test_user) + NewRelic::Agent.notice_error(NewRelic::TestHelpers::Exceptions::TestError.new) + end + + assert_equal test_user, harvest_transaction_events![1][0][2][:'enduser.id'] + assert_equal test_user, harvest_error_events![1][0][2][:'enduser.id'] + end + + def test_set_user_id_nil_or_empty_error + [nil, ''].each do |test_user_id| + in_transaction do |txn| + NewRelic::Agent.set_user_id(test_user_id) + NewRelic::Agent.notice_error(NewRelic::TestHelpers::Exceptions::TestError.new) + end + + [harvest_transaction_events!, harvest_error_events!].each do |events| + refute events[1][0][2].key?(:'enduser.id') + end + end + end + private def with_unstarted_agent diff --git a/test/new_relic/cli/commands/deployments_test.rb b/test/new_relic/cli/commands/deployments_test.rb index 6d66238c24..6ad6aa692d 100644 --- a/test/new_relic/cli/commands/deployments_test.rb +++ b/test/new_relic/cli/commands/deployments_test.rb @@ -35,8 +35,8 @@ def teardown def test_help begin - NewRelic::Cli::Deployments.new("-h") - fail "should have thrown" + NewRelic::Cli::Deployments.new('-h') + fail 'should have thrown' rescue NewRelic::Cli::Command::CommandFailure => c assert_match(/^Usage/, c.message) end @@ -45,7 +45,7 @@ def test_help def test_bad_command assert_raises NewRelic::Cli::Command::CommandFailure do - NewRelic::Cli::Deployments.new(["-foo", "bar"]) + NewRelic::Cli::Deployments.new(['-foo', 'bar']) end @deployment = nil end @@ -55,7 +55,7 @@ def test_interactive @deployment = NewRelic::Cli::Deployments.new(:appname => 'APP', :revision => 3838, :user => 'Bill', - :description => "Some lengthy description") + :description => 'Some lengthy description') assert_nil @deployment.exit_status assert_nil @deployment.errors @@ -69,16 +69,16 @@ def test_interactive_v2 with_config(:api_key => 'fake_api_key') do @deployment = NewRelic::Cli::Deployments.new(:appname => 'APP', :revision => 3838, - :application_id => "appid", + :application_id => 'appid', :user => 'Bill', - :description => "Some lengthy description") + :description => 'Some lengthy description') assert_nil @deployment.exit_status assert_nil @deployment.errors assert_equal '3838', @deployment.revision @deployment.run - refute @deployment.api_v1?, "Using v1 when v2 should be used" + refute @deployment.api_v1?, 'Using v1 when v2 should be used' @deployment = nil end end @@ -86,7 +86,7 @@ def test_interactive_v2 def test_command_line_run mock_the_connection # @mock_response.expects(:body).returns("deployment") - @deployment = NewRelic::Cli::Deployments.new(%w[-a APP -r 3838 --user=Bill] << "Some lengthy description") + @deployment = NewRelic::Cli::Deployments.new(%w[-a APP -r 3838 --user=Bill] << 'Some lengthy description') assert_nil @deployment.exit_status assert_nil @deployment.errors @@ -103,14 +103,14 @@ def test_command_line_run def test_command_line_run_v2 mock_the_connection with_config(:api_key => 'fake_api_key') do - @deployment = NewRelic::Cli::Deployments.new(%w[-a APP -r 3838 --user=Bill --appid=appid1234] << "Some lengthy description") + @deployment = NewRelic::Cli::Deployments.new(%w[-a APP -r 3838 --user=Bill --appid=appid1234] << 'Some lengthy description') assert_nil @deployment.exit_status assert_nil @deployment.errors assert_equal '3838', @deployment.revision @deployment.run - refute @deployment.api_v1?, "Using v1 when v2 should be used" + refute @deployment.api_v1?, 'Using v1 when v2 should be used' @deployment = nil end end @@ -118,7 +118,7 @@ def test_command_line_run_v2 def test_error_if_no_license_key with_config(:license_key => '') do assert_raises NewRelic::Cli::Command::CommandFailure do - deployment = NewRelic::Cli::Deployments.new(%w[-a APP -r 3838 --user=Bill] << "Some lengthy description") + deployment = NewRelic::Cli::Deployments.new(%w[-a APP -r 3838 --user=Bill] << 'Some lengthy description') deployment.run end end @@ -128,7 +128,7 @@ def test_error_if_no_license_key def test_error_if_no_revision_with_api_key with_config(:api_key => 'fake_api_key') do assert_raises NewRelic::Cli::Command::CommandFailure do - deployment = NewRelic::Cli::Deployments.new(%w[-a APP --user=Bill] << "Some lengthy description") + deployment = NewRelic::Cli::Deployments.new(%w[-a APP --user=Bill] << 'Some lengthy description') deployment.run end end @@ -139,7 +139,7 @@ def test_error_if_failed_yaml NewRelic::Agent::Configuration::YamlSource.any_instance.stubs(:failed?).returns(true) assert_raises NewRelic::Cli::Command::CommandFailure do - deployment = NewRelic::Cli::Deployments.new(%w[-a APP -r 3838 --user=Bill] << "Some lengthy description") + deployment = NewRelic::Cli::Deployments.new(%w[-a APP -r 3838 --user=Bill] << 'Some lengthy description') deployment.run end @deployment = nil @@ -150,7 +150,7 @@ def test_with_specified_license_key @deployment = NewRelic::Cli::Deployments.new(:appname => 'APP', :revision => 3838, :user => 'Bill', - :description => "Some lengthy description", + :description => 'Some lengthy description', :license_key => 'b' * 40) assert_nil @deployment.exit_status @@ -165,7 +165,7 @@ def test_with_unspecified_license_key @deployment = NewRelic::Cli::Deployments.new(:appname => 'APP', :revision => 3838, :user => 'Bill', - :description => "Some lengthy description") + :description => 'Some lengthy description') assert_nil @deployment.exit_status assert_nil @deployment.errors @@ -179,7 +179,7 @@ def test_gets_appid_from_connect_when_not_provided_with_v2 mock_the_collector with_config(:api_key => 'fake_api_key') do - @deployment = NewRelic::Cli::Deployments.new(%w[-a APP -r 3838 --user=Bill] << "Some lengthy description") + @deployment = NewRelic::Cli::Deployments.new(%w[-a APP -r 3838 --user=Bill] << 'Some lengthy description') assert_nil @deployment.exit_status assert_nil @deployment.errors diff --git a/test/new_relic/cli/commands/install_test.rb b/test/new_relic/cli/commands/install_test.rb index a07b6d9007..e98291d299 100644 --- a/test/new_relic/cli/commands/install_test.rb +++ b/test/new_relic/cli/commands/install_test.rb @@ -9,21 +9,21 @@ class NewRelic::Cli::InstallTest < Minitest::Test def test_fails_without_app_name assert_raises(NewRelic::Cli::Command::CommandFailure) do - NewRelic::Cli::Install.new(["-l", "license"]) + NewRelic::Cli::Install.new(['-l', 'license']) end end def test_basic_run - install = NewRelic::Cli::Install.new(["-l", "license", "app"]) + install = NewRelic::Cli::Install.new(['-l', 'license', 'app']) - assert_equal "license", install.license_key - assert_equal "app", install.app_name + assert_equal 'license', install.license_key + assert_equal 'app', install.app_name end def test_app_name_with_spaces - install = NewRelic::Cli::Install.new(["-l", "license", "my", "app"]) + install = NewRelic::Cli::Install.new(['-l', 'license', 'my', 'app']) - assert_equal "license", install.license_key - assert_equal "my app", install.app_name + assert_equal 'license', install.license_key + assert_equal 'my app', install.app_name end end diff --git a/test/new_relic/coerce_test.rb b/test/new_relic/coerce_test.rb index 9b4d117773..266cd7229f 100644 --- a/test/new_relic/coerce_test.rb +++ b/test/new_relic/coerce_test.rb @@ -10,77 +10,77 @@ class CoerceTest < Minitest::Test def test_int_coerce assert_equal 1, int(1) - assert_equal 1, int("1") + assert_equal 1, int('1') assert_equal 1, int(1.0) assert_equal 1, int(Rational(1, 1)) - assert_equal 0, int("invalid") + assert_equal 0, int('invalid') assert_equal 0, int(nil) assert_equal 0, int(:wat) end def test_int_coerce_logs - expects_logging(:warn, Not(includes("context")), any_parameters) - int("not valid") + expects_logging(:warn, Not(includes('context')), any_parameters) + int('not valid') end def test_int_coerce_logs_with_context - expects_logging(:warn, all_of(includes("HERE"), includes("Integer")), anything) - int("not valid", "HERE") + expects_logging(:warn, all_of(includes('HERE'), includes('Integer')), anything) + int('not valid', 'HERE') end def test_int_coerce_or_nil assert_equal 1, int_or_nil(1) - assert_equal 1, int_or_nil("1") + assert_equal 1, int_or_nil('1') assert_equal 1, int_or_nil(1.0) assert_equal 1, int_or_nil(Rational(1, 1)) - assert_nil int_or_nil("invalid") + assert_nil int_or_nil('invalid') assert_nil int_or_nil(nil) end def test_int_or_nil_coerce_logs_with_context - expects_logging(:warn, all_of(includes("HERE"), includes("Integer")), anything) - int_or_nil("not valid", "HERE") + expects_logging(:warn, all_of(includes('HERE'), includes('Integer')), anything) + int_or_nil('not valid', 'HERE') end def test_float_coerce assert_in_delta(1.0, float(1.0)) - assert_in_delta(1.0, float("1.0")) + assert_in_delta(1.0, float('1.0')) assert_in_delta(1.0, float(1)) assert_in_delta(1.0, float(Rational(1, 1))) - assert_in_delta(0.0, float("invalid")) + assert_in_delta(0.0, float('invalid')) assert_in_delta(0.0, float(nil)) assert_in_delta(0.0, float(:symbols_are_fun)) end def test_float_coerce_logs_with_context - expects_logging(:warn, all_of(includes("HERE"), includes("Float")), anything) - float("not valid", "HERE") + expects_logging(:warn, all_of(includes('HERE'), includes('Float')), anything) + float('not valid', 'HERE') end def test_float_coerce_with_infinite_value_logs_and_returns_0_0 - expects_logging(:warn, all_of(includes("TestingInfinity"), includes("Float"), includes("'Infinity'")), anything) + expects_logging(:warn, all_of(includes('TestingInfinity'), includes('Float'), includes("'Infinity'")), anything) infinity = 1337807.0 / 0.0 - result = float(infinity, "TestingInfinity") + result = float(infinity, 'TestingInfinity') assert_in_delta(0.0, result) end def test_float_coerce_with_nan_value_logs_and_returns_0_0 - expects_logging(:warn, all_of(includes("TestingNaN"), includes("Float"), includes("'NaN'")), anything) + expects_logging(:warn, all_of(includes('TestingNaN'), includes('Float'), includes("'NaN'")), anything) nan = 0.0 / 0.0 - result = float(nan, "TestingNaN") + result = float(nan, 'TestingNaN') assert_in_delta(0.0, result) end def test_string_coerce - assert_equal "1", string(1) - assert_equal "1.0", string(1.0) - assert_equal "string", string("string") - assert_equal "1/100", string(Rational(1, 100)) - assert_equal "yeah", string(:yeah) + assert_equal '1', string(1) + assert_equal '1.0', string(1.0) + assert_equal 'string', string('string') + assert_equal '1/100', string(Rational(1, 100)) + assert_equal 'yeah', string(:yeah) assert_nil string(nil) - assert_equal "", string(Unstringable.new) + assert_equal '', string(Unstringable.new) end def test_int! @@ -104,8 +104,8 @@ def test_value_or_nil end def test_string_coerce_logs_with_context - expects_logging(:warn, all_of(includes("HERE"), includes("String")), anything) - string(Unstringable.new, "HERE") + expects_logging(:warn, all_of(includes('HERE'), includes('String')), anything) + string(Unstringable.new, 'HERE') end class Unstringable diff --git a/test/new_relic/collection_helper_test.rb b/test/new_relic/collection_helper_test.rb index cc67f7a080..9ebbeb3527 100644 --- a/test/new_relic/collection_helper_test.rb +++ b/test/new_relic/collection_helper_test.rb @@ -21,7 +21,7 @@ def teardown def test_string val = (('A'..'Z').to_a.join * 1024).to_s - assert_equal val[0...16384] + "...", normalize_params(val) + assert_equal val[0...16384] + '...', normalize_params(val) end def test_array @@ -38,7 +38,7 @@ def test_boolean end def test_string__singleton - val = String.new('This String') + val = +'This String' def val.hello; end assert_equal 'This String', normalize_params(val) @@ -49,9 +49,9 @@ def val.hello; end class MyString < String; end def test_kind_of_string - s = MyString.new("This is a string") + s = MyString.new('This is a string') - assert_equal "This is a string", s.to_s + assert_equal 'This is a string', s.to_s assert_equal MyString, s.class assert_equal String, s.to_s.class params = normalize_params(:val => [s]) @@ -68,14 +68,14 @@ def test_number def test_nil np = normalize_params({nil => 1.0, 'two' => nil}) - assert_equal "1.0", np[''] + assert_equal '1.0', np[''] assert_nil np['two'] end def test_hash val = ('A'..'Z').to_a.join * 100 - assert_equal Hash[(val[0..63] + "...") => (("0" * 16384) + "...")], normalize_params({val => '0' * (16384 * 2)}) + assert_equal Hash[(val[0..63] + '...') => (('0' * 16384) + '...')], normalize_params({val => '0' * (16384 * 2)}) end class MyHash < Hash @@ -106,14 +106,14 @@ def test_enumerable def test_stringio # Verify StringIO works like this normally: - s = StringIO.new("start" + ("foo bar bat " * 1000)) + s = StringIO.new('start' + ('foo bar bat ' * 1000)) val = nil s.each { |entry| val = entry; break } assert_match(/^startfoo bar/, val) # make sure stringios aren't affected by calling normalize_params: - s = StringIO.new("start" + ("foo bar bat " * 1000)) + s = StringIO.new('start' + ('foo bar bat ' * 1000)) normalize_params({:foo => s.string}) s.each { |entry| val = entry; break } @@ -124,11 +124,11 @@ class MyEnumerable include Enumerable def each - yield("1") + yield('1') end end def test_object - assert_equal ["foo", '#'], normalize_params(['foo', OpenStruct.new('z' => 'q')]) + assert_equal ['foo', '#'], normalize_params(['foo', OpenStruct.new('z' => 'q')]) end end diff --git a/test/new_relic/control/class_methods_test.rb b/test/new_relic/control/class_methods_test.rb index afe86431d6..089d2cb04e 100644 --- a/test/new_relic/control/class_methods_test.rb +++ b/test/new_relic/control/class_methods_test.rb @@ -24,7 +24,7 @@ def test_instance assert_nil(@base.instance_variable_get(:@instance), 'instance should start out nil') @base.expects(:new_instance).returns('a new instance') - assert_equal('a new instance', @base.instance, "should return the result from the #new_instance call") + assert_equal('a new instance', @base.instance, 'should return the result from the #new_instance call') end def test_load_test_framework diff --git a/test/new_relic/control/instrumentation_test.rb b/test/new_relic/control/instrumentation_test.rb index 075cf9bcb6..e428fc6fee 100644 --- a/test/new_relic/control/instrumentation_test.rb +++ b/test/new_relic/control/instrumentation_test.rb @@ -20,7 +20,7 @@ def setup def test_load_instrumentation_files_logs_errors_during_require @test_class.stubs(:require).raises('Instrumentation Test Error') - expects_logging(:warn, includes("Error loading"), any_parameters) + expects_logging(:warn, includes('Error loading'), any_parameters) @test_class.load_instrumentation_files('*') end diff --git a/test/new_relic/control_test.rb b/test/new_relic/control_test.rb index 75bcbeb42d..1e41e2efb0 100644 --- a/test/new_relic/control_test.rb +++ b/test/new_relic/control_test.rb @@ -26,13 +26,13 @@ def test_root assert File.directory?(NewRelic::Control.newrelic_root) return unless defined?(Rails::VERSION) - assert File.directory?(File.join(NewRelic::Control.newrelic_root, "lib")) + assert File.directory?(File.join(NewRelic::Control.newrelic_root, 'lib')) end def test_info NewRelic::Agent.manual_start if defined?(Rails::VERSION) - assert_match(/jdbc|postgres|mysql|sqlite/, NewRelic::EnvironmentReport.new["Database adapter"]) + assert_match(/jdbc|postgres|mysql|sqlite/, NewRelic::EnvironmentReport.new['Database adapter']) end end @@ -96,7 +96,7 @@ def test_init_plugin_loads_samplers_enabled :license_key => 'a' * 40) do NewRelic::Control.instance.init_plugin - assert_predicate NewRelic::Agent.instance.harvest_samplers, :any? + assert_predicate NewRelic::Agent.instance.instance_variable_get(:@harvest_samplers), :any? end end @@ -110,7 +110,7 @@ def test_init_plugin_loads_samplers_disabled :license_key => 'a' * 40) do NewRelic::Control.instance.init_plugin - refute NewRelic::Agent.instance.harvest_samplers.any? + refute NewRelic::Agent.instance.instance_variable_get(:@harvest_samplers).any? end end @@ -127,7 +127,7 @@ def test_agent_not_starting_does_not_load_samplers NewRelic::Control.instance.init_plugin refute NewRelic::Agent.instance.already_started? - refute NewRelic::Agent.instance.harvest_samplers.any? + refute NewRelic::Agent.instance.instance_variable_get(:@harvest_samplers).any? end end @@ -146,15 +146,15 @@ def test_agent_starting_after_fork_does_load_samplers NewRelic::Agent.after_fork assert_predicate NewRelic::Agent.instance, :already_started? - assert_predicate NewRelic::Agent.instance.harvest_samplers, :any? + assert_predicate NewRelic::Agent.instance.instance_variable_get(:@harvest_samplers), :any? end end def reset_agent NewRelic::Agent.shutdown - NewRelic::Agent.instance.harvest_samplers.clear + NewRelic::Agent.instance.instance_variable_get(:@harvest_samplers).clear NewRelic::Agent.instance.instance_variable_set(:@connect_state, :pending) NewRelic::Agent.instance.instance_variable_set(:@worker_thread, nil) - NewRelic::Agent.instance.harvester.instance_variable_set(:@starting_pid, nil) + NewRelic::Agent.instance.instance_variable_get(:@harvester).instance_variable_set(:@starting_pid, nil) end end diff --git a/test/new_relic/dependency_detection_test.rb b/test/new_relic/dependency_detection_test.rb index 9099c08053..9b0d062b5d 100644 --- a/test/new_relic/dependency_detection_test.rb +++ b/test/new_relic/dependency_detection_test.rb @@ -6,12 +6,12 @@ class DependencyDetectionTest < Minitest::Test def setup - @original_items = DependencyDetection.items - DependencyDetection.items = [] + @original_items = DependencyDetection.instance_variable_get(:@items) + DependencyDetection.instance_variable_set(:@items, []) end def teardown - DependencyDetection.items = @original_items + DependencyDetection.instance_variable_set(:@items, @original_items) end def test_passes_dependency @@ -70,7 +70,7 @@ def test_short_circuits_on_failure # Requires that depends_on would let failures pass through, which it does DependencyDetection.defer do depends_on { false } - depends_on { raise "OH NOES" } + depends_on { raise 'OH NOES' } executes { executed = true } end DependencyDetection.detect! @@ -140,7 +140,7 @@ def test_config_disabling executes { executed = true } end - with_config(:'instrumentation.testing' => "disabled") do + with_config(:'instrumentation.testing' => 'disabled') do executed = false DependencyDetection.detect! @@ -150,7 +150,7 @@ def test_config_disabling refute executed end - with_config(:'instrumentation.testing' => "enabled") do + with_config(:'instrumentation.testing' => 'enabled') do executed = false DependencyDetection.detect! @@ -180,7 +180,7 @@ def test_config_enabling executes { executed = true } end - with_config(:'instrumentation.testing' => "enabled") do + with_config(:'instrumentation.testing' => 'enabled') do executed = false DependencyDetection.detect! @@ -190,7 +190,7 @@ def test_config_enabling assert_predicate dd, :use_prepend? end - with_config(:'instrumentation.testing' => "auto") do + with_config(:'instrumentation.testing' => 'auto') do DependencyDetection.detect! refute dd.disabled_configured? @@ -198,7 +198,7 @@ def test_config_enabling assert_predicate dd, :use_prepend? end - with_config(:'instrumentation.testing' => "prepend") do + with_config(:'instrumentation.testing' => 'prepend') do DependencyDetection.detect! refute dd.disabled_configured? @@ -206,7 +206,7 @@ def test_config_enabling assert_predicate dd, :use_prepend? end - with_config(:'instrumentation.testing' => "chain") do + with_config(:'instrumentation.testing' => 'chain') do DependencyDetection.detect! refute dd.disabled_configured? @@ -228,14 +228,14 @@ def test_config_prepend assert_predicate dd, :use_prepend? end - with_config(:'instrumentation.testing' => "prepend") do + with_config(:'instrumentation.testing' => 'prepend') do DependencyDetection.detect! assert_equal :prepend, dd.config_value assert_predicate dd, :use_prepend? end - with_config(:'instrumentation.testing' => "disabled") do + with_config(:'instrumentation.testing' => 'disabled') do DependencyDetection.detect! refute dd.use_prepend? @@ -250,7 +250,7 @@ def test_selects_chain_method_explicitly executes { executed = true } end - with_config(:'instrumentation.testing' => "chain") do + with_config(:'instrumentation.testing' => 'chain') do DependencyDetection.detect! refute dd.use_prepend? @@ -269,7 +269,7 @@ def test_conflicts_simple_truthy DependencyDetection.detect! - assert conflicted, "should be truthy!" + assert conflicted, 'should be truthy!' end def test_conflicts_simple_falsey @@ -282,7 +282,7 @@ def test_conflicts_simple_falsey DependencyDetection.detect! - refute conflicted, "should be falsey!" + refute conflicted, 'should be falsey!' end def test_conflicts_defined_falsey @@ -295,8 +295,8 @@ def test_conflicts_defined_falsey DependencyDetection.detect! - refute conflicted, "should be falsey!" - assert_predicate dd, :use_prepend?, "should use prepend when no conflicts exist" + refute conflicted, 'should be falsey!' + assert_predicate dd, :use_prepend?, 'should use prepend when no conflicts exist' end def test_conflicts_defined_truthy @@ -309,8 +309,8 @@ def test_conflicts_defined_truthy DependencyDetection.detect! - assert conflicted, "should be truthy!" - refute dd.use_prepend?, "should not use prepend when conflicts exist" + assert conflicted, 'should be truthy!' + refute dd.use_prepend?, 'should not use prepend when conflicts exist' end def test_conflicts_multiples_truthy @@ -324,19 +324,19 @@ def test_conflicts_multiples_truthy DependencyDetection.detect! - assert conflicted, "should be truthy!" - refute dd.use_prepend?, "should not use prepend when conflicts exist" + assert conflicted, 'should be truthy!' + refute dd.use_prepend?, 'should not use prepend when conflicts exist' end def test_exception_during_depends_on_check_doesnt_propagate DependencyDetection.defer do named(:something_exceptional) - depends_on { raise "Oops" } + depends_on { raise 'Oops' } end DependencyDetection.detect! - assert_falsy(DependencyDetection.items.first.executed) + assert_falsy(DependencyDetection.instance_variable_get(:@items).first.executed) end def test_exception_during_execution_doesnt_propagate @@ -344,13 +344,13 @@ def test_exception_during_execution_doesnt_propagate DependencyDetection.defer do named(:something_exceptional) - executes { raise "Ack!" } + executes { raise 'Ack!' } executes { ran_second_block = true } end DependencyDetection.detect! - assert_truthy(DependencyDetection.items.first.executed) + assert_truthy(DependencyDetection.instance_variable_get(:@items).first.executed) assert_falsy(ran_second_block) end diff --git a/test/new_relic/dispatcher_test.rb b/test/new_relic/dispatcher_test.rb index e6a83efa8c..266e194ad3 100644 --- a/test/new_relic/dispatcher_test.rb +++ b/test/new_relic/dispatcher_test.rb @@ -17,7 +17,7 @@ def teardown end def assert_dispatcher_reported_to_environment_report(dispatcher) - assert_equal dispatcher.to_s, NewRelic::EnvironmentReport.new["Dispatcher"] + assert_equal dispatcher.to_s, NewRelic::EnvironmentReport.new['Dispatcher'] end def test_detects_dispatcher_via_loaded_libraries @@ -33,7 +33,7 @@ module ::PhusionPassenger end def test_detects_dispatcher_via_ENV_NEW_RELIC_DISPATCHER - ENV['NEW_RELIC_DISPATCHER'] = "foobared" + ENV['NEW_RELIC_DISPATCHER'] = 'foobared' NewRelic::Agent.reset_config assert_equal :foobared, NewRelic::Agent.config[:dispatcher] @@ -43,7 +43,7 @@ def test_detects_dispatcher_via_ENV_NEW_RELIC_DISPATCHER end def test_detects_dispatcher_via_ENV_NEWRELIC_DISPATCHER - ENV['NEWRELIC_DISPATCHER'] = "bazbang" + ENV['NEWRELIC_DISPATCHER'] = 'bazbang' NewRelic::Agent.reset_config assert_equal :bazbang, NewRelic::Agent.config[:dispatcher] diff --git a/test/new_relic/environment_report_test.rb b/test/new_relic/environment_report_test.rb index 2954247d59..663d9f6c5b 100644 --- a/test/new_relic/environment_report_test.rb +++ b/test/new_relic/environment_report_test.rb @@ -16,7 +16,7 @@ def teardown end def test_converts_to_array - ::NewRelic::EnvironmentReport.report_on("something") { "awesome" } + ::NewRelic::EnvironmentReport.report_on('something') { 'awesome' } data = Array(::NewRelic::EnvironmentReport.new) expected = %w[something awesome] @@ -24,33 +24,33 @@ def test_converts_to_array end def test_register_a_value_to_report_on - ::NewRelic::EnvironmentReport.report_on("What time is it?") do - "beer-o-clock" + ::NewRelic::EnvironmentReport.report_on('What time is it?') do + 'beer-o-clock' end - assert_equal 'beer-o-clock', ::NewRelic::EnvironmentReport.new["What time is it?"] + assert_equal 'beer-o-clock', ::NewRelic::EnvironmentReport.new['What time is it?'] end def test_report_on_handles_errors_gracefully - ::NewRelic::EnvironmentReport.report_on("What time is it?") do - raise ArgumentError, "woah! something blew up" + ::NewRelic::EnvironmentReport.report_on('What time is it?') do + raise ArgumentError, 'woah! something blew up' end - assert_nil ::NewRelic::EnvironmentReport.new["What time is it?"] + assert_nil ::NewRelic::EnvironmentReport.new['What time is it?'] end def test_it_does_not_set_keys_for_nil_values - ::NewRelic::EnvironmentReport.report_on("What time is it?") do + ::NewRelic::EnvironmentReport.report_on('What time is it?') do nil end - refute NewRelic::EnvironmentReport.new.data.has_key?("What time is it?") + refute NewRelic::EnvironmentReport.new.data.has_key?('What time is it?') end def test_can_set_an_environment_value_directly - @report['My Value'] = "so awesome!!" + @report['My Value'] = 'so awesome!!' - assert_equal "so awesome!!", @report['My Value'] + assert_equal 'so awesome!!', @report['My Value'] end def test_it_knows_what_gems_are_in_the_environment @@ -85,12 +85,12 @@ def test_gathers_system_info def test_has_logic_for_keys [ - "Gems", - "Plugin List", - "Ruby version", - "Ruby description", - "Ruby platform", - "Ruby patchlevel", + 'Gems', + 'Plugin List', + 'Ruby version', + 'Ruby description', + 'Ruby platform', + 'Ruby patchlevel', 'JRuby version', 'Java VM version', 'Logical Processors', diff --git a/test/new_relic/evil_server.rb b/test/new_relic/evil_server.rb index 1d968d030e..d287537032 100644 --- a/test/new_relic/evil_server.rb +++ b/test/new_relic/evil_server.rb @@ -27,14 +27,14 @@ def stop @state = :stopped # just a lazy way of just forcing the server to wakeup from accept - TCPSocket.open("localhost", @port).close rescue nil + TCPSocket.open('localhost', @port).close rescue nil @thread.join @thread = nil end def start - return if @thread && @thread.alive? + return if @thread&.alive? @requests = [] @server = TCPServer.new(0) diff --git a/test/new_relic/fake_collector.rb b/test/new_relic/fake_collector.rb index 9ed8ff5561..875555e513 100644 --- a/test/new_relic/fake_collector.rb +++ b/test/new_relic/fake_collector.rb @@ -59,7 +59,7 @@ def initialize @id_counter = 0 @mock = { 'preconnect' => Response.new(200, {'return_value' => {'redirect_host' => 'localhost'}}), - 'connect' => Response.new(200, proc { {'return_value' => {"agent_run_id" => agent_run_id}} }), + 'connect' => Response.new(200, proc { {'return_value' => {'agent_run_id' => agent_run_id}} }), 'get_agent_commands' => Response.new(200, {'return_value' => []}), 'agent_command_results' => Response.new(200, {'return_value' => []}), 'metric_data' => Response.new(200, {'return_value' => [[{'name' => 'Some/Metric/Spec'}, 1]]}), @@ -103,7 +103,7 @@ def stub_exception(method, exception, status = 200) def stub_wait(method, wait_time, status = 200) self.mock[method] ||= default_response - self.mock[method].override(status, proc { sleep(wait_time); {'return_value' => ""} }) + self.mock[method].override(status, proc { sleep(wait_time); {'return_value' => ''} }) end def method_from_request(req) @@ -129,15 +129,15 @@ def call(env) res.write(::JSON.dump(body)) else res.status = 500 - res.write("Method not found") + res.write('Method not found') end run_id = uri.query =~ /run_id=(\d+)/ ? $1 : nil req.body.rewind begin raw_body = req.body.read - raw_body = Zlib::Inflate.inflate(raw_body) if req.env["HTTP_CONTENT_ENCODING"] == "deflate" - raw_body = Zlib::GzipReader.new(StringIO.new(raw_body)).read if req.env["HTTP_CONTENT_ENCODING"] == "gzip" + raw_body = Zlib::Inflate.inflate(raw_body) if req.env['HTTP_CONTENT_ENCODING'] == 'deflate' + raw_body = Zlib::GzipReader.new(StringIO.new(raw_body)).read if req.env['HTTP_CONTENT_ENCODING'] == 'gzip' body = ::JSON.load(raw_body) rescue @@ -241,7 +241,7 @@ def metrics end def metric_names - metrics.map { |m| m[0]["name"] } + metrics.map { |m| m[0]['name'] } end end @@ -252,7 +252,7 @@ def initialize(opts = {}) end def utilization - @body["utilization"] + @body['utilization'] end end @@ -387,15 +387,15 @@ def initialize(error_info) end def agent_attributes - @params["agentAttributes"] + @params['agentAttributes'] end def custom_attributes - @params["userAttributes"] + @params['userAttributes'] end def intrinsic_attributes - @params["intrinsics"] + @params['intrinsics'] end end @@ -404,8 +404,8 @@ class LogEventDataPost < AgentPost def initialize(opts = {}) super - @common = body.first["common"] - @logs = body.first["logs"] + @common = body.first['common'] + @logs = body.first['logs'] end end end diff --git a/test/new_relic/fake_external_server.rb b/test/new_relic/fake_external_server.rb index eb2b28373c..c26de00793 100644 --- a/test/new_relic/fake_external_server.rb +++ b/test/new_relic/fake_external_server.rb @@ -9,7 +9,7 @@ module NewRelic class FakeExternalServer < FakeServer - STATUS_MESSAGE = "FakeExternalServer status" + + STATUS_MESSAGE = 'FakeExternalServer status' + "The FakeExternalServer is rockin'" attr_reader :overridden_response_headers @@ -26,7 +26,7 @@ def call(env) req = ::Rack::Request.new(env) res = ::Rack::Response.new - res.status = req.params["status"].to_i if req.params["status"] + res.status = req.params['status'].to_i if req.params['status'] in_transaction('test') do res.write(STATUS_MESSAGE) diff --git a/test/new_relic/fake_rpm_site.rb b/test/new_relic/fake_rpm_site.rb index 3012c73cee..2331258f04 100644 --- a/test/new_relic/fake_rpm_site.rb +++ b/test/new_relic/fake_rpm_site.rb @@ -18,7 +18,7 @@ def initialize(*_) def call(env) @requests << unpack(env) - [200, {}, ["Fine"]] + [200, {}, ['Fine']] end def unpack(env) diff --git a/test/new_relic/fake_server.rb b/test/new_relic/fake_server.rb index a74235d87d..8dc38237fd 100644 --- a/test/new_relic/fake_server.rb +++ b/test/new_relic/fake_server.rb @@ -5,7 +5,7 @@ require 'webrick' require 'webrick/https' require 'rack' -require 'rackup/handler' unless Rack.release =~ /^1|2/ +require 'rackup/handler' unless /^1|2/.match?(Rack.release) require 'timeout' require 'json' @@ -16,20 +16,20 @@ class FakeServer # Default server options DEFAULT_OPTIONS = { - :Logger => ::WEBrick::Log.new(String.new('/dev/null')), - :AccessLog => [[String.new('/dev/null'), '']] + :Logger => ::WEBrick::Log.new((+'/dev/null')), + :AccessLog => [[+'/dev/null', '']] } CONFIG_PATH = String.new(File.join(File.dirname(__FILE__), '..', 'config')) - FAKE_SSL_CERT_PATH = File.join(CONFIG_PATH, String.new('test.cert.crt')) - FAKE_SSL_KEY_PATH = File.join(CONFIG_PATH, String.new('test.cert.key')) + FAKE_SSL_CERT_PATH = File.join(CONFIG_PATH, (+'test.cert.crt')) + FAKE_SSL_KEY_PATH = File.join(CONFIG_PATH, (+'test.cert.key')) SSL_OPTIONS = { :SSLEnable => true, :SSLVerifyClient => OpenSSL::SSL::VERIFY_NONE, :SSLPrivateKey => OpenSSL::PKey::RSA.new(File.read(FAKE_SSL_KEY_PATH)), :SSLCertificate => OpenSSL::X509::Certificate.new(File.read(FAKE_SSL_CERT_PATH)), - :SSLCertName => [[String.new('CN'), String.new('newrelic.com')]] + :SSLCertName => [[+'CN', +'newrelic.com']] } def initialize(port = DEFAULT_PORT) @@ -57,7 +57,7 @@ def restart end def running? - @thread && @thread.alive? + @thread&.alive? end def run @@ -66,7 +66,7 @@ def run @started_options = build_webrick_options @server = WEBrick::HTTPServer.new(@started_options) - @server.mount(String.new('/'), webrick_handler, app) + @server.mount((+'/'), webrick_handler, app) @thread = Thread.new(&self.method(:run_server)).tap { |t| t.abort_on_exception = true } end @@ -114,7 +114,7 @@ def call(env) req = ::Rack::Request.new(env) res = ::Rack::Response.new res.status = 403 - res.body = [String.new("Forbidden\n")] + res.body = [+"Forbidden\n"] res.finish end @@ -130,7 +130,7 @@ def reset end def call(env) - raise String.new('something went wrong!') + raise (+'something went wrong!') end def app diff --git a/test/new_relic/filtering_test_app.rb b/test/new_relic/filtering_test_app.rb index 4ca537ed43..e1c3f8c2e5 100644 --- a/test/new_relic/filtering_test_app.rb +++ b/test/new_relic/filtering_test_app.rb @@ -13,8 +13,8 @@ def call(env) filtered = ::NewRelic::Agent::ParameterFiltering.apply_filters(env, params) txn.filtered_params = filtered txn.merge_request_parameters(filtered) - raise "Intentional error" if params["raise"] + raise 'Intentional error' if params['raise'] - [200, {}, ["Filters applied"]] + [200, {}, ['Filters applied']] end end diff --git a/test/new_relic/framework_test.rb b/test/new_relic/framework_test.rb index 08e16383d8..acb9a715b8 100644 --- a/test/new_relic/framework_test.rb +++ b/test/new_relic/framework_test.rb @@ -35,7 +35,7 @@ module Base end # does the path match "rails\d" (ex: rails7) or "railsedge"? - if ENV['BUNDLE_GEMFILE'] =~ /rails(?:\d|edge)/ + if /rails(?:\d|edge)/.match?(ENV['BUNDLE_GEMFILE']) # rubocop:disable Performance/StringInclude assert_truthy NewRelic::Agent.config[:framework].match(/rails/) # rubocop:enable Performance/StringInclude @@ -47,7 +47,7 @@ module Base end def test_detects_framework_via_ENV_NEW_RELIC_FRAMEWORK - ENV['NEW_RELIC_FRAMEWORK'] = "foobared" + ENV['NEW_RELIC_FRAMEWORK'] = 'foobared' NewRelic::Agent.reset_config assert_equal :foobared, NewRelic::Agent.config[:framework] @@ -56,7 +56,7 @@ def test_detects_framework_via_ENV_NEW_RELIC_FRAMEWORK end def test_detects_framework_via_ENV_NEWRELIC_FRAMEWORK - ENV['NEWRELIC_FRAMEWORK'] = "bazbang" + ENV['NEWRELIC_FRAMEWORK'] = 'bazbang' NewRelic::Agent.reset_config assert_equal :bazbang, NewRelic::Agent.config[:framework] diff --git a/test/new_relic/http_client_test_cases.rb b/test/new_relic/http_client_test_cases.rb index 507a64e68e..ea3bc675da 100644 --- a/test/new_relic/http_client_test_cases.rb +++ b/test/new_relic/http_client_test_cases.rb @@ -2,9 +2,9 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -require "newrelic_rpm" -require "fake_external_server" -require "evil_server" +require 'newrelic_rpm' +require 'fake_external_server' +require 'evil_server' module HttpClientTestCases include NewRelic::Agent::Instrumentation::ControllerInstrumentation, @@ -18,8 +18,8 @@ module HttpClientTestCases setup_and_teardown_agent( :"cross_application_tracer.enabled" => false, - :cross_process_id => "269975#22824", - :encoding_key => "gringletoes", + :cross_process_id => '269975#22824', + :encoding_key => 'gringletoes', :trusted_account_ids => [269975] ) @@ -45,7 +45,7 @@ def server end def protocol - @ssl ? "https" : "http" + @ssl ? 'https' : 'http' end def default_url @@ -73,11 +73,12 @@ def test_validate_request_wrapper req = request_instance assert_implements req, :type + assert_implements req, :headers assert_implements req, :host assert_implements req, :host_from_header assert_implements req, :method - assert_implements req, :[], "foo" - assert_implements req, :[]=, "foo", "bar" + assert_implements req, :[], 'foo' + assert_implements req, :[]=, 'foo', 'bar' assert_implements req, :uri end @@ -85,7 +86,7 @@ def test_validate_response_wrapper res = response_instance assert_implements res, :get_status_code - assert_implements res, :[], "foo" + assert_implements res, :[], 'foo' assert_implements res, :to_hash end @@ -97,15 +98,24 @@ def test_status_code_is_present assert_equal 200, res.status_code end + def test_request_headers + header_key = 'Honolooploop' + instance = request_instance + instance[header_key] = 'Charles Petrescu' + + assert instance.headers.is_a?(Hash) + assert instance.headers.any? { |k, v| k.casecmp?(header_key) } + end + # Some libraries (older Typhoeus), have had odd behavior around [] for # missing keys. This generates log messages, although it behaves right in # terms of metrics, so double-check we get what we expect def test_request_headers_for_missing_key - assert_nil request_instance["boo"] + assert_nil request_instance['boo'] end def test_response_headers_for_missing_key - assert_nil response_instance["boo"] + assert_nil response_instance['boo'] end def test_response_wrapper_ignores_case_in_header_keys @@ -119,7 +129,7 @@ def test_get in_transaction { res = get_response } assert_match %r{}i, body(res) - assert_externals_recorded_for("localhost", "GET") + assert_externals_recorded_for('localhost', 'GET') end # Although rare, some clients do explicitly set the "host" header on their @@ -136,7 +146,7 @@ def test_get_with_host_header end assert_match %r{}i, body(res) - assert_externals_recorded_for("test.local", "GET") + assert_externals_recorded_for('test.local', 'GET') end def test_get_with_host_header_lowercase @@ -149,7 +159,7 @@ def test_get_with_host_header_lowercase end assert_match %r{}i, body(res) - assert_externals_recorded_for("test.local", "GET") + assert_externals_recorded_for('test.local', 'GET') end # Only some HTTP clients support explicit connection reuse, so this test @@ -169,47 +179,47 @@ def test_get_with_reused_connection expected = {:call_count => n} - assert_externals_recorded_for("localhost", "GET", :counts => expected) + assert_externals_recorded_for('localhost', 'GET', :counts => expected) end end def test_background res = nil - perform_action_with_newrelic_trace(:name => "task", :category => :task) do + perform_action_with_newrelic_trace(:name => 'task', :category => :task) do res = get_response end assert_match %r{}i, body(res) - assert_externals_recorded_for("localhost", "GET") + assert_externals_recorded_for('localhost', 'GET') assert_metrics_recorded([ ["External/localhost/#{client_name}/GET", "OtherTransaction/Background/#{self.class.name}/task"], "OtherTransaction/Background/#{self.class.name}/task", - "OtherTransaction/Background/all", - "OtherTransaction/all" + 'OtherTransaction/Background/all', + 'OtherTransaction/all' ]) end def test_transactional_metrics res = nil - perform_action_with_newrelic_trace(:name => "task") do + perform_action_with_newrelic_trace(:name => 'task') do res = get_response end assert_match %r{}i, body(res) - assert_externals_recorded_for("localhost", "GET", :transaction_type => "Web") + assert_externals_recorded_for('localhost', 'GET', :transaction_type => 'Web') assert_metrics_recorded([ "Controller/#{self.class.name}/task" ]) assert_metrics_not_recorded([ - "External/allOther" + 'External/allOther' ]) end def test_transactional_traces_nodes - perform_action_with_newrelic_trace(:name => "task") do + perform_action_with_newrelic_trace(:name => 'task') do get_response end @@ -233,7 +243,7 @@ def test_ignore def test_head in_transaction { head_response } - assert_externals_recorded_for("localhost", "HEAD") + assert_externals_recorded_for('localhost', 'HEAD') end def test_post @@ -241,7 +251,7 @@ def test_post in_transaction { post_response } - assert_externals_recorded_for("localhost", "POST") + assert_externals_recorded_for('localhost', 'POST') end def test_put @@ -249,13 +259,13 @@ def test_put in_transaction { put_response } - assert_externals_recorded_for("localhost", "PUT") + assert_externals_recorded_for('localhost', 'PUT') end def test_delete in_transaction { delete_response } - assert_externals_recorded_for("localhost", "DELETE") + assert_externals_recorded_for('localhost', 'DELETE') end if defined?(::Addressable) @@ -266,7 +276,7 @@ def test_url_not_supported_by_stdlib_uri end assert_match %r{}i, body(res) - assert_externals_recorded_for("localhost", "GET") + assert_externals_recorded_for('localhost', 'GET') end end @@ -278,7 +288,7 @@ def test_adds_a_request_header_to_outgoing_requests_if_xp_enabled with_config(:"cross_application_tracer.enabled" => true, :'distributed_tracing.enabled' => false) do in_transaction { get_response } - assert_equal "VURQV1BZRkZdXUFT", server.requests.last["HTTP_X_NEWRELIC_ID"] + assert_equal 'VURQV1BZRkZdXUFT', server.requests.last['HTTP_X_NEWRELIC_ID'] end NewRelic::Agent::Agent.any_instance.unstub(:connected?) end @@ -288,7 +298,7 @@ def test_adds_a_request_header_to_outgoing_requests_if_old_xp_config_is_present with_config(:'cross_application_tracer.enabled' => true, :'distributed_tracing.enabled' => false) do in_transaction { get_response } - assert_equal "VURQV1BZRkZdXUFT", server.requests.last["HTTP_X_NEWRELIC_ID"] + assert_equal 'VURQV1BZRkZdXUFT', server.requests.last['HTTP_X_NEWRELIC_ID'] end NewRelic::Agent::Agent.any_instance.unstub(:connected?) end @@ -304,7 +314,7 @@ def test_adds_newrelic_transaction_header get_response end - transaction_data = server.requests.last["HTTP_X_NEWRELIC_TRANSACTION"] + transaction_data = server.requests.last['HTTP_X_NEWRELIC_TRANSACTION'] refute_empty(transaction_data) @@ -327,7 +337,7 @@ def test_agent_doesnt_add_a_request_header_to_outgoing_requests_if_xp_disabled def test_agent_doesnt_add_a_request_header_if_empty_cross_process_id with_config(:'cross_application_tracer.enabled' => true, :'distributed_tracing.enabled' => false, - :cross_process_id => "") do + :cross_process_id => '') do in_transaction { get_response } refute server.requests.last.keys.any? { |k| k.include?('NEWRELIC_ID') } @@ -338,7 +348,7 @@ def test_agent_doesnt_add_a_request_header_if_empty_encoding_key with_config( :'cross_application_tracer.enabled' => true, :'distributed_tracing.enabled' => false, - :encoding_key => "" + :encoding_key => '' ) do in_transaction { get_response } @@ -350,33 +360,33 @@ def test_instrumentation_with_crossapp_enabled_records_normal_metrics_if_no_head $fake_server.override_response_headers('X-NewRelic-App-Data' => '') with_config(:"cross_application_tracer.enabled" => true) do - in_transaction("test") do + in_transaction('test') do get_response end end - assert_externals_recorded_for("localhost", "GET") - assert_metrics_recorded([["External/localhost/#{client_name}/GET", "test"]]) + assert_externals_recorded_for('localhost', 'GET') + assert_metrics_recorded([["External/localhost/#{client_name}/GET", 'test']]) end def test_instrumentation_with_crossapp_disabled_records_normal_metrics_even_if_header_is_present $fake_server.override_response_headers('X-NewRelic-App-Data' => - make_app_data_payload("18#1884", "txn-name", 2, 8, 0, TRANSACTION_GUID)) + make_app_data_payload('18#1884', 'txn-name', 2, 8, 0, TRANSACTION_GUID)) - in_transaction("test") do + in_transaction('test') do get_response end - assert_externals_recorded_for("localhost", "GET") - assert_metrics_recorded([["External/localhost/#{client_name}/GET", "test"]]) + assert_externals_recorded_for('localhost', 'GET') + assert_metrics_recorded([["External/localhost/#{client_name}/GET", 'test']]) end def test_instrumentation_with_crossapp_enabled_records_crossapp_metrics_if_header_present $fake_server.override_response_headers('X-NewRelic-App-Data' => - make_app_data_payload("18#1884", "txn-name", 2, 8, 0, TRANSACTION_GUID)) + make_app_data_payload('18#1884', 'txn-name', 2, 8, 0, TRANSACTION_GUID)) with_config(:"cross_application_tracer.enabled" => true, :'distributed_tracing.enabled' => false) do - in_transaction("test") do + in_transaction('test') do get_response end end @@ -387,21 +397,21 @@ def test_instrumentation_with_crossapp_enabled_records_crossapp_metrics_if_heade assert_equal TRANSACTION_GUID, last_node.params[:transaction_guid] assert_metrics_recorded([ - "External/all", - "External/allOther", - "ExternalApp/localhost/18#1884/all", - "ExternalTransaction/localhost/18#1884/txn-name", - "External/localhost/all", - ["ExternalTransaction/localhost/18#1884/txn-name", "test"] + 'External/all', + 'External/allOther', + 'ExternalApp/localhost/18#1884/all', + 'ExternalTransaction/localhost/18#1884/txn-name', + 'External/localhost/all', + ['ExternalTransaction/localhost/18#1884/txn-name', 'test'] ]) end def test_crossapp_metrics_allow_valid_utf8_characters $fake_server.override_response_headers('X-NewRelic-App-Data' => - make_app_data_payload("12#1114", "世界線航跡蔵", 18.0, 88.1, 4096, TRANSACTION_GUID)) + make_app_data_payload('12#1114', '世界線航跡蔵', 18.0, 88.1, 4096, TRANSACTION_GUID)) with_config(:"cross_application_tracer.enabled" => true, :'distributed_tracing.enabled' => false) do - in_transaction("test") do + in_transaction('test') do get_response end end @@ -412,27 +422,27 @@ def test_crossapp_metrics_allow_valid_utf8_characters assert_equal TRANSACTION_GUID, last_node.params[:transaction_guid] assert_metrics_recorded([ - "External/all", - "External/allOther", - "ExternalApp/localhost/12#1114/all", - "External/localhost/all", - "ExternalTransaction/localhost/12#1114/世界線航跡蔵", - ["ExternalTransaction/localhost/12#1114/世界線航跡蔵", "test"] + 'External/all', + 'External/allOther', + 'ExternalApp/localhost/12#1114/all', + 'External/localhost/all', + 'ExternalTransaction/localhost/12#1114/世界線航跡蔵', + ['ExternalTransaction/localhost/12#1114/世界線航跡蔵', 'test'] ]) end def test_crossapp_metrics_ignores_crossapp_header_with_malformed_cross_process_id $fake_server.override_response_headers('X-NewRelic-App-Data' => - make_app_data_payload("88#88#88", "invalid", 1, 2, 4096, TRANSACTION_GUID)) + make_app_data_payload('88#88#88', 'invalid', 1, 2, 4096, TRANSACTION_GUID)) with_config(:"cross_application_tracer.enabled" => true) do - in_transaction("test") do + in_transaction('test') do get_response end end - assert_externals_recorded_for("localhost", "GET") - assert_metrics_recorded([["External/localhost/#{client_name}/GET", "test"]]) + assert_externals_recorded_for('localhost', 'GET') + assert_metrics_recorded([["External/localhost/#{client_name}/GET", 'test']]) end def test_doesnt_affect_the_request_if_an_exception_is_raised_while_setting_up_tracing @@ -470,7 +480,7 @@ def test_doesnt_misbehave_when_transaction_tracing_is_disabled end refute_match(/undefined method `.*" for nil:NilClass/i, - logger.messages.flatten.map { |log| log.to_s }.join(" ")) + logger.messages.flatten.map { |log| log.to_s }.join(' ')) end def test_includes_full_url_in_transaction_trace @@ -488,19 +498,19 @@ def test_includes_full_url_in_transaction_trace # https://newrelic.atlassian.net/browse/RUBY-1244 def test_failure_in_our_start_code_still_records_externals # Fake a failure in our start-up code... - ::JSON.stubs(:dump).raises("Boom!") + ::JSON.stubs(:dump).raises('Boom!') with_config(:"cross_application_tracer.enabled" => true) do in_transaction { get_response } end - assert_externals_recorded_for("localhost", "GET") + assert_externals_recorded_for('localhost', 'GET') end # https://newrelic.atlassian.net/browse/RUBY-1244 def test_failure_to_add_tt_node_doesnt_append_params_to_wrong_node # Fake a failure in our start-up code... - ::JSON.stubs(:dump).raises("Boom!") + ::JSON.stubs(:dump).raises('Boom!') in_transaction do with_config(:"cross_application_tracer.enabled" => true) do @@ -509,7 +519,7 @@ def test_failure_to_add_tt_node_doesnt_append_params_to_wrong_node end last_node = find_last_transaction_node() - unless last_node.metric_name.start_with?("External") + unless last_node.metric_name.start_with?('External') refute last_node.params.key?(:uri) end end @@ -522,7 +532,7 @@ def test_still_records_tt_node_when_request_fails # fixing it for old versions of Typhoeus would require large changes to # the instrumentation, makes us say 'meh'. is_typhoeus = (client_name == 'Typhoeus') - if !is_typhoeus || (is_typhoeus && Typhoeus::VERSION >= "0.5.4") + if !is_typhoeus || (is_typhoeus && Typhoeus::VERSION >= '0.5.4') evil_server = NewRelic::EvilServer.new evil_server.start @@ -547,11 +557,11 @@ def test_still_records_tt_node_when_request_fails def test_raw_synthetics_header_is_passed_along_if_present with_config(:"cross_application_tracer.enabled" => true) do in_transaction do - NewRelic::Agent::Tracer.current_transaction.raw_synthetics_header = "boo" + NewRelic::Agent::Tracer.current_transaction.raw_synthetics_header = 'boo' get_response - assert_equal "boo", server.requests.last["HTTP_X_NEWRELIC_SYNTHETICS"] + assert_equal 'boo', server.requests.last['HTTP_X_NEWRELIC_SYNTHETICS'] end end end @@ -561,7 +571,7 @@ def test_no_raw_synthetics_header_if_not_present in_transaction do get_response - refute_includes server.requests.last.keys, "HTTP_X_NEWRELIC_SYNTHETICS" + refute_includes server.requests.last.keys, 'HTTP_X_NEWRELIC_SYNTHETICS' end end end @@ -569,16 +579,16 @@ def test_no_raw_synthetics_header_if_not_present def test_raw_synthetics_header_is_passed_along_when_cat_disabled with_config(:"cross_application_tracer.enabled" => false) do in_transaction do - NewRelic::Agent::Tracer.current_transaction.raw_synthetics_header = "boo" + NewRelic::Agent::Tracer.current_transaction.raw_synthetics_header = 'boo' get_response - assert_equal "boo", server.requests.last["HTTP_X_NEWRELIC_SYNTHETICS"] + assert_equal 'boo', server.requests.last['HTTP_X_NEWRELIC_SYNTHETICS'] end end end - load_cross_agent_test("cat_map").each do |test_case| + load_cross_agent_test('cat_map').each do |test_case| # Test cases that don't involve outgoing calls are done elsewhere if test_case['outboundRequests'] define_method("test_#{test_case['name']}") do @@ -601,7 +611,7 @@ def test_raw_synthetics_header_is_passed_along_when_cat_disabled set_explicit_transaction_name(req['outboundTxnName']) get_response - outbound_payload = server.requests.last["HTTP_X_NEWRELIC_TRANSACTION"] + outbound_payload = server.requests.last['HTTP_X_NEWRELIC_TRANSACTION'] decoded_outbound_payload = decode_payload(outbound_payload) assert_equal(req['expectedOutboundPayload'], decoded_outbound_payload) @@ -669,7 +679,7 @@ def test_raw_synthetics_header_is_passed_along_when_cat_disabled end def http_header_name_to_rack_key(name) - "HTTP_" + name.upcase.tr('-', '_') + 'HTTP_' + name.upcase.tr('-', '_') end def make_app_data_payload(*args) @@ -683,25 +693,25 @@ def decode_payload(payload) end def set_explicit_transaction_name(name) - parts = name.split("/") + parts = name.split('/') category = parts.shift NewRelic::Agent.set_transaction_name(parts.join('/'), :category => category) end def assert_externals_recorded_for(host, meth, opts = {}) - txn_type = opts.fetch(:transaction_type, "Other") + txn_type = opts.fetch(:transaction_type, 'Other') counts = opts.fetch(:counts, nil) if counts.nil? assert_metrics_recorded([ - "External/all", + 'External/all', "External/all#{txn_type}", "External/#{host}/#{client_name}/#{meth}", "External/#{host}/all" ]) else assert_metrics_recorded( - "External/all" => counts, + 'External/all' => counts, "External/all#{txn_type}" => counts, "External/#{host}/#{client_name}/#{meth}" => counts, "External/#{host}/all" => counts diff --git a/test/new_relic/language_support_test.rb b/test/new_relic/language_support_test.rb index 075c4fc059..29b0def05f 100644 --- a/test/new_relic/language_support_test.rb +++ b/test/new_relic/language_support_test.rb @@ -91,20 +91,20 @@ class ContainedObject end def test_should_look_within_module - assert_equal ::Outer::Included, NewRelic::LanguageSupport.constantize("Outer::Included") + assert_equal ::Outer::Included, NewRelic::LanguageSupport.constantize('Outer::Included') end def test_shouldnt_look_outside_module_for_class - assert_nil NewRelic::LanguageSupport.constantize("Outer::Excluded") + assert_nil NewRelic::LanguageSupport.constantize('Outer::Excluded') end def test_shouldnt_look_outside_module_for_module - assert_nil NewRelic::LanguageSupport.constantize("Outer::Outer") + assert_nil NewRelic::LanguageSupport.constantize('Outer::Outer') end def test_should_allow_object_in_module_names assert_equal ::ContainsAnObject::ContainedObject, - NewRelic::LanguageSupport.constantize("ContainsAnObject::ContainedObject") + NewRelic::LanguageSupport.constantize('ContainsAnObject::ContainedObject') end def test_should_camelize_names_with_hyphens diff --git a/test/new_relic/local_environment_test.rb b/test/new_relic/local_environment_test.rb index e8f1236e39..094d36a09b 100644 --- a/test/new_relic/local_environment_test.rb +++ b/test/new_relic/local_environment_test.rb @@ -26,9 +26,9 @@ def test_passenger end def test_not_resque - combinations = [["notrake", "resque:work", {"QUEUE" => "*"}], - ["rake", "notresque:work", {"QUEUE" => "*"}], - ["rake", "resque:work", {"BBQ" => "*"}]] + combinations = [['notrake', 'resque:work', {'QUEUE' => '*'}], + ['rake', 'notresque:work', {'QUEUE' => '*'}], + ['rake', 'resque:work', {'BBQ' => '*'}]] combinations.each do |settings| with_resque(*settings) do @@ -38,8 +38,8 @@ def test_not_resque end def test_resque - combinations = [["rake", "resque:work", {"QUEUE" => "*"}], - ["rake", "resque:work", {"QUEUES" => "*"}]] + combinations = [['rake', 'resque:work', {'QUEUE' => '*'}], + ['rake', 'resque:work', {'QUEUES' => '*'}]] combinations.each do |settings| with_resque(*settings) do @@ -49,8 +49,8 @@ def test_resque end def test_not_resque_pool - combinations = [["notresque-pool", nil], - ["rake", "notresque:pool"]] + combinations = [['notresque-pool', nil], + ['rake', 'notresque:pool']] combinations.each do |settings| with_resque_pool(*settings) do @@ -60,8 +60,8 @@ def test_not_resque_pool end def test_resque_pool - combinations = [["resque-pool", nil], - ["rake", "resque:pool"]] + combinations = [['resque-pool', nil], + ['rake', 'resque:pool']] combinations.each do |settings| with_resque_pool(*settings) do diff --git a/test/new_relic/marshalling_test_cases.rb b/test/new_relic/marshalling_test_cases.rb index 3c5f62b151..c9b23ee44c 100644 --- a/test/new_relic/marshalling_test_cases.rb +++ b/test/new_relic/marshalling_test_cases.rb @@ -20,7 +20,7 @@ def test_sends_metrics def test_sends_errors with_around_hook do - NewRelic::Agent.notice_error(StandardError.new("Boom")) + NewRelic::Agent.notice_error(StandardError.new('Boom')) end transmit_data @@ -29,7 +29,7 @@ def test_sends_errors assert_equal 1, result.length assert_equal 1, result.first.errors.length - assert_equal "StandardError", result.first.errors.first.exception_class_name + assert_equal 'StandardError', result.first.errors.first.exception_class_name end def test_sends_transaction_traces @@ -44,7 +44,7 @@ def test_sends_transaction_traces result = $collector.calls_for('transaction_sample_data') assert_equal 1, result.length - assert_equal "TestTransaction/do_it", result.first.metric_name + assert_equal 'TestTransaction/do_it', result.first.metric_name end def test_sends_transaction_events @@ -66,18 +66,18 @@ def test_sends_transaction_events event = events.first # this is only present on REE, and we don't really care - the point of this # test is just to validate basic marshalling - event[0].delete("gcCumulative") + event[0].delete('gcCumulative') # this value will be randomly assigned and not useful to compare - event[0].delete("priority") - - assert_equal "Transaction", event[0]["type"] - assert_equal t0, event[0]["timestamp"] - assert_equal "TestTransaction/do_it", event[0]["name"] - assert_in_delta(0.0, event[0]["duration"]) - refute event[0]["error"] - assert_equal "Unknown", event[0]["parent.transportType"] + event[0].delete('priority') + + assert_equal 'Transaction', event[0]['type'] + assert_equal t0, event[0]['timestamp'] + assert_equal 'TestTransaction/do_it', event[0]['name'] + assert_in_delta(0.0, event[0]['duration']) + refute event[0]['error'] + assert_equal 'Unknown', event[0]['parent.transportType'] refute_nil event[0]['guid'] - refute_nil event[0]["traceId"] + refute_nil event[0]['traceId'] assert_equal 9, event[0].size end @@ -86,7 +86,7 @@ def test_sends_custom_events t0 = nr_freeze_process_time with_around_hook do - NewRelic::Agent.record_custom_event("CustomEventType", :foo => 'bar', :baz => 'qux') + NewRelic::Agent.record_custom_event('CustomEventType', :foo => 'bar', :baz => 'qux') end transmit_event_data @@ -100,17 +100,17 @@ def test_sends_custom_events expected_event = [ { - "type" => "CustomEventType", - "timestamp" => t0.to_i + 'type' => 'CustomEventType', + 'timestamp' => t0.to_i }, { - "foo" => "bar", - "baz" => "qux" + 'foo' => 'bar', + 'baz' => 'qux' } ] # we don't care about the specific priority for this test - events.first[0].delete("priority") + events.first[0].delete('priority') assert_equal(expected_event, events.first) end @@ -136,22 +136,22 @@ def test_sends_error_events # this is only present on REE, and we don't really care - the point of this # test is just to validate basic marshalling - event[0].delete("gcCumulative") + event[0].delete('gcCumulative') # we don't care about the specific priority for this test - event[0].delete("priority") - - assert_equal "TransactionError", event[0]["type"] - assert_equal "StandardError", event[0]["error.class"] - assert_equal "Sorry!", event[0]["error.message"] - refute event[0]["error.expected"] - assert_equal t0.to_f, event[0]["timestamp"] - assert_equal "TestTransaction/break_it", event[0]["transactionName"] - assert_in_delta(0.0, event[0]["duration"]) - assert_equal "Unknown", event[0]["parent.transportType"] - refute_nil event[0]["spanId"] + event[0].delete('priority') + + assert_equal 'TransactionError', event[0]['type'] + assert_equal 'StandardError', event[0]['error.class'] + assert_equal 'Sorry!', event[0]['error.message'] + refute event[0]['error.expected'] + assert_equal t0.to_f, event[0]['timestamp'] + assert_equal 'TestTransaction/break_it', event[0]['transactionName'] + assert_in_delta(0.0, event[0]['duration']) + assert_equal 'Unknown', event[0]['parent.transportType'] + refute_nil event[0]['spanId'] refute_nil event[0]['guid'] - refute_nil event[0]["traceId"] + refute_nil event[0]['traceId'] assert_equal 12, event[0].size @@ -164,8 +164,8 @@ def test_sends_error_events def test_sends_log_events # Standard with other agents on millis, not seconds t0 = nr_freeze_process_time.to_f * 1000 - message = "A deadly message" - severity = "FATAL" + message = 'A deadly message' + severity = 'FATAL' with_config(:'application_logging.forwarding.enabled' => true) do with_around_hook do @@ -179,35 +179,35 @@ def test_sends_log_events assert_equal 1, result.length - common = result.first.common["attributes"] + common = result.first.common['attributes'] - refute_nil common["hostname"] + refute_nil common['hostname'] # Excluding this explicitly vs classic logs-in-context to save space - assert_nil common["entity.type"] + assert_nil common['entity.type'] logs = result.first.logs refute_empty logs - log = logs.find { |l| l["message"] == message && l["level"] == severity } + log = logs.find { |l| l['message'] == message && l['level'] == severity } refute_nil log - assert_equal t0, log["timestamp"] + assert_equal t0, log['timestamp'] end class Transactioner include NewRelic::Agent::Instrumentation::ControllerInstrumentation def do_it - NewRelic::Agent.set_transaction_name("do_it", :category => "TestTransaction") + NewRelic::Agent.set_transaction_name('do_it', :category => 'TestTransaction') end add_transaction_tracer :do_it def break_it - NewRelic::Agent.set_transaction_name("break_it", :category => "TestTransaction") - NewRelic::Agent.notice_error(StandardError.new("Sorry!")) + NewRelic::Agent.set_transaction_name('break_it', :category => 'TestTransaction') + NewRelic::Agent.notice_error(StandardError.new('Sorry!')) NewRelic::Agent::Tracer.current_span_id end diff --git a/test/new_relic/metric_data_test.rb b/test/new_relic/metric_data_test.rb index 1a361d2fd5..707f5b53ce 100644 --- a/test/new_relic/metric_data_test.rb +++ b/test/new_relic/metric_data_test.rb @@ -66,7 +66,7 @@ def test_metric_spec_equal_should_not_set_original_spec_with_no_metric_spec new_spec = mock('new metric_spec') - assert_equal(new_spec, md1.metric_spec = (new_spec), "should return the new spec") + assert_equal(new_spec, md1.metric_spec = (new_spec), 'should return the new spec') new_original_spec = md1.instance_variable_get(:@original_spec) @@ -83,7 +83,7 @@ def test_metric_spec_equal_should_set_original_spec_with_existing_metric_spec new_spec = mock('new metric_spec') - assert_equal(new_spec, md1.metric_spec = (new_spec), "should return the new spec") + assert_equal(new_spec, md1.metric_spec = (new_spec), 'should return the new spec') new_original_spec = md1.instance_variable_get(:@original_spec) @@ -104,17 +104,17 @@ def test_to_json md = NewRelic::MetricData.new(NewRelic::MetricSpec.new('Custom/test/method', ''), NewRelic::Agent::Stats.new) json = md.to_json - assert_includes(json, '"Custom/test/method"', "should include the metric spec in the json") + assert_includes(json, '"Custom/test/method"', 'should include the metric spec in the json') end else - puts "Skipping tests in #{File.basename(__FILE__)} because Hash#to_json not available" if ENV["VERBOSE_TEST_OUTPUT"] + puts "Skipping tests in #{File.basename(__FILE__)} because Hash#to_json not available" if ENV['VERBOSE_TEST_OUTPUT'] end def test_to_s_with_metric_spec md = NewRelic::MetricData.new(NewRelic::MetricSpec.new('Custom/test/method', ''), NewRelic::Agent::Stats.new) - assert_equal('Custom/test/method(): [ 0 calls 0.0000s / 0.0000s ex]', md.to_s, "should include the metric spec") + assert_equal('Custom/test/method(): [ 0 calls 0.0000s / 0.0000s ex]', md.to_s, 'should include the metric spec') end def test_to_collector_array_with_spec @@ -140,7 +140,7 @@ def test_to_collector_array_with_rationals spec = NewRelic::MetricSpec.new('foo') md = NewRelic::MetricData.new(spec, stats) - expected = [{"name" => "foo", "scope" => ""}, [1, 2.0, 3.0, 4.0, 5.0, 6.0]] + expected = [{'name' => 'foo', 'scope' => ''}, [1, 2.0, 3.0, 4.0, 5.0, 6.0]] assert_equal expected, md.to_collector_array end @@ -148,15 +148,15 @@ def test_to_collector_array_with_rationals def test_to_collector_array_with_bad_values stats = NewRelic::Agent::Stats.new stats.call_count = nil - stats.total_call_time = "junk" + stats.total_call_time = 'junk' stats.total_exclusive_time = Object.new stats.min_call_time = [] stats.max_call_time = {} - stats.sum_of_squares = Exception.new("Boo") + stats.sum_of_squares = Exception.new('Boo') spec = NewRelic::MetricSpec.new('foo') md = NewRelic::MetricData.new(spec, stats) - expected = [{"name" => "foo", "scope" => ""}, [0, 0, 0, 0, 0, 0]] + expected = [{'name' => 'foo', 'scope' => ''}, [0, 0, 0, 0, 0, 0]] assert_equal expected, md.to_collector_array end diff --git a/test/new_relic/metric_spec_test.rb b/test/new_relic/metric_spec_test.rb index 75caf872f7..9cddfbbd0b 100644 --- a/test/new_relic/metric_spec_test.rb +++ b/test/new_relic/metric_spec_test.rb @@ -50,7 +50,7 @@ def test_equal # test to make sure the MetricSpec class can serialize to json if defined?(::ActiveSupport) def test_json - spec = NewRelic::MetricSpec.new("controller", "metric#find") + spec = NewRelic::MetricSpec.new('controller', 'metric#find') import = ::ActiveSupport::JSON.decode(spec.to_json) @@ -69,16 +69,16 @@ def test_json compare_metric_data(metric_data, import) end else - puts "Skipping `test_json` in #{File.basename(__FILE__)} because ActiveSupport is unavailable" if ENV["VERBOSE_TEST_OUTPUT"] + puts "Skipping `test_json` in #{File.basename(__FILE__)} because ActiveSupport is unavailable" if ENV['VERBOSE_TEST_OUTPUT'] end def test_initialize_truncates_name_and_scope - long_name = "a" * 300 - long_scope = "b" * 300 + long_name = 'a' * 300 + long_scope = 'b' * 300 spec = NewRelic::MetricSpec.new(long_name, long_scope) - assert_equal("a" * 255, spec.name, "should have shortened the name") - assert_equal("b" * 255, spec.scope, "should have shortened the scope") + assert_equal('a' * 255, spec.name, 'should have shortened the name') + assert_equal('b' * 255, spec.scope, 'should have shortened the scope') end # These next three tests are here only because rpm_site uses our MetricSpec @@ -94,7 +94,7 @@ def test_initialize_can_take_a_nil_name end def test_initialize_can_take_a_non_string_name - name = string_wrapper_class.new("name") + name = string_wrapper_class.new('name') spec = NewRelic::MetricSpec.new(name) @@ -103,8 +103,8 @@ def test_initialize_can_take_a_non_string_name end def test_initialize_can_take_a_non_string_scope - name = "name" - scope = string_wrapper_class.new("scope") + name = 'name' + scope = string_wrapper_class.new('scope') spec = NewRelic::MetricSpec.new(name, scope) diff --git a/test/new_relic/multiverse_helpers.rb b/test/new_relic/multiverse_helpers.rb index f8be9c578f..922641c395 100644 --- a/test/new_relic/multiverse_helpers.rb +++ b/test/new_relic/multiverse_helpers.rb @@ -14,7 +14,7 @@ def after_teardown end def current_active_record_migration_version - ActiveRecord::VERSION::STRING >= "5.0.0" ? ActiveRecord::Migration["#{ActiveRecord::VERSION::STRING[0]}.0"] : ActiveRecord::Migration + ActiveRecord::VERSION::STRING >= '5.0.0' ? ActiveRecord::Migration["#{ActiveRecord::VERSION::STRING[0]}.0"] : ActiveRecord::Migration end module MultiverseHelpers @@ -132,7 +132,7 @@ def initialize(instrumentation_method) def value unless @emitted - puts "*" * 40, "INSTRUMENTING #{@value}", "*" * 40 + puts '*' * 40, "INSTRUMENTING #{@value}", '*' * 40 @emitted = true end @value @@ -148,7 +148,7 @@ def to_s end def instrumentation_method - ENV["MULTIVERSE_INSTRUMENTATION_METHOD"] ||= "chain" + ENV['MULTIVERSE_INSTRUMENTATION_METHOD'] ||= 'chain' end def ensure_instrumentation_method @@ -176,7 +176,7 @@ def start_fake_collector end def omit_collector? - ENV["NEWRELIC_OMIT_FAKE_COLLECTOR"] == "true" + ENV['NEWRELIC_OMIT_FAKE_COLLECTOR'] == 'true' end def stub_for_span_collection @@ -193,35 +193,35 @@ def run_harvest end def single_transaction_trace_posted - posts = $collector.calls_for("transaction_sample_data") + posts = $collector.calls_for('transaction_sample_data') - assert_equal 1, posts.length, "Unexpected post count" + assert_equal 1, posts.length, 'Unexpected post count' transactions = posts.first.samples - assert_equal 1, transactions.length, "Unexpected trace count" + assert_equal 1, transactions.length, 'Unexpected trace count' transactions.first end def single_error_posted - assert_equal 1, $collector.calls_for("error_data").length - assert_equal 1, $collector.calls_for("error_data").first.errors.length + assert_equal 1, $collector.calls_for('error_data').length + assert_equal 1, $collector.calls_for('error_data').first.errors.length - $collector.calls_for("error_data").first.errors.first + $collector.calls_for('error_data').first.errors.first end def single_event_posted - assert_equal 1, $collector.calls_for("analytic_event_data").length - assert_equal 1, $collector.calls_for("analytic_event_data").first.events.length + assert_equal 1, $collector.calls_for('analytic_event_data').length + assert_equal 1, $collector.calls_for('analytic_event_data').first.events.length - $collector.calls_for("analytic_event_data").first.events.first + $collector.calls_for('analytic_event_data').first.events.first end def single_metrics_post - assert_equal 1, $collector.calls_for("metric_data").length + assert_equal 1, $collector.calls_for('metric_data').length - $collector.calls_for("metric_data").first + $collector.calls_for('metric_data').first end def single_connect_posted @@ -236,7 +236,7 @@ def capture_js_data @instrumentor = NewRelic::Agent::JavaScriptInstrumentor.new(events) @js_data = @instrumentor.data_for_js_agent(transaction) - raw_attributes = @js_data["atts"] + raw_attributes = @js_data['atts'] if raw_attributes attributes = ::JSON.load(@instrumentor.obfuscator.deobfuscate(raw_attributes)) @@ -256,7 +256,7 @@ def assert_event_has_agent_attribute(attribute, expected) end def assert_error_has_agent_attribute(attribute, expected) - assert_equal expected, single_error_posted.params["agentAttributes"][attribute] + assert_equal expected, single_error_posted.params['agentAttributes'][attribute] end def assert_transaction_tracer_has_custom_attributes(attribute, expected) @@ -270,7 +270,7 @@ def assert_transaction_event_has_custom_attributes(attribute, expected) end def assert_error_collector_has_custom_attributes(attribute, expected) - assert_equal expected, single_error_posted.params["userAttributes"][attribute] + assert_equal expected, single_error_posted.params['userAttributes'][attribute] end def assert_browser_monitoring_has_custom_attributes(attribute, expected) @@ -290,7 +290,7 @@ def refute_transaction_event_has_custom_attributes(attribute) end def refute_error_collector_has_custom_attributes(attribute) - refute_includes single_error_posted.params["userAttributes"], attribute + refute_includes single_error_posted.params['userAttributes'], attribute end def refute_browser_monitoring_has_custom_attributes(_) @@ -306,11 +306,11 @@ def refute_event_has_agent_attribute(attribute) end def refute_error_has_agent_attribute(attribute) - refute_includes single_error_posted.params["agentAttributes"], attribute + refute_includes single_error_posted.params['agentAttributes'], attribute end def refute_browser_monitoring_has_any_attributes - refute_includes @js_data, "atts" + refute_includes @js_data, 'atts' end def refute_browser_monitoring_has_agent_attribute(_) @@ -331,11 +331,11 @@ def attributes_for_single_error_posted(key) end def user_attributes_for_single_error_posted - attributes_for_single_error_posted("userAttributes") + attributes_for_single_error_posted('userAttributes') end def agent_attributes_for_single_error_posted - attributes_for_single_error_posted("agentAttributes") + attributes_for_single_error_posted('agentAttributes') end def agent_attributes_for_single_event_posted @@ -344,8 +344,8 @@ def agent_attributes_for_single_event_posted end def agent_attributes_for_single_event_posted_without_ignored_attributes - ignored_keys = ["http.statusCode", "request.headers.referer", - "request.parameters.controller", "request.parameters.action", "http.statusCode"] + ignored_keys = ['http.statusCode', 'request.headers.referer', + 'request.parameters.controller', 'request.parameters.action', 'http.statusCode'] attrs = agent_attributes_for_single_event_posted ignored_keys.each { |k| attrs.delete(k) } attrs diff --git a/test/new_relic/net_http_test_cases.rb b/test/new_relic/net_http_test_cases.rb index 79921a9f82..0f98bb5371 100644 --- a/test/new_relic/net_http_test_cases.rb +++ b/test/new_relic/net_http_test_cases.rb @@ -2,9 +2,9 @@ # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. # frozen_string_literal: true -require "net/http" -require "newrelic_rpm" -require "http_client_test_cases" +require 'net/http' +require 'newrelic_rpm' +require 'http_client_test_cases' module NetHttpTestCases include HttpClientTestCases @@ -14,7 +14,7 @@ module NetHttpTestCases # def client_name - "Net::HTTP" + 'Net::HTTP' end def timeout_error_class @@ -57,11 +57,11 @@ def head_response end def post_response - start(default_uri) { |http| http.post(default_uri.path, "") } + start(default_uri) { |http| http.post(default_uri.path, '') } end def put_response - start(default_uri) { |http| http.put(default_uri.path, "") } + start(default_uri) { |http| http.put(default_uri.path, '') } end def delete_response diff --git a/test/new_relic/noticed_error_test.rb b/test/new_relic/noticed_error_test.rb index 032f363cc5..463b3bf595 100644 --- a/test/new_relic/noticed_error_test.rb +++ b/test/new_relic/noticed_error_test.rb @@ -25,7 +25,7 @@ def test_to_collector_array error = create_error(e) error.attributes.add_agent_attribute(:'request.uri', - "http://com.google", + 'http://com.google', NewRelic::Agent::AttributeFilter::DST_ERROR_COLLECTOR) error.attributes_from_notice_error = @attributes_from_notice_error @@ -47,7 +47,7 @@ def test_to_collector_array def test_to_collector_array_merges_custom_attributes_and_params e = TestError.new('test exception') - @attributes.merge_custom_attributes(:custom => "attribute") + @attributes.merge_custom_attributes(:custom => 'attribute') error = create_error(e) error.attributes_from_notice_error = @attributes_from_notice_error @@ -68,32 +68,32 @@ def test_to_collector_array_merges_custom_attributes_and_params def test_to_collector_array_includes_agent_attributes e = TestError.new('test exception') - @attributes.add_agent_attribute(:agent, "attribute", NewRelic::Agent::AttributeFilter::DST_ALL) + @attributes.add_agent_attribute(:agent, 'attribute', NewRelic::Agent::AttributeFilter::DST_ALL) error = create_error(e) actual = extract_attributes(error) - assert_equal({:agent => "attribute"}, actual["agentAttributes"]) + assert_equal({:agent => 'attribute'}, actual['agentAttributes']) end def test_to_collector_array_includes_intrinsic_attributes e = TestError.new('test exception') - @attributes.add_intrinsic_attribute(:intrinsic, "attribute") + @attributes.add_intrinsic_attribute(:intrinsic, 'attribute') error = create_error(e) actual = extract_attributes(error) - assert_equal({:intrinsic => "attribute"}, actual["intrinsics"]) + assert_equal({:intrinsic => 'attribute'}, actual['intrinsics']) end def test_to_collector_array_happy_without_attribute_collections - error = NewRelic::NoticedError.new(@path, "BOOM") + error = NewRelic::NoticedError.new(@path, 'BOOM') expected = [ (@time.to_f * 1000).round, @path, - "BOOM", - "Error", + 'BOOM', + 'Error', { 'userAttributes' => {}, 'agentAttributes' => {}, @@ -110,8 +110,8 @@ def test_to_collector_array_with_bad_values expected = [ 10_000.0, @path, - "", - "Error", + '', + 'Error', { :'error.expected' => false, 'userAttributes' => {}, @@ -142,7 +142,7 @@ def test_strips_message_from_exceptions_in_high_security_mode def test_long_message # yes, times 500. it's a 5000 byte string. Assuming strings are # still 1 byte / char. - err = create_error(StandardError.new("1234567890" * 500)) + err = create_error(StandardError.new('1234567890' * 500)) assert_equal 4096, err.message.length assert_equal ('1234567890' * 500)[0..4095], err.message @@ -208,24 +208,24 @@ def test_uses_original_exception_class_name def test_intrinsics_always_get_sent with_config(:'error_collector.attributes.enabled' => false) do attributes = NewRelic::Agent::Attributes.new(NewRelic::Agent.instance.attribute_filter) - attributes.add_intrinsic_attribute(:intrinsic, "attribute") + attributes.add_intrinsic_attribute(:intrinsic, 'attribute') - error = NewRelic::NoticedError.new(@path, Exception.new("O_o")) + error = NewRelic::NoticedError.new(@path, Exception.new('O_o')) error.attributes = attributes serialized_attributes = extract_attributes(error) - assert_equal({:intrinsic => "attribute"}, serialized_attributes["intrinsics"]) + assert_equal({:intrinsic => 'attribute'}, serialized_attributes['intrinsics']) end end def test_custom_attributes_sent_when_enabled with_config(:'error_collector.attributes.enabled' => true) do attributes = NewRelic::Agent::Attributes.new(NewRelic::Agent.instance.attribute_filter) - custom_attrs = {"name" => "Ron Burgundy", "channel" => 4} + custom_attrs = {'name' => 'Ron Burgundy', 'channel' => 4} attributes.merge_custom_attributes(custom_attrs) - error = NewRelic::NoticedError.new(@path, Exception.new("O_o")) + error = NewRelic::NoticedError.new(@path, Exception.new('O_o')) error.attributes = attributes assert_equal custom_attrs, error.custom_attributes @@ -235,10 +235,10 @@ def test_custom_attributes_sent_when_enabled def test_custom_attributes_not_sent_when_disabled with_config(:'error_collector.attributes.enabled' => false) do attributes = NewRelic::Agent::Attributes.new(NewRelic::Agent.instance.attribute_filter) - custom_attrs = {"name" => "Ron Burgundy", "channel" => 4} + custom_attrs = {'name' => 'Ron Burgundy', 'channel' => 4} attributes.merge_custom_attributes(custom_attrs) - error = NewRelic::NoticedError.new(@path, Exception.new("O_o")) + error = NewRelic::NoticedError.new(@path, Exception.new('O_o')) error.attributes = attributes assert_empty(error.custom_attributes) @@ -248,12 +248,12 @@ def test_custom_attributes_not_sent_when_disabled def test_agent_attributes_sent_when_enabled with_config(:'error_collector.attributes.enabled' => true) do attributes = NewRelic::Agent::Attributes.new(NewRelic::Agent.instance.attribute_filter) - attributes.add_agent_attribute(:"request.headers.referer", "http://blog.site/home", NewRelic::Agent::AttributeFilter::DST_ALL) + attributes.add_agent_attribute(:"request.headers.referer", 'http://blog.site/home', NewRelic::Agent::AttributeFilter::DST_ALL) - error = NewRelic::NoticedError.new(@path, Exception.new("O_o")) + error = NewRelic::NoticedError.new(@path, Exception.new('O_o')) error.attributes = attributes - expected = {:"request.headers.referer" => "http://blog.site/home"} + expected = {:"request.headers.referer" => 'http://blog.site/home'} assert_equal expected, error.agent_attributes end @@ -262,15 +262,71 @@ def test_agent_attributes_sent_when_enabled def test_agent_attributes_not_sent_when_disabled with_config(:'error_collector.attributes.enabled' => false) do attributes = NewRelic::Agent::Attributes.new(NewRelic::Agent.instance.attribute_filter) - attributes.add_agent_attribute(:"request.headers.referer", "http://blog.site/home", NewRelic::Agent::AttributeFilter::DST_ALL) + attributes.add_agent_attribute(:"request.headers.referer", 'http://blog.site/home', NewRelic::Agent::AttributeFilter::DST_ALL) - error = NewRelic::NoticedError.new(@path, Exception.new("O_o")) + error = NewRelic::NoticedError.new(@path, Exception.new('O_o')) error.attributes = attributes assert_empty(error.agent_attributes) end end + def test_error_group_can_be_read + error_group = 'lucky tiger' + error = NewRelic::NoticedError.new(@path, StandardError.new) + error.instance_variable_set(:@error_group, error_group) + + assert_equal error_group, error.error_group + end + + def test_error_group_can_be_set + error_group = 'lucky tiger' + error = NewRelic::NoticedError.new(@path, StandardError.new) + error.error_group = error_group + + assert_equal error_group, error.error_group + end + + def test_error_group_setting_ignores_empty_strings + error = NewRelic::NoticedError.new(@path, StandardError.new) + + assert_nil error.error_group + + error.error_group = '' + + assert_nil error.error_group + end + + def test_error_group_setting_ignores_nil + error = NewRelic::NoticedError.new(@path, StandardError.new) + error_group = 'lucky tiger' + error.instance_variable_set(:@error_group, error_group) + error.error_group = nil + + assert_equal error_group, error.error_group + end + + def test_error_group_name_agent_attribute_is_set + error_group = 'spicy lavender' + error = NewRelic::NoticedError.new(@path, StandardError.new) + error.error_group = error_group + agent_attributes = error.agent_attributes + + assert_equal error_group, agent_attributes[:'error.group.name'] + end + + def test_noticed_errors_group_is_not_frozen + error_group = 'mint tea' + exception = RuntimeError.new + noticed_error = ::NewRelic::NoticedError.new('www.mint_tea.com', exception) + noticed_error.instance_variable_set(:@processed_attributes, {noticed_error.class::AGENT_ATTRIBUTES => {}}) + noticed_error.send(:error_group=, error_group) + + assert_equal error_group, noticed_error.agent_attributes[::NewRelic::NoticedError::AGENT_ATTRIBUTE_ERROR_GROUP] + end + + private + def create_error(exception = StandardError.new) noticed_error = NewRelic::NoticedError.new(@path, exception, @time) noticed_error.attributes = @attributes diff --git a/test/new_relic/rack/agent_hooks_test.rb b/test/new_relic/rack/agent_hooks_test.rb index 313e6690c8..9fe83b34a0 100644 --- a/test/new_relic/rack/agent_hooks_test.rb +++ b/test/new_relic/rack/agent_hooks_test.rb @@ -9,7 +9,7 @@ class AgentHooksTest < Minitest::Test def setup @app = stub_everything @hooks = NewRelic::Rack::AgentHooks.new(@app) - @env = {:env => "env"} + @env = {:env => 'env'} end def test_before_call diff --git a/test/new_relic/rack/browser_monitoring_test.rb b/test/new_relic/rack/browser_monitoring_test.rb index f076068667..1555f5aa1c 100644 --- a/test/new_relic/rack/browser_monitoring_test.rb +++ b/test/new_relic/rack/browser_monitoring_test.rb @@ -88,9 +88,9 @@ def test_make_sure_header_is_set end def test_should_only_instrument_successful_html_requests - assert app.should_instrument?({}, 200, {'Content-Type' => 'text/html'}), "Expected to instrument 200 requests." - refute app.should_instrument?({}, 500, {'Content-Type' => 'text/html'}), "Expected not to instrument 500 requests." - refute app.should_instrument?({}, 200, {'Content-Type' => 'text/xhtml'}), "Expected not to instrument requests with content type other than text/html." + assert app.should_instrument?({}, 200, {'Content-Type' => 'text/html'}), 'Expected to instrument 200 requests.' + refute app.should_instrument?({}, 500, {'Content-Type' => 'text/html'}), 'Expected not to instrument 500 requests.' + refute app.should_instrument?({}, 200, {'Content-Type' => 'text/xhtml'}), 'Expected not to instrument requests with content type other than text/html.' end def test_should_not_instrument_when_content_disposition @@ -128,12 +128,12 @@ def test_insert_header_should_mark_environment # header manually, and then re-insert, verifying that it ends up in the right # place. - source_files = Dir[File.join(cross_agent_tests_dir, 'rum_loader_insertion_location', "*.html")] + source_files = Dir[File.join(cross_agent_tests_dir, 'rum_loader_insertion_location', '*.html')] - RUM_PLACEHOLDER = "EXPECTED_RUM_LOADER_LOCATION" + RUM_PLACEHOLDER = 'EXPECTED_RUM_LOADER_LOCATION' source_files.each do |source_file| - source_filename = File.basename(source_file).tr(".", "_") + source_filename = File.basename(source_file).tr('.', '_') instrumented_html = File.read(source_file) uninstrumented_html = instrumented_html.gsub(RUM_PLACEHOLDER, '') @@ -157,7 +157,7 @@ def test_insert_header_should_mark_environment end def test_should_close_response - TestApp.next_response = Rack::Response.new("") + TestApp.next_response = Rack::Response.new('') TestApp.next_response.expects(:close) get('/') @@ -166,8 +166,8 @@ def test_should_close_response end def test_with_invalid_us_ascii_encoding - response = String.new('Jürgen') - response.force_encoding(Encoding.find("US-ASCII")) + response = +'Jürgen' + response.force_encoding(Encoding.find('US-ASCII')) TestApp.next_response = Rack::Response.new(response) get('/') @@ -176,7 +176,7 @@ def test_with_invalid_us_ascii_encoding end def test_should_not_close_if_not_responded_to - TestApp.next_response = Rack::Response.new("") + TestApp.next_response = Rack::Response.new('') TestApp.next_response.stubs(:respond_to?).with(:close).returns(false) TestApp.next_response.expects(:close).never @@ -194,32 +194,32 @@ def test_should_not_throw_exception_on_empty_response def test_content_length_set_when_we_modify_source original_headers = { - "Content-Length" => "0", - "Content-Type" => "text/html" + 'Content-Length' => '0', + 'Content-Type' => 'text/html' } - headers = headers_from_request(original_headers, "") + headers = headers_from_request(original_headers, '') - assert_equal "390", headers["Content-Length"] + assert_equal '390', headers['Content-Length'] end def test_content_length_set_when_we_modify_source_containing_unicode original_headers = { - "Content-Length" => "0", - "Content-Type" => "text/html" + 'Content-Length' => '0', + 'Content-Type' => 'text/html' } - headers = headers_from_request(original_headers, "☃") + headers = headers_from_request(original_headers, '☃') - assert_equal "393", headers["Content-Length"] + assert_equal '393', headers['Content-Length'] end def test_content_length_set_when_response_is_nil original_headers = { - "Content-Length" => "0", - "Content-Type" => "text/html" + 'Content-Length' => '0', + 'Content-Type' => 'text/html' } headers = headers_from_request(original_headers, nil) - assert_equal "0", headers["Content-Length"] + assert_equal '0', headers['Content-Length'] end def headers_from_request(headers, content) @@ -232,5 +232,5 @@ def headers_from_request(headers, content) end end else - puts "Skipping tests in #{File.basename(__FILE__)} because Rack::Test is unavailable" if ENV["VERBOSE_TEST_OUTPUT"] + puts "Skipping tests in #{File.basename(__FILE__)} because Rack::Test is unavailable" if ENV['VERBOSE_TEST_OUTPUT'] end diff --git a/test/new_relic/slack_notifications_tests/cve_notifier_tests.rb b/test/new_relic/slack_notifications_tests/cve_notifier_tests.rb index 43f186eee8..a6e925137e 100644 --- a/test/new_relic/slack_notifications_tests/cve_notifier_tests.rb +++ b/test/new_relic/slack_notifications_tests/cve_notifier_tests.rb @@ -11,11 +11,11 @@ def test_cve_message_zero_args end def test_cve_message_one_arg - assert_raises(ArgumentError) { CveNotifier.cve_message("allosaurus") } + assert_raises(ArgumentError) { CveNotifier.cve_message('allosaurus') } end def test_cve_message - message = CveNotifier.cve_message("allosaurus", "dinotracker.com") + message = CveNotifier.cve_message('allosaurus', 'dinotracker.com') assert_equal message == '{"text":":rotating_light: allosaurus\n"}' assert_kind_of String, text diff --git a/test/new_relic/slack_notifications_tests/gem_notifier_tests.rb b/test/new_relic/slack_notifications_tests/gem_notifier_tests.rb index 4f26fbda76..582e5050d1 100644 --- a/test/new_relic/slack_notifications_tests/gem_notifier_tests.rb +++ b/test/new_relic/slack_notifications_tests/gem_notifier_tests.rb @@ -17,23 +17,23 @@ def unsuccessful_http_response end def http_get_response - [{"created_at" => "2001-07-18T16:15:29.083Z", "platform" => "ruby", "number" => "4.0.0.preview"}, - {"created_at" => "2001-07-18T16:15:29.083Z", "platform" => "ruby", "number" => "3.0.0.rc1"}, - {"created_at" => "2001-07-18T16:15:29.083Z", "platform" => "ruby", "number" => "3.0.0"}, - {"created_at" => "1997-05-23T16:15:29.083Z", "platform" => "java", "number" => "2.0.0"}, - {"created_at" => "1993-06-11T16:15:29.083Z", "platform" => "ruby", "number" => "1.0.0"}] + [{'created_at' => '2001-07-18T16:15:29.083Z', 'platform' => 'ruby', 'number' => '4.0.0.preview'}, + {'created_at' => '2001-07-18T16:15:29.083Z', 'platform' => 'ruby', 'number' => '3.0.0.rc1'}, + {'created_at' => '2001-07-18T16:15:29.083Z', 'platform' => 'ruby', 'number' => '3.0.0'}, + {'created_at' => '1997-05-23T16:15:29.083Z', 'platform' => 'java', 'number' => '2.0.0'}, + {'created_at' => '1993-06-11T16:15:29.083Z', 'platform' => 'ruby', 'number' => '1.0.0'}] end def gem_versions_array - [{"created_at" => "2001-07-18T16:15:29.083Z", "platform" => "ruby", "number" => "1.2"}, - {"created_at" => "2001-07-18T16:15:29.083Z", "platform" => "ruby", "number" => "1.1"}] + [{'created_at' => '2001-07-18T16:15:29.083Z', 'platform' => 'ruby', 'number' => '1.2'}, + {'created_at' => '2001-07-18T16:15:29.083Z', 'platform' => 'ruby', 'number' => '1.1'}] end def test_valid_gem_name response = successful_http_response HTTParty.stub(:get, response) do - assert GemNotifier.verify_gem("puma!") + assert GemNotifier.verify_gem('puma!') end end @@ -43,13 +43,13 @@ def test_invalid_gem_name HTTParty.stub(:get, response) do GemNotifier.stub(:abort, nil) do - assert_predicate GemNotifier.verify_gem("TrexRawr!"), :ouch? + assert_predicate GemNotifier.verify_gem('TrexRawr!'), :ouch? end end end def test_github_diff_get_request_failure - HTTParty.stub(:get, -> { raise "Oh no a failure" }) do + HTTParty.stub(:get, -> { raise 'Oh no a failure' }) do GemNotifier.stub(:abort, nil) do assert_raises(StandardError) { GemNotifier.github_diff('invalid_git_diff', '1.2', '1.1') } end @@ -99,20 +99,20 @@ def test_previous_version_must_be_a_stable_release end def test_gem_updated_true - assert GemNotifier.gem_updated?([{"created_at" => "#{Time.now}"}]) + assert GemNotifier.gem_updated?([{'created_at' => "#{Time.now}"}]) end def test_gem_updated_false - refute GemNotifier.gem_updated?([{"created_at" => "1993-06-11T17:31:14.298Z"}]) + refute GemNotifier.gem_updated?([{'created_at' => '1993-06-11T17:31:14.298Z'}]) end def test_interpolate_github_url_one_arg - gem_name = "stegosaurus" + gem_name = 'stegosaurus' assert_raises(ArgumentError) { GemNotifier.interpolate_github_url(gem_name) } end def test_interpolate_github_url - gem_name, newest, previous = "stegosaurus", "2.0", "1.0" + gem_name, newest, previous = 'stegosaurus', '2.0', '1.0' assert_kind_of String, GemNotifier.interpolate_github_url(gem_name, newest, previous) end @@ -122,7 +122,7 @@ def test_interpolate_rubygems_url_one_arg end def test_interpolate_rubygems_url - gem_name = "velociraptor" + gem_name = 'velociraptor' assert_kind_of String, GemNotifier.interpolate_rubygems_url(gem_name) end @@ -135,7 +135,7 @@ def test_gem_message_incorrect_args def test_gem_message_with_github_diff GemNotifier.stub(:github_diff, 'fake_gem_diff_url') do - assert_equal "A new gem version is out :sparkles: , 1.1 -> 1.2" \ + assert_equal 'A new gem version is out :sparkles: , 1.1 -> 1.2' \ "\n\n", GemNotifier.gem_message('fake_gem', gem_versions_array) end @@ -143,7 +143,7 @@ def test_gem_message_with_github_diff def test_gem_message_with_gem_compare GemNotifier.stub(:github_diff, false) do - assert_equal "A new gem version is out :sparkles: , 1.1 -> 1.2" \ + assert_equal 'A new gem version is out :sparkles: , 1.1 -> 1.2' \ "\n\nSee what's new with gem-compare:\n`gem compare fake_gem 1.1 1.2 --diff`", GemNotifier.gem_message('fake_gem', gem_versions_array) end diff --git a/test/new_relic/slack_notifications_tests/slack_notifier_tests.rb b/test/new_relic/slack_notifications_tests/slack_notifier_tests.rb index ddbaf6aacc..81231e4b1c 100644 --- a/test/new_relic/slack_notifications_tests/slack_notifier_tests.rb +++ b/test/new_relic/slack_notifications_tests/slack_notifier_tests.rb @@ -16,14 +16,14 @@ def test_send_slack_message_zero_args def test_send_slack_message_too_many_args assert_raises(ArgumentError) { - SlackNotifier.send_slack_message("I am a notification message!", "But I'm one too many") + SlackNotifier.send_slack_message('I am a notification message!', "But I'm one too many") } end def test_send_slack_message SlackNotifier.stub(:sleep, nil) do HTTParty.stub(:post, nil) do - assert_nil SlackNotifier.send_slack_message("I am a notification message!") + assert_nil SlackNotifier.send_slack_message('I am a notification message!') end end end @@ -31,7 +31,7 @@ def test_send_slack_message def test_errors_array_no_errors SlackNotifier.stub(:sleep, nil) do HTTParty.stub(:post, nil) do - SlackNotifier.send_slack_message("I am a notification message!") + SlackNotifier.send_slack_message('I am a notification message!') assert_empty SlackNotifier.errors_array end @@ -40,7 +40,7 @@ def test_errors_array_no_errors def test_errors_array_one_error HTTParty.stub(:post, -> { raise "Yikes this didn't work!!" }) do - SlackNotifier.send_slack_message("I am a notification message!") + SlackNotifier.send_slack_message('I am a notification message!') assert_equal 1, SlackNotifier.errors_array.length end @@ -49,8 +49,8 @@ def test_errors_array_one_error def test_errors_array_multiple_errors HTTParty.stub(:post, -> { raise "Yikes this didn't work!!" }) do - SlackNotifier.send_slack_message("I am a notification message!") - SlackNotifier.send_slack_message("I am a another notification message!") + SlackNotifier.send_slack_message('I am a notification message!') + SlackNotifier.send_slack_message('I am a another notification message!') assert_equal 2, SlackNotifier.errors_array.length end diff --git a/test/new_relic/supportability_helper_test.rb b/test/new_relic/supportability_helper_test.rb index 3f6e360357..daeb4dd635 100644 --- a/test/new_relic/supportability_helper_test.rb +++ b/test/new_relic/supportability_helper_test.rb @@ -13,14 +13,14 @@ def teardown include NewRelic::SupportabilityHelper def test_valid_api_argument_class_truthy - assert valid_api_argument_class?({foo: :bar}, "headers", Hash) + assert valid_api_argument_class?({foo: :bar}, 'headers', Hash) end def test_valid_api_argument_class_falsey log = with_array_logger do NewRelic::Agent.manual_start - refute valid_api_argument_class?("bogus", "headers", Hash) + refute valid_api_argument_class?('bogus', 'headers', Hash) end assert_log_contains(log, /Bad argument passed to #block/) diff --git a/test/new_relic/test_time_reporter_test.rb b/test/new_relic/test_time_reporter_test.rb index 8170f8da59..2d3f3f0d55 100644 --- a/test/new_relic/test_time_reporter_test.rb +++ b/test/new_relic/test_time_reporter_test.rb @@ -39,7 +39,7 @@ def test_report_prints_outside_multiverse refute(defined?(::Multiverse::ROOT), 'Multiverse::ROOT is defined.') @reporter.instance_variable_set(:@test_times, [PARSED_RESULT]) - assert_output(/Ten slowest tests/) { @reporter.report } if ENV["VERBOSE_TEST_OUTPUT"] + assert_output(/Ten slowest tests/) { @reporter.report } if ENV['VERBOSE_TEST_OUTPUT'] end def test_report_does_not_print_inside_multiverse diff --git a/test/new_relic/transaction_ignoring_test_cases.rb b/test/new_relic/transaction_ignoring_test_cases.rb index 636c2bb104..408518e3c9 100644 --- a/test/new_relic/transaction_ignoring_test_cases.rb +++ b/test/new_relic/transaction_ignoring_test_cases.rb @@ -9,8 +9,8 @@ module TransactionIgnoringTestCases setup_and_teardown_agent do |collector| collector.stub('connect', { - 'transaction_name_rules' => [{"match_expression" => "ignored_transaction", - "ignore" => true}], + 'transaction_name_rules' => [{'match_expression' => 'ignored_transaction', + 'ignore' => true}], 'agent_run_id' => 1 }) end diff --git a/test/nullverse/default_source_require_test.rb b/test/nullverse/default_source_require_test.rb index 3f04c0d110..dd6bad93be 100644 --- a/test/nullverse/default_source_require_test.rb +++ b/test/nullverse/default_source_require_test.rb @@ -16,6 +16,6 @@ def test_require_default_source_doesnt_raise exception = e end - assert_nil exception, "Expected not to raise when requiring default source without the agent" + assert_nil exception, 'Expected not to raise when requiring default source without the agent' end end diff --git a/test/performance/lib/performance/baseline.rb b/test/performance/lib/performance/baseline.rb index d208acedf7..91ea306969 100644 --- a/test/performance/lib/performance/baseline.rb +++ b/test/performance/lib/performance/baseline.rb @@ -4,7 +4,7 @@ module Performance class Baseline - PERSIST_PATH = File.expand_path(ENV.fetch("NEWRELIC_RPM_BASELINE_FILE", "~/.newrelic_rpm_baseline")) + PERSIST_PATH = File.expand_path(ENV.fetch('NEWRELIC_RPM_BASELINE_FILE', '~/.newrelic_rpm_baseline')) attr_reader :results diff --git a/test/performance/lib/performance/baseline_compare_reporter.rb b/test/performance/lib/performance/baseline_compare_reporter.rb index f432d78914..a017efda23 100644 --- a/test/performance/lib/performance/baseline_compare_reporter.rb +++ b/test/performance/lib/performance/baseline_compare_reporter.rb @@ -38,7 +38,7 @@ def report_successful_results(baseline, results) missing_from_baseline.each do |identifier| puts " #{identifier}" end - puts "" + puts '' end if !missing_from_baseline.empty? @@ -46,7 +46,7 @@ def report_successful_results(baseline, results) missing_from_new.each do |identifier| puts " #{identifier}" end - puts "" + puts '' end rows = [] @@ -98,7 +98,7 @@ def report_successful_results(baseline, results) end format_percent_delta = proc { |v| - prefix = v > 0 ? "+" : "" + prefix = v > 0 ? '+' : '' sprintf("#{prefix}%.1f%%", v) } diff --git a/test/performance/lib/performance/console_reporter.rb b/test/performance/lib/performance/console_reporter.rb index e23e227a8a..c29447e19b 100644 --- a/test/performance/lib/performance/console_reporter.rb +++ b/test/performance/lib/performance/console_reporter.rb @@ -24,7 +24,7 @@ def format_measurements(result) measurements = result.measurements.merge(:iterations => result.iterations) key_width = measurements.keys.map(&:size).max - formatted_values = measurements.values.map { |v| sprintf("%g", v) } + formatted_values = measurements.values.map { |v| sprintf('%g', v) } value_width = formatted_values.map(&:size).max rows = measurements.map do |key, value| @@ -55,7 +55,7 @@ def report_successful_results(results) puts format_measurements(result) end unless result.artifacts.empty? - puts " artifacts:" + puts ' artifacts:' result.artifacts.each do |artifact| puts " #{make_relative(artifact)}" end diff --git a/test/performance/lib/performance/formatting_helpers.rb b/test/performance/lib/performance/formatting_helpers.rb index 0172e827e9..0e3283b6a9 100644 --- a/test/performance/lib/performance/formatting_helpers.rb +++ b/test/performance/lib/performance/formatting_helpers.rb @@ -7,16 +7,16 @@ module FormattingHelpers def self.format_duration(d) if d < 0.001 ds = d * 1000 * 1000 - unit = "µs" + unit = 'µs' elsif d < 1.0 ds = d * 1000 - unit = "ms" + unit = 'ms' else ds = d - unit = "s" + unit = 's' end - sprintf("%.2f %s", ds, unit) + sprintf('%.2f %s', ds, unit) end end end diff --git a/test/performance/lib/performance/hako_client.rb b/test/performance/lib/performance/hako_client.rb index c9e752c775..6be4353acb 100644 --- a/test/performance/lib/performance/hako_client.rb +++ b/test/performance/lib/performance/hako_client.rb @@ -17,7 +17,7 @@ def initialize(token) def submit(result) body = JSON.dump('result' => result.to_h) - uri = URI(BASE_URI + "/api/results") + uri = URI(BASE_URI + '/api/results') req = Net::HTTP::Post.new(uri.to_s) req.body = body req.content_type = 'application/json' diff --git a/test/performance/lib/performance/hako_reporter.rb b/test/performance/lib/performance/hako_reporter.rb index 708e887cad..19a9d3dc1e 100644 --- a/test/performance/lib/performance/hako_reporter.rb +++ b/test/performance/lib/performance/hako_reporter.rb @@ -16,7 +16,7 @@ def report rsp = client.submit(result) case rsp when Net::HTTPSuccess - Performance.logger.debug("Successfully posted result to Hako") + Performance.logger.debug('Successfully posted result to Hako') else Performance.logger.error("Failed to post results to Hako: #{rsp.inspect}") end diff --git a/test/performance/lib/performance/instrumentation/perf_tools.rb b/test/performance/lib/performance/instrumentation/perf_tools.rb index 5857f72063..9e406d9209 100644 --- a/test/performance/lib/performance/instrumentation/perf_tools.rb +++ b/test/performance/lib/performance/instrumentation/perf_tools.rb @@ -14,13 +14,13 @@ def self.setup def before(test, test_name) @profile_dir = Dir.mktmpdir('profile') - @profile_path = File.join(@profile_dir, "profile") + @profile_path = File.join(@profile_dir, 'profile') PerfTools::CpuProfiler.start(@profile_path) end def after(test, test_name) PerfTools::CpuProfiler.stop - output_profile_path = artifact_path(test, test_name, "dot") + output_profile_path = artifact_path(test, test_name, 'dot') system("pprof.rb --dot #{@profile_path} >#{output_profile_path}") @artifacts << output_profile_path FileUtils.remove_entry_secure(@profile_dir) diff --git a/test/performance/lib/performance/instrumentation/stackprof.rb b/test/performance/lib/performance/instrumentation/stackprof.rb index 4abca2faa3..e28f0d0ee4 100644 --- a/test/performance/lib/performance/instrumentation/stackprof.rb +++ b/test/performance/lib/performance/instrumentation/stackprof.rb @@ -23,14 +23,14 @@ def before(test, test_name) def after(test, test_name) StackProf.stop - output_dump_path = artifact_path(test, test_name, "dump") + output_dump_path = artifact_path(test, test_name, 'dump') StackProf.results(output_dump_path) @artifacts << output_dump_path results = Marshal.load(File.read(output_dump_path)) - output_dot_path = artifact_path(test, test_name, "dot") + output_dot_path = artifact_path(test, test_name, 'dot') report = StackProf::Report.new(results) - File.open(output_dot_path, "w") do |f| + File.open(output_dot_path, 'w') do |f| report.print_graphviz({}, f) end @artifacts << output_dot_path diff --git a/test/performance/lib/performance/instrumentor.rb b/test/performance/lib/performance/instrumentor.rb index 71d25f5548..b48d51d0e6 100644 --- a/test/performance/lib/performance/instrumentor.rb +++ b/test/performance/lib/performance/instrumentor.rb @@ -6,7 +6,7 @@ module Performance module Instrumentation def self.load_instrumentors dir = File.expand_path(File.join(File.dirname(__FILE__), 'instrumentation')) - Dir.glob(File.join(dir, "*.rb")).each do |filename| + Dir.glob(File.join(dir, '*.rb')).each do |filename| require filename end end @@ -73,7 +73,7 @@ def reset end def pretty_name - self.class.name.split("::").last + self.class.name.split('::').last end def artifacts_dir_for(test_case, test_name) diff --git a/test/performance/lib/performance/reporting.rb b/test/performance/lib/performance/reporting.rb index 5890b7a2fc..3f4afe2076 100644 --- a/test/performance/lib/performance/reporting.rb +++ b/test/performance/lib/performance/reporting.rb @@ -27,7 +27,7 @@ def report_failed_results puts "#{e['class']}: #{e['message']}" puts failure.exception['backtrace'].map { |l| " #{l}" }.join("\n") else - puts "" + puts '' end end puts '' diff --git a/test/performance/lib/performance/result.rb b/test/performance/lib/performance/result.rb index 459256dcea..78087dde41 100644 --- a/test/performance/lib/performance/result.rb +++ b/test/performance/lib/performance/result.rb @@ -69,11 +69,11 @@ def time_per_iteration def to_h h = { - "suite" => suite_name, - "name" => @test_name, - "measurements" => measurements_hash, - "tags" => @tags, - "iterations" => @iterations + 'suite' => suite_name, + 'name' => @test_name, + 'measurements' => measurements_hash, + 'tags' => @tags, + 'iterations' => @iterations } h['exception'] = @exception if @exception h['artifacts'] = @artifacts if @artifacts && !@artifacts.empty? diff --git a/test/performance/lib/performance/runner.rb b/test/performance/lib/performance/runner.rb index d6e1b60a79..ff7ce0ddb4 100644 --- a/test/performance/lib/performance/runner.rb +++ b/test/performance/lib/performance/runner.rb @@ -47,7 +47,7 @@ def create_instrumentors(names) end def load_test_files(dir) - Dir.glob(File.join(dir, "**", "*.rb")).each do |filename| + Dir.glob(File.join(dir, '**', '*.rb')).each do |filename| require filename end end @@ -120,7 +120,7 @@ def load_newrelic_rpm unless @loaded_newrelic_rpm path = newrelic_rpm_path $:.unshift(path) - require "newrelic_rpm" + require 'newrelic_rpm' @newrelic_rpm_version = NewRelic::VERSION::STRING @newrelic_rpm_git_sha = find_newrelic_rpm_git_sha(path) @loaded_newrelic_rpm = true diff --git a/test/performance/lib/performance/table.rb b/test/performance/lib/performance/table.rb index 7ac7122c5b..59fbf23ac9 100644 --- a/test/performance/lib/performance/table.rb +++ b/test/performance/lib/performance/table.rb @@ -74,7 +74,7 @@ def column_widths end def render_row(parts) - "| " + parts.join(" | ") + " |" + '| ' + parts.join(' | ') + ' |' end def left_corner @@ -92,7 +92,7 @@ def delimiter def render widths = column_widths - blanks = widths.map { |w| "-" * w } + blanks = widths.map { |w| '-' * w } top = left_corner + blanks.join(delimiter) + right_corner separator = '|-' + blanks.join(delimiter) + '-|' bottom = left_corner + blanks.join(delimiter) + right_corner diff --git a/test/performance/lib/performance/test_case.rb b/test/performance/lib/performance/test_case.rb index ccdaf302b9..cf2431d492 100644 --- a/test/performance/lib/performance/test_case.rb +++ b/test/performance/lib/performance/test_case.rb @@ -44,9 +44,7 @@ def on(event, &action) end def fire(event, *args) - if @callbacks[event] - @callbacks[event].each { |cb| cb.arity > 0 ? cb.call(*args) : cb.call } - end + @callbacks[event]&.each { |cb| cb.arity > 0 ? cb.call(*args) : cb.call } end def runnable_test_methods diff --git a/test/performance/script/baselines b/test/performance/script/baselines index f352de715e..3ec913fab8 100755 --- a/test/performance/script/baselines +++ b/test/performance/script/baselines @@ -58,7 +58,7 @@ class FetchedGem end def fetch! - File.open(path, "w") do |f| + File.open(path, 'w') do |f| rsp = HTTParty.get(uri) f.write(rsp.body) end diff --git a/test/performance/script/runner b/test/performance/script/runner index c8ddd97480..ec108a0f83 100755 --- a/test/performance/script/runner +++ b/test/performance/script/runner @@ -14,7 +14,7 @@ options = {} parser = OptionParser.new do |opts| opts.banner = "Usage: #{$0} [options]" - opts.on("-P", "--profile", "Do profiling around each test") do + opts.on('-P', '--profile', 'Do profiling around each test') do best_profiling_instrumentor = [ Performance::Instrumentation::StackProfProfile, Performance::Instrumentation::PerfToolsProfile @@ -24,95 +24,95 @@ parser = OptionParser.new do |opts| options[:inline] = true options[:instrumentors] = [best_profiling_instrumentor.to_s] else - Performance.logger.warn("Could not find a supported instrumentor for profiling.") + Performance.logger.warn('Could not find a supported instrumentor for profiling.') end end - opts.on("-a", "--profile-alloc", "Do profiling around each test for object allocations") do + opts.on('-a', '--profile-alloc', 'Do profiling around each test for object allocations') do options[:inline] = true options[:instrumentors] = [Performance::Instrumentation::StackProfAllocationProfile.to_s] end - opts.on("-l", "--list", "List all available suites and tests") do + opts.on('-l', '--list', 'List all available suites and tests') do options[:list] = true end - opts.on("-s", "--suite=NAME", "Filter test suites to run (allows comma separated list)") do |name| + opts.on('-s', '--suite=NAME', 'Filter test suites to run (allows comma separated list)') do |name| options[:suite] ||= [] - options[:suite].concat(name.split(",")) + options[:suite].concat(name.split(',')) end - opts.on("-n", "--name=NAME", "Filter tests to those matching NAME") do |name| + opts.on('-n', '--name=NAME', 'Filter tests to those matching NAME') do |name| options[:name] = name end - opts.on("-B", "--baseline", "Save results as a baseline") do |b| + opts.on('-B', '--baseline', 'Save results as a baseline') do |b| options[:reporter_classes] = ['BaselineSaveReporter'] end - opts.on("-C", "--compare", "Compare results to a saved baseline") do |c| + opts.on('-C', '--compare', 'Compare results to a saved baseline') do |c| options[:reporter_classes] = ['BaselineCompareReporter'] end - opts.on("-N", "--iterations=NUM", - "Set a fixed number of iterations for each test.", - "Overrides the -d / --duration option.") do |iterations| + opts.on('-N', '--iterations=NUM', + 'Set a fixed number of iterations for each test.', + 'Overrides the -d / --duration option.') do |iterations| options[:iterations] = iterations.to_i end - opts.on("-d", "--duration=TIME", - "Run each test for TIME seconds. Defaults to 5s.") do |duration| + opts.on('-d', '--duration=TIME', + 'Run each test for TIME seconds. Defaults to 5s.') do |duration| options[:duration] = duration.to_f end - opts.on("-I", "--inline", "Run tests inline - do not isolate each test into a sub-invocation") do |i| + opts.on('-I', '--inline', 'Run tests inline - do not isolate each test into a sub-invocation') do |i| options[:inline] = true end - opts.on("-j", "--json", "Produce JSON output") do |q| + opts.on('-j', '--json', 'Produce JSON output') do |q| options[:reporter_classes] = ['JSONReporter'] end - opts.on("-R", "--reporters=NAMES", "Use the specified reporters (comma-separated list of class names)") do |reporter_names| + opts.on('-R', '--reporters=NAMES', 'Use the specified reporters (comma-separated list of class names)') do |reporter_names| reporter_names = reporter_names.split(',') options[:reporter_classes] = reporter_names end - opts.on("-r", "--randomize", "Randomize test order") do |r| + opts.on('-r', '--randomize', 'Randomize test order') do |r| options[:randomize] = r end - opts.on("-b", "--brief", "Don't print out details for each test, just the elapsed time") do |b| + opts.on('-b', '--brief', "Don't print out details for each test, just the elapsed time") do |b| options[:brief] = b end - opts.on("-T", "--test=NAME", "Run one specific test, identified by #") do |identifier| + opts.on('-T', '--test=NAME', 'Run one specific test, identified by #') do |identifier| options[:identifier] = identifier end - opts.on("-i", "--instrumentor=NAME", "Use the named instrumentor") do |name| + opts.on('-i', '--instrumentor=NAME', 'Use the named instrumentor') do |name| options[:instrumentors] = [name] end - opts.on("-q", "--quiet", "Disable diagnostic logging") do - Performance.log_path = "/dev/null" + opts.on('-q', '--quiet', 'Disable diagnostic logging') do + Performance.log_path = '/dev/null' end - opts.on("-L", "--log=PATH", "Log diagnostic information to PATH") do |log_path| + opts.on('-L', '--log=PATH', 'Log diagnostic information to PATH') do |log_path| Performance.log_path = log_path end - opts.on("-A", "--agent=PATH", "Run tests against the copy of the agent at PATH") do |path| + opts.on('-A', '--agent=PATH', 'Run tests against the copy of the agent at PATH') do |path| options[:agent_path] = path end - opts.on("-m", "--metadata=METADATA", "Attach metadata to the run. Format: 'key:value'. May be specified multiple times.") do |tag_string| - key, value = tag_string.split(":", 2) + opts.on('-m', '--metadata=METADATA', "Attach metadata to the run. Format: 'key:value'. May be specified multiple times.") do |tag_string| + key, value = tag_string.split(':', 2) options[:tags] ||= {} options[:tags][key] = value end - opts.on("-M", "--markdown", "Format the tabular output in Markdown") do + opts.on('-M', '--markdown', 'Format the tabular output in Markdown') do options[:markdown] = true end end diff --git a/test/performance/suites/active_record.rb b/test/performance/suites/active_record.rb index d0ab3455bd..8d2a4518ed 100644 --- a/test/performance/suites/active_record.rb +++ b/test/performance/suites/active_record.rb @@ -5,9 +5,9 @@ require 'new_relic/agent/instrumentation/active_record_helper' class ActiveRecordTest < Performance::TestCase - NAME = "Model Load" - SQL = "SELECT * FROM star" - ADAPTER = "mysql2" + NAME = 'Model Load' + SQL = 'SELECT * FROM star' + ADAPTER = 'mysql2' def test_helper_by_name measure do @@ -15,7 +15,7 @@ def test_helper_by_name end end - UNKNOWN_NAME = "Blah" + UNKNOWN_NAME = 'Blah' def test_helper_by_sql measure do diff --git a/test/performance/suites/agent_attributes.rb b/test/performance/suites/agent_attributes.rb index 19c28bb87e..974f94bb53 100644 --- a/test/performance/suites/agent_attributes.rb +++ b/test/performance/suites/agent_attributes.rb @@ -7,8 +7,8 @@ def setup require 'new_relic/agent/attribute_filter' end - ALPHA = "alpha".freeze - BETA = "beta".freeze + ALPHA = 'alpha'.freeze + BETA = 'beta'.freeze def test_empty_agent_attributes @filter = NewRelic::Agent::AttributeFilter.new(NewRelic::Agent.config) diff --git a/test/performance/suites/agent_module.rb b/test/performance/suites/agent_module.rb index c60f8e6553..239f823ac7 100644 --- a/test/performance/suites/agent_module.rb +++ b/test/performance/suites/agent_module.rb @@ -5,7 +5,7 @@ # This suite is for perf testing methods from the NewRelic::Agent module class AgentModuleTest < Performance::TestCase - METRIC = "Some/Custom/Metric".freeze + METRIC = 'Some/Custom/Metric'.freeze def test_increment_metric_by_1 measure do diff --git a/test/performance/suites/config.rb b/test/performance/suites/config.rb index e5b43fb22b..c87f689615 100644 --- a/test/performance/suites/config.rb +++ b/test/performance/suites/config.rb @@ -5,7 +5,7 @@ class ConfigPerfTests < Performance::TestCase def setup @config = NewRelic::Agent::Configuration::Manager.new - @config.add_config_for_testing(:my_value => "boo") + @config.add_config_for_testing(:my_value => 'boo') end def test_raw_access diff --git a/test/performance/suites/datastores.rb b/test/performance/suites/datastores.rb index 45584d405a..7cd55a790e 100644 --- a/test/performance/suites/datastores.rb +++ b/test/performance/suites/datastores.rb @@ -5,18 +5,18 @@ class DatastoresPerfTest < Performance::TestCase class FauxDB def self.query - "foo" + 'foo' end end def test_instrumentation_via_trace db_class = Class.new do def query - "foo" + 'foo' end end - NewRelic::Agent::Datastores.trace(db_class, "query", "FakeDB") + NewRelic::Agent::Datastores.trace(db_class, 'query', 'FakeDB') db = db_class.new measure do @@ -27,9 +27,9 @@ def query end def test_wrap - product = "FauxDB".freeze - operation = "query".freeze - collection = "collection".freeze + product = 'FauxDB'.freeze + operation = 'query'.freeze + collection = 'collection'.freeze measure do in_transaction do @@ -40,8 +40,8 @@ def test_wrap end end - SQL = "select * from users".freeze - METRIC_NAME = "Datastore/statement/MySQL/users/select".freeze + SQL = 'select * from users'.freeze + METRIC_NAME = 'Datastore/statement/MySQL/users/select'.freeze def test_notice_sql measure do @@ -50,7 +50,7 @@ def test_notice_sql end def test_segment_notice_sql - segment = NewRelic::Agent::Transaction::DatastoreSegment.new("MySQL", "select", "users") + segment = NewRelic::Agent::Transaction::DatastoreSegment.new('MySQL', 'select', 'users') conf = {:adapter => :mysql} measure do segment._notice_sql(SQL, conf) diff --git a/test/performance/suites/error_collector.rb b/test/performance/suites/error_collector.rb index 349cb783c0..5d736d9ca4 100644 --- a/test/performance/suites/error_collector.rb +++ b/test/performance/suites/error_collector.rb @@ -4,8 +4,8 @@ class ErrorCollectorTests < Performance::TestCase def setup - @txn_name = "Controller/blogs/index".freeze - @err_msg = "Sorry!".freeze + @txn_name = 'Controller/blogs/index'.freeze + @err_msg = 'Sorry!'.freeze end def test_notice_error @@ -17,7 +17,7 @@ def test_notice_error end def test_notice_error_with_custom_attributes - opts = {:custom_params => {:name => "Wes Mantooth", :channel => 9}} + opts = {:custom_params => {:name => 'Wes Mantooth', :channel => 9}} measure do in_transaction(:name => @txn_name) do diff --git a/test/performance/suites/external_segment.rb b/test/performance/suites/external_segment.rb index b282f39be0..3241f84a6b 100644 --- a/test/performance/suites/external_segment.rb +++ b/test/performance/suites/external_segment.rb @@ -9,15 +9,15 @@ class ExternalSegment < Performance::TestCase CAT_CONFIG = { :license_key => 'a' * 40, :'cross_application_tracer.enabled' => true, - :cross_process_id => "1#1884", - :encoding_key => "jotorotoes", + :cross_process_id => '1#1884', + :encoding_key => 'jotorotoes', :trusted_account_ids => [1] } TRACE_CONTEXT_CONFIG = { :'distributed_tracing.enabled' => true, - :account_id => "190", - :primary_application_id => "46954", + :account_id => '190', + :primary_application_id => '46954', :disable_harvest_thread => true } @@ -27,7 +27,7 @@ def setup ) end - TEST_URI = URI("http://localhost:3035/status") + TEST_URI = URI('http://localhost:3035/status') def test_external_request io_server = start_server @@ -93,30 +93,30 @@ def test_external_trace_context_request_within_thread def start_server io = IO.popen(SERVER_SCRIPT_PATH, 'r+') response = JSON.parse(io.gets) - if response["message"] == "started" + if response['message'] == 'started' io else - fail "Could not start server" + fail 'Could not start server' end end def reply_with_cat_headers(io_server) message = { - :command => "add_headers", + :command => 'add_headers', :payload => cat_response_headers }.to_json io_server.puts message end def stop_server(io_server) - message = {:command => "shutdown"}.to_json + message = {:command => 'shutdown'}.to_json io_server.puts message Process.wait end def cat_response_headers obfuscator = NewRelic::Agent::Obfuscator.new(NewRelic::Agent.config[:encoding_key]) - app_data = obfuscator.obfuscate(["1#1884", "txn-name", 2, 8, 0, 'BEC1BC64675138B9'].to_json) + "\n" + app_data = obfuscator.obfuscate(['1#1884', 'txn-name', 2, 8, 0, 'BEC1BC64675138B9'].to_json) + "\n" {'X-NewRelic-App-Data' => app_data} end end diff --git a/test/performance/suites/marshalling.rb b/test/performance/suites/marshalling.rb index e4843935ff..64b2210b46 100644 --- a/test/performance/suites/marshalling.rb +++ b/test/performance/suites/marshalling.rb @@ -104,7 +104,7 @@ def build_transaction_trace_payload(depth = 6) i * rand(10), "This/Is/The/Name/Of/A/Transaction/Trace/Node/Depth/#{depth}/#{i}", { - "sql" => "SELECT #{(0..100).to_a.join(",")}" + 'sql' => "SELECT #{(0..100).to_a.join(',')}" }, [] ] @@ -120,16 +120,16 @@ def build_analytics_events_payload 1000.times do event = { 'timestamp' => Process.clock_gettime(Process::CLOCK_REALTIME), - 'name' => String.new('Controller/foo/bar'), - 'type' => String.new('Transaction'), + 'name' => +'Controller/foo/bar', + 'type' => +'Transaction', 'duration' => rand, 'databaseDuration' => rand, 'databaseCallCount' => rand, 'gcCumulative' => rand, - 'host' => String.new('lo-calhost'), - 'color' => String.new('blue-green'), - 'shape' => String.new('squarish'), - 'texture' => String.new('sort of lumpy like a bag of frozen peas') + 'host' => +'lo-calhost', + 'color' => +'blue-green', + 'shape' => +'squarish', + 'texture' => +'sort of lumpy like a bag of frozen peas' } events << [event, {}] end diff --git a/test/performance/suites/queue_time.rb b/test/performance/suites/queue_time.rb index 29ce2b6321..93c5243b07 100644 --- a/test/performance/suites/queue_time.rb +++ b/test/performance/suites/queue_time.rb @@ -5,9 +5,9 @@ class QueueTimePerfTests < Performance::TestCase def setup @headers = [ - {'HTTP_X_REQUEST_START' => "t=1409849996.2152882"}, - {'HTTP_X_REQUEST_START' => "t=1409850011020.236"}, - {'HTTP_X_REQUEST_START' => "t=1409850011020236.0"} + {'HTTP_X_REQUEST_START' => 't=1409849996.2152882'}, + {'HTTP_X_REQUEST_START' => 't=1409850011020.236'}, + {'HTTP_X_REQUEST_START' => 't=1409850011020236.0'} ] end diff --git a/test/performance/suites/redis.rb b/test/performance/suites/redis.rb index b8651fb0e5..6a41db4e0d 100644 --- a/test/performance/suites/redis.rb +++ b/test/performance/suites/redis.rb @@ -10,7 +10,7 @@ class RedisTest < Performance::TestCase def test_no_args with_config(:'transaction_tracer.record_redis_arguments' => true) do - command = ["lonely_command"] + command = ['lonely_command'] measure do NewRelic::Agent::Datastores::Redis.format_command(command) end @@ -28,7 +28,7 @@ def test_args def test_long_args with_config(:'transaction_tracer.record_redis_arguments' => true) do - commands = ["loooooong_command", "a" * 100, "b" * 100, "c" * 100] + commands = ['loooooong_command', 'a' * 100, 'b' * 100, 'c' * 100] measure do NewRelic::Agent::Datastores::Redis.format_command(commands) end @@ -38,8 +38,8 @@ def test_long_args def test_pipelined with_config(:'transaction_tracer.record_redis_arguments' => true) do pipeline = [ - ["first", "a" * 100, "b" * 100, "c" * 100], - ["second", "a" * 100, "b" * 100, "c" * 100] + ['first', 'a' * 100, 'b' * 100, 'c' * 100], + ['second', 'a' * 100, 'b' * 100, 'c' * 100] ] measure do diff --git a/test/performance/suites/rules_engine.rb b/test/performance/suites/rules_engine.rb index 5b1702d9ad..99961010e8 100644 --- a/test/performance/suites/rules_engine.rb +++ b/test/performance/suites/rules_engine.rb @@ -7,11 +7,11 @@ def setup @basic_rule_specs = { "transaction_segment_terms": [ { - "prefix": "WebTransaction/Custom", + "prefix": 'WebTransaction/Custom', "terms": %w[one two three] }, { - "prefix": "WebTransaction/Uri", + "prefix": 'WebTransaction/Uri', "terms": %w[seven eight nine] } ] @@ -27,9 +27,9 @@ def test_rules_engine_init_transaction_rules def test_rules_engine_rename_transaction_rules measure do rules_engine = NewRelic::Agent::RulesEngine.create_transaction_rules(@basic_rule_specs) - rules_engine.rename("WebTransaction/Uri/one/two/seven/user/nine/account") - rules_engine.rename("WebTransaction/Custom/one/two/seven/user/nine/account") - rules_engine.rename("WebTransaction/Other/one/two/foo/bar") + rules_engine.rename('WebTransaction/Uri/one/two/seven/user/nine/account') + rules_engine.rename('WebTransaction/Custom/one/two/seven/user/nine/account') + rules_engine.rename('WebTransaction/Other/one/two/foo/bar') end end end diff --git a/test/performance/suites/rum_autoinsertion.rb b/test/performance/suites/rum_autoinsertion.rb index 112faa40ff..049b1d64a4 100644 --- a/test/performance/suites/rum_autoinsertion.rb +++ b/test/performance/suites/rum_autoinsertion.rb @@ -26,7 +26,7 @@ def setup attr_accessor :text def call(*_) - [200, {"Content-Type" => "text/html"}, [text]] + [200, {'Content-Type' => 'text/html'}, [text]] end end.new diff --git a/test/performance/suites/thread_profiling.rb b/test/performance/suites/thread_profiling.rb index f6e5e4b8ba..f25e753517 100644 --- a/test/performance/suites/thread_profiling.rb +++ b/test/performance/suites/thread_profiling.rb @@ -61,11 +61,11 @@ def teardown rescue Exception => e if e.message.include?('Deadlock') Thread.list.select(&:alive?).each do |t| - STDERR.puts "*" * 80 + STDERR.puts '*' * 80 STDERR.puts "Live thread: #{t.inspect}" - STDERR.puts "Backtrace:" + STDERR.puts 'Backtrace:' STDERR.puts (t.backtrace || []).join("\n") - STDERR.puts "*" * 80 + STDERR.puts '*' * 80 end end diff --git a/test/performance/suites/trace_context.rb b/test/performance/suites/trace_context.rb index 6af79c9749..87ac96df9e 100644 --- a/test/performance/suites/trace_context.rb +++ b/test/performance/suites/trace_context.rb @@ -9,8 +9,8 @@ class TraceContext < Performance::TestCase CONFIG = { :'distributed_tracing.enabled' => true, - :account_id => "190", - :primary_application_id => "46954", + :account_id => '190', + :primary_application_id => '46954', :disable_harvest_thread => true } @@ -23,7 +23,7 @@ def test_parse measure do NewRelic::Agent::DistributedTracing::TraceContext.parse( \ carrier: carrier, - trace_state_entry_key: "33@nr" + trace_state_entry_key: '33@nr' ) end end diff --git a/test/performance/suites/trace_context_request_monitor.rb b/test/performance/suites/trace_context_request_monitor.rb index 788171c73c..65828cf553 100644 --- a/test/performance/suites/trace_context_request_monitor.rb +++ b/test/performance/suites/trace_context_request_monitor.rb @@ -17,9 +17,9 @@ class TraceContextRequestMonitor < Performance::TestCase :'cross_application_tracer.enabled' => false, :'distributed_tracing.enabled' => true, :encoding_key => "\0", - :account_id => "190", - :primary_application_id => "46954", - :trusted_account_key => "99999" + :account_id => '190', + :primary_application_id => '46954', + :trusted_account_key => '99999' } def setup diff --git a/test/performance/suites/trace_execution_scoped.rb b/test/performance/suites/trace_execution_scoped.rb index c7df40a459..afd44a9f1d 100644 --- a/test/performance/suites/trace_execution_scoped.rb +++ b/test/performance/suites/trace_execution_scoped.rb @@ -5,7 +5,7 @@ class TestClass def method_1 trace_execution_scoped(%w[a b]) do - "hi" + 'hi' end end end diff --git a/test/performance/suites/transaction_tracing.rb b/test/performance/suites/transaction_tracing.rb index 96f76a3030..77cca8bcd3 100644 --- a/test/performance/suites/transaction_tracing.rb +++ b/test/performance/suites/transaction_tracing.rb @@ -3,12 +3,12 @@ # frozen_string_literal: true class TransactionTracingPerfTests < Performance::TestCase - FAILURE_MESSAGE = "O_o" + FAILURE_MESSAGE = 'O_o' - BOO = "boo" - HOO = "hoo" - OH = "oh" - NO = "no" + BOO = 'boo' + HOO = 'hoo' + OH = 'oh' + NO = 'no' def klass(instrument) Class.new do @@ -122,7 +122,7 @@ def test_failure end end - TXNAME = "Controller/Blogs/index".freeze + TXNAME = 'Controller/Blogs/index'.freeze def test_start_with_tracer_start measure do @@ -142,9 +142,9 @@ def test_short_transaction_with_datastore_segment in_transaction do |txn| txn.sampled = true segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "insert", - collection: "Blog" + product: 'SQLite', + operation: 'insert', + collection: 'Blog' ) segment.finish end @@ -157,9 +157,9 @@ def test_short_transaction_with_datastore_segment_in_thread txn.sampled = true thread = Thread.new do segment = NewRelic::Agent::Tracer.start_datastore_segment( - product: "SQLite", - operation: "insert", - collection: "Blog" + product: 'SQLite', + operation: 'insert', + collection: 'Blog' ) segment.finish end @@ -173,9 +173,9 @@ def test_short_transaction_with_external_request_segment in_transaction do |txn| txn.sampled = true segment = NewRelic::Agent::Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET' ) segment.finish end @@ -187,9 +187,9 @@ def test_short_transaction_with_external_request_segment_in_thread in_transaction do |txn| txn.sampled = true segment = NewRelic::Agent::Tracer.start_external_request_segment( - library: "Net::HTTP", - uri: "http://remotehost.com/blogs/index", - procedure: "GET" + library: 'Net::HTTP', + uri: 'http://remotehost.com/blogs/index', + procedure: 'GET' ) segment.finish end diff --git a/test/script/external_server.rb b/test/script/external_server.rb index e66e0f2c2a..6b38cd0f78 100755 --- a/test/script/external_server.rb +++ b/test/script/external_server.rb @@ -18,14 +18,14 @@ server.reset server.run -puts JSON.dump({:message => "started"}) +puts JSON.dump({:message => 'started'}) while message = JSON.parse(gets) - case message["command"] - when "shutdown" + case message['command'] + when 'shutdown' server.stop exit(0) - when "add_headers" - server.override_response_headers(message["payload"]) + when 'add_headers' + server.override_response_headers(message['payload']) end end diff --git a/test/script/path_hash.rb b/test/script/path_hash.rb index 6df63c3cfc..dfdc8a8c52 100755 --- a/test/script/path_hash.rb +++ b/test/script/path_hash.rb @@ -26,7 +26,7 @@ def usage identifier = "#{app_name};#{transaction_name}" md5sum = Digest::MD5.digest(identifier) - low4_of_md5 = md5sum.unpack("@12N").first + low4_of_md5 = md5sum.unpack('@12N').first rotated_path_hash = ((path_hash << 1) | (path_hash >> 31)) & 0xffffffff @@ -39,7 +39,7 @@ def usage puts '' puts "D: Input path_hash: 0x#{path_hash.to_s(16).rjust(8, '0')} (0b#{path_hash.to_s(2).rjust(32, '0')})" puts "E: Rotated E: 0x#{rotated_path_hash.to_s(16).rjust(8, '0')} (0b#{rotated_path_hash.to_s(2).rjust(32, '0')})" - puts "" + puts '' puts "F: XOR(D, F): 0x#{xor_result.to_s(16).rjust(8, '0')} (0b#{xor_result.to_s(2).rjust(32, '0')})" puts '--' diff --git a/test/script/run_tests b/test/script/run_tests index b5c622387b..9d9ad6aaaf 100755 --- a/test/script/run_tests +++ b/test/script/run_tests @@ -126,23 +126,39 @@ run_env_tests() { # organizes the args for the unit tests and calls the command run_unit_tests() { + find_test_file "$1" "new_relic" if [[ -n "$2" ]]; then # echo "running file and name" set_test_opts $2 - TEST="$1" TESTOPTS="$test_opts_result" unit_command; + TEST=${TEST:-"$1"} TESTOPTS="$test_opts_result" unit_command; elif [[ -n "$1" && "$1" =~ ^test_ ]]; then # echo "running name" set_test_opts $1 TESTOPTS="$test_opts_result" unit_command; elif [[ -n "$1" ]]; then # echo "running file" - TEST="$1" unit_command; + TEST=${TEST:-"$1"} unit_command; else # echo "running unit tests" unit_command; fi } +# If the first argument doesn't contain a slash or start with test_ +# then assume it is a partial filename match. Find the file. +find_test_file() { + if [[ "$1" != */* && "$1" != test* ]]; then + file=$(find "test/$2" -name "*$1*" -print -quit) + if [[ "$file" == "" ]]; then + echo "Could not find a file match for '$1'" + exit + else + echo "Testing against file '$file'..." + TEST="$file" + fi + fi +} + # helper method to output the help info and error and then exit the script output_arg_error(){ help @@ -184,4 +200,4 @@ while getopts "huemq" option; do esac done -help \ No newline at end of file +help diff --git a/test/simplecov_test_helper.rb b/test/simplecov_test_helper.rb index 22aabf7b96..18aa49e3af 100644 --- a/test/simplecov_test_helper.rb +++ b/test/simplecov_test_helper.rb @@ -8,7 +8,7 @@ SIMPLECOV_MIN_RUBY_VERSION = '2.7.0' begin - require 'simplecov' if RUBY_VERSION >= SIMPLECOV_MIN_RUBY_VERSION && ENV["VERBOSE_TEST_OUTPUT"] + require 'simplecov' if RUBY_VERSION >= SIMPLECOV_MIN_RUBY_VERSION && ENV['VERBOSE_TEST_OUTPUT'] rescue LoadError => e puts puts "SimpleCov requested by Ruby #{RUBY_VERSION} which is >=#{SIMPLECOV_MIN_RUBY_VERSION} " diff --git a/test/test_helper.rb b/test/test_helper.rb index 01f57ffcf8..af692b3444 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -32,18 +32,18 @@ module NewRelic; TEST = true; end unless defined? NewRelic::TEST # will be skipped. if ENV['NO_RAILS'] - puts "Running tests in standalone mode without Rails." + puts 'Running tests in standalone mode without Rails.' require 'newrelic_rpm' else begin # try loading rails via attempted loading of config/environment.rb require './config/environment' require 'newrelic_rpm' - puts "Running in standalone mode with Rails" if ENV['VERBOSE_TEST_OUTPUT'] + puts 'Running in standalone mode with Rails' if ENV['VERBOSE_TEST_OUTPUT'] rescue LoadError # if there was not a file at config/environment.rb fall back to running without it require 'newrelic_rpm' - puts "Running in standalone mode without Rails" if ENV['VERBOSE_TEST_OUTPUT'] + puts 'Running in standalone mode without Rails' if ENV['VERBOSE_TEST_OUTPUT'] end end