index
int64
0
0
repo_id
stringclasses
829 values
file_path
stringlengths
34
254
content
stringlengths
6
5.38M
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/sign_in/delete_expired_sessions_job_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SignIn::DeleteExpiredSessionsJob do let!(:expired_oauth_session) { create(:oauth_session, refresh_expiration: 3.days.ago) } let!(:active_oauth_session) { create(:oauth_session, refresh_expiration: 3.days.from_now) } describe '#perform' do let(:job) { SignIn::DeleteExpiredSessionsJob.new } it 'deletes expired oauth sessions' do expect { job.perform }.to change(SignIn::OAuthSession, :count).by(-1) end it 'does not delete active oauth sessions' do expect { job.perform }.not_to change(active_oauth_session, :reload) end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/sign_in/certificate_checker_job_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SignIn::CertificateCheckerJob, type: :job do subject(:job) { described_class.new } before do allow(Rails.logger).to receive(:warn) end describe '#perform' do %i[service_account_config client_config].each do |factory_name| context "for #{factory_name.to_s.humanize} configs" do let(:config) { create(factory_name) } context 'with no certificates' do it 'does not log any alerts' do job.perform expect(Rails.logger).not_to have_received(:warn) end end context 'with only an expiring_later certificate' do let(:expiring_later_certificate) { create(:sign_in_certificate, :expiring_later) } before do config.certs << expiring_later_certificate config.save(validate: false) end it 'does not log any alerts' do job.perform expect(Rails.logger).not_to have_received(:warn) end end context 'with an expired certificate' do let(:expired_certificate) { build(:sign_in_certificate, :expired) } before do expired_certificate.save(validate: false) config_certificate = config.config_certificates.new(cert: expired_certificate, config:) config_certificate.save(validate: false) config.save(validate: false) end it 'logs an alert for the expired certificate' do job.perform expect(Rails.logger).to have_received(:warn).with( '[SignIn] [CertificateChecker] expired_certificate', hash_including( config_type: config.class.name, config_id: config.id, config_description: config.description, certificate_subject: expired_certificate.subject.to_s, certificate_issuer: expired_certificate.issuer.to_s, certificate_serial: expired_certificate.serial.to_s, certificate_not_before: expired_certificate.not_before.to_s, certificate_not_after: expired_certificate.not_after.to_s ) ) end context 'and an expiring_later certificate exists' do let(:expiring_later_certificate) { create(:sign_in_certificate, :expiring_later) } before do config.certs << expiring_later_certificate config.save(validate: false) end it 'does not log an alert for the expired certificate' do job.perform expect(Rails.logger).not_to have_received(:warn).with( '[SignIn] [CertificateChecker] expired_certificate', anything ) end end context 'and an expiring_soon certificate exists' do let(:expiring_soon_certificate) { create(:sign_in_certificate, :expiring_soon) } before do config.certs << expiring_soon_certificate config.save(validate: false) end it 'does not log an alert for the expired certificate' do job.perform expect(Rails.logger).not_to have_received(:warn).with( '[SignIn] [CertificateChecker] expired_certificate', anything ) end end end context 'with an expiring_soon certificate' do let(:expiring_soon_certificate) { create(:sign_in_certificate, :expiring_soon) } before do config.certs << expiring_soon_certificate config.save(validate: false) end it 'logs an alert for the expiring_soon certificate' do job.perform expect(Rails.logger).to have_received(:warn).with( '[SignIn] [CertificateChecker] expiring_soon_certificate', hash_including( config_type: config.class.name, config_id: config.id, config_description: config.description, certificate_subject: expiring_soon_certificate.subject.to_s, certificate_issuer: expiring_soon_certificate.issuer.to_s, certificate_serial: expiring_soon_certificate.serial.to_s, certificate_not_before: expiring_soon_certificate.not_before.to_s, certificate_not_after: expiring_soon_certificate.not_after.to_s ) ) end context 'and an expiring_later certificate exists' do let(:expiring_later_certificate) { create(:sign_in_certificate, :expiring_later) } before do config.certs << expiring_later_certificate config.save(validate: false) end it 'does not log an alert for the expiring_soon certificate' do job.perform expect(Rails.logger).not_to have_received(:warn).with( '[SignIn] [CertificateChecker] expiring_soon_certificate', anything ) end end context 'and an expired certificate exists' do let(:expired_certificate) { build(:sign_in_certificate, :expired) } before do expired_certificate.save(validate: false) config_certificate = config.config_certificates.new(cert: expired_certificate, config:) config_certificate.save(validate: false) config.save(validate: false) end it 'logs only for the expiring_soon certificate' do job.perform expect(Rails.logger).to have_received(:warn).with( '[SignIn] [CertificateChecker] expiring_soon_certificate', hash_including(certificate_serial: expiring_soon_certificate.serial.to_s) ) expect(Rails.logger).not_to have_received(:warn).with( '[SignIn] [CertificateChecker] expired_certificate', anything ) end end end context 'with multiple expired certificates' do let(:expired_cert1) { build(:sign_in_certificate, :expired) } let(:expired_cert2) { build(:sign_in_certificate, :expired) } before do expired_cert1.save(validate: false) expired_cert2.save(validate: false) config_certificate1 = config.config_certificates.new(cert: expired_cert1, config:) config_certificate2 = config.config_certificates.new(cert: expired_cert2, config:) config_certificate1.save(validate: false) config_certificate2.save(validate: false) config.save(validate: false) end it 'logs an alert for each expired certificate when no active (expiring_later & expiring_soon) exist' do job.perform expect(Rails.logger).to have_received(:warn).with( '[SignIn] [CertificateChecker] expired_certificate', hash_including(certificate_serial: expired_cert1.serial.to_s) ) expect(Rails.logger).to have_received(:warn).with( '[SignIn] [CertificateChecker] expired_certificate', hash_including(certificate_serial: expired_cert2.serial.to_s) ) end end end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/bgs/submit_form686c_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'sidekiq/job_retry' RSpec.describe BGS::SubmitForm686cJob, type: :job do let(:job) { subject.perform(user.uuid, dependency_claim.id, encrypted_vet_info) } let(:user) { create(:evss_user, :loa3) } let(:dependency_claim) { create(:dependency_claim) } let(:all_flows_payload) { build(:form_686c_674_kitchen_sink) } let(:birth_date) { '1809-02-12' } let(:client_stub) { instance_double(BGS::Form686c) } let(:vet_info) do { 'veteran_information' => { 'full_name' => { 'first' => 'WESLEY', 'middle' => nil, 'last' => 'FORD' }, 'common_name' => user.common_name, 'participant_id' => '600061742', 'uuid' => user.uuid, 'email' => user.email, 'va_profile_email' => user.va_profile_email, 'ssn' => '796043735', 'va_file_number' => '796043735', 'icn' => user.icn, 'birth_date' => birth_date } } end let(:encrypted_vet_info) { KmsEncrypted::Box.new.encrypt(vet_info.to_json) } let(:user_struct) do nested_info = vet_info['veteran_information'] OpenStruct.new( first_name: nested_info['full_name']['first'], last_name: nested_info['full_name']['last'], middle_name: nested_info['full_name']['middle'], ssn: nested_info['ssn'], email: nested_info['email'], va_profile_email: nested_info['va_profile_email'], participant_id: nested_info['participant_id'], icn: nested_info['icn'], uuid: nested_info['uuid'], common_name: nested_info['common_name'] ) end let(:vanotify) { double(send_email: true) } before do allow_any_instance_of(SavedClaim::DependencyClaim).to receive(:submittable_674?).and_return(false) allow(OpenStruct).to receive(:new) .with(hash_including(icn: vet_info['veteran_information']['icn'])) .and_return(user_struct) allow_any_instance_of(SavedClaim::DependencyClaim).to receive(:pdf_overflow_tracking) end context 'successfully' do it 'calls #submit for 686c submission' do expect(BGS::Form686c).to receive(:new).with(user_struct, dependency_claim).and_return(client_stub) expect(client_stub).to receive(:submit).once expect { job }.not_to raise_error end it 'sends confirmation email for 686c only' do expect(BGS::Form686c).to receive(:new).with(user_struct, dependency_claim).and_return(client_stub) expect(client_stub).to receive(:submit).once api_key = 'fake_secret' callback_options = { callback_klass: 'Dependents::NotificationCallback', callback_metadata: { email_template_id: 'fake_received686', email_type: :received686, form_id: '686C-674', claim_id: dependency_claim.id, saved_claim_id: dependency_claim.id, service_name: 'dependents' } } personalization = { 'confirmation_number' => dependency_claim.confirmation_number, 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'first_name' => 'WESLEY' } expect(VaNotify::Service).to receive(:new).with(api_key, callback_options).and_return(vanotify) expect(vanotify).to receive(:send_email).with( { email_address: user.va_profile_email, template_id: 'fake_received686', personalisation: personalization }.compact ) expect { job }.not_to raise_error end it 'does not send confirmation email for 686c_674 combo' do allow_any_instance_of(SavedClaim::DependencyClaim).to receive(:submittable_674?).and_return(true) expect(BGS::Form686c).to receive(:new).with(user_struct, dependency_claim).and_return(client_stub) expect(client_stub).to receive(:submit).once expect(VANotify::EmailJob).not_to receive(:perform_async) expect { job }.not_to raise_error end end context 'Claim is submittable_674' do it 'enqueues SubmitForm674Job' do allow_any_instance_of(SavedClaim::DependencyClaim).to receive(:submittable_674?).and_return(true) expect(BGS::Form686c).to receive(:new).with(user_struct, dependency_claim).and_return(client_stub) expect(client_stub).to receive(:submit).once expect(BGS::SubmitForm674Job).to receive(:perform_async).with(user.uuid, dependency_claim.id, encrypted_vet_info, an_instance_of(String)) expect { job }.not_to raise_error end end context 'Claim is not submittable_674' do it 'does not enqueue SubmitForm674Job' do expect(BGS::Form686c).to receive(:new).with(user_struct, dependency_claim).and_return(client_stub) expect(client_stub).to receive(:submit).once expect(BGS::SubmitForm674Job).not_to receive(:perform_async) expect { job }.not_to raise_error end end context 'when submission raises error' do it 'raises error' do expect(BGS::Form686c).to receive(:new).with(user_struct, dependency_claim).and_return(client_stub) expect(client_stub).to receive(:submit).and_raise(BGS::SubmitForm686cJob::Invalid686cClaim) expect { job }.to raise_error(BGS::SubmitForm686cJob::Invalid686cClaim) end it 'filters based on error cause' do expect(BGS::Form686c).to receive(:new).with(user_struct, dependency_claim).and_return(client_stub) expect(client_stub).to receive(:submit) { raise_nested_err } expect { job }.to raise_error(Sidekiq::JobRetry::Skip) end end # submit_forms looks like it's dead code. It's not called by subject and I'm not finding it using # vscode search. # TODO: Research and remove if not needed. # context 'submit_forms' do # end # send_confirmation_email looks like it's dead code. It's not called by subject. A further indication # that it's dead code is it does not implement silent failure handling and other related files do. # TODO: Research and remove if not needed. # context 'send_confirmation_email' do # end context 'sidekiq_retries_exhausted' do it 'tracks exhaustion event and sends backup submission' do msg = { 'args' => [user.uuid, dependency_claim.id, encrypted_vet_info], 'error_message' => 'Connection timeout' } error = StandardError.new('Job failed') # Mock the monitor monitor_double = instance_double(Dependents::Monitor) expect(Dependents::Monitor).to receive(:new).with(dependency_claim.id).and_return(monitor_double) # Expect the monitor to track the exhaustion event expect(monitor_double).to receive(:track_event).with( 'error', 'BGS::SubmitForm686cJob failed, retries exhausted! Last error: Connection timeout', 'worker.submit_686c_bgs.exhaustion' ) # Expect the backup submission to be called expect(BGS::SubmitForm686cJob) .to receive(:send_backup_submission) .with(vet_info, dependency_claim.id, user.uuid) # Call the sidekiq_retries_exhausted callback described_class.sidekiq_retries_exhausted_block.call(msg, error) end end context 'send_backup_submission exception' do let(:in_progress_form) do InProgressForm.create!( form_id: '686C-674', user_uuid: user.uuid, user_account: user.user_account, form_data: all_flows_payload ) end before do allow(OpenStruct).to receive(:new).and_call_original in_progress_form end it 'handles exceptions during backup submission' do # Mock the monitor monitor_double = instance_double(Dependents::Monitor) expect(Dependents::Monitor).to receive(:new).with(dependency_claim.id).and_return(monitor_double) # Mock the backup submission to raise an error expect(Lighthouse::BenefitsIntake::SubmitCentralForm686cJob).to receive(:perform_async) .and_raise(StandardError.new('Backup submission failed')) # Expect the monitor to track the error event expect(monitor_double).to receive(:track_event).with( 'error', 'BGS::SubmitForm686cJob backup submission failed...', 'worker.submit_686c_bgs.backup_failure', hash_including(error: 'Backup submission failed') ) # Expect the in-progress form to be marked as submission pending expect_any_instance_of(InProgressForm).to receive(:submission_pending!) # Call the send_backup_submission method expect do described_class.send_backup_submission( vet_info, dependency_claim.id, user.uuid ) end.not_to raise_error end end end def raise_nested_err raise BGS::SubmitForm686cJob::Invalid686cClaim, 'A very specific error occurred: insertBenefitClaim: Invalid zipcode.' rescue raise BGS::SubmitForm686cJob::Invalid686cClaim, 'A Generic Error Occurred' end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/bgs/submit_form674_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'sidekiq/job_retry' RSpec.describe BGS::SubmitForm674Job, type: :job do # performance tweak before do allow_any_instance_of(SavedClaim::DependencyClaim).to receive(:pdf_overflow_tracking) end let(:user) { create(:evss_user, :loa3, :with_terms_of_use_agreement) } let(:dependency_claim) { create(:dependency_claim) } let(:dependency_claim_674_only) { create(:dependency_claim_674_only) } let(:all_flows_payload) { build(:form_686c_674_kitchen_sink) } let(:birth_date) { '1809-02-12' } let(:client_stub) { instance_double(BGS::Form674) } let(:vet_info) do { 'veteran_information' => { 'full_name' => { 'first' => 'WESLEY', 'middle' => nil, 'last' => 'FORD' }, 'common_name' => user.common_name, 'participant_id' => '600061742', 'uuid' => user.uuid, 'email' => user.email, 'va_profile_email' => user.va_profile_email, 'ssn' => '796043735', 'va_file_number' => '796043735', 'icn' => user.icn, 'birth_date' => birth_date } } end let(:encrypted_vet_info) { KmsEncrypted::Box.new.encrypt(vet_info.to_json) } let(:user_struct) do OpenStruct.new( first_name: vet_info['veteran_information']['full_name']['first'], last_name: vet_info['veteran_information']['full_name']['last'], middle_name: vet_info['veteran_information']['full_name']['middle'], ssn: vet_info['veteran_information']['ssn'], email: vet_info['veteran_information']['email'], va_profile_email: vet_info['veteran_information']['va_profile_email'], participant_id: vet_info['veteran_information']['participant_id'], icn: vet_info['veteran_information']['icn'], uuid: vet_info['veteran_information']['uuid'], common_name: vet_info['veteran_information']['common_name'] ) end let(:encrypted_user_struct) { KmsEncrypted::Box.new.encrypt(user_struct.to_h.to_json) } let(:vanotify) { double(send_email: true) } context 'success' do before do expect(BGS::Form674).to receive(:new).with(user_struct, dependency_claim).and_return(client_stub) expect(client_stub).to receive(:submit).once end it 'successfully calls #submit for 674 submission' do expect(OpenStruct).to receive(:new) .with(hash_including(user_struct.to_h.stringify_keys)) .and_return(user_struct) expect do subject.perform(user.uuid, dependency_claim.id, encrypted_vet_info, encrypted_user_struct) end.not_to raise_error end it 'successfully calls #submit without a user_struct passed in by 686c' do expect(OpenStruct).to receive(:new) .with(hash_including(icn: vet_info['veteran_information']['icn'])) .and_return(user_struct) expect do subject.perform(user.uuid, dependency_claim.id, encrypted_vet_info) end.not_to raise_error end it 'sends confirmation email for combined forms' do expect(OpenStruct).to receive(:new) .with(hash_including('icn' => vet_info['veteran_information']['icn'])) .and_return(user_struct) callback_options = { callback_klass: 'Dependents::NotificationCallback', callback_metadata: { email_template_id: 'fake_received686c674', email_type: :received686c674, form_id: '686C-674', claim_id: dependency_claim.id, saved_claim_id: dependency_claim.id, service_name: 'dependents' } } personalization = { 'confirmation_number' => dependency_claim.confirmation_number, 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'first_name' => 'WESLEY' } expect(VaNotify::Service).to receive(:new).with('fake_secret', callback_options).and_return(vanotify) expect(vanotify).to receive(:send_email).with( { email_address: user.va_profile_email, template_id: 'fake_received686c674', personalisation: personalization }.compact ) subject.perform(user.uuid, dependency_claim.id, encrypted_vet_info, encrypted_user_struct) end end context 'error with central submission' do before do allow(OpenStruct).to receive(:new).and_call_original InProgressForm.create!(form_id: '686C-674', user_uuid: user.uuid, user_account: user.user_account, form_data: all_flows_payload) end it 'raises error' do expect(OpenStruct).to receive(:new) .with(hash_including('icn' => vet_info['veteran_information']['icn'])) .and_return(user_struct) expect(BGS::Form674).to receive(:new).with(user_struct, dependency_claim) { client_stub } expect(client_stub).to receive(:submit).and_raise(BGS::SubmitForm674Job::Invalid674Claim) expect do subject.perform(user.uuid, dependency_claim.id, encrypted_vet_info, encrypted_user_struct) end.to raise_error(BGS::SubmitForm674Job::Invalid674Claim) end it 'filters based on error cause' do expect(OpenStruct).to receive(:new) .with(hash_including('icn' => vet_info['veteran_information']['icn'])) .and_return(user_struct) expect(BGS::Form674).to receive(:new).with(user_struct, dependency_claim) { client_stub } expect(client_stub).to receive(:submit) { raise_nested_err } expect do subject.perform(user.uuid, dependency_claim.id, encrypted_vet_info, encrypted_user_struct) end.to raise_error(Sidekiq::JobRetry::Skip) end end context '674 only' do it 'sends confirmation email for 674 only' do expect(BGS::Form674).to receive(:new).and_return(client_stub) expect(client_stub).to receive(:submit).once expect(OpenStruct).to receive(:new) .with(hash_including('icn' => vet_info['veteran_information']['icn'])) .and_return(user_struct) callback_options = { callback_klass: 'Dependents::NotificationCallback', callback_metadata: { email_template_id: 'fake_received674', email_type: :received674, form_id: '686C-674', claim_id: dependency_claim_674_only.id, saved_claim_id: dependency_claim_674_only.id, service_name: 'dependents' } } personalization = { 'confirmation_number' => dependency_claim_674_only.confirmation_number, 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'first_name' => 'WESLEY' } expect(VaNotify::Service).to receive(:new).with('fake_secret', callback_options).and_return(vanotify) expect(vanotify).to receive(:send_email).with( { email_address: user.va_profile_email, template_id: 'fake_received674', personalisation: personalization }.compact ) subject.perform(user.uuid, dependency_claim_674_only.id, encrypted_vet_info, encrypted_user_struct) end end context 'sidekiq_retries_exhausted' do it 'tracks exhaustion event and sends backup submission' do msg = { 'args' => [user.uuid, dependency_claim.id, encrypted_vet_info, encrypted_user_struct], 'error_message' => 'Connection timeout' } error = StandardError.new('Job failed') # Mock the monitor monitor_double = instance_double(Dependents::Monitor) expect(Dependents::Monitor).to receive(:new).with(dependency_claim.id).and_return(monitor_double) # Expect the monitor to track the exhaustion event expect(monitor_double).to receive(:track_event).with( 'error', 'BGS::SubmitForm674Job failed, retries exhausted! Last error: Connection timeout', 'worker.submit_674_bgs.exhaustion' ) # Expect the backup submission to be called expect(BGS::SubmitForm674Job).to receive(:send_backup_submission).with( encrypted_user_struct, vet_info, dependency_claim.id, user.uuid ) # Call the sidekiq_retries_exhausted callback described_class.sidekiq_retries_exhausted_block.call(msg, error) end end end def raise_nested_err raise BGS::SubmitForm674Job::Invalid674Claim, 'A very specific error occurred: insertBenefitClaim: Invalid zipcode.' rescue raise BGS::SubmitForm674Job::Invalid674Claim, 'A Generic Error Occurred' end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/bgs/submit_form674_v2_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'sidekiq/job_retry' RSpec.describe BGS::SubmitForm674V2Job, type: :job do # Performance tweak before { allow_any_instance_of(SavedClaim::DependencyClaim).to receive(:pdf_overflow_tracking) } let(:user) { create(:evss_user, :loa3, :with_terms_of_use_agreement) } let(:dependency_claim) { create(:dependency_claim) } let(:dependency_claim_674_only) { create(:dependency_claim_674_only) } let(:all_flows_payload) { build(:form_686c_674_kitchen_sink) } let(:birth_date) { '1809-02-12' } let(:client_stub) { instance_double(BGSV2::Form674) } let(:vet_info) do { 'veteran_information' => { 'full_name' => { 'first' => 'WESLEY', 'middle' => nil, 'last' => 'FORD' }, 'common_name' => user.common_name, 'participant_id' => '600061742', 'uuid' => user.uuid, 'email' => user.email, 'va_profile_email' => user.va_profile_email, 'ssn' => '796043735', 'va_file_number' => '796043735', 'icn' => user.icn, 'birth_date' => birth_date } } end let(:encrypted_vet_info) { KmsEncrypted::Box.new.encrypt(vet_info.to_json) } let(:user_struct) do OpenStruct.new( first_name: vet_info['veteran_information']['full_name']['first'], last_name: vet_info['veteran_information']['full_name']['last'], middle_name: vet_info['veteran_information']['full_name']['middle'], ssn: vet_info['veteran_information']['ssn'], email: vet_info['veteran_information']['email'], va_profile_email: vet_info['veteran_information']['va_profile_email'], participant_id: vet_info['veteran_information']['participant_id'], icn: vet_info['veteran_information']['icn'], uuid: vet_info['veteran_information']['uuid'], common_name: vet_info['veteran_information']['common_name'] ) end let(:encrypted_user_struct) { KmsEncrypted::Box.new.encrypt(user_struct.to_h.to_json) } let(:vanotify) { double(send_email: true) } context 'success' do before do expect(BGSV2::Form674).to receive(:new).with(user_struct, dependency_claim).and_return(client_stub) expect(client_stub).to receive(:submit).once end it 'successfully calls #submit for 674 submission' do expect(OpenStruct).to receive(:new) .with(hash_including(user_struct.to_h.stringify_keys)) .and_return(user_struct) expect do subject.perform(user.uuid, dependency_claim.id, encrypted_vet_info, encrypted_user_struct) end.not_to raise_error end it 'successfully calls #submit without a user_struct passed in by 686c' do expect(OpenStruct).to receive(:new) .with(hash_including(icn: vet_info['veteran_information']['icn'])) .and_return(user_struct) expect do subject.perform(user.uuid, dependency_claim.id, encrypted_vet_info) end.not_to raise_error end it 'sends confirmation email for combined forms' do expect(OpenStruct).to receive(:new) .with(hash_including('icn' => vet_info['veteran_information']['icn'])) .and_return(user_struct) callback_options = { callback_klass: 'Dependents::NotificationCallback', callback_metadata: { email_template_id: 'fake_received686c674', email_type: :received686c674, form_id: '686C-674', claim_id: dependency_claim.id, saved_claim_id: dependency_claim.id, service_name: 'dependents' } } personalization = { 'confirmation_number' => dependency_claim.confirmation_number, 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'first_name' => 'WESLEY' } expect(VaNotify::Service).to receive(:new).with('fake_secret', callback_options).and_return(vanotify) expect(vanotify).to receive(:send_email).with( { email_address: user.va_profile_email, template_id: 'fake_received686c674', personalisation: personalization }.compact ) subject.perform(user.uuid, dependency_claim.id, encrypted_vet_info, encrypted_user_struct) end end context 'error with central submission' do before do allow(OpenStruct).to receive(:new).and_call_original InProgressForm.create!(form_id: '686C-674', user_uuid: user.uuid, user_account: user.user_account, form_data: all_flows_payload) end it 'raises error' do expect(OpenStruct).to receive(:new) .with(hash_including('icn' => vet_info['veteran_information']['icn'])) .and_return(user_struct) expect(BGSV2::Form674).to receive(:new).with(user_struct, dependency_claim) { client_stub } expect(client_stub).to receive(:submit).and_raise(BGS::SubmitForm674V2Job::Invalid674Claim) expect do subject.perform(user.uuid, dependency_claim.id, encrypted_vet_info, encrypted_user_struct) end.to raise_error(BGS::SubmitForm674V2Job::Invalid674Claim) end it 'filters based on error cause' do expect(OpenStruct).to receive(:new) .with(hash_including('icn' => vet_info['veteran_information']['icn'])) .and_return(user_struct) expect(BGSV2::Form674).to receive(:new).with(user_struct, dependency_claim) { client_stub } expect(client_stub).to receive(:submit) { raise_nested_err } expect do subject.perform(user.uuid, dependency_claim.id, encrypted_vet_info, encrypted_user_struct) end.to raise_error(Sidekiq::JobRetry::Skip) end end context '674 only' do it 'sends confirmation email for 674 only' do expect(BGSV2::Form674).to receive(:new).and_return(client_stub) expect(client_stub).to receive(:submit).once expect(OpenStruct).to receive(:new) .with(hash_including('icn' => vet_info['veteran_information']['icn'])) .and_return(user_struct) callback_options = { callback_klass: 'Dependents::NotificationCallback', callback_metadata: { email_template_id: 'fake_received674', email_type: :received674, form_id: '686C-674', claim_id: dependency_claim_674_only.id, saved_claim_id: dependency_claim_674_only.id, service_name: 'dependents' } } personalization = { 'confirmation_number' => dependency_claim_674_only.confirmation_number, 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'first_name' => 'WESLEY' } expect(VaNotify::Service).to receive(:new).with('fake_secret', callback_options).and_return(vanotify) expect(vanotify).to receive(:send_email).with( { email_address: user.va_profile_email, template_id: 'fake_received674', personalisation: personalization }.compact ) subject.perform(user.uuid, dependency_claim_674_only.id, encrypted_vet_info, encrypted_user_struct) end end context 'sidekiq_retries_exhausted' do it 'tracks exhaustion event and sends backup submission' do msg = { 'args' => [user.uuid, dependency_claim.id, encrypted_vet_info, encrypted_user_struct], 'error_message' => 'Connection timeout' } error = StandardError.new('Job failed') # Mock the monitor monitor_double = instance_double(Dependents::Monitor) expect(Dependents::Monitor).to receive(:new).with(dependency_claim.id).and_return(monitor_double) # Expect the monitor to track the exhaustion event expect(monitor_double).to receive(:track_event).with( 'error', 'BGS::SubmitForm674Job failed, retries exhausted! Last error: Connection timeout', 'worker.submit_674_bgs.exhaustion' ) # Expect the backup submission to be called expect(BGS::SubmitForm674V2Job).to receive(:send_backup_submission).with( encrypted_user_struct, vet_info, dependency_claim.id, user.uuid ) # Call the sidekiq_retries_exhausted callback described_class.sidekiq_retries_exhausted_block.call(msg, error) end end context 'send_backup_submission exception' do let(:in_progress_form) do InProgressForm.create!( form_id: '686C-674-V2', user_uuid: user.uuid, user_account: user.user_account, form_data: all_flows_payload ) end before do allow(OpenStruct).to receive(:new).and_call_original in_progress_form end end end def raise_nested_err raise BGS::SubmitForm674V2Job::Invalid674Claim, 'A very specific error occurred: insertBenefitClaim: Invalid zipcode.' rescue raise BGS::SubmitForm674V2Job::Invalid674Claim, 'A Generic Error Occurred' end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/bgs/job_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe BGS::Job, type: :job do let(:user) { create(:evss_user, :loa3) } let(:dependency_claim) { create(:dependency_claim) } let(:all_flows_payload) { build(:form_686c_674_kitchen_sink) } let(:all_flows_payload_v2) { build(:form686c_674_v2) } describe '#in_progress_form_copy' do it 'returns nil if the in progress form is blank' do job = described_class.new in_progress_form = job.in_progress_form_copy(nil) expect(in_progress_form).to be_nil end it 'returns an object with metadata and formdata' do in_progress_form = InProgressForm.new(form_id: '686C-674', user_uuid: user.uuid, form_data: all_flows_payload, user_account: user.user_account) job = described_class.new in_progress_form_copy = job.in_progress_form_copy(in_progress_form) expect(in_progress_form_copy.meta_data['expiresAt']).to be_truthy end end describe '#salvage_save_in_progress_form' do let(:user_verification) { user.user_verification } it 'returns nil if the in progress form is blank' do job = described_class.new in_progress_form = job.salvage_save_in_progress_form('686C-674', user.uuid, nil) expect(in_progress_form).to be_nil end it 'upserts an InProgressForm' do in_progress_form = InProgressForm.create!(form_id: '686C-674', user_uuid: user.uuid, form_data: all_flows_payload, user_account: user.user_account) job = described_class.new in_progress_form = job.salvage_save_in_progress_form('686C-674', user.uuid, in_progress_form) expect(in_progress_form).to be(true) end end describe '#normalize_names_and_addresses!(hash)' do it 'removes non-ASCII characters from name and address values in given hash, modifying the hash in-place' do # rubocop:disable Layout/LineLength raw_string = "Téśt'-Strïñg/1*`" normalized_name_string = 'Test-String/' normalized_address_string = "Test'-String/1" # Should modify name fields all_flows_payload['veteran_information']['full_name']['first'] = raw_string all_flows_payload['veteran_information']['full_name']['middle'] = raw_string all_flows_payload['veteran_information']['full_name']['last'] = raw_string # Should modify name fields deeper in the hash all_flows_payload['dependents_application']['report_divorce']['full_name']['first'] = raw_string all_flows_payload['dependents_application']['report_divorce']['full_name']['middle'] = raw_string all_flows_payload['dependents_application']['report_divorce']['full_name']['last'] = raw_string # Should modify address_line fields all_flows_payload['dependents_application']['last_term_school_information']['address']['address_line1'] = raw_string all_flows_payload['dependents_application']['last_term_school_information']['address']['address_line2'] = raw_string all_flows_payload['dependents_application']['last_term_school_information']['address']['address_line3'] = raw_string # Should modify fields, even within arrays of hashes all_flows_payload['dependents_application']['children_to_add'][0]['child_address_info']['address']['address_line1'] = raw_string all_flows_payload['dependents_application']['children_to_add'][0]['child_address_info']['address']['address_line2'] = raw_string all_flows_payload['dependents_application']['children_to_add'][0]['child_address_info']['address']['address_line3'] = raw_string # Should modify fields, even within arrays of hashes all_flows_payload_v2['dependents_application']['veteran_contact_information']['veteran_address']['street'] = raw_string all_flows_payload_v2['dependents_application']['veteran_contact_information']['veteran_address']['street2'] = raw_string all_flows_payload_v2['dependents_application']['veteran_contact_information']['veteran_address']['street3'] = raw_string # Should modify fields within arrays of hashes, beyond the first element in such arrays all_flows_payload['dependents_application']['children_to_add'][1]['full_name']['first'] = raw_string all_flows_payload['dependents_application']['children_to_add'][1]['full_name']['middle'] = raw_string all_flows_payload['dependents_application']['children_to_add'][1]['full_name']['last'] = raw_string # Should not modify other fields with similar names to the name and address fields that should be modified (e.g. should not modify country_name, email_address, etc.) all_flows_payload['dependents_application']['veteran_contact_information']['email_address'] = raw_string all_flows_payload['dependents_application']['last_term_school_information']['address']['country_name'] = raw_string BGS::Job.new.normalize_names_and_addresses!(all_flows_payload) BGS::Job.new.normalize_names_and_addresses!(all_flows_payload_v2) expect(all_flows_payload['veteran_information']['full_name']['first']).to eq(normalized_name_string) expect(all_flows_payload['veteran_information']['full_name']['middle']).to eq(normalized_name_string) expect(all_flows_payload['veteran_information']['full_name']['last']).to eq(normalized_name_string) expect(all_flows_payload['dependents_application']['report_divorce']['full_name']['first']).to eq(normalized_name_string) expect(all_flows_payload['dependents_application']['report_divorce']['full_name']['middle']).to eq(normalized_name_string) expect(all_flows_payload['dependents_application']['report_divorce']['full_name']['last']).to eq(normalized_name_string) expect(all_flows_payload['dependents_application']['last_term_school_information']['address']['address_line1']).to eq(normalized_address_string) expect(all_flows_payload['dependents_application']['last_term_school_information']['address']['address_line2']).to eq(normalized_address_string) expect(all_flows_payload['dependents_application']['last_term_school_information']['address']['address_line3']).to eq(normalized_address_string) expect(all_flows_payload['dependents_application']['children_to_add'][0]['child_address_info']['address']['address_line1']).to eq(normalized_address_string) expect(all_flows_payload['dependents_application']['children_to_add'][0]['child_address_info']['address']['address_line2']).to eq(normalized_address_string) expect(all_flows_payload['dependents_application']['children_to_add'][0]['child_address_info']['address']['address_line3']).to eq(normalized_address_string) expect(all_flows_payload['dependents_application']['children_to_add'][1]['full_name']['first']).to eq(normalized_name_string) expect(all_flows_payload['dependents_application']['children_to_add'][1]['full_name']['middle']).to eq(normalized_name_string) expect(all_flows_payload['dependents_application']['children_to_add'][1]['full_name']['last']).to eq(normalized_name_string) expect(all_flows_payload['dependents_application']['veteran_contact_information']['email_address']).to eq(raw_string) expect(all_flows_payload['dependents_application']['last_term_school_information']['address']['country_name']).to eq(raw_string) expect(all_flows_payload_v2['dependents_application']['veteran_contact_information']['veteran_address']['street']).to eq(normalized_address_string) expect(all_flows_payload_v2['dependents_application']['veteran_contact_information']['veteran_address']['street2']).to eq(normalized_address_string) expect(all_flows_payload_v2['dependents_application']['veteran_contact_information']['veteran_address']['street3']).to eq(normalized_address_string) # rubocop:enable Layout/LineLength end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/bgs/submit_form686c_v2_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'sidekiq/job_retry' RSpec.describe BGS::SubmitForm686cV2Job, type: :job do let(:job) { subject.perform(user.uuid, dependency_claim.id, encrypted_vet_info) } let(:user) { create(:evss_user, :loa3) } let(:dependency_claim) { create(:dependency_claim) } let(:all_flows_payload) { build(:form_686c_674_kitchen_sink) } let(:birth_date) { '1809-02-12' } let(:client_stub) { instance_double(BGSV2::Form686c) } let(:vet_info) do { 'veteran_information' => { 'full_name' => { 'first' => 'WESLEY', 'middle' => nil, 'last' => 'FORD' }, 'common_name' => user.common_name, 'participant_id' => '600061742', 'uuid' => user.uuid, 'email' => user.email, 'va_profile_email' => user.va_profile_email, 'ssn' => '796043735', 'va_file_number' => '796043735', 'icn' => user.icn, 'birth_date' => birth_date } } end let(:encrypted_vet_info) { KmsEncrypted::Box.new.encrypt(vet_info.to_json) } let(:user_struct) do nested_info = vet_info['veteran_information'] OpenStruct.new( first_name: nested_info['full_name']['first'], last_name: nested_info['full_name']['last'], middle_name: nested_info['full_name']['middle'], ssn: nested_info['ssn'], email: nested_info['email'], va_profile_email: nested_info['va_profile_email'], participant_id: nested_info['participant_id'], icn: nested_info['icn'], uuid: nested_info['uuid'], common_name: nested_info['common_name'] ) end let(:vanotify) { double(send_email: true) } before do allow_any_instance_of(SavedClaim::DependencyClaim).to receive(:submittable_674?).and_return(false) allow(OpenStruct).to receive(:new) .with(hash_including(icn: vet_info['veteran_information']['icn'])) .and_return(user_struct) allow_any_instance_of(SavedClaim::DependencyClaim).to receive(:pdf_overflow_tracking) end context 'successfully' do it 'calls #submit for 686c submission' do expect(BGSV2::Form686c).to receive(:new).with(user_struct, dependency_claim).and_return(client_stub) expect(client_stub).to receive(:submit).once expect { job }.not_to raise_error end it 'sends confirmation email for 686c only' do expect(BGSV2::Form686c).to receive(:new).with(user_struct, dependency_claim).and_return(client_stub) expect(client_stub).to receive(:submit).once callback_options = { callback_klass: 'Dependents::NotificationCallback', callback_metadata: { email_template_id: 'fake_received686', email_type: :received686, form_id: '686C-674', claim_id: dependency_claim.id, saved_claim_id: dependency_claim.id, service_name: 'dependents' } } personalization = { 'confirmation_number' => dependency_claim.confirmation_number, 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'first_name' => 'WESLEY' } expect(VaNotify::Service).to receive(:new).with('fake_secret', callback_options).and_return(vanotify) expect(vanotify).to receive(:send_email).with( { email_address: user.va_profile_email, template_id: 'fake_received686', personalisation: personalization }.compact ) expect { job }.not_to raise_error end it 'does not send confirmation email for 686c_674 combo' do allow_any_instance_of(SavedClaim::DependencyClaim).to receive(:submittable_674?).and_return(true) expect(BGSV2::Form686c).to receive(:new).with(user_struct, dependency_claim).and_return(client_stub) expect(client_stub).to receive(:submit).once expect(VANotify::EmailJob).not_to receive(:perform_async) expect { job }.not_to raise_error end end context 'Claim is submittable_674' do it 'enqueues SubmitForm674Job' do allow_any_instance_of(SavedClaim::DependencyClaim).to receive(:submittable_674?).and_return(true) expect(BGSV2::Form686c).to receive(:new).with(user_struct, dependency_claim).and_return(client_stub) expect(client_stub).to receive(:submit).once expect(BGS::SubmitForm674V2Job).to receive(:perform_async).with(user.uuid, dependency_claim.id, encrypted_vet_info, an_instance_of(String)) expect { job }.not_to raise_error end end context 'Claim is not submittable_674' do it 'does not enqueue SubmitForm674Job' do expect(BGSV2::Form686c).to receive(:new).with(user_struct, dependency_claim).and_return(client_stub) expect(client_stub).to receive(:submit).once expect(BGS::SubmitForm674V2Job).not_to receive(:perform_async) expect { job }.not_to raise_error end end context 'when submission raises error' do it 'raises error' do expect(BGSV2::Form686c).to receive(:new).with(user_struct, dependency_claim).and_return(client_stub) expect(client_stub).to receive(:submit).and_raise(BGS::SubmitForm686cV2Job::Invalid686cClaim) expect { job }.to raise_error(BGS::SubmitForm686cV2Job::Invalid686cClaim) end it 'filters based on error cause' do expect(BGSV2::Form686c).to receive(:new).with(user_struct, dependency_claim).and_return(client_stub) expect(client_stub).to receive(:submit) { raise_nested_err } expect { job }.to raise_error(Sidekiq::JobRetry::Skip) end end context 'sidekiq_retries_exhausted' do it 'tracks exhaustion event and sends backup submission' do msg = { 'args' => [user.uuid, dependency_claim.id, encrypted_vet_info], 'error_message' => 'Connection timeout' } error = StandardError.new('Job failed') # Mock the monitor monitor_double = instance_double(Dependents::Monitor) expect(Dependents::Monitor).to receive(:new).with(dependency_claim.id).and_return(monitor_double) # Expect the monitor to track the exhaustion event expect(monitor_double).to receive(:track_event).with( 'error', 'BGS::SubmitForm686cV2Job failed, retries exhausted! Last error: Connection timeout', 'worker.submit_686c_bgs.exhaustion' ) # Expect the backup submission to be called expect(BGS::SubmitForm686cV2Job) .to receive(:send_backup_submission) .with(vet_info, dependency_claim.id, user.uuid) # Call the sidekiq_retries_exhausted callback described_class.sidekiq_retries_exhausted_block.call(msg, error) end end context 'send_backup_submission exception' do let(:in_progress_form) do InProgressForm.create!( form_id: '686C-674-V2', user_uuid: user.uuid, user_account: user.user_account, form_data: all_flows_payload ) end before do allow(OpenStruct).to receive(:new).and_call_original in_progress_form end it 'handles exceptions during backup submission' do # Mock the monitor monitor_double = instance_double(Dependents::Monitor) expect(Dependents::Monitor).to receive(:new).with(dependency_claim.id).and_return(monitor_double) # Mock the backup submission to raise an error expect(Lighthouse::BenefitsIntake::SubmitCentralForm686cV2Job).to receive(:perform_async) .and_raise(StandardError.new('Backup submission failed')) # Expect the monitor to track the error event expect(monitor_double).to receive(:track_event).with( 'error', 'BGS::SubmitForm686cV2Job backup submission failed...', 'worker.submit_686c_bgs.backup_failure', hash_including(error: 'Backup submission failed') ) # Expect the in-progress form to be marked as submission pending expect_any_instance_of(InProgressForm).to receive(:submission_pending!) # Call the send_backup_submission method expect do described_class.send_backup_submission( vet_info, dependency_claim.id, user.uuid ) end.not_to raise_error end end end def raise_nested_err raise BGS::SubmitForm686cV2Job::Invalid686cClaim, 'A very specific error occurred: insertBenefitClaim: Invalid zipcode.' # rubocop:disable Layout/LineLength rescue raise BGS::SubmitForm686cV2Job::Invalid686cClaim, 'A Generic Error Occurred' end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/bgs/flash_updater_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe BGS::FlashUpdater, type: :job do subject { described_class } let(:user) { create(:evss_user, :loa3) } # ssn 796043735 let(:submission) { create(:form526_submission, :with_uploads, user_uuid: user.uuid) } let(:ssn) { submission.auth_headers['va_eauth_pnid'] } let(:flashes) { %w[Homeless POW] } let(:assigned_flashes) do { flashes: flashes.map { |flash| { assigned_indicator: nil, flash_name: "#{flash} ", flash_type: nil } } } end it 'submits successfully with claim id' do expect do subject.perform_async(submission.id) end.to change(subject.jobs, :size).by(1) end it 'submits flashes to bgs successfully' do flashes.each do |flash_name| expect_any_instance_of(BGS::ClaimantWebService) .to receive(:add_flash).with(file_number: ssn, flash_name:) end expect_any_instance_of(BGS::ClaimantWebService) .to receive(:find_assigned_flashes).with(ssn).and_return(assigned_flashes) subject.new.perform(submission.id) end it 'continues submitting flashes on exception' do flashes.each_with_index do |flash_name, index| if index.zero? expect_any_instance_of(BGS::ClaimantWebService).to receive(:add_flash) .with(file_number: ssn, flash_name:).and_raise(BGS::ShareError.new('failed', 500)) else expect_any_instance_of(BGS::ClaimantWebService) .to receive(:add_flash).with(file_number: ssn, flash_name:) end end expect_any_instance_of(BGS::ClaimantWebService) .to receive(:find_assigned_flashes).with(ssn).and_return(assigned_flashes) subject.new.perform(submission.id) end context 'catastrophic failure state' do describe 'when all retries are exhausted' do let!(:form526_submission) { create(:form526_submission) } let!(:form526_job_status) { create(:form526_job_status, :retryable_error, form526_submission:, job_id: 1) } it 'updates a StatsD counter and updates the status on an exhaustion event' do subject.within_sidekiq_retries_exhausted_block({ 'jid' => form526_job_status.job_id }) do expect(StatsD).to receive(:increment).with("#{subject::STATSD_KEY_PREFIX}.exhausted", { tags: ['service:bgs', 'function:log_event', 'action:exhausted'] }) expect(Rails).to receive(:logger).and_call_original end form526_job_status.reload expect(form526_job_status.status).to eq(Form526JobStatus::STATUS[:exhausted]) end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/dependents/form686c674_failure_email_job_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Dependents::Form686c674FailureEmailJob, type: :job do let(:job) { described_class.new } let(:claim_id) { 123 } let(:email) { 'test@example.com' } let(:template_id) { 'test-template-id' } let(:claim) do instance_double( SavedClaim::DependencyClaim, form_id: described_class::FORM_ID, confirmation_number: 'ABCD1234', parsed_form: { 'veteran_information' => { 'full_name' => { 'first' => 'John' } } } ) end let(:personalisation) do { 'first_name' => 'JOHN', 'date_submitted' => 'January 01, 2023', 'confirmation_number' => 'ABCD1234' } end let(:va_notify_client) { instance_double(VaNotify::Service) } let(:monitor) { instance_double(Dependents::Monitor) } let(:default_monitor_payload) do { service: 'dependent-change', use_v2: @use_v2, claim: @claim, user_account_uuid: @claim&.user_account_id, tags: { function: described_class::ZSF_DD_TAG_FUNCTION } } end before do allow(Dependents::Monitor).to receive(:new).with(claim_id).and_return(monitor) allow(monitor).to receive_messages( log_silent_failure: nil, log_silent_failure_avoided: nil, default_payload: default_monitor_payload ) end describe '#perform' do before do allow(SavedClaim::DependencyClaim).to receive(:find).with(claim_id).and_return(claim) allow(VaNotify::Service).to receive(:new).and_return(va_notify_client) allow(va_notify_client).to receive(:send_email) allow(Rails.logger).to receive(:warn) end it 'sends an email with the correct parameters' do expect(va_notify_client).to receive(:send_email).with( email_address: email, template_id:, personalisation: { 'first_name' => 'JOHN', 'date_submitted' => 'January 01, 2023', 'confirmation_number' => 'ABCD1234' } ) job.perform(claim_id, email, template_id, personalisation) end it 'logs a silent failure when email is sent successfully' do expect(monitor).to receive(:log_silent_failure_avoided).with( default_monitor_payload, call_location: anything ) job.perform(claim_id, email, template_id, personalisation) end context 'when an error occurs' do before do allow(va_notify_client).to receive(:send_email).and_raise(StandardError.new('Test error')) end it 'logs the error and raises error to kick off retries' do expect(Rails.logger).to receive(:warn).with( 'Form686c674FailureEmailJob failed, retrying send...', { claim_id:, error: instance_of(StandardError) } ) expect(monitor).not_to receive(:log_silent_failure_avoided) expect { job.perform(claim_id, email, template_id, personalisation) }.to raise_error(StandardError) end end end describe 'sidekiq_retries_exhausted' do it 'logs an error when retries are exhausted' do msg = { 'args' => [claim_id] } ex = StandardError.new('Test exhausted error') expect(Rails.logger).to receive(:error).with( 'Form686c674FailureEmailJob exhausted all retries', { saved_claim_id: claim_id, error_message: 'Test exhausted error' } ) expect(monitor).to receive(:log_silent_failure).with( default_monitor_payload.merge(message: ex.message), call_location: anything ) described_class.sidekiq_retries_exhausted_block.call(msg, ex) end end describe '#va_notify_client' do before do allow(SavedClaim::DependencyClaim).to receive(:find).with(claim_id).and_return(claim) allow(VaNotify::Service).to receive(:new).and_return(va_notify_client) vanotify = double('vanotify') services = double('services') va_gov = double('va_gov') allow(Settings).to receive(:vanotify).and_return(vanotify) allow(vanotify).to receive(:services).and_return(services) allow(services).to receive(:va_gov).and_return(va_gov) allow(va_gov).to receive(:api_key).and_return('test-api-key') end it 'initializes VaNotify::Service with correct parameters' do expected_callback_options = { callback_metadata: { notification_type: 'error', form_id: described_class::FORM_ID, statsd_tags: { service: 'dependent-change', function: described_class::ZSF_DD_TAG_FUNCTION } } } expect(VaNotify::Service).to receive(:new).with('test-api-key', expected_callback_options) # Just allow the job to execute, which should create the client allow(va_notify_client).to receive(:send_email) job.perform(claim_id, email, template_id, personalisation) end end describe '#personalisation' do before do allow(SavedClaim::DependencyClaim).to receive(:find).with(claim_id).and_return(claim) today = double('today') allow(Time.zone).to receive(:today).and_return(today) allow(today).to receive(:strftime).with('%B %d, %Y').and_return('January 01, 2023') # Create the service but don't set expectations on send_email yet allow(VaNotify::Service).to receive(:new).and_return(va_notify_client) end it 'sends correct personalisation data in the email' do # Instead of directly calling the private method, test what gets sent to va_notify_client expect(va_notify_client).to receive(:send_email).with( email_address: email, template_id:, personalisation: ) job.perform(claim_id, email, template_id, { 'first_name' => 'JOHN', 'date_submitted' => 'January 01, 2023', 'confirmation_number' => 'ABCD1234' }) end context 'when first name is nil' do let(:claim) do instance_double( SavedClaim::DependencyClaim, form_id: described_class::FORM_ID, confirmation_number: 'ABCD1234', parsed_form: { 'veteran_information' => { 'full_name' => { 'first' => nil } } } ) end before do allow(va_notify_client) .to receive(:send_email) .and_raise(StandardError.new('BadRequestError: Missing personalisation: first_name')) end it 'throws an error' do expect(va_notify_client).to receive(:send_email).with( email_address: email, template_id:, personalisation: hash_including('first_name' => nil) ) personalisation['first_name'] = nil expect(Rails.logger).to receive(:warn).with( 'Form686c674FailureEmailJob failed, retrying send...', { claim_id:, error: instance_of(StandardError) } ) expect(monitor).not_to receive(:log_silent_failure_avoided) expect { job.perform(claim_id, email, template_id, personalisation) }.to raise_error(StandardError) end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/preneeds/delete_old_uploads_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Preneeds::DeleteOldUploads, type: :model do let(:job) { described_class.new } describe '::EXPIRATION_TIME' do it 'is 2.months' do expect(described_class::EXPIRATION_TIME).to eq(2.months) end end describe '#uuids_to_keep' do it 'gets the uuids of attachments in in progress forms' do create( :in_progress_form, form_id: '40-10007', form_data: build(:burial_form).as_json.to_json ) expect(job.uuids_to_keep).to match_array(FormAttachment.pluck(:guid)) end end describe '#perform' do it 'deletes attachments older than 2 months that arent associated with an in progress form' do attach1 = create(:preneed_attachment) attach2 = create(:preneed_attachment, created_at: 3.months.ago) attach3 = create(:preneed_attachment, created_at: 3.months.ago) expect(job).to receive(:uuids_to_keep).and_return([attach3.guid]) job.perform expect(model_exists?(attach1)).to be(true) expect(model_exists?(attach2)).to be(false) expect(model_exists?(attach3)).to be(true) end end end
0
code_files/vets-api-private/spec/sidekiq/simple_forms_api
code_files/vets-api-private/spec/sidekiq/simple_forms_api/notification/send_notification_email_job_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SimpleFormsApi::Notification::SendNotificationEmailJob, type: :worker do subject(:perform) { described_class.new.perform(benefits_intake_uuid, form_number) } let(:form_submission_attempt) { create(:form_submission_attempt, :failure) } let(:form_number) { 'abc-123' } let(:benefits_intake_uuid) { form_submission_attempt.benefits_intake_uuid } describe '#perform' do shared_examples 'sends notification email' do |email_class| let(:notification_email) { instance_double(email_class, send: nil) } before do allow(email_class).to receive(:new).and_return(notification_email) end it 'sends the email' do perform expect(notification_email).to have_received(:send).with(at: anything) end context 'when email initialization fails' do before do allow(email_class).to receive(:new).and_raise(ArgumentError) allow(StatsD).to receive(:increment) end it 'increments StatsD' do perform expect(StatsD).to have_received(:increment).with('silent_failure', tags: anything) end end end context 'when submitted with digital form submission tool' do let(:form_number) { 'abc-123' } it_behaves_like 'sends notification email', SimpleFormsApi::Notification::Email end context 'when submitted with Form Upload tool' do let(:form_number) { '21-0779' } it_behaves_like 'sends notification email', SimpleFormsApi::Notification::FormUploadEmail end end describe '.perform_async' do subject(:perform_async) { described_class.perform_async(benefits_intake_uuid, form_number) } it 'enqueues the job' do expect { perform_async }.to change(described_class.jobs, :size).by(1) end end end
0
code_files/vets-api-private/spec/sidekiq/simple_forms_api
code_files/vets-api-private/spec/sidekiq/simple_forms_api/form_remediation/upload_retry_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'simple_forms_api/form_remediation/configuration/vff_config' RSpec.describe SimpleFormsApi::FormRemediation::UploadRetryJob, type: :worker do let(:file) { instance_double(CarrierWave::SanitizedFile, filename: 'test_file.txt') } let(:directory) { 'test/directory' } let(:s3_settings) { OpenStruct.new(region: 'us-east-1') } let(:config) do instance_double(SimpleFormsApi::FormRemediation::Configuration::VffConfig, uploader_class:, s3_settings:) end let(:uploader_class) { class_double(SimpleFormsApi::FormRemediation::Uploader) } let(:uploader_instance) { instance_double(SimpleFormsApi::FormRemediation::Uploader) } let(:s3_client_instance) { instance_double(Aws::S3::Client) } before do allow(uploader_class).to receive(:new).with(directory:, config:).and_return(uploader_instance) allow(StatsD).to receive(:increment) allow(Aws::S3::Client).to receive(:new).and_return(s3_client_instance) allow(Rails.logger).to receive(:info) allow(Rails.logger).to receive(:error) end describe '#perform' do context 'when the upload succeeds' do it 'uploads the file and increments the StatsD counter' do allow(uploader_instance).to receive(:store!).with(file) described_class.new.perform(file, directory, config) expect(uploader_instance).to have_received(:store!).with(file) expect(StatsD).to have_received(:increment).with('api.simple_forms_api.upload_retry_job.total') end end context 'when the upload fails with a ServiceError' do before do allow(uploader_instance).to receive(:store!).and_raise(Aws::S3::Errors::ServiceError.new(nil, 'Service error')) end context 'and the service is available' do before do allow(s3_client_instance).to receive(:list_buckets).and_return(true) end it 'raises the error' do expect do described_class.new.perform(file, directory, config) end.to raise_error(Aws::S3::Errors::ServiceError) expect(StatsD).to have_received(:increment).with('api.simple_forms_api.upload_retry_job.total') end end context 'and the service is unavailable' do before do allow(s3_client_instance).to( receive(:list_buckets).and_return(true) .and_raise(Aws::S3::Errors::ServiceError.new(nil, 'Service error')) ) allow(described_class).to receive(:perform_in) end it 'retries the job later and logs the retry' do described_class.new.perform(file, directory, config) expect(described_class).to have_received(:perform_in) expect(Rails.logger).to have_received(:info).with( 'S3 service unavailable. Retrying upload later for test_file.txt.' ) end end end end describe 'sidekiq_retries_exhausted' do it 'logs the retries exhausted error and increments the StatsD counter' do exception = Aws::S3::Errors::ServiceError.new(%w[backtrace1 backtrace2], 'Service error') allow(StatsD).to receive(:increment).with('api.simple_forms_api.upload_retry_job.retries_exhausted') allow(Rails.logger).to receive(:error).with( 'SimpleFormsApi::FormRemediation::UploadRetryJob retries exhausted', hash_including(exception: "#{exception.class} - #{exception.message}") ) job = described_class.new job.sidekiq_retries_exhausted_block.call('Oops', exception) expect(StatsD).to have_received(:increment).with('api.simple_forms_api.upload_retry_job.retries_exhausted') expect(Rails.logger).to have_received(:error).with( 'SimpleFormsApi::FormRemediation::UploadRetryJob retries exhausted', hash_including(exception: "#{exception.class} - #{exception.message}") ) end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/unified_health_data/labs_refresh_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'unified_health_data/service' Sidekiq::Testing.fake! RSpec.describe UnifiedHealthData::LabsRefreshJob, type: :job do let(:user) { create(:user, :loa3) } let(:uhd_service) { instance_double(UnifiedHealthData::Service) } let(:labs_data) { [instance_double(UnifiedHealthData::LabOrTest)] } before do allow(User).to receive(:find).with(user.uuid).and_return(user) allow(UnifiedHealthData::Service).to receive(:new).with(user).and_return(uhd_service) allow(uhd_service).to receive(:get_labs).and_return(labs_data) allow(StatsD).to receive(:gauge) end describe '#perform' do context 'when the user exists' do it 'fetches labs data using the configured date range' do end_date = Date.current days_back = Settings.mhv.uhd.labs_logging_date_range_days.to_i start_date = end_date - days_back.days expect(uhd_service).to receive(:get_labs).with( start_date: start_date.strftime('%Y-%m-%d'), end_date: end_date.strftime('%Y-%m-%d') ) described_class.new.perform(user.uuid) end it 'respects custom date range configuration' do allow(Settings.mhv.uhd).to receive(:labs_logging_date_range_days).and_return(7) end_date = Date.current start_date = end_date - 7.days expect(uhd_service).to receive(:get_labs).with( start_date: start_date.strftime('%Y-%m-%d'), end_date: end_date.strftime('%Y-%m-%d') ) described_class.new.perform(user.uuid) end it 'logs successful completion' do expect(Rails.logger).to receive(:info).with( 'UHD Labs Refresh Job completed successfully', hash_including( records_count: labs_data.size ) ) described_class.new.perform(user.uuid) end it 'returns the count of records fetched' do result = described_class.new.perform(user.uuid) expect(result).to eq(labs_data.size) end it 'sends labs count metric to StatsD' do described_class.new.perform(user.uuid) expect(StatsD).to have_received(:gauge).with('unified_health_data.labs_refresh_job.labs_count', labs_data.size) end end context 'when the user does not exist' do it 'logs an error and returns early' do allow(User).to receive(:find).with('nonexistent_uuid').and_return(nil) expect(Rails.logger).to receive(:error).with( 'UHD Labs Refresh Job: User not found for UUID: nonexistent_uuid' ) described_class.new.perform('nonexistent_uuid') end end context 'when the service raises an error' do let(:error_message) { 'Service unavailable' } before do allow(uhd_service).to receive(:get_labs).and_raise(StandardError.new(error_message)) end it 'logs the error and re-raises' do expect(Rails.logger).to receive(:error).with( 'UHD Labs Refresh Job failed', hash_including( error: error_message ) ) expect { described_class.new.perform(user.uuid) }.to raise_error(StandardError, error_message) end end end describe 'sidekiq options' do it 'has a retry count of 0' do expect(described_class.get_sidekiq_options['retry']).to eq(0) end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/unified_health_data/facility_name_cache_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lighthouse/facilities/v1/client' require 'lighthouse/facilities/v1/response' RSpec.describe UnifiedHealthData::FacilityNameCacheJob, type: :job do subject(:job) { described_class.new } let(:mock_lighthouse_client) { instance_double(Lighthouse::Facilities::V1::Client) } let(:mock_response) { instance_double(Lighthouse::Facilities::V1::Response) } let(:mock_facilities) do [ double('Facility', id: 'vha_648', name: 'Portland VA Medical Center'), double('Facility', id: 'vha_556', name: 'Captain James A. Lovell Federal Health Care Center'), double('Facility', id: 'vba_123', name: 'Non-VHA Facility'), # Should be filtered out double('Facility', id: 'vha_442', name: 'Cheyenne VA Medical Center') ] end before do allow(Lighthouse::Facilities::V1::Client).to receive(:new).and_return(mock_lighthouse_client) allow(mock_lighthouse_client).to receive(:get_paginated_facilities).and_return(mock_response) allow(mock_response).to receive_messages(facilities: mock_facilities, links: nil) # No next page by default # Mock Rails cache allow(Rails.cache).to receive(:write) allow(Rails.cache).to receive(:delete) # Mock time calculations allow(Time).to receive(:current).and_return(Time.zone.parse('2023-01-15 02:00:00 EST')) # Mock StatsD allow(StatsD).to receive(:increment) allow(StatsD).to receive(:gauge) # Mock Rails logger allow(Rails.logger).to receive(:info) allow(Rails.logger).to receive(:error) end describe '#perform' do context 'when successful' do it 'fetches VHA facilities and caches them in Rails cache' do expect(mock_lighthouse_client).to receive(:get_paginated_facilities).with( type: 'health', per_page: 1000, page: 1 ) job.perform # Should cache only VHA facilities (excluding vba_123) expect(Rails.cache).to have_received(:write).with('uhd:facility_names:648', 'Portland VA Medical Center', expires_in: 4.hours) expect(Rails.cache).to have_received(:write).with('uhd:facility_names:556', 'Captain James A. Lovell Federal Health Care Center', expires_in: 4.hours) expect(Rails.cache).to have_received(:write).with('uhd:facility_names:442', 'Cheyenne VA Medical Center', expires_in: 4.hours) end it 'logs successful completion' do job.perform expect(Rails.logger).to have_received(:info).with( '[UnifiedHealthData] - Cache operation complete: 3 facilities cached' ) end it 'sends success metrics to StatsD' do job.perform expect(StatsD).to have_received(:increment).with('unified_health_data.facility_name_cache_job.complete') expect(StatsD).to have_received(:gauge).with('unified_health_data.facility_name_cache_job.facilities_cached', 3) end end context 'when an error occurs' do before do allow(mock_lighthouse_client).to receive(:get_paginated_facilities) .and_raise(StandardError, 'API Error') end it 'logs the error and re-raises' do expect { job.perform }.to raise_error('Failed to cache facility names: API Error') expect(Rails.logger).to have_received(:error) .with('[UnifiedHealthData] - Error in UnifiedHealthData::FacilityNameCacheJob: API Error') expect(StatsD).to have_received(:increment).with('unified_health_data.facility_name_cache_job.error') end end context 'when no facilities are returned' do before do allow(mock_response).to receive(:facilities).and_return([]) end it 'does not attempt to cache anything' do job.perform expect(Rails.cache).not_to have_received(:write) expect(StatsD).to have_received(:gauge).with('unified_health_data.facility_name_cache_job.facilities_cached', 0) end end context 'when multiple pages of facilities exist' do let(:first_page_response) { instance_double(Lighthouse::Facilities::V1::Response) } let(:second_page_response) { instance_double(Lighthouse::Facilities::V1::Response) } let(:batch_size) { UnifiedHealthData::FacilityNameCacheJob::BATCH_SIZE } before do first_page_facilities = [ double('Facility', id: 'vha_001', name: 'Facility 1'), double('Facility', id: 'vha_002', name: 'Facility 2') ] second_page_facilities = [ double('Facility', id: 'vha_003', name: 'Facility 3') ] allow(first_page_response).to receive_messages(facilities: first_page_facilities, links: { 'next' => 'https://api.va.gov/services/va_facilities/v1/facilities?type=health&page=2&per_page=1000' }) allow(second_page_response).to receive_messages(facilities: second_page_facilities, links: nil) # No next page allow(mock_lighthouse_client).to receive(:get_paginated_facilities).and_return( first_page_response, second_page_response ) end it 'requests subsequent pages using links.next until no next link is present' do job.perform expect(mock_lighthouse_client).to have_received(:get_paginated_facilities).with( type: 'health', per_page: batch_size, page: 1 ) expect(mock_lighthouse_client).to have_received(:get_paginated_facilities).with( type: 'health', page: '2', per_page: '1000' ) end end end describe 'Sidekiq configuration' do it 'is configured with proper retry settings' do expect(described_class.sidekiq_options_hash['retry']).to eq(3) end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/evss/delete_old_claims_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EVSS::DeleteOldClaims do before do @claim_nil = create(:evss_claim, updated_at: nil) @claim_new = create(:evss_claim, updated_at: Time.now.utc) @claim_old = create(:evss_claim, updated_at: 2.days.ago) end describe '#perform' do it 'deletes old records' do expect { subject.perform }.to change(EVSSClaim, :count).from(3).to(2) expect { @claim_old.reload }.to raise_exception(ActiveRecord::RecordNotFound) end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/evss/failure_notification_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'evss/failure_notification' require 'va_notify/service' RSpec.describe EVSS::FailureNotification, type: :job do subject { described_class } let(:notify_client_stub) { instance_double(VaNotify::Service) } let(:user_account) { create(:user_account) } let(:document_type) { 'L029' } let(:document_description) { 'Copy of a DD214' } let(:filename) { 'docXXXX-XXte.pdf' } let(:icn) { user_account.icn } let(:first_name) { 'Bob' } let(:issue_instant) { Time.now.to_i } let(:formatted_submit_date) do # We want to return all times in EDT timestamp = Time.at(issue_instant).in_time_zone('America/New_York') # We display dates in mailers in the format "May 1, 2024 3:01 p.m. EDT" timestamp.strftime('%B %-d, %Y %-l:%M %P %Z').sub(/([ap])m/, '\1.m.') end let(:date_submitted) { formatted_submit_date } let(:date_failed) { formatted_submit_date } before do allow(Rails.logger).to receive(:info) end context 'when EVSS::FailureNotification is called' do it 'enqueues a failure notification mailer to send to the veteran' do allow(VaNotify::Service).to receive(:new) { notify_client_stub } subject.perform_async(icn, first_name, filename, date_submitted, date_failed) do expect(notify_client_stub).to receive(:send_email).with( { recipient_identifier: { id_value: user_account.icn, id_type: 'ICN' }, template_id: 'fake_template_id', personalisation: { first_name:, document_type: document_description, filename: file_name, date_submitted: formatted_submit_date, date_failed: formatted_submit_date } } ) expect(Rails.logger) .to receive(:info) .with('EVSS::FailureNotification email sent') end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/evss/document_upload_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'sidekiq/testing' Sidekiq::Testing.fake! require 'evss/document_upload' require 'va_notify/service' require 'lighthouse/benefits_documents/constants' require 'lighthouse/benefits_documents/utilities/helpers' RSpec.describe EVSS::DocumentUpload, type: :job do let(:auth_headers) { EVSS::AuthHeaders.new(user).to_h } let(:user) { create(:user, :loa3) } let(:user_account) { create(:user_account) } let(:user_account_uuid) { user_account.id } let(:claim_id) { 4567 } let(:file_name) { 'doctors-note.pdf' } let(:file) { Rails.root.join('spec', 'fixtures', 'files', file_name).read } let(:tracked_item_id) { 1234 } let(:document_type) { 'L023' } let(:document_description) { 'Other Correspondence' } let(:document_data) do EVSSClaimDocument.new( va_eauth_firstName: 'First Name', evss_claim_id: claim_id, file_name:, tracked_item_id:, document_type: ) end let(:job_id) { '5555' } let(:client_stub) { instance_double(EVSS::DocumentsService) } let(:issue_instant) { Time.current.to_i } let(:current_date_time) { DateTime.current } context 'when :cst_send_evidence_submission_failure_emails is enabled' do before do allow(Flipper).to receive(:enabled?).with(:cst_send_evidence_submission_failure_emails).and_return(true) allow(StatsD).to receive(:increment) allow(Rails.logger).to receive(:info) end # Create Evidence Submission records from factory let(:evidence_submission_created) do create(:bd_evidence_submission_created, tracked_item_id:, claim_id:, job_id:, job_class: described_class) end context 'when upload succeeds' do let(:uploader_stub) { instance_double(EVSSClaimDocumentUploader) } it 'there is an evidence submission id, uploads to EVSS' do allow(EVSSClaimDocumentUploader).to receive(:new) { uploader_stub } allow(EVSS::DocumentsService).to receive(:new) { client_stub } allow(uploader_stub).to receive(:retrieve_from_store!).with(file_name) { file } allow(uploader_stub).to receive(:read_for_upload) { file } expect(uploader_stub).to receive(:remove!).once expect(client_stub).to receive(:upload).with(file, document_data) allow(EvidenceSubmission).to receive(:find_by).with({ id: evidence_submission_created.id }) .and_return(evidence_submission_created) # Runs all queued jobs of this class described_class.new.perform(auth_headers, user.uuid, document_data.to_serializable_hash, evidence_submission_created.id) evidence_submission = EvidenceSubmission.find_by(id: evidence_submission_created.id) expect(evidence_submission.upload_status).to eql(BenefitsDocuments::Constants::UPLOAD_STATUS[:SUCCESS]) expect(evidence_submission.delete_date).not_to be_nil expect(StatsD) .to have_received(:increment) .with('cst.evss.document_uploads.evidence_submission_record_updated.queued') expect(Rails.logger) .to have_received(:info) .with('EVSS - Updated Evidence Submission Record to QUEUED', any_args) expect(StatsD) .to have_received(:increment) .with('cst.evss.document_uploads.evidence_submission_record_updated.success') expect(Rails.logger) .to have_received(:info) .with('EVSS - Updated Evidence Submission Record to SUCCESS', any_args) end it 'when there is no evidence submission id' do allow(EVSS::DocumentUpload).to receive(:update_evidence_submission_for_failure) allow(EVSSClaimDocumentUploader).to receive(:new) { uploader_stub } allow(EVSS::DocumentsService).to receive(:new) { client_stub } allow(uploader_stub).to receive(:retrieve_from_store!).with(file_name) { file } allow(uploader_stub).to receive(:read_for_upload) { file } expect(uploader_stub).to receive(:remove!).once expect(client_stub).to receive(:upload).with(file, document_data) allow(EvidenceSubmission).to receive(:find_by) .with({ id: nil }) .and_return(nil) # runs all queued jobs of this class described_class.new.perform(auth_headers, user.uuid, document_data.to_serializable_hash, nil) expect(EvidenceSubmission.count).to equal(0) expect(EVSS::DocumentUpload).not_to have_received(:update_evidence_submission_for_failure) end end context 'when upload fails' do let(:error_message) { "#{described_class} failed to update EvidenceSubmission" } let(:message) { "#{described_class} EvidenceSubmission updated" } let(:tags) { ['service:claim-status', "function: #{error_message}"] } context 'when there is an evidence submission record that fails' do let(:msg_with_errors) do { 'jid' => job_id, 'args' => [ { 'va_eauth_firstName' => 'Bob' }, user_account_uuid, { 'evss_claim_id' => claim_id, 'tracked_item_id' => tracked_item_id, 'document_type' => document_type, 'file_name' => file_name }, evidence_submission_created.id ], 'created_at' => issue_instant, 'failed_at' => issue_instant, 'error_message' => 'An error ', 'error_class' => 'Faraday::BadRequestError' } end let(:failed_date) do BenefitsDocuments::Utilities::Helpers.format_date_for_mailers(issue_instant) end it 'updates an evidence submission record to FAILED' do described_class.within_sidekiq_retries_exhausted_block(msg_with_errors) do allow(EvidenceSubmission).to receive(:find_by) .with({ id: msg_with_errors['args'][3] }) .and_return(evidence_submission_created) allow(EvidenceSubmission).to receive(:update!) expect(Rails.logger) .to receive(:info) .with('EVSS - Updated Evidence Submission Record to FAILED', any_args) expect(StatsD).to receive(:increment).with('silent_failure_avoided_no_confirmation', tags: ['service:claim-status', "function: #{message}"]) end failed_evidence_submission = EvidenceSubmission.find_by(id: evidence_submission_created.id) current_personalisation = JSON.parse(failed_evidence_submission.template_metadata)['personalisation'] expect(failed_evidence_submission.upload_status).to eql(BenefitsDocuments::Constants::UPLOAD_STATUS[:FAILED]) expect(failed_evidence_submission.error_message).to eql('EVSS::DocumentUpload document upload failure') expect(current_personalisation['date_failed']).to eql(failed_date) Timecop.freeze(current_date_time) do expect(failed_evidence_submission.failed_date).to be_within(1.second).of(current_date_time) expect(failed_evidence_submission.acknowledgement_date) .to be_within(1.second).of(current_date_time + 30.days) end Timecop.unfreeze end end context 'does not have an evidence submission id' do before do allow(Flipper).to receive(:enabled?).with(:cst_send_evidence_failure_emails).and_return(true) allow(EVSS::DocumentUpload).to receive(:update_evidence_submission_for_failure) allow(EVSS::DocumentUpload).to receive(:call_failure_notification) end let(:msg_with_nil_es_id) do { 'jid' => job_id, 'args' => [ { 'va_eauth_firstName' => 'Bob' }, user_account_uuid, { 'evss_claim_id' => claim_id, 'tracked_item_id' => tracked_item_id, 'document_type' => document_type, 'file_name' => file_name } ], 'created_at' => issue_instant, 'failed_at' => issue_instant } end it 'does not update an evidence submission record' do described_class.within_sidekiq_retries_exhausted_block(msg_with_nil_es_id) do allow(EvidenceSubmission).to receive(:find_by) .with({ id: nil }) .and_return(nil) end expect(EVSS::DocumentUpload).not_to have_received(:update_evidence_submission_for_failure) expect(EVSS::DocumentUpload).to have_received(:call_failure_notification) expect(EvidenceSubmission.count).to equal(0) end end context 'when args malformed' do let(:msg_args_malformed) do ## added 'test' so file would error { 'jid' => job_id, 'args' => [ 'test', { 'va_eauth_firstName' => 'Bob' }, user_account_uuid, { 'evss_claim_id' => claim_id, 'tracked_item_id' => tracked_item_id, 'document_type' => document_type, 'file_name' => file_name }, evidence_submission_created.id ], 'created_at' => issue_instant, 'failed_at' => issue_instant } end it 'fails to create a failed evidence submission record' do expect do described_class.within_sidekiq_retries_exhausted_block(msg_args_malformed) {} end.to raise_error(StandardError, "Missing fields in #{described_class}") end end context 'when error occurs updating evidence submission to FAILED' do let(:msg_args) do { 'jid' => job_id, 'args' => [ { 'va_eauth_firstName' => 'Bob' }, user_account_uuid, { 'evss_claim_id' => claim_id, 'tracked_item_id' => tracked_item_id, 'document_type' => document_type, 'file_name' => file_name }, evidence_submission_created.id ], 'created_at' => issue_instant, 'failed_at' => issue_instant } end let(:log_error_message) { "#{described_class} failed to update EvidenceSubmission" } let(:statsd_error_tags) { ['service:claim-status', "function: #{log_error_message}"] } before do allow_any_instance_of(EvidenceSubmission).to receive(:update!).and_raise(StandardError) allow(Rails.logger).to receive(:error) end it 'error is raised and logged' do described_class.within_sidekiq_retries_exhausted_block(msg_args) do expect(Rails.logger) .to receive(:error) .with(log_error_message, { message: 'StandardError' }) expect(StatsD).to receive(:increment).with('silent_failure', tags: statsd_error_tags) end end end context 'when evss returns a failure response' do it 'raises an error when EVSS returns a failure response' do VCR.use_cassette('evss/documents/upload_with_errors') do expect do described_class.new.perform(user_icn, document_data.to_serializable_hash, evidence_submission_created.id) end.to raise_error(StandardError) end end end end end context 'when :cst_send_evidence_submission_failure_emails is disabled' do before do allow(Flipper).to receive(:enabled?).with(:cst_send_evidence_submission_failure_emails).and_return(false) end let(:msg) do { 'jid' => job_id, 'args' => [{ 'va_eauth_firstName' => 'Bob' }, user_account_uuid, { 'evss_claim_id' => claim_id, 'tracked_item_id' => tracked_item_id, 'document_type' => document_type, 'file_name' => file_name }], 'created_at' => issue_instant, 'failed_at' => issue_instant } end let(:uploader_stub) { instance_double(EVSSClaimDocumentUploader) } let(:formatted_submit_date) do BenefitsDocuments::Utilities::Helpers.format_date_for_mailers(issue_instant) end it 'retrieves the file and uploads to EVSS' do allow(EVSSClaimDocumentUploader).to receive(:new) { uploader_stub } allow(EVSS::DocumentsService).to receive(:new) { client_stub } file = Rails.root.join('spec', 'fixtures', 'files', file_name).read allow(uploader_stub).to receive(:retrieve_from_store!).with(file_name) { file } allow(uploader_stub).to receive(:read_for_upload) { file } expect(uploader_stub).to receive(:remove!).once expect(client_stub).to receive(:upload).with(file, document_data) expect(EvidenceSubmission.count).to equal(0) described_class.new.perform(auth_headers, user.uuid, document_data.to_serializable_hash, nil) end context 'when cst_send_evidence_failure_emails is enabled' do before do allow(Flipper).to receive(:enabled?).with(:cst_send_evidence_failure_emails).and_return(true) end let(:log_message) { "#{described_class} exhaustion handler email queued" } let(:statsd_tags) { ['service:claim-status', 'function: evidence upload to EVSS'] } it 'calls EVSS::FailureNotification' do described_class.within_sidekiq_retries_exhausted_block(msg) do expect(EVSS::FailureNotification).to receive(:perform_async).with( user_account.icn, { first_name: 'Bob', document_type: document_description, filename: BenefitsDocuments::Utilities::Helpers.generate_obscured_file_name(file_name), date_submitted: formatted_submit_date, date_failed: formatted_submit_date } ) expect(EvidenceSubmission.count).to equal(0) expect(Rails.logger) .to receive(:info) .with(log_message) expect(StatsD).to receive(:increment).with('silent_failure_avoided_no_confirmation', tags: statsd_tags) end end end context 'when cst_send_evidence_failure_emails is disabled' do before do allow(Flipper).to receive(:enabled?).with(:cst_send_evidence_failure_emails).and_return(false) end it 'does not call EVSS::Failure Notification' do described_class.within_sidekiq_retries_exhausted_block(msg) do expect(EVSS::FailureNotification).not_to receive(:perform_async) end end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/evss/request_decision_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EVSS::RequestDecision, type: :job do let(:client_stub) { instance_double(EVSS::ClaimsService) } let(:user) { build(:user, :loa3) } let(:auth_headers) { EVSS::AuthHeaders.new(user).to_h } let(:evss_id) { 189_625 } it 'posts a waiver to EVSS' do allow(EVSS::ClaimsService).to receive(:new) { client_stub } expect(client_stub).to receive(:request_decision).with(evss_id) described_class.new.perform(auth_headers, evss_id) end end RSpec.describe EVSSClaim::RequestDecision, type: :job do it 're-queues the job into the new namespace' do expect { described_class.new.perform(nil, nil) } .to change { EVSS::RequestDecision.jobs.size } .from(0) .to(1) end end
0
code_files/vets-api-private/spec/sidekiq/evss
code_files/vets-api-private/spec/sidekiq/evss/disability_compensation_form/submit_form526_all_claim_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'disability_compensation/factories/api_provider_factory' require 'contention_classification/client' # pulled from vets-api/spec/support/disability_compensation_form/submissions/only_526.json ONLY_526_JSON_CLASSIFICATION_CODE = 'string' RSpec.describe EVSS::DisabilityCompensationForm::SubmitForm526AllClaim, type: :job do subject { described_class } # This needs to be modernized (using allow) before do Sidekiq::Job.clear_all allow(Flipper).to receive(:enabled?).and_call_original allow(Flipper).to receive(:enabled?).with(:validate_saved_claims_with_json_schemer).and_return(false) allow(Flipper).to receive(:enabled?).with(:disability_compensation_production_tester, anything).and_return(false) allow(Flipper).to receive(:enabled?).with(:disability_compensation_fail_submission, anything).and_return(false) allow(Flipper).to receive(:enabled?).with(:contention_classification_ml_classifier, anything).and_return(false) allow_any_instance_of(BenefitsClaims::Configuration).to receive(:access_token) .and_return('access_token') allow_any_instance_of(Auth::ClientCredentials::Service).to receive(:get_token) .and_return('fake_access_token') end let(:user) { create(:user, :loa3, :legacy_icn) } let(:user_account) { user.user_account } let(:auth_headers) do EVSS::DisabilityCompensationAuthHeaders.new(user).add_headers(EVSS::AuthHeaders.new(user).to_h) end describe '.perform_async' do define_negated_matcher :not_change, :change let(:saved_claim) { create(:va526ez) } let(:submitted_claim_id) { 600_130_094 } let(:submission) do create(:form526_submission, user_account:, user_uuid: user.uuid, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id) end let(:open_claims_cassette) { 'evss/claims/claims_without_open_compensation_claims' } let(:caseflow_cassette) { 'caseflow/appeals' } let(:rated_disabilities_cassette) { 'lighthouse/veteran_verification/disability_rating/200_response' } let(:lh_claims_cassette) { 'lighthouse/claims/200_response' } let(:submit_form_cassette) { 'evss/disability_compensation_form/submit_form_v2' } let(:lh_upload) { 'lighthouse/benefits_intake/200_lighthouse_intake_upload_location' } let(:evss_get_pdf) { 'form526_backup/200_evss_get_pdf' } let(:lh_intake_upload) { 'lighthouse/benefits_intake/200_lighthouse_intake_upload' } let(:lh_submission) { 'lighthouse/benefits_claims/submit526/200_synchronous_response' } let(:lh_longer_icn_claims) { 'lighthouse/claims/200_response_longer_icn' } let(:cassettes) do [open_claims_cassette, caseflow_cassette, rated_disabilities_cassette, submit_form_cassette, lh_upload, evss_get_pdf, lh_intake_upload, lh_submission, lh_claims_cassette, lh_longer_icn_claims] end let(:backup_klass) { Sidekiq::Form526BackupSubmissionProcess::Submit } before do cassettes.each { |cassette| VCR.insert_cassette(cassette) } end after do cassettes.each { |cassette| VCR.eject_cassette(cassette) } end def expect_retryable_error(error_class) subject.perform_async(submission.id) expect_any_instance_of(Sidekiq::Form526JobStatusTracker::Metrics).to receive(:increment_retryable).once expect(Form526JobStatus).to receive(:upsert).twice expect do described_class.drain end.to raise_error(error_class).and not_change(backup_klass.jobs, :size) end def expect_non_retryable_error subject.perform_async(submission.id) expect_any_instance_of(Sidekiq::Form526JobStatusTracker::Metrics).to receive(:increment_non_retryable).once expect(Form526JobStatus).to receive(:upsert).thrice expect_any_instance_of(EVSS::DisabilityCompensationForm::SubmitForm526AllClaim).to( receive(:non_retryable_error_handler).and_call_original ) described_class.drain end context 'Submission inspection for flashes' do before do allow(Rails.logger).to receive(:info) allow(StatsD).to receive(:increment) end def submit_it subject.perform_async(submission.id) VCR.use_cassette('contention_classification/contention_classification_null_response') do described_class.drain end submission.reload expect(Form526JobStatus.last.status).to eq 'success' end context 'without any flashes' do let(:submission) do create(:form526_submission, :asthma_claim_for_increase, user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id) end it 'does not log or push metrics' do submit_it expect(Rails.logger).not_to have_received(:info).with('Flash Prototype Added', anything) expect(StatsD).not_to have_received(:increment).with('worker.flashes', anything) end end context 'with flash but without prototype' do let(:submission) do create(:form526_submission, :without_diagnostic_code, user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id) end it 'does not log prototype statement but pushes metrics' do submit_it expect(Rails.logger).not_to have_received(:info).with('Flash Prototype Added', anything) expect(StatsD).to have_received(:increment).with( 'worker.flashes', tags: ['flash:Priority Processing - Veteran over age 85', 'prototype:false'] ).once end end context 'with ALS flash' do let(:submission) do create(:form526_submission, :als_claim_for_increase, user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id) end it 'logs prototype statement and pushes metrics' do submit_it expect(Rails.logger).to have_received(:info).with( 'Flash Prototype Added', { submitted_claim_id:, flashes: ['Amyotrophic Lateral Sclerosis'] } ).once expect(StatsD).to have_received(:increment).with( 'worker.flashes', tags: ['flash:Amyotrophic Lateral Sclerosis', 'prototype:true'] ).once end end context 'with multiple flashes' do let(:submission) do create(:form526_submission, :als_claim_for_increase_terminally_ill, user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id) end it 'logs prototype statement and pushes metrics' do submit_it expect(Rails.logger).to have_received(:info).with( 'Flash Prototype Added', { submitted_claim_id:, flashes: ['Amyotrophic Lateral Sclerosis', 'Terminally Ill'] } ).once expect(StatsD).to have_received(:increment).with( 'worker.flashes', tags: ['flash:Amyotrophic Lateral Sclerosis', 'prototype:true'] ).once expect(StatsD).to have_received(:increment).with( 'worker.flashes', tags: ['flash:Terminally Ill', 'prototype:false'] ).once end end end context 'Contention Classification' do let(:submission) do create(:form526_submission, :with_mixed_action_disabilities_and_free_text, user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id) end context 'with contention classification enabled' do it 'uses the expanded lookup endpoint as default' do mock_cc_client = instance_double(ContentionClassification::Client) allow(ContentionClassification::Client).to receive(:new).and_return(mock_cc_client) allow(mock_cc_client).to receive(:classify_vagov_contentions_expanded) expect_any_instance_of(Form526Submission).to receive(:classify_vagov_contentions).and_call_original expect(mock_cc_client).to receive(:classify_vagov_contentions_expanded) subject.perform_async(submission.id) described_class.drain end context 'with ml classification toggle enabled' do before do allow(Flipper).to receive(:enabled?).with(:contention_classification_ml_classifier, anything).and_return(true) end it 'uses the hybrid contention classification endpoint' do mock_cc_client = instance_double(ContentionClassification::Client) allow(ContentionClassification::Client).to receive(:new).and_return(mock_cc_client) allow(mock_cc_client).to receive(:classify_vagov_contentions_hybrid) expect_any_instance_of(Form526Submission).to receive(:classify_vagov_contentions).and_call_original expect(mock_cc_client).to receive(:classify_vagov_contentions_hybrid) subject.perform_async(submission.id) described_class.drain end end context 'with ml classification toggle disabled' do before do allow(Flipper).to receive(:enabled?).with(:contention_classification_ml_classifier, anything).and_return(false) end it 'uses the expanded lookup endpoint' do mock_cc_client = instance_double(ContentionClassification::Client) allow(ContentionClassification::Client).to receive(:new).and_return(mock_cc_client) allow(mock_cc_client).to receive(:classify_vagov_contentions_expanded) expect_any_instance_of(Form526Submission).to receive(:classify_vagov_contentions).and_call_original expect(mock_cc_client).to receive(:classify_vagov_contentions_expanded) subject.perform_async(submission.id) described_class.drain end end context 'when diagnostic code is not set' do let(:submission) do create(:form526_submission, :without_diagnostic_code, user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id) end end context 'when diagnostic code is set' do it 'still completes form 526 submission when CC fails' do subject.perform_async(submission.id) expect do VCR.use_cassette('contention_classification/contention_classification_failure') do described_class.drain end end.not_to change(backup_klass.jobs, :size) expect(Form526JobStatus.last.status).to eq 'success' end it 'handles null response gracefully' do subject.perform_async(submission.id) expect do VCR.use_cassette('contention_classification/contention_classification_null_response') do described_class.drain submission.reload final_code = submission.form['form526']['form526']['disabilities'][0]['classificationCode'] expect(final_code).to eq(ONLY_526_JSON_CLASSIFICATION_CODE) end end.not_to change(Sidekiq::Form526BackupSubmissionProcess::Submit.jobs, :size) expect(Form526JobStatus.last.status).to eq 'success' end it 'updates Form526Submission form with id' do expect(described_class).to be < EVSS::DisabilityCompensationForm::SubmitForm526 subject.perform_async(submission.id) expect do VCR.use_cassette('contention_classification/fully_classified_contention_classification') do described_class.drain submission.reload final_code = submission.form['form526']['form526']['disabilities'][0]['classificationCode'] expect(final_code).to eq(9012) end end.not_to change(Sidekiq::Form526BackupSubmissionProcess::Submit.jobs, :size) end end end it 'does something when multi-contention api endpoint is hit' do subject.perform_async(submission.id) expect do VCR.use_cassette('contention_classification/multi_contention_classification') do described_class.drain end end.not_to change(Sidekiq::Form526BackupSubmissionProcess::Submit.jobs, :size) submission.reload classification_codes = submission.form['form526']['form526']['disabilities'].pluck('classificationCode') expect(classification_codes).to eq([9012, 8994, nil, nil]) end it 'uses expanded classification to classify contentions' do subject.perform_async(submission.id) expect do VCR.use_cassette('contention_classification/expanded_classification') do described_class.drain end end.not_to change(Sidekiq::Form526BackupSubmissionProcess::Submit.jobs, :size) submission.reload classification_codes = submission.form['form526']['form526']['disabilities'].pluck('classificationCode') expect(classification_codes).to eq([9012, 8994, nil, 8997]) end context 'with ml classification toggle enabled' do before do allow(Flipper).to receive(:enabled?).with(:contention_classification_ml_classifier, anything).and_return(true) end it 'uses hybrid classifier to classify contentions' do subject.perform_async(submission.id) expect do VCR.use_cassette('contention_classification/hybrid_contention_classification') do described_class.drain end end.not_to change(Sidekiq::Form526BackupSubmissionProcess::Submit.jobs, :size) submission.reload classification_codes = submission.form['form526']['form526']['disabilities'].pluck('classificationCode') expect(classification_codes).to eq([9012, 8994, 8989, 8997]) end end context 'with ml classification toggle disabled' do before do allow(Flipper).to receive(:enabled?).with(:contention_classification_ml_classifier, anything).and_return(false) end it 'uses expanded classification to classify contentions' do subject.perform_async(submission.id) expect do VCR.use_cassette('contention_classification/expanded_classification') do described_class.drain end end.not_to change(Sidekiq::Form526BackupSubmissionProcess::Submit.jobs, :size) submission.reload classification_codes = submission.form['form526']['form526']['disabilities'].pluck('classificationCode') expect(classification_codes).to eq([9012, 8994, nil, 8997]) end end context 'when the disabilities array is empty' do before do allow(Rails.logger).to receive(:info) end let(:submission) do create(:form526_submission, :with_empty_disabilities, user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id) end it 'returns false to skip classification and continue other jobs' do subject.perform_async(submission.id) expect(submission.update_contention_classification_all!).to be false expect(Rails.logger).to have_received(:info).with( "No disabilities found for classification on claim #{submission.id}" ) end it 'does not call va-gov-claim-classifier' do subject.perform_async(submission.id) described_class.drain expect(submission).not_to receive(:classify_vagov_contentions) end end end context 'with a successful submission job' do it 'queues a job for submit' do expect do subject.perform_async(submission.id) end.to change(subject.jobs, :size).by(1) end it 'submits successfully' do subject.perform_async(submission.id) expect { described_class.drain }.not_to change(backup_klass.jobs, :size) expect(Form526JobStatus.last.status).to eq 'success' end it 'submits successfully without calling classification service' do subject.perform_async(submission.id) expect do VCR.use_cassette('contention_classification/multi_contention_classification') do described_class.drain end end.not_to change(backup_klass.jobs, :size) expect(Form526JobStatus.last.status).to eq 'success' end it 'does not call contention classification endpoint' do subject.perform_async(submission.id) expect(submission).not_to receive(:classify_vagov_contentions) described_class.drain end context 'with an MAS-related diagnostic code' do let(:submission) do create(:form526_submission, :non_rrd_with_mas_diagnostic_code, user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id) end let(:mas_cassette) { 'mail_automation/mas_initiate_apcas_request' } let(:cassettes) do [open_claims_cassette, rated_disabilities_cassette, submit_form_cassette, mas_cassette, lh_claims_cassette, lh_longer_icn_claims] end before do allow(StatsD).to receive(:increment) end it 'sends form526 to the MAS endpoint successfully' do subject.perform_async(submission.id) described_class.drain expect(Form526JobStatus.last.status).to eq 'success' rrd_submission = Form526Submission.find(Form526JobStatus.last.form526_submission_id) expect(rrd_submission.form.dig('rrd_metadata', 'mas_packetId')).to eq '12345' expect(StatsD).to have_received(:increment) .with('worker.rapid_ready_for_decision.notify_mas.success').once end it 'sends an email for tracking purposes' do subject.perform_async(submission.id) described_class.drain expect(ActionMailer::Base.deliveries.last.subject).to eq 'MA claim - 6847' end context 'when MAS endpoint handshake fails' do let(:mas_cassette) { 'mail_automation/mas_initiate_apcas_request_failure' } it 'handles MAS endpoint handshake failure by sending failure notification' do subject.perform_async(submission.id) described_class.drain expect(ActionMailer::Base.deliveries.last.subject).to eq "Failure: MA claim - #{submitted_claim_id}" expect(StatsD).to have_received(:increment) .with('worker.rapid_ready_for_decision.notify_mas.failure').once end end context 'MAS-related claim that already includes classification code' do let(:submission) do create(:form526_submission, :mas_diagnostic_code_with_classification, user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id) end it 'already includes classification code and does not modify' do subject.perform_async(submission.id) described_class.drain mas_submission = Form526Submission.find(Form526JobStatus.last.form526_submission_id) expect(mas_submission.form.dig('form526', 'form526', 'disabilities').first['classificationCode']).to eq '8935' end end context 'when the rated disability has decision code NOTSVCCON in EVSS' do let(:rated_disabilities_cassette) do 'lighthouse/veteran_verification/disability_rating/200_Not_Connected_response' end it 'skips forwarding to MAS' do subject.perform_async(submission.id) described_class.drain expect(Form526JobStatus.last.status).to eq 'success' rrd_submission = Form526Submission.find(submission.id) expect(rrd_submission.form.dig('rrd_metadata', 'mas_packetId')).to be_nil end end end context 'with multiple MAS-related diagnostic codes' do let(:submission) do create(:form526_submission, :with_multiple_mas_diagnostic_code, user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id) end context 'when tracking and APCAS notification are enabled for all claims' do it 'calls APCAS and sends two emails' do VCR.use_cassette('mail_automation/mas_initiate_apcas_request') do subject.perform_async(submission.id) end described_class.drain expect(ActionMailer::Base.deliveries.length).to eq 2 end end end context 'with Lighthouse as submission provider' do let(:user) { create(:user, :loa3, :legacy_icn) } let(:submission) do create(:form526_submission, :with_everything, user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id, submit_endpoint: 'claims_api') end let(:headers) { { 'content-type' => 'application/json' } } it 'performs a successful submission' do subject.perform_async(submission.id) expect { described_class.drain }.not_to change(backup_klass.jobs, :size) expect(Form526JobStatus.last.status).to eq Form526JobStatus::STATUS[:success] submission.reload expect(submission.submitted_claim_id).to eq(Form526JobStatus.last.submission.submitted_claim_id) end it 'retries UpstreamUnprocessableEntity errors' do body = { 'errors' => [{ 'status' => '422', 'title' => 'Backend Service Exception', 'detail' => 'The claim failed to establish' }] } allow_any_instance_of(BenefitsClaims::Service).to receive(:prepare_submission_body) .and_raise(Faraday::UnprocessableEntityError.new( body:, status: 422, headers: )) expect_retryable_error(Common::Exceptions::UpstreamUnprocessableEntity) end it 'retries with a Net::ReadTimeout Error' do error = Net::ReadTimeout.new('#<TCPSocket:(closed)>') allow_any_instance_of(BenefitsClaims::Service).to receive(:submit526).and_raise(error) expect_retryable_error(error) end it 'retries with a Faraday::TimeoutError Error' do error = Faraday::TimeoutError.new allow_any_instance_of(BenefitsClaims::Service).to receive(:submit526).and_raise(error) expect_retryable_error(error) end it 'retries with a Common::Exceptions::Timeout Error' do error = Common::Exceptions::Timeout.new('Timeout error') allow_any_instance_of(BenefitsClaims::Service).to receive(:submit526).and_raise(error) expect_retryable_error(error) end it 'does not retry UnprocessableEntity errors with "pointer" defined' do body = { 'errors' => [{ 'status' => '422', 'title' => 'Backend Service Exception', 'detail' => 'The claim failed to establish', 'source' => { 'pointer' => 'data/attributes/' } }] } allow_any_instance_of(BenefitsClaims::Service).to receive(:prepare_submission_body) .and_raise(Faraday::UnprocessableEntityError.new( body:, status: 422, headers: )) expect_non_retryable_error end it 'does not retry UnprocessableEntity errors with "retries will fail" in detail message' do body = { 'errors' => [{ 'status' => '422', 'title' => 'Backend Service Exception', 'detail' => 'The claim failed to establish. rEtries WilL fAiL.' }] } allow_any_instance_of(BenefitsClaims::Service).to receive(:prepare_submission_body) .and_raise(Faraday::UnprocessableEntityError.new( body:, status: 422, headers: )) expect_non_retryable_error end Lighthouse::ServiceException::ERROR_MAP.slice(429, 499, 500, 501, 502, 503).each do |status, error_class| it "throws a #{status} error if Lighthouse sends it back" do allow_any_instance_of(Form526Submission).to receive(:prepare_for_evss!).and_return(nil) allow_any_instance_of(BenefitsClaims::Service).to receive(:prepare_submission_body) .and_raise(error_class.new(status:)) expect_retryable_error(error_class) end it "throws a #{status} error if Lighthouse sends it back for rated disabilities" do allow_any_instance_of(Flipper) .to(receive(:enabled?)) .with(:validate_saved_claims_with_json_schemer) .and_return(false) allow_any_instance_of(EVSS::DisabilityCompensationForm::SubmitForm526) .to(receive(:fail_submission_feature_enabled?)) .and_return(false) allow_any_instance_of(Form526ClaimFastTrackingConcern).to receive(:pending_eps?) .and_return(false) allow_any_instance_of(Form526ClaimFastTrackingConcern).to receive(:classify_vagov_contentions) .and_return(nil) allow_any_instance_of(VeteranVerification::Service).to receive(:get_rated_disabilities) .and_raise(error_class.new(status:)) expect_retryable_error(error_class) end end context 'when disability_526_send_form526_submitted_email is enabled' do before do allow(Flipper).to receive(:enabled?) .with(:disability_526_send_form526_submitted_email) .and_return(true) end it 'sends the submitted email' do expect(Form526SubmittedEmailJob).to receive(:perform_async).once subject.perform_async(submission.id) described_class.drain end end context 'when disability_526_send_form526_submitted_email is disabled' do before do allow(Flipper).to receive(:enabled?) .with(:disability_526_send_form526_submitted_email) .and_return(false) end it 'does not send the submitted email' do expect(Form526SubmittedEmailJob).not_to receive(:perform_async) subject.perform_async(submission.id) described_class.drain end end end end context 'with non-MAS-related diagnostic code' do let(:submission) do create(:form526_submission, :with_uploads, user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id) end it 'does not set a classification code for irrelevant claims' do subject.perform_async(submission.id) described_class.drain mas_submission = Form526Submission.find(Form526JobStatus.last.form526_submission_id) expect(mas_submission.form.dig('form526', 'form526', 'disabilities').first['classificationCode']).to eq '8935' end end context 'when retrying a job' do it 'doesnt recreate the job status' do subject.perform_async(submission.id) jid = subject.jobs.last['jid'] values = { form526_submission_id: submission.id, job_id: jid, job_class: subject.class, status: Form526JobStatus::STATUS[:try], updated_at: Time.now.utc } Form526JobStatus.upsert(values, unique_by: :job_id) expect_any_instance_of(Sidekiq::Form526JobStatusTracker::Metrics).to( receive(:increment_success).with(false, 'evss').once ) described_class.drain job_status = Form526JobStatus.where(job_id: values[:job_id]).first expect(job_status.status).to eq 'success' expect(job_status.error_class).to be_nil expect(job_status.job_class).to eq 'SubmitForm526AllClaim' expect(Form526JobStatus.count).to eq 1 end end context 'with an upstream service error for EP code not valid' do it 'sets the transaction to "non_retryable_error"' do VCR.use_cassette('evss/disability_compensation_form/submit_200_with_ep_not_valid') do subject.perform_async(submission.id) expect_any_instance_of(Sidekiq::Form526JobStatusTracker::Metrics) .to receive(:increment_non_retryable).once expect { described_class.drain }.to change(backup_klass.jobs, :size).by(1) expect(Form526JobStatus.last.status).to eq Form526JobStatus::STATUS[:non_retryable_error] expect(backup_klass.jobs.last['class']).to eq(backup_klass.to_s) end end end context 'with a max ep code server error' do it 'sets the transaction to "non_retryable_error"' do VCR.use_cassette('evss/disability_compensation_form/submit_500_with_max_ep_code') do subject.perform_async(submission.id) expect_any_instance_of(Sidekiq::Form526JobStatusTracker::Metrics) .to receive(:increment_non_retryable).once expect { described_class.drain }.to change(backup_klass.jobs, :size).by(1) expect(Form526JobStatus.last.status).to eq Form526JobStatus::STATUS[:non_retryable_error] expect(backup_klass.jobs.last['class']).to eq(backup_klass.to_s) end end end context 'with a unused [418] error' do it 'sets the transaction to "retryable_error"' do VCR.use_cassette('evss/disability_compensation_form/submit_200_with_418') do backup_jobs_count = backup_klass.jobs.count subject.perform_async(submission.id) expect_any_instance_of(Sidekiq::Form526JobStatusTracker::Metrics).to receive(:increment_retryable).once expect { described_class.drain }.to raise_error(EVSS::DisabilityCompensationForm::ServiceException) .and not_change(backup_klass.jobs, :size) expect(Form526JobStatus.last.status).to eq Form526JobStatus::STATUS[:retryable_error] expect(backup_klass.jobs.count).to eq(backup_jobs_count) end end end context 'with a BGS error' do it 'sets the transaction to "retryable_error"' do VCR.use_cassette('evss/disability_compensation_form/submit_200_with_bgs_error') do subject.perform_async(submission.id) expect_any_instance_of(Sidekiq::Form526JobStatusTracker::Metrics).to receive(:increment_retryable).once expect { described_class.drain }.to raise_error(EVSS::DisabilityCompensationForm::ServiceException) .and not_change(backup_klass.jobs, :size) expect(Form526JobStatus.last.status).to eq Form526JobStatus::STATUS[:retryable_error] end end end context 'with a pif in use server error' do it 'sets the transaction to "non_retryable_error"' do VCR.use_cassette('evss/disability_compensation_form/submit_500_with_pif_in_use') do subject.perform_async(submission.id) expect_any_instance_of(Sidekiq::Form526JobStatusTracker::Metrics) .to receive(:increment_non_retryable).once expect { described_class.drain }.to change(backup_klass.jobs, :size).by(1) expect(Form526JobStatus.last.status).to eq Form526JobStatus::STATUS[:non_retryable_error] expect(backup_klass.jobs.last['class']).to eq(backup_klass.to_s) end end end context 'with a VeteranRecordWsClientException java error' do it 'sets the transaction to "retryable_error"' do VCR.use_cassette('evss/disability_compensation_form/submit_500_with_java_ws_error') do subject.perform_async(submission.id) expect_any_instance_of(Sidekiq::Form526JobStatusTracker::Metrics).to receive(:increment_retryable).once expect { described_class.drain }.to raise_error(EVSS::DisabilityCompensationForm::ServiceException) expect(Form526JobStatus.last.status).to eq Form526JobStatus::STATUS[:retryable_error] end end end context 'with an error that is not mapped' do it 'sets the transaction to "non_retryable_error"' do VCR.use_cassette('evss/disability_compensation_form/submit_500_with_unmapped') do subject.perform_async(submission.id) expect { described_class.drain }.to change(backup_klass.jobs, :size).by(1) expect(Form526JobStatus.last.status).to eq Form526JobStatus::STATUS[:non_retryable_error] end end end context 'with an unexpected error' do before do allow_any_instance_of(Faraday::Connection).to receive(:post).and_raise(StandardError.new('foo')) end it 'sets the transaction to "non_retryable_error"' do subject.perform_async(submission.id) expect { described_class.drain }.to change(backup_klass.jobs, :size).by(1) expect(Form526JobStatus.last.status).to eq Form526JobStatus::STATUS[:non_retryable_error] end context 'when disability_526_send_form526_submitted_email is enabled' do before do allow(Flipper).to receive(:enabled?) .with(:disability_526_send_form526_submitted_email) .and_return(true) end it 'behaves sends the submitted email in the backup path' do expect(Form526SubmittedEmailJob).to receive(:perform_async).once subject.perform_async(submission.id) described_class.drain end end context 'when disability_526_send_form526_submitted_email is disabled' do before do allow(Flipper).to receive(:enabled?) .with(:disability_526_send_form526_submitted_email) .and_return(false) end it 'behaves does not send the submitted email in the backup path' do expect(Form526SubmittedEmailJob).not_to receive(:perform_async) subject.perform_async(submission.id) described_class.drain end end end context 'with an RRD claim' do context 'with a non-retryable (unexpected) error' do before do allow_any_instance_of(Faraday::Connection).to receive(:post).and_raise(StandardError.new('foo')) end it 'sends a "non-retryable" RRD alert' do subject.perform_async(submission.id) described_class.drain expect(Form526JobStatus.last.status).to eq Form526JobStatus::STATUS[:non_retryable_error] end end end context 'MST Metrics Logging' do before do allow(Rails.logger).to receive(:info) end def submit_and_expect_success subject.perform_async(submission.id) VCR.use_cassette('contention_classification/contention_classification_null_response') do described_class.drain end submission.reload expect(Form526JobStatus.last.status).to eq 'success' end context 'when form0781 is not present' do let(:submission) do create(:form526_submission, user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id) end it 'does not log MST metrics' do submit_and_expect_success expect(Rails.logger).not_to have_received(:info).with('Form526 MST checkbox selection', anything) end end context 'when form0781 is present' do context 'when mst checkbox is false' do let(:submission) do sub = create(:form526_submission, :with_0781v2, user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id) form_data = sub.form form_data['form0781']['form0781v2']['eventTypes']['mst'] = false sub.update!(form_json: form_data.to_json) sub.invalidate_form_hash sub end it 'does not log MST metrics' do submit_and_expect_success expect(Rails.logger).not_to have_received(:info).with('Form526 MST checkbox selection', anything) end end context 'when mst checkbox is true' do context 'with classification codes populated by contention classification service' do let(:submission) do sub = create(:form526_submission, :with_0781v2, user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id) form_data = sub.form form_data['form0781']['form0781v2']['eventTypes']['mst'] = true form_data['form526']['form526']['disabilities'] = [ { 'name' => 'PTSD (post traumatic stress disorder)', 'diagnosticCode' => 9411, 'disabilityActionType' => 'NEW' }, { 'name' => 'Anxiety', 'diagnosticCode' => 9400, 'disabilityActionType' => 'INCREASE' }, { 'name' => 'Some condition that cant be classified because of free text', 'disabilityActionType' => 'NEW' } ] sub.update!(form_json: form_data.to_json) sub.invalidate_form_hash sub end it 'logs MST metrics with classification codes from service response' do subject.perform_async(submission.id) VCR.use_cassette('contention_classification/mental_health_conditions') do described_class.drain end submission.reload expect(Rails.logger).to have_received(:info).with( 'Form526-0781 MST selected', { id: submission.id, disabilities: [ { name: 'PTSD (post traumatic stress disorder)', disabilityActionType: 'NEW', diagnosticCode: 9411, classificationCode: 8989 }, { name: 'Anxiety', disabilityActionType: 'INCREASE', diagnosticCode: 9400, classificationCode: 8989 }, { name: 'unclassifiable', disabilityActionType: 'NEW', diagnosticCode: nil, classificationCode: nil } ] } ) end end end end end end end
0
code_files/vets-api-private/spec/sidekiq/evss
code_files/vets-api-private/spec/sidekiq/evss/disability_compensation_form/submit_form0781_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EVSS::DisabilityCompensationForm::SubmitForm0781, type: :job do subject { described_class } before do Sidekiq::Job.clear_all # Toggle off all flippers allow(Flipper).to receive(:enabled?) .with(:disability_compensation_use_api_provider_for_0781_uploads).and_return(false) allow(Flipper).to receive(:enabled?).with('disability_compensation_upload_0781_to_lighthouse', instance_of(User)).and_return(false) allow(Flipper).to receive(:enabled?).with(:form526_send_0781_failure_notification).and_return(false) allow(Flipper).to receive(:enabled?).with(:saved_claim_schema_validation_disable).and_return(false) allow(Flipper).to receive(:enabled?).with(:disability_compensation_0781v2_extras_redesign, anything).and_return(false) end let(:user) { create(:user, :loa3, :with_terms_of_use_agreement) } let(:user_account) { user.user_account } let(:auth_headers) do EVSS::DisabilityCompensationAuthHeaders.new(user).add_headers(EVSS::AuthHeaders.new(user).to_h) end let(:evss_claim_id) { 123_456_789 } let(:saved_claim) { create(:va526ez) } # contains 0781 and 0781a let(:saved_claim_with_0781v2) { create(:va526ez_0781v2) } # contains 0781V2 let(:form0781) do File.read 'spec/support/disability_compensation_form/submissions/with_0781.json' end let(:form0781v2) do File.read 'spec/support/disability_compensation_form/submissions/with_0781v2.json' end VCR.configure do |c| c.default_cassette_options = { match_requests_on: [:method, VCR.request_matchers.uri_without_params(:qqfile, :docType, :docTypeDescription)] } # the response body may not be encoded according to the encoding specified in the HTTP headers # VCR will base64 encode the body of the request or response during serialization, # in order to preserve the bytes exactly. c.preserve_exact_body_bytes do |http_message| http_message.body.encoding.name == 'ASCII-8BIT' || !http_message.body.valid_encoding? end end describe '.perform_async' do context 'when a submission has both 0781 and 0781a' do let(:submission) do Form526Submission.create(user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id, form_json: form0781, submitted_claim_id: evss_claim_id) end context 'with a successful submission job' do it 'queues a job for submit' do expect do subject.perform_async(submission.id) end.to change(subject.jobs, :size).by(1) end it 'submits successfully' do VCR.use_cassette('evss/disability_compensation_form/submit_0781') do subject.perform_async(submission.id) jid = subject.jobs.last['jid'] described_class.drain expect(jid).not_to be_empty end end end context 'with a submission timeout' do before do allow_any_instance_of(Faraday::Connection).to receive(:post).and_raise(Faraday::TimeoutError) end it 'raises a gateway timeout error' do subject.perform_async(submission.id) expect { described_class.drain }.to raise_error(StandardError) end end context 'with an unexpected error' do before do allow_any_instance_of(Faraday::Connection).to receive(:post).and_raise(StandardError.new('foo')) end it 'raises a standard error' do subject.perform_async(submission.id) expect { described_class.drain }.to raise_error(StandardError) end end end context 'when a submission has 0781v2' do let(:submission) do Form526Submission.create(user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim_with_0781v2.id, form_json: form0781v2, submitted_claim_id: evss_claim_id) end context 'with a successful submission job' do it 'queues a job for submit' do expect do subject.perform_async(submission.id) end.to change(subject.jobs, :size).by(1) end it 'submits successfully' do VCR.use_cassette('evss/disability_compensation_form/submit_0781') do subject.perform_async(submission.id) jid = subject.jobs.last['jid'] described_class.drain expect(jid).not_to be_empty end end end context 'with a submission timeout' do before do allow_any_instance_of(Faraday::Connection).to receive(:post).and_raise(Faraday::TimeoutError) end it 'raises a gateway timeout error' do subject.perform_async(submission.id) expect { described_class.drain }.to raise_error(StandardError) end end context 'with an unexpected error' do before do allow_any_instance_of(Faraday::Connection).to receive(:post).and_raise(StandardError.new('foo')) end it 'raises a standard error' do subject.perform_async(submission.id) expect { described_class.drain }.to raise_error(StandardError) end end end end context 'catastrophic failure state' do describe 'when all retries are exhausted' do let!(:form526_submission) { create(:form526_submission, user_account:) } let!(:form526_job_status) { create(:form526_job_status, :retryable_error, form526_submission:, job_id: 1) } it 'updates a StatsD counter and updates the status on an exhaustion event' do subject.within_sidekiq_retries_exhausted_block({ 'jid' => form526_job_status.job_id }) do # Will receieve increment for failure mailer metric allow(StatsD).to receive(:increment).with( 'shared.sidekiq.default.EVSS_DisabilityCompensationForm_Form0781DocumentUploadFailureEmail.enqueue' ) expect(StatsD).to receive(:increment).with("#{subject::STATSD_KEY_PREFIX}.exhausted") expect(Rails).to receive(:logger).and_call_original end form526_job_status.reload expect(form526_job_status.status).to eq(Form526JobStatus::STATUS[:exhausted]) end context 'when an error occurs during exhaustion handling and FailureEmail fails to enqueue' do let!(:failure_email) { EVSS::DisabilityCompensationForm::Form0781DocumentUploadFailureEmail } let!(:zsf_tag) { Form526Submission::ZSF_DD_TAG_SERVICE } let!(:zsf_monitor) { ZeroSilentFailures::Monitor.new(zsf_tag) } before do allow(Flipper).to receive(:enabled?).with(:form526_send_0781_failure_notification).and_return(true) allow(ZeroSilentFailures::Monitor).to receive(:new).with(zsf_tag).and_return(zsf_monitor) end it 'logs a silent failure' do expect(zsf_monitor).to receive(:log_silent_failure).with( { job_id: form526_job_status.job_id, error_class: nil, error_message: 'An error occurred', timestamp: instance_of(Time), form526_submission_id: form526_submission.id }, user_account.id, call_location: instance_of(Logging::CallLocation) ) args = { 'jid' => form526_job_status.job_id, 'args' => [form526_submission.id] } expect do subject.within_sidekiq_retries_exhausted_block(args) do allow(failure_email).to receive(:perform_async).and_raise(StandardError, 'Simulated error') end end.to raise_error(StandardError, 'Simulated error') end end context 'when the form526_send_0781_failure_notification Flipper is enabled' do before do allow(Flipper).to receive(:enabled?).with(:form526_send_0781_failure_notification).and_return(true) end it 'enqueues a failure notification mailer to send to the veteran' do subject.within_sidekiq_retries_exhausted_block( { 'jid' => form526_job_status.job_id, 'args' => [form526_submission.id] } ) do expect(EVSS::DisabilityCompensationForm::Form0781DocumentUploadFailureEmail) .to receive(:perform_async).with(form526_submission.id) end end end context 'when the form526_send_0781_failure_notification Flipper is disabled' do before do allow(Flipper).to receive(:enabled?).with(:form526_send_0781_failure_notification).and_return(false) end it 'does not enqueue a failure notification mailer to send to the veteran' do subject.within_sidekiq_retries_exhausted_block( { 'jid' => form526_job_status.job_id, 'args' => [form526_submission.id] } ) do expect(EVSS::DisabilityCompensationForm::Form0781DocumentUploadFailureEmail) .not_to receive(:perform_async) end end end context 'when the API Provider uploads are enabled' do before do allow(Flipper).to receive(:enabled?) .with(:disability_compensation_use_api_provider_for_0781_uploads).and_return(true) end let(:sidekiq_job_exhaustion_errors) do { 'jid' => form526_job_status.job_id, 'error_class' => 'Broken Job Error', 'error_message' => 'Your Job Broke', 'args' => [form526_submission.id] } end context 'for a Lighthouse upload' do it 'logs the job failure' do allow(Flipper).to receive(:enabled?).with('disability_compensation_upload_0781_to_lighthouse', instance_of(User)).and_return(true) subject.within_sidekiq_retries_exhausted_block(sidekiq_job_exhaustion_errors) do expect_any_instance_of(LighthouseSupplementalDocumentUploadProvider) .to receive(:log_uploading_job_failure) .with(EVSS::DisabilityCompensationForm::SubmitForm0781, 'Broken Job Error', 'Your Job Broke') end end end context 'for an EVSS Upload' do it 'logs the job failure' do allow(Flipper).to receive(:enabled?).with('disability_compensation_upload_0781_to_lighthouse', instance_of(User)).and_return(false) subject.within_sidekiq_retries_exhausted_block(sidekiq_job_exhaustion_errors) do expect_any_instance_of(EVSSSupplementalDocumentUploadProvider).to receive(:log_uploading_job_failure) .with(EVSS::DisabilityCompensationForm::SubmitForm0781, 'Broken Job Error', 'Your Job Broke') end end end end end end context 'When an ApiProvider is used for uploads' do before do allow(Flipper).to receive(:enabled?) .with(:disability_compensation_use_api_provider_for_0781_uploads).and_return(true) # StatsD metrics are incremented in several callbacks we're not testing here so we need to allow them allow(StatsD).to receive(:increment) # There is an ensure block in the upload_to_vbms method that deletes the generated PDF allow(File).to receive(:delete).and_return(nil) end context 'when a submission includes either 0781 and/or 0781a' do let(:path_to_0781_fixture) { 'spec/fixtures/pdf_fill/21-0781/simple.pdf' } let(:parsed_0781_form) { JSON.parse(submission.form_to_json(Form526Submission::FORM_0781))['form0781'] } let(:form0781_only) do original = JSON.parse(form0781) original['form0781'].delete('form0781a') original.to_json end let(:path_to_0781a_fixture) { 'spec/fixtures/pdf_fill/21-0781a/kitchen_sink.pdf' } let(:parsed_0781a_form) { JSON.parse(submission.form_to_json(Form526Submission::FORM_0781))['form0781a'] } let(:form0781a_only) do original = JSON.parse(form0781) original['form0781'].delete('form0781') original.to_json end let(:submission) do Form526Submission.create(user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id, form_json: form0781, # contains 0781 and 0781a submitted_claim_id: evss_claim_id) end let(:perform_upload) do subject.perform_async(submission.id) described_class.drain end context 'when the disability_compensation_upload_0781_to_lighthouse flipper is enabled' do let(:faraday_response) { instance_double(Faraday::Response) } let(:lighthouse_request_id) { Faker::Number.number(digits: 8) } let(:lighthouse_0781_document) do LighthouseDocument.new( claim_id: submission.submitted_claim_id, participant_id: submission.auth_headers['va_eauth_pid'], document_type: 'L228' ) end let(:lighthouse_0781a_document) do LighthouseDocument.new( claim_id: submission.submitted_claim_id, participant_id: submission.auth_headers['va_eauth_pid'], document_type: 'L229' ) end let(:expected_statsd_metrics_prefix) do 'worker.evss.submit_form0781.lighthouse_supplemental_document_upload_provider' end before do allow(Flipper).to receive(:enabled?).with('disability_compensation_upload_0781_to_lighthouse', instance_of(User)).and_return(true) allow(BenefitsDocuments::Form526::UploadSupplementalDocumentService).to receive(:call) .and_return(faraday_response) allow(faraday_response).to receive(:body).and_return( { 'data' => { 'success' => true, 'requestId' => lighthouse_request_id } } ) end context 'when a submission has both 0781 and 0781a' do context 'when the request is successful' do it 'uploads both documents to Lighthouse' do # 0781 allow_any_instance_of(described_class) .to receive(:generate_stamp_pdf) .with(parsed_0781_form, submission.submitted_claim_id, '21-0781') .and_return(path_to_0781_fixture) allow_any_instance_of(LighthouseSupplementalDocumentUploadProvider) .to receive(:generate_upload_document) .and_return(lighthouse_0781_document) expect(BenefitsDocuments::Form526::UploadSupplementalDocumentService) .to receive(:call) .with(File.read(path_to_0781_fixture), lighthouse_0781a_document) # 0781a allow_any_instance_of(described_class) .to receive(:generate_stamp_pdf) .with(parsed_0781a_form, submission.submitted_claim_id, '21-0781a') .and_return(path_to_0781a_fixture) allow_any_instance_of(LighthouseSupplementalDocumentUploadProvider) .to receive(:generate_upload_document) .and_return(lighthouse_0781a_document) expect(BenefitsDocuments::Form526::UploadSupplementalDocumentService) .to receive(:call) .with(File.read(path_to_0781a_fixture), lighthouse_0781a_document) perform_upload end it 'logs the upload attempt with the correct job prefix' do expect(StatsD).to receive(:increment).with( "#{expected_statsd_metrics_prefix}.upload_attempt" ).twice # For 0781 and 0781a perform_upload end it 'increments the correct StatsD success metric' do expect(StatsD).to receive(:increment).with( "#{expected_statsd_metrics_prefix}.upload_success" ).twice # For 0781 and 0781a perform_upload end it 'creates a pending Lighthouse526DocumentUpload record so we can poll Lighthouse later' do upload_attributes = { aasm_state: 'pending', form526_submission_id: submission.id, lighthouse_document_request_id: lighthouse_request_id } expect(Lighthouse526DocumentUpload.where(**upload_attributes).count).to eq(0) perform_upload expect(Lighthouse526DocumentUpload.where(**upload_attributes) .where(document_type: 'Form 0781').count).to eq(1) expect(Lighthouse526DocumentUpload.where(**upload_attributes) .where(document_type: 'Form 0781a').count).to eq(1) end end end context 'when a submission has 0781 only' do before do submission.update(form_json: form0781_only) end context 'when the request is successful' do it 'uploads to Lighthouse' do allow_any_instance_of(described_class) .to receive(:generate_stamp_pdf) .with(parsed_0781_form, submission.submitted_claim_id, '21-0781') .and_return(path_to_0781_fixture) allow_any_instance_of(LighthouseSupplementalDocumentUploadProvider) .to receive(:generate_upload_document) .and_return(lighthouse_0781_document) expect(BenefitsDocuments::Form526::UploadSupplementalDocumentService) .to receive(:call) .with(File.read(path_to_0781_fixture), lighthouse_0781_document) perform_upload end end context 'when Lighthouse returns an error response' do let(:exception_errors) { [{ detail: 'Something Broke' }] } before do # Skip additional logging that occurs in Lighthouse::ServiceException handling allow(Rails.logger).to receive(:error) allow(BenefitsDocuments::Form526::UploadSupplementalDocumentService).to receive(:call) .and_raise(Common::Exceptions::BadRequest.new(errors: exception_errors)) end it 'logs the Lighthouse error response and re-raises the exception' do expect(Rails.logger).to receive(:error).with( 'LighthouseSupplementalDocumentUploadProvider upload failed', { class: 'LighthouseSupplementalDocumentUploadProvider', submission_id: submission.id, submitted_claim_id: submission.submitted_claim_id, user_uuid: submission.user_uuid, va_document_type_code: 'L228', primary_form: 'Form526', error_info: exception_errors } ) expect { perform_upload }.to raise_error(Common::Exceptions::BadRequest) end it 'increments the correct status failure metric' do expect(StatsD).to receive(:increment).with( "#{expected_statsd_metrics_prefix}.upload_failure" ) expect { perform_upload }.to raise_error(Common::Exceptions::BadRequest) end end end context 'when a submission has 0781a only' do before do submission.update(form_json: form0781a_only) end context 'when a request is successful' do it 'uploads to Lighthouse' do allow_any_instance_of(described_class) .to receive(:generate_stamp_pdf) .with(parsed_0781a_form, submission.submitted_claim_id, '21-0781a') .and_return(path_to_0781a_fixture) allow_any_instance_of(LighthouseSupplementalDocumentUploadProvider) .to receive(:generate_upload_document) .and_return(lighthouse_0781a_document) expect(BenefitsDocuments::Form526::UploadSupplementalDocumentService) .to receive(:call) .with(File.read(path_to_0781a_fixture), lighthouse_0781a_document) perform_upload end end context 'when Lighthouse returns an error response' do let(:exception_errors) { [{ detail: 'Something Broke' }] } before do # Skip additional logging that occurs in Lighthouse::ServiceException handling allow(Rails.logger).to receive(:error) allow(BenefitsDocuments::Form526::UploadSupplementalDocumentService).to receive(:call) .and_raise(Common::Exceptions::BadRequest.new(errors: exception_errors)) end it 'logs the Lighthouse error response and re-raises the exception' do expect(Rails.logger).to receive(:error).with( 'LighthouseSupplementalDocumentUploadProvider upload failed', { class: 'LighthouseSupplementalDocumentUploadProvider', submission_id: submission.id, submitted_claim_id: submission.submitted_claim_id, user_uuid: submission.user_uuid, va_document_type_code: 'L229', primary_form: 'Form526', error_info: exception_errors } ) expect { perform_upload }.to raise_error(Common::Exceptions::BadRequest) end it 'increments the correct status failure metric' do expect(StatsD).to receive(:increment).with( "#{expected_statsd_metrics_prefix}.upload_failure" ) expect { perform_upload }.to raise_error(Common::Exceptions::BadRequest) end end end end context 'when the disability_compensation_upload_0781_to_lighthouse flipper is disabled' do let(:evss_claim_0781_document) do EVSSClaimDocument.new( evss_claim_id: submission.submitted_claim_id, document_type: 'L228' ) end let(:evss_claim_0781a_document) do EVSSClaimDocument.new( evss_claim_id: submission.submitted_claim_id, document_type: 'L229' ) end let(:client_stub) { instance_double(EVSS::DocumentsService) } let(:expected_statsd_metrics_prefix) do 'worker.evss.submit_form0781.evss_supplemental_document_upload_provider' end before do allow(Flipper).to receive(:enabled?).with('disability_compensation_upload_0781_to_lighthouse', instance_of(User)).and_return(false) allow(EVSS::DocumentsService).to receive(:new) { client_stub } allow(client_stub).to receive(:upload) # 0781 allow_any_instance_of(described_class) .to receive(:generate_stamp_pdf) .with(parsed_0781_form, submission.submitted_claim_id, '21-0781') .and_return(path_to_0781_fixture) allow_any_instance_of(EVSSSupplementalDocumentUploadProvider) .to receive(:generate_upload_document) .with('simple.pdf') .and_return(evss_claim_0781_document) # 0781a allow_any_instance_of(described_class) .to receive(:generate_stamp_pdf) .with(parsed_0781a_form, submission.submitted_claim_id, '21-0781a') .and_return(path_to_0781a_fixture) allow_any_instance_of(EVSSSupplementalDocumentUploadProvider) .to receive(:generate_upload_document) .with('kitchen_sink.pdf') .and_return(evss_claim_0781a_document) end context 'when a submission has both 0781 and 0781a' do context 'when the request is successful' do it 'uploads both documents to EVSS' do expect(client_stub).to receive(:upload).with(File.read(path_to_0781_fixture), evss_claim_0781_document) expect(client_stub).to receive(:upload).with(File.read(path_to_0781a_fixture), evss_claim_0781a_document) perform_upload end it 'logs the upload attempt with the correct job prefix' do allow(client_stub).to receive(:upload) expect(StatsD).to receive(:increment).with( "#{expected_statsd_metrics_prefix}.upload_attempt" ).twice # For 0781 and 0781a perform_upload end it 'increments the correct StatsD success metric' do allow(client_stub).to receive(:upload) expect(StatsD).to receive(:increment).with( "#{expected_statsd_metrics_prefix}.upload_success" ).twice # For 0781 and 0781a perform_upload end end context 'when an upload raises an EVSS response error' do it 'logs an upload error and re-raises the error' do allow(client_stub).to receive(:upload).and_raise(EVSS::ErrorMiddleware::EVSSError) expect_any_instance_of(EVSSSupplementalDocumentUploadProvider).to receive(:log_upload_failure) expect do subject.perform_async(submission.id) described_class.drain end.to raise_error(EVSS::ErrorMiddleware::EVSSError) end end end context 'when a submission has only a 0781 form' do before do submission.update(form_json: form0781_only) end context 'when the request is successful' do it 'uploads to EVSS' do submission.update(form_json: form0781_only) expect(client_stub).to receive(:upload).with(File.read(path_to_0781_fixture), evss_claim_0781_document) perform_upload end end context 'when an upload raises an EVSS response error' do it 'logs an upload error and re-raises the error' do allow(client_stub).to receive(:upload).and_raise(EVSS::ErrorMiddleware::EVSSError) expect_any_instance_of(EVSSSupplementalDocumentUploadProvider).to receive(:log_upload_failure) expect do subject.perform_async(submission.id) described_class.drain end.to raise_error(EVSS::ErrorMiddleware::EVSSError) end end end context 'when a submission has only a 0781a form' do context 'when the request is successful' do it 'uploads the 0781a document to EVSS' do submission.update(form_json: form0781a_only) expect(client_stub).to receive(:upload).with(File.read(path_to_0781a_fixture), evss_claim_0781a_document) perform_upload end end context 'when an upload raises an EVSS response error' do it 'logs an upload error and re-raises the error' do allow(client_stub).to receive(:upload).and_raise(EVSS::ErrorMiddleware::EVSSError) expect_any_instance_of(EVSSSupplementalDocumentUploadProvider).to receive(:log_upload_failure) expect do subject.perform_async(submission.id) described_class.drain end.to raise_error(EVSS::ErrorMiddleware::EVSSError) end end end end end context 'when a submission includes 0781v2' do let(:path_to_0781v2_fixture) { 'spec/fixtures/pdf_fill/21-0781V2/kitchen_sink.pdf' } let(:parsed_0781v2_form) { JSON.parse(submission.form_to_json(Form526Submission::FORM_0781))['form0781v2'] } let(:form0781v2_only) do original = JSON.parse(form0781) original.to_json end let(:submission) do Form526Submission.create(user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim_with_0781v2.id, form_json: form0781v2, submitted_claim_id: evss_claim_id) end let(:perform_upload) do subject.perform_async(submission.id) described_class.drain end context 'when the disability_compensation_upload_0781_to_lighthouse flipper is enabled' do let(:faraday_response) { instance_double(Faraday::Response) } let(:lighthouse_request_id) { Faker::Number.number(digits: 8) } let(:lighthouse_0781v2_document) do LighthouseDocument.new( claim_id: submission.submitted_claim_id, participant_id: submission.auth_headers['va_eauth_pid'], document_type: 'L228' ) end let(:expected_statsd_metrics_prefix) do 'worker.evss.submit_form0781.lighthouse_supplemental_document_upload_provider' end before do allow(Flipper).to receive(:enabled?).with('disability_compensation_upload_0781_to_lighthouse', instance_of(User)).and_return(true) allow(BenefitsDocuments::Form526::UploadSupplementalDocumentService).to receive(:call) .and_return(faraday_response) allow(faraday_response).to receive(:body).and_return( { 'data' => { 'success' => true, 'requestId' => lighthouse_request_id } } ) end context 'when a request is successful' do it 'uploads to Lighthouse' do allow_any_instance_of(described_class) .to receive(:generate_stamp_pdf) .with(parsed_0781v2_form, submission.submitted_claim_id, '21-0781V2') .and_return(path_to_0781v2_fixture) allow_any_instance_of(LighthouseSupplementalDocumentUploadProvider) .to receive(:generate_upload_document) .and_return(lighthouse_0781v2_document) expect(BenefitsDocuments::Form526::UploadSupplementalDocumentService) .to receive(:call) .with(File.read(path_to_0781v2_fixture), lighthouse_0781v2_document) perform_upload end end context 'when Lighthouse returns an error response' do let(:exception_errors) { [{ detail: 'Something Broke' }] } before do # Skip additional logging that occurs in Lighthouse::ServiceException handling allow(Rails.logger).to receive(:error) allow(BenefitsDocuments::Form526::UploadSupplementalDocumentService).to receive(:call) .and_raise(Common::Exceptions::BadRequest.new(errors: exception_errors)) end it 'logs the Lighthouse error response and re-raises the exception' do expect(Rails.logger).to receive(:error).with( 'LighthouseSupplementalDocumentUploadProvider upload failed', { class: 'LighthouseSupplementalDocumentUploadProvider', submission_id: submission.id, submitted_claim_id: submission.submitted_claim_id, user_uuid: submission.user_uuid, va_document_type_code: 'L228', primary_form: 'Form526', error_info: exception_errors } ) expect { perform_upload }.to raise_error(Common::Exceptions::BadRequest) end it 'increments the correct status failure metric' do expect(StatsD).to receive(:increment).with( "#{expected_statsd_metrics_prefix}.upload_failure" ) expect { perform_upload }.to raise_error(Common::Exceptions::BadRequest) end end end context 'when the disability_compensation_upload_0781_to_lighthouse flipper is disabled' do let(:evss_claim_0781v2_document) do EVSSClaimDocument.new( evss_claim_id: submission.submitted_claim_id, document_type: 'L228' ) end let(:client_stub) { instance_double(EVSS::DocumentsService) } let(:expected_statsd_metrics_prefix) do 'worker.evss.submit_form0781.evss_supplemental_document_upload_provider' end before do allow(Flipper).to receive(:enabled?).with('disability_compensation_upload_0781_to_lighthouse', instance_of(User)).and_return(false) allow(EVSS::DocumentsService).to receive(:new) { client_stub } allow(client_stub).to receive(:upload) allow_any_instance_of(described_class) .to receive(:generate_stamp_pdf) .with(parsed_0781v2_form, submission.submitted_claim_id, '21-0781V2') .and_return(path_to_0781v2_fixture) allow_any_instance_of(EVSSSupplementalDocumentUploadProvider) .to receive(:generate_upload_document) .with('kitchen_sink.pdf') .and_return(evss_claim_0781v2_document) submission.update(form_json: form0781v2) end context 'when the request is successful' do it 'uploads to EVSS' do submission.update(form_json: form0781v2) expect(client_stub).to receive(:upload).with(File.read(path_to_0781v2_fixture), evss_claim_0781v2_document) perform_upload end end context 'when an upload raises an EVSS response error' do it 'logs an upload error and re-raises the error' do allow(client_stub).to receive(:upload).and_raise(EVSS::ErrorMiddleware::EVSSError) expect_any_instance_of(EVSSSupplementalDocumentUploadProvider).to receive(:log_upload_failure) expect do subject.perform_async(submission.id) described_class.drain end.to raise_error(EVSS::ErrorMiddleware::EVSSError) end end context 'when validating stamping the pdf behavior' do let(:pdf_filler) { instance_double(PdfFill::Filler) } let(:datestamp_pdf_instance) { instance_double(PDFUtilities::DatestampPdf) } before do allow_any_instance_of(described_class).to receive(:generate_stamp_pdf).and_call_original allow(PdfFill::Filler).to receive(:fill_ancillary_form).and_return(path_to_0781v2_fixture) allow(PDFUtilities::DatestampPdf).to receive(:new).and_return(datestamp_pdf_instance) allow(datestamp_pdf_instance).to receive(:run).and_return(path_to_0781v2_fixture) end context 'when the disability_compensation_0781v2_extras_redesign flipper is enabled' do before do allow(Flipper).to receive(:enabled?).with(:disability_compensation_0781v2_extras_redesign, anything).and_return(true) end it 'this class does not stamp the pdf' do submission.update(form_json: form0781v2) expect(PDFUtilities::DatestampPdf).not_to receive(:new) perform_upload end end context 'when the disability_compensation_0781v2_extras_redesign flipper is disabled' do it 'this class stamps the pdf' do submission.update(form_json: form0781v2) expect(PDFUtilities::DatestampPdf).to receive(:new).and_return(datestamp_pdf_instance) perform_upload end end end end end end describe '#get_docs' do let(:submission_id) { 1 } let(:uuid) { 'some-uuid' } let(:submission) { build(:form526_submission, id: submission_id) } let(:parsed_forms) do { 'form0781' => { 'content_0781' => 'value_0781' }, 'form0781a' => { 'content_0781a' => 'value_0781a' }, 'form0781v2' => nil } end before do allow(Form526Submission).to receive(:find_by).with(id: submission_id).and_return(submission) allow_any_instance_of(described_class).to receive(:parsed_forms).and_return(parsed_forms) allow_any_instance_of(described_class).to receive(:process_0781).and_return('file_path') # rubocop:disable Naming/VariableNumber end it 'returns the correct file type and file objects' do result = subject.new.get_docs(submission_id, uuid) expect(result).to eq([ { type: described_class::FORM_ID_0781, file: 'file_path' }, { type: described_class::FORM_ID_0781A, file: 'file_path' } ]) end it 'does not include forms with no content' do result = subject.new.get_docs(submission_id, uuid) expect(result).not_to include({ type: described_class::FORM_ID_0781V2, file: 'file_path' }) end it 'correctly discerns whether to process a 0781 or 0781a' do expect_any_instance_of(described_class).to receive(:process_0781).with(uuid, described_class::FORM_ID_0781, # rubocop:disable Naming/VariableNumber parsed_forms['form0781'], upload: false) expect_any_instance_of(described_class).to receive(:process_0781).with(uuid, described_class::FORM_ID_0781A, # rubocop:disable Naming/VariableNumber parsed_forms['form0781a'], upload: false) expect_any_instance_of(described_class).not_to receive(:process_0781).with(uuid, # rubocop:disable Naming/VariableNumber described_class::FORM_ID_0781V2, parsed_forms['form0781v2'], upload: false) subject.new.get_docs(submission_id, uuid) end end end
0
code_files/vets-api-private/spec/sidekiq/evss
code_files/vets-api-private/spec/sidekiq/evss/disability_compensation_form/submit_uploads_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EVSS::DisabilityCompensationForm::SubmitUploads, type: :job do subject { described_class } before do Sidekiq::Job.clear_all Flipper.disable(:disability_compensation_use_api_provider_for_submit_veteran_upload) Flipper.disable(:form526_send_document_upload_failure_notification) end let(:user) { create(:user, :loa3, :with_terms_of_use_agreement) } let(:user_account) { user.user_account } let(:auth_headers) do EVSS::DisabilityCompensationAuthHeaders.new(user).add_headers(EVSS::AuthHeaders.new(user).to_h) end let(:saved_claim) { create(:va526ez) } let(:submission) do create(:form526_submission, :with_uploads, user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id, submitted_claim_id: '600130094') end let(:form526_job_status) { create(:form526_job_status, :retryable_error, form526_submission: submission, job_id: 1) } let(:upload_data) { [submission.form[Form526Submission::FORM_526_UPLOADS].first] } let(:file) { Rack::Test::UploadedFile.new('spec/fixtures/files/sm_file1.jpg', 'image/jpg') } let!(:attachment) do sea = SupportingEvidenceAttachment.new(guid: upload_data.first['confirmationCode']) sea.set_file_data!(file) sea.save! sea end describe 'perform' do let(:document_data) { double(:document_data, valid?: true) } context 'when file_data exists' do it 'calls the documents service api with file body and document data' do VCR.use_cassette('evss/documents/upload_with_errors') do expect(EVSSClaimDocument) .to receive(:new) .with( evss_claim_id: submission.submitted_claim_id, file_name: upload_data.first['name'], tracked_item_id: nil, document_type: upload_data.first['attachmentId'] ) .and_return(document_data) subject.perform_async(submission.id, upload_data) expect_any_instance_of(EVSS::DocumentsService).to receive(:upload).with(file.read, document_data) described_class.drain end end context 'with a timeout' do it 'logs a retryable error and re-raises the original error' do allow_any_instance_of(EVSS::DocumentsService).to receive(:upload) .and_raise(EVSS::ErrorMiddleware::EVSSBackendServiceError) subject.perform_async(submission.id, upload_data) expect(Form526JobStatus).to receive(:upsert).twice expect { described_class.drain }.to raise_error(EVSS::ErrorMiddleware::EVSSBackendServiceError) end end context 'when all retries are exhausted' do let!(:form526_job_status) do create( :form526_job_status, :retryable_error, form526_submission: submission, job_id: 1 ) end context 'when the form526_send_document_upload_failure_notification Flipper is enabled' do before do Flipper.enable(:form526_send_document_upload_failure_notification) end it 'enqueues a failure notification mailer to send to the veteran' do subject.within_sidekiq_retries_exhausted_block( { 'jid' => form526_job_status.job_id, 'args' => [submission.id, upload_data] } ) do expect(EVSS::DisabilityCompensationForm::Form526DocumentUploadFailureEmail) .to receive(:perform_async).with(submission.id, attachment.guid) end end end context 'when the form526_send_document_upload_failure_notification Flipper is disabled' do it 'does not enqueue a failure notification mailer to send to the veteran' do subject.within_sidekiq_retries_exhausted_block( { 'jid' => form526_job_status.job_id, 'args' => [submission.id, upload_data] } ) do expect(EVSS::DisabilityCompensationForm::Form526DocumentUploadFailureEmail) .not_to receive(:perform_async) end end end end end context 'when misnamed file_data exists' do let(:file) { Rack::Test::UploadedFile.new('spec/fixtures/files/sm_file1_actually_jpg.png', 'image/png') } let!(:attachment) do sea = SupportingEvidenceAttachment.new(guid: upload_data.first['confirmationCode']) sea.set_file_data!(file) sea.save end it 'calls the documents service api with file body and document data' do VCR.use_cassette('evss/documents/upload_with_errors') do expect(EVSSClaimDocument) .to receive(:new) .with( evss_claim_id: submission.submitted_claim_id, file_name: 'converted_sm_file1_actually_jpg_png.jpg', tracked_item_id: nil, document_type: upload_data.first['attachmentId'] ) .and_return(document_data) subject.perform_async(submission.id, upload_data) expect_any_instance_of(EVSS::DocumentsService).to receive(:upload).with(file.read, document_data) described_class.drain end end end context 'when get_file is nil' do let(:attachment) { double(:attachment, get_file: nil) } it 'logs a non_retryable_error' do subject.perform_async(submission.id, upload_data) expect(Form526JobStatus).to receive(:upsert).twice expect { described_class.drain }.to raise_error(ArgumentError) end end end describe 'When an ApiProvider is used for uploads' do before do Flipper.enable(:disability_compensation_use_api_provider_for_submit_veteran_upload) # StatsD metrics are incremented in several callbacks we're not testing here so we need to allow them allow(StatsD).to receive(:increment) end context 'when file_data exists' do let(:perform_upload) do subject.perform_async(submission.id, upload_data.first) described_class.drain end context 'when the disability_compensation_upload_veteran_evidence_to_lighthouse flipper is enabled' do let(:faraday_response) { instance_double(Faraday::Response) } let(:lighthouse_request_id) { Faker::Number.number(digits: 8) } let(:expected_statsd_metrics_prefix) do 'worker.evss.submit_form526_upload.lighthouse_supplemental_document_upload_provider' end let(:expected_lighthouse_document) do LighthouseDocument.new( claim_id: submission.submitted_claim_id, participant_id: user.participant_id, document_type: upload_data.first['attachmentId'], file_name: upload_data.first['name'], supporting_evidence_attachment: attachment ) end before do Flipper.enable(:disability_compensation_upload_veteran_evidence_to_lighthouse) allow(BenefitsDocuments::Form526::UploadSupplementalDocumentService).to receive(:call) .and_return(faraday_response) allow(faraday_response).to receive(:body).and_return( { 'data' => { 'success' => true, 'requestId' => lighthouse_request_id } } ) end it 'uploads the veteran evidence to Lighthouse' do expect(BenefitsDocuments::Form526::UploadSupplementalDocumentService).to receive(:call) .with(file.read, expected_lighthouse_document) perform_upload end it 'logs the upload attempt with the correct job prefix' do expect(StatsD).to receive(:increment).with( "#{expected_statsd_metrics_prefix}.upload_attempt" ) perform_upload end it 'increments the correct StatsD success metric' do expect(StatsD).to receive(:increment).with( "#{expected_statsd_metrics_prefix}.upload_success" ) perform_upload end it 'creates a pending Lighthouse526DocumentUpload record for the submission so we can poll Lighthouse later' do upload_attributes = { aasm_state: 'pending', form526_submission_id: submission.id, document_type: 'Veteran Upload', lighthouse_document_request_id: lighthouse_request_id } expect(Lighthouse526DocumentUpload.where(**upload_attributes).count).to eq(0) perform_upload expect(Lighthouse526DocumentUpload.where(**upload_attributes).count).to eq(1) end # This is a possibility accounted for in the existing EVSS submission code. # The original attachment object does not have a converted_filename. context 'when the SupportingEvidenceAttachment returns a converted_filename' do before do attachment.update!(file_data: JSON.parse(attachment.file_data) .merge('converted_filename' => 'converted_filename.pdf').to_json) end let(:expected_lighthouse_document_with_converted_file_name) do LighthouseDocument.new( claim_id: submission.submitted_claim_id, participant_id: user.participant_id, document_type: upload_data.first['attachmentId'], file_name: 'converted_filename.pdf', supporting_evidence_attachment: attachment ) end it 'uses the converted_filename instead of the metadata in upload_data["name"]' do expect(BenefitsDocuments::Form526::UploadSupplementalDocumentService).to receive(:call) .with(file.read, expected_lighthouse_document_with_converted_file_name) perform_upload end end context 'when Lighthouse returns an error response' do let(:exception_errors) { [{ detail: 'Something Broke' }] } before do # Skip additional logging that occurs in Lighthouse::ServiceException handling allow(Rails.logger).to receive(:error) allow(BenefitsDocuments::Form526::UploadSupplementalDocumentService).to receive(:call) .and_raise(Common::Exceptions::BadRequest.new(errors: exception_errors)) end it 'logs the Lighthouse error response' do expect(Rails.logger).to receive(:error).with( 'LighthouseSupplementalDocumentUploadProvider upload failed', { class: 'LighthouseSupplementalDocumentUploadProvider', submitted_claim_id: submission.submitted_claim_id, submission_id: submission.id, user_uuid: submission.user_uuid, va_document_type_code: 'L451', primary_form: 'Form526', error_info: exception_errors } ) expect { perform_upload }.to raise_error(Common::Exceptions::BadRequest) end it 'increments the correct status failure metric' do expect(StatsD).to receive(:increment).with( "#{expected_statsd_metrics_prefix}.upload_failure" ) expect { perform_upload }.to raise_error(Common::Exceptions::BadRequest) end end end # Upload to EVSS context 'when the disability_compensation_upload_veteran_evidence_to_lighthouse flipper is disabled' do before do Flipper.disable(:disability_compensation_upload_veteran_evidence_to_lighthouse) allow_any_instance_of(EVSS::DocumentsService).to receive(:upload) end let(:evss_claim_document) do EVSSClaimDocument.new( evss_claim_id: submission.submitted_claim_id, document_type: upload_data.first['attachmentId'], file_name: upload_data.first['name'] ) end let(:expected_statsd_metrics_prefix) do 'worker.evss.submit_form526_upload.evss_supplemental_document_upload_provider' end it 'uploads the document via the EVSS Documents Service' do expect_any_instance_of(EVSS::DocumentsService).to receive(:upload) .with(file.read, evss_claim_document) perform_upload end it 'logs the upload attempt with the correct job prefix' do expect(StatsD).to receive(:increment).with( "#{expected_statsd_metrics_prefix}.upload_attempt" ) perform_upload end it 'increments the correct StatsD success metric' do expect(StatsD).to receive(:increment).with( "#{expected_statsd_metrics_prefix}.upload_success" ) perform_upload end context 'when an upload raises an EVSS response error' do it 'logs an upload error and re-raises the error' do allow_any_instance_of(EVSS::DocumentsService) .to receive(:upload).and_raise(EVSS::ErrorMiddleware::EVSSError) expect_any_instance_of(EVSSSupplementalDocumentUploadProvider).to receive(:log_upload_failure) expect { perform_upload }.to raise_error(EVSS::ErrorMiddleware::EVSSError) end end end end end context 'catastrophic failure state' do describe 'when all retries are exhausted' do let!(:form526_submission) { create(:form526_submission, :with_uploads, user_account:) } let!(:form526_job_status) { create(:form526_job_status, :retryable_error, form526_submission:, job_id: 1) } it 'updates a StatsD counter and updates the status on an exhaustion event' do subject.within_sidekiq_retries_exhausted_block({ 'jid' => form526_job_status.job_id }) do expect(StatsD).to receive(:increment).with("#{subject::STATSD_KEY_PREFIX}.exhausted") expect(Rails).to receive(:logger).and_call_original end form526_job_status.reload expect(form526_job_status.status).to eq(Form526JobStatus::STATUS[:exhausted]) end context 'when the API Provider uploads are enabled' do before do Flipper.enable(:disability_compensation_use_api_provider_for_submit_veteran_upload) end let(:sidekiq_job_exhaustion_errors) do { 'jid' => form526_job_status.job_id, 'error_class' => 'Broken Job Error', 'error_message' => 'Your Job Broke', 'args' => [form526_submission.id, upload_data.first] } end context 'for a Lighthouse upload' do it 'logs the job failure' do Flipper.enable(:disability_compensation_upload_veteran_evidence_to_lighthouse) subject.within_sidekiq_retries_exhausted_block(sidekiq_job_exhaustion_errors) do expect_any_instance_of(LighthouseSupplementalDocumentUploadProvider) .to receive(:log_uploading_job_failure) .with(EVSS::DisabilityCompensationForm::SubmitUploads, 'Broken Job Error', 'Your Job Broke') end end end context 'for an EVSS Upload' do it 'logs the job failure' do Flipper.disable(:disability_compensation_upload_veteran_evidence_to_lighthouse) subject.within_sidekiq_retries_exhausted_block(sidekiq_job_exhaustion_errors) do expect_any_instance_of(EVSSSupplementalDocumentUploadProvider).to receive(:log_uploading_job_failure) .with(EVSS::DisabilityCompensationForm::SubmitUploads, 'Broken Job Error', 'Your Job Broke') end end end end end describe 'when an error occurs during exhaustion handling and FailureEmail fails to enqueue' do let!(:zsf_tag) { Form526Submission::ZSF_DD_TAG_SERVICE } let!(:zsf_monitor) { ZeroSilentFailures::Monitor.new(zsf_tag) } let!(:failure_email) { EVSS::DisabilityCompensationForm::Form526DocumentUploadFailureEmail } before do Flipper.enable(:form526_send_document_upload_failure_notification) allow(ZeroSilentFailures::Monitor).to receive(:new).with(zsf_tag).and_return(zsf_monitor) end it 'logs a silent failure' do expect(zsf_monitor).to receive(:log_silent_failure).with( { job_id: form526_job_status.job_id, error_class: nil, error_message: 'An error occurred', timestamp: instance_of(Time), form526_submission_id: submission.id }, user_account.id, call_location: instance_of(Logging::CallLocation) ) args = { 'jid' => form526_job_status.job_id, 'args' => [submission.id, upload_data] } expect do subject.within_sidekiq_retries_exhausted_block(args) do allow(failure_email).to receive(:perform_async).and_raise(StandardError, 'Simulated error') end end.to raise_error(StandardError, 'Simulated error') end end end end
0
code_files/vets-api-private/spec/sidekiq/evss
code_files/vets-api-private/spec/sidekiq/evss/disability_compensation_form/submit_form526_cleanup_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EVSS::DisabilityCompensationForm::SubmitForm526Cleanup, type: :job do subject { described_class } before do Sidekiq::Job.clear_all end let(:user) { create(:user, :loa3) } let(:submission) { create(:form526_submission, user_uuid: user.uuid) } describe '.perform_async' do context 'with a successful call' do it 'deletes the in progress form' do create(:in_progress_form, user_uuid: user.uuid, form_id: '21-526EZ') subject.perform_async(submission.id) expect { described_class.drain }.to change(InProgressForm, :count).by(-1) end end end context 'catastrophic failure state' do describe 'when all retries are exhausted' do let!(:form526_submission) { create(:form526_submission) } let!(:form526_job_status) { create(:form526_job_status, :retryable_error, form526_submission:, job_id: 1) } it 'updates a StatsD counter and updates the status on an exhaustion event' do subject.within_sidekiq_retries_exhausted_block({ 'jid' => form526_job_status.job_id }) do expect(StatsD).to receive(:increment).with("#{subject::STATSD_KEY_PREFIX}.exhausted") expect(Rails).to receive(:logger).and_call_original end form526_job_status.reload expect(form526_job_status.status).to eq(Form526JobStatus::STATUS[:exhausted]) end end end end
0
code_files/vets-api-private/spec/sidekiq/evss
code_files/vets-api-private/spec/sidekiq/evss/disability_compensation_form/form526_document_upload_failure_email_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EVSS::DisabilityCompensationForm::Form526DocumentUploadFailureEmail, type: :job do subject { described_class } let!(:form526_submission) do create( :form526_submission, :with_uploads ) end let(:upload_data) { [form526_submission.form[Form526Submission::FORM_526_UPLOADS].first] } let(:file) { Rack::Test::UploadedFile.new('spec/fixtures/files/sm_file1.jpg', 'image/jpg') } let!(:form_attachment) do sea = SupportingEvidenceAttachment.new( guid: upload_data.first['confirmationCode'] ) sea.set_file_data!(file) sea.save! sea end let(:notification_client) { instance_double(Notifications::Client) } let(:va_notify_client) { instance_double(VaNotify::Client) } before do Sidekiq::Job.clear_all allow(Notifications::Client).to receive(:new).and_return(notification_client) allow(VaNotify::Client).to receive(:new).and_return(va_notify_client) allow(Flipper).to receive(:enabled?).with(:va_notify_request_level_callbacks).and_return(false) end describe '#perform' do let(:formatted_submit_date) do # We display dates in mailers in the format "May 1, 2024 3:01 p.m. EDT" form526_submission.created_at.strftime('%B %-d, %Y %-l:%M %P %Z').sub(/([ap])m/, '\1.m.') end let(:obscured_filename) { 'sm_XXXe1.jpg' } it 'dispatches a failure notification email with an obscured filename' do expect(notification_client).to receive(:send_email).with( # Email address and first_name are from our User fixtures # form526_document_upload_failure_notification_template_id is a placeholder in settings.yml { email_address: 'test@email.com', template_id: 'form526_document_upload_failure_notification_template_id', personalisation: { first_name: 'BEYONCE', filename: obscured_filename, date_submitted: formatted_submit_date } } ) subject.perform_async(form526_submission.id, form_attachment.guid) subject.drain end describe 'logging' do before do allow(notification_client).to receive(:send_email).and_return({}) end it 'logs to the Rails logger' do # Necessary to allow multiple logging statements and test has_received on ours # Required as other logging occurs (in lib/sidekiq/form526_job_status_tracker/job_tracker.rb callbacks) allow(Rails.logger).to receive(:info) exhaustion_time = Time.new(1985, 10, 26).utc Timecop.freeze(exhaustion_time) do subject.perform_async(form526_submission.id, form_attachment.guid) subject.drain expect(Rails.logger).to have_received(:info).with( 'Form526DocumentUploadFailureEmail notification dispatched', { obscured_filename:, form526_submission_id: form526_submission.id, supporting_evidence_attachment_guid: form_attachment.guid, timestamp: exhaustion_time, va_notify_response: {} } ) end end it 'increments StatsD success & silent failure avoided metrics' do expect do subject.perform_async(form526_submission.id, form_attachment.guid) subject.drain end.to trigger_statsd_increment( 'api.form_526.veteran_notifications.document_upload_failure_email.success' ) end it 'creates a Form526JobStatus' do expect do subject.perform_async(form526_submission.id, form_attachment.guid) subject.drain end.to change(Form526JobStatus, :count).by(1) end end end context 'when all retries are exhausted' do let!(:form526_job_status) { create(:form526_job_status, :retryable_error, form526_submission:, job_id: 123) } let(:retry_params) do { 'jid' => 123, 'error_class' => 'JennyNotFound', 'error_message' => 'I tried to call you before but I lost my nerve', 'args' => [form526_submission.id, form_attachment.guid] } end let(:exhaustion_time) { DateTime.new(1985, 10, 26).utc } before do allow(notification_client).to receive(:send_email) end it 'increments StatsD exhaustion & silent failure metrics, logs to the Rails logger and updates the job status' do Timecop.freeze(exhaustion_time) do described_class.within_sidekiq_retries_exhausted_block(retry_params) do expect(Rails.logger).to receive(:warn).with( 'Form526DocumentUploadFailureEmail retries exhausted', { job_id: 123, error_class: 'JennyNotFound', error_message: 'I tried to call you before but I lost my nerve', timestamp: exhaustion_time, form526_submission_id: form526_submission.id, supporting_evidence_attachment_guid: form_attachment.guid } ).and_call_original expect(StatsD).to receive(:increment).with( 'api.form_526.veteran_notifications.document_upload_failure_email.exhausted' ).ordered expect(StatsD).to receive(:increment).with( 'silent_failure', tags: [ 'service:disability-application', 'function:526_evidence_upload_failure_email_queuing' ] ).ordered end form526_job_status.reload expect(form526_job_status.status).to eq(Form526JobStatus::STATUS[:exhausted]) end end end end
0
code_files/vets-api-private/spec/sidekiq/evss
code_files/vets-api-private/spec/sidekiq/evss/disability_compensation_form/form4142_document_upload_failure_email_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EVSS::DisabilityCompensationForm::Form4142DocumentUploadFailureEmail, type: :job do subject { described_class } let!(:form526_submission) { create(:form526_submission) } let(:notification_client) { instance_double(Notifications::Client) } let(:va_notify_client) { instance_double(VaNotify::Client) } let(:formatted_submit_date) do # We display dates in mailers in the format "May 1, 2024 3:01 p.m. EDT" form526_submission.created_at.strftime('%B %-d, %Y %-l:%M %P %Z').sub(/([ap])m/, '\1.m.') end before do Sidekiq::Job.clear_all allow(Notifications::Client).to receive(:new).and_return(notification_client) allow(VaNotify::Client).to receive(:new).and_return(va_notify_client) allow(Flipper).to receive(:enabled?).with(:va_notify_request_level_callbacks).and_return(false) end describe '#perform' do it 'dispatches a failure notification' do expect(notification_client).to receive(:send_email).with( # Email address and first_name are from our User fixtures # form4142_upload_failure_notification_template_id is a placeholder in settings.yml { email_address: 'test@email.com', template_id: 'form4142_upload_failure_notification_template_id', personalisation: { first_name: 'BEYONCE', date_submitted: formatted_submit_date } } ) subject.perform_async(form526_submission.id) subject.drain end end describe 'logging' do before do allow(notification_client).to receive(:send_email).and_return({}) end it 'increments StatsD success and silent failure avoided metrics' do expect do subject.perform_async(form526_submission.id) subject.drain end.to trigger_statsd_increment( 'api.form_526.veteran_notifications.form4142_upload_failure_email.success' ) end it 'logs to the Rails logger' do allow(Rails.logger).to receive(:info) exhaustion_time = Time.new(1985, 10, 26).utc Timecop.freeze(exhaustion_time) do subject.perform_async(form526_submission.id) subject.drain expect(Rails.logger).to have_received(:info).with( 'Form4142DocumentUploadFailureEmail notification dispatched', { form526_submission_id: form526_submission.id, timestamp: exhaustion_time, va_notify_response: {} } ) end end it 'creates a Form526JobStatus' do expect do subject.perform_async(form526_submission.id) subject.drain end.to change(Form526JobStatus, :count).by(1) end context 'when an error throws when sending an email' do before do allow_any_instance_of(VaNotify::Service).to receive(:send_email).and_raise(Common::Client::Errors::ClientError) end it 'passes the error to the included JobTracker retryable_error_handler and re-raises the error' do # Sidekiq::Form526JobStatusTracker::JobTracker is included in this job's inheritance hierarchy expect_any_instance_of( Sidekiq::Form526JobStatusTracker::JobTracker ).to receive(:retryable_error_handler).with(an_instance_of(Common::Client::Errors::ClientError)) expect do subject.perform_async(form526_submission.id) subject.drain end.to raise_error(Common::Client::Errors::ClientError) end end end context 'when retries are exhausted' do let!(:form526_job_status) { create(:form526_job_status, :retryable_error, form526_submission:, job_id: 123) } let(:retry_params) do { 'jid' => 123, 'error_class' => 'JennyNotFound', 'error_message' => 'I tried to call you before but I lost my nerve', 'args' => [form526_submission.id] } end let(:exhaustion_time) { DateTime.new(1985, 10, 26).utc } before do allow(notification_client).to receive(:send_email) end it 'increments StatsD exhaustion & silent failure metrics, logs to the Rails logger and updates the job status' do Timecop.freeze(exhaustion_time) do described_class.within_sidekiq_retries_exhausted_block(retry_params) do expect(Rails.logger).to receive(:warn).with( 'Form4142DocumentUploadFailureEmail retries exhausted', { job_id: 123, error_class: 'JennyNotFound', error_message: 'I tried to call you before but I lost my nerve', timestamp: exhaustion_time, form526_submission_id: form526_submission.id } ).and_call_original expect(StatsD).to receive(:increment).with( 'api.form_526.veteran_notifications.form4142_upload_failure_email.exhausted' ).ordered expect(StatsD).to receive(:increment).with( 'silent_failure', tags: [ 'service:disability-application', 'function:526_form_4142_upload_failure_email_sending' ] ).ordered end expect(form526_job_status.reload.status).to eq(Form526JobStatus::STATUS[:exhausted]) end end end end
0
code_files/vets-api-private/spec/sidekiq/evss
code_files/vets-api-private/spec/sidekiq/evss/disability_compensation_form/submit_form8940_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EVSS::DisabilityCompensationForm::SubmitForm8940, type: :job do subject { described_class } before do Sidekiq::Job.clear_all Flipper.disable(:disability_compensation_lighthouse_document_service_provider) end let(:user) { create(:user, :loa3) } let(:auth_headers) do EVSS::DisabilityCompensationAuthHeaders.new(user).add_headers(EVSS::AuthHeaders.new(user).to_h) end let(:form8940) { File.read 'spec/support/disability_compensation_form/form_8940.json' } VCR.configure do |c| c.default_cassette_options = { match_requests_on: [:method, VCR.request_matchers.uri_without_params(:qqfile, :docType, :docTypeDescription)] } end describe '.perform_async' do with8940 = File.read 'spec/support/disability_compensation_form/submissions/with_8940.json' submitted_claim_id = 123_456_789 let(:saved_claim) { create(:va526ez) } let(:submitted_claim_id) { 123_456_789 } let(:submission) do create(:form526_submission, user_uuid: user.uuid, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id, submitted_claim_id:, form_json: with8940) end context 'with a successful submission job' do it 'queues a job for submit' do expect do subject.perform_async(submission.id) end.to change(subject.jobs, :size).by(1) end it 'submits successfully' do VCR.use_cassette('evss/disability_compensation_form/submit_8940') do subject.perform_async(submission.id) jid = subject.jobs.last['jid'] described_class.drain expect(jid).not_to be_empty end end end context 'with a submission timeout' do before do allow_any_instance_of(Faraday::Connection).to receive(:post).and_raise(Faraday::TimeoutError) end it 'raises a gateway timeout error' do subject.perform_async(submission.id) expect { described_class.drain }.to raise_error(StandardError) end end context 'with an unexpected error' do before do allow_any_instance_of(Faraday::Connection).to receive(:post).and_raise(StandardError.new('foo')) end it 'raises a standard error' do subject.perform_async(submission.id) expect { described_class.drain }.to raise_error(StandardError) end end end context 'catastrophic failure state' do describe 'when all retries are exhausted' do let!(:form526_submission) { create(:form526_submission) } let!(:form526_job_status) { create(:form526_job_status, :retryable_error, form526_submission:, job_id: 1) } it 'updates a StatsD counter and updates the status on an exhaustion event' do subject.within_sidekiq_retries_exhausted_block({ 'jid' => form526_job_status.job_id }) do expect(StatsD).to receive(:increment).with("#{subject::STATSD_KEY_PREFIX}.exhausted") expect(Rails).to receive(:logger).and_call_original end form526_job_status.reload expect(form526_job_status.status).to eq(Form526JobStatus::STATUS[:exhausted]) end end end end
0
code_files/vets-api-private/spec/sidekiq/evss
code_files/vets-api-private/spec/sidekiq/evss/disability_compensation_form/submit_form526_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EVSS::DisabilityCompensationForm::SubmitForm526, type: :job do subject { described_class } before do Sidekiq::Job.clear_all Flipper.disable(:disability_compensation_fail_submission) end let(:user) { create(:user, :loa3) } let(:auth_headers) do EVSS::DisabilityCompensationAuthHeaders.new(user).add_headers(EVSS::AuthHeaders.new(user).to_h) end describe '.perform_async' do let(:saved_claim) { create(:va526ez) } let(:submitted_claim_id) { 600_130_094 } let(:submission) do create(:form526_submission, user_uuid: user.uuid, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id) end context 'when the base class is used' do it 'raises an error as a subclass should be used to perform the job' do allow_any_instance_of(Form526Submission).to receive(:prepare_for_evss!).and_return(nil) expect { subject.new.perform(submission.id) }.to raise_error NotImplementedError end end context 'when all retries are exhausted' do let!(:form526_submission) { create(:form526_submission) } let!(:form526_job_status) { create(:form526_job_status, :non_retryable_error, form526_submission:, job_id: 1) } it 'marks the job status as exhausted' do job_params = { 'jid' => form526_job_status.job_id, 'args' => [form526_submission.id] } allow(Sidekiq::Form526JobStatusTracker::JobTracker).to receive(:send_backup_submission_if_enabled) subject.within_sidekiq_retries_exhausted_block(job_params) do # block is required to use this functionality true end form526_job_status.reload expect(form526_job_status.status).to eq(Form526JobStatus::STATUS[:exhausted]) end context 'when logging errors in sidekiq_retries_exhausted callback' do let!(:form526_submission) { create(:form526_submission) } let!(:form526_job_status) do create(:form526_job_status, :non_retryable_error, form526_submission:, job_id: '123abc') end let(:job_params) do { 'class' => 'EVSS::DisabilityCompensationForm::SubmitForm526', 'jid' => '123abc', 'args' => [form526_submission.id], 'error_message' => 'Original failure reason', 'error_class' => 'StandardError' } end before do allow(Sidekiq::Form526JobStatusTracker::JobTracker).to receive(:send_backup_submission_if_enabled) end it 'logs error details to Rails.logger when job_exhausted fails' do # Simulate job_exhausted failing by making find_by return nil allow(Form526JobStatus).to receive(:find_by).with(job_id: '123abc').and_return(nil) # The JobTracker logs its own error message first expect(Rails.logger).to receive(:error).with( 'Failure in SubmitForm526#sidekiq_retries_exhausted', hash_including( job_id: '123abc', submission_id: form526_submission.id, messaged_content: kind_of(String) ) ) # Then our log_error method is called and logs again expect(Rails.logger).to receive(:error).with( 'SubmitForm526#sidekiq_retries_exhausted error', hash_including( job_class: 'SubmitForm526', job_id: '123abc', submission_id: form526_submission.id, error_message: kind_of(String), original_job_failure_reason: 'Original failure reason' ) ) # This will trigger the error logging in the sidekiq_retries_exhausted callback subject.within_sidekiq_retries_exhausted_block(job_params) do true end end it 'can be called as a class method directly' do test_error = StandardError.new('Test error message') expect(Rails.logger).to receive(:error).with( 'SubmitForm526#sidekiq_retries_exhausted error', { job_class: 'SubmitForm526', job_id: '123abc', submission_id: form526_submission.id, error_message: 'Test error message', original_job_failure_reason: 'Original failure reason' } ) # Call the class method directly described_class.log_error(job_params, test_error) end it 'logs error when Form526Submission.find fails' do # Allow job_exhausted to succeed allow(Form526JobStatus).to receive(:find_by).with(job_id: '123abc').and_return(form526_job_status) allow(form526_job_status).to receive(:update) # But make Form526Submission.find fail allow(Form526Submission).to receive(:find).and_raise(ActiveRecord::RecordNotFound) expect(Rails.logger).to receive(:warn).with( 'Submit Form 526 Retries exhausted', hash_including(job_id: '123abc') ) expect(Rails.logger).to receive(:error).with( 'SubmitForm526#sidekiq_retries_exhausted error', hash_including( job_class: 'SubmitForm526', job_id: '123abc', submission_id: form526_submission.id, error_message: kind_of(String), original_job_failure_reason: 'Original failure reason' ) ) subject.within_sidekiq_retries_exhausted_block(job_params) do true end end it 'logs error when email notification fails' do # Setup successful job_exhausted allow(Form526JobStatus).to receive(:find_by).with(job_id: '123abc').and_return(form526_job_status) allow(form526_job_status).to receive(:update) # Setup submission that will trigger email notification job_params['error_message'] = 'PIF in use' allow(Form526Submission).to receive(:find).and_return(form526_submission) allow(form526_submission).to receive(:submit_with_birls_id_that_hasnt_been_tried_yet!).and_return(nil) allow(Flipper).to receive(:enabled?).with(:disability_compensation_pif_fail_notification).and_return(true) allow(form526_submission).to receive(:get_first_name).and_raise(StandardError.new('Email error')) expect(Rails.logger).to receive(:warn).with( 'Submit Form 526 Retries exhausted', hash_including(job_id: '123abc') ) expect(Rails.logger).to receive(:error).with( 'SubmitForm526#sidekiq_retries_exhausted error', hash_including( job_class: 'SubmitForm526', job_id: '123abc', submission_id: form526_submission.id, error_message: 'Email error', original_job_failure_reason: 'PIF in use' ) ) subject.within_sidekiq_retries_exhausted_block(job_params) do true end end end end end end
0
code_files/vets-api-private/spec/sidekiq/evss
code_files/vets-api-private/spec/sidekiq/evss/disability_compensation_form/upload_bdd_instructions_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EVSS::DisabilityCompensationForm::UploadBddInstructions, type: :job do subject { described_class } before do Sidekiq::Job.clear_all Flipper.disable(:disability_compensation_use_api_provider_for_bdd_instructions) end let(:user) { create(:user, :loa3) } let(:auth_headers) do EVSS::DisabilityCompensationAuthHeaders.new(user).add_headers(EVSS::AuthHeaders.new(user).to_h) end let(:saved_claim) { create(:va526ez) } let(:submission) do create(:form526_submission, :with_uploads, user_uuid: user.uuid, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id, submitted_claim_id: '600130094') end let(:file_read) { File.read('lib/evss/disability_compensation_form/bdd_instructions.pdf') } describe 'perform' do let(:client) { double(:client) } let(:document_data) { double(:document_data) } before do allow(EVSS::DocumentsService) .to receive(:new) .and_return(client) end context 'when file_data exists' do it 'calls the documents service api with file body and document data' do expect(EVSSClaimDocument) .to receive(:new) .with( evss_claim_id: submission.submitted_claim_id, file_name: 'BDD_Instructions.pdf', tracked_item_id: nil, document_type: 'L023' ) .and_return(document_data) subject.perform_async(submission.id) expect(client).to receive(:upload).with(file_read, document_data) described_class.drain end context 'with a timeout' do it 'logs a retryable error and re-raises the original error' do allow(client).to receive(:upload).and_raise(EVSS::ErrorMiddleware::EVSSBackendServiceError) subject.perform_async(submission.id) expect(Form526JobStatus).to receive(:upsert).twice expect { described_class.drain }.to raise_error(EVSS::ErrorMiddleware::EVSSBackendServiceError) end end end end describe 'When an ApiProvider is used for uploads' do before do Flipper.enable(:disability_compensation_use_api_provider_for_bdd_instructions) # StatsD metrics are incremented in several callbacks we're not testing here so we need to allow them allow(StatsD).to receive(:increment) end let(:perform_upload) do subject.perform_async(submission.id) described_class.drain end context 'when the disability_compensation_upload_bdd_instructions_to_lighthouse flipper is enabled' do let(:faraday_response) { instance_double(Faraday::Response) } let(:lighthouse_request_id) { Faker::Number.number(digits: 8) } let(:expected_statsd_metrics_prefix) do 'worker.evss.submit_form526_bdd_instructions.lighthouse_supplemental_document_upload_provider' end let(:expected_lighthouse_document) do LighthouseDocument.new( claim_id: submission.submitted_claim_id, participant_id: submission.auth_headers['va_eauth_pid'], document_type: 'L023', file_name: 'BDD_Instructions.pdf' ) end before do Flipper.enable(:disability_compensation_upload_bdd_instructions_to_lighthouse) allow(BenefitsDocuments::Form526::UploadSupplementalDocumentService).to receive(:call) .and_return(faraday_response) allow(faraday_response).to receive(:body).and_return( { 'data' => { 'success' => true, 'requestId' => lighthouse_request_id } } ) end it 'uploads a BDD Instruction PDF to Lighthouse' do expect(BenefitsDocuments::Form526::UploadSupplementalDocumentService).to receive(:call) .with(file_read, expected_lighthouse_document) perform_upload end it 'logs the upload attempt with the correct job prefix' do expect(StatsD).to receive(:increment).with( "#{expected_statsd_metrics_prefix}.upload_attempt" ) perform_upload end it 'increments the correct StatsD success metric' do expect(StatsD).to receive(:increment).with( "#{expected_statsd_metrics_prefix}.upload_success" ) perform_upload end it 'creates a pending Lighthouse526DocumentUpload record for the submission so we can poll Lighthouse later' do upload_attributes = { aasm_state: 'pending', form526_submission_id: submission.id, document_type: 'BDD Instructions', lighthouse_document_request_id: lighthouse_request_id } expect(Lighthouse526DocumentUpload.where(**upload_attributes).count).to eq(0) perform_upload expect(Lighthouse526DocumentUpload.where(**upload_attributes).count).to eq(1) end context 'when Lighthouse returns an error response' do let(:exception_errors) { [{ detail: 'Something Broke' }] } before do # Skip additional logging that occurs in Lighthouse::ServiceException handling allow(Rails.logger).to receive(:error) allow(BenefitsDocuments::Form526::UploadSupplementalDocumentService).to receive(:call) .and_raise(Common::Exceptions::BadRequest.new(errors: exception_errors)) end it 'logs the Lighthouse error response and re-raises the error' do expect(Rails.logger).to receive(:error).with( 'LighthouseSupplementalDocumentUploadProvider upload failed', { class: 'LighthouseSupplementalDocumentUploadProvider', submitted_claim_id: submission.submitted_claim_id, submission_id: submission.id, user_uuid: submission.user_uuid, va_document_type_code: 'L023', primary_form: 'Form526', error_info: exception_errors } ) expect { perform_upload }.to raise_error(Common::Exceptions::BadRequest) end it 'increments the correct status failure metric and re-raises the error' do expect(StatsD).to receive(:increment).with( "#{expected_statsd_metrics_prefix}.upload_failure" ) expect { perform_upload }.to raise_error(Common::Exceptions::BadRequest) end end end # Upload to EVSS context 'when the disability_compensation_upload_bdd_instructions_to_lighthouse flipper is disabled' do before do Flipper.disable(:disability_compensation_upload_bdd_instructions_to_lighthouse) allow_any_instance_of(EVSS::DocumentsService).to receive(:upload) end let(:evss_claim_document) do EVSSClaimDocument.new( evss_claim_id: submission.submitted_claim_id, document_type: 'L023', file_name: 'BDD_Instructions.pdf' ) end let(:expected_statsd_metrics_prefix) do 'worker.evss.submit_form526_bdd_instructions.evss_supplemental_document_upload_provider' end it 'uploads the document via the EVSS Documents Service' do expect_any_instance_of(EVSS::DocumentsService).to receive(:upload) .with(file_read, evss_claim_document) perform_upload end it 'logs the upload attempt with the correct job prefix' do expect(StatsD).to receive(:increment).with( "#{expected_statsd_metrics_prefix}.upload_attempt" ) perform_upload end it 'increments the correct StatsD success metric' do expect(StatsD).to receive(:increment).with( "#{expected_statsd_metrics_prefix}.upload_success" ) perform_upload end context 'when an upload raises an EVSS response error' do it 'logs an upload error' do allow_any_instance_of(EVSS::DocumentsService).to receive(:upload).and_raise(EVSS::ErrorMiddleware::EVSSError) expect_any_instance_of(EVSSSupplementalDocumentUploadProvider).to receive(:log_upload_failure) expect do subject.perform_async(submission.id) described_class.drain end.to raise_error(EVSS::ErrorMiddleware::EVSSError) end end end end context 'catastrophic failure state' do describe 'when all retries are exhausted' do let!(:form526_submission) { create(:form526_submission) } let!(:form526_job_status) { create(:form526_job_status, :retryable_error, form526_submission:, job_id: 1) } it 'updates a StatsD counter and updates the status on an exhaustion event' do subject.within_sidekiq_retries_exhausted_block({ 'jid' => form526_job_status.job_id }) do expect(StatsD).to receive(:increment).with("#{subject::STATSD_KEY_PREFIX}.exhausted") expect(Rails).to receive(:logger).and_call_original end form526_job_status.reload expect(form526_job_status.status).to eq(Form526JobStatus::STATUS[:exhausted]) end context 'when the API Provider uploads are enabled' do before do Flipper.enable(:disability_compensation_use_api_provider_for_bdd_instructions) end let(:sidekiq_job_exhaustion_errors) do { 'jid' => form526_job_status.job_id, 'error_class' => 'Broken Job Error', 'error_message' => 'Your Job Broke', 'args' => [form526_submission.id] } end context 'for a Lighthouse upload' do it 'logs the job failure' do Flipper.enable(:disability_compensation_upload_bdd_instructions_to_lighthouse) subject.within_sidekiq_retries_exhausted_block(sidekiq_job_exhaustion_errors) do expect_any_instance_of(LighthouseSupplementalDocumentUploadProvider) .to receive(:log_uploading_job_failure) .with(EVSS::DisabilityCompensationForm::UploadBddInstructions, 'Broken Job Error', 'Your Job Broke') end end end context 'for an EVSS Upload' do it 'logs the job failure' do Flipper.disable(:disability_compensation_upload_bdd_instructions_to_lighthouse) subject.within_sidekiq_retries_exhausted_block(sidekiq_job_exhaustion_errors) do expect_any_instance_of(EVSSSupplementalDocumentUploadProvider).to receive(:log_uploading_job_failure) .with(EVSS::DisabilityCompensationForm::UploadBddInstructions, 'Broken Job Error', 'Your Job Broke') end end end end end end end
0
code_files/vets-api-private/spec/sidekiq/evss
code_files/vets-api-private/spec/sidekiq/evss/disability_compensation_form/form0781_document_upload_failure_email_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EVSS::DisabilityCompensationForm::Form0781DocumentUploadFailureEmail, type: :job do subject { described_class } let!(:form526_submission) { create(:form526_submission) } let(:notification_client) { instance_double(Notifications::Client) } let(:va_notify_client) { instance_double(VaNotify::Client) } let(:formatted_submit_date) do # We display dates in mailers in the format "May 1, 2024 3:01 p.m. EDT" form526_submission.created_at.strftime('%B %-d, %Y %-l:%M %P %Z').sub(/([ap])m/, '\1.m.') end before do Sidekiq::Job.clear_all allow(Notifications::Client).to receive(:new).and_return(notification_client) allow(VaNotify::Client).to receive(:new).and_return(va_notify_client) allow(Flipper).to receive(:enabled?).with(:va_notify_request_level_callbacks).and_return(false) end describe '#perform' do it 'dispatches a failure notification email' do expect(notification_client).to receive(:send_email).with( # Email address and first_name are from our User fixtures # form0781_upload_failure_notification_template_id is a placeholder in settings.yml { email_address: 'test@email.com', template_id: 'form0781_upload_failure_notification_template_id', personalisation: { first_name: 'BEYONCE', date_submitted: formatted_submit_date } } ) subject.perform_async(form526_submission.id) subject.drain end end describe 'logging' do before do allow(notification_client).to receive(:send_email).and_return({}) end it 'increments StatsD success & silent failure avoided metrics' do expect do subject.perform_async(form526_submission.id) subject.drain end.to trigger_statsd_increment( 'api.form_526.veteran_notifications.form0781_upload_failure_email.success' ) end it 'logs to the Rails logger' do allow(Rails.logger).to receive(:info) exhaustion_time = Time.new(1985, 10, 26).utc Timecop.freeze(exhaustion_time) do subject.perform_async(form526_submission.id) subject.drain expect(Rails.logger).to have_received(:info).with( 'Form0781DocumentUploadFailureEmail notification dispatched', { form526_submission_id: form526_submission.id, timestamp: exhaustion_time, va_notify_response: {} } ) end end it 'creates a Form526JobStatus' do expect do subject.perform_async(form526_submission.id) subject.drain end.to change(Form526JobStatus, :count).by(1) end context 'when an error throws when sending an email' do before do allow_any_instance_of(VaNotify::Service).to receive(:send_email).and_raise(Common::Client::Errors::ClientError) end it 'passes the error to the included JobTracker retryable_error_handler and re-raises the error' do # Sidekiq::Form526JobStatusTracker::JobTracker is included in this job's inheritance hierarchy expect_any_instance_of( Sidekiq::Form526JobStatusTracker::JobTracker ).to receive(:retryable_error_handler).with(an_instance_of(Common::Client::Errors::ClientError)) expect do subject.perform_async(form526_submission.id) subject.drain end.to raise_error(Common::Client::Errors::ClientError) end end end context 'when retries are exhausted' do let!(:form526_job_status) { create(:form526_job_status, :retryable_error, form526_submission:, job_id: 123) } let(:retry_params) do { 'jid' => 123, 'error_class' => 'JennyNotFound', 'error_message' => 'I tried to call you before but I lost my nerve', 'args' => [form526_submission.id] } end let(:exhaustion_time) { DateTime.new(1985, 10, 26).utc } before do allow(notification_client).to receive(:send_email) end it 'increments StatsD exhaustion & silent failure metrics, logs to the Rails logger and updates the job status' do Timecop.freeze(exhaustion_time) do described_class.within_sidekiq_retries_exhausted_block(retry_params) do expect(Rails.logger).to receive(:warn).with( 'Form0781DocumentUploadFailureEmail retries exhausted', { job_id: 123, error_class: 'JennyNotFound', error_message: 'I tried to call you before but I lost my nerve', timestamp: exhaustion_time, form526_submission_id: form526_submission.id } ).and_call_original expect(StatsD).to receive(:increment).with( 'api.form_526.veteran_notifications.form0781_upload_failure_email.exhausted' ).ordered expect(StatsD).to receive(:increment).with( 'silent_failure', tags: [ 'service:disability-application', 'function:526_form_0781_failure_email_queuing' ] ).ordered end expect(form526_job_status.reload.status).to eq(Form526JobStatus::STATUS[:exhausted]) end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/test_user_dashboard/daily_maintenance_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe TestUserDashboard::DailyMaintenance do describe '#perform' do let!(:accounts) do account = create(:tud_account) TestUserDashboard::TudAccount.where(id: account.id) end before do # rubocop:disable RSpec/MessageChain allow(TestUserDashboard::TudAccount).to receive_message_chain(:where, :not).and_return(accounts) # rubocop:enable RSpec/MessageChain allow_any_instance_of(TestUserDashboard::TudAccount).to receive(:update).and_return(true) allow_any_instance_of(TestUserDashboard::AccountMetrics).to receive(:checkin).and_return(true) end it 'checks in TUD accounts' do # rubocop:disable RSpec/MessageChain expect(TestUserDashboard::TudAccount).to receive_message_chain(:where, :not) expect(TestUserDashboard::AccountMetrics).to receive_message_chain(:new, :checkin) # rubocop:enable RSpec/MessageChain described_class.new.perform end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/mhv/phr_update_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'medical_records/phr_mgr/client' Sidekiq::Testing.fake! RSpec.describe MHV::PhrUpdateJob, type: :job do describe '#perform' do let(:icn) { 'some_icn' } let(:mhv_correlation_id) { 'some_id' } let(:phr_client_instance) { instance_double(PHRMgr::Client) } before do allow(PHRMgr::Client).to receive(:new).and_return(phr_client_instance) allow(phr_client_instance).to receive(:post_phrmgr_refresh) end context 'when the user is an MHV user' do it 'calls the PHR refresh' do described_class.new.perform(icn, mhv_correlation_id) expect(phr_client_instance).to have_received(:post_phrmgr_refresh) end end context 'when the user is not an MHV user' do let(:mhv_correlation_id) { nil } it 'does not call the PHR refresh' do described_class.new.perform(icn, mhv_correlation_id) expect(phr_client_instance).not_to have_received(:post_phrmgr_refresh) end end context 'when an error occurs' do it 'logs the error' do allow(Rails.logger).to receive(:error) allow(phr_client_instance).to receive(:post_phrmgr_refresh).and_raise(StandardError, 'some error') described_class.new.perform(icn, mhv_correlation_id) expect(Rails.logger).to have_received(:error).with(match(/MHV PHR refresh failed: some error/), instance_of(StandardError)) end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/mhv/account_creator_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'sidekiq/testing' RSpec.describe MHV::AccountCreatorJob, type: :job do let!(:user) { create(:user, :with_terms_of_use_agreement, icn:) } let(:user_account) { user.user_account } let(:user_verification) { user.user_verification } let(:icn) { '10101V964144' } let(:mhv_client) { instance_double(MHV::AccountCreation::Service) } let(:job) { described_class.new } let(:break_cache) { true } let(:mhv_response_body) do { user_profile_id: '12345678', premium: true, champ_va: true, patient: true, sm_account_created: true } end it 'is unique for 5 minutes' do expect(described_class.sidekiq_options['unique_for']).to eq(5.minutes) end describe '#perform' do before do allow(MHV::AccountCreation::Service).to receive(:new).and_return(mhv_client) allow(mhv_client).to receive(:create_account).and_return(mhv_response_body) end Sidekiq::Testing.inline! do context 'when a UserVerification exists' do it 'calls the MHV::UserAccount::Creator service class and returns the created MHVUserAccount instance' do expect(MHV::UserAccount::Creator).to receive(:new).with(user_verification:, break_cache:).and_call_original job.perform(user_verification.id) end context 'when the MHV API call is successful' do it 'creates & returns a new MHVUserAccount instance' do response = job.perform(user_verification.id) expect(response).to be_an_instance_of(MHVUserAccount) end end end context 'when a UserVerification does not exist' do let(:expected_error_id) { 999 } let(:expected_error_message) do "MHV AccountCreatorJob failed: UserVerification not found for id #{expected_error_id}" end it 'logs an error' do expect(Rails.logger).to receive(:error).with(expected_error_message) job.perform(expected_error_id) end end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/form1095/delete_old1095_bs_job_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Form1095::DeleteOld1095BsJob, type: :job do describe 'perform' do let!(:current_tax_year_form) { create(:form1095_b, tax_year: Form1095B.current_tax_year) } let!(:current_year_form) { create(:form1095_b, tax_year: Form1095B.current_tax_year + 1) } it 'deletes all 1095b forms prior to the current tax year' do create(:form1095_b, tax_year: Form1095B.current_tax_year - 5) create(:form1095_b, tax_year: Form1095B.current_tax_year - 3) create(:form1095_b, tax_year: Form1095B.current_tax_year - 1) expect(Rails.logger).to receive(:info).with('Form1095B Deletion Job: Begin deleting 3 old Form1095B files') expect(Rails.logger).to receive(:info).with( /Form1095B Deletion Job: Finished deleting old Form1095B files in \d+\.\d+ seconds/ ) subject.perform expect(Form1095B.pluck(:id)).to contain_exactly(current_tax_year_form.id, current_year_form.id) end it 'uses an optional limit parameter' do oldest_form = create(:form1095_b, tax_year: Form1095B.current_tax_year - 5) older_form = create(:form1095_b, tax_year: Form1095B.current_tax_year - 3) old_form = create(:form1095_b, tax_year: Form1095B.current_tax_year - 1) expect(Rails.logger).to receive(:info).with('Form1095B Deletion Job: Begin deleting 2 old Form1095B files') expect(Rails.logger).to receive(:info).with( /Form1095B Deletion Job: Finished deleting old Form1095B files in \d+\.\d+ seconds/ ) subject.perform(2) expect(Form1095B.where(id: [oldest_form.id, older_form.id, old_form.id]).count).to eq(1) expect(Form1095B.where(id: [current_tax_year_form.id, current_year_form.id]).count).to eq(2) end it 'logs a message and deletes nothing if there are no forms to delete' do expect(Rails.logger).to receive(:info).with('Form1095B Deletion Job: No old Form1095B records to delete') subject.perform expect(Form1095B.pluck(:id)).to contain_exactly(current_tax_year_form.id, current_year_form.id) end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/form1095/new1095_bs_job_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Form1095::New1095BsJob, type: :job do describe 'perform' do let(:bucket) { double } let(:s3_resource) { double } let(:objects) { double } let(:object) { double } let(:file_names1) { %w[MEC_DataExtract_O_2021_V_2021123016452.txt] } let(:file_data1) { File.read('spec/support/form1095/single_valid_form.txt') } let(:tempfile1) do tf = Tempfile.new(file_names1[0]) tf.write(file_data1) tf.rewind tf end let(:file_names2) { %w[MEC_DataExtract_O_2020_B_2020123017382.txt] } let(:file_data2) { File.read('spec/support/form1095/multiple_valid_forms.txt') } let(:tempfile2) do tf = Tempfile.new(file_names2[0]) tf.write(file_data2) tf.rewind tf end let(:file_names3) { %w[MEC_DataExtract_O_2021_V_2021123014353.txt] } let(:file_data3) { File.read('spec/support/form1095/single_invalid_form.txt') } let(:tempfile3) do tf = Tempfile.new(file_names3[0]) tf.write(file_data3) tf.rewind tf end let(:file_names4) { %w[MEC_DataExtract_C_2020_B_2021012117364.txt] } let(:file_data4) { File.read('spec/support/form1095/multiple_valid_forms_corrections.txt') } let(:tempfile4) do tf = Tempfile.new(file_names4[0]) tf.write(file_data4) tf.rewind tf end before do allow(Aws::S3::Resource).to receive(:new).and_return(s3_resource) allow(s3_resource).to receive(:bucket).and_return(bucket) allow(bucket).to receive_messages(objects:, delete_objects: true, object:) allow(object).to receive(:get).and_return(nil) end context 'when file is for a past tax year' do it 'does not save data and deletes the file' do allow(objects).to receive(:collect).and_return(file_names1) allow(Tempfile).to receive(:new).and_return(tempfile1) expect(Rails.logger).not_to receive(:error) expect(Rails.logger).not_to receive(:warn) expect(bucket).to receive(:delete_objects) expect { subject.perform }.not_to change(Form1095B, :count).from(0) end end context 'when file is for the current tax year or later' do before do time = Time.utc(2021, 9, 21, 0, 0, 0) Timecop.freeze(time) end after { Timecop.return } it 'saves valid form from S3 file' do allow(objects).to receive(:collect).and_return(file_names1) allow(Tempfile).to receive(:new).and_return(tempfile1) expect(Rails.logger).not_to receive(:error) expect(Rails.logger).not_to receive(:warn) expect { subject.perform }.to change(Form1095B, :count).from(0).to(1) end it 'saves multiple forms from a file' do allow(objects).to receive(:collect).and_return(file_names2) allow(Tempfile).to receive(:new).and_return(tempfile2) expect(Rails.logger).not_to receive(:error) expect(Rails.logger).not_to receive(:warn) expect { subject.perform }.to change(Form1095B, :count).from(0).to(8) end context 'when user data is missing icn' do it 'does not log errors or save form but does deletes file' do allow(objects).to receive(:collect).and_return(file_names3) allow(Tempfile).to receive(:new).and_return(tempfile3) expect(Rails.logger).not_to receive(:error) expect(Rails.logger).not_to receive(:warn) expect(bucket).to receive(:delete_objects) expect { subject.perform }.not_to change(Form1095B, :count).from(0) end end context 'when error is encountered processing the file' do it 'raises an error and does not delete file' do allow(objects).to receive(:collect).and_return(file_names3) allow(Tempfile).to receive(:new).and_return(tempfile3) allow(tempfile3).to receive(:each_line).and_raise(RuntimeError, 'Bad file') expect(Rails.logger).to receive(:error).once.with('Form1095B Creation Job Error: Error processing file: ' \ "#{file_names3.first}, on line 0; Bad file") expect(Rails.logger).to receive(:error).once.with( "Form1095B Creation Job Error: failed to save 0 forms from file: #{file_names3.first}; " \ 'successfully saved 0 forms' ) expect(bucket).not_to receive(:delete_objects) expect { subject.perform }.not_to change(Form1095B, :count).from(0) end end context 'saves form corrections from a corrected file' do let!(:form1) { create(:form1095_b, tax_year: 2020, veteran_icn: '23456789098765437') } let!(:form2) { create(:form1095_b, tax_year: 2020, veteran_icn: '23456789098765464') } before do allow(objects).to receive(:collect).and_return(file_names4) allow(Tempfile).to receive(:new).and_return(tempfile4) end it 'updates forms without errors' do expect(Rails.logger).not_to receive(:error) expect(Rails.logger).not_to receive(:warn) expect do subject.perform end.to change { [form1.reload.form_data, form2.reload.form_data] } end end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/event_bus_gateway/letter_ready_notification_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'sidekiq/attr_package' require_relative '../../../app/sidekiq/event_bus_gateway/constants' require_relative 'shared_examples_letter_ready_job' RSpec.describe EventBusGateway::LetterReadyNotificationJob, type: :job do subject { described_class } # Shared setup for most test scenarios before do allow_any_instance_of(MPI::Service).to receive(:find_profile_by_attributes) .and_return(mpi_profile_response) allow_any_instance_of(BGS::PersonWebService) .to receive(:find_person_by_ptcpnt_id) .and_return(bgs_profile) allow(VaNotify::Service).to receive(:new).and_return(va_notify_service) allow(StatsD).to receive(:increment) allow(Rails.logger).to receive(:info) allow(Rails.logger).to receive(:error) allow(Rails.logger).to receive(:warn) allow(Sidekiq::AttrPackage).to receive(:create).and_return('test_cache_key_123') allow(Sidekiq::AttrPackage).to receive(:delete) allow(Flipper).to receive(:enabled?) .with(:event_bus_gateway_letter_ready_push_notifications, instance_of(Flipper::Actor)) .and_return(true) end let(:participant_id) { '1234' } let(:email_template_id) { '5678' } let(:push_template_id) { '9012' } let(:notification_id) { SecureRandom.uuid } let(:bgs_profile) do { first_nm: 'Joe', last_nm: 'Smith', brthdy_dt: 30.years.ago, ssn_nbr: '123456789' } end let(:mpi_profile) { build(:mpi_profile) } let(:mpi_profile_response) { create(:find_profile_response, profile: mpi_profile) } let!(:user_account) { create(:user_account, icn: mpi_profile_response.profile.icn) } let(:va_notify_service) do instance_double(VaNotify::Service).tap do |service| email_response = instance_double(Notifications::Client::ResponseNotification, id: notification_id) push_response = double(id: notification_id) allow(service).to receive_messages(send_email: email_response, send_push: push_response) end end let(:expected_email_args) do { recipient_identifier: { id_value: participant_id, id_type: 'PID' }, template_id: email_template_id, personalisation: { host: Settings.hostname, first_name: 'Joe' } } end let(:expected_push_args) do { mobile_app: 'VA_FLAGSHIP_APP', recipient_identifier: { id_value: mpi_profile_response.profile.icn, id_type: 'ICN' }, template_id: push_template_id, personalisation: {} } end describe '#perform' do describe 'successful notification sending' do around do |example| Sidekiq::Testing.inline! { example.run } end context 'with both email and push template IDs' do it 'sends both notifications with correct arguments' do expect(va_notify_service).to receive(:send_email).with(expected_email_args) expect(va_notify_service).to receive(:send_push).with(expected_push_args) result = subject.new.perform(participant_id, email_template_id, push_template_id) expect(result).to eq([]) end it 'creates both notification records' do expect do subject.new.perform(participant_id, email_template_id, push_template_id) end.to change(EventBusGatewayNotification, :count).by(1) .and change(EventBusGatewayPushNotification, :count).by(1) end it 'increments success metrics for both notification types' do expect(StatsD).to receive(:increment).with( 'event_bus_gateway.letter_ready_email.success', tags: EventBusGateway::Constants::DD_TAGS ) expect(StatsD).to receive(:increment).with( 'event_bus_gateway.letter_ready_push.success', tags: EventBusGateway::Constants::DD_TAGS ) subject.new.perform(participant_id, email_template_id, push_template_id) end end context 'with only email template ID' do it 'sends only email notification' do expect(va_notify_service).to receive(:send_email) expect(va_notify_service).not_to receive(:send_push) result = subject.new.perform(participant_id, email_template_id) expect(result).to eq([]) end it 'creates only email notification record' do expect do subject.new.perform(participant_id, email_template_id) end.to change(EventBusGatewayNotification, :count).by(1) .and not_change(EventBusGatewayPushNotification, :count) end it 'increments email success metric and push skipped metric' do expect(StatsD).to receive(:increment).with( 'event_bus_gateway.letter_ready_email.success', tags: EventBusGateway::Constants::DD_TAGS ) expect(StatsD).to receive(:increment).with( 'event_bus_gateway.letter_ready_notification.skipped', tags: EventBusGateway::Constants::DD_TAGS + ['notification_type:push', 'reason:icn_or_template_not_available'] ) subject.new.perform(participant_id, email_template_id) end end context 'PII protection with AttrPackage' do it 'stores PII in Redis and passes only cache_key to email job' do expect(Sidekiq::AttrPackage).to receive(:create).with( first_name: 'Joe', icn: mpi_profile_response.profile.icn ).and_return('email_cache_key') expect(EventBusGateway::LetterReadyEmailJob).to receive(:perform_async).with( participant_id, email_template_id, 'email_cache_key' ) subject.new.perform(participant_id, email_template_id, push_template_id) end it 'stores PII in Redis and passes only cache_key to push job' do expect(Sidekiq::AttrPackage).to receive(:create).with( icn: mpi_profile_response.profile.icn ).and_return('push_cache_key') expect(EventBusGateway::LetterReadyPushJob).to receive(:perform_async).with( participant_id, push_template_id, 'push_cache_key' ) subject.new.perform(participant_id, email_template_id, push_template_id) end end context 'with only push template ID' do it 'sends only push notification' do expect(va_notify_service).not_to receive(:send_email) expect(va_notify_service).to receive(:send_push) result = subject.new.perform(participant_id, nil, push_template_id) expect(result).to eq([]) end it 'creates only push notification record' do expect do subject.new.perform(participant_id, nil, push_template_id) end.to not_change(EventBusGatewayNotification, :count) .and change(EventBusGatewayPushNotification, :count).by(1) end it 'increments push success metric and email skipped metric' do expect(StatsD).to receive(:increment).with( 'event_bus_gateway.letter_ready_push.success', tags: EventBusGateway::Constants::DD_TAGS ) expect(StatsD).to receive(:increment).with( 'event_bus_gateway.letter_ready_notification.skipped', tags: EventBusGateway::Constants::DD_TAGS + ['notification_type:email', 'reason:icn_or_template_not_available'] ) subject.new.perform(participant_id, nil, push_template_id) end end it 'configures sidekiq retry count' do expect(described_class.get_sidekiq_options['retry']).to eq(EventBusGateway::Constants::SIDEKIQ_RETRY_COUNT_FIRST_NOTIFICATION) end end describe 'data validation scenarios' do around do |example| Sidekiq::Testing.inline! { example.run } end context 'when ICN is not available' do let(:mpi_profile) { build(:mpi_profile, icn: nil) } it 'does not send any notifications and returns empty array' do expect(va_notify_service).not_to receive(:send_email) expect(va_notify_service).not_to receive(:send_push) result = subject.new.perform(participant_id, email_template_id, push_template_id) expect(result).to eq([]) end it 'logs skipped notifications for both email and push' do expect(Rails.logger).to receive(:error).with( 'LetterReadyNotificationJob email skipped', { notification_type: 'email', reason: 'ICN or template not available', template_id: email_template_id } ) expect(Rails.logger).to receive(:error).with( 'LetterReadyNotificationJob push skipped', { notification_type: 'push', reason: 'ICN or template not available', template_id: push_template_id } ) subject.new.perform(participant_id, email_template_id, push_template_id) end it 'increments skipped metrics for both email and push' do expect(StatsD).to receive(:increment).with( 'event_bus_gateway.letter_ready_notification.skipped', tags: EventBusGateway::Constants::DD_TAGS + ['notification_type:email', 'reason:icn_or_template_not_available'] ) expect(StatsD).to receive(:increment).with( 'event_bus_gateway.letter_ready_notification.skipped', tags: EventBusGateway::Constants::DD_TAGS + ['notification_type:push', 'reason:icn_or_template_not_available'] ) subject.new.perform(participant_id, email_template_id, push_template_id) end end context 'when BGS person name is missing' do let(:bgs_profile) { { last_nm: 'Smith', ssn_nbr: '123456789' } } it 'skips email but still sends push notification' do expect(va_notify_service).not_to receive(:send_email) expect(va_notify_service).to receive(:send_push) expect(StatsD).to receive(:increment).with( 'event_bus_gateway.letter_ready_push.success', tags: EventBusGateway::Constants::DD_TAGS ) result = subject.new.perform(participant_id, email_template_id, push_template_id) expect(result).to eq([]) end it 'creates only push notification record' do expect do subject.new.perform(participant_id, email_template_id, push_template_id) end.to not_change(EventBusGatewayNotification, :count) .and change(EventBusGatewayPushNotification, :count).by(1) end it 'logs skipped email notification due to missing first_name' do expect(Rails.logger).to receive(:error).with( 'LetterReadyNotificationJob email skipped', { notification_type: 'email', reason: 'first_name not present', template_id: email_template_id } ) subject.new.perform(participant_id, email_template_id, push_template_id) end it 'increments skipped metric for email' do expect(StatsD).to receive(:increment).with( 'event_bus_gateway.letter_ready_notification.skipped', tags: EventBusGateway::Constants::DD_TAGS + ['notification_type:email', 'reason:first_name_not_present'] ) subject.new.perform(participant_id, email_template_id, push_template_id) end end end describe 'partial failure scenarios' do around do |example| Sidekiq::Testing.inline! { example.run } end context 'when email job fails but push job succeeds' do before do allow(EventBusGateway::LetterReadyEmailJob).to receive(:perform_async) .and_raise(StandardError, 'Email job failed') end it 'sends push notification and returns error for email' do expect(va_notify_service).to receive(:send_push) expect(Rails.logger).to receive(:warn).with( 'LetterReadyNotificationJob partial failure', { successful: 'push', failed: 'email: Email job failed' } ) result = subject.new.perform(participant_id, email_template_id, push_template_id) expect(result).to eq([{ type: 'email', error: 'Email job failed' }]) end it 'creates only push notification record' do expect do subject.new.perform(participant_id, email_template_id, push_template_id) end.to not_change(EventBusGatewayNotification, :count) .and change(EventBusGatewayPushNotification, :count).by(1) end end context 'when push job fails but email job succeeds' do before do allow(EventBusGateway::LetterReadyPushJob).to receive(:perform_async) .and_raise(StandardError, 'Push job failed') end it 'sends email notification and returns error for push' do expect(va_notify_service).to receive(:send_email) expect(Rails.logger).to receive(:warn).with( 'LetterReadyNotificationJob partial failure', { successful: 'email', failed: 'push: Push job failed' } ) expect(StatsD).to receive(:increment).with( 'event_bus_gateway.letter_ready_email.success', tags: EventBusGateway::Constants::DD_TAGS ) result = subject.new.perform(participant_id, email_template_id, push_template_id) expect(result).to eq([{ type: 'push', error: 'Push job failed' }]) end it 'creates only email notification record' do expect do subject.new.perform(participant_id, email_template_id, push_template_id) end.to change(EventBusGatewayNotification, :count).by(1) .and not_change(EventBusGatewayPushNotification, :count) end end context 'when both email and push jobs fail' do before do allow(EventBusGateway::LetterReadyEmailJob).to receive(:perform_async) .and_raise(StandardError, 'Email job failed') allow(EventBusGateway::LetterReadyPushJob).to receive(:perform_async) .and_raise(StandardError, 'Push job failed') end it 'raises error with combined failure message' do expect do subject.new.perform(participant_id, email_template_id, push_template_id) end.to raise_error(EventBusGateway::Errors::NotificationEnqueueError, /All notifications failed/) .and not_change(EventBusGatewayNotification, :count) .and not_change(EventBusGatewayPushNotification, :count) end end end describe 'error handling' do context 'when BGS service fails' do include_examples 'letter ready job bgs error handling', 'Notification' it 'does not send any notifications and records failure' do expect(va_notify_service).not_to receive(:send_email) expect(va_notify_service).not_to receive(:send_push) expect_any_instance_of(described_class).to receive(:record_notification_send_failure) expect do subject.new.perform(participant_id, email_template_id, push_template_id) end.to raise_error(EventBusGateway::Errors::BgsPersonNotFoundError, 'Participant ID cannot be found in BGS') end end context 'when MPI service fails' do include_examples 'letter ready job mpi error handling', 'Notification' it 'does not send any notifications and records failure' do expect(va_notify_service).not_to receive(:send_email) expect(va_notify_service).not_to receive(:send_push) expect_any_instance_of(described_class).to receive(:record_notification_send_failure) expect do subject.new.perform(participant_id, email_template_id, push_template_id) end.to raise_error(EventBusGateway::Errors::MpiProfileNotFoundError, 'Failed to fetch MPI profile') end end context 'when an unexpected error occurs during data fetching' do before do allow_any_instance_of(BGS::PersonWebService) .to receive(:find_person_by_ptcpnt_id) .and_raise(StandardError, 'Unexpected BGS error') end it 'records failure because instance variables are nil' do expect_any_instance_of(described_class).to receive(:record_notification_send_failure) .with(instance_of(StandardError), 'Notification') expect do subject.new.perform(participant_id, email_template_id, push_template_id) end.to raise_error(StandardError, 'Unexpected BGS error') end end context 'when error occurs after data fetching completes' do before do allow(EventBusGateway::LetterReadyEmailJob).to receive(:perform_async) .and_raise(StandardError, 'Email job enqueue failed') end it 'does not record notification send failure' do expect_any_instance_of(described_class).not_to receive(:record_notification_send_failure) expect do subject.new.perform(participant_id, email_template_id, push_template_id) end.not_to raise_error end it 'returns error in the errors array' do result = subject.new.perform(participant_id, email_template_id, push_template_id) expect(result).to eq([{ type: 'email', error: 'Email job enqueue failed' }]) end end end describe 'feature flag scenarios' do around do |example| Sidekiq::Testing.inline! { example.run } end context 'when push notifications feature flag is disabled' do before do allow(Flipper).to receive(:enabled?) .with(:event_bus_gateway_letter_ready_push_notifications, instance_of(Flipper::Actor)) .and_return(false) end it 'sends email but skips push notification' do expect(va_notify_service).to receive(:send_email) expect(va_notify_service).not_to receive(:send_push) subject.new.perform(participant_id, email_template_id, push_template_id) end it 'logs that push notification was skipped due to feature flag' do expect(Rails.logger).to receive(:error).with( 'LetterReadyNotificationJob push skipped', { notification_type: 'push', reason: 'Push notifications not enabled for this user', template_id: push_template_id } ) subject.new.perform(participant_id, email_template_id, push_template_id) end it 'increments skipped metric for push with feature flag reason' do expect(StatsD).to receive(:increment).with( 'event_bus_gateway.letter_ready_email.success', tags: EventBusGateway::Constants::DD_TAGS ) expect(StatsD).to receive(:increment).with( 'event_bus_gateway.letter_ready_notification.skipped', tags: EventBusGateway::Constants::DD_TAGS + ['notification_type:push', 'reason:push_notifications_not_enabled_for_this_user'] ) subject.new.perform(participant_id, email_template_id, push_template_id) end end context 'when push notifications feature flag is enabled' do it 'sends both email and push notifications' do expect(va_notify_service).to receive(:send_email) expect(va_notify_service).to receive(:send_push) subject.new.perform(participant_id, email_template_id, push_template_id) end end end end include_examples 'letter ready job sidekiq retries exhausted', 'Notification' end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/event_bus_gateway/letter_ready_email_end_to_end_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'va_notify/service' RSpec.describe 'EventBusGateway Letter Ready Email End-to-End Flow', type: :feature do let(:participant_id) { '1234567890' } let(:template_id) { '5678' } let(:initial_va_notify_id) { SecureRandom.uuid } let(:retry_va_notify_id) { SecureRandom.uuid } let(:retry_va_notify_id_second) { SecureRandom.uuid } # Test data setup let(:bgs_profile) do { first_nm: 'John', last_nm: 'Smith', brthdy_dt: 30.years.ago, ssn_nbr: '123456789' } end let(:mpi_profile) { build(:mpi_profile, participant_id:) } let(:mpi_profile_response) { create(:find_profile_response, profile: mpi_profile) } let(:user_account) { create(:user_account, icn: mpi_profile_response.profile.icn) } # Mock services let(:va_notify_service) { instance_double(VaNotify::Service) } before do # Clear any existing jobs Sidekiq::Worker.clear_all # Setup user account user_account # Mock external services allow(VaNotify::Service).to receive(:new).and_return(va_notify_service) allow_any_instance_of(MPI::Service).to receive(:find_profile_by_attributes) .and_return(mpi_profile_response) allow_any_instance_of(MPI::Service).to receive(:find_profile_by_identifier) .and_return(mpi_profile_response) allow_any_instance_of(BGS::PersonWebService) .to receive(:find_person_by_ptcpnt_id).and_return(bgs_profile) # Mock StatsD and Rails logger allow(StatsD).to receive(:increment) allow(Rails.logger).to receive(:error) allow(Rails.logger).to receive(:info) end # Helper method to create notification doubles def create_notification_double(va_notify_id, status, options = {}) double('notification', id: options[:id] || SecureRandom.random_number(1_000_000), status:, notification_id: va_notify_id, source_location: options[:source_location] || 'test', status_reason: options[:status_reason] || "test #{status}", notification_type: options[:notification_type] || 'email') end describe 'Successful email flow without retries' do it 'completes the full flow: controller -> job -> email sent -> delivered callback' do # Mock successful email send email_response = instance_double(Notifications::Client::ResponseNotification, id: initial_va_notify_id) expect(va_notify_service).to receive(:send_email).once.and_return(email_response) # Step 1: Simulate controller request EventBusGateway::LetterReadyEmailJob.perform_async(participant_id, template_id) # Step 2: Process the job expect do Sidekiq::Worker.drain_all end.to change(EventBusGatewayNotification, :count).by(1) # Verify notification was created notification = EventBusGatewayNotification.last expect(notification.user_account).to eq(user_account) expect(notification.template_id).to eq(template_id) expect(notification.va_notify_id).to eq(initial_va_notify_id) expect(notification.attempts).to eq(1) # Step 3: Simulate delivered callback delivered_notification = create_notification_double(initial_va_notify_id, 'delivered', status_reason: 'delivered') EventBusGateway::VANotifyEmailStatusCallback.call(delivered_notification) # Verify metrics were recorded for delivery expect(StatsD).to have_received(:increment) .with('callbacks.event_bus_gateway.va_notify.notifications.delivered') # Verify no retry jobs were queued expect(EventBusGateway::LetterReadyRetryEmailJob.jobs).to be_empty end end describe 'Email retry flows with event_bus_gateway_retry_emails enabled' do before do allow(Flipper).to receive(:enabled?).with(:event_bus_gateway_retry_emails).and_return(true) end it "Allow up to #{EventBusGateway::Constants::MAX_EMAIL_ATTEMPTS} attempts." do initial_response = instance_double(Notifications::Client::ResponseNotification, id: initial_va_notify_id) retry_responses = Array.new(EventBusGateway::Constants::MAX_EMAIL_ATTEMPTS - 2) do |i| instance_double(Notifications::Client::ResponseNotification, id: "retry-#{i}-#{SecureRandom.uuid}") end expect(va_notify_service).to receive(:send_email) .exactly(EventBusGateway::Constants::MAX_EMAIL_ATTEMPTS - 1).times .and_return(initial_response, *retry_responses) # Step 1: Initial email job EventBusGateway::LetterReadyEmailJob.perform_async(participant_id, template_id) Sidekiq::Worker.drain_all notification = EventBusGatewayNotification.last expect(notification.attempts).to eq(1) temp_failure = create_notification_double(notification.va_notify_id, 'temporary-failure') EventBusGateway::VANotifyEmailStatusCallback.call(temp_failure) # Step 2: Simulate the remaining temporary failures up to one below MAX_EMAIL_ATTEMPTS. (EventBusGateway::Constants::MAX_EMAIL_ATTEMPTS - 2).times do |attempt| expect(EventBusGateway::LetterReadyRetryEmailJob.jobs.size).to eq(1) Sidekiq::Worker.drain_all notification.reload expect(notification.attempts).to eq(attempt + 2) temp_failure = create_notification_double(notification.va_notify_id, 'temporary-failure') EventBusGateway::VANotifyEmailStatusCallback.call(temp_failure) end expect(notification.attempts).to eq(EventBusGateway::Constants::MAX_EMAIL_ATTEMPTS - 1) expect(EventBusGateway::LetterReadyRetryEmailJob.jobs.length).to eq(1) expect(StatsD).not_to have_received(:increment) .with('event_bus_gateway.va_notify_email_status_callback.exhausted_retries', tags: EventBusGateway::Constants::DD_TAGS) expect(Rails.logger).not_to have_received(:error) .with('EventBusGateway email retries exhausted', { ebg_notification_id: notification.id, max_attempts: EventBusGateway::Constants::MAX_EMAIL_ATTEMPTS }) end it 'retries twice after multiple temporary failures, then succeeds' do # Mock all email sends initial_response = instance_double(Notifications::Client::ResponseNotification, id: initial_va_notify_id) retry_response_first = instance_double(Notifications::Client::ResponseNotification, id: retry_va_notify_id) retry_response_second = instance_double(Notifications::Client::ResponseNotification, id: retry_va_notify_id_second) expect(va_notify_service).to receive(:send_email).exactly(3).times .and_return(initial_response, retry_response_first, retry_response_second) # Step 1: Initial email job EventBusGateway::LetterReadyEmailJob.perform_async(participant_id, template_id) Sidekiq::Worker.drain_all notification = EventBusGatewayNotification.last expect(notification.attempts).to eq(1) # Step 2: First temporary failure (use actual va_notify_id from notification) temp_failure_first = create_notification_double(notification.va_notify_id, 'temporary-failure') EventBusGateway::VANotifyEmailStatusCallback.call(temp_failure_first) expect(EventBusGateway::LetterReadyRetryEmailJob.jobs.size).to eq(1) # Process first retry Sidekiq::Worker.drain_all notification.reload expect(notification.attempts).to eq(2) expect(notification.va_notify_id).to eq(retry_va_notify_id) # Step 3: Second temporary failure (use updated va_notify_id from notification) temp_failure_second = create_notification_double(notification.va_notify_id, 'temporary-failure') EventBusGateway::VANotifyEmailStatusCallback.call(temp_failure_second) expect(EventBusGateway::LetterReadyRetryEmailJob.jobs.size).to eq(1) # Process second retry Sidekiq::Worker.drain_all notification.reload expect(notification.attempts).to eq(3) expect(notification.va_notify_id).to eq(retry_va_notify_id_second) # Step 4: Finally delivered (use final va_notify_id) delivered_final = create_notification_double(notification.va_notify_id, 'delivered', status_reason: 'delivered') EventBusGateway::VANotifyEmailStatusCallback.call(delivered_final) # Verify no more retries queued expect(EventBusGateway::LetterReadyRetryEmailJob.jobs).to be_empty # Verify success metrics recorded twice expect(StatsD).to have_received(:increment) .with('event_bus_gateway.va_notify_email_status_callback.queued_retry_success', tags: EventBusGateway::Constants::DD_TAGS).twice end it 'exhausts retries after reaching MAX_EMAIL_ATTEMPTS' do initial_response = instance_double(Notifications::Client::ResponseNotification, id: initial_va_notify_id) retry_responses = Array.new(EventBusGateway::Constants::MAX_EMAIL_ATTEMPTS - 1) do |i| instance_double(Notifications::Client::ResponseNotification, id: "retry-#{i}-#{SecureRandom.uuid}") end expect(va_notify_service).to receive(:send_email) .exactly(EventBusGateway::Constants::MAX_EMAIL_ATTEMPTS).times .and_return(initial_response, *retry_responses) # Step 1: Initial email job EventBusGateway::LetterReadyEmailJob.perform_async(participant_id, template_id) Sidekiq::Worker.drain_all notification = EventBusGatewayNotification.last expect(notification.attempts).to eq(1) temp_failure = create_notification_double(notification.va_notify_id, 'temporary-failure') EventBusGateway::VANotifyEmailStatusCallback.call(temp_failure) # Step 2: Simulate the remaining temporary failures up to MAX_EMAIL_ATTEMPTS (EventBusGateway::Constants::MAX_EMAIL_ATTEMPTS - 1).times do |attempt| # Should queue retry if not at max attempts expect(EventBusGateway::LetterReadyRetryEmailJob.jobs.size).to eq(1) Sidekiq::Worker.drain_all notification.reload expect(notification.attempts).to eq(attempt + 2) # Create a temporary failure notification with the current va_notify_id temp_failure = create_notification_double(notification.va_notify_id, 'temporary-failure') EventBusGateway::VANotifyEmailStatusCallback.call(temp_failure) end expect(notification.attempts).to eq(EventBusGateway::Constants::MAX_EMAIL_ATTEMPTS) # initial + remaining retries # Verify no retry job queued and exhausted retry logged expect(EventBusGateway::LetterReadyRetryEmailJob.jobs).to be_empty expect(StatsD).to have_received(:increment) .with('event_bus_gateway.va_notify_email_status_callback.exhausted_retries', tags: EventBusGateway::Constants::DD_TAGS) expect(Rails.logger).to have_received(:error) .with('EventBusGateway email retries exhausted', { ebg_notification_id: notification.id, max_attempts: EventBusGateway::Constants::MAX_EMAIL_ATTEMPTS }) end end describe 'Email retry flows with event_bus_gateway_retry_emails disabled' do before do allow(Flipper).to receive(:enabled?).with(:event_bus_gateway_retry_emails).and_return(false) end it 'does not retry on temporary failure when feature flag is disabled' do # Mock initial email send email_response = instance_double(Notifications::Client::ResponseNotification, id: initial_va_notify_id) expect(va_notify_service).to receive(:send_email).once.and_return(email_response) # Step 1: Initial email job EventBusGateway::LetterReadyEmailJob.perform_async(participant_id, template_id) Sidekiq::Worker.drain_all notification = EventBusGatewayNotification.last expect(notification.attempts).to eq(1) # Step 2: Temporary failure callback (use actual notification va_notify_id) temp_failure_disabled = create_notification_double(notification.va_notify_id, 'temporary-failure') EventBusGateway::VANotifyEmailStatusCallback.call(temp_failure_disabled) # Verify no retry job was queued expect(EventBusGateway::LetterReadyRetryEmailJob.jobs).to be_empty # Verify temporary failure metrics recorded expect(StatsD).to have_received(:increment) .with('callbacks.event_bus_gateway.va_notify.notifications.temporary_failure') end end describe 'Error handling in end-to-end flow' do before do allow(Flipper).to receive(:enabled?).with(:event_bus_gateway_retry_emails).and_return(true) end it 'handles EventBusGatewayNotificationNotFoundError during retry callback' do # Mock initial email send email_response = instance_double(Notifications::Client::ResponseNotification, id: initial_va_notify_id) expect(va_notify_service).to receive(:send_email).once.and_return(email_response) # Step 1: Initial email job EventBusGateway::LetterReadyEmailJob.perform_async(participant_id, template_id) Sidekiq::Worker.drain_all notification = EventBusGatewayNotification.last # Step 2: Delete the notification to simulate not found scenario EventBusGatewayNotification.destroy_all # Step 3: Temporary failure callback should raise error (use the deleted notification's va_notify_id) temp_failure_not_found = create_notification_double(notification.va_notify_id, 'temporary-failure') expect do EventBusGateway::VANotifyEmailStatusCallback.call(temp_failure_not_found) end.to raise_error(EventBusGateway::VANotifyEmailStatusCallback::EventBusGatewayNotificationNotFoundError) # Verify failure metric was recorded expect(StatsD).to have_received(:increment) .with('event_bus_gateway.va_notify_email_status_callback.queued_retry_failure', tags: EventBusGateway::Constants::DD_TAGS + ['function: EventBusGateway::VANotifyEmailStatusCallback::EventBusGatewayNotificationNotFoundError']) end it 'handles MPI errors during retry scheduling' do # Mock initial email send email_response = instance_double(Notifications::Client::ResponseNotification, id: initial_va_notify_id) expect(va_notify_service).to receive(:send_email).once.and_return(email_response) # Step 1: Initial email job EventBusGateway::LetterReadyEmailJob.perform_async(participant_id, template_id) Sidekiq::Worker.drain_all notification = EventBusGatewayNotification.last # Step 2: Mock MPI failure for retry scheduling mpi_error_response = instance_double(MPI::Responses::FindProfileResponse, ok?: false) allow_any_instance_of(MPI::Service).to receive(:find_profile_by_identifier) .and_return(mpi_error_response) # Step 3: Temporary failure callback should raise MPIError (use actual notification va_notify_id) temp_failure_for_mpi_test = create_notification_double(notification.va_notify_id, 'temporary-failure') expect do EventBusGateway::VANotifyEmailStatusCallback.call(temp_failure_for_mpi_test) end.to raise_error(EventBusGateway::VANotifyEmailStatusCallback::MPIError) # Verify failure metric was recorded expect(StatsD).to have_received(:increment) .with('event_bus_gateway.va_notify_email_status_callback.queued_retry_failure', tags: EventBusGateway::Constants::DD_TAGS + ['function: EventBusGateway::VANotifyEmailStatusCallback::MPIError']) end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/event_bus_gateway/letter_ready_retry_email_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'va_notify/service' require_relative '../../../app/sidekiq/event_bus_gateway/constants' RSpec.describe EventBusGateway::LetterReadyRetryEmailJob, type: :job do subject { described_class } let(:notification_id) { existing_notification.id } let!(:existing_notification) do create(:event_bus_gateway_notification, template_id:, attempts: 1, va_notify_id: 'original-va-notify-id') end let(:va_notify_service) do service = instance_double(VaNotify::Service) response = instance_double(Notifications::Client::ResponseNotification, id: va_notify_response_id) allow(service).to receive(:send_email).and_return(response) service end let(:va_notify_response_id) { SecureRandom.uuid } let(:personalisation) { { host: 'localhost', first_name: 'Joe' } } let(:template_id) { '5678' } let(:participant_id) { '1234' } describe 'EventBusGatewayNotificationNotFoundError' do it 'is defined as a custom exception' do expect(EventBusGateway::LetterReadyRetryEmailJob::EventBusGatewayNotificationNotFoundError).to be < StandardError end end context 'when an error does not occur' do before do allow(VaNotify::Service).to receive(:new).and_return(va_notify_service) allow(StatsD).to receive(:increment) end it 'sends an email using VA Notify and updates the existing EventBusGatewayNotification' do expected_args = { recipient_identifier: { id_value: participant_id, id_type: 'PID' }, template_id:, personalisation: } expect(va_notify_service).to receive(:send_email).with(expected_args) expect(StatsD).to receive(:increment) .with("#{described_class::STATSD_METRIC_PREFIX}.success", tags: EventBusGateway::Constants::DD_TAGS) expect do subject.new.perform(participant_id, template_id, personalisation, notification_id) end.not_to change(EventBusGatewayNotification, :count) # Check that the existing notification was updated existing_notification.reload expect(existing_notification.attempts).to eq(2) expect(existing_notification.va_notify_id).to eq(va_notify_response_id) end end context 'when a VA Notify error occurs during email sending' do before do allow(VaNotify::Service).to receive(:new).and_return(va_notify_service) allow(va_notify_service).to receive(:send_email).and_raise(StandardError, 'VA Notify email error') allow(Rails.logger).to receive(:error) allow(StatsD).to receive(:increment) end let(:error_message) { 'LetterReadyRetryEmailJob email error' } let(:message_detail) { 'VA Notify email error' } let(:tags) { EventBusGateway::Constants::DD_TAGS + ["function: #{error_message}"] } it 'does not send an email successfully, logs the error, increments the statsd metric, and re-raises for retry' do expect(Rails.logger) .to receive(:error) .with(error_message, { message: message_detail }) expect(StatsD).to receive(:increment).with("#{described_class::STATSD_METRIC_PREFIX}.failure", tags:) expect do subject.new.perform(participant_id, template_id, personalisation, notification_id) end.to raise_error(StandardError, message_detail).and not_change(EventBusGatewayNotification, :count) # Notification should remain unchanged since email send failed existing_notification.reload expect(existing_notification.attempts).to eq(1) expect(existing_notification.va_notify_id).to eq('original-va-notify-id') end end context 'when notification record is not found' do before do allow(VaNotify::Service).to receive(:new).and_return(va_notify_service) allow(Rails.logger).to receive(:error) allow(StatsD).to receive(:increment) end it 'raises EventBusGatewayNotificationNotFoundError, logs failure, and re-raises for retry' do non_existent_id = SecureRandom.uuid expect(va_notify_service).not_to receive(:send_email) expect(Rails.logger).to receive(:error) .with('LetterReadyRetryEmailJob email error', { message: match(/EventBusGatewayNotificationNotFoundError/) }) expect(StatsD).to receive(:increment) .with("#{described_class::STATSD_METRIC_PREFIX}.failure", tags: EventBusGateway::Constants::DD_TAGS + ['function: LetterReadyRetryEmailJob email error']) expect do subject.new.perform(participant_id, template_id, personalisation, non_existent_id) end.to raise_error(EventBusGateway::LetterReadyRetryEmailJob::EventBusGatewayNotificationNotFoundError) end it 'raises EventBusGatewayNotificationNotFoundError when notification_id is nil and re-raises for retry' do expect(va_notify_service).not_to receive(:send_email) expect(Rails.logger).to receive(:error) .with('LetterReadyRetryEmailJob email error', { message: match(/EventBusGatewayNotificationNotFoundError/) }) expect(StatsD).to receive(:increment) .with("#{described_class::STATSD_METRIC_PREFIX}.failure", tags: EventBusGateway::Constants::DD_TAGS + ['function: LetterReadyRetryEmailJob email error']) expect do subject.new.perform(participant_id, template_id, personalisation, nil) end.to raise_error(EventBusGateway::LetterReadyRetryEmailJob::EventBusGatewayNotificationNotFoundError) end end context 'when sidekiq retries are exhausted' do before do allow(Rails.logger).to receive(:error) allow(StatsD).to receive(:increment) end let(:job_id) { 'test-job-id-123' } let(:error_class) { 'StandardError' } let(:error_message) { 'Some error message' } let(:msg) do { 'jid' => job_id, 'error_class' => error_class, 'error_message' => error_message } end let(:exception) { StandardError.new(error_message) } it 'logs the exhausted retries and increments the statsd metric' do # Get the retries exhausted callback from the job class retries_exhausted_callback = described_class.sidekiq_retries_exhausted_block expect(Rails.logger).to receive(:error) .with('LetterReadyRetryEmailJob retries exhausted', { job_id:, timestamp: be_within(1.second).of(Time.now.utc), error_class:, error_message: }) expect(StatsD).to receive(:increment) .with("#{described_class::STATSD_METRIC_PREFIX}.exhausted", tags: EventBusGateway::Constants::DD_TAGS) retries_exhausted_callback.call(msg, exception) end end describe 'Retry count limit.' do it "Sets Sidekiq retry count to #{EventBusGateway::Constants::SIDEKIQ_RETRY_COUNT_RETRY_EMAIL}." do expect(described_class.sidekiq_options['retry']).to eq(EventBusGateway::Constants::SIDEKIQ_RETRY_COUNT_RETRY_EMAIL) end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/event_bus_gateway/letter_ready_email_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'va_notify/service' require 'sidekiq/attr_package' require_relative '../../../app/sidekiq/event_bus_gateway/constants' require_relative 'shared_examples_letter_ready_job' RSpec.describe EventBusGateway::LetterReadyEmailJob, type: :job do subject { described_class } let(:participant_id) { '1234' } let(:template_id) { '5678' } let(:first_name) { 'Joe' } let(:icn) { '1234567890V123456' } let(:notification_id) { SecureRandom.uuid } let(:bgs_profile) do { first_nm: 'Joe', last_nm: 'Smith', brthdy_dt: 30.years.ago, ssn_nbr: '123456789' } end let(:mpi_profile) { build(:mpi_profile) } let(:mpi_profile_response) { create(:find_profile_response, profile: mpi_profile) } let!(:user_account) { create(:user_account, icn: mpi_profile_response.profile.icn) } let(:va_notify_service) do instance_double(VaNotify::Service).tap do |service| response = instance_double(Notifications::Client::ResponseNotification, id: notification_id) allow(service).to receive(:send_email).and_return(response) end end let(:expected_email_args) do { recipient_identifier: { id_value: participant_id, id_type: 'PID' }, template_id:, personalisation: { host: EventBusGateway::Constants::HOSTNAME_MAPPING[Settings.hostname] || Settings.hostname, first_name: } } end let(:notify_service_params) do { api_key: EventBusGateway::Constants::NOTIFY_SETTINGS.api_key, options: { callback_klass: 'EventBusGateway::VANotifyEmailStatusCallback' } } end # Shared setup for most test scenarios before do allow(VaNotify::Service).to receive(:new).with( EventBusGateway::Constants::NOTIFY_SETTINGS.api_key, { callback_klass: 'EventBusGateway::VANotifyEmailStatusCallback' } ).and_return(va_notify_service) allow_any_instance_of(MPI::Service).to receive(:find_profile_by_attributes) .and_return(mpi_profile_response) allow_any_instance_of(BGS::PersonWebService) .to receive(:find_person_by_ptcpnt_id) .and_return(bgs_profile) allow(StatsD).to receive(:increment) allow(Rails.logger).to receive(:error) allow(Sidekiq::AttrPackage).to receive(:find).and_return(nil) allow(Sidekiq::AttrPackage).to receive(:delete) end describe 'successful email notification' do it 'sends email with correct arguments' do expect(va_notify_service).to receive(:send_email).with(expected_email_args) subject.new.perform(participant_id, template_id) end it 'creates EventBusGatewayNotification record with correct attributes' do expect do subject.new.perform(participant_id, template_id) end.to change(EventBusGatewayNotification, :count).by(1) notification = EventBusGatewayNotification.last expect(notification.user_account).to eq(user_account) expect(notification.va_notify_id).to eq(notification_id) expect(notification.template_id).to eq(template_id) end it 'increments success metric' do expect(StatsD).to receive(:increment).with( "#{described_class::STATSD_METRIC_PREFIX}.success", tags: EventBusGateway::Constants::DD_TAGS ) subject.new.perform(participant_id, template_id) end it 'configures VaNotify::Service with correct parameters' do expect(VaNotify::Service).to receive(:new).with( EventBusGateway::Constants::NOTIFY_SETTINGS.api_key, { callback_klass: 'EventBusGateway::VANotifyEmailStatusCallback' } ).and_return(va_notify_service) subject.new.perform(participant_id, template_id) end end describe '#send_email_notification' do it 'sends email and creates notification record' do job_instance = subject.new expect(va_notify_service).to receive(:send_email).with(expected_email_args) expect do job_instance.send(:send_email_notification, participant_id, template_id, first_name, mpi_profile.icn) end.to change(EventBusGatewayNotification, :count).by(1) end context 'when notification record fails to save' do let(:invalid_notification) do instance_double(EventBusGatewayNotification, persisted?: false, errors: double(full_messages: ['Validation failed'])) end before do allow(EventBusGatewayNotification).to receive(:create).and_return(invalid_notification) allow(Rails.logger).to receive(:warn) end it 'logs a warning with error details' do job_instance = subject.new expect(Rails.logger).to receive(:warn).with( 'LetterReadyEmailJob notification record failed to save', { errors: ['Validation failed'], template_id:, va_notify_id: notification_id } ) job_instance.send(:send_email_notification, participant_id, template_id, first_name, mpi_profile.icn) end it 'still sends the email successfully' do job_instance = subject.new expect(va_notify_service).to receive(:send_email).with(expected_email_args) job_instance.send(:send_email_notification, participant_id, template_id, first_name, mpi_profile.icn) end it 'does not raise an error' do job_instance = subject.new expect do job_instance.send(:send_email_notification, participant_id, template_id, first_name, mpi_profile.icn) end.not_to raise_error end end context 'when user_account is nil' do before do allow_any_instance_of(described_class).to receive(:user_account).and_return(nil) end it 'successfully creates notification record without user_account' do job_instance = subject.new expect do job_instance.send(:send_email_notification, participant_id, template_id, first_name, mpi_profile.icn) end.to change(EventBusGatewayNotification, :count).by(1) notification = EventBusGatewayNotification.last expect(notification.user_account).to be_nil expect(notification.template_id).to eq(template_id) expect(notification.va_notify_id).to eq(notification_id) end it 'still sends email successfully' do job_instance = subject.new expect(va_notify_service).to receive(:send_email).with(expected_email_args) job_instance.send(:send_email_notification, participant_id, template_id, first_name, mpi_profile.icn) end end end describe 'PII protection with AttrPackage' do let(:cache_key) { 'test_cache_key_123' } context 'when cache_key is provided' do before do allow(Sidekiq::AttrPackage).to receive(:find).with(cache_key).and_return( first_name:, icn: mpi_profile.icn ) end it 'retrieves PII from Redis' do expect(Sidekiq::AttrPackage).to receive(:find).with(cache_key) subject.new.perform(participant_id, template_id, cache_key) end it 'sends email with PII from cache' do expect(va_notify_service).to receive(:send_email).with(expected_email_args) subject.new.perform(participant_id, template_id, cache_key) end it 'cleans up cache_key after successful processing' do expect(Sidekiq::AttrPackage).to receive(:delete).with(cache_key) subject.new.perform(participant_id, template_id, cache_key) end it 'does not call BGS or MPI services' do expect_any_instance_of(described_class).not_to receive(:get_first_name_from_participant_id) expect_any_instance_of(described_class).not_to receive(:get_icn) subject.new.perform(participant_id, template_id, cache_key) end end context 'when cache_key retrieval fails' do before do allow(Sidekiq::AttrPackage).to receive(:find).with(cache_key).and_return(nil) end it 'falls back to fetching PII from services' do expect_any_instance_of(described_class).to receive(:get_first_name_from_participant_id).and_call_original expect_any_instance_of(described_class).to receive(:get_icn).and_call_original subject.new.perform(participant_id, template_id, cache_key) end it 'still sends email successfully' do expect(va_notify_service).to receive(:send_email).with(expected_email_args) subject.new.perform(participant_id, template_id, cache_key) end end end describe '#hostname_for_template' do let(:job_instance) { subject.new } context 'when hostname mapping exists' do before do allow(Settings).to receive(:hostname).and_return('test-hostname') stub_const('EventBusGateway::Constants::HOSTNAME_MAPPING', { 'test-hostname' => 'mapped-hostname' }) end it 'returns the mapped hostname' do result = job_instance.send(:hostname_for_template) expect(result).to eq('mapped-hostname') end end context 'when hostname mapping does not exist' do before do allow(Settings).to receive(:hostname).and_return('unmapped-hostname') stub_const('EventBusGateway::Constants::HOSTNAME_MAPPING', {}) end it 'returns the original hostname' do result = job_instance.send(:hostname_for_template) expect(result).to eq('unmapped-hostname') end end end describe 'when ICN is not present' do let(:mpi_profile) { build(:mpi_profile, icn: nil) } it 'returns early without sending email' do expect(va_notify_service).not_to receive(:send_email) expect(StatsD).not_to receive(:increment).with( "#{described_class::STATSD_METRIC_PREFIX}.success", tags: EventBusGateway::Constants::DD_TAGS ) result = subject.new.perform(participant_id, template_id) expect(result).to be_nil end it 'does not create notification record' do expect do subject.new.perform(participant_id, template_id) end.not_to change(EventBusGatewayNotification, :count) end it 'logs the skipped notification' do expect(Rails.logger).to receive(:error).with( 'LetterReadyEmailJob email skipped', { notification_type: 'email', reason: 'ICN not available', template_id: } ) subject.new.perform(participant_id, template_id) end it 'increments the skipped metric' do expect(StatsD).to receive(:increment).with( "#{described_class::STATSD_METRIC_PREFIX}.skipped", tags: EventBusGateway::Constants::DD_TAGS + ['notification_type:email', 'reason:icn_not_available'] ) subject.new.perform(participant_id, template_id) end end describe 'when first_name is not present' do let(:bgs_profile) do { first_nm: nil, last_nm: 'Smith', brthdy_dt: 30.years.ago, ssn_nbr: '123456789' } end it 'returns early without sending email' do expect(va_notify_service).not_to receive(:send_email) expect(StatsD).not_to receive(:increment).with( "#{described_class::STATSD_METRIC_PREFIX}.success", tags: EventBusGateway::Constants::DD_TAGS ) result = subject.new.perform(participant_id, template_id) expect(result).to be_nil end it 'does not create notification record' do expect do subject.new.perform(participant_id, template_id) end.not_to change(EventBusGatewayNotification, :count) end it 'logs the skipped notification' do expect(Rails.logger).to receive(:error).with( 'LetterReadyEmailJob email skipped', { notification_type: 'email', reason: 'First Name not available', template_id: } ) subject.new.perform(participant_id, template_id) end it 'increments the skipped metric' do expect(StatsD).to receive(:increment).with( "#{described_class::STATSD_METRIC_PREFIX}.skipped", tags: EventBusGateway::Constants::DD_TAGS + ['notification_type:email', 'reason:first_name_not_available'] ) subject.new.perform(participant_id, template_id) end end describe 'error handling' do context 'when VA Notify service initialization fails' do before do allow(VaNotify::Service).to receive(:new).and_raise(StandardError, 'Service initialization failed') end include_examples 'letter ready job va notify error handling', 'Email' it 'does not send email and does not change notification count' do expect(va_notify_service).not_to receive(:send_email) expect do subject.new.perform(participant_id, template_id) end.to raise_error(StandardError, 'Service initialization failed') .and not_change(EventBusGatewayNotification, :count) end end context 'when VA Notify send_email fails' do let(:notify_error) { StandardError.new('Notify service error') } before do allow(va_notify_service).to receive(:send_email).and_raise(notify_error) end it 'records notification send failure and re-raises error' do expect_any_instance_of(described_class) .to receive(:record_notification_send_failure) .with(notify_error, 'Email') expect { subject.new.perform(participant_id, template_id) } .to raise_error(notify_error) end end context 'when BGS service fails' do include_examples 'letter ready job bgs error handling', 'Email' it 'does not send email and does not change notification count' do expect(va_notify_service).not_to receive(:send_email) expect do subject.new.perform(participant_id, template_id) end.to raise_error(EventBusGateway::Errors::BgsPersonNotFoundError, 'Participant ID cannot be found in BGS') .and not_change(EventBusGatewayNotification, :count) end end context 'when MPI service fails' do include_examples 'letter ready job mpi error handling', 'Email' it 'does not send email and does not change notification count' do expect(va_notify_service).not_to receive(:send_email) expect do subject.new.perform(participant_id, template_id) end.to raise_error(EventBusGateway::Errors::MpiProfileNotFoundError, 'Failed to fetch MPI profile') .and not_change(EventBusGatewayNotification, :count) end end end describe 'sidekiq_retries_exhausted callback' do let(:msg) do { 'jid' => '12345', 'error_class' => 'StandardError', 'error_message' => 'Test error' } end let(:exception) { StandardError.new('Test error') } let(:frozen_time) { Time.zone.parse('2023-01-01 12:00:00 UTC') } before do allow(Time).to receive(:now).and_return(frozen_time) end it 'logs error details with timestamp' do expect(Rails.logger).to receive(:error).with( 'LetterReadyEmailJob retries exhausted', { job_id: '12345', timestamp: frozen_time, error_class: 'StandardError', error_message: 'Test error' } ) described_class.sidekiq_retries_exhausted_block.call(msg, exception) end it 'increments exhausted metric with error message tag' do expected_tags = EventBusGateway::Constants::DD_TAGS + ['function: Test error'] expect(StatsD).to receive(:increment).with( 'event_bus_gateway.letter_ready_email.exhausted', tags: expected_tags ) described_class.sidekiq_retries_exhausted_block.call(msg, exception) end end describe 'Retry count limit.' do it "Sets Sidekiq retry count to #{EventBusGateway::Constants::SIDEKIQ_RETRY_COUNT_FIRST_EMAIL}." do expect(described_class.sidekiq_options['retry']).to eq(EventBusGateway::Constants::SIDEKIQ_RETRY_COUNT_FIRST_EMAIL) end end describe 'Sidekiq retry interval configuration and jitter.' do # Ensure the retry interval is always greater than one hour between retries. # This helps avoid excessive retry frequency and gives external services time to recover. it 'Ensures each retry interval is greater than one hour.' do retry_in_proc = EventBusGateway::LetterReadyEmailJob.sidekiq_retry_in_block (1..EventBusGateway::Constants::SIDEKIQ_RETRY_COUNT_FIRST_EMAIL).each do |count| interval = retry_in_proc.call(count, StandardError.new) expect(interval).to be > 1.hour.to_i end end # Ensure jitter is present in the retry intervals. it 'Adds jitter to the retry interval.' do retry_in_proc = EventBusGateway::LetterReadyEmailJob.sidekiq_retry_in_block intervals = Array.new(10) { retry_in_proc.call(2, StandardError.new) } expect(intervals.uniq.size).to be > 1 end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/event_bus_gateway/shared_examples_letter_ready_job.rb
# frozen_string_literal: true RSpec.shared_examples 'letter ready job bgs error handling' do |job_type| let(:participant_id) { '1234' } let(:template_id) { '5678' } let(:mpi_profile) { build(:mpi_profile) } let(:mpi_profile_response) { create(:find_profile_response, profile: mpi_profile) } before do allow_any_instance_of(BGS::PersonWebService) .to receive(:find_person_by_ptcpnt_id).and_return(nil) allow_any_instance_of(MPI::Service).to receive(:find_profile_by_attributes) .and_return(mpi_profile_response) allow(Rails.logger).to receive(:error) allow(StatsD).to receive(:increment) end let(:error_message) { "LetterReady#{job_type}Job #{job_type.downcase} error" } let(:message_detail) { 'Participant ID cannot be found in BGS' } let(:tags) { EventBusGateway::Constants::DD_TAGS + ["function: #{error_message}"] } it 'logs the error, increments the statsd metric, and re-raises for retry' do expect(Rails.logger) .to receive(:error) .with(error_message, { message: message_detail }) expect(StatsD).to receive(:increment).with("#{described_class::STATSD_METRIC_PREFIX}.failure", tags:) expect do described_class.new.perform(participant_id, template_id) end.to raise_error(EventBusGateway::Errors::BgsPersonNotFoundError, message_detail) end end RSpec.shared_examples 'letter ready job mpi error handling' do |job_type| let(:participant_id) { '1234' } let(:template_id) { '5678' } let(:bgs_profile) do { first_nm: 'Joe', last_nm: 'Smith', brthdy_dt: 30.years.ago, ssn_nbr: '123456789' } end before do expect_any_instance_of(BGS::PersonWebService) .to receive(:find_person_by_ptcpnt_id).and_return(bgs_profile) allow_any_instance_of(MPI::Service).to receive(:find_profile_by_attributes) .and_return(nil) allow(Rails.logger).to receive(:error) allow(StatsD).to receive(:increment) end let(:error_message) { "LetterReady#{job_type}Job #{job_type.downcase} error" } let(:message_detail) { 'Failed to fetch MPI profile' } let(:tags) { EventBusGateway::Constants::DD_TAGS + ["function: #{error_message}"] } it 'logs the error, increments the statsd metric, and re-raises for retry' do expect(Rails.logger) .to receive(:error) .with(error_message, { message: message_detail }) expect(StatsD).to receive(:increment).with("#{described_class::STATSD_METRIC_PREFIX}.failure", tags:) expect do described_class.new.perform(participant_id, template_id) end.to raise_error(EventBusGateway::Errors::MpiProfileNotFoundError, message_detail) end end RSpec.shared_examples 'letter ready job sidekiq retries exhausted' do |job_type| context 'when sidekiq retries are exhausted' do before do allow(Rails.logger).to receive(:error) allow(StatsD).to receive(:increment) end let(:job_id) { 'test-job-id-123' } let(:error_class) { 'StandardError' } let(:error_message) { 'Some error message' } let(:msg) do { 'jid' => job_id, 'error_class' => error_class, 'error_message' => error_message } end let(:exception) { StandardError.new(error_message) } it 'logs the exhausted retries and increments the statsd metric' do # Get the retries exhausted callback from the job class retries_exhausted_callback = described_class.sidekiq_retries_exhausted_block expect(Rails.logger).to receive(:error) .with("LetterReady#{job_type}Job retries exhausted", { job_id:, timestamp: be_within(1.second).of(Time.now.utc), error_class:, error_message: }) expect(StatsD).to receive(:increment) .with("#{described_class::STATSD_METRIC_PREFIX}.exhausted", tags: EventBusGateway::Constants::DD_TAGS + ["function: #{error_message}"]) retries_exhausted_callback.call(msg, exception) end end end RSpec.shared_examples 'letter ready job va notify error handling' do |job_type| let(:participant_id) { '1234' } let(:template_id) { '5678' } let(:bgs_profile) do { first_nm: 'Joe', last_nm: 'Smith', brthdy_dt: 30.years.ago, ssn_nbr: '123456789' } end let(:mpi_profile) { build(:mpi_profile) } let(:mpi_profile_response) { create(:find_profile_response, profile: mpi_profile) } context 'when a VA Notify error occurs' do before do allow_any_instance_of(MPI::Service).to receive(:find_profile_by_attributes) .and_return(mpi_profile_response) allow_any_instance_of(BGS::PersonWebService) .to receive(:find_person_by_ptcpnt_id).and_return(bgs_profile) allow(Rails.logger).to receive(:error) allow(StatsD).to receive(:increment) end let(:error_message) { "LetterReady#{job_type}Job #{job_type.downcase} error" } let(:message_detail) { 'Service initialization failed' } let(:tags) { EventBusGateway::Constants::DD_TAGS + ["function: #{error_message}"] } it 'raises and logs the error, and increments the statsd metric' do expect(Rails.logger) .to receive(:error) .with(error_message, { message: message_detail }) expect(StatsD).to receive(:increment).with("#{described_class::STATSD_METRIC_PREFIX}.failure", tags:) expect do described_class.new.perform(participant_id, template_id) end.to raise_error(StandardError) end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/event_bus_gateway/va_notify_email_status_callback_spec.rb
# frozen_string_literal: true require 'rails_helper' describe EventBusGateway::VANotifyEmailStatusCallback do describe '#call' do context 'notification callback' do let(:notification_type) { :error } let(:callback_metadata) { { notification_type: } } context 'permanent-failure' do let!(:notification_record) do build(:notification, id: SecureRandom.uuid, status: 'permanent-failure', notification_id: SecureRandom.uuid, callback_metadata:) end it 'logs error and increments StatsD' do allow(StatsD).to receive(:increment) allow(Rails.logger).to receive(:error) described_class.call(notification_record) expect(Rails.logger).to have_received(:error).with( 'EventBusGateway::VANotifyEmailStatusCallback', { notification_id: notification_record.notification_id, source_location: notification_record.source_location, status: notification_record.status, status_reason: notification_record.status_reason, notification_type: notification_record.notification_type } ) expect(StatsD).to have_received(:increment).with('api.vanotify.notifications.permanent_failure') expect(StatsD).to have_received(:increment) .with('callbacks.event_bus_gateway.va_notify.notifications.permanent_failure') expect(StatsD).to have_received(:increment) .with("#{described_class::STATSD_METRIC_PREFIX}.va_notify.notifications.permanent-failure", tags: EventBusGateway::Constants::DD_TAGS) end end context 'delivered' do let!(:notification_record) do build(:notification, id: SecureRandom.uuid, status: 'delivered', notification_id: SecureRandom.uuid) end it 'logs success and increments StatsD' do allow(StatsD).to receive(:increment) described_class.call(notification_record) expect(StatsD).to have_received(:increment).with('api.vanotify.notifications.delivered') expect(StatsD).to have_received(:increment) .with('callbacks.event_bus_gateway.va_notify.notifications.delivered') expect(StatsD).to have_received(:increment) .with("#{described_class::STATSD_METRIC_PREFIX}.va_notify.notifications.delivered", tags: EventBusGateway::Constants::DD_TAGS) end end context 'temporary-failure' do let!(:notification_record) do build(:notification, id: SecureRandom.uuid, status: 'temporary-failure', notification_id: SecureRandom.uuid) end context 'when event_bus_gateway_retry_emails is disabled' do before do allow(Flipper).to receive(:enabled?).with(:event_bus_gateway_retry_emails).and_return(false) end it 'does not attempt to send the email again' do expect(EventBusGateway::LetterReadyRetryEmailJob).not_to receive(:perform_in) described_class.call(notification_record) end it 'logs error and increments StatsD' do allow(StatsD).to receive(:increment) allow(Rails.logger).to receive(:error) described_class.call(notification_record) expect(StatsD).to have_received(:increment).with('api.vanotify.notifications.temporary_failure') expect(StatsD).to have_received(:increment) .with('callbacks.event_bus_gateway.va_notify.notifications.temporary_failure') expect(StatsD).to have_received(:increment) .with("#{described_class::STATSD_METRIC_PREFIX}.va_notify.notifications.temporary-failure", tags: EventBusGateway::Constants::DD_TAGS) expect(Rails.logger).to have_received(:error).with( 'EventBusGateway::VANotifyEmailStatusCallback', { notification_id: notification_record.notification_id, source_location: notification_record.source_location, status: notification_record.status, status_reason: notification_record.status_reason, notification_type: notification_record.notification_type } ) end end context 'when event_bus_gateway_retry_emails is enabled' do let(:mpi_profile) { build(:mpi_profile) } let(:mpi_profile_response) { create(:find_profile_response, profile: mpi_profile) } let(:user_account) { create(:user_account, icn: mpi_profile_response.profile.icn) } let(:ebg_noti) do create(:event_bus_gateway_notification, user_account:, va_notify_id: notification_record.notification_id) end before do allow(Flipper).to receive(:enabled?).with(:event_bus_gateway_retry_emails).and_return(true) allow_any_instance_of(MPI::Service).to receive(:find_profile_by_identifier).and_return(mpi_profile_response) ebg_noti end it 'attempts to send the email again using LetterReadyRetryEmailJob' do expected_personalisation = { host: EventBusGateway::Constants::HOSTNAME_MAPPING[Settings.hostname] || Settings.hostname, first_name: mpi_profile.given_names.first } expect(EventBusGateway::LetterReadyRetryEmailJob).to receive(:perform_in).with( 1.hour, mpi_profile.participant_id, ebg_noti.template_id, expected_personalisation, ebg_noti.id ) described_class.call(notification_record) end it 'increments queued retry success metric' do allow(EventBusGateway::LetterReadyRetryEmailJob).to receive(:perform_in) allow(StatsD).to receive(:increment) described_class.call(notification_record) expect(StatsD).to have_received(:increment) .with("#{described_class::STATSD_METRIC_PREFIX}.queued_retry_success", tags: EventBusGateway::Constants::DD_TAGS) end it 'logs error and increments StatsD' do allow(EventBusGateway::LetterReadyRetryEmailJob).to receive(:perform_in) allow(StatsD).to receive(:increment) allow(Rails.logger).to receive(:error) described_class.call(notification_record) expect(StatsD).to have_received(:increment).with('api.vanotify.notifications.temporary_failure') expect(StatsD).to have_received(:increment) .with('callbacks.event_bus_gateway.va_notify.notifications.temporary_failure') expect(StatsD).to have_received(:increment) .with("#{described_class::STATSD_METRIC_PREFIX}.va_notify.notifications.temporary-failure", tags: EventBusGateway::Constants::DD_TAGS) expect(Rails.logger).to have_received(:error).with( 'EventBusGateway::VANotifyEmailStatusCallback', { notification_id: notification_record.notification_id, source_location: notification_record.source_location, status: notification_record.status, status_reason: notification_record.status_reason, notification_type: notification_record.notification_type } ) end context 'when max attempts exceeded' do before do ebg_noti.update!(attempts: EventBusGateway::Constants::MAX_EMAIL_ATTEMPTS + 1) end it 'does not queue retry job and logs exhausted retries' do allow(Rails.logger).to receive(:error) allow(StatsD).to receive(:increment) expect(EventBusGateway::LetterReadyRetryEmailJob).not_to receive(:perform_in) # Expect the standard error log for temporary-failure expect(Rails.logger).to receive(:error).with( 'EventBusGateway::VANotifyEmailStatusCallback', { notification_id: notification_record.notification_id, source_location: notification_record.source_location, status: notification_record.status, status_reason: notification_record.status_reason, notification_type: notification_record.notification_type } ) # Expect the exhausted retry log with simplified fields expect(Rails.logger).to receive(:error).with( 'EventBusGateway email retries exhausted', { ebg_notification_id: ebg_noti.id, max_attempts: EventBusGateway::Constants::MAX_EMAIL_ATTEMPTS } ) expect(StatsD).to receive(:increment) .with("#{described_class::STATSD_METRIC_PREFIX}.exhausted_retries", tags: EventBusGateway::Constants::DD_TAGS) described_class.call(notification_record) end end context 'when EventBusGatewayNotification is not found' do before do allow(EventBusGatewayNotification).to receive(:find_by).and_return(nil) allow(StatsD).to receive(:increment) end it 'raises EventBusGatewayNotificationNotFoundError and increments failure metric' do expect(StatsD).to receive(:increment) .with("#{described_class::STATSD_METRIC_PREFIX}.queued_retry_failure", tags: EventBusGateway::Constants::DD_TAGS + ['function: EventBusGateway::VANotifyEmailStatusCallback::EventBusGatewayNotificationNotFoundError']) expect { described_class.call(notification_record) } .to raise_error(EventBusGateway::VANotifyEmailStatusCallback::EventBusGatewayNotificationNotFoundError) end end context 'when MPI lookup fails' do before do mpi_error_response = instance_double(MPI::Responses::FindProfileResponse, ok?: false) allow_any_instance_of(MPI::Service).to receive(:find_profile_by_identifier).and_return(mpi_error_response) allow(StatsD).to receive(:increment) end it 'raises MPIError and increments failure metric' do expect(StatsD).to receive(:increment) .with("#{described_class::STATSD_METRIC_PREFIX}.queued_retry_failure", tags: EventBusGateway::Constants::DD_TAGS + ['function: EventBusGateway::VANotifyEmailStatusCallback::MPIError']) expect { described_class.call(notification_record) } .to raise_error(EventBusGateway::VANotifyEmailStatusCallback::MPIError) end end context 'when first name is missing' do before do profile_without_name = build(:mpi_profile, given_names: nil) mpi_response = create(:find_profile_response, profile: profile_without_name) allow_any_instance_of(MPI::Service).to receive(:find_profile_by_identifier).and_return(mpi_response) allow(StatsD).to receive(:increment) end it 'raises MPINameError and increments failure metric' do expect(StatsD).to receive(:increment) .with("#{described_class::STATSD_METRIC_PREFIX}.queued_retry_failure", tags: EventBusGateway::Constants::DD_TAGS + ['function: EventBusGateway::VANotifyEmailStatusCallback::MPINameError']) expect { described_class.call(notification_record) } .to raise_error(EventBusGateway::VANotifyEmailStatusCallback::MPINameError) end end end end context 'other' do let!(:notification_record) do build(:notification, id: SecureRandom.uuid, status: '', notification_id: SecureRandom.uuid) end it 'logs error and increments StatsD' do allow(StatsD).to receive(:increment) allow(Rails.logger).to receive(:error) described_class.call(notification_record) expect(StatsD).to have_received(:increment).with('api.vanotify.notifications.other') expect(StatsD).to have_received(:increment) .with('callbacks.event_bus_gateway.va_notify.notifications.other') expect(StatsD).to have_received(:increment) .with("#{described_class::STATSD_METRIC_PREFIX}.va_notify.notifications.", tags: EventBusGateway::Constants::DD_TAGS) expect(Rails.logger).to have_received(:error).with( 'EventBusGateway::VANotifyEmailStatusCallback', { notification_id: notification_record.notification_id, source_location: notification_record.source_location, status: notification_record.status, status_reason: notification_record.status_reason, notification_type: notification_record.notification_type } ) end end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/event_bus_gateway/letter_ready_job_concern_spec.rb
# frozen_string_literal: true require 'rails_helper' require_relative '../../../app/sidekiq/event_bus_gateway/letter_ready_job_concern' require_relative '../../../app/sidekiq/event_bus_gateway/constants' RSpec.describe EventBusGateway::LetterReadyJobConcern, type: :job do let(:test_class) do Class.new do include EventBusGateway::LetterReadyJobConcern const_set(:STATSD_METRIC_PREFIX, 'test_job') end end let(:test_instance) { test_class.new } let(:participant_id) { '1234567890' } let(:icn) { '123456789V012345' } let(:bgs_profile) do { first_nm: 'John', last_nm: 'Doe', brthdy_dt: 30.years.ago, ssn_nbr: '123456789' } end let(:mpi_profile) { build(:mpi_profile, icn:) } let(:mpi_profile_response) { create(:find_profile_response, profile: mpi_profile) } let!(:user_account) { create(:user_account, icn: mpi_profile.icn) } let(:bgs_service) { instance_double(BGS::PersonWebService) } let(:mpi_service) { instance_double(MPI::Service) } # Shared setup for most test scenarios before do allow(BGS::PersonWebService).to receive(:new).and_return(bgs_service) allow(MPI::Service).to receive(:new).and_return(mpi_service) allow(bgs_service).to receive(:find_person_by_ptcpnt_id).and_return(bgs_profile) allow(mpi_service).to receive(:find_profile_by_attributes).and_return(mpi_profile_response) allow(Rails.logger).to receive(:error) allow(StatsD).to receive(:increment) end describe '#get_bgs_person' do context 'when BGS service returns person data' do it 'returns the person data' do result = test_instance.send(:get_bgs_person, participant_id) expect(result).to eq(bgs_profile) end it 'calls BGS service with correct participant ID' do expect(bgs_service).to receive(:find_person_by_ptcpnt_id).with(participant_id) test_instance.send(:get_bgs_person, participant_id) end end context 'when BGS service does not return person data' do before do allow(bgs_service).to receive(:find_person_by_ptcpnt_id).and_return(nil) end it 'raises the correct error message' do expect { test_instance.send(:get_bgs_person, participant_id) } .to raise_error(EventBusGateway::Errors::BgsPersonNotFoundError, 'Participant ID cannot be found in BGS') end end end describe '#get_mpi_profile' do context 'when MPI service returns profile data' do it 'returns the profile' do result = test_instance.send(:get_mpi_profile, participant_id) expect(result).to eq(mpi_profile) end it 'calls MPI service with correct attributes' do expected_attributes = { first_name: 'John', last_name: 'Doe', birth_date: bgs_profile[:brthdy_dt].strftime('%Y%m%d'), ssn: '123456789' } expect(mpi_service).to receive(:find_profile_by_attributes).with(expected_attributes) test_instance.send(:get_mpi_profile, participant_id) end end context 'when MPI service returns nil response' do before do allow(mpi_service).to receive(:find_profile_by_attributes).and_return(nil) end it 'raises the correct error message' do expect { test_instance.send(:get_mpi_profile, participant_id) } .to raise_error(EventBusGateway::Errors::MpiProfileNotFoundError, 'Failed to fetch MPI profile') end end context 'when MPI service returns response with nil profile' do let(:mpi_profile_response) { create(:find_profile_response, profile: nil) } it 'raises the correct error message' do expect { test_instance.send(:get_mpi_profile, participant_id) } .to raise_error(EventBusGateway::Errors::MpiProfileNotFoundError, 'Failed to fetch MPI profile') end end end describe '#record_notification_send_failure' do let(:error) { StandardError.new('Notification send failed') } let(:notification_type) { 'Email' } it 'logs the error with correct format' do expect(Rails.logger).to receive(:error).with( "LetterReady#{notification_type}Job #{notification_type.downcase} error", { message: 'Notification send failed' } ) test_instance.send(:record_notification_send_failure, error, notification_type) end it 'increments the failure metric with correct tags' do expected_tags = EventBusGateway::Constants::DD_TAGS + ["function: LetterReady#{notification_type}Job #{notification_type.downcase} error"] expect(StatsD).to receive(:increment).with('test_job.failure', tags: expected_tags) test_instance.send(:record_notification_send_failure, error, notification_type) end context 'with different notification types' do %w[Email Push SMS].each do |type| it "handles #{type} notification type correctly" do expect(Rails.logger).to receive(:error).with( "LetterReady#{type}Job #{type.downcase} error", { message: 'Notification send failed' } ) expected_tags = EventBusGateway::Constants::DD_TAGS + ["function: LetterReady#{type}Job #{type.downcase} error"] expect(StatsD).to receive(:increment).with('test_job.failure', tags: expected_tags) test_instance.send(:record_notification_send_failure, error, type) end end end end describe '#user_account' do context 'when user account exists' do it 'returns the user account' do result = test_instance.send(:user_account, icn) expect(result).to eq(user_account) end it 'finds user account by ICN' do expect(UserAccount).to receive(:find_by).with(icn:).and_return(user_account) test_instance.send(:user_account, icn) end end context 'when user account does not exist' do it 'returns nil' do result = test_instance.send(:user_account, 'nonexistent_icn') expect(result).to be_nil end end end describe '#get_first_name_from_participant_id' do context 'when BGS person has a first name' do it 'returns the capitalized first name' do result = test_instance.send(:get_first_name_from_participant_id, participant_id) expect(result).to eq('John') end end context 'when BGS person has uppercase first name' do let(:bgs_profile) do { first_nm: 'JANE', last_nm: 'DOE', brthdy_dt: 30.years.ago, ssn_nbr: '123456789' } end it 'returns the properly capitalized first name' do result = test_instance.send(:get_first_name_from_participant_id, participant_id) expect(result).to eq('Jane') end end shared_examples 'returns appropriate value for missing name' do |expected_value| it "returns #{expected_value.inspect}" do result = test_instance.send(:get_first_name_from_participant_id, participant_id) expect(result).to eq(expected_value) end end context 'when BGS person has nil first name' do let(:bgs_profile) do { first_nm: nil, last_nm: 'smith', brthdy_dt: 30.years.ago, ssn_nbr: '123456789' } end include_examples 'returns appropriate value for missing name', nil end context 'when BGS person has empty first name' do let(:bgs_profile) do { first_nm: '', last_nm: 'smith', brthdy_dt: 30.years.ago, ssn_nbr: '123456789' } end include_examples 'returns appropriate value for missing name', '' end context 'when BGS service returns nil' do before do allow(bgs_service).to receive(:find_person_by_ptcpnt_id).and_return(nil) end it 'raises error from get_bgs_person' do expect do test_instance.send(:get_first_name_from_participant_id, participant_id) end.to raise_error(EventBusGateway::Errors::BgsPersonNotFoundError, 'Participant ID cannot be found in BGS') end end context 'when BGS service raises an error' do before do allow(bgs_service).to receive(:find_person_by_ptcpnt_id) .and_raise(StandardError, 'BGS service unavailable') end it 'propagates the BGS error' do expect do test_instance.send(:get_first_name_from_participant_id, participant_id) end.to raise_error(StandardError, 'BGS service unavailable') end end end describe '#get_icn' do context 'when MPI profile exists with ICN' do it 'returns the ICN' do result = test_instance.send(:get_icn, participant_id) expect(result).to eq(icn) end end context 'when MPI profile has nil ICN' do let(:mpi_profile) { build(:mpi_profile, icn: nil) } it 'returns nil' do result = test_instance.send(:get_icn, participant_id) expect(result).to be_nil end end shared_examples 'raises MPI profile error' do |error_message| it 'raises error from get_mpi_profile' do expect do test_instance.send(:get_icn, participant_id) end.to raise_error(EventBusGateway::Errors::MpiProfileNotFoundError, error_message) end end context 'when MPI service returns nil profile' do before do allow(mpi_service).to receive(:find_profile_by_attributes).and_return(nil) end include_examples 'raises MPI profile error', 'Failed to fetch MPI profile' end context 'when MPI service returns response with nil profile' do let(:mpi_profile_response) { create(:find_profile_response, profile: nil) } include_examples 'raises MPI profile error', 'Failed to fetch MPI profile' end context 'when BGS service fails before MPI lookup' do before do allow(bgs_service).to receive(:find_person_by_ptcpnt_id).and_return(nil) end it 'raises BGS error before attempting MPI lookup' do expect do test_instance.send(:get_icn, participant_id) end.to raise_error(EventBusGateway::Errors::BgsPersonNotFoundError, 'Participant ID cannot be found in BGS') end end context 'when MPI service raises an error' do before do allow(mpi_service).to receive(:find_profile_by_attributes) .and_raise(StandardError, 'MPI service timeout') end it 'propagates the MPI error' do expect do test_instance.send(:get_icn, participant_id) end.to raise_error(StandardError, 'MPI service timeout') end end end describe 'method dependencies and caching' do let(:fresh_test_instance) { test_class.new } before do # Use real service initialization for caching tests allow(BGS::PersonWebService).to receive(:new).and_call_original allow(MPI::Service).to receive(:new).and_call_original end it 'caches BGS person data to avoid duplicate calls' do expect_any_instance_of(BGS::PersonWebService) .to receive(:find_person_by_ptcpnt_id) .with(participant_id).once.and_return(bgs_profile) expect_any_instance_of(MPI::Service) .to receive(:find_profile_by_attributes) .and_return(mpi_profile_response) # Call both methods that depend on get_bgs_person fresh_test_instance.send(:get_first_name_from_participant_id, participant_id) fresh_test_instance.send(:get_icn, participant_id) end it 'caches MPI profile data to avoid duplicate calls' do expect_any_instance_of(BGS::PersonWebService) .to receive(:find_person_by_ptcpnt_id) .and_return(bgs_profile) expect_any_instance_of(MPI::Service) .to receive(:find_profile_by_attributes) .once.and_return(mpi_profile_response) # Call get_icn multiple times fresh_test_instance.send(:get_icn, participant_id) fresh_test_instance.send(:get_icn, participant_id) end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/event_bus_gateway/letter_ready_push_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'va_notify/service' require 'sidekiq/attr_package' require_relative '../../../app/sidekiq/event_bus_gateway/constants' require_relative 'shared_examples_letter_ready_job' RSpec.describe EventBusGateway::LetterReadyPushJob, type: :job do subject { described_class } # Shared setup for most test scenarios before do allow(VaNotify::Service).to receive(:new) .with(EventBusGateway::Constants::NOTIFY_SETTINGS.api_key) .and_return(va_notify_service) allow_any_instance_of(MPI::Service).to receive(:find_profile_by_attributes) .and_return(mpi_profile_response) allow_any_instance_of(BGS::PersonWebService) .to receive(:find_person_by_ptcpnt_id) .and_return(bgs_profile) allow(StatsD).to receive(:increment) allow(Rails.logger).to receive(:error) allow(Sidekiq::AttrPackage).to receive(:find).and_return(nil) allow(Sidekiq::AttrPackage).to receive(:delete) end let(:participant_id) { '1234' } let(:template_id) { '5678' } let(:icn) { '1234567890V123456' } let(:notification_id) { SecureRandom.uuid } let(:bgs_profile) do { first_nm: 'Joe', last_nm: 'Smith', brthdy_dt: 30.years.ago, ssn_nbr: '123456789' } end let(:mpi_profile) { build(:mpi_profile) } let(:mpi_profile_response) { create(:find_profile_response, profile: mpi_profile) } let!(:user_account) { create(:user_account, icn: mpi_profile_response.profile.icn) } let(:va_notify_service) do instance_double(VaNotify::Service).tap do |service| allow(service).to receive(:send_push).and_return(double(id: notification_id)) end end let(:expected_push_args) do { mobile_app: 'VA_FLAGSHIP_APP', recipient_identifier: { id_value: mpi_profile_response.profile.icn, id_type: 'ICN' }, template_id:, personalisation: {} } end describe 'successful push notification' do it 'sends push notification with correct arguments' do expect(va_notify_service).to receive(:send_push).with(expected_push_args) subject.new.perform(participant_id, template_id) end it 'creates EventBusGatewayPushNotification record' do expect do subject.new.perform(participant_id, template_id) end.to change(EventBusGatewayPushNotification, :count).by(1) notification = EventBusGatewayPushNotification.last expect(notification.user_account).to eq(user_account) expect(notification.template_id).to eq(template_id) end it 'increments success metric' do expect(StatsD).to receive(:increment).with( "#{described_class::STATSD_METRIC_PREFIX}.success", tags: EventBusGateway::Constants::DD_TAGS ) subject.new.perform(participant_id, template_id) end it 'configures VaNotify::Service with correct API key' do expect(VaNotify::Service).to receive(:new) .with(EventBusGateway::Constants::NOTIFY_SETTINGS.api_key) .and_return(va_notify_service) subject.new.perform(participant_id, template_id) end end describe '#send_push_notification' do it 'sends push and creates notification record' do job_instance = subject.new expect(va_notify_service).to receive(:send_push).with(expected_push_args) expect do job_instance.send(:send_push_notification, mpi_profile.icn, template_id) end.to change(EventBusGatewayPushNotification, :count).by(1) end context 'when user_account is nil' do before do allow_any_instance_of(described_class).to receive(:user_account).and_return(nil) end it 'successfully creates notification record without user_account' do job_instance = subject.new expect do job_instance.send(:send_push_notification, mpi_profile.icn, template_id) end.to change(EventBusGatewayPushNotification, :count).by(1) notification = EventBusGatewayPushNotification.last expect(notification.user_account).to be_nil expect(notification.template_id).to eq(template_id) end it 'still sends push notification successfully' do job_instance = subject.new expect(va_notify_service).to receive(:send_push).with(expected_push_args) job_instance.send(:send_push_notification, mpi_profile.icn, template_id) end end end describe 'PII protection with AttrPackage' do let(:cache_key) { 'test_cache_key_456' } context 'when cache_key is provided' do before do allow(Sidekiq::AttrPackage).to receive(:find).with(cache_key).and_return( icn: mpi_profile.icn ) end it 'retrieves PII from Redis' do expect(Sidekiq::AttrPackage).to receive(:find).with(cache_key) subject.new.perform(participant_id, template_id, cache_key) end it 'sends push with PII from cache' do expect(va_notify_service).to receive(:send_push).with(expected_push_args) subject.new.perform(participant_id, template_id, cache_key) end it 'cleans up cache_key after successful processing' do expect(Sidekiq::AttrPackage).to receive(:delete).with(cache_key) subject.new.perform(participant_id, template_id, cache_key) end it 'does not call MPI service' do expect_any_instance_of(described_class).not_to receive(:get_icn) subject.new.perform(participant_id, template_id, cache_key) end end context 'when cache_key retrieval fails' do before do allow(Sidekiq::AttrPackage).to receive(:find).with(cache_key).and_return(nil) end it 'falls back to fetching ICN from MPI' do expect_any_instance_of(described_class).to receive(:get_icn).and_call_original subject.new.perform(participant_id, template_id, cache_key) end it 'still sends push successfully' do expect(va_notify_service).to receive(:send_push).with(expected_push_args) subject.new.perform(participant_id, template_id, cache_key) end end end describe 'ICN validation' do let(:error_message) { 'LetterReadyPushJob push error' } let(:message_detail) { 'Failed to fetch ICN' } let(:tags) { EventBusGateway::Constants::DD_TAGS + ["function: #{error_message}"] } shared_examples 'raises ICN error' do it 'raises error immediately and does not send notification' do expect(va_notify_service).not_to receive(:send_push) expect(EventBusGatewayPushNotification).not_to receive(:create!) expect(Rails.logger).to receive(:error) .with(error_message, { message: message_detail }) expect(StatsD).to receive(:increment) .with("#{described_class::STATSD_METRIC_PREFIX}.failure", tags:) expect do subject.new.perform(participant_id, template_id) end.to raise_error(EventBusGateway::Errors::IcnNotFoundError, message_detail) end end context 'when ICN is nil' do let(:mpi_profile) { build(:mpi_profile, icn: nil) } include_examples 'raises ICN error' end context 'when ICN is blank' do let(:mpi_profile) { build(:mpi_profile, icn: '') } include_examples 'raises ICN error' end end describe 'error handling' do context 'when VA Notify service initialization fails' do before do allow(VaNotify::Service).to receive(:new) .with(EventBusGateway::Constants::NOTIFY_SETTINGS.api_key) .and_raise(StandardError, 'Service initialization failed') end include_examples 'letter ready job va notify error handling', 'Push' it 'does not send push notification' do expect(va_notify_service).not_to receive(:send_push) expect { subject.new.perform(participant_id, template_id) } .to raise_error(StandardError, 'Service initialization failed') end end context 'when VA Notify send_push fails' do let(:notify_error) { StandardError.new('Notify service error') } before do allow(va_notify_service).to receive(:send_push).and_raise(notify_error) end it 'records notification send failure and re-raises error' do expect_any_instance_of(described_class) .to receive(:record_notification_send_failure) .with(notify_error, 'Push') expect { subject.new.perform(participant_id, template_id) } .to raise_error(notify_error) end end context 'when BGS service fails' do include_examples 'letter ready job bgs error handling', 'Push' it 'does not send notification and does not change notification count' do expect(va_notify_service).not_to receive(:send_push) expect do subject.new.perform(participant_id, template_id) end.to raise_error(EventBusGateway::Errors::BgsPersonNotFoundError, 'Participant ID cannot be found in BGS') .and not_change(EventBusGatewayNotification, :count) end end context 'when MPI service fails' do include_examples 'letter ready job mpi error handling', 'Push' it 'does not send notification and does not change notification count' do expect(va_notify_service).not_to receive(:send_push) expect do subject.new.perform(participant_id, template_id) end.to raise_error(EventBusGateway::Errors::MpiProfileNotFoundError, 'Failed to fetch MPI profile') .and not_change(EventBusGatewayNotification, :count) end end context 'when MPI profile is nil' do before do allow_any_instance_of(MPI::Service).to receive(:find_profile_by_attributes) .and_return(nil) end it 'raises error for missing MPI profile' do expect(va_notify_service).not_to receive(:send_push) expect { subject.new.perform(participant_id, template_id) } .to raise_error(EventBusGateway::Errors::MpiProfileNotFoundError, 'Failed to fetch MPI profile') end end context 'when notification creation fails' do let(:invalid_notification) do instance_double(EventBusGatewayPushNotification, persisted?: false, errors: double(full_messages: ['Template must exist'])) end before do allow(EventBusGatewayPushNotification).to receive(:create).and_return(invalid_notification) allow(Rails.logger).to receive(:warn) end it 'logs a warning with error details' do expect(Rails.logger).to receive(:warn).with( 'LetterReadyPushJob notification record failed to save', { errors: ['Template must exist'], template_id: } ) subject.new.perform(participant_id, template_id) end it 'still sends the push notification successfully' do expect(va_notify_service).to receive(:send_push) subject.new.perform(participant_id, template_id) end it 'does not raise an error' do expect { subject.new.perform(participant_id, template_id) }.not_to raise_error end end end describe 'sidekiq_retries_exhausted callback' do let(:msg) do { 'jid' => '12345', 'error_class' => 'StandardError', 'error_message' => 'Test error' } end let(:exception) { StandardError.new('Test error') } let(:frozen_time) { Time.zone.parse('2023-01-01 12:00:00 UTC') } before do allow(Time).to receive(:now).and_return(frozen_time) end it 'logs error details with timestamp' do expect(Rails.logger).to receive(:error).with( 'LetterReadyPushJob retries exhausted', { job_id: '12345', timestamp: frozen_time, error_class: 'StandardError', error_message: 'Test error' } ) described_class.sidekiq_retries_exhausted_block.call(msg, exception) end it 'configures sidekiq retry count' do expect(described_class.get_sidekiq_options['retry']).to eq(EventBusGateway::Constants::SIDEKIQ_RETRY_COUNT_FIRST_PUSH) end it 'increments exhausted metric with error message tag' do expected_tags = EventBusGateway::Constants::DD_TAGS + ['function: Test error'] expect(StatsD).to receive(:increment).with( 'event_bus_gateway.letter_ready_push.exhausted', tags: expected_tags ) described_class.sidekiq_retries_exhausted_block.call(msg, exception) end end include_examples 'letter ready job sidekiq retries exhausted', 'Push' end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/schema_contract/delete_validation_records_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require_relative Rails.root.join('app', 'models', 'schema_contract', 'validation_initiator') RSpec.describe SchemaContract::DeleteValidationRecordsJob do let(:job) { described_class.new } let(:response) do OpenStruct.new({ success?: true, status: 200, body: { key: 'value' } }) end context 'when records exist that are over a month old' do let!(:old_contract) do create(:schema_contract_validation, contract_name: 'test_index', user_uuid: '1234', response:, status: 'initialized', updated_at: 1.month.ago - 2.days) end let!(:new_contract) do create(:schema_contract_validation, contract_name: 'test_index', user_uuid: '1234', response:, status: 'initialized') end it 'removes old records' do job = SchemaContract::DeleteValidationRecordsJob.new job.perform expect { old_contract.reload }.to raise_error(ActiveRecord::RecordNotFound) expect { new_contract.reload }.not_to raise_error end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/form1010cg/delete_old_uploads_job_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Form1010cg::DeleteOldUploadsJob do it 'inherits DeleteAttachmentJob' do expect(described_class.ancestors).to include(DeleteAttachmentJob) end describe '::ATTACHMENT_CLASSES' do it 'is references the attachment model\'s name' do expect(described_class::ATTACHMENT_CLASSES).to eq(['Form1010cg::Attachment']) end end describe '::FORM_ID' do it 'is references the form\'s id' do expect(described_class::FORM_ID).to eq('10-10CG') end end describe '::EXPIRATION_TIME' do it 'is set to 30 days' do expect(described_class::EXPIRATION_TIME).to eq(30.days) end end describe '#uuids_to_keep' do it 'returns an empty array' do expect(subject.uuids_to_keep).to eq([]) end end describe '#perform' do it 'deletes attachments created more than 30 days ago' do Timecop.freeze(DateTime.new(2025, 6, 25)) do now = DateTime.now old_attachment = create(:form1010cg_attachment, :with_attachment, created_at: now - 31.days) older_attachment = create(:form1010cg_attachment, :with_attachment, created_at: now - 32.days) newer_attachment = create(:form1010cg_attachment, :with_attachment, created_at: now - 29.days) allow_any_instance_of(Form1010cg::Attachment).to receive(:get_file).and_return(double(delete: true)) subject.perform expect { old_attachment.reload }.to raise_error(ActiveRecord::RecordNotFound) expect { older_attachment.reload }.to raise_error(ActiveRecord::RecordNotFound) expect(Form1010cg::Attachment.all).to eq([newer_attachment]) expect(Form1010cg::Attachment.count).to eq(1) end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/form1010cg/submission_job_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Form1010cg::SubmissionJob do let(:form) { VetsJsonSchema::EXAMPLES['10-10CG'].clone.to_json } let(:claim) { create(:caregivers_assistance_claim, form:) } let(:statsd_key_prefix) { described_class::STATSD_KEY_PREFIX } let(:zsf_tags) { described_class::DD_ZSF_TAGS } let(:email_address) { 'jane.doe@example.com' } let(:form_with_email) do data = JSON.parse(VetsJsonSchema::EXAMPLES['10-10CG'].clone.to_json) data['veteran']['email'] = email_address data.to_json end before do allow(VANotify::EmailJob).to receive(:perform_async) end it 'has a retry count of 16' do expect(described_class.get_sidekiq_options['retry']).to eq(16) end it 'defines #notify' do expect(described_class.new.respond_to?(:notify)).to be(true) end it 'requires a parameter for notify' do expect { described_class.new.notify } .to raise_error(ArgumentError, 'wrong number of arguments (given 0, expected 1)') end it 'defines retry_limits_for_notification' do expect(described_class.new.respond_to?(:retry_limits_for_notification)).to be(true) end it 'returns an array of integers from retry_limits_for_notification' do expect(described_class.new.retry_limits_for_notification).to eq([1, 10]) end describe '#notify' do subject(:notify) { described_class.new.notify(params) } let(:tags) { ["params:#{params}", "claim_id:#{claim.id}"] } before { allow(StatsD).to receive(:increment) } context 'retry_count is 0' do let(:params) { { 'retry_count' => 0, 'args' => [claim.id] } } it 'increments applications_retried statsd' do expect(StatsD).to receive(:increment).with('api.form1010cg.async.applications_retried') notify end end context 'retry_count is not 0 or 9' do let(:params) { { 'retry_count' => 5, 'args' => [claim.id] } } it 'does not increment applications_retried statsd' do expect(StatsD).not_to receive(:increment).with('api.form1010cg.async.applications_retried') notify end it 'does not increment failed_ten_retries statsd' do expect(StatsD).not_to receive(:increment).with('api.form1010cg.async.failed_ten_retries', tags:) notify end end context 'retry_count is 9' do let(:params) { { 'retry_count' => 9, 'args' => [claim.id] } } it 'increments failed_ten_retries statsd' do expect(StatsD).to receive(:increment).with('api.form1010cg.async.failed_ten_retries', tags:) notify end end end describe 'when retries are exhausted' do let(:msg) do { 'args' => [claim.id] } end context 'when the parsed form does not have an email' do it 'only increments StatsD' do described_class.within_sidekiq_retries_exhausted_block(msg) do allow(StatsD).to receive(:increment) expect(StatsD).to receive(:increment).with( "#{statsd_key_prefix}failed_no_retries_left", tags: ["claim_id:#{claim.id}"] ) expect(StatsD).to receive(:increment).with('silent_failure', tags: zsf_tags) expect(VANotify::EmailJob).not_to receive(:perform_async) end end end context 'when the parsed form has an email' do let(:form) { form_with_email } let(:api_key) { Settings.vanotify.services.health_apps_1010.api_key } let(:template_id) { Settings.vanotify.services.health_apps_1010.template_id.form1010_cg_failure_email } let(:template_params) do [ email_address, template_id, { 'salutation' => "Dear #{claim.parsed_form.dig('veteran', 'fullName', 'first')}," }, api_key, { callback_metadata: { notification_type: 'error', form_number: claim.form_id, statsd_tags: zsf_tags } } ] end it 'increments StatsD and sends the failure email' do described_class.within_sidekiq_retries_exhausted_block(msg) do allow(StatsD).to receive(:increment) expect(StatsD).to receive(:increment).with( "#{statsd_key_prefix}failed_no_retries_left", tags: ["claim_id:#{claim.id}"] ) expect(VANotify::EmailJob).to receive(:perform_async).with(*template_params) expect(StatsD).to receive(:increment).with( "#{statsd_key_prefix}submission_failure_email_sent", tags: ["claim_id:#{claim.id}"] ) end end end end describe '#perform' do let(:job) { described_class.new } context 'when there is a standarderror' do it 'increments statsd except applications_retried' do allow_any_instance_of(Form1010cg::Service).to receive( :process_claim_v2! ).and_raise(StandardError) expect(Rails.logger).to receive(:error).with( '[10-10CG] - Error processing Caregiver claim submission in job', { exception: StandardError, claim_id: claim.id } ).twice 2.times do expect do job.perform(claim.id) end.to raise_error(StandardError) end end end context 'when the service throws a record parse error' do before do allow(Process).to receive(:clock_gettime).and_call_original allow(Process).to receive(:clock_gettime).with(Process::CLOCK_MONOTONIC, :float_millisecond) allow(Process).to receive(:clock_gettime).with(Process::CLOCK_THREAD_CPUTIME_ID, :float_millisecond) end context 'form has email' do let(:form) { form_with_email } it 'rescues the error, increments statsd, and attempts to send failure email' do start_time = Time.current expected_arguments = { context: :process_job, event: :failure, start_time: } expect_any_instance_of(Form1010cg::Auditor).to receive(:log_caregiver_request_duration) .with(**expected_arguments) allow(Process).to receive(:clock_gettime).with(Process::CLOCK_MONOTONIC) { start_time } expect_any_instance_of(Form1010cg::Service).to receive( :process_claim_v2! ).and_raise(CARMA::Client::MuleSoftClient::RecordParseError.new) expect(SavedClaim.exists?(id: claim.id)).to be(true) expect(VANotify::EmailJob).to receive(:perform_async) expect(StatsD).to receive(:increment).with( "#{statsd_key_prefix}submission_failure_email_sent", tags: ["claim_id:#{claim.id}"] ) expect(StatsD).to receive(:increment).with( "#{statsd_key_prefix}record_parse_error", tags: ["claim_id:#{claim.id}"] ) job.perform(claim.id) end end context 'form does not have email' do it 'rescues the error, increments statsd, and attempts to send failure email' do start_time = Time.current expected_arguments = { context: :process_job, event: :failure, start_time: } expect_any_instance_of(Form1010cg::Auditor).to receive(:log_caregiver_request_duration) .with(**expected_arguments) allow(Process).to receive(:clock_gettime).and_call_original allow(Process).to receive(:clock_gettime).with(Process::CLOCK_MONOTONIC) { start_time } expect_any_instance_of(Form1010cg::Service).to receive( :process_claim_v2! ).and_raise(CARMA::Client::MuleSoftClient::RecordParseError.new) expect do job.perform(claim.id) end.to trigger_statsd_increment('api.form1010cg.async.record_parse_error', tags: ["claim_id:#{claim.id}"]) .and trigger_statsd_increment('silent_failure', tags: zsf_tags) expect(SavedClaim.exists?(id: claim.id)).to be(true) expect(VANotify::EmailJob).not_to receive(:perform_async) end end end context 'when claim can not be destroyed' do it 'logs the exception using the Rails logger' do expect_any_instance_of(Form1010cg::Service).to receive(:process_claim_v2!) error = StandardError.new expect_any_instance_of(SavedClaim::CaregiversAssistanceClaim).to receive(:destroy!).and_raise(error) expect(Rails.logger).to receive(:error).with( '[10-10CG] - Error destroying Caregiver claim after processing submission in job', { exception: error, claim_id: claim.id } ) job.perform(claim.id) end end it 'calls process_claim_v2!' do start_time = Time.current expected_arguments = { context: :process_job, event: :success, start_time: } expect_any_instance_of(Form1010cg::Auditor).to receive(:log_caregiver_request_duration).with(**expected_arguments) allow(Process).to receive(:clock_gettime).and_call_original allow(Process).to receive(:clock_gettime).with(Process::CLOCK_MONOTONIC) { start_time } allow(Process).to receive(:clock_gettime).with(Process::CLOCK_MONOTONIC, :float_millisecond) allow(Process).to receive(:clock_gettime).with(Process::CLOCK_THREAD_CPUTIME_ID, :float_millisecond) expect_any_instance_of(Form1010cg::Service).to receive(:process_claim_v2!) job.perform(claim.id) expect(SavedClaim::CaregiversAssistanceClaim.exists?(id: claim.id)).to be(false) end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/terms_of_use/sign_up_service_updater_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'sidekiq/attr_package' RSpec.describe TermsOfUse::SignUpServiceUpdaterJob, type: :job do before do Timecop.freeze(Time.zone.now) allow(MAP::SignUp::Service).to receive(:new).and_return(service_instance) end after do Timecop.return end describe '#perform' do subject(:job) { described_class.new } let(:user_account) { create(:user_account) } let(:user_account_uuid) { user_account.id } let(:icn) { user_account.icn } let(:terms_of_use_agreement) { create(:terms_of_use_agreement, user_account:, response:) } let(:response) { 'accepted' } let(:response_time) { terms_of_use_agreement.created_at.iso8601 } let(:given_names) { %w[given_name] } let(:family_name) { 'family_name' } let(:common_name) { "#{given_names.first} #{family_name}" } let(:sec_id) { 'some-sec-id' } let(:sec_ids) { [sec_id] } let(:service_instance) { instance_double(MAP::SignUp::Service) } let(:version) { terms_of_use_agreement&.agreement_version } let(:expires_in) { 72.hours } let(:find_profile_response) { create(:find_profile_response, profile: mpi_profile) } let(:mpi_profile) { build(:mpi_profile, icn:, sec_id:, sec_ids:, given_names:, family_name:) } let(:mpi_service) { instance_double(MPI::Service, find_profile_by_identifier: find_profile_response) } before do allow(MPI::Service).to receive(:new).and_return(mpi_service) end it 'retries for 47 hours after failure' do expect(described_class.get_sidekiq_options['retry_for']).to eq(48.hours) end context 'when retries have been exhausted' do let(:job) { { args: [user_account_uuid, version] }.as_json } let(:exception_message) { 'some-error' } let(:exception) { StandardError.new(exception_message) } let(:expected_log_message) { '[TermsOfUse][SignUpServiceUpdaterJob] retries exhausted' } before do allow(Rails.logger).to receive(:warn) Timecop.travel(47.hours.from_now) end context 'when the attr_package is found' do let(:expected_log_payload) do { icn:, response:, response_time:, version:, exception_message: } end it 'logs a warning message with the expected payload' do described_class.sidekiq_retries_exhausted_block.call(job, exception) expect(Rails.logger).to have_received(:warn).with(expected_log_message, expected_log_payload) end end context 'when the agreement is not found' do let(:terms_of_use_agreement) { nil } let(:expected_log_payload) do { icn:, response: nil, response_time: nil, version: nil, exception_message: } end it 'logs a warning message with the expected payload' do described_class.sidekiq_retries_exhausted_block.call(job, exception) expect(Rails.logger).to have_received(:warn).with(expected_log_message, expected_log_payload) end end end context 'when sec_id is present' do let(:status) { { opt_out: false, agreement_signed: false } } before do allow(service_instance).to receive(:agreements_accept) allow(service_instance).to receive(:status).and_return(status) allow(Rails.logger).to receive(:info) end shared_examples 'logs an unchanged agreement' do let(:expected_log) do '[TermsOfUse][SignUpServiceUpdaterJob] Not updating Sign Up Service due to unchanged agreement' end before do allow(Rails.logger).to receive(:info) end it 'logs that the agreement is not changed' do job.perform(user_account_uuid, version) expect(Rails.logger).to have_received(:info).with(expected_log, icn:) end end shared_examples 'logs an icn mismatch warning' do let(:expected_log) do '[TermsOfUse][SignUpServiceUpdaterJob] Detected changed ICN for user' end let(:mpi_profile) { build(:mpi_profile, icn: mpi_icn, sec_id:, given_names:, family_name:) } let(:mpi_icn) { 'some-mpi-icn' } before do allow(Rails.logger).to receive(:info) end it 'logs a detected changed ICN message' do job.perform(user_account_uuid, version) expect(MAP::SignUp::Service).to have_received(:new) expect(Rails.logger).to have_received(:info).with(expected_log, { icn:, mpi_icn: }) end end context 'when multiple sec_id values are detected' do let(:sec_ids) { [sec_id, 'other-sec-id'] } let(:expected_log) { '[TermsOfUse][SignUpServiceUpdaterJob] Multiple sec_id values detected' } it 'logs a warning message' do job.perform(user_account_uuid, version) expect(Rails.logger).to have_received(:info).with(expected_log, icn:) end end context 'and terms of use agreement is accepted' do let(:response) { 'accepted' } before do allow(service_instance).to receive(:status).and_return(status) allow(service_instance).to receive(:agreements_accept) end context 'when sign up service status agreement response is true' do let(:status) { { opt_out: false, agreement_signed: true } } it_behaves_like 'logs an unchanged agreement' it 'does not update terms of use agreement in sign up service' do job.perform(user_account_uuid, version) expect(service_instance).not_to have_received(:agreements_accept) end end context 'when sign up service status agreement response is false' do let(:status) { { opt_out: false, agreement_signed: false } } it 'updates the terms of use agreement in sign up service' do job.perform(user_account_uuid, version) expect(service_instance).to have_received(:agreements_accept).with(icn: user_account.icn, signature_name: common_name, version:) end context 'and user account icn does not equal the mpi profile icn' do it_behaves_like 'logs an icn mismatch warning' end end end context 'and terms of use agreement is declined' do let(:response) { 'declined' } before do allow(service_instance).to receive(:status).and_return(status) allow(service_instance).to receive(:agreements_decline) end context 'when sign up service status opt out response is true' do let(:status) { { opt_out: true, agreement_signed: false } } it_behaves_like 'logs an unchanged agreement' it 'does not update terms of use agreement in sign up service' do job.perform(user_account_uuid, version) expect(service_instance).not_to have_received(:agreements_decline) end end context 'when sign up service status opt out response is false' do let(:status) { { opt_out: false, agreement_signed: false } } it 'updates the terms of use agreement in sign up service' do job.perform(user_account_uuid, version) expect(service_instance).to have_received(:agreements_decline).with(icn: user_account.icn) end context 'and user account icn does not equal the mpi profile icn' do it_behaves_like 'logs an icn mismatch warning' end end end end context 'when sec_id is not present' do let(:sec_id) { nil } let(:expected_log) do '[TermsOfUse][SignUpServiceUpdaterJob] Sign Up Service not updated due to user missing sec_id' end before do allow(Rails.logger).to receive(:info) end it 'does not update the terms of use agreement in sign up service and logs expected message' do job.perform(user_account_uuid, version) expect(MAP::SignUp::Service).not_to have_received(:new) expect(Rails.logger).to have_received(:info).with(expected_log, icn:) end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/education_form/create_daily_spool_files_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EducationForm::CreateDailySpoolFiles, form: :education_benefits, type: :model do subject { described_class.new } let!(:application_1606) do create(:va1990).education_benefits_claim end let(:line_break) { EducationForm::CreateDailySpoolFiles::WINDOWS_NOTEPAD_LINEBREAK } before do allow(Flipper).to receive(:enabled?).and_call_original end after(:all) do FileUtils.rm_rf('tmp/spool_files') end context 'scheduling' do before do allow(Rails.env).to receive('development?').and_return(true) end context 'job only runs on business days', run_at: '2016-12-31 00:00:00 EDT' do let(:scheduler) { Rufus::Scheduler.new } let(:possible_runs) do { '2017-01-02 03:00:00 -0500': false, '2017-01-03 03:00:00 -0500': true, '2017-01-04 03:00:00 -0500': true, '2017-01-05 03:00:00 -0500': true, '2017-01-06 03:00:00 -0500': true } end before do sidekiq_file = Rails.root.join('lib', 'periodic_jobs.rb') lines = File.readlines(sidekiq_file).grep(/EducationForm::CreateDailySpoolFiles/i) cron = lines.first.gsub(" mgr.register('", '').gsub("', 'EducationForm::CreateDailySpoolFiles')\n", '') scheduler.schedule_cron(cron) {} # schedule_cron requires a block end it 'is only triggered by sidekiq-scheduler on weekdays' do scheduler_data = scheduler.jobs.first.cron_line expect(scheduler_data.hours).to eq([3]) expect(scheduler_data.weekdays).to eq([[1], [2], [3], [4], [5]]) end it 'skips observed holidays' do expect(Flipper).to receive(:enabled?).with(:spool_testing_error_2).and_return(false).at_least(:once) possible_runs.each do |day, should_run| Timecop.freeze(Time.zone.parse(day.to_s).beginning_of_day) do expect(subject.perform).to be(should_run) end end end end it 'logs a message on holidays', run_at: '2017-01-02 03:00:00 EDT' do expect(subject).not_to receive(:write_files) expect(subject).to receive('log_info').with("Skipping on a Holiday: New Year's Day") expect(subject.perform).to be false end it 'does not skip informal holidays', run_at: '2017-04-01 03:00:00 EDT' do # Sanity check that this *is* an informal holiday we're testing expect(Holidays.on(Time.zone.today, :us, :informal).first[:name]).to eq("April Fool's Day") expect(Flipper).to receive(:enabled?).with(:spool_testing_error_2).and_return(false).at_least(:once) expect(subject).to receive(:write_files) expect(subject.perform).to be true end end describe '#format_application' do context 'with a 0993 form' do let(:application_1606) { create(:va0993_full_form).education_benefits_claim } it 'tracks the 0993 form' do expect(subject).to receive(:track_form_type).with('22-0993', 999) result = subject.format_application(application_1606, rpo: 999) expect(result).to be_a(EducationForm::Forms::VA0993) end end context 'with a 0994 form' do let(:application_1606) { create(:va0994_full_form).education_benefits_claim } it 'tracks the 0994 form' do expect(subject).to receive(:track_form_type).with('22-0994', 999) result = subject.format_application(application_1606, rpo: 999) expect(result).to be_a(EducationForm::Forms::VA0994) end end context 'with a 1990 form' do it 'tracks and returns a form object' do expect(subject).to receive(:track_form_type).with('22-1990', 999) result = subject.format_application(application_1606, rpo: 999) expect(result).to be_a(EducationForm::Forms::VA1990) end end context 'with a 1995 form' do let(:application_1606) { create(:va1995_full_form).education_benefits_claim } it 'tracks the 1995 form' do expect(subject).to receive(:track_form_type).with('22-1995', 999) result = subject.format_application(application_1606, rpo: 999) expect(result).to be_a(EducationForm::Forms::VA1995) end end context 'with a 5490 form' do let(:application_1606) { create(:va5490_full_form).education_benefits_claim } it 'tracks the 5490 form' do expect(subject).to receive(:track_form_type).with('22-5490', 999) result = subject.format_application(application_1606, rpo: 999) expect(result).to be_a(EducationForm::Forms::VA5490) end end context 'with a 5495 form' do let(:application_1606) { create(:va5495_full_form).education_benefits_claim } it 'tracks the 5495 form' do expect(subject).to receive(:track_form_type).with('22-5495', 999) result = subject.format_application(application_1606, rpo: 999) expect(result).to be_a(EducationForm::Forms::VA5495) end end context 'with a 10203 form' do let(:application_1606) { create(:va10203, :va10203_full_form).education_benefits_claim } it 'tracks the 10203 form' do expect(subject).to receive(:track_form_type).with('22-10203', 999) result = subject.format_application(application_1606, rpo: 999) expect(result).to be_a(EducationForm::Forms::VA10203) end end context 'with a 10297 form' do let(:application_1606) { create(:va10297_full_form).education_benefits_claim } it 'tracks the 10297 form' do expect(subject).to receive(:track_form_type).with('22-10297', 999) result = subject.format_application(application_1606, rpo: 999) expect(result).to be_a(EducationForm::Forms::VA10297) end end context 'result tests' do subject { described_class.new.format_application(application_1606).text } it 'outputs a valid spool file fragment' do expect(subject.lines.select { |line| line.length > 80 }).to be_empty end it 'contains only windows-style newlines' do expect(subject).not_to match(/([^\r]\n)/) end end end describe '#perform' do context 'with a mix of valid and invalid record', run_at: '2016-09-16 03:00:00 EDT' do let(:spool_files) { Rails.root.join('tmp', 'spool_files', '*') } before do allow(Rails.env).to receive('development?').and_return(true) application_1606.saved_claim.form = {}.to_json application_1606.saved_claim.save!(validate: false) # Make this claim super malformed create(:va1990_western_region) create(:va1995_full_form) create(:va0994_full_form) # clear out old test files FileUtils.rm_rf(Dir.glob(spool_files)) # ensure our test data is spread across 2 regions.. expect(EducationBenefitsClaim.unprocessed.pluck(:regional_processing_office).uniq.count).to eq(2) end it 'processes the valid messages' do expect(Flipper).to receive(:enabled?).with(any_args).and_return(false).at_least(:once) expect { subject.perform }.to change { EducationBenefitsClaim.unprocessed.count }.from(4).to(0) expect(Dir[spool_files].count).to eq(2) end end context 'with records in staging', run_at: '2016-09-16 03:00:00 EDT' do before do application_1606.saved_claim.form = {}.to_json create(:va1990_western_region) create(:va1995_full_form) create(:va0994_full_form) ActionMailer::Base.deliveries.clear end it 'processes the valid messages' do with_settings(Settings, hostname: 'staging-api.va.gov') do expect(Flipper).to receive(:enabled?).with(any_args).and_return(false).at_least(:once) expect { subject.perform }.to change { EducationBenefitsClaim.unprocessed.count }.from(4).to(0) expect(ActionMailer::Base.deliveries.count).to be > 0 end end end context 'with records in production', run_at: '2016-09-16 03:00:00 EDT' do before do allow(Settings).to receive(:hostname).and_return('api.va.gov') application_1606.saved_claim.form = {}.to_json create(:va1990_western_region) create(:va1995_full_form) create(:va0994_full_form) ActionMailer::Base.deliveries.clear end it 'does not process the valid messages' do expect(Flipper).to receive(:enabled?).with(any_args).and_return(false).at_least(:once) expect { subject.perform }.to change { EducationBenefitsClaim.unprocessed.count }.from(4).to(0) expect(ActionMailer::Base.deliveries.count).to be 0 end end context 'with no records', run_at: '2016-09-16 03:00:00 EDT' do before do EducationBenefitsClaim.delete_all end it 'prints a statement and exits', run_at: '2017-02-21 00:00:00 EDT' do expect(subject).not_to receive(:write_files) expect(subject).to receive('log_info').with('No records to process.').once expect(subject.perform).to be(true) end it 'notifies slack', run_at: '2017-02-21 00:00:00 EDT' do expect(Flipper).to receive(:enabled?).with(:spool_testing_error_2).and_return(true).once expect_any_instance_of(SlackNotify::Client).to receive(:notify) with_settings(Settings.edu, audit_enabled: true, slack: OpenStruct.new(webhook_url: 'https://example.com')) do described_class.new.perform end end end end describe '#group_submissions_by_region' do it 'takes a list of records into chunked forms' do base_form = { veteranFullName: { first: 'Mark', last: 'Olson' }, privacyAgreementAccepted: true } base_address = { street: 'A', city: 'B', country: 'USA' } submissions = [] [ { state: 'MD' }, { state: 'GA' }, { state: 'WI' }, { state: 'OK' }, { state: 'XX', country: 'PHL' } ].each do |address_data| submissions << SavedClaim::EducationBenefits::VA1990.create( form: base_form.merge( educationProgram: { address: base_address.merge(address_data) } ).to_json ).education_benefits_claim end submissions << SavedClaim::EducationBenefits::VA1990.create( form: base_form.to_json ).education_benefits_claim output = subject.group_submissions_by_region(submissions) expect(output[:eastern].length).to be(3) expect(output[:western].length).to be(3) end end context 'write_files', run_at: '2016-09-17 03:00:00 EDT' do let(:filename) { '307_09172016_070000_vetsgov.spl' } let!(:second_record) { create(:va1995) } context 'in the development env' do let(:file_path) { "tmp/spool_files/#{filename}" } before do expect(Rails.env).to receive('development?').once.and_return(true) expect(Flipper).to receive(:enabled?).with(any_args).and_return(false).at_least(:once) end after do File.delete(file_path) end it 'writes a file to the tmp dir' do expect(EducationBenefitsClaim.unprocessed).not_to be_empty subject.perform contents = File.read(file_path) expect(contents).to include('APPLICATION FOR VA EDUCATION BENEFITS') # Concatenation is done in #write_files, so check for it here in the caller expect(contents).to include("*END*#{line_break}*INIT*") expect(contents).to include(second_record.education_benefits_claim.confirmation_number) expect(contents).to include(application_1606.confirmation_number) expect(EducationBenefitsClaim.unprocessed).to be_empty end end context 'on first retry attempt with a previous success' do let(:file_path) { "tmp/spool_files/#{filename}" } before do expect(Rails.env).to receive('development?').twice.and_return(true) expect(Flipper).to receive(:enabled?).with(:spool_testing_error_2).and_return(false).at_least(:once) end after do File.delete(file_path) end it 'notifies file was already created for filename and RPO' do expect(EducationBenefitsClaim.unprocessed).not_to be_empty subject.perform create(:va1995) expect(subject).to receive(:log_info).once msg = 'A spool file for 307 on 09172016 was already created' expect(subject).to receive(:log_info).with(msg) subject.perform end end context 'notifies which file failed during initial attempt' do let(:file_path) { "tmp/spool_files/#{filename}" } before do expect(Rails.env).to receive('development?').and_return(true).at_least(:once) expect(Flipper).to receive(:enabled?).with(:spool_testing_error_3).and_return(false).at_least(:once) expect(Flipper).to receive(:enabled?).with(:spool_testing_error_2).and_return(false).at_least(:once) end it 'logs exception to sentry' do local_mock = instance_double(SFTPWriter::Local) expect(EducationBenefitsClaim.unprocessed).not_to be_empty expect(SFTPWriter::Local).to receive(:new).exactly(6).and_return(local_mock) expect(local_mock).to receive(:write).exactly(6).times.and_raise('boom') expect(local_mock).to receive(:close).once.and_return(true) expect(subject).to receive(:log_exception_to_sentry).exactly(6) .times.with(instance_of(EducationForm::DailySpoolFileError)) subject.perform end end context 'in the production env' do it 'writes files out over sftp' do # we're only pushing spool files on production, b/c of issues with staging data getting into TIMS at RPO's allow(Rails.env).to receive(:production?).and_return(true) allow(Settings).to receive(:hostname).and_return('api.va.gov') expect(EducationBenefitsClaim.unprocessed).not_to be_empty expect(Flipper).to receive(:enabled?).with(any_args).and_return(false).at_least(:once) # any readable file will work for this spec key_path = Rails.root.join(*'/spec/fixtures/files/idme_cert.crt'.split('/')).to_s with_settings(Settings.edu.sftp, host: 'localhost', key_path:) do session_mock = instance_double(Net::SSH::Connection::Session) sftp_mock = instance_double(Net::SFTP::Session, session: session_mock) expect(Net::SFTP).to receive(:start).once.and_return(sftp_mock) expect(sftp_mock).to receive(:open?).once.and_return(true) expect(sftp_mock).to receive(:mkdir!).with('spool_files').once.and_return(true) expect(sftp_mock).to receive(:upload!) do |contents, path| expect(path).to eq File.join(Settings.edu.sftp.relative_path, filename) expect(contents.read).to include('EDUCATION BENEFIT BEING APPLIED FOR: Chapter 1606') end expect(sftp_mock).to receive(:stat!).with(anything).and_return(4619) expect(session_mock).to receive(:close) expect { subject.perform }.to trigger_statsd_gauge( 'worker.education_benefits_claim.transmissions.307.22-1990', value: 1 ).and trigger_statsd_gauge( 'worker.education_benefits_claim.transmissions.307.22-1995', value: 1 ) expect(EducationBenefitsClaim.unprocessed).to be_empty end end # rubocop:disable RSpec/NoExpectationExample it 'notifies the slack channel with a warning if no files were written' do stub_env_and_writer( byte_count: 0, expected_message: 'Warning: Uploaded 0 bytes to region: eastern' ) end # rubocop:enable RSpec/NoExpectationExample def stub_env_and_writer(byte_count:, expected_message:) allow(Rails.env).to receive(:production?).and_return(true) allow(Settings).to receive(:hostname).and_return('api.va.gov') expect(EducationBenefitsClaim.unprocessed).not_to be_empty key_path = Rails.root.join('spec', 'fixtures', 'files', 'idme_cert.crt').to_s with_settings(Settings.edu.sftp, host: 'localhost', key_path:) do sftp_writer_mock = instance_double(SFTPWriter::Remote) allow(SFTPWriter::Factory).to receive(:get_writer).with(Settings.edu.sftp).and_return(SFTPWriter::Remote) allow(SFTPWriter::Remote) .to receive(:new) .with(Settings.edu.sftp, logger: anything) .and_return(sftp_writer_mock) allow(sftp_writer_mock).to receive(:write).once.and_return(byte_count) allow(sftp_writer_mock).to receive(:close).once.and_return(true) instance = described_class.new # allow is needed because it's called multiple times and expect fails without it allow(instance).to receive(:log_to_slack) expect(instance).to receive(:log_to_slack).with(include(expected_message)) instance.perform end end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/education_form/create_spool_submissions_report_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EducationForm::CreateSpoolSubmissionsReport, type: :aws_helpers do subject do described_class.new end let(:time) { Time.zone.now } context 'with some sample claims', run_at: '2017-07-27 00:00:00 -0400' do let!(:education_benefits_claim) do create(:education_benefits_claim, processed_at: time.beginning_of_day) end before do subject.instance_variable_set(:@time, time) end describe '#create_csv_array' do it 'creates the right array' do expect( subject.create_csv_array ).to eq( csv_array: [['Claimant Name', 'Veteran Name', 'Confirmation #', 'Time Submitted', 'RPO'], [nil, 'Mark Olson', education_benefits_claim.confirmation_number, '2017-07-27 00:00:00 UTC', 'eastern']], stem_exists: false ) end it 'checks for stem submissions' do data = subject.create_csv_array expect(data[:stem_exists]).to be(false) end end describe '#perform' do before do expect(FeatureFlipper).to receive(:send_edu_report_email?).once.and_return(true) end after do File.delete(filename) end let(:filename) { "tmp/spool_reports/#{time.to_date}.csv" } def perform stub_reports_s3(filename) do subject.perform end end it 'sends an email' do expect { perform }.to change { ActionMailer::Base.deliveries.count }.by(1) end it 'creates a csv file' do perform data = subject.create_csv_array csv_array = data[:csv_array] csv_string = CSV.generate do |csv| csv_array.each do |row| csv << row end end expect(File.read(filename)).to eq(csv_string) end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/education_form/process10203_submissions_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'fugit' require 'feature_flipper' RSpec.describe EducationForm::Process10203Submissions, form: :education_benefits, type: :model do subject { described_class.new } sidekiq_file = Rails.root.join('lib', 'periodic_jobs.rb') lines = File.readlines(sidekiq_file).grep(/EducationForm::Process10203Submissions/i) cron = lines.first.gsub(" mgr.register('", '').gsub("', 'EducationForm::Process10203Submissions')\n", '') let(:user) { create(:user, :loa3, :with_terms_of_use_agreement) } let(:parsed_schedule) { Fugit.do_parse(cron) } let(:user2) { create(:user, uuid: '87ebe3da-36a3-4c92-9a73-61e9d700f6ea') } let(:no_edipi_user) { create(:user, :with_terms_of_use_agreement, idme_uuid: SecureRandom.uuid, participant_id: nil) } let(:evss_response_with_poa) { OpenStruct.new(body: get_fixture('json/evss_with_poa')) } before do allow(Flipper).to receive(:enabled?).and_call_original end describe 'scheduling' do before do allow(Rails.env).to receive('development?').and_return(true) end context 'job only runs between 6-18 every 6 hours', run_at: '2017-01-01 00:00:00 EDT' do it 'is only triggered by sidekiq periodic jobs every 6 hours between 6-18' do expect(parsed_schedule.original).to eq('0 6-18/6 * * *') expect(parsed_schedule.hours).to eq([6, 12, 18]) end end end describe '#group_user_uuid' do before do expect(FeatureFlipper).to receive(:send_email?).twice.and_return(false) end it 'takes a list of records into groups by user_uuid' do application_10203 = create(:va10203) application_10203.after_submit(user) application_user2 = create(:va10203) application_user2.after_submit(user2) submissions = [application_10203, application_user2] users = [user, user2] output = subject.send(:group_user_uuid, submissions.map(&:education_benefits_claim)) expect(output.keys).to eq(users.map(&:uuid)) end end describe '#perform' do before do EducationBenefitsClaim.delete_all EducationStemAutomatedDecision.delete_all end # rubocop:disable Layout/MultilineMethodCallIndentation context 'sets automated_decision_state' do context 'evss user with less than 180 days of entitlement' do before do expect(FeatureFlipper).to receive(:send_email?).once.and_return(false) end it 'changes from init to processed with good answers' do application_10203 = create(:va10203) application_10203.after_submit(user) expect do subject.perform end.to change { EducationStemAutomatedDecision.init.count }.from(1).to(0) .and change { EducationStemAutomatedDecision.processed.count }.from(0).to(1) end context 'multiple submissions' do before do expect(FeatureFlipper).to receive(:send_email?).once.and_return(false) end it 'without any be processed by CreateDailySpoolFiles' do application_10203 = create(:va10203) application_10203.after_submit(user) expect do subject.perform end.to change { EducationStemAutomatedDecision.init.count }.from(1).to(0) .and change { EducationStemAutomatedDecision.processed.count }.from(0).to(1) application_10203_2 = create(:va10203) application_10203_2.after_submit(user) expect do subject.perform end.to change { EducationStemAutomatedDecision.init.count }.from(1).to(0) .and change { EducationStemAutomatedDecision.processed.count }.from(1).to(2) end end end context 'evss user with more than 180 days' do before do gi_bill_status = build(:gi_bill_status_response) allow_any_instance_of(BenefitsEducation::Service).to receive(:get_gi_bill_status) .and_return(gi_bill_status) end end it 'evss user with no entitlement is processed' do application_10203 = create(:va10203) application_10203.after_submit(user) expect do subject.perform end.to change { EducationStemAutomatedDecision.init.count }.from(1).to(0) .and change { EducationStemAutomatedDecision.processed.count }.from(0).to(1) end it 'skips POA check for user without an EDIPI' do allow(Flipper).to receive(:enabled?).with(:form21_10203_confirmation_email) application_10203 = create(:va10203) application_10203.after_submit(no_edipi_user) subject.perform application_10203.reload expect(application_10203.education_benefits_claim.education_stem_automated_decision.poa).to be_nil end it 'sets POA to nil for new submissions' do allow(Flipper).to receive(:enabled?).with(:form21_10203_confirmation_email) application_10203 = create(:va10203) application_10203.after_submit(user) subject.perform application_10203.reload expect(application_10203.education_benefits_claim.education_stem_automated_decision.poa).to be_nil end it 'sets claim poa for claim with decision poa flag' do application_10203 = create(:education_benefits_claim_10203, processed_at: Time.zone.now.beginning_of_day, education_stem_automated_decision: build(:education_stem_automated_decision, :with_poa, :denied)) subject.perform application_10203.reload expect(application_10203.education_stem_automated_decision.poa).to be(true) end end # rubocop:enable Layout/MultilineMethodCallIndentation context 'with no records' do before do EducationBenefitsClaim.delete_all EducationStemAutomatedDecision.delete_all end it 'prints a statement and exits' do expect(subject).not_to receive(:process_user_submissions) expect(subject).to receive('log_info').with('No records with init status to process.').once expect(subject.perform).to be(true) end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/education_form/create_daily_spool_files_live_sftp_spec.rb
# frozen_string_literal: true require 'rails_helper' # Skip the test if ENV['RUN_SFTP_TEST'] is not set to 'true'. This will blow up the pipeline # and fail if you try to run it in Github. # To run it, copy and paste the below onto the command line # RUN_SFTP_TEST=true rspec spec/sidekiq/education_form/create_daily_spool_files_live_sftp_spec.rb if ENV['RUN_SFTP_TEST'] == 'true' # To set this up, you need to have another machine in your network that you can sftp to. # To install the ssh server on that machine (linux) do: sudo apt install openssh-server # You will also need to copy your id_rsa.pub file to that machine. Typically thats located # at ~/.ssh/id_rsa.pub. Use ssh-copy-id to copy the file over and make the key login work. # Then configure the settings below (use settings.local.yml) to point to that machine. # I encountered a situation where the remote machine was unreachable. Bouncing both VMs fixed it. # The remote machine should be configured with a bridged adapter if you are using virtualbox. # Set the host ip, key_path, user, port, and relative_307_path in your settings.local.yml RSpec.describe EducationForm::CreateDailySpoolFiles, form: :education_benefits, type: :model do subject { described_class.new } # rubocop:disable Naming/VariableNumber let!(:application_1606) do create(:va1990).education_benefits_claim end # rubocop:enable Naming/VariableNumber let(:line_break) { EducationForm::CreateDailySpoolFiles::WINDOWS_NOTEPAD_LINEBREAK } before do local_settings_path = Rails.root.join('config', 'settings.local.yml') if File.exist?(local_settings_path) local_settings = YAML.load_file(local_settings_path) || {} Settings.add_source!(local_settings) Settings.reload! end allow(Flipper).to receive(:enabled?).and_call_original end after(:all) do FileUtils.rm_rf('tmp/spool_files') end context 'write_files', run_at: '2016-09-17 03:00:00 EDT' do let(:filename) { '307_09172016_070000_vetsgov.spl' } let!(:second_record) { create(:va1995) } # If your remote is using /home/user/Downloads, mkdir_save blows up and the test fails. # Override this behavior. It doesn't seem to like trying to make /home/user before do allow_any_instance_of(SFTPWriter::Remote).to receive(:mkdir_safe).and_return(true) end # rubocop:disable Lint/ConstantDefinitionInBlock # rubocop:disable Lint/UselessMethodDefinition context 'in the production env' do it 'counts the number of bytes written in a live sftp' do allow(Rails.env).to receive(:production?).and_return(true) allow(Settings).to receive(:hostname).and_return('api.va.gov') instance = described_class.new allow(instance).to receive(:log_to_slack) # This is necessary because it takes the last monkey patch in the sequence of tests and applies it # here unless it's the first test that runs. Any tests that get added to this have to have this as # a minimum monkey patch RSpec::Mocks.with_temporary_scope do module SFTPPatch def stat!(path) super(path) # Call original stat! method end end Net::SFTP::Session.prepend(SFTPPatch) with_settings(Settings.edu.sftp, Settings.edu.sftp.to_h) do log_message = 'Uploaded 4619 bytes to region: eastern' instance.perform expect(instance).to have_received(:log_to_slack).with(include(log_message)) end end end it 'writes a warning message to slack if no bytes were sent in a live sftp' do allow(Rails.env).to receive(:production?).and_return(true) allow(Settings).to receive(:hostname).and_return('api.va.gov') instance = described_class.new allow(instance).to receive(:log_to_slack) # Prepend the patch for this test RSpec::Mocks.with_temporary_scope do module SFTPPatch def stat!(path) # Delete the file on the remote server before calling original stat! remove!(path) super(path) # Call original stat! method end end Net::SFTP::Session.prepend(SFTPPatch) with_settings(Settings.edu.sftp, Settings.edu.sftp.to_h) do log_message = 'Warning: Uploaded 0 bytes to region: eastern' instance.perform expect(instance).to have_received(:log_to_slack).with(include(log_message)) end end end it 'writes a warning message to slack if bytes sent do not match the remote file size in a live sftp' do allow(Rails.env).to receive(:production?).and_return(true) allow(Settings).to receive(:hostname).and_return('api.va.gov') instance = described_class.new allow(instance).to receive(:log_to_slack) # Prepend the patch for this test RSpec::Mocks.with_temporary_scope do module SFTPPatch def stat!(path) # change the remote file size by uploading small string upload!(StringIO.new('Hello World'), path) super(path) # Call original stat! method end end Net::SFTP::Session.prepend(SFTPPatch) with_settings(Settings.edu.sftp, Settings.edu.sftp.to_h) do log_message = 'Warning: Uploaded 11 bytes to region: eastern' instance.perform expect(instance).to have_received(:log_to_slack).with(include(log_message)) end end end end # rubocop:enable Lint/UselessMethodDefinition # rubocop:enable Lint/ConstantDefinitionInBlock end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/education_form/education_facility_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EducationForm::EducationFacility do let(:education_benefits_claim) { build(:education_benefits_claim) } let(:eastern_address) do OpenStruct.new(country: 'USA', state: 'DE') end let(:central_address) do OpenStruct.new(country: 'USA', state: 'IL') end let(:western_address) do OpenStruct.new(country: 'USA', state: 'CA') end def school(data) OpenStruct.new(address: data) end describe '#routing_address' do let(:form) { OpenStruct.new } context '22-1990' do it 'uses educationProgram over veteranAddress' do form.educationProgram = school(eastern_address) form.veteranAddress = western_address expect(described_class.routing_address(form, form_type: '1990').state).to eq(eastern_address.state) end it 'uses veteranAddress when no school address is given' do form.veteranAddress = western_address expect(described_class.routing_address(form, form_type: '1990').state).to eq(western_address.state) end end context '22-1995' do let(:form) { OpenStruct.new(veteranAddress: western_address) } it 'uses newSchool over relativeAddress' do form.newSchool = school(central_address) expect(described_class.routing_address(form, form_type: '1995').state).to eq(central_address.state) end it 'uses veteranAddress when no school address is given' do expect(described_class.routing_address(form, form_type: '1995').state).to eq(western_address.state) end end %w[5490 5495].each do |form_type| context "22-#{form_type}" do let(:form) { OpenStruct.new(relativeAddress: western_address) } it 'uses educationProgram over relativeAddress' do form.educationProgram = school(central_address) expect(described_class.routing_address(form, form_type:).state).to eq(central_address.state) end it 'uses relativeAddress when no educationProgram address is given' do expect(described_class.routing_address(form, form_type:).state).to eq(western_address.state) end end end end describe '#regional_office_for' do { eastern: ['VA', "VA Regional Office\nP.O. Box 4616\nBuffalo, NY 14240-4616"], central: ['CO', "VA Regional Office\nP.O. Box 4616\nBuffalo, NY 14240-4616"], western: ['AK', "VA Regional Office\nP.O. Box 8888\nMuskogee, OK 74402-8888"] }.each do |region, region_data| context "with a #{region} address" do before do new_form = education_benefits_claim.parsed_form new_form['educationProgram']['address']['state'] = region_data[0] education_benefits_claim.saved_claim.form = new_form.to_json end it 'returns the right address' do expect(described_class.regional_office_for(education_benefits_claim)).to eq(region_data[1]) end end end end describe '#region_for' do context '22-1995' do it 'routes to Eastern RPO for former CENTRAL RPO state' do form = education_benefits_claim.parsed_form form['newSchool'] = { 'address' => { state: 'IL' } } education_benefits_claim.saved_claim.form = form.to_json education_benefits_claim.saved_claim.form_id = '22-1995' expect(described_class.region_for(education_benefits_claim)).to eq(:eastern) end it 'routes to Eastern RPO' do form = education_benefits_claim.parsed_form education_benefits_claim.saved_claim.form = form.to_json education_benefits_claim.saved_claim.form_id = '22-1995' expect(described_class.region_for(education_benefits_claim)).to eq(:eastern) end end context '22-0994' do it 'routes to Eastern RPO' do education_benefits_claim.saved_claim.form_id = '22-0994' expect(described_class.region_for(education_benefits_claim)).to eq(:eastern) end end context '22-10297' do it 'routes to Eastern RPO' do education_benefits_claim.saved_claim.form_id = '22-10297' expect(described_class.region_for(education_benefits_claim)).to eq(:eastern) end end context '22-0993' do it 'routes to Western RPO' do education_benefits_claim.saved_claim.form_id = '22-0993' expect(described_class.region_for(education_benefits_claim)).to eq(:western) end end context 'address country Phillipines' do it 'routes to Western RPO' do form = education_benefits_claim.parsed_form form['educationProgram'] = { 'address' => { country: 'PHL' } } education_benefits_claim.saved_claim.form = form.to_json education_benefits_claim.saved_claim.form_id = '22-1990' expect(described_class.region_for(education_benefits_claim)).to eq(:western) end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/education_form/create_daily_fiscal_year_to_date_report_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'feature_flipper' def get_education_form_fixture(filename) get_fixture("education_form/#{filename}") end RSpec.describe EducationForm::CreateDailyFiscalYearToDateReport, type: :aws_helpers do subject do described_class.new end let(:date) { Time.zone.today - 1.day } before do allow_any_instance_of(EducationBenefitsClaim).to receive(:create_education_benefits_submission) end context 'with a report date of 2017-09-30' do subject do described_class.new('2017-09-30'.to_date) end describe '#fiscal_year' do it 'returns a fiscal year of 2017' do expect(subject.fiscal_year).to eq(2017) end end describe '#beginning_of_fiscal_year' do it 'returns a October 1st, 2016' do expect(subject.beginning_of_fiscal_year).to eq(Date.new(2016, 10)) end end end context 'with a report date of 2017-10-01' do subject do described_class.new('2017-10-01'.to_date) end describe '#fiscal_year' do it 'returns a fiscal year of 2018' do expect(subject.fiscal_year).to eq(2018) end end describe '#beginning_of_fiscal_year' do it 'returns a October 1st, 2017' do expect(subject.beginning_of_fiscal_year).to eq(Date.new(2017, 10)) end end end context 'with some sample submissions', run_at: '2017-01-10 03:00:00 EDT' do before do create_list(:education_benefits_submission, 2, status: :processed, created_at: date) create( :education_benefits_submission, status: :processed, region: :western, chapter33: false, chapter1606: true, created_at: date ) # outside of yearly range create(:education_benefits_submission, created_at: date - 2.years, status: 'processed') # outside of daily range, given the timecop freeze. create(:education_benefits_submission, created_at: date - 26.hours, status: 'processed') create(:education_benefits_submission, created_at: date, status: 'submitted') %w[1995 5490 5495 10203].each do |form_type| create(:education_benefits_submission, form_type:, created_at: date) end create(:education_benefits_submission, form_type: '0993', created_at: date, region: :western) create(:education_benefits_submission, form_type: '0994', created_at: date, region: :eastern, vettec: true, chapter33: false) end context 'with the date variable set' do subject do job_with_date end let(:job_with_date) do job = described_class.new(date) job end describe '#create_csv_array' do it 'makes the right csv array' do expect(subject.create_csv_array).to eq( get_education_form_fixture('fiscal_year_create_csv_array') ) end end describe '#calculate_submissions' do subject do job_with_date.create_csv_header job_with_date.calculate_submissions(range_type:, status:) end def self.verify_status_numbers(status, result) context "for #{status} applications" do let(:status) { status } it 'returns data about the number of submissions' do expect(subject.deep_stringify_keys).to eq(result) end end end %i[day year].each do |range_type| %i[processed submitted].each do |status| context "for the current #{range_type}" do let(:range_type) { range_type } verify_status_numbers( status, get_education_form_fixture("ytd_#{range_type}_#{status}") ) end end end end end describe '#perform' do subject do create_daily_year_to_date_report = described_class.new stub_reports_s3(filename) do create_daily_year_to_date_report.perform end create_daily_year_to_date_report end before do expect(FeatureFlipper).to receive(:send_edu_report_email?).once.and_return(true) end after do File.delete(filename) end let(:filename) { "tmp/daily_reports/#{date}.csv" } it 'creates a csv file' do subject csv_string = CSV.generate do |csv| subject.create_csv_array.each do |row| csv << row end end expect(File.read(filename)).to eq(csv_string) end it 'sends an email' do expect { subject }.to change { ActionMailer::Base.deliveries.count }.by(1) end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/education_form/delete_old_applications_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EducationForm::DeleteOldApplications do before do @saved_claim_nil = build(:education_benefits_1990, form: '{}') @saved_claim_nil.save(validate: false) @edu_claim_nil = create(:education_benefits_claim, processed_at: nil, saved_claim: @saved_claim_nil) @saved_claim_new = build(:education_benefits_1990, form: '{}') @saved_claim_new.save(validate: false) @edu_claim_new = create(:education_benefits_claim, processed_at: Time.now.utc, saved_claim: @saved_claim_new) @saved_claim_semi_new = build(:education_benefits_1990, form: '{}') @saved_claim_semi_new.save(validate: false) @edu_claim_semi_new = create(:education_benefits_claim, processed_at: 45.days.ago.utc, saved_claim: @saved_claim_semi_new) @saved_claim_old = build(:education_benefits_1990, form: '{}') @saved_claim_old.save(validate: false) @edu_claim_old = create(:education_benefits_claim, processed_at: 3.months.ago, saved_claim: @saved_claim_old) @saved_claim10203_old = build(:education_benefits_10203, form: '{}') @saved_claim10203_old.save(validate: false) @edu_claim10203_old = create(:education_benefits_claim_10203, education_stem_automated_decision: build(:education_stem_automated_decision), processed_at: 13.months.ago, saved_claim: @saved_claim10203_old) @saved_claim10203_newer = build(:education_benefits_10203, form: '{}') @saved_claim10203_newer.save(validate: false) @edu_claim10203_newer = create(:education_benefits_claim_10203, education_stem_automated_decision: build(:education_stem_automated_decision), processed_at: 11.months.ago, saved_claim: @saved_claim10203_newer) end describe '#perform' do it 'deletes old records' do expect { subject.perform } .to change(EducationBenefitsClaim, :count).from(6).to(4) .and change(SavedClaim::EducationBenefits, :count) .from(6).to(4) .and change(EducationStemAutomatedDecision, :count) .from(2).to(1) expect { @edu_claim_old.reload }.to raise_exception(ActiveRecord::RecordNotFound) expect { @saved_claim_old.reload }.to raise_exception(ActiveRecord::RecordNotFound) expect { @edu_claim_new.reload }.not_to raise_error expect { @saved_claim_new.reload }.not_to raise_error expect { @edu_claim_semi_new.reload }.not_to raise_error expect { @saved_claim_semi_new.reload }.not_to raise_error expect { @edu_claim_nil.reload }.not_to raise_error expect { @saved_claim_nil.reload }.not_to raise_error end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/education_form/create10203_applicant_decision_letters_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EducationForm::Create10203ApplicantDecisionLetters, form: :education_benefits, type: :model do subject { described_class.new } let(:time) { Time.zone.now } let(:count) do EducationBenefitsClaim.includes(:saved_claim, :education_stem_automated_decision).where( processed_at: (time - 24.hours)..time, saved_claims: { form_id: '22-10203' }, education_stem_automated_decisions: { automated_decision_state: EducationStemAutomatedDecision::DENIED } ).count end describe '#perform' do EducationBenefitsClaim.delete_all EducationStemAutomatedDecision.delete_all before do subject.instance_variable_set(:@time, time) end context 'with denied records' do let!(:education_benefits_claim) do create(:education_benefits_claim_10203, processed_at: time.beginning_of_day, education_stem_automated_decision: build(:education_stem_automated_decision, :with_poa, :denied)) end it 'logs number of applications being processed' do expect(subject).to receive('log_info') .with("Processing #{count} denied application(s)") .once expect(subject.perform).to be(true) end end context 'with no records' do before do EducationBenefitsClaim.delete_all EducationStemAutomatedDecision.delete_all end it 'prints a statement and exits' do expect(StemApplicantDenialMailer).not_to receive(:build) expect(subject).to receive('log_info').with('No records to process.').once expect(subject.perform).to be(true) end end context 'with error' do before do EducationBenefitsClaim.delete_all EducationStemAutomatedDecision.delete_all end it 'prints a statement and exits' do create(:education_benefits_claim_10203, processed_at: time.beginning_of_day, education_stem_automated_decision: build(:education_stem_automated_decision, :with_poa, :denied)) expect(StemApplicantDenialMailer).to receive(:build).and_raise(StandardError.new) expect(subject).to receive('log_exception_to_sentry').with(any_args).once expect(subject.perform).to be(true) end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/education_form/create_daily_excel_files_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EducationForm::CreateDailyExcelFiles, form: :education_benefits, type: :model do # Changed from application_10282 to application_form to fix Naming/VariableNumber let!(:application_form) do create(:va10282).education_benefits_claim end before do allow(Flipper).to receive(:enabled?).with(:form_10282_sftp_upload).and_return(true) end after do FileUtils.rm_rf(Dir.glob('tmp/**/*.csv')) end context 'with the feature flag disabled' do before do allow(Flipper).to receive(:enabled?).with(:form_10282_sftp_upload).and_return(false) end it 'just returns immediately' do expect(SFTPWriter::Factory).not_to receive(:get_writer) expect { described_class.new.perform }.not_to change { EducationBenefitsClaim.unprocessed.count } end end context 'scheduling' do before do allow(Rails.env).to receive('development?').and_return(true) end context 'job only runs on business days', run_at: '2016-12-31 00:00:00 EDT' do let(:scheduler) { Rufus::Scheduler.new } let(:possible_runs) do { '2017-01-02 03:00:00 -0500': false, '2017-01-03 03:00:00 -0500': true, '2017-01-04 03:00:00 -0500': true, '2017-01-05 03:00:00 -0500': true, '2017-01-06 03:00:00 -0500': true } end it 'skips observed holidays' do possible_runs.each do |day, should_run| Timecop.freeze(Time.zone.parse(day.to_s).beginning_of_day) do expect(described_class.new.perform).to be(should_run) end end end end # Fixed RSpec/SubjectStub by using instance instead of subject it 'logs a message on holidays', run_at: '2017-01-02 03:00:00 EDT' do instance = described_class.new allow(instance).to receive(:write_csv_file) allow(instance).to receive(:log_info) expect(instance.perform).to be false expect(instance).to have_received(:log_info).with("Skipping on a Holiday: New Year's Day") end end describe '#perform' do context 'with a mix of valid and invalid records', run_at: '2016-09-16 03:00:00 EDT' do before do allow(Rails.env).to receive('development?').and_return(true) application_form.saved_claim.form = {}.to_json application_form.saved_claim.save!(validate: false) # Make this claim malformed create(:va10282) # clear out old test files FileUtils.rm_rf(Dir.glob('tmp/*.csv')) end it 'processes the valid records' do expect { described_class.new.perform }.to change { EducationBenefitsClaim.unprocessed.count }.from(2).to(0) expect(Dir['tmp/*.csv'].count).to eq(1) end end context 'with records in staging', run_at: '2016-09-16 03:00:00 EDT' do before do application_form.saved_claim.form = {}.to_json create(:va10282) ActionMailer::Base.deliveries.clear end it 'processes records and uploads to SFTP' do with_settings(Settings, hostname: 'staging-api.va.gov') do expect(SFTPWriter::Factory).to receive(:get_writer).and_call_original expect { described_class.new.perform }.to change { EducationBenefitsClaim.unprocessed.count }.from(2).to(0) expect(Dir['tmp/form_10282/*.csv'].count).to eq(1) end end end context 'with no records', run_at: '2016-09-16 03:00:00 EDT' do before do EducationBenefitsClaim.delete_all end # Fixed RSpec/SubjectStub by using instance instead of subject it 'prints a statement and exits' do instance = described_class.new allow(instance).to receive(:write_csv_file) allow(instance).to receive(:log_info) expect(instance.perform).to be(true) expect(instance).to have_received(:log_info).with('No records to process.') end end end describe '#write_csv_file' do let(:filename) { "22-10282_#{Time.zone.now.strftime('%m%d%Y_%H%M%S')}.csv" } let(:test_records) do [ double('Record', name: 'John Doe', first_name: 'John', last_name: 'Doe', military_affiliation: 'Veteran', phone_number: '555-555-5555', email_address: 'john@example.com', country: 'USA', state: 'CA', race_ethnicity: 'White', gender: 'Male', education_level: "Bachelor's", employment_status: 'Employed', salary: '75000', technology_industry: 'Software') ] end before do allow(File).to receive(:write) end it 'creates a CSV file with correct headers and data' do instance = described_class.new csv_contents = instance.write_csv_file(test_records, filename) parsed_csv = CSV.parse(csv_contents) expect(parsed_csv.first).to eq(described_class::HEADERS) data_row = parsed_csv[1] expect(data_row).to eq([ 'John Doe', 'John', 'Doe', 'Veteran', '555-555-5555', 'john@example.com', 'USA', 'CA', 'White', 'Male', "Bachelor's", 'Employed', '75000', 'Software' ]) end it 'writes the CSV contents to a file' do instance = described_class.new instance.write_csv_file(test_records, filename) expect(File).to have_received(:write).with("tmp/#{filename}", anything) end context 'when a record fails to process' do let(:error_record) do double('ErrorRecord').tap do |record| allow(record).to receive(:name).and_raise(StandardError.new('Test error')) # Fixed Style/SlicingWithRange described_class::EXCEL_FIELDS[1..].each do |field| allow(record).to receive(field).and_return('test') end end end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/education_form/create10203_spool_submissions_report_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EducationForm::Create10203SpoolSubmissionsReport, type: :aws_helpers do subject do described_class.new end let(:time) { Time.zone.now } context 'with some sample claims', run_at: '2017-07-27 00:00:00 -0400' do let!(:education_benefits_claim_1) do create(:education_benefits_claim_10203, processed_at: time.beginning_of_day, education_stem_automated_decision: build(:education_stem_automated_decision, :with_poa, :denied)) end let!(:education_benefits_claim_2) do create(:education_benefits_claim_10203, processed_at: time.beginning_of_day, education_stem_automated_decision: build(:education_stem_automated_decision, :processed)) end before do subject.instance_variable_set(:@time, time) end describe '#create_csv_array' do it 'creates the right array' do expect( subject.create_csv_array ).to eq( csv_array: [['Submitted VA.gov Applications - Report YYYY-MM-DD', 'Claimant Name', 'Veteran Name', 'Confirmation #', 'Time Submitted', 'Denied (Y/N)', 'POA (Y/N)', 'RPO'], ['', nil, 'Mark Olson', education_benefits_claim_1.confirmation_number, '2017-07-27 00:00:00 UTC', 'Y', 'Y', 'eastern'], ['', nil, 'Mark Olson', education_benefits_claim_2.confirmation_number, '2017-07-27 00:00:00 UTC', 'N', 'N', 'eastern'], ['Total Submissions and Denials', '', '', '', 2, 1, '']] ) end end describe '#perform' do before do expect(FeatureFlipper).to receive(:send_edu_report_email?).once.and_return(true) end after do File.delete(filename) end let(:filename) { "tmp/spool10203_reports/#{time.to_date}.csv" } def perform stub_reports_s3(filename) do subject.perform end end it 'sends an email' do expect { perform }.to change { ActionMailer::Base.deliveries.count }.by(1) end it 'creates a csv file' do perform data = subject.create_csv_array csv_array = data[:csv_array] csv_string = CSV.generate do |csv| csv_array.each do |row| csv << row end end expect(File.read(filename)).to eq(csv_string) end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/education_form/create_daily_year_to_date_report_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'feature_flipper' def get_education_form_fixture(filename) get_fixture("education_form/#{filename}") end RSpec.describe EducationForm::CreateDailyYearToDateReport, type: :aws_helpers do subject do described_class.new end let(:date) { Time.zone.today - 1.day } before do allow_any_instance_of(EducationBenefitsClaim).to receive(:create_education_benefits_submission) end context 'with some sample submissions', run_at: '2017-01-04 03:00:00 EDT' do before do create_list(:education_benefits_submission, 2, status: :processed, created_at: date) create( :education_benefits_submission, status: :processed, region: :western, chapter33: false, chapter1606: true, created_at: date ) # outside of yearly range create(:education_benefits_submission, created_at: date - 1.year, status: 'processed') # outside of daily range, given the timecop freeze. create(:education_benefits_submission, created_at: date - 26.hours, status: 'processed') create(:education_benefits_submission, created_at: date, status: 'submitted') %w[1995 5490 5495 10203].each do |form_type| create(:education_benefits_submission, form_type:, created_at: date) end create(:education_benefits_submission, form_type: '0993', created_at: date, region: :western) create(:education_benefits_submission, form_type: '0994', created_at: date, region: :eastern, vettec: true, chapter33: false) end context 'with the date variable set' do subject do job_with_date end let(:job_with_date) do job = described_class.new job.instance_variable_set(:@date, date) job end describe '#create_csv_array' do it 'makes the right csv array' do expect(subject.create_csv_array).to eq( get_education_form_fixture('create_csv_array') ) end end describe '#calculate_submissions' do subject do job_with_date.create_csv_header job_with_date.calculate_submissions(range_type:, status:) end def self.verify_status_numbers(status, result) context "for #{status} applications" do let(:status) { status } it 'returns data about the number of submissions' do expect(subject.deep_stringify_keys).to eq(result) end end end %i[day year].each do |range_type| %i[processed submitted].each do |status| context "for the current #{range_type}" do let(:range_type) { range_type } verify_status_numbers( status, get_education_form_fixture("ytd_#{range_type}_#{status}") ) end end end end end describe '#perform' do subject do create_daily_year_to_date_report = described_class.new stub_reports_s3(filename) do create_daily_year_to_date_report.perform end create_daily_year_to_date_report end before do expect(FeatureFlipper).to receive(:send_edu_report_email?).once.and_return(true) end after do FileUtils.rm_f(filename) end let(:filename) { "tmp/daily_reports/#{date}.csv" } it 'creates a csv file' do subject csv_string = CSV.generate do |csv| subject.create_csv_array.each do |row| csv << row end end expect(File.read(filename)).to eq(csv_string) end it 'sends an email' do expect { subject }.to change { ActionMailer::Base.deliveries.count }.by(1) end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/education_form/send_school_certifying_officials_email_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'gi/client' # required for stubbing, isn't loaded normally until GIDSRedis is loaded RSpec.describe EducationForm::SendSchoolCertifyingOfficialsEmail, form: :education_benefits, type: :model do subject { described_class.new } let(:claim) { create(:va10203) } let(:user) { create(:evss_user) } def sco_email_sent_false(less_than_six_months, facility_code) subject.perform(claim.id, less_than_six_months, facility_code) db_claim = SavedClaim::EducationBenefits::VA10203.find(claim.id) expect(db_claim.parsed_form['scoEmailSent']).to be(false) end describe '#perform' do it 'when gi_bill_status does not have remaining_entitlement sco email sent is false' do sco_email_sent_false(false, '1') end context 'when no facility code is present' do it 'sco email sent is false' do sco_email_sent_false(true, nil) end end context 'when more than six months of entitlement remaining' do it 'sco email sent is false' do sco_email_sent_false(false, '1') end end context 'when institution is blank' do before do gids_response = build(:gids_response, :empty) allow_any_instance_of(GI::Client).to receive(:get_institution_details_v0) .and_return(gids_response) end it 'sco email sent is false' do sco_email_sent_false(true, '1') end end context 'when school has changed' do before do gids_response = build(:gids_response) allow_any_instance_of(GI::Client).to receive(:get_institution_details_v0) .and_return(gids_response) end it 'sco email sent is false' do form = create(:va10203, :school_changed) subject.perform(form.id, true, '1') db_claim = SavedClaim::EducationBenefits::VA10203.find(form.id) expect(db_claim.parsed_form['scoEmailSent']).to be(false) end end context 'when neither a primary or secondary sco with an email address is found' do before do gids_response = build(:gids_response, :no_scos) allow_any_instance_of(GI::Client).to receive(:get_institution_details_v0) .and_return(gids_response) end it 'sco email sent is false' do sco_email_sent_false(true, '1') end end context 'when all conditions are met' do before do gids_response = build(:gids_response) allow_any_instance_of(GI::Client).to receive(:get_institution_details_v0) .and_return(gids_response) end it 'sco email sent is true' do subject.perform(claim.id, true, '1') db_claim = SavedClaim::EducationBenefits::VA10203.find(claim.id) expect(db_claim.parsed_form['scoEmailSent']).to be(true) end it 'sends the SCO and applicant emails with correct contents' do # Clear any previous deliveries ActionMailer::Base.deliveries.clear # Perform the action that triggers email sending subject.perform(claim.id, true, '1') # Fetch the updated claim db_claim = SavedClaim::EducationBenefits::VA10203.find(claim.id) # Verify that scoEmailSent is true expect(db_claim.parsed_form['scoEmailSent']).to be(true) # Verify that two emails were sent expect(ActionMailer::Base.deliveries.count).to eq(2) # Find the SCO email sco_email = ActionMailer::Base.deliveries.find do |email| email.to.include?('user@school.edu') end expect(sco_email).not_to be_nil # Verify the SCO email contents expect(sco_email.subject).to eq('Applicant for VA Rogers STEM Scholarship') expect(sco_email.from).to include('stage.va-notifications@public.govdelivery.com') expect(sco_email.body.encoded).to include('<p>Dear VA School Certifying Official,</p>') # Add a line to download the contents of the email to a file File.write('tmp/sco_email_body.html', sco_email.body) end end end end
0
code_files/vets-api-private/spec/sidekiq/education_form
code_files/vets-api-private/spec/sidekiq/education_form/forms/va8794_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EducationForm::Forms::VA8794 do subject { described_class.new(application) } before do allow_any_instance_of(EducationForm::Forms::Base).to receive(:format).and_return('') end let(:application) { create(:va8794).education_benefits_claim } it 'reads designating official fields' do expect(subject.designating_official_name).to eq({ 'first' => 'John', 'middle' => 'A', 'last' => 'Doe' }) expect(subject.designating_official_title).to eq('Designating Official') expect(subject.designating_official_email).to eq('john.doe@example.com') end it 'reads institution details' do expect(subject.institution_name).to eq('Test University') expect(subject.facility_code).to eq('12345678') expect(subject.va_facility_code?).to be(true) end it 'reads primary official fields' do expect(subject.primary_official_name).to eq({ 'first' => 'Jane', 'middle' => 'B', 'last' => 'Smith' }) expect(subject.primary_official_title).to eq('Primary Certifying Official') expect(subject.primary_official_email).to eq('jane.smith@example.com') end it 'reads training and benefit fields' do expect(subject.training_completion_date).to eq('2024-03-15') expect(subject.training_exempt).to be(false) expect(subject.va_education_benefits?).to be(true) end it 'handles arrays and booleans' do expect(subject.additional_certifying_officials.size).to eq(2) expect(subject.read_only_certifying_officials.size).to eq(2) end it 'reads remarks and signature fields even when absent' do expect(subject.remarks).to eq('lorem ipsum dolor sit amet') expect(subject.statement_of_truth_signature).to eq('John A Doe') expect(subject.date_signed).to eq('2024-03-15') end it 'exposes the header form type' do expect(subject.header_form_type).to eq('V8794') end end
0
code_files/vets-api-private/spec/sidekiq/education_form
code_files/vets-api-private/spec/sidekiq/education_form/forms/va10297_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EducationForm::Forms::VA10297 do subject { described_class.new(application) } let(:application) { create(:va10297_full_form).education_benefits_claim } it 'exposes the header form type' do expect(subject.header_form_type).to eq('V10297') end it 'exposes the va file number' do expect(subject.applicant_va_file_number).to eq('123456789') end it 'exposes the bank info' do expect(subject.bank_routing_number).to eq('123456789') expect(subject.bank_account_number).to eq('123456') expect(subject.bank_account_type).to eq('checking') end it 'exposes the education level' do expect(subject.education_level_name).to eq('Bachelor’s degree') end it 'exposes the high tech area name' do expect(subject.high_tech_area_name).to eq('Computer programming') end it 'exposes the salary' do expect(subject.salary_text).to eq('$20,000-$35,000') end end
0
code_files/vets-api-private/spec/sidekiq/education_form
code_files/vets-api-private/spec/sidekiq/education_form/forms/va5490_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EducationForm::Forms::VA5490 do context 'method tests' do subject do education_benefits_claim.instance_variable_set(:@application, nil) education_benefits_claim.saved_claim.instance_variable_set(:@application, nil) described_class.new(education_benefits_claim) end let(:education_benefits_claim) { create(:va5490).education_benefits_claim } before do allow_any_instance_of(described_class).to receive(:format) end describe 'previous benefits' do context 'without previous benefits' do before do education_benefits_claim.saved_claim.form = { privacyAgreementAccepted: true, previousBenefits: { disability: false, dic: false, chapter31: false, ownServiceBenefits: '', chapter35: false, chapter33: false, transferOfEntitlement: false, other: '' } }.to_json end it 'previously_applied_for_benefits? should return false' do expect(subject.previously_applied_for_benefits?).to be(false) end end context 'with previous benefits' do before do education_benefits_claim.saved_claim.form = { privacyAgreementAccepted: true, previousBenefits: { disability: true, dic: true, chapter31: true, ownServiceBenefits: 'foo', chapter35: true, chapter33: true, transferOfEntitlement: true, other: 'other' } }.to_json end it 'previous_benefits should return the right value' do # rubocop:disable Layout/LineLength expect(subject.previous_benefits).to eq("DISABILITY COMPENSATION OR PENSION\nDEPENDENTS' INDEMNITY COMPENSATION\nVOCATIONAL REHABILITATION BENEFITS (Chapter 31)\nVETERANS EDUCATION ASSISTANCE BASED ON SOMEONE ELSE'S SERVICE: CHAPTER 35 - SURVIVORS' AND DEPENDENTS' EDUCATIONAL ASSISTANCE PROGRAM (DEA)\nVETERANS EDUCATION ASSISTANCE BASED ON SOMEONE ELSE'S SERVICE: CHAPTER 33 - POST-9/11 GI BILL MARINE GUNNERY SERGEANT DAVID FRY SCHOLARSHIP\nVETERANS EDUCATION ASSISTANCE BASED ON SOMEONE ELSE'S SERVICE: TRANSFERRED ENTITLEMENT\nVETERANS EDUCATION ASSISTANCE BASED ON YOUR OWN SERVICE SPECIFY BENEFIT(S): foo\nOTHER; Specify benefit(s): other") # rubocop:enable Layout/LineLength end it 'previously_applied_for_benefits? should return true' do expect(subject.previously_applied_for_benefits?).to be(true) end end end end context 'spool_file tests' do %w[ simple_chapter_33_biological_child simple_chapter_33_step_child kitchen_sink_chapter_33_spouse kitchen_sink_chapter_35_spouse kitchen_sink_chapter_35_adopted_child ].each do |test_application| test_spool_file('5490', test_application) end end context 'spool_file tests with pow/mia labels' do %w[ kitchen_sink_chapter_33_died_on_duty kitchen_sink_chapter_33_died_non_duty kitchen_sink_chapter_33_pow_or_mia ].each do |test_application| test_spool_file('5490', test_application) end end context 'spool_file tests with guardian' do %w[ kitchen_sink_chapter_33_died_non_duty_guardian_graduated kitchen_sink_chapter_33_died_non_duty_guardian_not_graduated ].each do |test_application| test_spool_file('5490', test_application) end end end
0
code_files/vets-api-private/spec/sidekiq/education_form
code_files/vets-api-private/spec/sidekiq/education_form/forms/va1995_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EducationForm::Forms::VA1995 do subject { described_class.new(education_benefits_claim) } let(:education_benefits_claim) { build(:va1995).education_benefits_claim } before do allow(Flipper).to receive(:enabled?).and_call_original allow(Flipper).to receive(:enabled?).with(:validate_saved_claims_with_json_schemer).and_return(false) end # For each sample application we have, format it and compare it against a 'known good' # copy of that submission. This technically covers all the helper logic found in the # `Form` specs, but are a good safety net for tracking how forms change over time. %i[ minimal kitchen_sink kitchen_sink_blank_appliedfor kitchen_sink_blank_appliedfor_ch30 kitchen_sink_ch35_ch33 kitchen_sink_ch35_ch35 ch33_post911 ch33_fry ch30 ch1606 kitchen_sink_ch33_p911_baf ch33_p911_to_fry ch33_fry_baf ch30_mgi_bill ch1606_baf toe toe_baf ].each do |application_name| test_spool_file('1995', application_name) end # run PROD_EMULATION=true rspec spec/sidekiq/education_form/forms/va1995_spec.rb to # emulate production (e.g. when removing feature flags) prod_emulation = true if ENV['PROD_EMULATION'].eql?('true') # :nocov: context 'test 1995 - production emulation', if: prod_emulation do before do allow(Settings).to receive(:vsp_environment).and_return('vagov-production') end %i[minimal kitchen_sink kitchen_sink_blank_appliedfor kitchen_sink_blank_appliedfor_ch30 kitchen_sink_ch35_ch33 kitchen_sink_ch35_ch35 ch33_post911 ch33_fry ch30 ch1606].each do |application_name| test_spool_file('1995', application_name) end end # :nocov: describe '#direct_deposit_type' do let(:education_benefits_claim) { create(:va1995_full_form).education_benefits_claim } it 'converts internal keys to text' do expect(subject.direct_deposit_type('startUpdate')).to eq('Start or Update') expect(subject.direct_deposit_type('stop')).to eq('Stop') expect(subject.direct_deposit_type('noChange')).to eq('Do Not Change') end end # :nocov: describe '#direct_deposit_type - production emulation', if: prod_emulation do before do allow(Settings).to receive(:vsp_environment).and_return('vagov-production') end let(:education_benefits_claim) { create(:va1995_full_form).education_benefits_claim } it 'converts internal keys to text' do expect(subject.direct_deposit_type('startUpdate')).to eq('Start or Update') expect(subject.direct_deposit_type('stop')).to eq('Stop') expect(subject.direct_deposit_type('noChange')).to eq('Do Not Change') end end # :nocov: context 'spool_file tests with high school minors' do %w[ ch30_guardian_not_graduated ch30_guardian_graduated_sponsor ch30_guardian_graduated ].each do |test_application| test_spool_file('1995', test_application) end end # :nocov: context 'spool_file tests with high school minors - production emulation', if: prod_emulation do before do allow(Settings).to receive(:vsp_environment).and_return('vagov-production') end %w[ ch30_guardian_not_graduated ch30_guardian_graduated_sponsor ch30_guardian_graduated ].each do |test_application| test_spool_file('1995', test_application) end end # :nocov: end
0
code_files/vets-api-private/spec/sidekiq/education_form
code_files/vets-api-private/spec/sidekiq/education_form/forms/va0993_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EducationForm::Forms::VA0993 do subject { described_class.new(education_benefits_claim) } let(:education_benefits_claim) { build(:va0993).education_benefits_claim } %w[ssn va_file_number].each do |form| test_spool_file('0993', form) end describe '#direct_deposit_type' do let(:education_benefits_claim) { create(:va0993).education_benefits_claim } it 'converts internal keys to text' do expect(subject.direct_deposit_type('startUpdate')).to eq('Start or Update') expect(subject.direct_deposit_type('stop')).to eq('Stop') expect(subject.direct_deposit_type('noChange')).to eq('Do Not Change') end end end
0
code_files/vets-api-private/spec/sidekiq/education_form
code_files/vets-api-private/spec/sidekiq/education_form/forms/va10203_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EducationForm::Forms::VA10203 do %w[kitchen_sink minimal].each do |test_application| test_spool_file('10203', test_application) end def spool_file_text(file_name) windows_linebreak = EducationForm::CreateDailySpoolFiles::WINDOWS_NOTEPAD_LINEBREAK expected_text = File.read("spec/fixtures/education_benefits_claims/10203/#{file_name}").rstrip expected_text.gsub!("\n", windows_linebreak) unless expected_text.include?(windows_linebreak) end context 'STEM automated decision' do subject { described_class.new(claim) } before do allow(claim).to receive(:id).and_return(1) claim.instance_variable_set(:@application, nil) claim.instance_variable_set(:@stem_automated_decision, nil) end let(:claim) do SavedClaim::EducationBenefits::VA10203.create!( form: File.read('spec/fixtures/education_benefits_claims/10203/kitchen_sink.json') ).education_benefits_claim end it 'generates the denial spool file with poa', run_at: '2017-01-17 03:00:00 -0500' do claim.education_stem_automated_decision = build(:education_stem_automated_decision, :with_poa, :denied) expect(subject.text).to eq(spool_file_text('kitchen_sink_stem_ad_with_poa.spl')) end it 'generates the denial spool file without poa', run_at: '2017-01-17 03:00:00 -0500' do claim.education_stem_automated_decision = build(:education_stem_automated_decision, :denied) expect(subject.text).to eq(spool_file_text('kitchen_sink_stem_ad_without_poa.spl')) end end end
0
code_files/vets-api-private/spec/sidekiq/education_form
code_files/vets-api-private/spec/sidekiq/education_form/forms/va0976_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EducationForm::Forms::VA0976 do subject { described_class.new(application) } before do allow_any_instance_of(EducationForm::Forms::Base).to receive(:format).and_return('') end let(:application) { create(:va8794).education_benefits_claim } it 'exposes the header form type' do expect(subject.header_form_type).to eq('V0976') end end
0
code_files/vets-api-private/spec/sidekiq/education_form
code_files/vets-api-private/spec/sidekiq/education_form/forms/va1990_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EducationForm::Forms::VA1990, form: :education_benefits, type: :model do subject { described_class.new(application) } let(:application) { create(:va1990).education_benefits_claim } # For each sample application we have, format it and compare it against a 'known good' # copy of that submission. This technically covers all the helper logic found in the # `Form` specs, but are a good safety net for tracking how forms change over time. %i[simple_ch33 kitchen_sink kitchen_sink_edu_prog kitchen_sink_active_duty].each do |application_name| test_spool_file('1990', application_name) end describe '#rotc_scholarship_amounts' do it 'always outputs 5 double-spaced lines' do output = subject.rotc_scholarship_amounts(nil) expect(output.lines.count).to eq(9) (1..5).each do |i| expect(output).to include "Year #{i}" end end it 'includes partial records' do values = [OpenStruct.new(amount: 1), OpenStruct.new(amount: 2), OpenStruct.new(amount: 3)] output = subject.rotc_scholarship_amounts(values) expect(output.lines.count).to eq(9) (1..3).each do |i| expect(output).to include "Year #{i}" expect(output).to include "Amount: #{i}" end expect(output).to include 'Year 4' expect(output).to include 'Year 5' end end describe '#disclosure_for', run_at: '2017-01-04 03:00:00 EDT' do before do subject.instance_variable_set(:@applicant, OpenStruct.new(benefitsRelinquishedDate: Time.zone.today)) end { CH32: 'Chapter 32', CH30: 'Chapter 30', CH1606: 'Chapter 1606', CH33: 'Chapter 33 ', CH33_1606: 'Chapter 33 ', CH33_1607: 'Chapter 33 ', CH33_30: 'Chapter 33 ' }.each do |type, check| it "shows a partial containing the #{type} disclaimer" do output = subject.disclosure_for(type) expect(output).to include(check) end end end describe '#disclosures' do it 'adds disclosures for different types' do expect(subject).to receive(:disclosure_for).with('CH30') expect(subject).to receive(:disclosure_for).with('CH32') expect(subject).to receive(:disclosure_for).with('CH33') expect(subject).to receive(:disclosure_for).with('CH1606') subject.disclosures(OpenStruct.new(chapter1606: true, chapter30: true, chapter32: true, chapter33: true)) end it 'handles chapter 33 relinquishments' do expect(subject).to receive(:disclosure_for).with('CH33_1606') subject.disclosures(OpenStruct.new(chapter33: true, benefitsRelinquished: 'chapter1606')) end end context 'spool_file tests with guardian' do %w[ kitchen_sink_active_duty_guardian_graduated kitchen_sink_active_duty_guardian_not_graduated ].each do |test_application| test_spool_file('1990', test_application) end end end
0
code_files/vets-api-private/spec/sidekiq/education_form
code_files/vets-api-private/spec/sidekiq/education_form/forms/va5495_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EducationForm::Forms::VA5495 do %w[kitchen_sink simple].each do |test_application| test_spool_file('5495', test_application) end end
0
code_files/vets-api-private/spec/sidekiq/education_form
code_files/vets-api-private/spec/sidekiq/education_form/forms/va10282_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EducationForm::Forms::VA10282 do subject { described_class.new(application) } let(:application) { create(:va10282).education_benefits_claim } %w[minimal].each do |test_application| test_excel_file('10282', test_application) end it 'exposes the header form type' do expect(subject.header_form_type).to eq('V10282') end end
0
code_files/vets-api-private/spec/sidekiq/education_form
code_files/vets-api-private/spec/sidekiq/education_form/forms/va0994_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EducationForm::Forms::VA0994 do subject { described_class.new(education_benefits_claim) } let(:education_benefits_claim) { build(:va0994).education_benefits_claim } %w[kitchen_sink prefill simple].each do |form| test_spool_file('0994', form) end end
0
code_files/vets-api-private/spec/sidekiq/education_form
code_files/vets-api-private/spec/sidekiq/education_form/forms/base_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe EducationForm::Forms::Base, form: :education_benefits, type: :model do let!(:application) { create(:va1990).education_benefits_claim } let(:renderer) { described_class.new(application) } describe '#hours_and_type' do subject do renderer.hours_and_type(OpenStruct.new(training)) end let(:training) do {} end context 'with hours' do let(:training) do { hours: 4 } end it 'outputs the hours' do expect(subject).to eq('4') end end context 'with hours and hours_type' do let(:training) do { hours: 4, hoursType: 'semester' } end it 'outputs hours and hours_type' do expect(subject).to eq('4 (semester)') end end context 'without hours' do it 'returns blank string' do expect(subject).to eq('') end end end context 'yesno' do it 'returns N/A for nil values' do expect(renderer.yesno(nil)).to eq('N/A') end it 'returns NO for falsey values' do expect(renderer.yesno(false)).to eq('NO') end it 'returns YES for truthy values' do expect(renderer.yesno(true)).to eq('YES') expect(renderer.yesno('true')).to eq('YES') end end describe '#full_name' do subject { renderer.full_name(name) } let(:name) { OpenStruct.new(first: 'Mark', last: 'Olson') } context 'with no middle name' do it 'does not have extra spaces' do expect(subject).to eq('Mark Olson') end end context 'with a middle name' do it 'is included' do name.middle = 'Middle' expect(subject).to eq 'Mark Middle Olson' end end end describe '#full_address' do subject { renderer.full_address(address) } let(:address) { application.open_struct_form.veteranAddress } context 'with a nil address' do let(:address) { nil } it 'returns the blank string' do expect(subject).to eq('') end end context 'with no street2' do it 'formats the address correctly' do expect(subject).to eq("123 MAIN ST\nMILWAUKEE, WI, 53130\nUSA") end end context 'with no state' do before do address.state = nil end it 'formats the address correctly' do expect(subject).to eq("123 MAIN ST\nMILWAUKEE, 53130\nUSA") end context 'with no city and zip' do before do address.city = nil address.postalCode = nil end it 'formats the address correctly' do expect(subject).to eq("123 MAIN ST\n\nUSA") end end end context 'with a street2' do before do address.street2 = 'apt 2' end it 'formats the address correctly' do expect(subject).to eq("123 MAIN ST\nAPT 2\nMILWAUKEE, WI, 53130\nUSA") end end end describe '#value_or_na' do it 'returns value' do expect(renderer.value_or_na('Value')).to eq('Value') end it 'returns N/A' do expect(renderer.value_or_na(nil)).to eq('N/A') end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/lighthouse/create_intent_to_file_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lighthouse/benefits_claims/service' RSpec.describe Lighthouse::CreateIntentToFileJob do let(:job) { described_class.new } let(:user) { create(:user) } let(:user_account) { user.user_account } let(:pension_ipf) { create(:in_progress_527_form, user_account:) } let(:itf_type) { Lighthouse::CreateIntentToFileJob::ITF_FORMS[pension_ipf.form_id] } let(:service) { double('service') } let(:monitor) { double('monitor') } describe '#perform' do let(:timestamp) { Time.zone.now } let(:response) do { 'data' => { 'id' => '123456', 'type' => 'intent_to_file', 'attributes' => { 'creationDate' => timestamp.to_s, 'expirationDate' => timestamp.to_s, 'type' => 'pensions', 'status' => 'active' } } } end before do allow(user).to receive(:participant_id).and_return('test-pid') allow(InProgressForm).to receive(:find).and_return(pension_ipf) allow(BenefitsClaims::Service).to receive(:new).and_return(service) job.instance_variable_set(:@monitor, monitor) allow(monitor).to receive :track_create_itf_begun allow(monitor).to receive :track_create_itf_failure allow(monitor).to receive :track_create_itf_success allow(monitor).to receive :track_create_itf_exhaustion allow(monitor).to receive :track_missing_user_icn allow(monitor).to receive :track_missing_user_pid allow(monitor).to receive :track_missing_form allow(monitor).to receive :track_invalid_itf_type end it 'returns an established ITF' do expect(service).to receive(:get_intent_to_file).with(itf_type).and_return(response) expect(monitor).to receive(:track_create_itf_active_found) expect(monitor).not_to receive(:track_create_itf_begun) expect(service).not_to receive(:create_intent_to_file).with(itf_type, '') # as when invoked from in_progress_form_controller ret = job.perform(123, user.icn, user.participant_id) expect(ret).to be response end it 'successfully submits an ITF' do expect(service).to receive(:get_intent_to_file).with(itf_type).and_raise Common::Exceptions::ResourceNotFound expect(monitor).to receive(:track_create_itf_begun).once expect(service).to receive(:create_intent_to_file).with(itf_type, '').and_return(response) expect(monitor).to receive(:track_create_itf_success).once # as when invoked from in_progress_form_controller ret = job.perform(123, user.icn, user.participant_id) expect(ret).to be response end it 'continues to submit if ITF is not active' do response['data']['attributes']['status'] = 'FUBAR' expect(service).to receive(:get_intent_to_file).with(itf_type).and_return(response) expect(monitor).to receive(:track_create_itf_begun).once expect(service).to receive(:create_intent_to_file).with(itf_type, '').and_return(response) expect(monitor).to receive(:track_create_itf_success).once # as when invoked from in_progress_form_controller ret = job.perform(123, user.icn, user.participant_id) expect(ret).to be response end it 'raises MissingICN' do allow(user).to receive(:icn).and_return nil expect(monitor).not_to receive(:track_create_itf_begun) expect(monitor).to receive(:track_missing_user_icn) # as when invoked from in_progress_form_controller job.perform(123, user.icn, user.participant_id) end it 'raises MissingParticipantIDError' do allow(user).to receive(:participant_id).and_return nil expect(monitor).not_to receive(:track_create_itf_begun) expect(monitor).to receive(:track_missing_user_pid) # as when invoked from in_progress_form_controller job.perform(123, user.icn, user.participant_id) end it 'raises FormNotFoundError' do allow(InProgressForm).to receive(:find).and_return nil expect(monitor).not_to receive(:track_create_itf_begun) expect(monitor).to receive(:track_missing_form) # as when invoked from in_progress_form_controller job.perform(123, user.icn, user.participant_id) end it 'raises InvalidITFTypeError' do allow(pension_ipf).to receive(:form_id).and_return 'invalid_type' expect(monitor).not_to receive(:track_create_itf_begun) expect(monitor).to receive(:track_invalid_itf_type) # as when invoked from in_progress_form_controller job.perform(123, user.icn, user.participant_id) end it 'raises other errors and logs failure' do allow(user_account).to receive(:icn).and_return 'non-matching-icn' expect(monitor).not_to receive(:track_create_itf_begun) expect(monitor).to receive(:track_create_itf_failure) # as when invoked from in_progress_form_controller expect { job.perform(123, user.icn, user.participant_id) }.to raise_error ActiveRecord::RecordNotFound end end # Retries exhausted describe 'sidekiq_retries_exhausted block' do context 'when retries are exhausted' do let(:exhaustion_msg) do { 'args' => [pension_ipf.id, user_account.icn, 'PID'], 'class' => 'Lighthouse::CreateIntentToFileJob', 'error_message' => 'An error occurred', 'queue' => 'default' } end before do allow(BenefitsClaims::IntentToFile::Monitor).to receive(:new).and_return(monitor) allow(InProgressForm).to receive(:find).and_return(pension_ipf) end it 'logs a distinct error when form_type, form_start_date, and veteran_icn provided' do Lighthouse::CreateIntentToFileJob.within_sidekiq_retries_exhausted_block( exhaustion_msg, 'TESTERROR' ) do expect(monitor).to receive(:track_create_itf_exhaustion).with('pension', pension_ipf, 'TESTERROR') end end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/lighthouse/failure_notification_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lighthouse/failure_notification' require 'va_notify/service' RSpec.describe Lighthouse::FailureNotification, type: :job do subject { described_class } let(:notify_client_stub) { instance_double(VaNotify::Service) } let(:user_account) { create(:user_account) } let(:document_type) { 'L029' } let(:document_description) { 'Copy of a DD214' } let(:filename) { 'docXXXX-XXte.pdf' } let(:icn) { user_account.icn } let(:first_name) { 'Bob' } let(:issue_instant) { Time.now.to_i } let(:formatted_submit_date) do # We want to return all times in EDT timestamp = Time.at(issue_instant).in_time_zone('America/New_York') # We display dates in mailers in the format "May 1, 2024 3:01 p.m. EDT" timestamp.strftime('%B %-d, %Y %-l:%M %P %Z').sub(/([ap])m/, '\1.m.') end let(:date_submitted) { formatted_submit_date } let(:date_failed) { formatted_submit_date } before do allow(Rails.logger).to receive(:info) end context 'when Lighthouse::FailureNotification is called' do it 'enqueues a failure notification mailer to send to the veteran' do allow(VaNotify::Service).to receive(:new) { notify_client_stub } subject.perform_async(icn, first_name, filename, date_submitted, date_failed) do expect(notify_client_stub).to receive(:send_email).with( { recipient_identifier: { id_value: user_account.icn, id_type: 'ICN' }, template_id: 'fake_template_id', personalisation: { first_name:, document_type: document_description, filename: file_name, date_submitted: formatted_submit_date, date_failed: formatted_submit_date } } ) expect(Rails.logger) .to receive(:info) .with('Lighthouse::FailureNotification email sent') end end end context 'when retries are exhausted' do before do allow(Rails.logger).to receive(:info) allow(StatsD).to receive(:increment) end let(:message) { 'Lighthouse::FailureNotification email could not be sent' } let(:statsd_tags) { ['service:claim-status', "function: #{message}"] } it 'logs failure and increments silent_failure metric' do expect(Rails.logger) .to receive(:info) .with(message) Lighthouse::FailureNotification.within_sidekiq_retries_exhausted_block do expect(StatsD).to receive(:increment).with('silent_failure', tags: statsd_tags) end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/lighthouse/poll_form526_pdf_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Lighthouse::PollForm526Pdf, type: :job do subject { described_class } before do Sidekiq::Job.clear_all allow_any_instance_of(BenefitsClaims::Service).to receive(:get_claim) .and_return({ 'data' => { 'attributes' => { 'supportingDocuments' => [] } } }) end describe '.perform_async' do let(:form526_submission) { create(:form526_submission, submitted_claim_id: 1) } context 'successful polling' do it 'logs success when PDF is found' do allow(Flipper).to receive(:enabled?).with(:disability_526_call_received_email_from_polling).and_return(true) allow_any_instance_of(BenefitsClaims::Service).to receive(:get_claim) .and_return( { 'data' => { 'attributes' => { 'supportingDocuments' => [{ 'documentTypeLabel' => 'VA 21-526 Veterans Application for Compensation or Pension' }] } } } ) expect(Rails.logger).to receive(:info).with( 'Form526 Submission', hash_including( 'job_id' => kind_of(String), 'saved_claim_id' => kind_of(Integer), 'service_provider' => nil, 'status' => 'try', 'submission_id' => form526_submission.id ) ) expect(Rails.logger).to receive(:info).with('Form526ConfirmationEmailJob called for user ' \ "#{form526_submission.account.id}, " \ "submission: #{form526_submission.id} from PollForm526Pdf#perform" \ ' pdf_found') expect(Rails.logger).to receive(:info).with( 'Form526 Submission', hash_including( 'job_id' => kind_of(String), 'saved_claim_id' => kind_of(Integer), 'service_provider' => nil, 'status' => 'success', 'submission_id' => form526_submission.id ) ) expect(Rails.logger).to receive(:info).with('Poll for form 526 PDF: PDF found') subject.perform_sync(form526_submission.id) form526_submission.reload job_status = form526_submission.form526_job_statuses.find_by(job_class: 'PollForm526Pdf') job_status.reload expect(job_status.status).to eq 'success' end end context 'pdf not found scenarios' do it 'raises an error and retries when no supporting documents are found and submission is less than 1 day old' do form526_submission.update!(created_at: 12.hours.ago) allow_any_instance_of(BenefitsClaims::Service).to receive(:get_claim) .and_return({ 'data' => { 'attributes' => { 'supportingDocuments' => [] } } }) expect do subject.perform_sync(form526_submission.id) end.to raise_error(Lighthouse::PollForm526PdfError, 'Poll for form 526 PDF: Keep on retrying!') end it 'transitions to pdf_not_found when submission is exactly 4 days old' do form526_submission.update!(created_at: 4.days.ago) expect(Rails.logger).to receive(:warn).with('Poll for form 526 PDF: Submission creation date is over 4 days' \ ' old. Exiting...', hash_including(error_class: 'PollForm526PdfError')) subject.perform_sync(form526_submission.id) form526_submission.reload job_status = form526_submission.form526_job_statuses.find_by(job_class: 'PollForm526Pdf') expect(job_status.status).to eq 'pdf_not_found' end it 'transitions to pdf_not_found status if submission is older than 4 days' do form526_submission.update(created_at: 5.days.ago) expect(Rails.logger).to receive(:warn).with( 'Poll for form 526 PDF: Submission creation date is over 4 days old. Exiting...', { error_class: 'PollForm526PdfError', error_message: 'Poll for form 526 PDF: Submission creation date is over 4 days old. Exiting...', form526_submission_id: form526_submission.id, job_id: kind_of(String), timestamp: kind_of(Time) } ) subject.perform_sync(form526_submission.id) form526_submission.reload job_status = form526_submission.form526_job_statuses.find_by(job_class: 'PollForm526Pdf') job_status.reload expect(job_status.status).to eq 'pdf_not_found' end it 'warns if submission is between 1 and 4 days old' do id = form526_submission.id form526_submission.update!(created_at: 2.days.ago) expect(Rails.logger).to receive(:warn).with( "Poll for form 526 PDF: Submission creation date is over 1 day old for submission_id #{id}", { error_class: 'PollForm526PdfError', error_message: "Poll for form 526 PDF: Submission creation date is over 1 day old for submission_id #{id}", form526_submission_id: id, job_id: kind_of(String), timestamp: kind_of(Time) } ) expect { subject.perform_sync(form526_submission.id) }.to raise_error(Lighthouse::PollForm526PdfError) form526_submission.reload end end context 'when all retries are exhausted' do let(:form526_job_status) { create(:form526_job_status, :poll_form526_pdf, form526_submission:, job_id: 1) } it 'transitions to the pdf_not_found status' do job_params = { 'jid' => form526_job_status.job_id, 'args' => [form526_submission.id] } subject.within_sidekiq_retries_exhausted_block(job_params) do # block is required to use this functionality. true end form526_job_status.reload expect(form526_job_status.status).to eq 'pdf_not_found' end end context 'startedFormVersion missing' do it 'calls polling only for startedFormVersion present, does not retry because the form is there, and triggers confirmation email' do allow_any_instance_of(BenefitsClaims::Service).to receive(:get_claim) .and_return( { 'data' => { 'attributes' => { 'supportingDocuments' => [{ 'documentTypeLabel' => 'VA 21-526 Veterans Application for Compensation or Pension' }] } } } ) allow(Lighthouse::PollForm526Pdf).to receive(:perform_async).with(form526_submission.id).and_call_original expect(Lighthouse::PollForm526Pdf).to receive(:perform_async).with(form526_submission.id) form526_submission.send(:poll_form526_pdf) expect do Lighthouse::PollForm526Pdf.drain job_status = form526_submission.form526_job_statuses.find_by(job_class: 'PollForm526Pdf') job_status.reload expect(job_status.status).to eq 'success' end.not_to raise_error form526_submission.send(:poll_form526_pdf) expect do Lighthouse::PollForm526Pdf.drain end.to change(Form526ConfirmationEmailJob.jobs, :size).by(1) end it 'calls polling only for startedFormVersion present and retries' do allow(Lighthouse::PollForm526Pdf).to receive(:perform_async).with(form526_submission.id).and_call_original expect(Lighthouse::PollForm526Pdf).to receive(:perform_async).with(form526_submission.id) form526_submission.send(:poll_form526_pdf) expect do Lighthouse::PollForm526Pdf.drain job_status = form526_submission.form526_job_statuses.find_by(job_class: 'PollForm526Pdf') job_status.reload expect(job_status.status).to eq 'try' end.to raise_error(Lighthouse::PollForm526PdfError) end it 'does not call polling if startedFormVersion blank' do form = form526_submission.saved_claim.parsed_form form['startedFormVersion'] = nil form526_submission.saved_claim.update(form: form.to_json) expect(Lighthouse::PollForm526Pdf).not_to receive(:perform_async) form526_submission.send(:poll_form526_pdf) end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/lighthouse/submit_benefits_intake_claim_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Lighthouse::SubmitBenefitsIntakeClaim, :uploader_helpers do include StatsD::Instrument::Helpers stub_virus_scan let(:job) { described_class.new } let(:claim) { create(:fake_saved_claim) } describe '#perform' do context 'with SavedClaim::Test' do let(:service) { double('service') } let(:response) { double('response') } let(:pdf_path) { 'random/path/to/pdf' } let(:location) { 'test_location' } let(:notification) { double('notification') } before do stub_const('SavedClaim::Test::FORM', '10-10EZ') job.instance_variable_set(:@claim, claim) allow(SavedClaim).to receive(:find).and_return(claim) allow(BenefitsIntakeService::Service).to receive(:new).and_return(service) allow(service).to receive(:uuid) allow(service).to receive_messages(location:, upload_doc: response) end it 'submits the saved claim successfully' do allow(service).to receive(:valid_document?).and_return(pdf_path) allow(response).to receive(:success?).and_return(true) expect(job).to receive(:create_form_submission_attempt) expect(job).to receive(:generate_metadata).once.and_call_original expect(job).to receive(:send_confirmation_email).once expect(service).to receive(:upload_doc) expect(StatsD).to receive(:increment).with('worker.lighthouse.submit_benefits_intake_claim.success') job.perform(claim.id) expect(response.success?).to be(true) expect(claim.form_submissions).not_to be_nil expect(claim.business_line).not_to be_nil end it 'submits and gets a response error' do allow(service).to receive(:valid_document?).and_return(pdf_path) allow(response).to receive_messages(success?: false, body: 'There was an error submitting the claim') expect(job).to receive(:create_form_submission_attempt) expect(job).to receive(:generate_metadata).once expect(service).to receive(:upload_doc) expect(Rails.logger).to receive(:warn) expect(StatsD).to receive(:increment).with('worker.lighthouse.submit_benefits_intake_claim.failure') expect { job.perform(claim.id) }.to raise_error(Lighthouse::SubmitBenefitsIntakeClaim::BenefitsIntakeClaimError) expect(response.success?).to be(false) end it 'handles an invalid document' do allow(service).to receive(:valid_document?).and_raise(BenefitsIntakeService::Service::InvalidDocumentError) expect(Rails.logger).to receive(:warn) expect(StatsD).to receive(:increment).with( 'worker.lighthouse.submit_benefits_intake_claim.document_upload_error' ) expect(StatsD).to receive(:increment).with('worker.lighthouse.submit_benefits_intake_claim.failure') expect { job.perform(claim.id) }.to raise_error(BenefitsIntakeService::Service::InvalidDocumentError) end end context 'With SavedClaim::Form210779' do let(:va210779claim) { create(:va210779) } let(:job779) { described_class.new } it 'submits the saved claim successfully' do VCR.use_cassette('lighthouse/benefits_claims/submit210779') do Sidekiq::Testing.inline! do expect(job779).to receive(:create_form_submission_attempt) expect(job779).to receive(:generate_metadata).once.and_call_original expect(job779).to receive(:send_confirmation_email).once metrics = capture_statsd_calls do job779.perform(va210779claim.id) end expect(metrics.collect(&:source)).to include( 'saved_claim.create:1|c|#form_id:21-0779,doctype:222', 'worker.lighthouse.submit_benefits_intake_claim.success:1|c' ) expect(va210779claim.form_submissions).not_to be_nil expect(va210779claim.business_line).not_to be_nil end end end end end describe '#process_record' do let(:path) { 'tmp/pdf_path' } let(:service) { double('service') } before do allow(BenefitsIntakeService::Service).to receive(:new).and_return(service) job.init(claim.id) end it 'processes a 21P-530EZ record and add stamps' do record = double allow(record).to receive_messages({ created_at: claim.created_at }) datestamp_double1 = double datestamp_double2 = double double timestamp = claim.created_at expect(record).to receive(:to_pdf).and_return('path1') expect(PDFUtilities::DatestampPdf).to receive(:new).with('path1').and_return(datestamp_double1) expect(datestamp_double1).to receive(:run).with(text: 'VA.GOV', x: 5, y: 5, timestamp:).and_return('path2') expect(PDFUtilities::DatestampPdf).to receive(:new).with('path2').and_return(datestamp_double2) expect(datestamp_double2).to receive(:run).with( text: 'FDC Reviewed - va.gov Submission', x: 400, y: 770, text_only: true ).and_return('path3') expect(service).to receive(:valid_document?).and_return(path) expect(job.process_record(record)).to eq(path) end end describe 'sidekiq_retries_exhausted block' do it 'logs a distinct error when retries are exhausted' do Lighthouse::SubmitBenefitsIntakeClaim.within_sidekiq_retries_exhausted_block do expect(Rails.logger).to receive(:error).exactly(:once) expect(StatsD).to receive(:increment).with('worker.lighthouse.submit_benefits_intake_claim.exhausted') end end end # Rspec.describe end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/lighthouse/form526_document_upload_polling_job_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Lighthouse::Form526DocumentUploadPollingJob, type: :job do before do Sidekiq::Job.clear_all # NOTE: to re-record the VCR cassettes for these tests: # 1. Comment out the line below stubbing the token # 2. Include both a valid Lighthouse client_id and rsa_key in config/settings/test.local.yml: # lighthouse: # auth: # ccg: # client_id: <MY CLIENT ID> # rsa_key: <MY RSA KEY PATH> # To generate the above credentials refer to this tutorial: # https://developer.va.gov/explore/api/benefits-documents/client-credentials allow_any_instance_of(BenefitsDocuments::Configuration).to receive(:access_token).and_return('abcd1234') allow(Flipper).to receive(:enabled?).and_call_original end describe '#perform' do shared_examples 'document status updates' do |state, request_id, cassette| around { |example| VCR.use_cassette(cassette, match_requests_on: [:body]) { example.run } } let!(:document) { create(:lighthouse526_document_upload, lighthouse_document_request_id: request_id) } it 'updates document status' do described_class.new.perform expect(document.reload.aasm_state).to eq(state) expect(document.reload.lighthouse_processing_ended_at).not_to be_nil expect(document.reload.last_status_response).not_to be_nil end it 'saves the status_last_polled_at time' do polling_time = DateTime.new(1985, 10, 26).utc Timecop.freeze(polling_time) do described_class.new.perform expect(document.reload.status_last_polled_at).to eq(polling_time) end end end # End-to-end integration test - completion context 'for a document that has completed' do # Completed Lighthouse QA environment document requestId provided by Lighthouse for end-to-end testing it_behaves_like 'document status updates', 'completed', '22', 'lighthouse/benefits_claims/documents/form526_document_upload_status_complete' end context 'for a document that has failed' do # Failed Lighthouse QA environment document requestId provided by Lighthouse for end-to-end testing it_behaves_like 'document status updates', 'failed', '16819', 'lighthouse/benefits_claims/documents/form526_document_upload_status_failed' end context 'for a single document request whose status is not found' do # Non-existent Lighthouse QA environment document requestId let!(:unknown_document) { create(:lighthouse526_document_upload, lighthouse_document_request_id: '21') } let(:error_body) do { 'errors' => [{ 'detail' => 'Upload Request Async Status Not Found', 'status' => 404, 'title' => 'Not Found', 'instance' => '062dd917-a229-42d7-ad39-741eb81766a8', 'diagnostics' => '7YODuWbVvC0k+iFgaQC0SrlARmYKPKz4' }] } end around do |example| VCR.use_cassette('lighthouse/benefits_claims/documents/form526_document_upload_status_not_found', match_requests_on: [:body]) do example.run end end it 'increments a StatsD counter and logs error' do expect(StatsD).to receive(:increment).with('worker.lighthouse.poll_form526_document_uploads.polling_error') Timecop.freeze(Time.new(1985, 10, 26).utc) do expect(Rails.logger).to receive(:warn).with( 'Lighthouse::Form526DocumentUploadPollingJob status endpoint error', hash_including(response_status: 404, response_body: error_body, lighthouse_document_request_ids: [unknown_document.lighthouse_document_request_id]) ) described_class.new.perform end end end context 'for a document with status and another document whose request id is not found' do let!(:complete_document) { create(:lighthouse526_document_upload, lighthouse_document_request_id: '22') } let!(:unknown_document) { create(:lighthouse526_document_upload, lighthouse_document_request_id: '21') } around do |example| VCR.use_cassette('lighthouse/benefits_claims/documents/form526_document_upload_with_request_ids_not_found', match_requests_on: [:body]) do example.run end end it 'increments StatsD counters for both documents and logs unknown document error' do expect(StatsD).to receive(:increment) .with('api.form526.lighthouse_document_upload_processing_status.bdd_instructions.complete').ordered expect(StatsD).to receive(:increment) .with('worker.lighthouse.poll_form526_document_uploads.polling_error').ordered Timecop.freeze(Time.new(1985, 10, 26).utc) do expect(Rails.logger).to receive(:warn).with( 'Lighthouse::Form526DocumentUploadPollingJob status endpoint error', hash_including(response_status: 404, response_body: 'Upload Request Async Status Not Found', lighthouse_document_request_ids: [unknown_document.lighthouse_document_request_id]) ) described_class.new.perform end end end context 'non-200 failure response from Lighthouse' do let!(:pending_document) { create(:lighthouse526_document_upload) } # Error body example from: https://dev-developer.va.gov/explore/api/benefits-documents/docs?version=current let(:error_body) { { 'errors' => [{ 'detail' => 'Code must match \'^[A-Z]{2}$\'', 'status' => 400 }] } } let(:error_response) { Faraday::Response.new(response_body: error_body, status: 400) } before do allow(BenefitsDocuments::Form526::DocumentsStatusPollingService) .to receive(:call).and_return(error_response) end it 'increments a StatsD counter and logs error' do expect(StatsD).to receive(:increment).with('worker.lighthouse.poll_form526_document_uploads.polling_error') Timecop.freeze(Time.new(1985, 10, 26).utc) do expect(Rails.logger).to receive(:warn).with( 'Lighthouse::Form526DocumentUploadPollingJob status endpoint error', hash_including(response_status: 400, response_body: error_body, lighthouse_document_request_ids: [pending_document.lighthouse_document_request_id]) ) described_class.new.perform end end end context 'retries exhausted' do it 'updates the exhaustion StatsD counter' do described_class.within_sidekiq_retries_exhausted_block do expect(StatsD).to receive(:increment).with('worker.lighthouse.poll_form526_document_uploads.exhausted') end end it 'logs exhaustion metadata to the Rails logger' do exhaustion_time = DateTime.new(1985, 10, 26).utc sidekiq_exhaustion_metadata = { 'jid' => 8_675_309, 'error_class' => 'BROKESKI', 'error_message' => 'We are going to need a bigger boat' } Timecop.freeze(exhaustion_time) do described_class.within_sidekiq_retries_exhausted_block(sidekiq_exhaustion_metadata) do expect(Rails.logger).to receive(:warn).with( 'Lighthouse::Form526DocumentUploadPollingJob retries exhausted', { job_id: 8_675_309, error_class: 'BROKESKI', error_message: 'We are going to need a bigger boat', timestamp: exhaustion_time } ) end end end end describe 'Documents Polling' do let(:faraday_response) { instance_double(Faraday::Response, body: {}, status: 200) } let(:polling_service) { BenefitsDocuments::Form526::DocumentsStatusPollingService } let(:polling_time) { DateTime.new(1985, 10, 26).utc } before do # Verifies correct info is being passed to both services allow(BenefitsDocuments::Form526::DocumentsStatusPollingService) .to receive(:call).and_return(faraday_response) allow(BenefitsDocuments::Form526::UpdateDocumentsStatusService) .to receive(:call).and_return(success: true, response: { status: 200 }) end context 'for a pending document' do around { |example| Timecop.freeze(polling_time) { example.run } } it 'polls for unpolled and repoll documents' do documents = [ create(:lighthouse526_document_upload), create(:lighthouse526_document_upload, status_last_polled_at: polling_time - 2.hours) ] document_request_ids = documents.map(&:lighthouse_document_request_id) expect(polling_service).to receive(:call).with(document_request_ids) described_class.new.perform end it 'does not poll for recently polled documents' do recently_polled_document = create(:lighthouse526_document_upload, status_last_polled_at: polling_time - 42.minutes) expect(polling_service).not_to receive(:call) .with([recently_polled_document.lighthouse_document_request_id]) described_class.new.perform end end context 'for completed and failed documents' do let!(:documents) do [ create(:lighthouse526_document_upload, aasm_state: 'completed', status_last_polled_at: polling_time - 2.hours), create(:lighthouse526_document_upload, aasm_state: 'failed', status_last_polled_at: polling_time - 2.hours) ] end it 'does not poll for completed or failed documents' do documents.each do |doc| expect(polling_service).not_to receive(:call).with([doc.lighthouse_document_request_id]) end described_class.new.perform end end end describe 'Document Polling Logging' do context 'for pending documents' do let!(:pending_polling_documents) { create_list(:lighthouse526_document_upload, 2, aasm_state: 'pending') } let!(:pending_recently_polled_document) do create( :lighthouse526_document_upload, aasm_state: 'pending', status_last_polled_at: polling_time - 45.minutes ) end let(:polling_time) { DateTime.new(1985, 10, 26).utc } let(:faraday_response) do instance_double( Faraday::Response, body: { 'data' => { 'statuses' => [ { 'requestId' => pending_polling_documents.first.lighthouse_document_request_id, 'time' => { 'startTime' => 1_502_199_000, 'endTime' => 1_502_199_000 }, 'status' => 'SUCCESS' }, { 'requestId' => pending_polling_documents[1].lighthouse_document_request_id, 'time' => { 'startTime' => 1_502_199_000, 'endTime' => 1_502_199_000 }, 'status' => 'FAILED', 'error' => { 'detail' => 'Something went wrong', 'step' => 'BENEFITS_GATEWAY_SERVICE' } } ], 'requestIdsNotFound' => [ 0 ] } }, status: 200 ) end around { |example| Timecop.freeze(polling_time) { example.run } } before do allow(BenefitsDocuments::Form526::DocumentsStatusPollingService) .to receive(:call).and_return(faraday_response) # StatsD will receive multiple gauge calls in this code flow allow(StatsD).to receive(:gauge) end describe 'polled documents metric' do it 'increments a StatsD gauge metric with total documents polled, discluding recently polled documents' do expect(StatsD).to receive(:gauge) .with('worker.lighthouse.poll_form526_document_uploads.pending_documents_polled', 2) described_class.new.perform end end describe 'completed and failed documents' do let!(:existing_completed_documents) do create_list(:lighthouse526_document_upload, 2, aasm_state: 'completed') end let!(:existing_failed_documents) { create_list(:lighthouse526_document_upload, 2, aasm_state: 'failed') } it 'increments a StatsD gauge metric with the total number of documents marked complete' do # Should only count documents newly counted success expect(StatsD).to receive(:gauge) .with('worker.lighthouse.poll_form526_document_uploads.pending_documents_marked_completed', 1) described_class.new.perform end it 'increments a StatsD gauge metric with the total number of documents marked failed' do # Should only count documents newly counted failed expect(StatsD).to receive(:gauge) .with('worker.lighthouse.poll_form526_document_uploads.pending_documents_marked_failed', 1) described_class.new.perform end end end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/lighthouse/submit_career_counseling_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'pcpg/monitor' RSpec.describe Lighthouse::SubmitCareerCounselingJob do let(:claim) { create(:education_career_counseling_claim) } let(:job) { described_class.new } let(:monitor) { double('monitor') } let(:exhaustion_msg) do { 'args' => [], 'class' => 'Lighthouse::SubmitCareerCounselingJob', 'error_message' => 'An error occurred', 'queue' => 'default' } end let(:user_account_uuid) { 123 } describe '#perform' do it 'sends to central mail' do expect_any_instance_of(SavedClaim::EducationCareerCounselingClaim).to receive(:send_to_benefits_intake!) job.perform(claim.id) end it 'sends confirmation email' do allow_any_instance_of(SavedClaim::EducationCareerCounselingClaim).to receive(:send_to_benefits_intake!) expect(job).to receive(:send_confirmation_email).with(nil) job.perform(claim.id) end end describe '#send_confirmation_email' do context 'user logged in' do let(:user) { create(:evss_user, :loa3) } it 'calls the VA notify email job with the user email' do expect(VANotify::EmailJob).to receive(:perform_async).with( user.va_profile_email, 'career_counseling_confirmation_email_template_id', { 'date' => Time.zone.today.strftime('%B %d, %Y'), 'first_name' => 'DERRICK' } ) job.instance_variable_set(:@claim, claim) job.send_confirmation_email(user.uuid) end end context 'user not logged in' do it 'calls the VA notify email job with the claimant email' do expect(VANotify::EmailJob).to receive(:perform_async).with( 'foo@foo.com', 'career_counseling_confirmation_email_template_id', { 'date' => Time.zone.today.strftime('%B %d, %Y'), 'first_name' => 'DERRICK' } ) job.instance_variable_set(:@claim, claim) job.send_confirmation_email(nil) end end end describe 'sidekiq_retries_exhausted block with flipper on' do before do Flipper.enable(:form27_8832_action_needed_email) allow(PCPG::Monitor).to receive(:new).and_return(monitor) allow(monitor).to receive :track_submission_exhaustion end it 'logs error when retries are exhausted' do Lighthouse::SubmitCareerCounselingJob.within_sidekiq_retries_exhausted_block( { 'args' => [claim.id, user_account_uuid] } ) do expect(SavedClaim).to receive(:find).with(claim.id).and_return(claim) exhaustion_msg['args'] = [claim.id, user_account_uuid] expect(monitor).to receive(:track_submission_exhaustion).with(exhaustion_msg, claim, 'foo@foo.com') expect(VANotify::EmailJob).to receive(:perform_async).with( 'foo@foo.com', 'form27_8832_action_needed_email_template_id', { 'first_name' => 'DERRICK', 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'confirmation_number' => claim.confirmation_number } ) end end it 'logs error when retries are exhausted with no email' do Lighthouse::SubmitCareerCounselingJob.within_sidekiq_retries_exhausted_block( { 'args' => [claim.id, user_account_uuid] } ) do expect(SavedClaim).to receive(:find).with(claim.id).and_return(claim) exhaustion_msg['args'] = [claim.id, user_account_uuid] claim.parsed_form['claimantInformation'].delete('emailAddress') expect(monitor).to receive(:track_submission_exhaustion).with(exhaustion_msg, claim, nil) end end end end
0
code_files/vets-api-private/spec/sidekiq/lighthouse
code_files/vets-api-private/spec/sidekiq/lighthouse/benefits_intake/submit_central_form686c_job_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Lighthouse::BenefitsIntake::SubmitCentralForm686cJob, :uploader_helpers do stub_virus_scan subject(:job) { described_class.new } before do allow(PdfFill::Filler) .to receive(:fill_form) { |saved_claim, *_| "tmp/pdfs/686C-674_#{saved_claim.id || 'stub'}_final.pdf" } end let(:user) { create(:evss_user, :loa3) } let(:claim) { create(:dependency_claim) } let(:claim_v2) { create(:dependency_claim_v2) } let(:all_flows_payload) { build(:form_686c_674_kitchen_sink) } let(:all_flows_payload_v2) { build(:form686c_674_v2) } let(:birth_date) { '1809-02-12' } let(:vet_info) do { 'veteran_information' => { 'full_name' => { 'first' => 'Mark', 'middle' => 'A', 'last' => 'Webb' }, 'common_name' => 'Mark', 'participant_id' => '600061742', 'uuid' => user.uuid, 'email' => 'vets.gov.user+228@gmail.com', 'va_profile_email' => 'vets.gov.user+228@gmail.com', 'ssn' => '796104437', 'va_file_number' => '796104437', 'icn' => user.icn, 'birth_date' => '1950-10-04' } } end let(:encrypted_vet_info) { KmsEncrypted::Box.new.encrypt(vet_info.to_json) } let(:central_mail_submission) { claim.central_mail_submission } let(:central_mail_submission_v2) { claim_v2.central_mail_submission } let(:user_struct) do OpenStruct.new( first_name: vet_info['veteran_information']['full_name']['first'], last_name: vet_info['veteran_information']['full_name']['last'], middle_name: vet_info['veteran_information']['full_name']['middle'], ssn: vet_info['veteran_information']['ssn'], email: vet_info['veteran_information']['email'], va_profile_email: vet_info['veteran_information']['va_profile_email'], participant_id: vet_info['veteran_information']['participant_id'], icn: vet_info['veteran_information']['icn'], uuid: vet_info['veteran_information']['uuid'], common_name: vet_info['veteran_information']['common_name'] ) end let(:encrypted_user_struct) { KmsEncrypted::Box.new.encrypt(user_struct.to_h.to_json) } let(:monitor) { double('monitor') } let(:exhaustion_msg) do { 'queue' => 'default', 'args' => [], 'class' => 'Lighthouse::BenefitsIntake::SubmitCentralForm686cJob', 'error_message' => 'An error occurred' } end context 'with va_dependents_v2 disabled' do before do allow(Flipper).to receive(:enabled?).with(:saved_claim_pdf_overflow_tracking).and_return(true) end describe '#perform' do let(:success) { true } let(:path) { 'tmp/pdf_path' } let(:lighthouse_mock) { double(:lighthouse_service) } before do expect(BenefitsIntakeService::Service).to receive(:new) .with(with_upload_location: true) .and_return(lighthouse_mock) expect(lighthouse_mock).to receive(:uuid).and_return('uuid') datestamp_double1 = double datestamp_double2 = double datestamp_double3 = double timestamp = claim.created_at expect(SavedClaim::DependencyClaim).to receive(:find).with(claim.id).and_return(claim).at_least(:once) expect(claim).to receive(:to_pdf).and_return('path1') expect(PDFUtilities::DatestampPdf).to receive(:new).with('path1').and_return(datestamp_double1) expect(datestamp_double1).to receive(:run).with(text: 'VA.GOV', x: 5, y: 5, timestamp:).and_return('path2') expect(PDFUtilities::DatestampPdf).to receive(:new).with('path2').and_return(datestamp_double2) expect(datestamp_double2).to receive(:run).with( text: 'FDC Reviewed - va.gov Submission', x: 400, y: 770, text_only: true ).and_return('path3') expect(PDFUtilities::DatestampPdf).to receive(:new).with('path3').and_return(datestamp_double3) expect(datestamp_double3).to receive(:run).with( text: 'Application Submitted on va.gov', x: 400, y: 675, text_only: true, timestamp:, page_number: 6, template: 'lib/pdf_fill/forms/pdfs/686C-674.pdf', multistamp: true ).and_return(path) data = JSON.parse('{"id":"6d8433c1-cd55-4c24-affd-f592287a7572","type":"document_upload"}') expect(lighthouse_mock).to receive(:upload_form).with( main_document: { file: path, file_name: 'pdf_path' }, attachments: [], form_metadata: hash_including(file_number: '796104437') ).and_return(OpenStruct.new(success?: success, data:)) expect(Common::FileHelpers).to receive(:delete_file_if_exists).with(path) expect(FormSubmission).to receive(:create).with( form_type: '686C-674', saved_claim: claim, user_account: user.user_account ).and_return(FormSubmission.new) expect(FormSubmissionAttempt).to receive(:create).with(form_submission: an_instance_of(FormSubmission), benefits_intake_uuid: 'uuid') end context 'with an response error' do let(:success) { false } it 'raises BenefitsIntakeResponseError and updates submission to failed' do mailer_double = double('Mail::Message') allow(mailer_double).to receive(:deliver_now) expect(claim).to receive(:submittable_686?).and_return(true).exactly(:twice) expect(claim).to receive(:submittable_674?).and_return(false) expect { subject.perform(claim.id, encrypted_vet_info, encrypted_user_struct) }.to raise_error(Lighthouse::BenefitsIntake::SubmitCentralForm686cJob::BenefitsIntakeResponseError) # rubocop:disable Layout/LineLength expect(central_mail_submission.reload.state).to eq('failed') end end it 'submits the saved claim and updates submission to success' do vanotify = double(send_email: true) api_key = 'fake_secret' callback_options = { callback_klass: 'Dependents::NotificationCallback', callback_metadata: { email_template_id: 'fake_received686', email_type: :received686, form_id: '686C-674', claim_id: claim.id, saved_claim_id: claim.id, service_name: 'dependents' } } personalization = { 'confirmation_number' => claim.confirmation_number, 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'first_name' => 'MARK' } expect(VaNotify::Service).to receive(:new).with(api_key, callback_options).and_return(vanotify) expect(vanotify).to receive(:send_email).with( { email_address: user_struct.va_profile_email, template_id: 'fake_received686', personalisation: personalization }.compact ) # expect(VANotify::EmailJob).to receive(:perform_async).with( # user_struct.va_profile_email, # 'fake_received686', # { 'confirmation_number' => claim.confirmation_number, # 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), # 'first_name' => 'MARK' }, # 'fake_secret', # { callback_klass: 'Dependents::NotificationCallback', # callback_metadata: { email_template_id: 'fake_received686', # email_type: :received686, # form_id: '686C-674', # saved_claim_id: claim.id, # service_name: 'dependents' } } # ) expect(claim).to receive(:submittable_686?).and_return(true).exactly(4).times expect(claim).to receive(:submittable_674?).and_return(false).at_least(:once) subject.perform(claim.id, encrypted_vet_info, encrypted_user_struct) expect(central_mail_submission.reload.state).to eq('success') end end describe '#process_pdf' do timestamp = Time.zone.now subject { job.process_pdf('path1', timestamp, '686C-674') } it 'processes a record and add stamps' do datestamp_double1 = double datestamp_double2 = double datestamp_double3 = double expect(PDFUtilities::DatestampPdf).to receive(:new).with('path1').and_return(datestamp_double1) expect(datestamp_double1).to receive(:run).with(text: 'VA.GOV', x: 5, y: 5, timestamp:).and_return('path2') expect(PDFUtilities::DatestampPdf).to receive(:new).with('path2').and_return(datestamp_double2) expect(datestamp_double2).to receive(:run).with( text: 'FDC Reviewed - va.gov Submission', x: 400, y: 770, text_only: true ).and_return('path3') expect(PDFUtilities::DatestampPdf).to receive(:new).with('path3').and_return(datestamp_double3) expect(datestamp_double3).to receive(:run).with( text: 'Application Submitted on va.gov', x: 400, y: 675, text_only: true, timestamp:, page_number: 6, template: 'lib/pdf_fill/forms/pdfs/686C-674.pdf', multistamp: true ).and_return('path4') expect(subject).to eq('path4') end end describe '#get_hash_and_pages' do it 'gets sha and number of pages' do expect(Digest::SHA256).to receive(:file).with('path').and_return( OpenStruct.new(hexdigest: 'hexdigest') ) expect(PdfInfo::Metadata).to receive(:read).with('path').and_return( OpenStruct.new(pages: 2) ) expect(described_class.new.get_hash_and_pages('path')).to eq( hash: 'hexdigest', pages: 2 ) end end describe '#generate_metadata' do subject { job.generate_metadata } before do job.instance_variable_set('@claim', claim) job.instance_variable_set('@form_path', 'pdf_path') job.instance_variable_set('@attachment_paths', ['attachment_path']) expect(Digest::SHA256).to receive(:file).with('pdf_path').and_return( OpenStruct.new(hexdigest: 'hash1') ) expect(PdfInfo::Metadata).to receive(:read).with('pdf_path').and_return( OpenStruct.new(pages: 1) ) expect(Digest::SHA256).to receive(:file).with('attachment_path').and_return( OpenStruct.new(hexdigest: 'hash2') ) expect(PdfInfo::Metadata).to receive(:read).with('attachment_path').and_return( OpenStruct.new(pages: 2) ) end context 'with a non us address' do before do form = JSON.parse(claim.form) form['dependents_application']['veteran_contact_information']['veteran_address']['country_name'] = 'AGO' claim.form = form.to_json claim.send(:remove_instance_variable, :@parsed_form) end it 'generates metadata with 00000 for zipcode' do expect(subject['zipCode']).to eq('00000') end end it 'generates the metadata', run_at: '2017-01-04 03:00:00 EDT' do expect(subject).to eq( 'veteranFirstName' => vet_info['veteran_information']['full_name']['first'], 'veteranLastName' => vet_info['veteran_information']['full_name']['last'], 'fileNumber' => vet_info['veteran_information']['va_file_number'], 'receiveDt' => '2017-01-04 01:00:00', 'zipCode' => '21122', 'uuid' => claim.guid, 'source' => 'va.gov', 'hashV' => 'hash1', 'numberAttachments' => 1, 'docType' => '686C-674', 'numberPages' => 1, 'ahash1' => 'hash2', 'numberPages1' => 2 ) end end end context 'with va_dependents_v2 enabled' do before do allow(Flipper).to receive(:enabled?).with(anything).and_call_original allow(Flipper).to receive(:enabled?).with(:saved_claim_pdf_overflow_tracking).and_return(true) end describe '#perform' do let(:success) { true } let(:path) { 'tmp/pdf_path' } let(:lighthouse_mock) { double(:lighthouse_service) } before do expect(BenefitsIntakeService::Service).to receive(:new) .with(with_upload_location: true) .and_return(lighthouse_mock) expect(lighthouse_mock).to receive(:uuid).and_return('uuid') datestamp_double1 = double datestamp_double2 = double datestamp_double3 = double timestamp = claim.created_at expect(SavedClaim::DependencyClaim).to receive(:find).with(claim.id).and_return(claim).at_least(:once) expect(claim).to receive(:to_pdf).and_return('path1') expect(PDFUtilities::DatestampPdf).to receive(:new).with('path1').and_return(datestamp_double1) expect(datestamp_double1).to receive(:run).with(text: 'VA.GOV', x: 5, y: 5, timestamp:).and_return('path2') expect(PDFUtilities::DatestampPdf).to receive(:new).with('path2').and_return(datestamp_double2) expect(datestamp_double2).to receive(:run).with( text: 'FDC Reviewed - va.gov Submission', x: 400, y: 770, text_only: true ).and_return('path3') expect(PDFUtilities::DatestampPdf).to receive(:new).with('path3').and_return(datestamp_double3) expect(datestamp_double3).to receive(:run).with( text: 'Application Submitted on va.gov', x: 400, y: 675, text_only: true, timestamp:, page_number: 6, template: 'lib/pdf_fill/forms/pdfs/686C-674.pdf', multistamp: true ).and_return(path) data = JSON.parse('{"id":"6d8433c1-cd55-4c24-affd-f592287a7572","type":"document_upload"}') expect(lighthouse_mock).to receive(:upload_form).with( main_document: { file: path, file_name: 'pdf_path' }, attachments: [], form_metadata: hash_including(file_number: '796104437') ).and_return(OpenStruct.new(success?: success, data:)) expect(Common::FileHelpers).to receive(:delete_file_if_exists).with(path) expect(FormSubmission).to receive(:create).with( form_type: '686C-674', saved_claim: claim, user_account: user.user_account ).and_return(FormSubmission.new) expect(FormSubmissionAttempt).to receive(:create).with(form_submission: an_instance_of(FormSubmission), benefits_intake_uuid: 'uuid') end context 'with an response error' do let(:success) { false } it 'raises BenefitsIntakeResponseError and updates submission to failed' do mailer_double = double('Mail::Message') allow(mailer_double).to receive(:deliver_now) expect(claim).to receive(:submittable_686?).and_return(true).exactly(:twice) expect(claim).to receive(:submittable_674?).and_return(false) expect { subject.perform(claim.id, encrypted_vet_info, encrypted_user_struct) }.to raise_error(Lighthouse::BenefitsIntake::SubmitCentralForm686cJob::BenefitsIntakeResponseError) # rubocop:disable Layout/LineLength expect(central_mail_submission.reload.state).to eq('failed') end end it 'submits the saved claim and updates submission to success' do vanotify = double(send_email: true) callback_options = { callback_klass: 'Dependents::NotificationCallback', callback_metadata: { email_template_id: 'fake_received686', email_type: :received686, form_id: '686C-674', claim_id: claim.id, saved_claim_id: claim.id, service_name: 'dependents' } } personalization = { 'confirmation_number' => claim.confirmation_number, 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'first_name' => 'MARK' } expect(VaNotify::Service).to receive(:new).with('fake_secret', callback_options).and_return(vanotify) expect(vanotify).to receive(:send_email).with( { email_address: user_struct.va_profile_email, template_id: 'fake_received686', personalisation: personalization }.compact ) # expect(VANotify::EmailJob).to receive(:perform_async).with( # user_struct.va_profile_email, # 'fake_received686', # { 'confirmation_number' => claim.confirmation_number, # 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), # 'first_name' => 'MARK' }, # 'fake_secret', # { callback_klass: 'Dependents::NotificationCallback', # callback_metadata: { email_template_id: 'fake_received686', # email_type: :received686, # form_id: '686C-674', # saved_claim_id: claim.id, # service_name: 'dependents' } } # ) expect(claim).to receive(:submittable_686?).and_return(true).exactly(4).times expect(claim).to receive(:submittable_674?).and_return(false).at_least(:once) subject.perform(claim.id, encrypted_vet_info, encrypted_user_struct) expect(central_mail_submission.reload.state).to eq('success') end end describe '#process_pdf' do timestamp = Time.zone.now subject { job.process_pdf('path1', timestamp, '686C-674') } it 'processes a record and add stamps' do datestamp_double1 = double datestamp_double2 = double datestamp_double3 = double expect(PDFUtilities::DatestampPdf).to receive(:new).with('path1').and_return(datestamp_double1) expect(datestamp_double1).to receive(:run).with(text: 'VA.GOV', x: 5, y: 5, timestamp:).and_return('path2') expect(PDFUtilities::DatestampPdf).to receive(:new).with('path2').and_return(datestamp_double2) expect(datestamp_double2).to receive(:run).with( text: 'FDC Reviewed - va.gov Submission', x: 400, y: 770, text_only: true ).and_return('path3') expect(PDFUtilities::DatestampPdf).to receive(:new).with('path3').and_return(datestamp_double3) expect(datestamp_double3).to receive(:run).with( text: 'Application Submitted on va.gov', x: 400, y: 675, text_only: true, timestamp:, page_number: 6, template: 'lib/pdf_fill/forms/pdfs/686C-674.pdf', multistamp: true ).and_return('path4') expect(subject).to eq('path4') end end describe '#get_hash_and_pages' do it 'gets sha and number of pages' do expect(Digest::SHA256).to receive(:file).with('path').and_return( OpenStruct.new(hexdigest: 'hexdigest') ) expect(PdfInfo::Metadata).to receive(:read).with('path').and_return( OpenStruct.new(pages: 2) ) expect(described_class.new.get_hash_and_pages('path')).to eq( hash: 'hexdigest', pages: 2 ) end end describe '#generate_metadata' do subject { job.generate_metadata } before do job.instance_variable_set('@claim', claim) job.instance_variable_set('@form_path', 'pdf_path') job.instance_variable_set('@attachment_paths', ['attachment_path']) expect(Digest::SHA256).to receive(:file).with('pdf_path').and_return( OpenStruct.new(hexdigest: 'hash1') ) expect(PdfInfo::Metadata).to receive(:read).with('pdf_path').and_return( OpenStruct.new(pages: 1) ) expect(Digest::SHA256).to receive(:file).with('attachment_path').and_return( OpenStruct.new(hexdigest: 'hash2') ) expect(PdfInfo::Metadata).to receive(:read).with('attachment_path').and_return( OpenStruct.new(pages: 2) ) end context 'with a non us address' do before do form = JSON.parse(claim.form) form['dependents_application']['veteran_contact_information']['veteran_address']['country_name'] = 'AGO' claim.form = form.to_json claim.send(:remove_instance_variable, :@parsed_form) end it 'generates metadata with 00000 for zipcode' do expect(subject['zipCode']).to eq('00000') end end it 'generates the metadata', run_at: '2017-01-04 03:00:00 EDT' do expect(subject).to eq( 'veteranFirstName' => vet_info['veteran_information']['full_name']['first'], 'veteranLastName' => vet_info['veteran_information']['full_name']['last'], 'fileNumber' => vet_info['veteran_information']['va_file_number'], 'receiveDt' => '2017-01-04 01:00:00', 'zipCode' => '21122', 'uuid' => claim.guid, 'source' => 'va.gov', 'hashV' => 'hash1', 'numberAttachments' => 1, 'docType' => '686C-674', 'numberPages' => 1, 'ahash1' => 'hash2', 'numberPages1' => 2 ) end end end context 'sidekiq_retries_exhausted' do context 'successful exhaustion processing' do it 'tracks exhaustion event and sends backup submission' do msg = { 'args' => [claim.id, user.uuid, encrypted_user_struct], 'error_message' => 'Connection timeout' } error = StandardError.new('Job failed') # Make find return the same claim instance allow(SavedClaim::DependencyClaim).to receive(:find).with(claim.id).and_return(claim) # Mock the monitor monitor_double = instance_double(Dependents::Monitor) expect(Dependents::Monitor).to receive(:new).with(claim.id).and_return(monitor_double) # Expect the monitor to track the exhaustion event expect(monitor_double).to receive(:track_submission_exhaustion).with(msg, 'vets.gov.user+228@gmail.com') # Expect the claim to send a failure email expect(claim).to receive(:send_failure_email).with('vets.gov.user+228@gmail.com') # Call the sidekiq_retries_exhausted callback described_class.sidekiq_retries_exhausted_block.call(msg, error) end end context 'failed exhaustion processing' do it 'logs silent failure when an exception occurs' do msg = { 'args' => [claim.id, user.uuid, encrypted_user_struct], 'error_message' => 'Connection timeout' } error = StandardError.new('Job failed') json_error = StandardError.new('JSON parse error') # Make find return the same claim instance allow(JSON).to receive(:parse).and_raise(json_error) expect(Rails.logger) .to receive(:error) .with( 'Lighthouse::BenefitsIntake::SubmitCentralForm686cJob silent failure!', { e: json_error, msg:, v2: false } ) expect(StatsD) .to receive(:increment) .with("#{described_class::STATSD_KEY_PREFIX}.silent_failure") # Call the sidekiq_retries_exhausted callback described_class.sidekiq_retries_exhausted_block.call(msg, error) end end end end
0
code_files/vets-api-private/spec/sidekiq/lighthouse
code_files/vets-api-private/spec/sidekiq/lighthouse/benefits_intake/submit_central_form686c_v2_job_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Lighthouse::BenefitsIntake::SubmitCentralForm686cV2Job, :uploader_helpers do stub_virus_scan subject(:job) { described_class.new } before do allow(PdfFill::Filler) .to receive(:fill_form) { |saved_claim, *_| "tmp/pdfs/686C-674_#{saved_claim.id || 'stub'}_final.pdf" } end let(:user) { create(:evss_user, :loa3) } let(:claim) { create(:dependency_claim) } let(:claim_v2) { create(:dependency_claim_v2) } let(:all_flows_payload) { build(:form_686c_674_kitchen_sink) } let(:all_flows_payload_v2) { build(:form686c_674_v2) } let(:birth_date) { '1809-02-12' } let(:vet_info) do { 'veteran_information' => { 'full_name' => { 'first' => 'Mark', 'middle' => 'A', 'last' => 'Webb' }, 'common_name' => 'Mark', 'participant_id' => '600061742', 'uuid' => user.uuid, 'email' => 'vets.gov.user+228@gmail.com', 'va_profile_email' => 'vets.gov.user+228@gmail.com', 'ssn' => '796104437', 'va_file_number' => '796104437', 'icn' => user.icn, 'birth_date' => '1950-10-04' } } end let(:encrypted_vet_info) { KmsEncrypted::Box.new.encrypt(vet_info.to_json) } let(:central_mail_submission) { claim.central_mail_submission } let(:central_mail_submission_v2) { claim_v2.central_mail_submission } let(:user_struct) do OpenStruct.new( first_name: vet_info['veteran_information']['full_name']['first'], last_name: vet_info['veteran_information']['full_name']['last'], middle_name: vet_info['veteran_information']['full_name']['middle'], ssn: vet_info['veteran_information']['ssn'], email: vet_info['veteran_information']['email'], va_profile_email: vet_info['veteran_information']['va_profile_email'], participant_id: vet_info['veteran_information']['participant_id'], icn: vet_info['veteran_information']['icn'], uuid: vet_info['veteran_information']['uuid'], common_name: vet_info['veteran_information']['common_name'] ) end let(:encrypted_user_struct) { KmsEncrypted::Box.new.encrypt(user_struct.to_h.to_json) } let(:monitor) { double('monitor') } let(:exhaustion_msg) do { 'queue' => 'default', 'args' => [], 'class' => 'Lighthouse::BenefitsIntake::SubmitCentralForm686cV2Job', 'error_message' => 'An error occurred' } end context 'with overflow tracking enabled' do before do allow(Flipper).to receive(:enabled?).with(anything).and_call_original allow(Flipper).to receive(:enabled?).with(:saved_claim_pdf_overflow_tracking).and_return(true) end describe '#perform' do let(:success) { true } let(:path) { 'tmp/pdf_path' } let(:lighthouse_mock) { double(:lighthouse_service) } before do expect(BenefitsIntakeService::Service).to receive(:new) .with(with_upload_location: true) .and_return(lighthouse_mock) expect(lighthouse_mock).to receive(:uuid).and_return('uuid') datestamp_double1 = double datestamp_double2 = double datestamp_double3 = double timestamp = claim_v2.created_at expect(SavedClaim::DependencyClaim).to receive(:find).with(claim_v2.id).and_return(claim_v2).at_least(:once) expect(claim_v2).to receive(:to_pdf).and_return('path1') expect(PDFUtilities::DatestampPdf).to receive(:new).with('path1').and_return(datestamp_double1) expect(datestamp_double1).to receive(:run).with(text: 'VA.GOV', x: 5, y: 5, timestamp:).and_return('path2') expect(PDFUtilities::DatestampPdf).to receive(:new).with('path2').and_return(datestamp_double2) expect(datestamp_double2).to receive(:run).with( text: 'FDC Reviewed - va.gov Submission', x: 400, y: 770, text_only: true ).and_return('path3') expect(PDFUtilities::DatestampPdf).to receive(:new).with('path3').and_return(datestamp_double3) expect(datestamp_double3).to receive(:run).with( text: 'Application Submitted on va.gov', x: 400, y: 675, text_only: true, timestamp:, page_number: 6, template: 'lib/pdf_fill/forms/pdfs/686C-674-V2.pdf', multistamp: true ).and_return(path) data = JSON.parse('{"id":"6d8433c1-cd55-4c24-affd-f592287a7572","type":"document_upload"}') expect(lighthouse_mock).to receive(:upload_form).with( main_document: { file: path, file_name: 'pdf_path' }, attachments: [], form_metadata: hash_including(file_number: '796104437') ).and_return(OpenStruct.new(success?: success, data:)) expect(Common::FileHelpers).to receive(:delete_file_if_exists).with(path) expect(FormSubmission).to receive(:create).with( form_type: '686C-674-V2', saved_claim: claim_v2, user_account: user.user_account ).and_return(FormSubmission.new) expect(FormSubmissionAttempt).to receive(:create).with(form_submission: an_instance_of(FormSubmission), benefits_intake_uuid: 'uuid') end context 'with an response error' do let(:success) { false } it 'raises BenefitsIntakeResponseError and updates submission to failed' do mailer_double = double('Mail::Message') allow(mailer_double).to receive(:deliver_now) expect(claim_v2).to receive(:submittable_686?).and_return(true).exactly(:twice) expect(claim_v2).to receive(:submittable_674?).and_return(false) expect { subject.perform(claim_v2.id, encrypted_vet_info, encrypted_user_struct) }.to raise_error(Lighthouse::BenefitsIntake::SubmitCentralForm686cV2Job::BenefitsIntakeResponseError) # rubocop:disable Layout/LineLength expect(central_mail_submission_v2.reload.state).to eq('failed') end end it 'submits the saved claim and updates submission to success' do vanotify = double(send_email: true) callback_options = { callback_klass: 'Dependents::NotificationCallback', callback_metadata: { email_template_id: 'fake_received686', email_type: :received686, form_id: '686C-674-V2', claim_id: claim_v2.id, saved_claim_id: claim_v2.id, service_name: 'dependents' } } personalization = { 'confirmation_number' => claim_v2.confirmation_number, 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'first_name' => 'MARK' } expect(VaNotify::Service).to receive(:new).with('fake_secret', callback_options).and_return(vanotify) expect(vanotify).to receive(:send_email).with( { email_address: user_struct.va_profile_email, template_id: 'fake_received686', personalisation: personalization }.compact ) expect(claim_v2).to receive(:submittable_686?).and_return(true).exactly(4).times expect(claim_v2).to receive(:submittable_674?).and_return(false).at_least(:once) subject.perform(claim_v2.id, encrypted_vet_info, encrypted_user_struct) expect(central_mail_submission_v2.reload.state).to eq('success') end end describe 'get files from claim' do subject { job.get_files_from_claim } # Performance tweak # We are not testing the PDF generation or process_pdf method here. These are computationally expensive # and are tested in other specs # rubocop:disable RSpec/SubjectStub before do allow(claim_v2).to receive(:to_pdf).and_return('mocked.pdf') allow(job).to receive(:process_pdf).and_return('mocked-processed.pdf') end # rubocop:enable RSpec/SubjectStub it 'compiles 686 and 674 files and returns attachments array with the generated 674' do job.instance_variable_set('@claim', claim_v2) expect(subject).to be_an_instance_of(Array) expect(subject.size).to eq(1) end end describe '#process_pdf' do timestamp = Time.zone.now subject { job.process_pdf('path1', timestamp, '686C-674-V2') } it 'processes a record and add stamps' do datestamp_double1 = double datestamp_double2 = double datestamp_double3 = double expect(PDFUtilities::DatestampPdf).to receive(:new).with('path1').and_return(datestamp_double1) expect(datestamp_double1).to receive(:run).with(text: 'VA.GOV', x: 5, y: 5, timestamp:).and_return('path2') expect(PDFUtilities::DatestampPdf).to receive(:new).with('path2').and_return(datestamp_double2) expect(datestamp_double2).to receive(:run).with( text: 'FDC Reviewed - va.gov Submission', x: 400, y: 770, text_only: true ).and_return('path3') expect(PDFUtilities::DatestampPdf).to receive(:new).with('path3').and_return(datestamp_double3) expect(datestamp_double3).to receive(:run).with( text: 'Application Submitted on va.gov', x: 400, y: 675, text_only: true, timestamp:, page_number: 6, template: 'lib/pdf_fill/forms/pdfs/686C-674-V2.pdf', multistamp: true ).and_return('path4') expect(subject).to eq('path4') end end describe '#get_hash_and_pages' do it 'gets sha and number of pages' do expect(Digest::SHA256).to receive(:file).with('path').and_return( OpenStruct.new(hexdigest: 'hexdigest') ) expect(PdfInfo::Metadata).to receive(:read).with('path').and_return( OpenStruct.new(pages: 2) ) expect(described_class.new.get_hash_and_pages('path')).to eq( hash: 'hexdigest', pages: 2 ) end end describe '#generate_metadata' do subject { job.generate_metadata } before do job.instance_variable_set('@claim', claim_v2) job.instance_variable_set('@form_path', 'pdf_path') job.instance_variable_set('@attachment_paths', ['attachment_path']) expect(Digest::SHA256).to receive(:file).with('pdf_path').and_return( OpenStruct.new(hexdigest: 'hash1') ) expect(PdfInfo::Metadata).to receive(:read).with('pdf_path').and_return( OpenStruct.new(pages: 1) ) expect(Digest::SHA256).to receive(:file).with('attachment_path').and_return( OpenStruct.new(hexdigest: 'hash2') ) expect(PdfInfo::Metadata).to receive(:read).with('attachment_path').and_return( OpenStruct.new(pages: 2) ) end context 'with a non us address' do before do form = JSON.parse(claim_v2.form) form['dependents_application']['veteran_contact_information']['veteran_address']['country_name'] = 'AGO' claim_v2.form = form.to_json claim_v2.send(:remove_instance_variable, :@parsed_form) end it 'generates metadata with 00000 for zipcode' do expect(subject['zipCode']).to eq('00000') end end it 'generates the metadata', run_at: '2017-01-04 03:00:00 EDT' do expect(subject).to eq( 'veteranFirstName' => vet_info['veteran_information']['full_name']['first'], 'veteranLastName' => vet_info['veteran_information']['full_name']['last'], 'fileNumber' => claim_v2.parsed_form['veteran_information']['va_file_number'], 'receiveDt' => '2017-01-04 01:00:00', 'zipCode' => '00000', 'uuid' => claim_v2.guid, 'source' => 'va.gov', 'hashV' => 'hash1', 'numberAttachments' => 1, 'docType' => '686C-674-V2', 'numberPages' => 1, 'ahash1' => 'hash2', 'numberPages1' => 2 ) end end end describe '#to_faraday_upload' do it 'converts a file to faraday upload object' do file_path = 'tmp/foo' expect(Faraday::UploadIO).to receive(:new).with( file_path, 'application/pdf' ) described_class.new.to_faraday_upload(file_path) end end describe 'sidekiq_retries_exhausted block' do before do allow(SavedClaim::DependencyClaim).to receive(:find).and_return(claim) allow(Dependents::Monitor).to receive(:new).and_return(monitor) allow(monitor).to receive :track_submission_exhaustion end it 'logs the error to zsf and sends an email with the 686C template' do Lighthouse::BenefitsIntake::SubmitCentralForm686cV2Job.within_sidekiq_retries_exhausted_block( { 'args' => [claim.id, encrypted_vet_info, encrypted_user_struct] } ) do exhaustion_msg['args'] = [claim.id, encrypted_vet_info, encrypted_user_struct] expect(monitor).to receive(:track_submission_exhaustion).with(exhaustion_msg, user_struct.va_profile_email) expect(SavedClaim::DependencyClaim).to receive(:find).with(claim.id).and_return(claim) claim.parsed_form['view:selectable686_options']['report674'] = false expect(Dependents::Form686c674FailureEmailJob).to receive(:perform_async).with( claim.id, 'vets.gov.user+228@gmail.com', 'form21_686c_action_needed_email_template_id', { 'first_name' => 'MARK', 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'confirmation_number' => claim.confirmation_number } ) end end it 'logs the error to zsf and sends an email with the 674 template' do Lighthouse::BenefitsIntake::SubmitCentralForm686cV2Job.within_sidekiq_retries_exhausted_block( { 'args' => [claim.id, encrypted_vet_info, encrypted_user_struct] } ) do exhaustion_msg['args'] = [claim.id, encrypted_vet_info, encrypted_user_struct] expect(monitor).to receive(:track_submission_exhaustion).with(exhaustion_msg, user_struct.va_profile_email) expect(SavedClaim::DependencyClaim).to receive(:find).with(claim.id).and_return(claim) claim.parsed_form['view:selectable686_options'].delete('add_child') expect(Dependents::Form686c674FailureEmailJob).to receive(:perform_async).with( claim.id, 'vets.gov.user+228@gmail.com', 'form21_674_action_needed_email_template_id', { 'first_name' => 'MARK', 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'confirmation_number' => claim.confirmation_number } ) end end it 'logs the error to zsf and a combo email with 686c-674' do Lighthouse::BenefitsIntake::SubmitCentralForm686cV2Job.within_sidekiq_retries_exhausted_block( { 'args' => [claim.id, encrypted_vet_info, encrypted_user_struct] } ) do exhaustion_msg['args'] = [claim.id, encrypted_vet_info, encrypted_user_struct] expect(monitor).to receive(:track_submission_exhaustion).with(exhaustion_msg, user_struct.va_profile_email) expect(SavedClaim::DependencyClaim).to receive(:find).with(claim.id).and_return(claim) expect(Dependents::Form686c674FailureEmailJob).to receive(:perform_async).with( claim.id, 'vets.gov.user+228@gmail.com', 'form21_686c_674_action_needed_email_template_id', { 'first_name' => 'MARK', 'date_submitted' => Time.zone.today.strftime('%B %d, %Y'), 'confirmation_number' => claim.confirmation_number } ) end end it 'logs the error to zsf and does not send an email' do Lighthouse::BenefitsIntake::SubmitCentralForm686cV2Job.within_sidekiq_retries_exhausted_block( { 'args' => [claim.id, encrypted_vet_info, encrypted_user_struct] } ) do exhaustion_msg['args'] = [claim.id, encrypted_vet_info, encrypted_user_struct] user_struct.va_profile_email = nil claim.parsed_form['dependents_application'].delete('veteran_contact_information') expect(monitor).to receive(:track_submission_exhaustion).with(exhaustion_msg, nil) expect(SavedClaim::DependencyClaim).to receive(:find).with(claim.id).and_return(claim) end end end end
0
code_files/vets-api-private/spec/sidekiq/lighthouse
code_files/vets-api-private/spec/sidekiq/lighthouse/benefits_discovery/log_eligible_benefits_job_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Lighthouse::BenefitsDiscovery::LogEligibleBenefitsJob, type: :job do let(:user) { create(:user, :loa3, :accountable, :legacy_icn) } let(:service_instance) { instance_double(BenefitsDiscovery::Service) } let(:params_instance) { instance_double(BenefitsDiscovery::Params) } let(:eligible_benefits) do { 'undetermined' => [], 'recommended' => [ { 'benefit_name' => 'Life Insurance (VALife)', 'benefit_url' => 'https://www.va.gov/life-insurance/' }, { 'benefit_name' => 'Health', 'benefit_url' => 'https://www.va.gov/health-care/' } ], 'not_recommended' => [] } end let(:prepared_params) { { doesnt: 'matter' } } let(:prepared_service_history) { { stilldoesnt: 'matter' } } describe '#perform' do before do allow(BenefitsDiscovery::Service).to receive(:new).with( api_key: Settings.lighthouse.benefits_discovery.x_api_key, app_id: Settings.lighthouse.benefits_discovery.x_app_id ).and_return(service_instance) allow(BenefitsDiscovery::Params).to receive(:new).and_return(params_instance) allow(params_instance).to \ receive(:build_from_service_history).with(prepared_service_history).and_return(prepared_params) end context 'when all upstream services work' do before do allow(service_instance).to receive(:get_eligible_benefits).with(prepared_params).and_return(eligible_benefits) end it 'processes benefits discovery successfully' do expect(StatsD).to receive(:measure).with(described_class.name, be_a(Float)) expected_tags = 'eligible_benefits:not_recommended//recommended/Health:Life Insurance (VALife)/undetermined//' expect(StatsD).to receive(:increment).with('benefits_discovery_logging', { tags: [expected_tags] }) described_class.new.perform(user.uuid, prepared_service_history) end it 'always logs items in the same order' do benefits = { 'undetermined' => [ { 'benefit_name' => 'Job Assistance', 'benefit_url' => 'https://www.va.gov/job-assistance/' }, { 'benefit_name' => 'Wealth', 'benefit_url' => 'https://www.va.gov/wealth/' } ], 'not_recommended' => [ { 'benefit_name' => 'Life Insurance (VALife)', 'benefit_url' => 'https://www.va.gov/life-insurance/' }, { 'benefit_name' => 'Health', 'benefit_url' => 'https://www.va.gov/health-care/' } ], 'recommended' => [ { 'benefit_name' => 'Education', 'benefit_url' => 'https://www.va.gov/education/' }, { 'benefit_name' => 'Childcare', 'benefit_url' => 'https://www.va.gov/childcare/' } ] } reordered_benefits = { 'recommended' => [ { 'benefit_name' => 'Childcare', 'benefit_url' => 'https://www.va.gov/childcare/' }, { 'benefit_name' => 'Education', 'benefit_url' => 'https://www.va.gov/education/' } ], 'not_recommended' => [ { 'benefit_name' => 'Health', 'benefit_url' => 'https://www.va.gov/health-care/' }, { 'benefit_name' => 'Life Insurance (VALife)', 'benefit_url' => 'https://www.va.gov/life-insurance/' } ], 'undetermined' => [ { 'benefit_name' => 'Wealth', 'benefit_url' => 'https://www.va.gov/wealth/' }, { 'benefit_name' => 'Job Assistance', 'benefit_url' => 'https://www.va.gov/job-assistance/' } ] } expected_tags = 'eligible_benefits:not_recommended/Health:Life Insurance (VALife)' \ '/recommended/Childcare:Education/undetermined/Job Assistance:Wealth/' allow(service_instance).to receive(:get_eligible_benefits).and_return(benefits) expect(StatsD).to receive(:increment).with('benefits_discovery_logging', { tags: [expected_tags] }) described_class.new.perform(user.uuid, prepared_service_history) allow(service_instance).to receive(:get_eligible_benefits).and_return(reordered_benefits) expect(StatsD).to receive(:increment).with('benefits_discovery_logging', { tags: [expected_tags] }) described_class.new.perform(user.uuid, prepared_service_history) end end context 'when user cannot be found' do it 'raises error' do expect { described_class.new.perform('abc123', prepared_service_history) }.to \ raise_error(Common::Exceptions::RecordNotFound, 'Record not found') end end context 'when params preparation fails' do before do allow(service_instance).to receive(:get_eligible_benefits).and_raise(StandardError, 'Failed to prepare params') end it 'logs error and re-raises the exception' do expect(Rails.logger).to receive(:error).with( "Failed to process eligible benefits for user: #{user.uuid}, error: Failed to prepare params" ) expect do described_class.new.perform(user.uuid, prepared_service_history) end.to raise_error(StandardError, 'Failed to prepare params') end end context 'when service call fails' do before do allow(service_instance).to receive(:get_eligible_benefits).and_raise(StandardError, 'API call failed') end it 'logs error and re-raises the exception' do expect(Rails.logger).to receive(:error).with( "Failed to process eligible benefits for user: #{user.uuid}, error: API call failed" ) expect do described_class.new.perform(user.uuid, prepared_service_history) end.to raise_error(StandardError, 'API call failed') end end end end
0
code_files/vets-api-private/spec/sidekiq/lighthouse
code_files/vets-api-private/spec/sidekiq/lighthouse/evidence_submissions/document_upload_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'sidekiq/testing' Sidekiq::Testing.fake! require 'lighthouse/evidence_submissions/document_upload' require 'va_notify/service' require 'lighthouse/benefits_documents/constants' require 'lighthouse/benefits_documents/utilities/helpers' RSpec.describe Lighthouse::EvidenceSubmissions::DocumentUpload, type: :job do let(:user_icn) { user_account.icn } let(:claim_id) { 4567 } let(:file_name) { 'doctors-note.pdf' } let(:tracked_item_ids) { 1234 } let(:document_type) { 'L029' } let(:document_description) { 'Copy of a DD214' } let(:document_data) do LighthouseDocument.new( first_name: 'First Name', participant_id: '1111', claim_id:, uuid: SecureRandom.uuid, file_extension: 'pdf', file_name:, tracked_item_id: tracked_item_ids, document_type: ) end let(:user_account) { create(:user_account) } let(:job_id) { '1234' } let(:client_stub) { instance_double(BenefitsDocuments::WorkerService) } let(:issue_instant) { Time.current.to_i } let(:current_date_time) { DateTime.current } let(:file) { Rails.root.join('spec', 'fixtures', 'files', file_name).read } let(:formatted_submit_date) do BenefitsDocuments::Utilities::Helpers.format_date_for_mailers(issue_instant) end def mock_response(status:, body:) instance_double(Faraday::Response, status:, body:) end context 'when :cst_send_evidence_submission_failure_emails is enabled' do before do allow(Flipper).to receive(:enabled?).with(:cst_send_evidence_submission_failure_emails).and_return(true) allow(StatsD).to receive(:increment) allow(Rails.logger).to receive(:info) end # Create Evidence Submission records from factory let(:evidence_submission_created) do create(:bd_evidence_submission_created, tracked_item_id: tracked_item_ids, claim_id:, job_id:, job_class: described_class) end context 'when upload succeeds' do let(:uploader_stub) { instance_double(LighthouseDocumentUploader) } let(:success_response) do mock_response( status: 200, body: { 'data' => { 'success' => true, 'requestId' => 1234 } } ) end let(:failed_date) do BenefitsDocuments::Utilities::Helpers.format_date_for_mailers(issue_instant) end it 'there is an evidence submission id, uploads to Lighthouse and returns a success response' do allow(LighthouseDocumentUploader).to receive(:new) { uploader_stub } allow(BenefitsDocuments::WorkerService).to receive(:new) { client_stub } allow(uploader_stub).to receive(:retrieve_from_store!).with(file_name) { file } allow(uploader_stub).to receive(:read_for_upload) { file } expect(uploader_stub).to receive(:remove!).once expect(client_stub).to receive(:upload_document).with(file, document_data).and_return(success_response) allow(EvidenceSubmission).to receive(:find_by) .with({ id: evidence_submission_created.id }) .and_return(evidence_submission_created) # Runs all queued jobs of this class described_class.new.perform(user_icn, document_data.to_serializable_hash, evidence_submission_created.id) # After running DocumentUpload job, there should be an updated EvidenceSubmission record # with the response request_id new_evidence_submission = EvidenceSubmission.find_by(id: evidence_submission_created.id) expect(new_evidence_submission.request_id).to eql(success_response.body.dig('data', 'requestId')) expect(new_evidence_submission.upload_status).to eql(BenefitsDocuments::Constants::UPLOAD_STATUS[:PENDING]) expect(StatsD) .to have_received(:increment) .with('cst.lighthouse.document_uploads.evidence_submission_record_updated.queued') expect(Rails.logger) .to have_received(:info) .with('LH - Updated Evidence Submission Record to QUEUED', any_args) expect(StatsD) .to have_received(:increment) .with('cst.lighthouse.document_uploads.evidence_submission_record_updated.added_request_id') expect(Rails.logger) .to have_received(:info) .with('LH - Updated Evidence Submission Record to PENDING', any_args) end it 'there is no evidence submission id' do allow(Lighthouse::EvidenceSubmissions::DocumentUpload).to receive(:update_evidence_submission_for_failure) allow(LighthouseDocumentUploader).to receive(:new) { uploader_stub } allow(BenefitsDocuments::WorkerService).to receive(:new) { client_stub } allow(uploader_stub).to receive(:retrieve_from_store!).with(file_name) { file } allow(uploader_stub).to receive(:read_for_upload) { file } expect(uploader_stub).to receive(:remove!).once expect(client_stub).to receive(:upload_document).with(file, document_data).and_return(success_response) allow(EvidenceSubmission).to receive(:find_by) .with({ id: nil }) .and_return(nil) # runs all queued jobs of this class described_class.new.perform(user_icn, document_data.to_serializable_hash, nil) expect(EvidenceSubmission.count).to equal(0) expect(Lighthouse::EvidenceSubmissions::DocumentUpload) .not_to have_received(:update_evidence_submission_for_failure) end end context 'when upload fails' do let(:error_message) { "#{described_class} failed to create EvidenceSubmission" } let(:tags) { ['service:claim-status', "function: #{error_message}"] } let(:failed_date) do BenefitsDocuments::Utilities::Helpers.format_date_for_mailers(issue_instant) end context 'when there is an evidence submission record that fails' do let(:msg_with_errors) do { 'jid' => job_id, 'args' => [user_account.icn, { 'first_name' => 'Bob', 'claim_id' => claim_id, 'document_type' => document_type, 'file_name' => file_name, 'tracked_item_id' => tracked_item_ids }, evidence_submission_created.id], 'created_at' => issue_instant, 'failed_at' => issue_instant, 'error_message' => 'An error ', 'error_class' => 'Faraday::BadRequestError' } end it 'updates an evidence submission record to FAILED' do described_class.within_sidekiq_retries_exhausted_block(msg_with_errors) do allow(EvidenceSubmission).to receive(:find_by) .with({ id: msg_with_errors['args'][2] }) .and_return(evidence_submission_created) allow(EvidenceSubmission).to receive(:update!) expect(Rails.logger) .to receive(:info) .with('LH - Updated Evidence Submission Record to FAILED', any_args) end failed_evidence_submission = EvidenceSubmission.find_by(id: evidence_submission_created.id) current_personalisation = JSON.parse(failed_evidence_submission.template_metadata)['personalisation'] expect(failed_evidence_submission.upload_status).to eql(BenefitsDocuments::Constants::UPLOAD_STATUS[:FAILED]) expect(failed_evidence_submission.error_message) .to eql('Lighthouse::EvidenceSubmissions::DocumentUpload document upload failure') expect(current_personalisation['date_failed']).to eql(failed_date) Timecop.freeze(current_date_time) do expect(failed_evidence_submission.failed_date).to be_within(1.second).of(current_date_time) expect(failed_evidence_submission.acknowledgement_date) .to be_within(1.second).of(current_date_time + 30.days) end Timecop.unfreeze end end context 'does not have an evidence submission id' do before do allow(Flipper).to receive(:enabled?).with(:cst_send_evidence_failure_emails).and_return(true) allow(described_class).to receive(:update_evidence_submission_for_failure) end let(:msg_with_nil_es_id) do { 'jid' => job_id, 'args' => [user_account.icn, { 'first_name' => 'Bob', 'claim_id' => claim_id, 'document_type' => document_type, 'file_name' => file_name, 'tracked_item_id' => tracked_item_ids }], 'created_at' => issue_instant, 'failed_at' => issue_instant } end it 'does not update an evidence submission record' do Lighthouse::EvidenceSubmissions::DocumentUpload.within_sidekiq_retries_exhausted_block(msg_with_nil_es_id) do allow(EvidenceSubmission).to receive(:find_by) .with({ id: nil }) .and_return(nil) expect(Lighthouse::FailureNotification).to receive(:perform_async).with( user_account.icn, { first_name: 'Bob', document_type: document_description, filename: BenefitsDocuments::Utilities::Helpers.generate_obscured_file_name(file_name), date_submitted: formatted_submit_date, date_failed: formatted_submit_date } ) expect(described_class).not_to receive(:update_evidence_submission_for_failure) expect(EvidenceSubmission.count).to equal(0) end end end context 'when args malformed' do let(:msg_args_malformed) do ## added 'test' so file would error { 'jid' => job_id, 'args' => ['test', user_account.icn, { 'first_name' => 'Bob', 'claim_id' => claim_id, 'document_type' => document_type, 'file_name' => file_name, 'tracked_item_id' => tracked_item_ids }, evidence_submission_created.id], 'created_at' => issue_instant, 'failed_at' => issue_instant } end it 'fails to create a failed evidence submission record' do expect do described_class.within_sidekiq_retries_exhausted_block(msg_args_malformed) {} end.to raise_error(StandardError, "Missing fields in #{described_class}") end end context 'when error occurs updating evidence submission to FAILED' do let(:msg_args) do { 'jid' => job_id, 'args' => [ user_account.icn, { 'first_name' => 'Bob', 'claim_id' => claim_id, 'document_type' => document_type, 'file_name' => file_name, 'tracked_item_id' => tracked_item_ids }, evidence_submission_created.id ], 'created_at' => issue_instant, 'failed_at' => issue_instant } end let(:log_error_message) { "#{described_class} failed to update EvidenceSubmission" } let(:statsd_error_tags) { ['service:claim-status', "function: #{log_error_message}"] } before do allow_any_instance_of(EvidenceSubmission).to receive(:update!).and_raise(StandardError) allow(Rails.logger).to receive(:error) end it 'error is raised and logged' do described_class.within_sidekiq_retries_exhausted_block(msg_args) do expect(Rails.logger) .to receive(:error) .with(log_error_message, { message: 'StandardError' }) expect(StatsD).to receive(:increment).with('silent_failure', tags: statsd_error_tags) end end end context 'when lighthouse returns a failure response' do let(:failure_response) do { data: { success: false } } end it 'raises an error' do allow(client_stub).to receive(:upload_document).with(file, document_data).and_return(failure_response) expect do described_class.new.perform(user_icn, document_data.to_serializable_hash, evidence_submission_created.id) end.to raise_error(StandardError) end end end end context 'when :cst_send_evidence_submission_failure_emails is disabled' do before do allow(Flipper).to receive(:enabled?).with(:cst_send_evidence_submission_failure_emails).and_return(false) end let(:msg) do { 'jid' => job_id, 'args' => [user_account.icn, { 'first_name' => 'Bob', 'claim_id' => claim_id, 'document_type' => document_type, 'file_name' => file_name, 'tracked_item_id' => tracked_item_ids }], 'created_at' => issue_instant, 'failed_at' => issue_instant } end let(:uploader_stub) { instance_double(LighthouseDocumentUploader) } it 'retrieves the file, uploads to Lighthouse and returns a success response' do allow(LighthouseDocumentUploader).to receive(:new) { uploader_stub } allow(BenefitsDocuments::WorkerService).to receive(:new) { client_stub } allow(uploader_stub).to receive(:retrieve_from_store!).with(file_name) { file } allow(uploader_stub).to receive(:read_for_upload) { file } expect(uploader_stub).to receive(:remove!).once expect(client_stub).to receive(:upload_document).with(file, document_data) expect(EvidenceSubmission.count).to equal(0) described_class.new.perform(user_icn, document_data.to_serializable_hash, nil) end context 'when cst_send_evidence_failure_emails is enabled' do before do allow(Flipper).to receive(:enabled?).with(:cst_send_evidence_failure_emails).and_return(true) end let(:log_message) { "#{described_class} exhaustion handler email queued" } let(:statsd_tags) { ['service:claim-status', 'function: evidence upload to Lighthouse'] } it 'calls Lighthouse::FailureNotification' do described_class.within_sidekiq_retries_exhausted_block(msg) do expect(Lighthouse::FailureNotification).to receive(:perform_async).with( user_account.icn, { first_name: 'Bob', document_type: document_description, filename: BenefitsDocuments::Utilities::Helpers.generate_obscured_file_name(file_name), date_submitted: formatted_submit_date, date_failed: formatted_submit_date } ) expect(EvidenceSubmission.count).to equal(0) expect(Rails.logger) .to receive(:info) .with(log_message) end end end context 'when cst_send_evidence_failure_emails is disabled' do before do allow(Flipper).to receive(:enabled?).with(:cst_send_evidence_failure_emails).and_return(false) end it 'does not call Lighthouse::Failure Notification' do described_class.within_sidekiq_retries_exhausted_block(msg) do expect(Lighthouse::FailureNotification).not_to receive(:perform_async) end end end end end
0
code_files/vets-api-private/spec/sidekiq/lighthouse
code_files/vets-api-private/spec/sidekiq/lighthouse/evidence_submissions/delete_evidence_submission_records_job_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Lighthouse::EvidenceSubmissions::DeleteEvidenceSubmissionRecordsJob, type: :job do subject { described_class } describe 'perform' do let!(:es_lh_delete_one) { create(:bd_evidence_submission_for_deletion, job_class: 'BenefitsDocuments::Service') } let!(:es_evss_delete_two) { create(:bd_evidence_submission_for_deletion, job_class: 'EVSSClaimService') } let!(:es_no_delete) { create(:bd_evidence_submission_not_for_deletion) } before do allow(StatsD).to receive(:increment) allow(Rails.logger).to receive(:info) end context 'when EvidenceSubmission records have a delete_date set' do it 'deletes only the records with a past or current delete_time' do expect(StatsD).to receive(:increment) .with('worker.cst.delete_evidence_submission_records.count', 2).exactly(1).time expect(Rails.logger) .to receive(:info) .with("#{subject} deleted 2 of 3 EvidenceSubmission records") subject.new.perform expect(EvidenceSubmission.where(id: es_no_delete.id).count).to eq(1) expect(EvidenceSubmission.where(id: es_lh_delete_one.id).count).to eq(0) expect(EvidenceSubmission.where(id: es_evss_delete_two.id).count).to eq(0) end end context 'when an exception is thrown' do let(:error_message) { 'Error message' } before do allow(EvidenceSubmission).to receive(:where).and_raise(ActiveRecord::ActiveRecordError.new(error_message)) end it 'rescues and logs the exception' do expect(Rails.logger) .to receive(:error) .with("#{subject} error: ", error_message) expect(StatsD).to receive(:increment) .with('worker.cst.delete_evidence_submission_records.error').exactly(1).time expect { subject.new.perform }.not_to raise_error end end end end
0
code_files/vets-api-private/spec/sidekiq/lighthouse
code_files/vets-api-private/spec/sidekiq/lighthouse/evidence_submissions/failure_notification_email_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'va_notify/service' require 'lighthouse/benefits_documents/utilities/helpers' RSpec.describe Lighthouse::EvidenceSubmissions::FailureNotificationEmailJob, type: :job do subject { described_class } let(:notification_id) { SecureRandom.uuid } let(:vanotify_service) do service = instance_double(VaNotify::Service) response = instance_double(Notifications::Client::ResponseNotification, id: notification_id) allow(service).to receive(:send_email).and_return(response) service end context 'when there are no FAILED records' do it 'doesnt send anything' do expect(EvidenceSubmission).not_to receive(:update) expect(vanotify_service).not_to receive(:send_email) expect(EvidenceSubmission.va_notify_email_queued.length).to equal(0) subject.new.perform end end context 'when there is a FAILED record with a va_notify_date' do before do allow(VaNotify::Service).to receive(:new).and_return(vanotify_service) create(:bd_evidence_submission_failed_va_notify_email_enqueued) end it 'doesnt update an evidence submission record or queue failure email' do expect(EvidenceSubmission.va_notify_email_queued.length).to eq(1) subject.new.perform expect(vanotify_service).not_to receive(:send_email) # This is still 1 since is has already been queued expect(EvidenceSubmission.va_notify_email_queued.length).to eq(1) end end context 'when the FAILED record is for EVSS and doesnt have a va_notify_date' do context 'when an error occurs' do before do allow(VaNotify::Service).to receive(:new).and_raise(StandardError) allow(EvidenceSubmission).to receive(:va_notify_email_not_queued).and_return([evidence_submission_failed]) allow(Rails.logger).to receive(:error) allow(StatsD).to receive(:increment) end let!(:evidence_submission_failed) { create(:bd_evss_evidence_submission_failed_type1_error) } let(:error_message) { "#{evidence_submission_failed.job_class} va notify failure email errored" } let(:tags) { ['service:claim-status', "function: #{error_message}"] } it 'handles the error and increments the statsd metric' do expect(EvidenceSubmission.count).to eq(1) expect(EvidenceSubmission.va_notify_email_queued.length).to eq(0) expect(vanotify_service).not_to receive(:send_email) expect(Rails.logger) .to receive(:error) .with(error_message, { message: 'StandardError' }) expect(StatsD).to receive(:increment).with('silent_failure', tags:) subject.new.perform end end context 'when no error occurs' do let(:tags) { ['service:claim-status', "function: #{message}"] } let(:message) { "#{evidence_submission_failed.job_class} va notify failure email queued" } let!(:evidence_submission_failed) { create(:bd_evss_evidence_submission_failed_type1_error) } let(:personalisation) do BenefitsDocuments::Utilities::Helpers.create_personalisation_from_upload(evidence_submission_failed) end let(:send_email_params) do { recipient_identifier: { id_value: evidence_submission_failed.user_account.icn, id_type: 'ICN' }, template_id: Settings.vanotify.services.benefits_management_tools .template_id.evidence_submission_failure_email, personalisation: } end before do allow(VaNotify::Service).to receive(:new).and_return(vanotify_service) allow(EvidenceSubmission).to receive(:va_notify_email_not_queued).and_return([evidence_submission_failed]) allow(Rails.logger).to receive(:info) allow(StatsD).to receive(:increment) end it 'successfully enqueues a failure notification mailer to send to the veteran' do expect(EvidenceSubmission.count).to eq(1) expect(EvidenceSubmission.va_notify_email_not_queued.length).to eq(1) expect(vanotify_service).to receive(:send_email).with(send_email_params) expect(evidence_submission_failed).to receive(:update).and_call_original expect(Rails.logger).to receive(:info).with(message) subject.new.perform expect(EvidenceSubmission.va_notify_email_queued.length).to eq(1) end end end context 'when the FAILED record is for Lighthouse type 1 error and doesnt have a va_notify_date' do context 'when an error occurs' do before do allow(VaNotify::Service).to receive(:new).and_raise(StandardError) allow(EvidenceSubmission).to receive(:va_notify_email_not_queued).and_return([evidence_submission_failed]) allow(Rails.logger).to receive(:error) allow(StatsD).to receive(:increment) end let!(:evidence_submission_failed) { create(:bd_lh_evidence_submission_failed_type1_error) } let(:error_message) { "#{evidence_submission_failed.job_class} va notify failure email errored" } let(:tags) { ['service:claim-status', "function: #{error_message}"] } it 'handles the error and increments the statsd metric' do expect(EvidenceSubmission.count).to eq(1) expect(EvidenceSubmission.va_notify_email_queued.length).to eq(0) expect(vanotify_service).not_to receive(:send_email) expect(Rails.logger) .to receive(:error) .with(error_message, { message: 'StandardError' }) expect(StatsD).to receive(:increment).with('silent_failure', tags:) subject.new.perform end end context 'when no error occurs' do let(:tags) { ['service:claim-status', "function: #{message}"] } let(:message) { "#{evidence_submission_failed.job_class} va notify failure email queued" } let!(:evidence_submission_failed) { create(:bd_lh_evidence_submission_failed_type1_error) } let(:personalisation) do BenefitsDocuments::Utilities::Helpers.create_personalisation_from_upload(evidence_submission_failed) end let(:send_email_params) do { recipient_identifier: { id_value: evidence_submission_failed.user_account.icn, id_type: 'ICN' }, template_id: Settings.vanotify.services.benefits_management_tools .template_id.evidence_submission_failure_email, personalisation: } end before do allow(VaNotify::Service).to receive(:new).and_return(vanotify_service) allow(EvidenceSubmission).to receive(:va_notify_email_not_queued).and_return([evidence_submission_failed]) allow(Rails.logger).to receive(:info) allow(StatsD).to receive(:increment) end it 'successfully enqueues a failure notification mailer to send to the veteran' do expect(EvidenceSubmission.count).to eq(1) expect(EvidenceSubmission.va_notify_email_not_queued.length).to eq(1) expect(vanotify_service).to receive(:send_email).with(send_email_params) expect(evidence_submission_failed).to receive(:update).and_call_original expect(Rails.logger).to receive(:info).with(message) subject.new.perform expect(EvidenceSubmission.va_notify_email_queued.length).to eq(1) evidence_submission = EvidenceSubmission.find_by(id: evidence_submission_failed.id) expect(evidence_submission.va_notify_date).not_to be_nil end end end context 'when the FAILED record is for Lighthouse type 2 error and doesnt have a va_notify_date' do context 'when an error occurs' do before do allow(VaNotify::Service).to receive(:new).and_raise(StandardError) allow(EvidenceSubmission).to receive(:va_notify_email_not_queued).and_return([evidence_submission_failed]) allow(Rails.logger).to receive(:error) allow(StatsD).to receive(:increment) end let!(:evidence_submission_failed) { create(:bd_lh_evidence_submission_failed_type2_error) } let(:error_message) { "#{evidence_submission_failed.job_class} va notify failure email errored" } let(:tags) { ['service:claim-status', "function: #{error_message}"] } it 'handles the error and increments the statsd metric' do expect(EvidenceSubmission.count).to eq(1) expect(EvidenceSubmission.va_notify_email_queued.length).to eq(0) expect(vanotify_service).not_to receive(:send_email) expect(Rails.logger) .to receive(:error) .with(error_message, { message: 'StandardError' }) expect(StatsD).to receive(:increment).with('silent_failure', tags:) subject.new.perform end end context 'when no error occurs' do let(:tags) { ['service:claim-status', "function: #{message}"] } let(:message) { "#{evidence_submission_failed.job_class} va notify failure email queued" } let!(:evidence_submission_failed) { create(:bd_lh_evidence_submission_failed_type2_error) } let(:personalisation) do BenefitsDocuments::Utilities::Helpers.create_personalisation_from_upload(evidence_submission_failed) end let(:send_email_params) do { recipient_identifier: { id_value: evidence_submission_failed.user_account.icn, id_type: 'ICN' }, template_id: Settings.vanotify.services.benefits_management_tools .template_id.evidence_submission_failure_email, personalisation: } end before do allow(VaNotify::Service).to receive(:new).and_return(vanotify_service) allow(EvidenceSubmission).to receive(:va_notify_email_not_queued).and_return([evidence_submission_failed]) allow(Rails.logger).to receive(:info) allow(StatsD).to receive(:increment) end it 'successfully enqueues a failure notification mailer to send to the veteran' do expect(EvidenceSubmission.count).to eq(1) expect(EvidenceSubmission.va_notify_email_not_queued.length).to eq(1) expect(vanotify_service).to receive(:send_email).with(send_email_params) expect(evidence_submission_failed).to receive(:update).and_call_original expect(Rails.logger).to receive(:info).with(message) subject.new.perform expect(EvidenceSubmission.va_notify_email_queued.length).to eq(1) evidence_submission = EvidenceSubmission.find_by(id: evidence_submission_failed.id) expect(evidence_submission.va_notify_date).not_to be_nil end end end context 'when there are multiple FAILED records without a va_notify_date' do let(:message1) { "#{evidence_submission_failed1.job_class} va notify failure email queued" } let(:message2) { "#{evidence_submission_failed2.job_class} va notify failure email queued" } let(:message3) { "#{evidence_submission_failed3.job_class} va notify failure email queued" } let!(:evidence_submission_failed1) { create(:bd_lh_evidence_submission_failed_type1_error) } let!(:evidence_submission_failed2) { create(:bd_lh_evidence_submission_failed_type2_error) } let!(:evidence_submission_failed3) { create(:bd_evss_evidence_submission_failed_type1_error) } before do allow(VaNotify::Service).to receive(:new).and_return(vanotify_service) allow(EvidenceSubmission).to receive(:va_notify_email_not_queued).and_return([evidence_submission_failed1, evidence_submission_failed2, evidence_submission_failed3]) allow(Rails.logger).to receive(:info) allow(StatsD).to receive(:increment) end it 'successfully enqueues a failure notification mailer to send to the veteran' do expect(EvidenceSubmission.count).to eq(3) expect(EvidenceSubmission.va_notify_email_not_queued.length).to eq(3) expect(vanotify_service).to receive(:send_email) expect(evidence_submission_failed1).to receive(:update).and_call_original expect(evidence_submission_failed2).to receive(:update).and_call_original expect(evidence_submission_failed3).to receive(:update).and_call_original expect(Rails.logger).to receive(:info).with(message1) expect(Rails.logger).to receive(:info).with(message2) expect(Rails.logger).to receive(:info).with(message3) subject.new.perform expect(EvidenceSubmission.va_notify_email_queued.length).to eq(3) end end end
0
code_files/vets-api-private/spec/sidekiq/lighthouse
code_files/vets-api-private/spec/sidekiq/lighthouse/evidence_submissions/va_notify_email_status_callback_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lighthouse/benefits_documents/constants' describe Lighthouse::EvidenceSubmissions::VANotifyEmailStatusCallback do describe '#call' do context 'notification callback' do let(:notification_type) { :error } let(:callback_metadata) { { notification_type: } } context 'permanent-failure' do let!(:notification_record) do build(:notification, status: 'permanent-failure', notification_id: SecureRandom.uuid, callback_metadata:) end let!(:notification_record_evss) do build(:notification, status: 'permanent-failure', notification_id: SecureRandom.uuid, callback_metadata:) end let!(:evidence_submission) do create(:bd_evidence_submission_failed_va_notify_email_enqueued, va_notify_id: notification_record.notification_id) end let!(:evidence_submission_evss) do create(:bd_evss_evidence_submission_failed_va_notify_email_enqueued, va_notify_id: notification_record_evss.notification_id) end it 'logs error and increments StatsD for Lighthouse' do allow(StatsD).to receive(:increment) allow(Rails.logger).to receive(:error) described_class.call(notification_record) es = EvidenceSubmission.find_by(va_notify_id: notification_record.notification_id) expect(Rails.logger).to have_received(:error).with( 'Lighthouse::EvidenceSubmissions::VANotifyEmailStatusCallback', { notification_id: notification_record.notification_id, source_location: notification_record.source_location, status: notification_record.status, status_reason: notification_record.status_reason, notification_type: notification_record.notification_type, request_id: es.request_id, job_class: es.job_class } ) expect(StatsD).to have_received(:increment) .with('silent_failure', tags: ['service:claim-status', 'function: Lighthouse - VA Notify evidence upload failure email']) expect(StatsD).to have_received(:increment).with('api.vanotify.notifications.permanent_failure') expect(StatsD).to have_received(:increment) .with('callbacks.cst_document_uploads.va_notify.notifications.permanent_failure') end it 'logs error and increments StatsD for EVSS' do allow(StatsD).to receive(:increment) allow(Rails.logger).to receive(:error) described_class.call(notification_record_evss) es = EvidenceSubmission.find_by(va_notify_id: notification_record_evss.notification_id) expect(Rails.logger).to have_received(:error).with( 'Lighthouse::EvidenceSubmissions::VANotifyEmailStatusCallback', { notification_id: notification_record_evss.notification_id, source_location: notification_record_evss.source_location, status: notification_record_evss.status, status_reason: notification_record_evss.status_reason, notification_type: notification_record_evss.notification_type, request_id: es.request_id, job_class: es.job_class } ) expect(StatsD).to have_received(:increment) .with('silent_failure', tags: ['service:claim-status', 'function: EVSS - VA Notify evidence upload failure email']) expect(StatsD).to have_received(:increment).with('api.vanotify.notifications.permanent_failure') expect(StatsD).to have_received(:increment) .with('callbacks.cst_document_uploads.va_notify.notifications.permanent_failure') end it 'updates va_notify_status' do described_class.call(notification_record) es = EvidenceSubmission.find_by(va_notify_id: notification_record.notification_id) expect(es.va_notify_status).to eq(BenefitsDocuments::Constants::VANOTIFY_STATUS[:FAILED]) end end context 'delivered' do let!(:notification_record) do build(:notification, status: 'delivered', notification_id: SecureRandom.uuid) end let!(:notification_record_evss) do build(:notification, status: 'delivered', notification_id: SecureRandom.uuid) end let!(:evidence_submission) do create(:bd_evidence_submission_failed_va_notify_email_enqueued, va_notify_id: notification_record.notification_id) end let!(:evidence_submission_evss) do create(:bd_evss_evidence_submission_failed_va_notify_email_enqueued, va_notify_id: notification_record_evss.notification_id) end it 'logs success and increments StatsD for Lighthouse' do allow(StatsD).to receive(:increment) described_class.call(notification_record) expect(StatsD).to have_received(:increment) .with('silent_failure_avoided', tags: ['service:claim-status', 'function: Lighthouse - VA Notify evidence upload failure email']) expect(StatsD).to have_received(:increment).with('api.vanotify.notifications.delivered') expect(StatsD).to have_received(:increment) .with('callbacks.cst_document_uploads.va_notify.notifications.delivered') end it 'logs success and increments StatsD for EVSS' do allow(StatsD).to receive(:increment) described_class.call(notification_record_evss) expect(StatsD).to have_received(:increment) .with('silent_failure_avoided', tags: ['service:claim-status', 'function: EVSS - VA Notify evidence upload failure email']) expect(StatsD).to have_received(:increment).with('api.vanotify.notifications.delivered') expect(StatsD).to have_received(:increment) .with('callbacks.cst_document_uploads.va_notify.notifications.delivered') end it 'updates va_notify_status' do described_class.call(notification_record) es = EvidenceSubmission.find_by(va_notify_id: notification_record.notification_id) expect(es.va_notify_status).to eq(BenefitsDocuments::Constants::VANOTIFY_STATUS[:SUCCESS]) end end context 'temporary-failure' do let!(:notification_record) do build(:notification, status: 'temporary-failure', notification_id: SecureRandom.uuid) end let!(:evidence_submission) do create(:bd_evidence_submission_failed_va_notify_email_enqueued, va_notify_id: notification_record.notification_id) end it 'logs error and increments StatsD' do allow(StatsD).to receive(:increment) allow(Rails.logger).to receive(:error) described_class.call(notification_record) es = EvidenceSubmission.find_by(va_notify_id: notification_record.notification_id) expect(StatsD).to have_received(:increment).with('api.vanotify.notifications.temporary_failure') expect(StatsD).to have_received(:increment) .with('callbacks.cst_document_uploads.va_notify.notifications.temporary_failure') expect(Rails.logger).to have_received(:error).with( 'Lighthouse::EvidenceSubmissions::VANotifyEmailStatusCallback', { notification_id: notification_record.notification_id, source_location: notification_record.source_location, status: notification_record.status, status_reason: notification_record.status_reason, notification_type: notification_record.notification_type, request_id: es.request_id, job_class: es.job_class } ) end end context 'other' do let!(:notification_record) do build(:notification, status: '', notification_id: SecureRandom.uuid) end let!(:evidence_submission) do create(:bd_evidence_submission_failed_va_notify_email_enqueued, va_notify_id: notification_record.notification_id) end it 'logs error and increments StatsD' do allow(StatsD).to receive(:increment) allow(Rails.logger).to receive(:error) described_class.call(notification_record) es = EvidenceSubmission.where(va_notify_id: notification_record.notification_id).first expect(StatsD).to have_received(:increment).with('api.vanotify.notifications.other') StatsD.increment('callbacks.cst_document_uploads.va_notify.notifications.other') expect(Rails.logger).to have_received(:error).with( 'Lighthouse::EvidenceSubmissions::VANotifyEmailStatusCallback', { notification_id: notification_record.notification_id, source_location: notification_record.source_location, status: notification_record.status, status_reason: notification_record.status_reason, notification_type: notification_record.notification_type, request_id: es.request_id, job_class: es.job_class } ) end end end end end
0
code_files/vets-api-private/spec/sidekiq/lighthouse
code_files/vets-api-private/spec/sidekiq/lighthouse/evidence_submissions/evidence_submission_document_upload_polling_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'lighthouse/benefits_documents/constants' require 'lighthouse/benefits_documents/utilities/helpers' RSpec.describe Lighthouse::EvidenceSubmissions::EvidenceSubmissionDocumentUploadPollingJob, type: :job do let(:job) { described_class.perform_async } let(:user_account) { create(:user_account) } let(:user_account_uuid) { user_account.id } let(:current_date_time) { DateTime.current } let!(:pending_lighthouse_document_upload1) do create(:bd_evidence_submission_pending, job_class: 'BenefitsDocuments::Service', request_id: 1) end let!(:pending_lighthouse_document_upload2) do create(:bd_evidence_submission_pending, job_class: 'BenefitsDocuments::Service', request_id: 2) end let!(:pending_lighthouse_document_upload_no_request_id) do create(:bd_evidence_submission_pending, job_class: 'BenefitsDocuments::Service', request_id: nil) end let(:error_message) do { 'detail' => 'string', 'step' => 'BENEFITS_GATEWAY_SERVICE' } end let(:issue_instant) { Time.current.to_i } let(:date_failed) do BenefitsDocuments::Utilities::Helpers.format_date_for_mailers(issue_instant) end context 'when there are EvidenceSubmission records' do before do allow_any_instance_of(Auth::ClientCredentials::Service).to receive(:get_token).and_return('fake_access_token') allow(StatsD).to receive(:increment) allow(Rails.logger).to receive(:warn) allow(Rails.logger).to receive(:error) end it 'polls and updates status for each EvidenceSubmission record that is still pending to "complete"' do VCR.use_cassette('lighthouse/benefits_claims/documents/lighthouse_document_upload_status_polling_success') do Timecop.freeze(current_date_time) do job described_class.drain end end pending_es = EvidenceSubmission.where(request_id: 1).first pending_es2 = EvidenceSubmission.where(request_id: 2).first expect(pending_es.completed?).to be(true) expect(pending_es.delete_date).to be_within(1.second).of(current_date_time + 60.days) expect(pending_es2.completed?).to be(true) expect(pending_es2.delete_date).to be_within(1.second).of(current_date_time + 60.days) expect(pending_lighthouse_document_upload_no_request_id.completed?).to be(false) expect(StatsD).to have_received(:increment).with( 'worker.lighthouse.cst_document_uploads.pending_documents_polled', 2 ) expect(StatsD).to have_received(:increment).with( 'worker.lighthouse.cst_document_uploads.pending_documents_marked_completed', 2 ) expect(StatsD).to have_received(:increment).with( 'worker.lighthouse.cst_document_uploads.pending_documents_marked_failed', 0 ) end it 'polls and updates status for each failed EvidenceSubmission to "failed"' do VCR.use_cassette('lighthouse/benefits_claims/documents/lighthouse_document_upload_status_polling_failed') do Timecop.freeze(current_date_time) do job described_class.drain end end pending_es = EvidenceSubmission.where(request_id: 1).first pending_es2 = EvidenceSubmission.where(request_id: 2).first expect(pending_es.failed?).to be(true) expect(pending_es.acknowledgement_date).to be_within(1.second).of(current_date_time + 30.days) expect(pending_es.failed_date).to be_within(1.second).of(current_date_time) expect(pending_es.error_message).to eq(error_message.to_s) expect(JSON.parse(pending_es.template_metadata)['personalisation']['date_failed']).to eq(date_failed) expect(pending_es2.failed?).to be(true) expect(pending_es2.acknowledgement_date).to be_within(1.second).of(current_date_time + 30.days) expect(pending_es2.failed_date).to be_within(1.second).of(current_date_time) expect(pending_es2.error_message).to eq(error_message.to_s) expect(JSON.parse(pending_es2.template_metadata)['personalisation']['date_failed']).to eq(date_failed) expect(StatsD).to have_received(:increment).with( 'worker.lighthouse.cst_document_uploads.pending_documents_polled', 2 ) expect(StatsD).to have_received(:increment).with( 'worker.lighthouse.cst_document_uploads.pending_documents_marked_completed', 0 ) expect(StatsD).to have_received(:increment).with( 'worker.lighthouse.cst_document_uploads.pending_documents_marked_failed', 2 ) end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/pager_duty/poll_maintenance_windows_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'pager_duty/poll_maintenance_windows' RSpec.describe PagerDuty::PollMaintenanceWindows, type: :job do let(:client_stub) { instance_double(PagerDuty::MaintenanceClient) } let(:maint_hash) { build(:maintenance_hash) } let(:maint_hash_updated) { build(:maintenance_hash_updated) } let(:maint_hash_multi1) { build(:maintenance_hash_multi1) } let(:maint_hash_multi2) { build(:maintenance_hash_multi2) } let(:maint_hash_message) { build(:maintenance_hash_with_message) } before do allow(PagerDuty::MaintenanceClient).to receive(:new) { client_stub } end after do MaintenanceWindow.delete_all end context 'with valid maintenance window data' do it 'handles empty list of windows' do allow(client_stub).to receive(:get_all).and_return([]) described_class.new.perform end it 'adds entries to database' do allow(client_stub).to receive(:get_all).and_return([maint_hash]) described_class.new.perform expect(MaintenanceWindow.find_by(pagerduty_id: 'ABCDEF')).not_to be_nil end it 'updates existing entries' do allow(client_stub).to receive(:get_all).and_return([maint_hash], [maint_hash_updated]) described_class.new.perform original = MaintenanceWindow.find_by(pagerduty_id: 'ABCDEF') expect(original).not_to be_nil expect(original.description).to eq('') original_time = original.end_time described_class.new.perform updated = MaintenanceWindow.find_by(pagerduty_id: 'ABCDEF') expect(updated.description).to eq('') updated_time = updated.end_time expect(updated_time).to be > original_time end it 'handles duplicate external IDs' do allow(client_stub).to receive(:get_all).and_return([maint_hash_multi1, maint_hash_multi2]) described_class.new.perform expect(MaintenanceWindow.where(pagerduty_id: 'ABC123').count).to eq(2) end it 'deletes obsolete entries' do Timecop.freeze(Date.new(2017, 12, 19)) do allow(client_stub).to receive(:get_all).and_return([maint_hash, maint_hash_multi1], [maint_hash_multi1]) described_class.new.perform expect(MaintenanceWindow.find_by(pagerduty_id: 'ABCDEF')).not_to be_nil expect(MaintenanceWindow.find_by(pagerduty_id: 'ABC123')).not_to be_nil described_class.new.perform expect(MaintenanceWindow.find_by(pagerduty_id: 'ABCDEF')).to be_nil expect(MaintenanceWindow.find_by(pagerduty_id: 'ABC123')).not_to be_nil end end it 'deletes all obsolete entries for an external ID' do Timecop.freeze(Date.new(2017, 12, 19)) do allow(client_stub).to receive(:get_all).and_return([maint_hash, maint_hash_multi1, maint_hash_multi2], [maint_hash]) described_class.new.perform expect(MaintenanceWindow.find_by(pagerduty_id: 'ABCDEF')).not_to be_nil expect(MaintenanceWindow.where(pagerduty_id: 'ABC123').count).to eq(2) described_class.new.perform expect(MaintenanceWindow.find_by(pagerduty_id: 'ABCDEF')).not_to be_nil expect(MaintenanceWindow.where(pagerduty_id: 'ABC123').count).to eq(0) end end it 'extracts the user-facing message correctly' do allow(client_stub).to receive(:get_all).and_return([maint_hash_message]) described_class.new.perform window = MaintenanceWindow.find_by(pagerduty_id: 'ABCDEF') expect(window).not_to be_nil expect(window.description).to eq('Sorry, VIC is unavailable RN\nTry again later') end end context 'with error response from client' do before do allow(Settings.sentry).to receive(:dsn).and_return('asdf') end it 'bails on backend error' do expect(client_stub).to receive(:get_all).and_raise(Common::Exceptions::BackendServiceException) expect(Sentry).to receive(:capture_exception).with(Common::Exceptions::BackendServiceException, level: 'error') described_class.new.perform end it 'bails on client error' do expect(client_stub).to receive(:get_all).and_raise(Common::Client::Errors::ClientError) expect(Sentry).to receive(:capture_exception).with(Common::Client::Errors::ClientError, level: 'error') described_class.new.perform end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/pager_duty/cache_global_downtime_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'pager_duty/cache_global_downtime' RSpec.describe PagerDuty::CacheGlobalDowntime, type: %i[job aws_helpers] do let(:subject) { described_class.new } let(:client_stub) { instance_double(PagerDuty::MaintenanceClient) } let(:mw_hash) { build(:maintenance_hash) } before do allow(Settings.maintenance).to receive(:services).and_return({ global: 'ABCDEF' }) allow(Settings.maintenance.aws).to receive_messages(access_key_id: 'key', secret_access_key: 'secret', bucket: 'bucket', region: 'region') allow(PagerDuty::MaintenanceClient).to receive(:new) { client_stub } end describe '#perform' do context 'with success response from client' do let(:filename) { 'tmp/maintenance_windows.json' } let(:options) { { 'service_ids' => %w[ABCDEF] } } before { stub_maintenance_windows_s3(filename) } after { File.delete(filename) } it 'uploads an empty list of global downtimes' do allow(client_stub).to receive(:get_all).with(options).and_return([]) subject.perform expect(File.read(filename)).to eq('[]') end it 'uploads a populated list of global downtimes' do allow(client_stub).to receive(:get_all).with(options).and_return([mw_hash]) subject.perform expect(File.read(filename)).to eq("[#{mw_hash.to_json}]") end end context 'with error response from client' do before do allow(Settings.sentry).to receive(:dsn).and_return('asdf') end it 'bails on backend error' do expect(client_stub).to receive(:get_all).and_raise(Common::Exceptions::BackendServiceException) expect(Sentry).to receive(:capture_exception).with(Common::Exceptions::BackendServiceException, level: 'error') subject.perform end it 'bails on client error' do expect(client_stub).to receive(:get_all).and_raise(Common::Client::Errors::ClientError) expect(Sentry).to receive(:capture_exception).with(Common::Client::Errors::ClientError, level: 'error') subject.perform end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/central_mail/submit_form4142_job_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'evss/disability_compensation_auth_headers' # required to build a Form526Submission RSpec.describe CentralMail::SubmitForm4142Job, type: :job do subject { described_class } # Use existing fixture simple.pdf as test input let(:fixture_pdf) { Rails.root.join('spec', 'fixtures', 'pdf_fill', '21-4142', 'simple.pdf') } let(:test_pdf) { Rails.root.join('tmp', 'test_output.pdf') } before do Sidekiq::Job.clear_all # Make Job use old CentralMail route for all tests allow(Flipper).to receive(:enabled?).with(:disability_compensation_form4142_supplemental).and_return(false) # By default, features are enabled in test environments and disabled by default in other environments # This is to ensure that the 2024 4142 template is # not used in tests unless explicitly enabled allow(Flipper).to receive(:enabled?).with(:disability_526_form4142_validate_schema).and_return(false) # Stub out pdf methods as they are not needed for these tests and are cpu expensive FileUtils.cp(fixture_pdf, test_pdf) allow_any_instance_of(EVSS::DisabilityCompensationForm::Form4142Processor).to receive(:fill_form_template) .and_return(test_pdf.to_s) allow_any_instance_of(EVSS::DisabilityCompensationForm::Form4142Processor).to receive(:add_signature_stamp) .and_return(test_pdf.to_s) allow_any_instance_of(EVSS::DisabilityCompensationForm::Form4142Processor).to receive(:add_vagov_timestamp) .and_return(test_pdf.to_s) allow_any_instance_of(EVSS::DisabilityCompensationForm::Form4142Processor).to receive(:submission_date_stamp) .and_return(test_pdf.to_s) end # Clean up the test output file after { FileUtils.rm_f(test_pdf) } ####################### ## CentralMail Route ## ####################### describe 'Test old CentralMail route' do before do # Make Job use old CentralMail route for all tests Flipper.disable(:disability_compensation_form4142_supplemental) end let(:user_account) { user.user_account } let(:user) { create(:user, :loa3, :with_terms_of_use_agreement) } let(:auth_headers) do EVSS::DisabilityCompensationAuthHeaders.new(user).add_headers(EVSS::AuthHeaders.new(user).to_h) end let(:evss_claim_id) { 123_456_789 } let(:saved_claim) { create(:va526ez) } describe '.perform_async' do let(:form_json) do File.read('spec/support/disability_compensation_form/submissions/with_4142.json') end let(:submission) do Form526Submission.create(user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id, form_json:, submitted_claim_id: evss_claim_id) end let(:metadata_hash) do form4142 = submission.form[Form526Submission::FORM_4142] form4142['veteranFullName'].update('first' => "Bey'oncé", 'last' => 'Knowle$-Carter') form4142['veteranAddress'].update('postalCode' => '123456789') subject.perform_async(submission.id) jid = subject.jobs.last['jid'] processor = EVSS::DisabilityCompensationForm::Form4142Processor.new(submission, jid) request_body = processor.request_body JSON.parse(request_body['metadata']) end context 'with a successful submission job' do it 'queues a job for submit' do expect do subject.perform_async(submission.id) end.to change(subject.jobs, :size).by(1) end it 'submits successfully' do VCR.use_cassette('central_mail/submit_4142') do subject.perform_async(submission.id) jid = subject.jobs.last['jid'] described_class.drain expect(jid).not_to be_empty end end it 'uses proper submission creation date for the received date' do received_date = metadata_hash['receiveDt'] # Form4142Processor should use Central Time Zone # See https://dsva.slack.com/archives/C053U7BUT27/p1706808933985779?thread_ts=1706727152.783229&cid=C053U7BUT27 expect( submission.created_at.in_time_zone('Central Time (US & Canada)').strftime('%Y-%m-%d %H:%M:%S') ).to eq(received_date) end it 'corrects for invalid characters in generated metadata' do veteran_first_name = metadata_hash['veteranFirstName'] veteran_last_name = metadata_hash['veteranLastName'] allowed_chars_regex = %r{^[a-zA-Z/\-\s]} expect(veteran_first_name).to match(allowed_chars_regex) expect(veteran_last_name).to match(allowed_chars_regex) end it 'reformats zip code in generated metadata' do zip_code = metadata_hash['zipCode'] expected_zip_format = /\A[0-9]{5}(?:-[0-9]{4})?\z/ expect(zip_code).to match(expected_zip_format) end end context 'with a submission timeout' do before do allow_any_instance_of(Faraday::Connection).to receive(:post).and_raise(Faraday::TimeoutError) end it 'raises a gateway timeout error' do subject.perform_async(submission.id) expect { described_class.drain }.to raise_error(Common::Exceptions::GatewayTimeout) end end context 'with an unexpected error' do before do allow_any_instance_of(Faraday::Connection).to receive(:post).and_raise(StandardError.new('foo')) end it 'raises a standard error' do subject.perform_async(submission.id) expect { described_class.drain }.to raise_error(StandardError) end end end describe '.perform_async for client error' do let(:missing_postalcode_form_json) do File.read 'spec/support/disability_compensation_form/submissions/with_4142_missing_postalcode.json' end let(:submission) do Form526Submission.create(user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id, form_json: missing_postalcode_form_json, submitted_claim_id: evss_claim_id) end context 'with a client error' do it 'raises a central mail response error' do VCR.use_cassette('central_mail/submit_4142_400') do subject.perform_async(submission.id) expect { described_class.drain }.to raise_error(CentralMail::SubmitForm4142Job::CentralMailResponseError) end end end end context 'catastrophic failure state' do describe 'when all retries are exhausted' do let!(:form526_submission) { create(:form526_submission, user_account:) } let!(:form526_job_status) { create(:form526_job_status, :retryable_error, form526_submission:, job_id: 1) } it 'updates a StatsD counter and updates the status on an exhaustion event' do # We are also incrementing a metric when the Form4142DocumentUploadFailureEmail job runs allow(StatsD).to receive(:increment) subject.within_sidekiq_retries_exhausted_block({ 'jid' => form526_job_status.job_id }) do expect(StatsD).to receive(:increment).with("#{subject::CENTRAL_MAIL_STATSD_KEY_PREFIX}.exhausted") expect(Rails).to receive(:logger).and_call_original end form526_job_status.reload expect(form526_job_status.status).to eq(Form526JobStatus::STATUS[:exhausted]) end describe 'when an error occurs during exhaustion handling and FailureEmail fails to enqueue' do let!(:zsf_tag) { Form526Submission::ZSF_DD_TAG_SERVICE } let!(:zsf_monitor) { ZeroSilentFailures::Monitor.new(zsf_tag) } let!(:failure_email) { EVSS::DisabilityCompensationForm::Form4142DocumentUploadFailureEmail } before do Flipper.enable(:form526_send_4142_failure_notification) allow(ZeroSilentFailures::Monitor).to receive(:new).with(zsf_tag).and_return(zsf_monitor) end it 'logs a silent failure' do expect(zsf_monitor).to receive(:log_silent_failure).with( { job_id: form526_job_status.job_id, error_class: nil, error_message: 'An error occurred', timestamp: instance_of(Time), form526_submission_id: form526_submission.id }, user_account.id, call_location: instance_of(Logging::CallLocation) ) args = { 'jid' => form526_job_status.job_id, 'args' => [form526_submission.id] } expect do subject.within_sidekiq_retries_exhausted_block(args) do allow(failure_email).to receive(:perform_async).and_raise(StandardError, 'Simulated error') end end.to raise_error(StandardError, 'Simulated error') end end end end # End of the Old CentralMail Route tests end ###################### ## Lighthouse Route ## ###################### describe 'Test new Lighthouse route' do before do # Make Job use new Lighthouse route for all tests allow(Flipper).to receive(:enabled?).with(:disability_compensation_form4142_supplemental).and_return(true) end let(:user_account) { user.user_account } let(:user) { create(:user, :loa3, :with_terms_of_use_agreement) } let(:auth_headers) do EVSS::DisabilityCompensationAuthHeaders.new(user).add_headers(EVSS::AuthHeaders.new(user).to_h) end let(:evss_claim_id) { 123_456_789 } let(:saved_claim) { create(:va526ez) } describe '.perform_async' do let(:form_json) do File.read('spec/support/disability_compensation_form/submissions/with_4142.json') end let(:submission) do Form526Submission.create(user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id, form_json:, submitted_claim_id: evss_claim_id) end let(:metadata_hash) do form4142 = submission.form[Form526Submission::FORM_4142] form4142['veteranFullName'].update('first' => "Bey'oncé", 'last' => 'Knowle$-Carter') form4142['veteranAddress'].update('postalCode' => '123456789') subject.perform_async(submission.id) jid = subject.jobs.last['jid'] processor = EVSS::DisabilityCompensationForm::Form4142Processor.new(submission, jid) request_body = processor.request_body JSON.parse(request_body['metadata']) end context 'with a successful submission job' do it 'queues a job for submit' do expect do subject.perform_async(submission.id) end.to change(subject.jobs, :size).by(1) end it 'Creates a form 4142 submission polling record, when enabled' do Flipper.enable(CentralMail::SubmitForm4142Job::POLLING_FLIPPER_KEY) expect do VCR.use_cassette('lighthouse/benefits_intake/200_lighthouse_intake_upload_location') do VCR.use_cassette('lighthouse/benefits_intake/200_lighthouse_intake_upload') do subject.perform_async(submission.id) described_class.drain end end end.to change(FormSubmission, :count).by(1) .and change(FormSubmissionAttempt, :count).by(1) fs_record = FormSubmission.last fs_attempt_record = FormSubmissionAttempt.last expect(Form526Submission.find_by(saved_claim_id: fs_record.saved_claim_id).id).to eq(submission.id) expect(fs_attempt_record.pending?).to be(true) end it 'Returns successfully after creating polling record' do Flipper.enable(CentralMail::SubmitForm4142Job::POLLING_FLIPPER_KEY) Sidekiq::Testing.inline! do VCR.use_cassette('lighthouse/benefits_intake/200_lighthouse_intake_upload_location') do VCR.use_cassette('lighthouse/benefits_intake/200_lighthouse_intake_upload') do allow_any_instance_of(SemanticLogger::Logger).to receive(:info).and_return(true) jid = subject.perform_async(submission.id) subject.drain job_status_record = submission.form526_job_statuses.find_by(job_id: jid) Rails.logger.level expect(job_status_record).not_to be_nil expect(job_status_record.job_class).to eq('SubmitForm4142Job') expect(job_status_record.status).to eq('success') end end end end it 'Does not create a form 4142 submission polling record, when disabled' do Flipper.disable(CentralMail::SubmitForm4142Job::POLLING_FLIPPER_KEY) expect do VCR.use_cassette('lighthouse/benefits_intake/200_lighthouse_intake_upload_location') do VCR.use_cassette('lighthouse/benefits_intake/200_lighthouse_intake_upload') do subject.perform_async(submission.id) described_class.drain end end end.to not_change(FormSubmission, :count) .and not_change(FormSubmissionAttempt, :count) end it 'submits successfully' do VCR.use_cassette('lighthouse/benefits_intake/200_lighthouse_intake_upload_location') do VCR.use_cassette('lighthouse/benefits_intake/200_lighthouse_intake_upload') do subject.perform_async(submission.id) jid = subject.jobs.last['jid'] described_class.drain expect(jid).not_to be_empty end end end it 'uses proper submission creation date for the received date' do received_date = metadata_hash['receiveDt'] # Form4142Processor should use Central Time Zone # See https://dsva.slack.com/archives/C053U7BUT27/p1706808933985779?thread_ts=1706727152.783229&cid=C053U7BUT27 expect( submission.created_at.in_time_zone('Central Time (US & Canada)').strftime('%Y-%m-%d %H:%M:%S') ).to eq(received_date) end it 'corrects for invalid characters in generated metadata' do veteran_first_name = metadata_hash['veteranFirstName'] veteran_last_name = metadata_hash['veteranLastName'] allowed_chars_regex = %r{^[a-zA-Z/\-\s]} expect(veteran_first_name).to match(allowed_chars_regex) expect(veteran_last_name).to match(allowed_chars_regex) end it 'reformats zip code in generated metadata' do zip_code = metadata_hash['zipCode'] expected_zip_format = /\A[0-9]{5}(?:-[0-9]{4})?\z/ expect(zip_code).to match(expected_zip_format) end end context 'with a submission timeout' do before do allow_any_instance_of(Faraday::Connection).to receive(:post).and_raise(Faraday::TimeoutError) end it 'raises a gateway timeout error' do subject.perform_async(submission.id) expect { described_class.drain }.to raise_error(Common::Exceptions::GatewayTimeout) end end context 'with an unexpected error' do before do allow_any_instance_of(Faraday::Connection).to receive(:post).and_raise(StandardError.new('foo')) end it 'raises a standard error' do subject.perform_async(submission.id) expect { described_class.drain }.to raise_error(StandardError) end end end describe '.perform_async for client error' do let(:missing_postalcode_form_json) do File.read 'spec/support/disability_compensation_form/submissions/with_4142_missing_postalcode.json' end let(:submission) do Form526Submission.create(user_uuid: user.uuid, user_account:, auth_headers_json: auth_headers.to_json, saved_claim_id: saved_claim.id, form_json: missing_postalcode_form_json, submitted_claim_id: evss_claim_id) end context 'with a client error' do it 'raises a central mail response error' do skip 'The VCR cassette needs to be changed to contain Lighthouse specific data.' VCR.use_cassette('lighthouse/benefits_intake/200_lighthouse_intake_upload') do subject.perform_async(submission.id) expect { described_class.drain }.to raise_error(CentralMail::SubmitForm4142Job::CentralMailResponseError) end end end end context 'catastrophic failure state' do describe 'when all retries are exhausted' do let!(:form526_submission) { create(:form526_submission) } let!(:form526_job_status) { create(:form526_job_status, :retryable_error, form526_submission:, job_id: 1) } it 'updates a StatsD counter and updates the status on an exhaustion event' do # We are also incrementing a metric when the Form4142DocumentUploadFailureEmail job runs allow(StatsD).to receive(:increment) subject.within_sidekiq_retries_exhausted_block({ 'jid' => form526_job_status.job_id }) do expect(StatsD).to receive(:increment).with("#{subject::LIGHTHOUSE_STATSD_KEY_PREFIX}.exhausted") expect(Rails).to receive(:logger).and_call_original end form526_job_status.reload expect(form526_job_status.status).to eq(Form526JobStatus::STATUS[:exhausted]) end context 'when the form526_send_4142_failure_notification Flipper is enabled' do before do Flipper.enable(:form526_send_4142_failure_notification) end it 'enqueues a failure notification mailer to send to the veteran' do subject.within_sidekiq_retries_exhausted_block( { 'jid' => form526_job_status.job_id, 'args' => [form526_submission.id] } ) do expect(EVSS::DisabilityCompensationForm::Form4142DocumentUploadFailureEmail) .to receive(:perform_async).with(form526_submission.id) end end end context 'when the form526_send_4142_failure_notification Flipper is disabled' do before do Flipper.disable(:form526_send_4142_failure_notification) end it 'does not enqueue a failure notification mailer to send to the veteran' do subject.within_sidekiq_retries_exhausted_block( { 'jid' => form526_job_status.job_id, 'args' => [form526_submission.id] } ) do expect(EVSS::DisabilityCompensationForm::Form4142DocumentUploadFailureEmail) .not_to receive(:perform_async) end end end end end # End of the new Lighthouse Route tests end # End of the overall Spec end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/income_limits/std_county_import_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'csv' RSpec.describe IncomeLimits::StdCountyImport, type: :worker do describe '#perform' do # rubocop:disable Layout/LineLength let(:csv_data) do %(ID,NAME,COUNTYNUMBER,DESCRIPTION,STATE_ID,VERSION,CREATED,UPDATED,CREATEDBY,UPDATEDBY\n1,County A,123,Description A,456,1,2010-02-19 08:36:52 +0000,2010-03-19 08:36:52 +0000,John,Sam) end # rubocop:enable Layout/LineLength before do allow_any_instance_of(IncomeLimits::StdCountyImport).to receive(:fetch_csv_data).and_return(csv_data) end it 'populates gmt thresholds' do IncomeLimits::StdCountyImport.new.perform expect(StdCounty.find_by(name: 'County A')).not_to be_nil expect(StdCounty.find_by(county_number: 123)).not_to be_nil end context 'when a matching record does not exist' do it 'creates a new record' do expect do described_class.new.perform end.to change(StdCounty, :count).by(1) end it 'sets the attributes correctly' do described_class.new.perform county = StdCounty.last expect(county.name).to eq('County A') expect(county.county_number).to eq(123) expect(county.description).to eq('Description A') expect(county.state_id).to eq(456) expect(county.version).to eq(1) expect(county.created_by).to eq('John') expect(county.updated_by).to eq('Sam') end end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/income_limits/std_income_threshold_import_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'csv' RSpec.describe IncomeLimits::StdIncomeThresholdImport, type: :worker do describe '#perform' do # rubocop:disable Layout/LineLength let(:csv_data) do %(ID,INCOME_THRESHOLD_YEAR,EXEMPT_AMOUNT,MEDICAL_EXPENSE_DEDUCTIBLE,CHILD_INCOME_EXCLUSION,DEPENDENT,ADD_DEPENDENT_THRESHOLD,PROPERTY_THRESHOLD,PENSION_THRESHOLD,PENSION_1_DEPENDENT,ADD_DEPENDENT_PENSION,NINETY_DAY_HOSPITAL_COPAY,ADD_90_DAY_HOSPITAL_COPAY,OUTPATIENT_BASIC_CARE_COPAY,OUTPATIENT_SPECIALTY_COPAY,THRESHOLD_EFFECTIVE_DATE,AID_AND_ATTENDANCE_THRESHOLD,OUTPATIENT_PREVENTIVE_COPAY,MEDICATION_COPAY,MEDICATIN_COPAY_ANNUAL_CAP,LTC_INPATIENT_COPAY,LTC_OUTPATIENT_COPAY,LTC_DOMICILIARY_COPAY,INPATIENT_PER_DIEM,DESCRIPTION,VERSION,CREATED,UPDATED,CREATED_BY,UPDATED_BY\n1,2023,1000,200,500,2,300,100000,15000,5000,2000,50,25,10,15,01/01/2023,300,5,5,1000,75,100,50,250,Description A,1,2010-02-19 08:36:52 +0000,2010-02-19 08:36:52 +0000,John,Sam) end # rubocop:enable Layout/LineLength before do allow_any_instance_of(IncomeLimits::StdIncomeThresholdImport).to receive(:fetch_csv_data).and_return(csv_data) end it 'populates income limits' do IncomeLimits::StdIncomeThresholdImport.new.perform expect(StdIncomeThreshold.find_by(income_threshold_year: 2023)).not_to be_nil expect(StdIncomeThreshold.find_by(exempt_amount: 1000)).not_to be_nil end it 'creates a new StdIncomeThreshold record' do expect do described_class.new.perform end.to change(StdIncomeThreshold, :count).by(1) end it 'sets the attributes correctly' do described_class.new.perform threshold = StdIncomeThreshold.last expect(threshold.income_threshold_year).to eq(2023) expect(threshold.pension_threshold).to eq(15_000) expect(threshold.pension_1_dependent).to eq(5000) expect(threshold.add_dependent_pension).to eq(2000) end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/income_limits/std_state_import_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'csv' RSpec.describe IncomeLimits::StdStateImport, type: :worker do describe '#perform' do # rubocop:disable Layout/LineLength let(:csv_data) do %(ID,NAME,POSTALNAME,FIPSCODE,COUNTRY_ID,VERSION,CREATED,UPDATED,CREATEDBY,UPDATEDBY\n1,Maine,Sample County,123,2,1,2010-02-19 08:36:52 +0000,2010-03-19 08:36:52 +0000,John,Sam) end # rubocop:enable Layout/LineLength before do allow_any_instance_of(IncomeLimits::StdStateImport).to receive(:fetch_csv_data).and_return(csv_data) end it 'populates states' do IncomeLimits::StdStateImport.new.perform expect(StdState.find_by(name: 'Maine')).not_to be_nil expect(StdState.find_by(fips_code: 123)).not_to be_nil end it 'creates a new StdState record' do expect do described_class.new.perform end.to change(StdState, :count).by(1) end it 'sets the attributes correctly' do described_class.new.perform state = StdState.last expect(state.name).to eq('Maine') expect(state.postal_name).to eq('Sample County') expect(state.fips_code).to eq(123) expect(state.country_id).to eq(2) expect(state.version).to eq(1) end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/income_limits/gmt_thresholds_import_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'csv' RSpec.describe IncomeLimits::GmtThresholdsImport, type: :worker do describe '#perform' do # rubocop:disable Layout/LineLength let(:csv_data) do %(ID,EFFECTIVEYEAR,STATENAME,COUNTYNAME,FIPS,TRHD1,TRHD2,TRHD3,TRHD4,TRHD5,TRHD6,TRHD7,TRHD8,MSA,MSANAME,VERSION,CREATED,UPDATED,CREATEDBY,UPDATEDBY\n1,2023,State A,County X,123,100,200,300,400,500,600,700,800,900,MSA A,1,2010-02-19 08:36:52 +0000,2010-03-19 08:36:52 +0000,John,Sam) end # rubocop:enable Layout/LineLength before do allow_any_instance_of(IncomeLimits::GmtThresholdsImport).to receive(:fetch_csv_data).and_return(csv_data) end it 'populates gmt thresholds' do IncomeLimits::GmtThresholdsImport.new.perform expect(GmtThreshold.find_by(effective_year: 2023)).not_to be_nil expect(GmtThreshold.find_by(county_name: 'County X')).not_to be_nil end it 'creates a new StdState record' do expect do described_class.new.perform end.to change(GmtThreshold, :count).by(1) end it 'sets the attributes correctly' do described_class.new.perform threshold = GmtThreshold.last expect(threshold.effective_year).to eq(2023) expect(threshold.state_name).to eq('State A') expect(threshold.county_name).to eq('County X') expect(threshold.fips).to eq(123) expect(threshold.trhd1).to eq(100) expect(threshold.trhd2).to eq(200) expect(threshold.trhd3).to eq(300) expect(threshold.trhd4).to eq(400) expect(threshold.trhd5).to eq(500) expect(threshold.trhd6).to eq(600) expect(threshold.trhd7).to eq(700) expect(threshold.trhd8).to eq(800) expect(threshold.msa).to eq(900) expect(threshold.msa_name).to eq('MSA A') expect(threshold.version).to eq(1) expect(threshold.created_by).to eq('John') expect(threshold.updated_by).to eq('Sam') end end end
0
code_files/vets-api-private/spec/sidekiq
code_files/vets-api-private/spec/sidekiq/income_limits/std_zipcode_import_spec.rb
# frozen_string_literal: true require 'rails_helper' require 'csv' RSpec.describe IncomeLimits::StdZipcodeImport, type: :worker do describe '#perform' do # rubocop:disable Layout/LineLength let(:csv_data) do %(ID,ZIPCODE,ZIPCLASSIFICATION_ID,PREFERREDZIPPLACE_ID,STATE_ID,COUNTYNUMBER,VERSION,CREATED,UPDATED,CREATEDBY,UPDATEDBY\n1,12345,1,2,3,123,5,2010-02-19 08:36:52 +0000,2010-03-19 08:36:52 +0000,John,Sam) end # rubocop:enable Layout/LineLength before do allow_any_instance_of(IncomeLimits::StdZipcodeImport).to receive(:fetch_csv_data).and_return(csv_data) end it 'populates zipcodes' do IncomeLimits::StdZipcodeImport.new.perform expect(StdZipcode.find_by(zip_code: '12345')).not_to be_nil expect(StdZipcode.find_by(county_number: 123)).not_to be_nil end context 'when a matching record does exist' do it 'creates a new record' do expect do described_class.new.perform end.to change(StdZipcode, :count).by(1) end it 'sets the attributes correctly' do described_class.new.perform zipcode = StdZipcode.last expect(zipcode.zip_code).to eq('12345') expect(zipcode.zip_classification_id).to eq(1) expect(zipcode.preferred_zip_place_id).to eq(2) expect(zipcode.state_id).to eq(3) expect(zipcode.county_number).to eq(123) expect(zipcode.version).to eq(5) expect(zipcode.created_by).to eq('John') expect(zipcode.updated_by).to eq('Sam') end end end end
0
code_files/vets-api-private/spec
code_files/vets-api-private/spec/mailers/year_to_date_report_mailer_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe YearToDateReportMailer, type: %i[mailer aws_helpers] do describe '#year_to_date_report_email' do subject do stub_reports_s3(filename) do mail end end let(:filename) { 'foo' } let(:mail) { described_class.build(filename).deliver_now } context 'when sending staging emails' do before do expect(FeatureFlipper).to receive(:staging_email?).once.and_return(true) end it 'sends the right email' do subject text = described_class::REPORT_TEXT expect(mail.body.encoded).to eq("#{text} (link expires in one week)<br>#{subject}") expect(mail.subject).to eq(text) end it 'emails the the right staging recipients' do subject expect(mail.to).to eq( %w[ Brian.Grubb@va.gov Joseph.Preisser@va.gov kyle.pietrosanto@va.gov lee.munson@va.gov lihan@adhocteam.us Lucas.Tickner@va.gov matthew.ziolkowski@va.gov Michael.Johnson19@va.gov patrick.burk@va.gov preston.sanders@va.gov robyn.noles@va.gov Ricardo.DaSilva@va.gov tammy.hurley1@va.gov vfep_support_team@va.gov eugenia.gina.ronat@accenturefederal.com morgan.whaley@accenturefederal.com m.c.shah@accenturefederal.com d.a.barnes@accenturefederal.com jacob.finnern@accenturefederal.com hocine.halli@accenturefederal.com adam.freemer@accenturefederal.com ] ) end end context 'when not sending staging emails' do before do expect(FeatureFlipper).to receive(:staging_email?).once.and_return(false) end it 'emails the va stakeholders' do subject expect(mail.to).to eq( %w[ 222A.VBAVACO@va.gov 224B.VBAVACO@va.gov 224C.VBAVACO@va.gov Brandon.Scott2@va.gov Brian.Grubb@va.gov Christina.DiTucci@va.gov EDU.VBAMUS@va.gov John.McNeal@va.gov Joseph.Preisser@va.gov Joshua.Lashbrook@va.gov kathleen.dalfonso@va.gov kyle.pietrosanto@va.gov Lucas.Tickner@va.gov michele.mendola@va.gov Ricardo.DaSilva@va.gov shay.norton@va.gov tammy.hurley1@va.gov ] ) end end end end
0
code_files/vets-api-private/spec
code_files/vets-api-private/spec/mailers/create_daily_spool_files_mailer_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe CreateDailySpoolFilesMailer, type: %i[mailer aws_helpers] do describe 'with RPO' do subject do described_class.build('eastern').deliver_now end # Commented out until email addreses are added back to Settings.edu.spool_error.staging_emails # context 'when sending staging emails' do # before do # expect(FeatureFlipper).to receive(:staging_email?).once.and_return(true) # end # # it 'sends the right email' do # date = Time.zone.now.strftime('%m%d%Y') # rpo_name = EducationForm::EducationFacility.rpo_name(region: 'eastern') # body = "There was an error generating the spool file for #{rpo_name} on #{date}" # subject_txt = "Error Generating Spool file on #{date}" # expect(subject.body.raw_source).to eq(body) # expect(subject.subject).to eq(subject_txt) # end # it 'emails the the right staging recipients' do # expect(subject.to).to eq([]) # end # end context 'when not sending staging emails' do before do expect(FeatureFlipper).to receive(:staging_email?).once.and_return(false) end it 'emails the the right recipients' do expect(subject.to).to eq( %w[ Joseph.Preisser@va.gov Shay.Norton-Leonard@va.gov PIERRE.BROWN@va.gov VAVBAHIN/TIMS@vba.va.gov EDUAPPMGMT.VBACO@VA.GOV vfep_support_team@va.gov eugenia.gina.ronat@accenturefederal.com morgan.whaley@accenturefederal.com m.c.shah@accenturefederal.com patrick.arthur@accenturefederal.com adam.freemer@accenturefederal.com dan.brooking@accenturefederal.com sebastian.cooper@accenturefederal.com david.rowley@accenturefederal.com nick.barthelemy@accenturefederal.com ] ) end end end describe 'without RPO' do subject do described_class.build.deliver_now end before do expect(FeatureFlipper).to receive(:staging_email?).once.and_return(false) end it 'has correct body' do date = Time.zone.now.strftime('%m%d%Y') body = "There was an error generating the spool files on #{date}" expect(subject.body.raw_source).to eq(body) end end end
0
code_files/vets-api-private/spec
code_files/vets-api-private/spec/mailers/stem_applicant_confirmation_mailer_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe StemApplicantConfirmationMailer, type: [:mailer] do subject do described_class.build(saved_claim, ga_client_id).deliver_now end let(:saved_claim) do claim = build(:va10203) claim.save claim end let(:applicant) { saved_claim.open_struct_form } let(:ga_client_id) { '123456543' } describe '#build' do it 'includes subject' do expect(subject.subject).to eq(StemApplicantConfirmationMailer::SUBJECT) end it 'includes recipients' do expect(subject.to).to eq([applicant.email]) end context 'applicant information in email body' do it 'includes veteran name' do name = applicant.veteranFullName first_and_last_name = "#{name.first} #{name.last}" expect(subject.body.raw_source).to include("for #{first_and_last_name}") end it 'includes confirmation number' do expect(subject.body.raw_source).to include("Confirmation number #{applicant.confirmation_number}") end it 'includes date received' do date_received = saved_claim.created_at.strftime('%b %d, %Y') expect(subject.body.raw_source).to include("Date received #{date_received}") end it 'includes Eastern RPO name' do expect(subject.body.raw_source).to include(EducationForm::EducationFacility::EMAIL_NAMES[:eastern]) end it 'includes Eastern RPO address' do expect(subject.body.raw_source).to include(EducationForm::EducationFacility::ADDRESSES[:eastern][0]) end it 'includes Eastern RPO address city, state, and zip' do expect(subject.body.raw_source).to include(EducationForm::EducationFacility::ADDRESSES[:eastern][1]) end end end end
0
code_files/vets-api-private/spec
code_files/vets-api-private/spec/mailers/spool10203_submissions_report_mailer_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe Spool10203SubmissionsReportMailer, type: %i[mailer aws_helpers] do describe '#build' do subject do stub_reports_s3(filename) do mail end end let(:filename) { 'foo' } let(:mail) { described_class.build(filename).deliver_now } context 'when sending staging emails' do before do expect(FeatureFlipper).to receive(:staging_email?).once.and_return(true) end it 'sends the right email' do subject text = described_class::REPORT_TEXT expect(mail.body.encoded).to eq("#{text} (link expires in one week)<br>#{subject}") expect(mail.subject).to eq(text) end it 'emails the the right staging recipients' do subject expect(mail.to).to eq( %w[ Brian.Grubb@va.gov Joseph.Preisser@va.gov kyle.pietrosanto@va.gov lihan@adhocteam.us Lucas.Tickner@va.gov Ricardo.DaSilva@va.gov tammy.hurley1@va.gov vfep_support_team@va.gov eugenia.gina.ronat@accenturefederal.com morgan.whaley@accenturefederal.com m.c.shah@accenturefederal.com d.a.barnes@accenturefederal.com jacob.finnern@accenturefederal.com hocine.halli@accenturefederal.com adam.freemer@accenturefederal.com ] ) end end context 'when not sending staging emails' do before do expect(FeatureFlipper).to receive(:staging_email?).once.and_return(false) end it 'emails the the right recipients' do subject expect(mail.to).to eq( %w[ Brian.Grubb@va.gov dana.kuykendall@va.gov Jennifer.Waltz2@va.gov Joseph.Preisser@va.gov Joshua.Lashbrook@va.gov kathleen.dalfonso@va.gov kyle.pietrosanto@va.gov lihan@adhocteam.us Lucas.Tickner@va.gov Ricardo.DaSilva@va.gov robert.shinners@va.gov shay.norton@va.gov tammy.hurley1@va.gov ] ) end end end end
0
code_files/vets-api-private/spec
code_files/vets-api-private/spec/mailers/spool_submissions_report_mailer_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe SpoolSubmissionsReportMailer, type: %i[mailer aws_helpers] do describe '#build' do subject do stub_reports_s3(filename) do mail end end let(:filename) { 'foo' } let(:mail) { described_class.build(filename).deliver_now } context 'when sending staging emails' do before do expect(FeatureFlipper).to receive(:staging_email?).once.and_return(true) end it 'sends the right email' do subject text = described_class::REPORT_TEXT expect(mail.body.encoded).to eq("#{text} (link expires in one week)<br>#{subject}") expect(mail.subject).to eq(text) end it 'emails the the right staging recipients' do subject expect(mail.to).to eq( %w[ Brian.Grubb@va.gov Joseph.Preisser@va.gov kyle.pietrosanto@va.gov lihan@adhocteam.us Lucas.Tickner@va.gov Ricardo.DaSilva@va.gov tammy.hurley1@va.gov vfep_support_team@va.gov eugenia.gina.ronat@accenturefederal.com morgan.whaley@accenturefederal.com m.c.shah@accenturefederal.com d.a.barnes@accenturefederal.com jacob.finnern@accenturefederal.com hocine.halli@accenturefederal.com adam.freemer@accenturefederal.com ] ) end end context 'when not sending staging emails' do before do expect(FeatureFlipper).to receive(:staging_email?).once.and_return(false) end it 'emails the the right recipients' do subject expect(mail.to).to eq( %w[ Brian.Grubb@va.gov dana.kuykendall@va.gov Jennifer.Waltz2@va.gov Joseph.Preisser@va.gov Joshua.Lashbrook@va.gov kathleen.dalfonso@va.gov kyle.pietrosanto@va.gov lihan@adhocteam.us Lucas.Tickner@va.gov Ricardo.DaSilva@va.gov shay.norton@va.gov tammy.hurley1@va.gov ] ) end end end end
0
code_files/vets-api-private/spec
code_files/vets-api-private/spec/mailers/dependents_application_failure_mailer_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe DependentsApplicationFailureMailer, type: [:mailer] do include ActionView::Helpers::TranslationHelper let(:user) { create(:evss_user, :loa3) } let(:recipients) do [user.email] end describe '#build' do it 'includes all info' do mailer = described_class.build(user).deliver_now expect(mailer.subject).to eq(t('dependency_claim_failure_mailer.subject')) expect(mailer.to).to eq(recipients) expect(mailer.body.raw_source).to include( "Dear #{user.first_name} #{user.last_name}", 'We’re sorry. Something went wrong when we tried to submit your application to add or remove a dependent' ) end end end
0
code_files/vets-api-private/spec
code_files/vets-api-private/spec/mailers/rrd_mas_notification_mailer_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe RrdMasNotificationMailer, type: [:mailer] do let(:email) do described_class.build(submission) end context 'when building an email with a disability name and diagnostic code' do let(:submission) { create(:form526_submission, :with_everything) } it 'includes the DC but not the name in the body' do expect(email.body).to include('9999') expect(email.body).not_to include('PTSD') end end end
0
code_files/vets-api-private/spec
code_files/vets-api-private/spec/mailers/create_staging_spool_files_mailer_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe CreateStagingSpoolFilesMailer, type: %i[mailer aws_helpers] do describe '#build' do subject do contents = File.read('spec/fixtures/education_form/stagingspool.txt') described_class.build(contents).deliver_now end context 'when sending emails' do it 'sends the right email' do date = Time.zone.now.strftime('%m%d%Y') subject_txt = "Staging Spool file on #{date}" body = "The staging spool file for #{date}" expect(subject.subject).to eq(subject_txt) expect(subject.body.raw_source).to include(body) end end end end
0
code_files/vets-api-private/spec
code_files/vets-api-private/spec/mailers/transactional_email_mailer_spec.rb
# frozen_string_literal: true require 'rails_helper' RSpec.describe TransactionalEmailMailer, type: [:mailer] do subject do described_class.build(email, google_analytics_client_id).deliver_now end let(:email) { 'foo@example.com' } let(:google_analytics_client_id) { '123456543' } describe 'as a parent class' do it 'cannot be called directly due to missing constants' do expect { subject }.to raise_error(NameError) end TransactionalEmailMailer.descendants.each do |mailer| it "requires #{mailer.name} subclass to define required constants" do expect(mailer::SUBJECT).to be_present expect(mailer::GA_CAMPAIGN_NAME).to be_present expect(mailer::GA_DOCUMENT_PATH).to be_present expect(mailer::GA_LABEL).to be_present expect(mailer::TEMPLATE).to be_present end end end end