password_policy_spec.rb 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. require 'rails_helper'
  3. RSpec.describe PasswordPolicy do
  4. subject(:instance) { described_class.new('some_password') }
  5. let(:passing_job_class) { make_job_class(valid: true, applicable: true, error: 'passing job') }
  6. let(:failing_job_class) { make_job_class(valid: false, applicable: true, error: 'failing job') }
  7. let(:another_failing_job_class) { make_job_class(valid: false, applicable: true, error: 'another failing job') }
  8. let(:not_applicable_job_class) { make_job_class(valid: false, applicable: false, error: 'not applicable job') }
  9. describe '#valid?' do
  10. it 'returns true when all backends pass' do
  11. instance.backends = Set.new [passing_job_class]
  12. expect(instance).to be_valid
  13. end
  14. it 'returns false when one of backends fail' do
  15. instance.backends = Set.new [passing_job_class, failing_job_class]
  16. expect(instance).not_to be_valid
  17. end
  18. it 'returns true when one of backends fail but is not applicable' do
  19. instance.backends = Set.new [passing_job_class, not_applicable_job_class]
  20. expect(instance).to be_valid
  21. end
  22. end
  23. describe '#error' do
  24. it 'returns nil when no errors present' do
  25. instance.backends = Set.new
  26. expect(instance.error).to be_nil
  27. end
  28. it 'returns Array with the error when an error is present' do
  29. instance.backends = Set.new [failing_job_class]
  30. expect(instance.errors.first).to eq(['failing job'])
  31. end
  32. it 'returns Array with the first error when multiple errors are present' do
  33. instance.backends = Set.new [another_failing_job_class, failing_job_class]
  34. expect(instance.errors.first).to eq(['another failing job'])
  35. end
  36. end
  37. describe '#errors' do
  38. it 'returns empty Array when all backends pass' do
  39. instance.backends = Set.new [passing_job_class]
  40. expect(instance.errors).to be_a(Array).and(be_blank)
  41. end
  42. it 'returns an Array of Arrays when one of backends fail' do
  43. instance.backends = Set.new [failing_job_class]
  44. expect(instance.errors.first).to be_a(Array)
  45. end
  46. end
  47. def make_job_class(valid:, applicable:, error:)
  48. klass = Class.new(PasswordPolicy::Backend)
  49. klass.define_method(:valid?) { valid }
  50. klass.define_singleton_method(:applicable?) { applicable }
  51. klass.define_method(:error) { [error] }
  52. klass
  53. end
  54. end