1
0

base_controller_spec.rb 2.3 KB

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