rails_helper.rb 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. # frozen_string_literal: true
  2. ENV['RAILS_ENV'] ||= 'test'
  3. # This needs to be defined before Rails is initialized
  4. RUN_SYSTEM_SPECS = ENV.fetch('RUN_SYSTEM_SPECS', false)
  5. if RUN_SYSTEM_SPECS
  6. STREAMING_PORT = ENV.fetch('TEST_STREAMING_PORT', '4020')
  7. ENV['STREAMING_API_BASE_URL'] = "http://localhost:#{STREAMING_PORT}"
  8. end
  9. require File.expand_path('../config/environment', __dir__)
  10. abort('The Rails environment is running in production mode!') if Rails.env.production?
  11. require 'spec_helper'
  12. require 'rspec/rails'
  13. require 'webmock/rspec'
  14. require 'paperclip/matchers'
  15. require 'capybara/rspec'
  16. require 'chewy/rspec'
  17. Dir[Rails.root.join('spec', 'support', '**', '*.rb')].each { |f| require f }
  18. ActiveRecord::Migration.maintain_test_schema!
  19. WebMock.disable_net_connect!(allow: Chewy.settings[:host], allow_localhost: RUN_SYSTEM_SPECS)
  20. Sidekiq::Testing.inline!
  21. Sidekiq.logger = nil
  22. # System tests config
  23. DatabaseCleaner.strategy = [:deletion]
  24. streaming_server_manager = StreamingServerManager.new
  25. Devise::Test::ControllerHelpers.module_eval do
  26. alias_method :original_sign_in, :sign_in
  27. def sign_in(resource, _deprecated = nil, scope: nil)
  28. original_sign_in(resource, scope: scope)
  29. SessionActivation.deactivate warden.cookies.signed['_session_id']
  30. warden.cookies.signed['_session_id'] = {
  31. value: resource.activate_session(warden.request),
  32. expires: 1.year.from_now,
  33. httponly: true,
  34. }
  35. end
  36. end
  37. module SignedRequestHelpers
  38. def get(path, headers: nil, sign_with: nil, **args)
  39. return super path, headers: headers, **args if sign_with.nil?
  40. headers ||= {}
  41. headers['Date'] = Time.now.utc.httpdate
  42. headers['Host'] = ENV.fetch('LOCAL_DOMAIN')
  43. signed_headers = headers.merge('(request-target)' => "get #{path}").slice('(request-target)', 'Host', 'Date')
  44. key_id = ActivityPub::TagManager.instance.key_uri_for(sign_with)
  45. keypair = sign_with.keypair
  46. signed_string = signed_headers.map { |key, value| "#{key.downcase}: #{value}" }.join("\n")
  47. signature = Base64.strict_encode64(keypair.sign(OpenSSL::Digest.new('SHA256'), signed_string))
  48. headers['Signature'] = "keyId=\"#{key_id}\",algorithm=\"rsa-sha256\",headers=\"#{signed_headers.keys.join(' ').downcase}\",signature=\"#{signature}\""
  49. super path, headers: headers, **args
  50. end
  51. end
  52. RSpec.configure do |config|
  53. # This is set before running spec:system, see lib/tasks/tests.rake
  54. config.filter_run_excluding type: :system unless RUN_SYSTEM_SPECS
  55. config.fixture_path = Rails.root.join('spec', 'fixtures')
  56. config.use_transactional_fixtures = true
  57. config.order = 'random'
  58. config.infer_spec_type_from_file_location!
  59. config.filter_rails_from_backtrace!
  60. config.define_derived_metadata(file_path: Regexp.new('spec/lib/mastodon/cli')) do |metadata|
  61. metadata[:type] = :cli
  62. end
  63. config.include Devise::Test::ControllerHelpers, type: :controller
  64. config.include Devise::Test::ControllerHelpers, type: :helper
  65. config.include Devise::Test::ControllerHelpers, type: :view
  66. config.include Devise::Test::IntegrationHelpers, type: :feature
  67. config.include Devise::Test::IntegrationHelpers, type: :request
  68. config.include Paperclip::Shoulda::Matchers
  69. config.include ActiveSupport::Testing::TimeHelpers
  70. config.include Chewy::Rspec::Helpers
  71. config.include Redisable
  72. config.include SignedRequestHelpers, type: :request
  73. config.before :each, type: :cli do
  74. stub_stdout
  75. stub_reset_connection_pools
  76. end
  77. config.before :each, type: :feature do
  78. Capybara.current_driver = :rack_test
  79. end
  80. config.before :each, type: :controller do
  81. stub_jsonld_contexts!
  82. end
  83. config.before :each, type: :service do
  84. stub_jsonld_contexts!
  85. end
  86. config.before :suite do
  87. if RUN_SYSTEM_SPECS
  88. Webpacker.compile
  89. streaming_server_manager.start(port: STREAMING_PORT)
  90. end
  91. end
  92. config.after :suite do
  93. streaming_server_manager.stop
  94. end
  95. config.around :each, type: :system do |example|
  96. # driven_by :selenium, using: :chrome, screen_size: [1600, 1200]
  97. driven_by :selenium, using: :headless_chrome, screen_size: [1600, 1200]
  98. # The streaming server needs access to the database
  99. # but with use_transactional_tests every transaction
  100. # is rolled-back, so the streaming server never sees the data
  101. # So we disable this feature for system tests, and use DatabaseCleaner to clean
  102. # the database tables between each test
  103. self.use_transactional_tests = false
  104. DatabaseCleaner.cleaning do
  105. example.run
  106. end
  107. self.use_transactional_tests = true
  108. end
  109. config.before(:each) do |example|
  110. unless example.metadata[:paperclip_processing]
  111. allow_any_instance_of(Paperclip::Attachment).to receive(:post_process).and_return(true) # rubocop:disable RSpec/AnyInstance
  112. end
  113. end
  114. config.after :each do
  115. Rails.cache.clear
  116. redis.del(redis.keys)
  117. end
  118. # Assign types based on dir name for non-inferred types
  119. config.define_derived_metadata(file_path: %r{/spec/}) do |metadata|
  120. unless metadata.key?(:type)
  121. match = metadata[:location].match(%r{/spec/([^/]+)/})
  122. metadata[:type] = match[1].singularize.to_sym
  123. end
  124. end
  125. end
  126. RSpec::Sidekiq.configure do |config|
  127. config.warn_when_jobs_not_processed_by_sidekiq = false
  128. end
  129. RSpec::Matchers.define_negated_matcher :not_change, :change
  130. def request_fixture(name)
  131. Rails.root.join('spec', 'fixtures', 'requests', name).read
  132. end
  133. def attachment_fixture(name)
  134. Rails.root.join('spec', 'fixtures', 'files', name).open
  135. end
  136. def stub_stdout
  137. # TODO: Is there a bettery way to:
  138. # - Avoid CLI command output being printed out
  139. # - Allow rspec to assert things against STDOUT
  140. # - Avoid disabling stdout for other desirable output (deprecation warnings, for example)
  141. allow($stdout).to receive(:write)
  142. end
  143. def stub_reset_connection_pools
  144. # TODO: Is there a better way to correctly run specs without stubbing this?
  145. # (Avoids reset_connection_pools! in test env)
  146. allow(ActiveRecord::Base).to receive(:establish_connection)
  147. allow(RedisConfiguration).to receive(:establish_pool)
  148. end
  149. def stub_jsonld_contexts!
  150. stub_request(:get, 'https://www.w3.org/ns/activitystreams').to_return(request_fixture('json-ld.activitystreams.txt'))
  151. stub_request(:get, 'https://w3id.org/identity/v1').to_return(request_fixture('json-ld.identity.txt'))
  152. stub_request(:get, 'https://w3id.org/security/v1').to_return(request_fixture('json-ld.security.txt'))
  153. end