base_controller_spec.rb 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. # frozen_string_literal: true
  2. require 'rails_helper'
  3. describe Api::BaseController do
  4. before do
  5. stub_const('FakeService', Class.new)
  6. end
  7. controller do
  8. def success
  9. head 200
  10. end
  11. def error
  12. FakeService.new
  13. end
  14. end
  15. it 'returns private cache control headers by default' do
  16. routes.draw { get 'success' => 'api/base#success' }
  17. get :success
  18. expect(response.headers['Cache-Control']).to include('private, no-store')
  19. end
  20. describe 'forgery protection' do
  21. before do
  22. routes.draw { post 'success' => 'api/base#success' }
  23. end
  24. it 'does not protect from forgery' do
  25. ActionController::Base.allow_forgery_protection = true
  26. post 'success'
  27. expect(response).to have_http_status(200)
  28. end
  29. end
  30. describe 'non-functional accounts handling' do
  31. let(:user) { Fabricate(:user) }
  32. let(:token) { Fabricate(:accessible_access_token, resource_owner_id: user.id, scopes: 'read') }
  33. controller do
  34. before_action :require_user!
  35. end
  36. before do
  37. routes.draw { post 'success' => 'api/base#success' }
  38. allow(controller).to receive(:doorkeeper_token) { token }
  39. end
  40. it 'returns http forbidden for unconfirmed accounts' do
  41. user.update(confirmed_at: nil)
  42. post 'success'
  43. expect(response).to have_http_status(403)
  44. end
  45. it 'returns http forbidden for pending accounts' do
  46. user.update(approved: false)
  47. post 'success'
  48. expect(response).to have_http_status(403)
  49. end
  50. it 'returns http forbidden for disabled accounts' do
  51. user.update(disabled: true)
  52. post 'success'
  53. expect(response).to have_http_status(403)
  54. end
  55. it 'returns http forbidden for suspended accounts' do
  56. user.account.suspend!
  57. post 'success'
  58. expect(response).to have_http_status(403)
  59. end
  60. end
  61. describe 'error handling' do
  62. before do
  63. routes.draw { get 'error' => 'api/base#error' }
  64. end
  65. {
  66. ActiveRecord::RecordInvalid => 422,
  67. Mastodon::ValidationError => 422,
  68. ActiveRecord::RecordNotFound => 404,
  69. Mastodon::UnexpectedResponseError => 503,
  70. HTTP::Error => 503,
  71. OpenSSL::SSL::SSLError => 503,
  72. Mastodon::NotPermittedError => 403,
  73. }.each do |error, code|
  74. it "Handles error class of #{error}" do
  75. allow(FakeService).to receive(:new).and_raise(error)
  76. get 'error'
  77. expect(response).to have_http_status(code)
  78. expect(FakeService).to have_received(:new)
  79. end
  80. end
  81. end
  82. end