rails_helper.rb 6.9 KB

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