rails_helper.rb 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  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. # NOTE: we switched registrations mode to closed by default, but the specs
  123. # very heavily rely on having it enabled by default, as it relies on users
  124. # being approved by default except in select cases where explicitly testing
  125. # other registration modes
  126. # Also needs to be set per-example here because of the database cleaner.
  127. Setting.registrations_mode = 'open'
  128. example.run
  129. end
  130. self.use_transactional_tests = true
  131. end
  132. config.around :each, type: :search do |example|
  133. search_data_manager.populate_indexes
  134. example.run
  135. search_data_manager.remove_indexes
  136. end
  137. config.before(:each) do |example|
  138. unless example.metadata[:paperclip_processing]
  139. allow_any_instance_of(Paperclip::Attachment).to receive(:post_process).and_return(true) # rubocop:disable RSpec/AnyInstance
  140. end
  141. end
  142. config.after :each do
  143. Rails.cache.clear
  144. redis.del(redis.keys)
  145. end
  146. # Assign types based on dir name for non-inferred types
  147. config.define_derived_metadata(file_path: %r{/spec/}) do |metadata|
  148. unless metadata.key?(:type)
  149. match = metadata[:location].match(%r{/spec/([^/]+)/})
  150. metadata[:type] = match[1].singularize.to_sym
  151. end
  152. end
  153. end
  154. RSpec::Sidekiq.configure do |config|
  155. config.warn_when_jobs_not_processed_by_sidekiq = false
  156. end
  157. RSpec::Matchers.define_negated_matcher :not_change, :change
  158. def request_fixture(name)
  159. Rails.root.join('spec', 'fixtures', 'requests', name).read
  160. end
  161. def attachment_fixture(name)
  162. Rails.root.join('spec', 'fixtures', 'files', name).open
  163. end
  164. def stub_stdout
  165. # TODO: Is there a bettery way to:
  166. # - Avoid CLI command output being printed out
  167. # - Allow rspec to assert things against STDOUT
  168. # - Avoid disabling stdout for other desirable output (deprecation warnings, for example)
  169. allow($stdout).to receive(:write)
  170. end
  171. def stub_reset_connection_pools
  172. # TODO: Is there a better way to correctly run specs without stubbing this?
  173. # (Avoids reset_connection_pools! in test env)
  174. allow(ActiveRecord::Base).to receive(:establish_connection)
  175. allow(RedisConfiguration).to receive(:establish_pool)
  176. end
  177. def stub_jsonld_contexts!
  178. stub_request(:get, 'https://www.w3.org/ns/activitystreams').to_return(request_fixture('json-ld.activitystreams.txt'))
  179. stub_request(:get, 'https://w3id.org/identity/v1').to_return(request_fixture('json-ld.identity.txt'))
  180. stub_request(:get, 'https://w3id.org/security/v1').to_return(request_fixture('json-ld.security.txt'))
  181. end