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/models
|
code_files/vets-api-private/spec/models/bgs_dependents/marriage_history_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe BGSDependents::MarriageHistory do
let(:marriage_history_info) do
{
'start_date' => '2007-04-03',
'start_location' => { 'state' => 'AK', 'city' => 'Rock Island' },
'reason_marriage_ended' => 'Other',
'reason_marriage_ended_other' => 'Some other reason',
'end_date' => '2009-05-05',
'end_location' => { 'state' => 'IL', 'city' => 'Chicago' },
'full_name' => { 'first' => 'Billy', 'middle' => 'Yohan', 'last' => 'Johnson', 'suffix' => 'Sr.' }
}
end
let(:formatted_params_result) do
{
'start_date' => '2007-04-03',
'end_date' => '2009-05-05',
'marriage_country' => nil,
'marriage_state' => 'AK',
'marriage_city' => 'Rock Island',
'divorce_state' => 'IL',
'divorce_city' => 'Chicago',
'divorce_country' => nil,
'marriage_termination_type_code' => 'Other',
'first' => 'Billy',
'middle' => 'Yohan',
'last' => 'Johnson',
'suffix' => 'Sr.'
}
end
describe '#format_info' do
it 'formats marriage history params for submission' do
formatted_info = described_class.new(marriage_history_info).format_info
expect(formatted_info).to eq(formatted_params_result)
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/bgs_dependents/spouse_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe BGSDependents::Spouse do
let(:veteran_spouse) { build(:spouse) }
let(:spouse) { described_class.new(veteran_spouse['dependents_application']) }
let(:format_info_output) do
{
'ssn' => '323454323',
'birth_date' => '1981-04-04',
'ever_married_ind' => 'Y',
'martl_status_type_cd' => 'Married',
'vet_ind' => 'Y',
'first' => 'Jenny',
'middle' => 'Lauren',
'last' => 'McCarthy',
'suffix' => 'Sr.',
'va_file_number' => '00000000'
}
end
let(:spouse_info) do
{
'ssn' => '323454323',
'birth_date' => '1981-04-04',
'ever_married_ind' => 'Y',
'martl_status_type_cd' => 'Married',
'vet_ind' => 'Y',
'lives_with_vet' => true,
'alt_address' => nil,
'first' => 'Jenny',
'middle' => 'Lauren',
'last' => 'McCarthy',
'suffix' => 'Sr.'
}
end
let(:address_output) do
{
'country_name' => 'USA',
'address_line1' => '8200 Doby LN',
'city' => 'Pasadena',
'state_code' => 'CA',
'zip_code' => '21122'
}
end
describe '#format_info' do
it 'formats relationship params for submission' do
formatted_info = spouse.format_info
expect(formatted_info).to include(format_info_output)
end
end
describe '#address' do
it 'returns an address for vet or spouse if separated' do
address = spouse.address
expect(address).to eq(address_output)
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/bgs_dependents/adult_child_attending_school_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe BGSDependents::AdultChildAttendingSchool do
let(:all_flows_payload) { build(:form_686c_674_kitchen_sink) }
let(:adult_child_attending_school) do
described_class.new(all_flows_payload['dependents_application'])
end
let(:formatted_info_response) do
{
'ssn' => '370947141',
'birth_date' => '2001-03-03',
'ever_married_ind' => 'Y',
'first' => 'Ernie',
'middle' => 'bubkis',
'last' => 'McCracken',
'suffix' => 'II',
'dependent_income' => 'Y'
}
end
let(:address_response) do
{
'country_name' => 'USA',
'address_line1' => '20374 Alexander Hamilton St',
'address_line2' => 'apt 4',
'address_line3' => 'Bldg 44',
'city' => 'Arroyo Grande',
'state_code' => 'CA',
'zip_code' => '93420'
}
end
describe '#format_info' do
it 'formats info' do
formatted_info = adult_child_attending_school.format_info
expect(formatted_info).to eq(formatted_info_response)
end
end
describe '#address' do
it 'formats info' do
address = adult_child_attending_school.address
expect(address).to eq(address_response)
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/bgs_dependents/child_marriage_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe BGSDependents::ChildMarriage do
let(:child_marriage_info) do
{
'date_married' => '1977-02-01',
'ssn' => '555612341',
'birth_date' => '2020-01-01',
'full_name' => { 'first' => 'Billy', 'middle' => 'Yohan', 'last' => 'Johnson', 'suffix' => 'Sr.' },
'dependent_income' => true
}
end
let(:formatted_params_result) do
{
'event_date' => '1977-02-01',
'first' => 'Billy',
'middle' => 'Yohan',
'last' => 'Johnson',
'suffix' => 'Sr.',
'ssn' => '555612341',
'birth_date' => '2020-01-01',
'ever_married_ind' => 'Y',
'dependent_income' => 'Y'
}
end
describe '#format_info' do
it 'formats child marriage params for submission' do
formatted_info = described_class.new(child_marriage_info).format_info
expect(formatted_info).to eq(formatted_params_result)
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/bgs_dependents/step_child_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe BGSDependents::StepChild do
let(:stepchild_info) do
{
'supporting_stepchild' => true,
'living_expenses_paid' => 'Half',
'ssn' => '213685794',
'birth_date' => '2010-03-03',
'who_does_the_stepchild_live_with' => { 'first' => 'Adam', 'middle' => 'Steven', 'last' => 'Huberws' },
'address' => {
'country_name' => 'USA',
'address_line1' => '412 Crooks Road',
'city' => 'Clawson',
'state_code' => 'AL',
'zip_code' => '48017'
},
'full_name' => { 'first' => 'Billy', 'middle' => 'Yohan', 'last' => 'Johnson', 'suffix' => 'Sr.' }
}
end
let(:formatted_params_result) do
{
'living_expenses_paid' => '.5',
'lives_with_relatd_person_ind' => 'N',
'first' => 'Billy',
'middle' => 'Yohan',
'last' => 'Johnson',
'ssn' => '213685794',
'birth_date' => '2010-03-03',
'suffix' => 'Sr.'
}
end
describe '#format_info' do
it 'formats stepchild params for submission' do
formatted_info = described_class.new(stepchild_info).format_info
expect(formatted_info).to eq(formatted_params_result)
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/bgs_dependents/child_student_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe BGSDependents::ChildStudent do
let(:all_flows_payload) { build(:form_686c_674_kitchen_sink) }
let(:child_student_info) do
described_class.new(all_flows_payload['dependents_application'], '3829729', '149471')
end
let(:formatted_params_result) do
{
vnp_proc_id: '3829729',
vnp_ptcpnt_id: '149471',
saving_amt: '3455',
real_estate_amt: '5623',
other_asset_amt: '4566',
rmks: 'Some remarks about the student\'s net worth',
marage_dt: DateTime.parse('2015-03-04 12:00:00').to_time.iso8601,
agency_paying_tuitn_nm: 'Some Agency',
stock_bond_amt: '3234',
govt_paid_tuitn_ind: 'Y',
govt_paid_tuitn_start_dt: DateTime.parse('2019-02-03 12:00:00').to_time.iso8601,
term_year_emplmt_income_amt: '12000',
term_year_other_income_amt: '5596',
term_year_ssa_income_amt: '3453',
term_year_annty_income_amt: '30595',
next_year_annty_income_amt: '3989',
next_year_emplmt_income_amt: '12000',
next_year_other_income_amt: '984',
next_year_ssa_income_amt: '3940',
acrdtdSchoolInd: 'Y',
atndedSchoolCntnusInd: 'N',
stopedAtndngSchoolDt: nil
}
end
describe '#params_for_686c' do
it 'formats child student params for submission' do
formatted_info = child_student_info.params_for_686c
expect(formatted_info).to eq(formatted_params_result)
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/bgs_dependents/relationship_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe BGSDependents::Relationship do
let(:event_date) { '2001/02/03' }
let(:dependent) do
{
vnp_participant_id: '146189',
participant_relationship_type_name: 'Spouse',
family_relationship_type_name: 'Spouse',
marriage_state: 'FL',
marriage_city: 'Tampa',
event_date:
}
end
let(:params_response) do
{
vnp_proc_id: '1234',
vnp_ptcpnt_id_a: '1234',
vnp_ptcpnt_id_b: '146189',
ptcpnt_rlnshp_type_nm: 'Spouse',
family_rlnshp_type_nm: 'Spouse',
event_dt: DateTime.parse("#{event_date} 12:00:00").to_time.iso8601
}
end
describe 'params for 686c' do
it 'formats relationship params for submission' do
expect(
described_class.new('1234')
.params_for_686c('1234', dependent)
).to include(params_response)
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/bgs_dependents/child_school_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe BGSDependents::ChildSchool do
let(:all_flows_payload) { build(:form_686c_674_kitchen_sink) }
let(:child_school_info) do
described_class.new(all_flows_payload['dependents_application'], '3829729', '149471')
end
let(:formatted_params_result) do
{
vnp_proc_id: '3829729',
vnp_ptcpnt_id: '149471',
last_term_start_dt: DateTime.parse('2016-03-04 12:00:00').to_time.iso8601,
last_term_end_dt: DateTime.parse('2017-04-05 12:00:00').to_time.iso8601,
prev_hours_per_wk_num: 40,
prev_sessns_per_wk_num: 4,
prev_school_nm: 'Another Amazing School',
prev_school_cntry_nm: 'USA',
prev_school_addrs_one_txt: '20374 twenty ninth St',
prev_school_city_nm: 'Rock Island',
prev_school_postal_cd: 'IL',
prev_school_addrs_zip_nbr: '61201',
curnt_school_nm: 'My Great School',
curnt_school_addrs_one_txt: '55 twenty ninth St',
curnt_school_postal_cd: 'AR',
curnt_school_city_nm: 'Rock Island',
curnt_school_addrs_zip_nbr: '61201',
curnt_school_cntry_nm: 'USA',
course_name_txt: 'Something amazing',
curnt_sessns_per_wk_num: 4,
curnt_hours_per_wk_num: 37,
school_actual_expctd_start_dt: '2019-03-03',
school_term_start_dt: DateTime.parse('2019-03-05 12:00:00').to_time.iso8601,
gradtn_dt: DateTime.parse('2023-03-03 12:00:00').to_time.iso8601,
full_time_studnt_type_cd: 'HighSch',
part_time_school_subjct_txt: 'An amazing program'
}
end
describe '#params for 686c' do
it 'formats child school params for submission' do
formatted_info = child_school_info.params_for_686c
expect(formatted_info).to include(formatted_params_result)
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/bgs_dependents/vnp_benefit_claim_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe BGSDependents::VnpBenefitClaim do
let(:veteran) do
{
vnp_participant_id: '146189',
vnp_participant_address_id: '113372',
participant_claimant_id: '600061742',
benefit_claim_type_end_product: '032312395'
}
end
let(:benefit_claim) { described_class.new('3828033', veteran) }
let(:create_params_output) do
{
vnp_proc_id: '3828033', ptcpnt_clmant_id: '146189', ptcpnt_mail_addrs_id: '113372', vnp_ptcpnt_vet_id: '146189'
}
end
let(:update_params_output) do
{
vnp_proc_id: '3828033',
vnp_bnft_claim_id: '425718',
bnft_claim_type_cd: '130DPNEBNADJ',
end_prdct_type_cd: '032312395',
bnft_claim_id: '600196508',
vnp_ptcpnt_vet_id: '146189',
ptcpnt_clmant_id: '146189',
status_type_cd: 'PEND'
}
end
let(:vnp_benefit_claim_update_param) do
{
vnp_proc_id: '3828033',
vnp_benefit_claim_id: '425718',
vnp_benefit_claim_type_code: '130DPNEBNADJ',
claim_jrsdtn_lctn_id: '335',
intake_jrsdtn_lctn_id: '335',
participant_claimant_id: '146189'
}
end
let(:benefit_claim_record) do
{
benefit_claim_id: '600196508',
claim_type_code: '130DPNEBNADJ',
program_type_code: 'CPL',
service_type_code: 'CP',
status_type_code: 'PEND'
}
end
let(:response_output) do
{
vnp_proc_id: '3828033',
vnp_benefit_claim_id: '425718',
vnp_benefit_claim_type_code: '130DPNEBNADJ',
claim_jrsdtn_lctn_id: '335',
intake_jrsdtn_lctn_id: '335',
participant_claimant_id: '146189'
}
end
let(:vnp_benefit_claim_response_param) do
{
vnp_bnft_claim_id: '425718',
bnft_claim_type_cd: '130DPNEBNADJ',
claim_jrsdtn_lctn_id: '335',
intake_jrsdtn_lctn_id: '335',
jrn_lctn_id: '281',
jrn_obj_id: 'VAgovAPI',
jrn_status_type_cd: 'U',
jrn_user_id: 'VAgovAPI',
pgm_type_cd: 'COMP',
ptcpnt_clmant_id: '146189',
vnp_ptcpnt_vet_id: '146189',
vnp_proc_id: '3828033'
}
end
describe '#create_params_for_686c' do
it 'creates params for submission to BGS for 686c' do
create_params = benefit_claim.create_params_for_686c
expect(create_params).to include(create_params_output)
end
end
describe '#update_params_for_686c' do
it 'creates update params for submission to BGS for 686c' do
update_params = benefit_claim.update_params_for_686c(vnp_benefit_claim_update_param, benefit_claim_record)
expect(update_params).to include(update_params_output)
end
end
describe '#vnp_benefit_claim_response' do
it 'creates update params for submission to BGS for 686c' do
response = benefit_claim.vnp_benefit_claim_response(vnp_benefit_claim_response_param)
expect(response).to include(response_output)
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/bgs_dependents/child_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe BGSDependents::Child do
let(:child_info) do
{
'does_child_live_with_you' => false,
'child_income' => false,
'child_address_info' => {
'person_child_lives_with' => { 'first' => 'Bill', 'middle' => 'Oliver', 'last' => 'Bradsky' },
'address' => {
'country_name' => 'USA',
'address_line1' => '1100 Robin Cir',
'city' => 'Los Angelas',
'state_code' => 'CA',
'zip_code' => '90210'
}
},
'place_of_birth' => { 'state' => 'CA', 'city' => 'Slawson' },
'child_status' => { 'biological' => true },
'previously_married' => 'Yes',
'previous_marriage_details' => { 'date_marriage_ended' => '2018-03-04', 'reason_marriage_ended' => 'Death' },
'full_name' => { 'first' => 'John', 'middle' => 'oliver', 'last' => 'Hamm', 'suffix' => 'Sr.' },
'ssn' => '370947142',
'birth_date' => '2009-03-03',
'not_self_sufficient' => false
}
end
let(:all_flows_payload) { build(:form_686c_674_kitchen_sink) }
let(:address_result) do
{
'country_name' => 'USA',
'address_line1' => '1100 Robin Cir',
'city' => 'Los Angelas',
'state_code' => 'CA',
'zip_code' => '90210'
}
end
describe '#format_info' do
let(:format_info_output) do
{
'ssn' => '370947142',
'family_relationship_type' => 'Biological',
'place_of_birth_state' => 'CA',
'place_of_birth_city' => 'Slawson',
'reason_marriage_ended' => 'Death',
'ever_married_ind' => 'Y',
'birth_date' => '2009-03-03',
'place_of_birth_country' => nil,
'first' => 'John',
'middle' => 'oliver',
'last' => 'Hamm',
'suffix' => 'Sr.',
'child_income' => 'N',
'not_self_sufficient' => 'N'
}
end
it 'formats relationship params for submission' do
formatted_info = described_class.new(child_info).format_info
expect(formatted_info).to eq(format_info_output)
end
end
describe '#address' do
it 'formats address' do
address = described_class.new(child_info).address(all_flows_payload['dependents_application'])
expect(address).to eq(address_result)
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/bgs_dependents/base_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
TEST_COUNTRIES = {
'USA' => 'USA', 'BOL' => 'Bolivia', 'BIH' => 'Bosnia-Herzegovina', 'BRN' => 'Brunei',
'CPV' => 'Cape Verde', 'COG' => "Congo, People's Republic of",
'COD' => 'Congo, Democratic Republic of', 'CIV' => "Cote d'Ivoire",
'CZE' => 'Czech Republic', 'PRK' => 'North Korea', 'KOR' => 'South Korea',
'LAO' => 'Laos', 'MKD' => 'Macedonia', 'MDA' => 'Moldavia', 'RUS' => 'Russia',
'KNA' => 'St. Kitts', 'LCA' => 'St. Lucia', 'STP' => 'Sao-Tome/Principe',
'SCG' => 'Serbia', 'SYR' => 'Syria', 'TZA' => 'Tanzania',
'GBR' => 'United Kingdom', 'VEN' => 'Venezuela', 'VNM' => 'Vietnam',
'YEM' => 'Yemen Arab Republic'
}.freeze
RSpec.describe BGSDependents::Base do
let(:base) { described_class.new }
let(:sample_dependent_application) do
{
'veteran_contact_information' => {
'veteran_address' => {
'country_name' => 'USA',
'address_line1' => '8200 Doby LN',
'city' => 'Pasadena',
'state_code' => 'CA',
'zip_code' => '21122'
}
}
}
end
let(:sample_v2_dependent_application) do
{
'veteran_contact_information' => {
'veteran_address' => {
'country' => 'USA',
'street' => '8200 Doby LN',
'street2' => 'test line two',
'street3' => 'test line 3',
'city' => 'Pasadena',
'state' => 'CA',
'postal_code' => '21122'
}
}
}
end
let(:alternative_address) do
{
'country_name' => 'USA',
'address_line1' => 'Alternative LN',
'city' => 'Stuart',
'state_code' => 'FL',
'zip_code' => '21122'
}
end
describe '#dependent_address' do
it 'returns the vet\'s address' do
address = base.dependent_address(
dependents_application: sample_dependent_application,
lives_with_vet: true,
alt_address: nil
)
expect(address).to eq(sample_dependent_application['veteran_contact_information']['veteran_address'])
end
it 'returns the alternative address' do
address = base.dependent_address(
dependents_application: sample_dependent_application,
lives_with_vet: false,
alt_address: alternative_address
)
expect(address).to eq(alternative_address)
end
context 'it is a foreign address' do
TEST_COUNTRIES.each do |abbreviation, bis_value|
it "returns #{bis_value} when it gets #{abbreviation} as the country" do
address = sample_dependent_application['veteran_contact_information']['veteran_address']
address['country_name'] = abbreviation
address['international_postal_code'] = '12345'
base.adjust_country_name_for!(address:)
expect(address['country_name']).to eq(bis_value)
end
end
it 'tests TUR when the city is Adana' do
address = sample_dependent_application['veteran_contact_information']['veteran_address']
address['country_name'] = 'TUR'
address['international_postal_code'] = '12345'
address['city'] = 'Adana'
base.adjust_country_name_for!(address:)
expect(address['country_name']).to eq('Turkey (Adana only)')
end
it 'tests TUR when the city is not Adana' do
address = sample_dependent_application['veteran_contact_information']['veteran_address']
address['country_name'] = 'TUR'
address['international_postal_code'] = '12345'
address['city'] = 'Istanbul'
base.adjust_country_name_for!(address:)
expect(address['country_name']).to eq('Turkey (except Adana)')
end
it 'tests a country outside of the hash' do
address = sample_dependent_application['veteran_contact_information']['veteran_address']
address['country_name'] = 'ITA'
address['international_postal_code'] = '12345'
base.adjust_country_name_for!(address:)
expect(address['country_name']).to eq('Italy')
end
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/schema_contract/validator_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require_relative Rails.root.join('app', 'models', 'schema_contract', 'validator')
describe SchemaContract::Validator, :aggregate_failures do
describe '#validate' do
let(:fixture) { 'spec/fixtures/schema_contract/test_schema.json' }
let(:test_data) { Rails.root.join(fixture).read }
let(:contract_record) { create(:schema_contract_validation, response:) }
let(:matching_response) do
{
data: [
{
required_string: '1234',
required_object: {
required_nested_string: 'required'
}
}
],
meta: [{}]
}
end
let(:uuid_regex) { /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/ }
###
# these tests are non-exhaustive and at times duplicative of the underlying JSON::Validator gem specs
# but are useful for confirming and documenting expected behavior
###
context 'when response matches schema' do
let(:response) { matching_response }
it 'updates record and does not raise errors' do
expect do
SchemaContract::Validator.new(contract_record.id).validate
end.not_to raise_error
expect(contract_record.reload.status).to eq('success')
end
end
context 'when required properties are missing' do
let(:response) do
matching_response[:data][0].delete(:required_string)
matching_response
end
it 'raises and records errors' do
expect do
SchemaContract::Validator.new(contract_record.id).validate
end.to raise_error(SchemaContract::Validator::SchemaContractValidationError)
expect(contract_record.reload.status).to eq('schema_errors_found')
expect(contract_record.error_details).to \
match(%r{^\["The property '#/data/0' did not contain a required property of 'required_string' in schema \
#{uuid_regex}"\]$})
end
end
context 'when response contains optional permitted properties' do
let(:response) do
matching_response[:data][0][:optional_nullable_string] = ':D'
matching_response
end
it 'updates record and does not raise errors' do
expect do
SchemaContract::Validator.new(contract_record.id).validate
end.not_to raise_error
expect(contract_record.reload.status).to eq('success')
end
end
context 'when response contains unpermitted properties' do
let(:response) do
matching_response[:data][0][:extra] = ':D'
matching_response
end
it 'raises and records errors' do
expect do
SchemaContract::Validator.new(contract_record.id).validate
end.to raise_error(SchemaContract::Validator::SchemaContractValidationError)
expect(contract_record.reload.status).to eq('schema_errors_found')
expect(contract_record.error_details).to \
match(%r{^\["The property '#/data/0' contains additional properties \[\\"extra\\"\] outside of the schema \
when none are allowed in schema #{uuid_regex}"\]$})
end
end
context 'when response contains properties of the wrong type' do
let(:response) do
matching_response[:data][0][:required_string] = 1
matching_response
end
it 'raises and records errors' do
expect do
SchemaContract::Validator.new(contract_record.id).validate
end.to raise_error(SchemaContract::Validator::SchemaContractValidationError)
expect(contract_record.reload.status).to eq('schema_errors_found')
expect(contract_record.error_details).to \
match(%r{^\["The property '#/data/0/required_string' of type integer did not match the following type: \
string in schema #{uuid_regex}"\]$})
end
end
context 'when response contains disallowed null value' do
let(:response) do
matching_response[:data][0][:required_string] = nil
matching_response
end
it 'raises and records errors' do
expect do
SchemaContract::Validator.new(contract_record.id).validate
end.to raise_error(SchemaContract::Validator::SchemaContractValidationError)
expect(contract_record.reload.status).to eq('schema_errors_found')
expect(contract_record.error_details).to \
match(%r{^\["The property '#/data/0/required_string' of type null did not match the following type: string \
in schema #{uuid_regex}"\]$})
end
end
context 'when response contains allowed null value' do
let(:response) do
matching_response[:data][0][:optional_nullable_string] = nil
matching_response
end
it 'updates record and does not raise errors' do
expect do
SchemaContract::Validator.new(contract_record.id).validate
end.not_to raise_error
expect(contract_record.reload.status).to eq('success')
end
end
context 'when schema contains nested properties' do
let(:response) do
matching_response[:data][0][:required_object].delete(:required_nested_string)
matching_response[:data][0][:required_object][:extra] = ':D'
matching_response[:data][0][:required_object][:optional_nested_int] = 'not an integer'
matching_response
end
it 'validates them as expected' do
expect do
SchemaContract::Validator.new(contract_record.id).validate
end.to raise_error(SchemaContract::Validator::SchemaContractValidationError)
expect(contract_record.reload.status).to eq('schema_errors_found')
expect(contract_record.error_details).to \
match(%r{^\["The property '#/data/0/required_object' did not contain a required property of \
'required_nested_string' in schema #{uuid_regex}", \
"The property '#/data/0/required_object' contains additional properties \[\\"extra\\"\] outside of the \
schema when none are allowed in schema #{uuid_regex}", \
"The property '#/data/0/required_object/optional_nested_int' of type string did not match the following \
type: integer in schema #{uuid_regex}"\]})
end
end
context 'when schema contract does not exist in db' do
it 'raises errors' do
error = nil
begin
SchemaContract::Validator.new('1').validate
rescue SchemaContract::Validator::SchemaContractValidationError => e
error = e
end
expect(error).to be_a(SchemaContract::Validator::SchemaContractValidationError)
expect(error.message).to match(/Couldn't find SchemaContract::Validation with 'id'/)
end
end
context 'when schema file does not exist' do
let(:contract_record) do
create(:schema_contract_validation, contract_name: 'not_real', response: matching_response)
end
it 'raises and records errors' do
expect do
SchemaContract::Validator.new(contract_record.id).validate
end.to raise_error(SchemaContract::Validator::SchemaContractValidationError, 'No schema file not_real found.')
expect(contract_record.reload.status).to eq('schema_not_found')
end
end
context 'when unexpected error occurs' do
let(:response) { matching_response }
it 'raises and records errors' do
allow(JSON::Validator).to receive(:fully_validate).and_raise(StandardError)
expect do
SchemaContract::Validator.new(contract_record.id).validate
end.to raise_error(SchemaContract::Validator::SchemaContractValidationError,
%({:error_type=>"Unknown", :record_id=>#{contract_record.id}, :details=>"StandardError"}))
expect(contract_record.reload.status).to eq('error')
end
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/schema_contract/validation_initiator_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require_relative Rails.root.join('app', 'models', 'schema_contract', 'validation_initiator')
describe SchemaContract::ValidationInitiator do
describe '.call' do
let(:user) { create(:user, :with_terms_of_use_agreement) }
let(:user_account_id) { user.user_account_uuid }
let(:response) do
OpenStruct.new({ success?: true, status: 200, body: { key: 'value' } })
end
before do
Timecop.freeze
Flipper.enable(:schema_contract_test_index)
end
context 'response is successful, feature flag is on, and no record exists for the current day' do
before do
create(:schema_contract_validation, contract_name: 'test_index', user_account_id:, user_uuid: '1234', response:,
status: 'initialized', created_at: Time.zone.yesterday.beginning_of_day)
end
it 'creates a record with provided details and enqueues a job' do
expect(SchemaContract::ValidationJob).to receive(:perform_async)
expect do
SchemaContract::ValidationInitiator.call(user:, response:, contract_name: 'test_index')
end.to change(SchemaContract::Validation, :count).by(1)
end
end
context 'when a validation record already exists for the current day' do
before do
create(:schema_contract_validation, contract_name: 'test_index', user_account_id:, user_uuid: '1234', response:,
status: 'initialized')
end
it 'does not create a record or enqueue a job' do
expect(SchemaContract::ValidationJob).not_to receive(:perform_async)
expect do
SchemaContract::ValidationInitiator.call(user:, response:, contract_name: 'test_index')
end.not_to change(SchemaContract::Validation, :count)
end
end
context 'when feature flag is off' do
before { Flipper.disable(:schema_contract_test_index) }
it 'does not create a record or enqueue a job' do
expect(SchemaContract::ValidationJob).not_to receive(:perform_async)
expect do
SchemaContract::ValidationInitiator.call(user:, response:, contract_name: 'test_index')
end.not_to change(SchemaContract::Validation, :count)
end
end
context 'when response is unsuccessful' do
let(:response) do
OpenStruct.new({ success?: false, status: 200, body: { key: 'value' } })
end
it 'does not create a record or enqueue a job' do
expect(SchemaContract::ValidationJob).not_to receive(:perform_async)
expect do
SchemaContract::ValidationInitiator.call(user:, response:, contract_name: 'test_index')
end.not_to change(SchemaContract::Validation, :count)
end
end
context 'when an error is encountered' do
it 'logs but does not raise the error' do
allow(SchemaContract::Validation).to receive(:create).with(any_args).and_raise(ArgumentError)
error_message = { response:, contract_name: 'test_index', error_details: 'ArgumentError' }
expect(Rails.logger).to receive(:error).with('Error creating schema contract job', error_message)
expect do
SchemaContract::ValidationInitiator.call(user:, response:, contract_name: 'test_index')
end.not_to raise_error
end
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/external_services_redis/status_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'support/pagerduty/services/spec_setup'
describe ExternalServicesRedis::Status do
include_context 'simulating Redis caching of PagerDuty#get_services'
let(:external_services) { ExternalServicesRedis::Status.new }
it 'sets its cache to expire (ttl) after 60 seconds' do
expect(ExternalServicesRedis::Status.redis_namespace_ttl).to eq 60
end
describe '#fetch_or_cache' do
let(:fetch_or_cache) { external_services.fetch_or_cache }
it 'is an instance of PagerDuty::ExternalServices::Response' do
expect(fetch_or_cache.class).to eq PagerDuty::ExternalServices::Response
end
it "includes the HTTP status code from call to PagerDuty's API" do
expect(fetch_or_cache.status).to eq 200
end
it "includes the time from the call to PagerDuty's API" do
expect(fetch_or_cache.reported_at).to be_present
end
it 'includes an array of PagerDuty::Models::Service hashes', :aggregate_failures do
expect(fetch_or_cache.statuses.class).to eq Array
expect(fetch_or_cache.statuses).to all(be_a(Hash))
end
it 'includes the relevant status details about each external service', :aggregate_failures do
service_status = fetch_or_cache.statuses.first
expect(service_status[:service]).to be_present
expect(service_status[:status]).to be_present
expect(service_status[:last_incident_timestamp]).to be_present
expect(service_status[:service_id]).to be_a(String)
end
context 'when the cache is empty' do
it 'caches and return the response', :aggregate_failures do
expect(external_services).to receive(:cache).once
expect_any_instance_of(PagerDuty::ExternalServices::Service).to receive(:get_services).once
expect(external_services.fetch_or_cache.class).to eq PagerDuty::ExternalServices::Response
end
end
end
describe '#response_status' do
it "returns the HTTP status code from call to PagerDuty's API" do
expect(external_services.response_status).to eq 200
end
end
describe '#reported_at' do
it "returns the time from the call to PagerDuty's API", :aggregate_failures do
expect(external_services.reported_at).to be_present
expect(external_services.reported_at.class).to eq Time
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/form1010cg/attachment_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Form1010cg::Attachment, type: :model do
let(:guid) { 'cdbaedd7-e268-49ed-b714-ec543fbb1fb8' }
let(:subject) { described_class.new(guid:) }
let(:vcr_options) do
{
record: :none,
allow_unused_http_interactions: false,
match_requests_on: %i[method host body]
}
end
it 'is a FormAttachment model' do
expect(described_class.ancestors).to include(FormAttachment)
end
it 'has an uploader configured' do
expect(described_class::ATTACHMENT_UPLOADER_CLASS).to eq(Form1010cg::PoaUploader)
end
describe '#to_local_file', skip: 'VCR failures' do
let(:file_fixture_path) { Rails.root.join('spec', 'fixtures', 'files', 'doctors-note.jpg') }
let(:expected_local_file_path) { "tmp/#{guid}_doctors-note.jpg" }
let(:remote_file_content) { nil }
before do
VCR.use_cassette("s3/object/put/#{guid}/doctors-note_jpg", vcr_options) do
subject.set_file_data!(
Rack::Test::UploadedFile.new(file_fixture_path, 'image/jpg')
)
end
end
after do
FileUtils.rm_f(expected_local_file_path)
end
it 'makes a local copy of the file' do
VCR.use_cassette("s3/object/get/#{guid}/doctors-note_jpg", vcr_options) do
expect(subject.to_local_file).to eq(expected_local_file_path)
expect(
FileUtils.compare_file(expected_local_file_path, file_fixture_path)
).to be(true)
end
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/form1010cg/submission_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Form1010cg::Submission, type: :model do
let(:sample_data) do
{
carma_case_id: 'aB9r00000004GW9CAK',
accepted_at: DateTime.now.iso8601,
metadata: {
'claimId' => nil,
'claimGuid' => 'uuid-1234',
'veteran' => {
'icn' => 'ICN_123',
'isVeteran' => true
},
'primaryCaregiver' => {
'icn' => nil
},
'secondaryCaregiverOne' => nil,
'secondaryCaregiverTwo' => nil
},
attachments: {
has_errors: false,
data: [
{
id: '06835000000YpsjAAC',
carma_case_id: 'aB9r00000004GW9CAK',
veteran_name: {
first: 'Jane',
last: 'Doe'
},
file_path: '10-10CG_123456.pdf',
document_type: '10-10CG',
document_date: '2020-03-30'
}
]
},
attachments_job_id: '12345abcdef'
}
end
it 'can initialize with attributes :carma_case_id, :accepted_at, :attachments, :metadata, :attachments_job_id' do
instance_1 = described_class.new
expect(instance_1.carma_case_id).to be_nil
expect(instance_1.accepted_at).to be_nil
expect(instance_1.metadata).to be_nil
expect(instance_1.attachments).to be_nil
expect(instance_1.attachments_job_id).to be_nil
instance_2 = described_class.new(sample_data)
expect(instance_2.carma_case_id).to eq(sample_data[:carma_case_id])
expect(instance_2.accepted_at).to eq(sample_data[:accepted_at])
expect(instance_2.metadata).to eq(sample_data[:metadata].deep_stringify_keys)
expect(instance_2.attachments).to eq(sample_data[:attachments].deep_stringify_keys)
expect(instance_2.attachments_job_id).to eq(sample_data[:attachments_job_id])
end
it 'has attribute accessors for :carma_case_id, :accepted_at, :attachments, :metadata, :attachments_job_id' do
expect(subject.carma_case_id).to be_nil
expect(subject.accepted_at).to be_nil
expect(subject.metadata).to be_nil
expect(subject.attachments).to be_nil
expect(subject.attachments_job_id).to be_nil
subject.carma_case_id = sample_data[:carma_case_id]
subject.accepted_at = sample_data[:accepted_at]
subject.metadata = sample_data[:metadata]
subject.attachments = sample_data[:attachments]
subject.attachments_job_id = sample_data[:attachments_job_id]
expect(subject.carma_case_id).to eq(sample_data[:carma_case_id])
expect(subject.accepted_at).to eq(sample_data[:accepted_at])
expect(subject.metadata).to eq(sample_data[:metadata].deep_stringify_keys)
expect(subject.attachments).to eq(sample_data[:attachments].deep_stringify_keys)
expect(subject.attachments_job_id).to eq(sample_data[:attachments_job_id])
end
describe 'associations' do
let(:claim) { build(:caregivers_assistance_claim) }
let(:submission) { build(:form1010cg_submission) }
after do
claim.delete unless claim.destroyed?
submission.delete unless submission.destroyed?
end
it 'accepts_nested_attributes_for claim' do
expect(submission.persisted?).to be(false)
expect(submission.persisted?).to be(false)
submission.claim = claim
submission.save
expect(submission.persisted?).to be(true)
expect(claim.persisted?).to be(true)
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/form_profiles/mdot_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe FormProfiles::MDOT, type: :model do
let(:user_details) do
{
first_name: 'Greg',
last_name: 'Anderson',
middle_name: 'A',
birth_date: '19910405',
ssn: '000550237'
}
end
let(:user) { build(:user, :loa3, user_details) }
describe '#prefill_form' do
it 'prefills the MDOT form' do
VCR.insert_cassette(
'mdot/get_supplies_200',
match_requests_on: %i[method uri headers],
erb: { icn: user.icn }
)
form_data = FormProfile.for(form_id: 'MDOT', user:).prefill[:form_data]
errors = JSON::Validator.fully_validate(VetsJsonSchema::SCHEMAS['MDOT'], form_data)
expect(errors).to be_empty
VCR.eject_cassette
end
it 'catches no-supplies 200' do
VCR.insert_cassette(
'mdot/get_supplies_200_no_supplies',
match_requests_on: %i[method uri]
)
form_data = FormProfile.for(form_id: 'MDOT', user:).prefill[:form_data]
errors = JSON::Validator.fully_validate(VetsJsonSchema::SCHEMAS['MDOT'], form_data)
schema_error = errors.any? do |error|
error.include?("did not contain a required property of 'supplies' in schema")
end
expect(schema_error).to be(true)
VCR.eject_cassette
end
context 'with assistive devices' do
it 'still prefills the MDOT form' do
VCR.insert_cassette(
'mdot/get_supplies_assistive_devices_200',
match_requests_on: %i[method uri headers],
erb: { icn: user.icn }
)
form_data = FormProfile.for(form_id: 'MDOT', user:).prefill[:form_data]
errors = JSON::Validator.fully_validate(VetsJsonSchema::SCHEMAS['MDOT'], form_data)
expect(errors).to be_empty
VCR.eject_cassette
end
end
context 'with null addresses' do
it 'still prefills the MDOT form' do
VCR.insert_cassette(
'mdot/get_supplies_null_addresses_200',
match_requests_on: %i[method uri headers],
erb: { icn: user.icn }
)
form_data = FormProfile.for(form_id: 'MDOT', user:).prefill[:form_data]
errors = JSON::Validator.fully_validate(VetsJsonSchema::SCHEMAS['MDOT'], form_data)
expect(errors).to be_empty
VCR.eject_cassette
end
end
context 'with errors' do
it 'handles 500 responses from system-of-record' do
VCR.insert_cassette(
'mdot/get_supplies_500',
match_requests_on: %i[method uri headers],
erb: { icn: user.icn }
)
expect { FormProfile.for(form_id: 'MDOT', user:).prefill }
.to raise_error(Common::Exceptions::BackendServiceException)
VCR.eject_cassette
end
it 'handles 401 responses from system-of-record' do
VCR.insert_cassette(
'mdot/get_supplies_401',
match_requests_on: %i[method uri],
erb: { icn: user.icn }
)
expect { FormProfile.for(form_id: 'MDOT', user:).prefill }
.to raise_error(Common::Exceptions::BackendServiceException)
VCR.eject_cassette
end
it 'handles 406 responses from system-of-record' do
VCR.insert_cassette(
'mdot/simulated_get_supplies_406',
match_requests_on: %i[method uri],
erb: { icn: user.icn }
)
expect { FormProfile.for(form_id: 'MDOT', user:).prefill }
.to raise_error(Common::Exceptions::BackendServiceException)
VCR.eject_cassette
end
it 'handles 410 responses from system-of-record' do
VCR.insert_cassette(
'mdot/simulated_get_supplies_410',
match_requests_on: %i[method uri],
erb: { icn: user.icn }
)
expect { FormProfile.for(form_id: 'MDOT', user:).prefill }
.to raise_error(Common::Exceptions::BackendServiceException)
VCR.eject_cassette
end
it 'handles non-JSON responses from system-of-record' do
VCR.insert_cassette(
'mdot/simulated_get_supplies_200_not_json',
match_requests_on: %i[method uri],
erb: { icn: user.icn }
)
expect { FormProfile.for(form_id: 'MDOT', user:).prefill }
.to raise_error(Common::Exceptions::BackendServiceException)
VCR.eject_cassette
end
end
it 'handles 401 (missing header) responses from system-of-record' do
VCR.insert_cassette(
'mdot/get_supplies_401_missing_header',
match_requests_on: %i[method uri]
)
expect { FormProfile.for(form_id: 'MDOT', user:).prefill }
.to raise_error(Common::Exceptions::BackendServiceException)
VCR.eject_cassette
end
it 'handles 401 (patient not found) responses from system-of-record' do
VCR.insert_cassette(
'mdot/get_supplies_401_patient_not_found.yml',
match_requests_on: %i[method uri]
)
expect { FormProfile.for(form_id: 'MDOT', user:).prefill }
.to raise_error(Common::Exceptions::BackendServiceException)
VCR.eject_cassette
end
it 'handles 400 responses from system-of-record' do
VCR.insert_cassette(
'mdot/get_supplies_400.yml',
match_requests_on: %i[method uri]
)
expect { FormProfile.for(form_id: 'MDOT', user:).prefill }
.to raise_error(Common::Exceptions::BackendServiceException)
VCR.eject_cassette
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/form_profiles/va8794_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe FormProfiles::VA8794 do
subject(:profile) { described_class.new(form_id: '22-8794', user: build(:user)) }
describe '#metadata' do
it 'returns expected metadata' do
expect(profile.metadata).to eq({ version: 0, prefill: true, returnUrl: '/applicant/information' })
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/form_profiles/va10297_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe FormProfiles::VA10297 do
subject(:profile) { described_class.new(form_id: '22-10297', user:) }
let(:user) { create(:user, icn: '123498767V234859') }
describe '#metadata' do
it 'returns expected metadata' do
expect(profile.metadata).to eq({ version: 0, prefill: true, returnUrl: '/applicant/information' })
end
end
describe '#prefill' do
before do
allow(user).to receive(:authorize).with(:evss, :access?).and_return(true)
allow(user).to receive(:authorize).with(:lighthouse, :direct_deposit_access?).and_return(true)
allow_any_instance_of(Auth::ClientCredentials::Service).to receive(:get_token).and_return('fake_token')
end
it 'prefills form data' do
VCR.use_cassette('lighthouse/direct_deposit/show/200_valid_new_icn') do
data = profile.prefill
expect(data[:form_data]['mailingAddress']).to eq({ 'street' => '140 Rock Creek Rd',
'city' => 'Washington',
'state' => 'DC',
'country' => 'USA',
'postalCode' => '20011' })
expect(data[:form_data]['bankAccount']).to eq({ 'bankAccountType' => 'Checking',
'bankAccountNumber' => '1234567890',
'bankRoutingNumber' => '031000503',
'bankName' => 'WELLS FARGO BANK' })
end
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/form_profiles/va0976_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe FormProfiles::VA0976 do
subject(:profile) { described_class.new(form_id: '22-0976', user: build(:user)) }
describe '#metadata' do
it 'returns expected metadata' do
expect(profile.metadata).to eq({ version: 0, prefill: true, returnUrl: '/applicant/information' })
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/form_profiles/va1330m_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe FormProfiles::VA1330m do
subject(:profile) { described_class.new(form_id: '1330M', user: build(:user)) }
describe '#metadata' do
it 'returns expected metadata' do
expect(profile.metadata).to eq({ version: 0, prefill: true, returnUrl: '/applicant-name' })
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/form_profiles/va0803_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe FormProfiles::VA0803 do
subject(:profile) { described_class.new(form_id: '22-0803', user:) }
let(:user) { create(:user, icn: '123498767V234859') }
describe '#metadata' do
it 'returns expected metadata' do
expect(profile.metadata).to eq({ version: 0, prefill: true, returnUrl: '/applicant/information' })
end
end
describe '#prefill' do
before do
allow_any_instance_of(BGS::People::Service).to(
receive(:find_person_by_participant_id).and_return(BGS::People::Response.new({ file_nbr: '796043735' }))
)
allow_any_instance_of(User).to(
receive(:participant_id).and_return('600061742')
)
end
it 'prefills form data' do
VCR.use_cassette('lighthouse/direct_deposit/show/200_valid_new_icn') do
data = profile.prefill
expect(data[:form_data]['applicantName']).to eq({ 'first' => 'Abraham',
'last' => 'Lincoln' })
expect(data[:form_data]['ssn']).to eq('796111863')
expect(data[:form_data]['vaFileNumber']).to eq('796043735')
end
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/form_profiles/va10282_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe FormProfiles::VA10282 do
subject(:profile) { described_class.new(form_id: '22-10282', user: build(:user)) }
describe '#metadata' do
it 'returns expected metadata' do
expect(profile.metadata).to eq({ version: 0, prefill: true, returnUrl: '/applicant/information' })
end
end
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/lighthouse/submission_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'support/models/shared_examples/submission'
RSpec.describe Lighthouse::Submission, type: :model do
it_behaves_like 'a Submission model'
end
|
0
|
code_files/vets-api-private/spec/models
|
code_files/vets-api-private/spec/models/lighthouse/submission_attempt_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'support/models/shared_examples/submission_attempt'
RSpec.describe Lighthouse::SubmissionAttempt, type: :model do
it_behaves_like 'a SubmissionAttempt model'
describe 'associations' do
it {
expect(subject).to belong_to(:submission).class_name('Lighthouse::Submission')
.with_foreign_key(:lighthouse_submission_id)
.inverse_of(:submission_attempts)
}
end
describe 'status transition methods' do
let(:submission) { build_stubbed(:lighthouse_submission) }
let(:attempt) { described_class.new(submission:) }
let(:monitor_double) { instance_double(Logging::Monitor, track_request: nil) }
before do
allow(attempt).to receive_messages(
status_change_hash: { id: 123 },
monitor: monitor_double
)
end
describe '#fail!' do
it 'sets status to failure and logs error' do
expect(attempt).to receive(:failure!)
expect(monitor_double).to receive(:track_request).with(
:error,
'Lighthouse Submission Attempt failed',
Lighthouse::SubmissionAttempt::STATS_KEY,
hash_including(message: 'Lighthouse Submission Attempt failed', id: 123)
)
attempt.fail!
end
end
describe '#manual!' do
it 'sets status to manually and logs warning' do
expect(attempt).to receive(:manually!)
expect(monitor_double).to receive(:track_request).with(
:warn,
'Lighthouse Submission Attempt is being manually remediated',
Lighthouse::SubmissionAttempt::STATS_KEY,
hash_including(message: 'Lighthouse Submission Attempt is being manually remediated', id: 123)
)
attempt.manual!
end
end
describe '#vbms!' do
it 'updates status to vbms and logs info' do
expect(attempt).to receive(:update).with(status: :vbms)
expect(monitor_double).to receive(:track_request).with(
:info,
'Lighthouse Submission Attempt went to vbms',
Lighthouse::SubmissionAttempt::STATS_KEY,
hash_including(message: 'Lighthouse Submission Attempt went to vbms', id: 123)
)
attempt.vbms!
end
end
describe '#pending!' do
it 'updates status to pending and logs info' do
expect(attempt).to receive(:update).with(status: :pending)
expect(monitor_double).to receive(:track_request).with(
:info,
'Lighthouse Submission Attempt is pending',
Lighthouse::SubmissionAttempt::STATS_KEY,
hash_including(message: 'Lighthouse Submission Attempt is pending', id: 123)
)
attempt.pending!
end
end
describe '#success!' do
it 'sets status to submitted and logs info' do
expect(attempt).to receive(:submitted!)
expect(monitor_double).to receive(:track_request).with(
:info,
'Lighthouse Submission Attempt is submitted',
Lighthouse::SubmissionAttempt::STATS_KEY,
hash_including(message: 'Lighthouse Submission Attempt is submitted', id: 123)
)
attempt.success!
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/policies/meb_policy_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe MebPolicy do
subject { described_class }
permissions :access? do
context 'when user has an ICN, SSN, and is LOA3' do
let(:user) { build(:user, :loa3) }
it 'grants access' do
expect(subject).to permit(user, :my_education_benefits)
end
it 'increments the StatsD success counter' do
expect do
MebPolicy.new(user,
:my_education_benefits).access?
end.to trigger_statsd_increment('api.my_education_benefits.policy.success')
end
end
context 'when user does not have an ICN, SSN, or is not LOA3' do
let(:user) { build(:user, :loa1) }
before do
user.identity.attributes = {
icn: nil,
ssn: nil
}
end
it 'denies access' do
expect(subject).not_to permit(user, :my_education_benefits)
end
it 'increments the StatsD failure counter' do
expect do
MebPolicy.new(user,
:my_education_benefits).access?
end.to trigger_statsd_increment('api.my_education_benefits.policy.failure')
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/policies/va_profile_policy_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe VAProfilePolicy do
subject { described_class }
permissions :access? do
context 'with a user who has the required VA Profile attributes' do
let(:user) { build(:user, :loa3) }
it 'grants access' do
expect(subject).to permit(user, :va_profile)
end
end
context 'with a user who does not have the required VA Profile attributes' do
let(:user) { build(:user, :loa1) }
it 'denies access' do
expect(subject).not_to permit(user, :va_profile)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/policies/power_of_attorney_policy_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe PowerOfAttorneyPolicy do
subject { described_class }
permissions :access? do
context 'when user is LOA3, has an ICN, and has a participant_id' do
let(:user) { build(:user, :loa3) }
it 'grants access' do
expect(subject).to permit(user, :power_of_attorney)
end
end
context 'when user is LOA3 but does not have an ICN' do
let(:user) { build(:user, :loa3, icn: nil) }
it 'denies access due to missing ICN' do
expect(subject).not_to permit(user, :power_of_attorney)
end
end
context 'when user is LOA3 but does not have a participant_id' do
let(:user) { build(:user, :loa3, participant_id: nil) }
it 'denies access due to missing participant_id' do
expect(subject).not_to permit(user, :power_of_attorney)
end
end
context 'when user is not LOA3' do
let(:user) { build(:user, :loa1) }
it 'denies access due to not being LOA3' do
expect(subject).not_to permit(user, :power_of_attorney)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/policies/mhv_prescriptions_policy_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'flipper'
require 'ostruct'
require 'mhv_prescriptions_policy'
require 'mhv/account_creation/service'
describe MHVPrescriptionsPolicy do
let(:mhv_prescriptions) { double('mhv_prescriptions') }
let(:mhv_response) do
{
user_profile_id: '12345678',
premium: true,
champ_va:,
patient:,
sm_account_created: true,
message: 'some-message'
}
end
let(:patient) { false }
let(:champ_va) { false }
before do
allow_any_instance_of(MHV::AccountCreation::Service).to receive(:create_account).and_return(mhv_response)
end
describe '#access?' do
context 'when user is verified' do
let(:user) { create(:user, :loa3, :with_terms_of_use_agreement) }
context 'when user is a patient' do
let(:patient) { true }
it 'returns true' do
expect(described_class.new(user, mhv_prescriptions).access?).to be(true)
end
end
context 'when user is champ_va eligible' do
let(:champ_va) { true }
it 'returns true' do
expect(described_class.new(user, mhv_prescriptions).access?).to be(true)
end
end
context 'when user is both patient and champ_va eligible' do
let(:patient) { true }
let(:champ_va) { true }
it 'returns true' do
expect(described_class.new(user, mhv_prescriptions).access?).to be(true)
end
end
context 'when user is not a patient or champ_va eligible' do
let(:patient) { false }
let(:champ_va) { false }
it 'returns false and logs access denial' do
expect(Rails.logger).to receive(:info).with(
'RX ACCESS DENIED',
hash_including(
mhv_id: anything,
sign_in_service: anything,
va_facilities: anything,
va_patient: anything
)
)
expect(described_class.new(user, mhv_prescriptions).access?).to be(false)
end
end
end
context 'when user is not verified' do
let(:user) { create(:user, :loa1) }
it 'returns false and logs access denial' do
expect(Rails.logger).to receive(:info).with(
'RX ACCESS DENIED',
hash_including(
mhv_id: anything,
sign_in_service: anything,
va_facilities: anything,
va_patient: anything
)
)
expect(described_class.new(user, mhv_prescriptions).access?).to be(false)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/policies/vet360_policy_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe Vet360Policy do
subject { described_class }
permissions :access? do
context 'with a user who has the required vet360 attributes' do
let(:user) { build(:user, :loa3) }
it 'grants access' do
expect(subject).to permit(user, :vet360)
end
end
context 'with a user who does not have the required vet360 attributes' do
let(:user) { build(:user, :loa1) }
it 'denies access' do
expect(subject).not_to permit(user, :vet360)
end
end
end
permissions :military_access? do
context 'with a user who has the required vet360 attributes' do
let(:user) { build(:user, :loa3) }
it 'grants access' do
expect(subject).to permit(user, :vet360)
end
end
context 'with a user who does not have the required vet360 attributes' do
let(:user) { build(:user, :loa1) }
it 'denies access' do
expect(subject).not_to permit(user, :vet360)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/policies/appeals_policy_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe AppealsPolicy do
subject { described_class }
permissions :access? do
context 'with a user who has the required appeals attributes' do
let(:user) { build(:user, :loa3) }
it 'grants access' do
expect(subject).to permit(user, :appeals)
end
end
context 'with a user who does not have the required appeals attributes' do
let(:user) { build(:user, :loa1) }
it 'denies access' do
expect(subject).not_to permit(user, :appeals)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/policies/mpi_policy_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe MPIPolicy do
subject { described_class }
permissions :queryable? do
let(:user) { build(:user, :loa3, :no_mpi_profile) }
before { stub_mpi_not_found }
context 'with a user who has the required mvi attributes' do
context 'where user has an icn, but not the required personal attributes' do
it 'is queryable' do
user.identity.attributes = {
icn: 'some-icn',
ssn: nil,
first_name: nil,
last_name: nil,
birth_date: nil,
gender: nil
}
expect(subject).to permit(user, :mvi)
end
end
context 'where user has no icn, but does have a first_name, last_name, birth_date, ssn and gender' do
it 'is queryable' do
allow(user).to receive(:icn).and_return(nil)
expect(subject).to permit(user, :mvi)
end
end
end
context 'with a user who does not have the required mvi attributes' do
context 'where user has no icn' do
before { allow(user).to receive(:icn).and_return(nil) }
it 'is not queryable without a ssn' do
user.identity.ssn = nil
expect(subject).not_to permit(user, :mvi)
end
it 'is not queryable without a first_name' do
user.identity.first_name = nil
expect(subject).not_to permit(user, :mvi)
end
it 'is not queryable without a last_name' do
user.identity.last_name = nil
expect(subject).not_to permit(user, :mvi)
end
it 'is not queryable without a birth_date' do
user.identity.birth_date = nil
expect(subject).not_to permit(user, :mvi)
end
it 'is not queryable without a gender' do
user.identity.gender = nil
expect(subject).not_to permit(user, :mvi)
end
end
end
end
permissions :access_add_person_proxy? do
context 'with a user who is missing birls and participant id' do
let(:user) { build(:user_with_no_ids) }
it 'grants access' do
expect(subject).to permit(user, :mvi)
end
end
context 'with a user who is missing only participant or birls id' do
let(:user) { build(:user, :loa3, birls_id: nil) }
it 'grants access' do
expect(subject).to permit(user, :mvi)
end
end
context 'with a user who is missing EDIPI' do
let(:user) { build(:unauthorized_evss_user, :loa3) }
it 'denies access' do
expect(subject).not_to permit(user, :mvi)
end
end
context 'with a user who is missing a SSN' do
let(:user) { build(:user, ssn: nil) }
it 'denies access' do
expect(subject).not_to permit(user, :mvi)
end
end
context 'with a user who already has the birls and participant ids' do
let(:user) { build(:user, :loa3) }
it 'denies access' do
expect(subject).not_to permit(user, :mvi)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/policies/bgs_policy_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe BGSPolicy do
subject { described_class }
permissions :access? do
context 'with a user who has the required bgs attributes' do
let(:user) { build(:user, :loa3) }
it 'grants access' do
expect(subject).to permit(user, :bgs)
end
it 'increments the StatsD success counter' do
expect { BGSPolicy.new(user, :bgs).access? }.to trigger_statsd_increment('api.bgs.policy.success')
end
context 'and sets log_stats to false' do
it 'does not increment the StatsD success counter' do
policy = BGSPolicy.new(user, :bgs).access?(log_stats: false)
expect { policy }.not_to trigger_statsd_increment('api.bgs.policy.success')
end
end
end
context 'with a user who does not have the required bgs attributes' do
let(:user) { build(:user, :loa3, ssn: nil, participant_id: nil, icn: nil) }
it 'denies access' do
expect(subject).not_to permit(user, :bgs)
end
it 'increments the StatsD failure counter' do
expect { BGSPolicy.new(user, :bgs).access? }.to trigger_statsd_increment('api.bgs.policy.failure')
end
context 'and sets log_stats to false' do
it 'does not increment the StatsD success counter' do
policy = BGSPolicy.new(user, :bgs).access?(log_stats: false)
expect { policy }.not_to trigger_statsd_increment('api.bgs.policy.failure')
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/policies/lighthouse_policy_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe LighthousePolicy do
subject { described_class }
permissions :access? do
context 'user has ICN and Participant ID' do
let(:user) { build(:user, :loa3) }
it 'grants access' do
expect(subject).to permit(user, :lighthouse)
end
end
context 'user without ICN' do
let(:user) { build(:user, :loa3) }
before { allow(user).to receive(:icn).and_return(nil) }
it 'denies access' do
expect(subject).not_to permit(user, :lighthouse)
end
end
context 'user without Participant ID' do
let(:user) { build(:user, :loa3) }
before { allow(user).to receive(:participant_id).and_return(nil) }
it 'denies access' do
expect(subject).not_to permit(user, :lighthouse)
end
end
end
permissions :access_vet_status? do
context 'user has ICN' do
let(:user) { build(:user, :loa3) }
it 'grants access' do
expect(subject).to permit(user, :lighthouse)
end
end
context 'user without ICN' do
let(:user) { build(:user, :loa3) }
before { allow(user).to receive(:icn).and_return(nil) }
it 'denies access' do
expect(subject).not_to permit(user, :lighthouse)
end
end
end
permissions :direct_deposit_access? do
let(:user) { build(:evss_user) }
context 'user has ICN and Participant ID' do
it 'grants access' do
expect(subject).to permit(user, :lighthouse)
end
end
context 'user without ICN' do
before { allow(user).to receive(:icn).and_return(nil) }
it 'denies access' do
expect(subject).not_to permit(user, :lighthouse)
end
end
context 'user without Participant ID' do
before { allow(user).to receive(:participant_id).and_return(nil) }
it 'denies access' do
expect(subject).not_to permit(user, :lighthouse)
end
end
context 'with an idme user' do
context 'with a loa1 user' do
let(:user) { build(:user) }
it 'disallows access' do
expect(described_class).not_to permit(user, :lighthouse)
end
end
context 'with a loa3 user' do
it 'allows access' do
expect(described_class).to permit(user, :lighthouse)
end
end
end
permissions :itf_access? do
context 'user has Participant ID and SSN and First/Last Name' do
let(:user) { build(:user, :loa3) }
it 'grants access' do
expect(subject).to permit(user, :lighthouse)
end
end
context 'user with blank first name (single name user)' do
let(:user) { build(:user, :loa3) }
before { allow(user).to receive(:first_name).and_return('') }
it 'grants access' do
expect(subject).to permit(user, :lighthouse)
end
end
context 'user without Participant ID' do
let(:user) { build(:user, :loa3) }
before { allow(user).to receive(:participant_id).and_return(nil) }
it 'denies access' do
expect(subject).not_to permit(user, :lighthouse)
end
end
context 'user without SSN' do
let(:user) { build(:user, :loa3) }
before { allow(user).to receive(:ssn).and_return(nil) }
it 'denies access' do
expect(subject).not_to permit(user, :lighthouse)
end
end
context 'user without first name' do
let(:user) { build(:user, :loa3) }
before { allow(user).to receive(:first_name).and_return(nil) }
it 'denies access' do
expect(subject).not_to permit(user, :lighthouse)
end
end
context 'user without last name' do
let(:user) { build(:user, :loa3) }
before { allow(user).to receive(:last_name).and_return(nil) }
it 'denies access' do
expect(subject).not_to permit(user, :lighthouse)
end
end
end
context 'with a login.gov user' do
before do
allow_any_instance_of(UserIdentity).to receive(:sign_in)
.and_return(service_name: SignIn::Constants::Auth::LOGINGOV)
end
it 'allows access' do
expect(described_class).to permit(user, :lighthouse)
end
end
context 'with a oauth idme user' do
before do
allow_any_instance_of(UserIdentity).to receive(:sign_in).and_return(service_name: 'oauth_IDME')
end
it 'allows access' do
expect(described_class).to permit(user, :lighthouse)
end
end
context 'with a non idme user' do
let(:user) { build(:user, :mhv) }
it 'disallows access' do
expect(described_class).not_to permit(user, :lighthouse)
end
end
context 'with a user with the feature enabled' do
it 'allows access' do
expect(described_class).to permit(user, :lighthouse)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/policies/vye_policy_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe VyePolicy do
subject { described_class }
permissions :access? do
context 'with a logged in user' do
let(:user) { build(:user, :loa3) }
it 'grants access' do
expect(subject).to permit(user, :vye)
end
end
context 'without a logged in user' do
let(:user) { nil }
it 'denies access' do
expect(subject).not_to permit(user, :vye)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/policies/hca_disability_rating_policy_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe HCADisabilityRatingPolicy do
subject { described_class }
permissions :access? do
context 'with a user who is loa3 verified' do
let(:user) { build(:user, :loa3, icn: '12345678654332534') }
it 'grants access' do
expect(subject).to permit(user, :hca_disability_rating)
end
end
context 'with a user who is not LOA3 verified' do
let(:user) { build(:user, :loa1, icn: '45678654356789876') }
it 'denies access' do
expect(subject).not_to permit(user, :hca_disability_rating)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/policies/coe_policy_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe CoePolicy do
subject { described_class }
permissions :access? do
context 'user is loa3 and has EDIPI' do
let(:user) { build(:user, :loa3) }
it 'grants access' do
expect(subject).to permit(user, :coe)
end
end
context 'user is not loa3' do
let(:user) { build(:user, :loa1) }
it 'denies access' do
expect(subject).not_to permit(user, :coe)
end
end
context 'user does not have EDIPI' do
let(:user) { build(:user, :loa3) }
before { allow(user).to receive(:edipi).and_return(nil) }
it 'denies access' do
expect(subject).not_to permit(user, :coe)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/policies/mhv_user_account_policy_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe MHVUserAccountPolicy do
subject { described_class }
permissions :show? do
context 'with a user who can create an MHV account' do
let(:user) { build(:user, :loa3) }
it 'grants access' do
expect(subject).to permit(user, :mhv_user_account)
end
end
context 'with a user who cannot create an MHV account' do
let(:user) { build(:user, :loa1) }
it 'denies access' do
expect(subject).not_to permit(user, :mhv_user_account)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/policies/debt_policy_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe DebtPolicy do
subject { described_class }
permissions :access? do
context 'with a user who has the required debt attributes' do
let(:user) { build(:user, :loa3) }
it 'grants access' do
expect(subject).to permit(user, :debt)
end
it 'increments the StatsD success counter' do
expect { DebtPolicy.new(user, :debt).access? }.to trigger_statsd_increment('api.debt.policy.success')
end
end
context 'with a user who does not have the required debt attributes' do
let(:user) { build(:user, :loa1) }
before do
user.identity.attributes = {
icn: nil,
ssn: nil
}
end
it 'denies access' do
expect(subject).not_to permit(user, :debt)
end
it 'increments the StatsD failure counter' do
expect { DebtPolicy.new(user, :debt).access? }.to trigger_statsd_increment('api.debt.policy.failure')
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/policies/medical_copays_policy_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe MedicalCopaysPolicy do
subject { described_class }
permissions :access? do
context 'with a user who has the required mcp attributes' do
let(:user) { build(:user, :loa3) }
it 'grants access' do
expect(subject).to permit(user, :mcp)
end
it 'increments statsD success' do
expect { MedicalCopaysPolicy.new(user, :mcp).access? }.to trigger_statsd_increment('api.mcp.policy.success')
end
end
context 'with a user who does not have the required mcp attributes' do
let(:user) { build(:user, :loa1) }
before do
user.identity.attributes = { icn: nil, edipi: nil }
end
it 'denies access' do
expect(subject).not_to permit(user, :mcp)
end
it 'increments statsD failure' do
expect { MedicalCopaysPolicy.new(user, :mcp).access? }.to trigger_statsd_increment('api.mcp.policy.failure')
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/policies/form1095_policy_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe Form1095Policy do
subject { described_class }
permissions :access? do
context 'with a user who has the required 1095-B attributes' do
let(:user) { build(:user, :loa3, icn: '12345678654332534') }
it 'grants access' do
expect(subject).to permit(user, :form1095)
end
end
context 'with a user who is not LOA3 verified' do
let(:user) { build(:user, :loa1, icn: '45678654356789876') }
it 'denies access' do
expect(subject).not_to permit(user, :form1095)
end
end
context 'with a user who does not have an ICN' do
let(:user) { build(:user, :loa1, icn: nil) }
it 'denies access' do
expect(subject).not_to permit(user, :form1095)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/policies/mhv_medical_records_policy_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'flipper'
require 'ostruct'
require 'mhv_medical_records_policy'
require 'mhv/account_creation/service'
describe MHVMedicalRecordsPolicy do
let(:mhv_medical_records) { double('mhv_medical_records') }
let(:mhv_response) do
{
user_profile_id: '12345678',
premium: true,
champ_va:,
patient:,
sm_account_created: true,
message: 'some-message'
}
end
let(:patient) { false }
let(:champ_va) { false }
before do
allow_any_instance_of(MHV::AccountCreation::Service).to receive(:create_account).and_return(mhv_response)
end
context 'when Flipper flag is enabled' do
before do
allow(Flipper).to receive(:enabled?).with(:mhv_medical_records_new_eligibility_check).and_return(true)
end
context 'and user is verified' do
let(:user) { create(:user, :loa3, :with_terms_of_use_agreement) }
context 'and user is a patient' do
let(:patient) { true }
it 'returns true' do
expect(described_class.new(user, mhv_medical_records).access?).to be(true)
end
end
context 'and user is champ_va eligible' do
let(:champ_va) { true }
it 'returns false' do
# CHAMPVA status does not grant access to medical records
expect(described_class.new(user, mhv_medical_records).access?).to be(false)
end
end
context 'and user is not a patient' do
let(:patient) { false }
it 'returns false' do
expect(described_class.new(user, mhv_medical_records).access?).to be(false)
end
end
end
context 'and user is not verified' do
let(:user) { create(:user, :loa1) }
it 'returns false' do
expect(described_class.new(user, mhv_medical_records).access?).to be(false)
end
end
end
context 'when Flipper flag is disabled' do
let(:user) { create(:user, :loa3, authn_context:) }
let(:mhv_account_type) { 'some-mhv-account-type' }
let(:authn_context) { LOA::IDME_MHV_LOA1 }
let(:va_patient) { true }
before do
allow(Flipper).to receive(:enabled?).with(:mhv_medical_records_new_eligibility_check).and_return(false)
allow_any_instance_of(MHVAccountTypeService).to receive(:mhv_account_type).and_return(mhv_account_type)
allow(user).to receive(:va_patient?).and_return(va_patient)
end
context 'and user is mhv_account_type premium' do
let(:mhv_account_type) { 'Premium' }
context 'and user is a va patient' do
let(:va_patient) { true }
it 'returns true' do
expect(described_class.new(user, mhv_medical_records).access?).to be(true)
end
end
context 'and user is not a va patient' do
let(:va_patient) { false }
it 'returns false' do
expect(described_class.new(user, mhv_medical_records).access?).to be(false)
end
end
end
context 'and user is mhv_account_type advanced' do
let(:mhv_account_type) { 'Advanced' }
it 'returns false' do
expect(described_class.new(user, mhv_medical_records).access?).to be(false)
end
end
context 'and user mhv_account_type is arbitrary' do
let(:mhv_account_type) { 'some-mhv-account-type' }
it 'returns false' do
expect(described_class.new(user, mhv_medical_records).access?).to be(false)
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/policies/evss_policy_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe EVSSPolicy do
subject { described_class }
permissions :access? do
context 'with a user who has the required evss attributes' do
let(:user) { build(:user, :loa3) }
it 'grants access' do
expect(subject).to permit(user, :evss)
end
it 'increments the StatsD success counter' do
expect { EVSSPolicy.new(user, :evss).access? }.to trigger_statsd_increment('api.evss.policy.success')
end
end
context 'with a user who does not have the required evss attributes' do
let(:user) { build(:unauthorized_evss_user, :loa3) }
it 'denies access' do
expect(subject).not_to permit(user, :evss)
end
it 'increments the StatsD failure counter' do
expect { EVSSPolicy.new(user, :evss).access? }.to trigger_statsd_increment('api.evss.policy.failure')
end
end
end
permissions :access_form526? do
context 'with a user who has the required form526 attributes' do
let(:user) { build(:user, :loa3) }
it 'grants access' do
expect(subject).to permit(user, :evss)
end
it 'increments the StatsD success counter' do
expect { EVSSPolicy.new(user, :evss).access_form526? }.to trigger_statsd_increment('api.evss.policy.success')
end
end
context 'with a user who does not have the required form526 attributes' do
let(:user) { build(:unauthorized_evss_user, :loa3) }
it 'denies access' do
expect(subject).not_to permit(user, :evss)
end
it 'increments the StatsD failure counter' do
expect { EVSSPolicy.new(user, :evss).access_form526? }.to trigger_statsd_increment('api.evss.policy.failure')
end
end
context 'with a user who does not have the required date of birth' do
let(:user) { build(:user, :loa3, birth_date: nil) }
it 'denies access' do
expect(subject).not_to permit(user, :evss)
end
it 'increments the StatsD failure counter' do
expect { EVSSPolicy.new(user, :evss).access_form526? }.to trigger_statsd_increment('api.evss.policy.failure')
end
end
end
end
|
0
|
code_files/vets-api-private/spec/policies
|
code_files/vets-api-private/spec/policies/sign_in/user_info_policy_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
describe SignIn::UserInfoPolicy do
subject { described_class }
let(:user) { build(:user) }
let(:access_token) { build(:access_token, client_id:) }
let(:client_id) { 'some-client-id' }
let(:user_info_clients) { [client_id] }
before do
allow(IdentitySettings.sign_in).to receive(:user_info_clients).and_return(user_info_clients)
end
permissions :show? do
context 'when the current_user is present' do
let(:user) { build(:user) }
context 'when the client_id is in the list of valid clients' do
it 'grants access' do
expect(subject).to permit(user, access_token)
end
end
context 'when the client_id is not in the list of valid clients' do
let(:user_info_clients) { ['some-other-client-id'] }
it 'denies access' do
expect(subject).not_to permit(user, access_token)
end
end
end
context 'when the current_user is not present' do
let(:user) { nil }
it 'denies access' do
expect(subject).not_to permit(user, access_token)
end
end
end
end
|
0
|
code_files/vets-api-private/spec/rswag
|
code_files/vets-api-private/spec/rswag/v0/form21p530a_spec.rb
|
# frozen_string_literal: true
require 'swagger_helper'
require Rails.root.join('spec', 'rswag_override.rb').to_s
require 'rails_helper'
RSpec.describe 'Form 21P-530a API', openapi_spec: 'public/openapi.json', type: :request do
before do
host! Settings.hostname
allow(SecureRandom).to receive(:uuid).and_return('12345678-1234-1234-1234-123456789abc')
allow(Time).to receive(:current).and_return(Time.zone.parse('2025-01-15 10:30:00 UTC'))
end
# Shared example for validation failure
shared_examples 'validates schema and returns 422' do
it 'returns a 422 when request fails schema validation' do |example|
submit_request(example.metadata)
expect(response).to have_http_status(:unprocessable_entity)
end
end
shared_examples 'matches rswag example with status' do |status|
it "matches rswag example and returns #{status}" do |example|
submit_request(example.metadata)
example.metadata[:response][:content] = {
'application/json' => {
example: JSON.parse(response.body, symbolize_names: true)
}
}
assert_response_matches_metadata(example.metadata)
expect(response).to have_http_status(status)
end
end
path '/v0/form21p530a' do
post 'Submit a 21P-530a form' do
tags 'benefits_forms'
operationId 'submitForm21p530a'
consumes 'application/json'
produces 'application/json'
description 'Submit a Form 21P-530a (Application for Burial Allowance - State/Tribal Organizations). ' \
'This endpoint is unauthenticated and may be used by cemetery officials.'
parameter name: :form_data, in: :body, required: true, schema: Openapi::Requests::Form21p530a::FORM_SCHEMA
# Success response
response '200', 'Form successfully submitted' do
schema Openapi::Responses::BenefitsIntakeSubmissionResponse::BENEFITS_INTAKE_SUBMISSION_RESPONSE
let(:form_data) do
JSON.parse(
Rails.root.join('spec', 'fixtures', 'form21p530a', 'valid_form.json').read
).with_indifferent_access
end
include_examples 'matches rswag example with status', :ok
end
response '422', 'Unprocessable Entity - schema validation failed' do
schema '$ref' => '#/components/schemas/Errors'
let(:form_data) do
{
veteranInformation: {
fullName: { first: 'OnlyFirst' }
}
}
end
include_examples 'validates schema and returns 422'
end
end
end
path '/v0/form21p530a/download_pdf' do
post 'Download PDF for Form 21P-530a' do
tags 'benefits_forms'
operationId 'downloadForm21p530aPdf'
consumes 'application/json'
produces 'application/pdf'
description 'Generate and download a filled PDF for Form 21P-530a (Application for Burial Allowance)'
parameter name: :form_data, in: :body, required: true, schema: Openapi::Requests::Form21p530a::FORM_SCHEMA
# Success response - PDF file
response '200', 'PDF generated successfully' do
produces 'application/pdf'
schema type: :string, format: :binary
let(:form_data) do
JSON.parse(
Rails.root.join('spec', 'fixtures', 'form21p530a', 'valid_form.json').read
).with_indifferent_access
end
it 'returns a PDF file' do |example|
submit_request(example.metadata)
expect(response).to have_http_status(:ok)
expect(response.content_type).to eq('application/pdf')
expect(response.headers['Content-Disposition']).to include('attachment')
expect(response.headers['Content-Disposition']).to include('.pdf')
end
end
response '422', 'Unprocessable Entity - schema validation failed' do
produces 'application/json'
schema '$ref' => '#/components/schemas/Errors'
let(:form_data) do
{
veteranInformation: {
fullName: { first: 'OnlyFirst' }
}
}
end
include_examples 'validates schema and returns 422'
end
response '500', 'Internal Server Error - PDF generation failed' do
produces 'application/json'
schema type: :object,
properties: {
errors: {
type: :array,
items: {
type: :object,
properties: {
title: { type: :string },
detail: { type: :string },
status: { type: :string }
}
}
}
}
let(:form_data) do
JSON.parse(
Rails.root.join('spec', 'fixtures', 'form21p530a', 'valid_form.json').read
).with_indifferent_access
end
it 'returns a 500 when PDF generation fails' do |example|
# Mock a PDF generation failure
allow(PdfFill::Filler).to receive(:fill_ancillary_form).and_raise(StandardError.new('PDF generation error'))
submit_request(example.metadata)
expect(response).to have_http_status(:internal_server_error)
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec/rswag
|
code_files/vets-api-private/spec/rswag/v0/form214192_spec.rb
|
# frozen_string_literal: true
require 'swagger_helper'
require Rails.root.join('spec', 'rswag_override.rb').to_s
require 'rails_helper'
RSpec.describe 'Form 21-4192 API', openapi_spec: 'public/openapi.json', type: :request do
before do
host! Settings.hostname
allow(SecureRandom).to receive(:uuid).and_return('12345678-1234-1234-1234-123456789abc')
allow(Time).to receive(:current).and_return(Time.zone.parse('2025-01-15 10:30:00 UTC'))
end
# Shared example for validation failure
shared_examples 'validates schema and returns 422' do
it 'returns a 422 when request fails schema validation' do |example|
submit_request(example.metadata)
expect(response).to have_http_status(:unprocessable_entity)
end
end
# Shared test data
let(:valid_form_data) { JSON.parse(Rails.root.join('spec', 'fixtures', 'form214192', 'valid_form.json').read) }
let(:invalid_form_data) { JSON.parse(Rails.root.join('spec', 'fixtures', 'form214192', 'invalid_form.json').read) }
path '/v0/form214192' do
post 'Submit a 21-4192 form' do
tags 'benefits_forms'
operationId 'submitForm214192'
consumes 'application/json'
produces 'application/json'
description 'Submit a Form 21-4192 (Request for Employment Information in Connection with ' \
'Claim for Disability Benefits)'
parameter name: :form_data, in: :body, required: true, schema: Openapi::Requests::Form214192::FORM_SCHEMA
# Success response
response '200', 'Form successfully submitted' do
schema type: :object,
properties: {
data: {
type: :object,
properties: {
id: { type: :string },
type: { type: :string },
attributes: {
type: :object,
properties: {
submitted_at: { type: :string, format: 'date-time' },
regional_office: {
type: :array,
items: { type: :string },
example: [
'Department of Veterans Affairs',
'Example Regional Office',
'P.O. Box 1234',
'Example City, Wisconsin 12345-6789'
]
},
confirmation_number: { type: :string },
guid: { type: :string },
form: { type: :string }
}
}
}
}
},
required: [:data]
let(:form_data) { JSON.parse(Rails.root.join('spec', 'fixtures', 'form214192', 'valid_form.json').read) }
it 'returns a successful response with form submission data' do |example|
submit_request(example.metadata)
example.metadata[:response][:content] = {
'application/json' => {
example: JSON.parse(response.body, symbolize_names: true)
}
}
assert_response_matches_metadata(example.metadata)
expect(response).to have_http_status(:ok)
end
end
response '422', 'Unprocessable Entity - schema validation failed' do
schema '$ref' => '#/components/schemas/Errors'
let(:form_data) { invalid_form_data }
include_examples 'validates schema and returns 422'
end
end
end
path '/v0/form214192/download_pdf' do
post 'Download PDF for Form 21-4192' do
tags 'benefits_forms'
operationId 'downloadForm214192Pdf'
consumes 'application/json'
produces 'application/pdf'
description 'Generate and download a filled PDF for Form 21-4192 (Request for Employment Information)'
parameter name: :form_data, in: :body, required: true, schema: Openapi::Requests::Form214192::FORM_SCHEMA
# Success response - PDF file
response '200', 'PDF generated successfully' do
produces 'application/pdf'
schema type: :string, format: :binary
let(:form_data) { valid_form_data }
it 'returns a PDF file' do |example|
submit_request(example.metadata)
expect(response).to have_http_status(:ok)
expect(response.content_type).to eq('application/pdf')
expect(response.headers['Content-Disposition']).to include('attachment')
expect(response.headers['Content-Disposition']).to include('.pdf')
end
end
response '422', 'Unprocessable Entity - schema validation failed' do
produces 'application/json'
schema '$ref' => '#/components/schemas/Errors'
let(:form_data) { invalid_form_data }
include_examples 'validates schema and returns 422'
end
response '400', 'Bad Request - invalid JSON' do
produces 'application/json'
schema type: :object,
properties: {
errors: {
type: :array,
items: {
type: :object,
properties: {
title: { type: :string },
detail: { type: :string },
status: { type: :string }
}
}
}
}
let(:form_data) { 'invalid-json-string' }
it 'returns a 400 when JSON is malformed' do
# This test would require manually sending bad JSON, which rswag makes difficult
# Skipping actual execution but documenting the response format
skip 'Requires manual JSON manipulation outside rswag framework'
end
end
response '500', 'Internal Server Error - PDF generation failed' do
produces 'application/json'
schema type: :object,
properties: {
errors: {
type: :array,
items: {
type: :object,
properties: {
title: { type: :string },
detail: { type: :string },
status: { type: :string }
}
}
}
}
let(:form_data) { valid_form_data }
it 'returns a 500 when PDF generation fails' do |example|
# Mock a PDF generation failure
allow(PdfFill::Filler).to receive(:fill_ancillary_form).and_raise(StandardError.new('PDF generation error'))
submit_request(example.metadata)
expect(response).to have_http_status(:internal_server_error)
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/requests/exceptions_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'exceptions', type: :request do
before do
exceptions_controller = Class.new(ApplicationController) do
def test_authentication
head :ok
end
end
stub_const('ExceptionsController', exceptions_controller)
Rails.application.routes.draw do
get '/test_authentication' => 'exceptions#test_authentication'
end
end
after { Rails.application.reload_routes! }
context 'authorization' do
it 'renders json for not authorized' do
get '/test_authentication'
expect(response).to have_http_status(:unauthorized)
expect(JSON.parse(response.body)['errors'].first)
.to eq(
'title' => 'Not authorized',
'detail' => 'Not authorized',
'code' => '401',
'status' => '401'
)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/requests/flipper_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'nokogiri'
RSpec.describe 'flipper', type: :request do
def bypass_flipper_authenticity_token
Rails.application.routes.draw do
mount Flipper::UI.app(
Flipper.instance,
rack_protection: { except: :authenticity_token }
) => '/flipper', constraints: Flipper::RouteAuthorizationConstraint
end
yield
Rails.application.reload_routes!
end
include Warden::Test::Helpers
let(:default_attrs) do
{ 'login' => 'john',
'name' => 'John Doe',
'gravatar_id' => '38581cb351a52002548f40f8066cfecg',
'avatar_url' => 'http://example.com/avatar.jpg',
'email' => 'john@doe.com',
'company' => 'Doe, Inc.' }
end
let(:user) { Warden::GitHub::User.new(default_attrs) }
github_oauth_message = "If you'd like to modify feature toggles, please login with GitHub"
before do
allow_any_instance_of(Warden::Proxy).to receive(:authenticate!).and_return(user)
allow_any_instance_of(Warden::Proxy).to receive(:user).and_return(user)
allow(user).to receive(:organization_member?).with(Settings.sidekiq.github_organization).and_return(false)
allow(user).to receive(:team_member?).with(Settings.sidekiq.github_team).and_return(false)
end
context 'GET /flipper/features' do
context 'Unauthenticated user' do
it 'is told to sign in with GitHub to access features' do
get '/flipper/features'
expect(response.body).to include(github_oauth_message)
assert_response :success
end
it 'is shown a button to sign in with GitHub' do
get '/flipper/features'
body = Nokogiri::HTML(response.body)
signin_button = body.at_css('button:contains("Login with GitHub")')
expect(signin_button).not_to be_nil
assert_response :success
end
it 'can see a list of features, but they are inside of a disabled div and not clickable' do
get '/flipper/features'
body = Nokogiri::HTML(response.body)
disabled_div = body.at_css('div[style="pointer-events: none; opacity: 0.5;"]')
expect(response.body).to include('this_is_only_a_test')
expect(disabled_div).not_to be_nil
assert_response :success
end
end
context 'Authenticated user (through GitHub Oauth)' do
before do
# Mimic the functionality of the end of the OAuth handshake, where #finalize_flow! (`warden_github.rb`)
# is called, setting the value of request.session[:flipper_user] to the mocked Warden::Github user
allow_any_instance_of(ActionDispatch::Request).to receive(:session) { { flipper_user: user } }
end
it 'is not shown a notice to sign into GitHub' do
get '/flipper/features'
expect(response.body).not_to include(github_oauth_message)
assert_response :success
end
it 'is not shown a button to sign in with GitHub' do
get '/flipper/features'
body = Nokogiri::HTML(response.body)
signin_button = body.at_css('button:contains("Login with GitHub")')
expect(signin_button).to be_nil
assert_response :success
end
context 'and Authorized user (organization and team membership)' do
before do
allow(user).to receive(:organization_member?).with(Settings.sidekiq.github_organization).and_return(true)
allow(user).to receive(:team_member?).with(Settings.sidekiq.github_team).and_return(true)
end
it 'can see a list of features and they are clickable (hrefs to feature page)' do
get '/flipper/features'
body = Nokogiri::HTML(response.body)
feature_link = body.at_css('a[href*="/flipper/features/this_is_only_a_test"]')
content_div = body.at_css('div#content')
expect(feature_link).not_to be_nil
expect(content_div).not_to be_nil
assert_response :success
end
end
context 'but Unauthorized user' do
unauthorized_message = 'You are not authorized to perform any actions'
it 'can see a list of features, but they are inside of a disabled div and not clickable' do
get '/flipper/features'
body = Nokogiri::HTML(response.body)
disabled_div = body.at_css('div[style="pointer-events: none; opacity: 0.5;"]')
expect(response.body).to include('this_is_only_a_test')
expect(disabled_div).not_to be_nil
assert_response :success
end
context 'without organization membership' do
it 'is told that they are unauthorized and links to documentation' do
allow(user).to receive(:organization_member?).with(Settings.sidekiq.github_organization).and_return(false)
get '/flipper/features'
body = Nokogiri::HTML(response.body)
docs_link = body.at_css('a[href*="depo-platform-documentation"]')
expect(response.body).to include(unauthorized_message)
expect(docs_link).not_to be_nil
end
end
context 'without team membership' do
it 'is told that they are unauthorized and links to documentation' do
allow(user).to receive(:organization_member?).with(Settings.sidekiq.github_organization).and_return(true)
allow(user).to receive(:team_member?).with(Settings.sidekiq.github_team).and_return(false)
get '/flipper/features'
body = Nokogiri::HTML(response.body)
docs_link = body.at_css('a[href*="depo-platform-documentation"]')
expect(response.body).to include(unauthorized_message)
expect(docs_link).not_to be_nil
end
end
end
end
end
context 'GET flipper/features/:some_feature' do
context 'Unauthenticated user' do
it 'is told to sign in with GitHub to access features' do
get '/flipper/features/this_is_only_a_test'
expect(response.body).to include(github_oauth_message)
assert_response :success
end
it 'is shown a button to sign in with GitHub' do
get '/flipper/features/this_is_only_a_test'
body = Nokogiri::HTML(response.body)
signin_button = body.at_css('button:contains("Login with GitHub")')
expect(signin_button).not_to be_nil
assert_response :success
end
it 'cannot see the feature name or content div on the page' do
get '/flipper/features/this_is_only_a_test'
body = Nokogiri::HTML(response.body)
title = body.at_css('h4:contains("this_is_only_a_test")')
content_div = body.at_css('div#content')
expect(title).to be_nil
expect(content_div).to be_nil
assert_response :success
end
end
context 'Authenticated (through GitHub Oauth)' do
before do
# Mimic the functionality of the end of the OAuth handshake, where #finalize_flow! (`warden_github.rb`)
# is called, setting the value of request.session[:flipper_user] to the mocked Warden::Github user
allow_any_instance_of(ActionDispatch::Request).to receive(:session) { { flipper_user: user } }
end
it 'is not shown a notice to sign into GitHub' do
get '/flipper/features/this_is_only_a_test'
expect(response.body).not_to include(github_oauth_message)
assert_response :success
end
it 'is not shown a button to sign in with GitHub' do
get '/flipper/features/this_is_only_a_test'
body = Nokogiri::HTML(response.body)
signin_button = body.at_css('button:contains("Login with Github")')
expect(signin_button).to be_nil
assert_response :success
end
context 'and Authorized user (organization and team membership)' do
before do
allow(user).to receive(:organization_member?).with(Settings.sidekiq.github_organization).and_return(true)
allow(user).to receive(:team_member?).with(Settings.sidekiq.github_team).and_return(true)
Flipper.disable(:this_is_only_a_test)
end
it 'can see the feature name in title (h4) and button to enable/disable feature' do
get '/flipper/features/this_is_only_a_test'
body = Nokogiri::HTML(response.body)
title = body.at_css('h4:contains("this_is_only_a_test")')
toggle_button = body.at_css('button:contains("Fully Enable")')
expect(title).not_to be_nil
expect(toggle_button).not_to be_nil
assert_response :success
end
end
context 'but Unauthorized user' do
unauthorized_message = 'You are not authorized to perform any actions'
it 'cannot see the feature name or content div on the page' do
get '/flipper/features/this_is_only_a_test'
body = Nokogiri::HTML(response.body)
title = body.at_css('h4:contains("this_is_only_a_test")')
content_div = body.at_css('div#content')
expect(title).to be_nil
expect(content_div).to be_nil
assert_response :success
end
context 'without organization membership' do
it 'is told that they are unauthorized and links to documentation' do
allow(user).to receive(:organization_member?).with(Settings.sidekiq.github_organization).and_return(false)
get '/flipper/features/this_is_only_a_test'
body = Nokogiri::HTML(response.body)
docs_link = body.at_css('a[href*="depo-platform-documentation"]')
expect(response.body).to include(unauthorized_message)
expect(docs_link).not_to be_nil
end
end
context 'without team membership' do
it 'is told that they are unauthorized and links to documentation' do
allow(user).to receive(:organization_member?).with(Settings.sidekiq.github_organization).and_return(true)
allow(user).to receive(:team_member?).with(Settings.sidekiq.github_team).and_return(false)
get '/flipper/features/this_is_only_a_test'
body = Nokogiri::HTML(response.body)
docs_link = body.at_css('a[href*="depo-platform-documentation"]')
expect(response.body).to include(unauthorized_message)
expect(docs_link).not_to be_nil
end
end
end
end
end
context 'POST flipper/features/:some_feature' do
context 'Unauthenticated User' do
it 'cannot toggle features and returns 403' do
bypass_flipper_authenticity_token do
expect do
post '/flipper/features/this_is_only_a_test/boolean'
end.to raise_error(Common::Exceptions::Forbidden)
end
end
it 'cannot add actors and returns 403' do
bypass_flipper_authenticity_token do
expect do
post '/flipper/features/this_is_only_a_test/actors'
end.to raise_error(Common::Exceptions::Forbidden)
end
end
it 'cannot add groups and returns 403' do
bypass_flipper_authenticity_token do
expect do
post '/flipper/features/this_is_only_a_test/groups'
end.to raise_error(Common::Exceptions::Forbidden)
end
end
it 'cannot adjust percentage_of_actors and returns 403' do
bypass_flipper_authenticity_token do
expect do
post '/flipper/features/this_is_only_a_test/percentage_of_actors'
end.to raise_error(Common::Exceptions::Forbidden)
end
end
it 'cannot adjust percentage_of_time and returns 403' do
bypass_flipper_authenticity_token do
expect do
post '/flipper/features/this_is_only_a_test/percentage_of_time'
end.to raise_error(Common::Exceptions::Forbidden)
end
end
end
context 'Authenticated User' do
before do
allow_any_instance_of(ActionDispatch::Request).to receive(:session) { { flipper_user: user } }
end
context 'Unauthorized User' do
it 'cannot toggle features and returns 403' do
bypass_flipper_authenticity_token do
expect do
post '/flipper/features/this_is_only_a_test/boolean'
end.to raise_error(Common::Exceptions::Forbidden)
end
end
it 'cannot add actors and returns 403' do
bypass_flipper_authenticity_token do
expect do
post '/flipper/features/this_is_only_a_test/actors'
end.to raise_error(Common::Exceptions::Forbidden)
end
end
it 'cannot add groups and returns 403' do
bypass_flipper_authenticity_token do
expect do
post '/flipper/features/this_is_only_a_test/groups'
end.to raise_error(Common::Exceptions::Forbidden)
end
end
it 'cannot adjust percentage_of_actors and returns 403' do
bypass_flipper_authenticity_token do
expect do
post '/flipper/features/this_is_only_a_test/percentage_of_actors'
end.to raise_error(Common::Exceptions::Forbidden)
end
end
it 'cannot adjust percentage_of_time and returns 403' do
bypass_flipper_authenticity_token do
expect do
post '/flipper/features/this_is_only_a_test/percentage_of_time'
end.to raise_error(Common::Exceptions::Forbidden)
end
end
end
context 'Authorized User' do
it 'can toggle features' do
allow(user).to receive(:organization_member?).with(Settings.flipper.github_organization).and_return(true)
allow(user).to receive(:team_member?).with(Settings.flipper.github_team).and_return(true)
Flipper.enable(:this_is_only_a_test)
bypass_flipper_authenticity_token do
expect(Flipper.enabled?(:this_is_only_a_test)).to be true
post '/flipper/features/this_is_only_a_test/boolean', params: nil
follow_redirect!
assert_response :success
expect(Flipper.enabled?(:this_is_only_a_test)).to be false
end
end
it 'can add actors' do
allow(user).to receive(:organization_member?).with(Settings.flipper.github_organization).and_return(true)
allow(user).to receive(:team_member?).with(Settings.flipper.github_team).and_return(true)
Flipper.disable(:this_is_only_a_test)
test_user = create(:user)
bypass_flipper_authenticity_token do
expect(Flipper.enabled?(:this_is_only_a_test)).to be false
post '/flipper/features/this_is_only_a_test/actors',
params: { operation: 'enable', value: test_user.flipper_id }
follow_redirect!
assert_response :success
expect(Flipper.enabled?(:this_is_only_a_test, test_user)).to be true
end
end
it 'can adjust percentage_of_actors' do
allow(user).to receive(:organization_member?).with(Settings.flipper.github_organization).and_return(true)
allow(user).to receive(:team_member?).with(Settings.flipper.github_team).and_return(true)
Flipper.disable(:this_is_only_a_test)
test_user1 = create(:user_account)
test_user2 = create(:user_account)
bypass_flipper_authenticity_token do
expect(Flipper.enabled?(:this_is_only_a_test)).to be false
post '/flipper/features/this_is_only_a_test/percentage_of_actors', params: { value: 100 }
follow_redirect!
assert_response :success
expect(Flipper.enabled?(:this_is_only_a_test, test_user1)).to be true
expect(Flipper.enabled?(:this_is_only_a_test, test_user2)).to be true
post '/flipper/features/this_is_only_a_test/percentage_of_actors', params: { value: 0 }
follow_redirect!
assert_response :success
expect(Flipper.enabled?(:this_is_only_a_test, test_user1)).to be false
expect(Flipper.enabled?(:this_is_only_a_test, test_user2)).to be false
end
end
end
end
end
context 'Flipper UI placeholder text for actors' do
before do
allow_any_instance_of(ActionDispatch::Request).to receive(:session) { { flipper_user: user } }
allow(user).to receive(:organization_member?).with(Settings.flipper.github_organization).and_return(true)
allow(user).to receive(:team_member?).with(Settings.flipper.github_team).and_return(true)
end
it 'displays placeholder text indicating case sensitivity and comma-separated values are supported' do
feature = Flipper[:this_is_only_a_test]
allow(feature).to receive_messages(boolean_value: false, actors_value: [])
get '/flipper/features/this_is_only_a_test'
assert_response :success
body = Nokogiri::HTML(response.body)
actor_input = body.at_css('input[name="value"][placeholder*="CASE SENSITIVE"]')
expect(actor_input).not_to be_nil
expect(actor_input['placeholder']).to include('CASE SENSITIVE')
expect(actor_input['placeholder']).to include('lowercase email')
expect(actor_input['placeholder']).to include('comma-separated')
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/requests/swagger_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'lighthouse/direct_deposit/configuration'
require 'support/bb_client_helpers'
require 'support/pagerduty/services/spec_setup'
require 'support/stub_debt_letters'
require 'support/medical_copays/stub_medical_copays'
require 'support/stub_efolder_documents'
require_relative '../../modules/debts_api/spec/support/stub_financial_status_report'
require 'bgs/service'
require 'sign_in/logingov/service'
require 'hca/enrollment_eligibility/constants'
require 'form1010_ezr/service'
require 'lighthouse/facilities/v1/client'
require 'debts_api/v0/digital_dispute_submission_service'
require 'debts_api/v0/digital_dispute_dmc_service'
RSpec.describe 'API doc validations', type: :request do
context 'json validation' do
it 'has valid json' do
get '/v0/apidocs.json'
json = response.body
JSON.parse(json).to_yaml
end
end
end
RSpec.describe 'the v0 API documentation', order: :defined, type: %i[apivore request] do
include AuthenticatedSessionHelper
subject { Apivore::SwaggerChecker.instance_for('/v0/apidocs.json') }
let(:mhv_user) { build(:user, :mhv, middle_name: 'Bob') }
let(:json_headers) do
{
'_headers' => {
'Accept' => 'application/json',
'Content-Type' => 'application/json'
}
}
end
context 'has valid paths' do
let(:headers) { { '_headers' => { 'Cookie' => sign_in(mhv_user, nil, true) } } }
before do
create(:mhv_user_verification, mhv_uuid: mhv_user.mhv_credential_uuid)
allow(VAProfile::Configuration::SETTINGS.contact_information).to receive(:cache_enabled).and_return(true)
allow(VAProfile::Configuration::SETTINGS.contact_information).to receive(:cache_enabled).and_return(true)
end
describe 'backend statuses' do
describe '/v0/backend_statuses' do
context 'when successful' do
include_context 'simulating Redis caching of PagerDuty#get_services'
it 'supports getting external services status data' do
expect(subject).to validate(:get, '/v0/backend_statuses', 200, headers)
end
end
context 'when the PagerDuty API rate limit has been exceeded' do
it 'returns a 429 with error details' do
VCR.use_cassette('pagerduty/external_services/get_services_429') do
expect(subject).to validate(:get, '/v0/backend_statuses', 429, headers)
end
end
end
end
end
describe 'sign in service' do
describe 'POST v0/sign_in/token' do
let(:user_verification) { create(:user_verification) }
let(:user_verification_id) { user_verification.id }
let(:grant_type) { 'authorization_code' }
let(:code) { '0c2d21d3-465b-4054-8030-1d042da4f667' }
let(:code_verifier) { '5787d673fb784c90f0e309883241803d' }
let(:code_challenge) { '1BUpxy37SoIPmKw96wbd6MDcvayOYm3ptT-zbe6L_zM' }
let!(:code_container) do
create(:code_container,
code:,
code_challenge:,
user_verification_id:,
client_id: client_config.client_id)
end
let(:client_config) { create(:client_config, enforced_terms: nil) }
it 'validates the authorization_code & returns tokens' do
expect(subject).to validate(
:post,
'/v0/sign_in/token',
200,
'_query_string' => "grant_type=#{grant_type}&code_verifier=#{code_verifier}&code=#{code}"
)
end
end
describe 'POST v0/sign_in/refresh' do
let(:user_verification) { create(:user_verification) }
let(:validated_credential) { create(:validated_credential, user_verification:, client_config:) }
let(:client_config) { create(:client_config, enforced_terms: nil) }
let(:session_container) do
SignIn::SessionCreator.new(validated_credential:).perform
end
let(:refresh_token) do
CGI.escape(SignIn::RefreshTokenEncryptor.new(refresh_token: session_container.refresh_token).perform)
end
let(:refresh_token_param) { { refresh_token: } }
it 'refreshes the session and returns new tokens' do
expect(subject).to validate(
:post,
'/v0/sign_in/refresh',
200,
'_query_string' => "refresh_token=#{refresh_token}"
)
end
end
describe 'POST v0/sign_in/revoke' do
let(:user_verification) { create(:user_verification) }
let(:validated_credential) { create(:validated_credential, user_verification:, client_config:) }
let(:client_config) { create(:client_config, enforced_terms: nil) }
let(:session_container) do
SignIn::SessionCreator.new(validated_credential:).perform
end
let(:refresh_token) do
CGI.escape(SignIn::RefreshTokenEncryptor.new(refresh_token: session_container.refresh_token).perform)
end
let(:refresh_token_param) { { refresh_token: CGI.escape(refresh_token) } }
it 'revokes the session' do
expect(subject).to validate(
:post,
'/v0/sign_in/revoke',
200,
'_query_string' => "refresh_token=#{refresh_token}"
)
end
end
describe 'GET v0/sign_in/revoke_all_sessions' do
let(:user_verification) { create(:user_verification) }
let(:validated_credential) { create(:validated_credential, user_verification:, client_config:) }
let(:client_config) { create(:client_config, enforced_terms: nil) }
let(:session_container) do
SignIn::SessionCreator.new(validated_credential:).perform
end
let(:access_token_object) { session_container.access_token }
let!(:user) { create(:user, :loa3, uuid: access_token_object.user_uuid, middle_name: 'leo') }
let(:access_token) { SignIn::AccessTokenJwtEncoder.new(access_token: access_token_object).perform }
it 'revokes the session' do
expect(subject).to validate(
:get,
'/v0/sign_in/revoke_all_sessions',
200,
'_headers' => {
'Authorization' => "Bearer #{access_token}"
}
)
end
end
end
it 'supports listing in-progress forms' do
expect(subject).to validate(:get, '/v0/in_progress_forms', 200, headers)
expect(subject).to validate(:get, '/v0/in_progress_forms', 401)
end
it 'supports fetching feature_toggles' do
expect(subject).to validate(:get, '/v0/feature_toggles', 200, features: 'facility_locator')
end
it 'supports fetching maintenance windows' do
expect(subject).to validate(:get, '/v0/maintenance_windows', 200)
end
it 'supports getting an in-progress form', :initiate_vaprofile do
create(:in_progress_form, user_uuid: mhv_user.uuid)
expect(subject).to validate(
:get,
'/v0/in_progress_forms/{id}',
200,
headers.merge('id' => '1010ez')
)
expect(subject).to validate(:get, '/v0/in_progress_forms/{id}', 401, 'id' => '1010ez')
end
it 'supports updating an in-progress form' do
expect(subject).to validate(
:put,
'/v0/in_progress_forms/{id}',
200,
headers.merge(
'id' => '1010ez',
'_data' => { 'form_data' => { wat: 'foo' } }
)
)
expect(subject).to validate(
:put,
'/v0/in_progress_forms/{id}',
500,
headers.merge('id' => '1010ez')
)
expect(subject).to validate(:put, '/v0/in_progress_forms/{id}', 401, 'id' => '1010ez')
end
it 'supports deleting an in-progress form' do
form = create(:in_progress_form, user_uuid: mhv_user.uuid)
expect(subject).to validate(
:delete,
'/v0/in_progress_forms/{id}',
200,
headers.merge('id' => form.form_id)
)
expect(subject).to validate(:delete, '/v0/in_progress_forms/{id}', 401, 'id' => form.form_id)
end
it 'supports getting an disability_compensation_in_progress form', :initiate_vaprofile do
create(:in_progress_526_form, user_uuid: mhv_user.uuid)
VCR.use_cassette('lighthouse/claims/200_response') do
expect(subject).to validate(
:get,
'/v0/disability_compensation_in_progress_forms/{id}',
200,
headers.merge('id' => FormProfiles::VA526ez::FORM_ID)
)
end
expect(subject).to validate(:get, '/v0/disability_compensation_in_progress_forms/{id}',
401,
'id' => FormProfiles::VA526ez::FORM_ID)
end
it 'supports updating an disability_compensation_in_progress form' do
expect(subject).to validate(
:put,
'/v0/disability_compensation_in_progress_forms/{id}',
200,
headers.merge(
'id' => FormProfiles::VA526ez::FORM_ID,
'_data' => { 'form_data' => { wat: 'foo' } }
)
)
expect(subject).to validate(
:put,
'/v0/disability_compensation_in_progress_forms/{id}',
500,
headers.merge('id' => FormProfiles::VA526ez::FORM_ID)
)
expect(subject).to validate(:put, '/v0/disability_compensation_in_progress_forms/{id}',
401,
'id' => FormProfiles::VA526ez::FORM_ID)
end
it 'supports deleting an disability_compensation_in_progress form' do
form = create(:in_progress_526_form, user_uuid: mhv_user.uuid)
expect(subject).to validate(
:delete,
'/v0/disability_compensation_in_progress_forms/{id}',
200,
headers.merge('id' => FormProfiles::VA526ez::FORM_ID)
)
expect(subject).to validate(:delete, '/v0/disability_compensation_in_progress_forms/{id}',
401,
'id' => form.form_id)
end
it 'supports adding an education benefits form' do
expect(subject).to validate(
:post,
'/v0/education_benefits_claims/{form_type}',
200,
'form_type' => '1990',
'_data' => {
'education_benefits_claim' => {
'form' => build(:va1990).form
}
}
)
expect(subject).to validate(
:post,
'/v0/education_benefits_claims/{form_type}',
422,
'form_type' => '1990',
'_data' => {
'education_benefits_claim' => {
'form' => {}.to_json
}
}
)
end
it 'supports adding a claim document', :skip_va_profile_user do
VCR.use_cassette('uploads/validate_document') do
expect(subject).to validate(
:post,
'/v0/claim_attachments',
200,
'_data' => {
'form_id' => '21P-530EZ',
file: fixture_file_upload('spec/fixtures/files/doctors-note.pdf')
}
)
expect(subject).to validate(
:post,
'/v0/claim_attachments',
422,
'_data' => {
'form_id' => '21P-530EZ',
file: fixture_file_upload('spec/fixtures/files/empty_file.txt')
}
)
end
end
it 'supports checking stem_claim_status' do
expect(subject).to validate(:get, '/v0/education_benefits_claims/stem_claim_status', 200)
end
describe '10-10CG' do
context 'submitting caregiver assistance claim form' do
it 'successfully submits a caregiver assistance claim' do
expect_any_instance_of(Form1010cg::Service).to receive(:assert_veteran_status)
expect(Form1010cg::SubmissionJob).to receive(:perform_async)
expect(subject).to validate(
:post,
'/v0/caregivers_assistance_claims',
200,
'_data' => {
'caregivers_assistance_claim' => {
'form' => build(:caregivers_assistance_claim).form
}
}
)
end
it 'handles 422' do
expect(subject).to validate(
:post,
'/v0/caregivers_assistance_claims',
422,
'_data' => {
'caregivers_assistance_claim' => {
'form' => {}.to_json
}
}
)
end
end
context 'supports uploading an attachment' do
it 'handles errors' do
expect(subject).to validate(
:post,
'/v0/form1010cg/attachments',
400,
'_data' => {
'attachment' => {}
}
)
end
it 'handles 422' do
expect(subject).to validate(
:post,
'/v0/form1010cg/attachments',
422,
'_data' => {
'attachment' => {
file_data: fixture_file_upload('spec/fixtures/files/doctors-note.gif')
}
}
)
end
it 'handles success' do
form_attachment = build(:form1010cg_attachment, :with_attachment)
allow_any_instance_of(FormAttachmentCreate).to receive(:save_attachment_to_cloud!).and_return(true)
allow_any_instance_of(FormAttachmentCreate).to receive(:form_attachment).and_return(form_attachment)
expect(subject).to validate(
:post,
'/v0/form1010cg/attachments',
200,
'_data' => {
'attachment' => {
'file_data' => fixture_file_upload('spec/fixtures/files/doctors-note.pdf', 'application/pdf')
}
}
)
end
end
context 'facilities' do
let(:mock_facility_response) do
{
'data' => [
{ 'id' => 'vha_123', 'attributes' => { 'name' => 'Facility 1' } },
{ 'id' => 'vha_456', 'attributes' => { 'name' => 'Facility 2' } }
]
}
end
let(:lighthouse_service) { double('FacilitiesApi::V2::Lighthouse::Client') }
it 'successfully returns list of facilities' do
expect(FacilitiesApi::V2::Lighthouse::Client).to receive(:new).and_return(lighthouse_service)
expect(lighthouse_service).to receive(:get_paginated_facilities).and_return(mock_facility_response)
expect(subject).to validate(
:post,
'/v0/caregivers_assistance_claims/facilities',
200
)
end
end
end
it 'supports adding a burial claim', run_at: 'Thu, 29 Aug 2019 17:45:03 GMT' do
allow(SecureRandom).to receive(:uuid).and_return('c3fa0769-70cb-419a-b3a6-d2563e7b8502')
VCR.use_cassette(
'mpi/find_candidate/find_profile_with_attributes',
VCR::MATCH_EVERYTHING
) do
expect(subject).to validate(
:post,
'/burials/v0/claims',
200,
'_data' => {
'burial_claim' => {
'form' => build(:burials_saved_claim).form
}
}
)
expect(subject).to validate(
:post,
'/burials/v0/claims',
422,
'_data' => {
'burial_claim' => {
'invalid-form' => { invalid: true }.to_json
}
}
)
end
end
it 'supports adding a pension claim' do
allow(SecureRandom).to receive(:uuid).and_return('c3fa0769-70cb-419a-b3a6-d2563e7b8502')
VCR.use_cassette(
'mpi/find_candidate/find_profile_with_attributes',
VCR::MATCH_EVERYTHING
) do
expect(subject).to validate(
:post,
'/pensions/v0/claims',
200,
'_data' => {
'pension_claim' => {
'form' => build(:pensions_saved_claim).form
}
}
)
expect(subject).to validate(
:post,
'/pensions/v0/claims',
422,
'_data' => {
'pension_claim' => {
'invalid-form' => { invalid: true }.to_json
}
}
)
end
end
context 'MDOT tests' do
let(:user_details) do
{
first_name: 'Greg',
last_name: 'Anderson',
middle_name: 'A',
birth_date: '1991-04-05',
ssn: '000550237'
}
end
let(:user) { build(:user, :loa3, user_details) }
let(:headers) do
{
'_headers' => {
'Cookie' => sign_in(user, nil, true),
'Accept' => 'application/json',
'Content-Type' => 'application/json'
}
}
end
let(:body) do
{
'use_veteran_address' => true,
'use_temporary_address' => false,
'order' => [{ 'product_id' => 6650 }, { 'product_id' => 8271 }],
'permanent_address' => {
'street' => '125 SOME RD',
'street2' => 'APT 101',
'city' => 'DENVER',
'state' => 'CO',
'country' => 'United States',
'postal_code' => '111119999'
},
'temporary_address' => {
'street' => '17250 w colfax ave',
'street2' => 'a-204',
'city' => 'Golden',
'state' => 'CO',
'country' => 'United States',
'postal_code' => '80401'
},
'vet_email' => 'vet1@va.gov'
}
end
it 'supports creating a MDOT order' do
expect(subject).to validate(:post, '/v0/mdot/supplies', 401)
VCR.use_cassette('mdot/submit_order_multi_orders', VCR::MATCH_EVERYTHING) do
set_mdot_token_for(user)
expect(subject).to validate(
:post,
'/v0/mdot/supplies',
200,
headers.merge(
'_data' => body.to_json
)
)
end
end
end
it 'supports getting cemetaries preneed claim' do
VCR.use_cassette('preneeds/cemeteries/gets_a_list_of_cemeteries') do
expect(subject).to validate(
:get,
'/v0/preneeds/cemeteries',
200,
'_headers' => { 'content-type' => 'application/json' }
)
end
end
context 'debts tests' do
let(:user) { build(:user, :loa3) }
let(:headers) do
{ '_headers' => { 'Cookie' => sign_in(user, nil, true) } }
end
context 'debt letters index' do
stub_debt_letters(:index)
it 'validates the route' do
expect(subject).to validate(
:get,
'/v0/debt_letters',
200,
headers
)
end
end
context 'debt letters show' do
stub_debt_letters(:show)
it 'validates the route' do
expect(subject).to validate(
:get,
'/v0/debt_letters/{id}',
200,
headers.merge(
'id' => CGI.escape(document_id)
)
)
end
end
context 'debts index' do
it 'validates the route' do
VCR.use_cassette('bgs/people_service/person_data') do
VCR.use_cassette('debts/get_letters', VCR::MATCH_EVERYTHING) do
expect(subject).to validate(
:get,
'/v0/debts',
200,
headers
)
end
end
end
end
context 'digital disputes' do
let(:pdf_file) do
fixture_file_upload('spec/fixtures/pdf_fill/686C-674/tester.pdf', 'application/pdf')
end
let(:metadata_json) do
{
'disputes' => [
{
'composite_debt_id' => '71166',
'deduction_code' => '71',
'original_ar' => 166.67,
'current_ar' => 120.4,
'benefit_type' => 'CH33 Books, Supplies/MISC EDU',
'dispute_reason' => "I don't think I owe this debt to VA"
}
]
}.to_json
end
context 'when the :digital_dmc_dispute_service feature is on' do
it 'validates the route' do
allow_any_instance_of(DebtsApi::V0::DigitalDisputeDmcService).to receive(:call!)
expect(subject).to validate(
:post,
'/debts_api/v0/digital_disputes',
200,
headers.merge(
'_data' => { metadata: metadata_json, files: [pdf_file] }
)
)
end
end
context 'when the :digital_dmc_dispute_service feature is off' do
it 'validates the route' do
allow(Flipper).to receive(:enabled?).with(:digital_dmc_dispute_service).and_return(false)
allow_any_instance_of(DebtsApi::V0::DigitalDisputeSubmissionService).to receive(:call).and_return(
success: true,
message: 'Dispute successfully submitted',
submission_id: '12345'
)
expect(subject).to validate(
:post,
'/debts_api/v0/digital_disputes',
200,
headers.merge(
'_data' => { metadata: metadata_json, files: [pdf_file] }
)
)
end
end
end
end
context 'medical copays tests' do
let(:user) { build(:user, :loa3) }
let(:headers) do
{ '_headers' => { 'Cookie' => sign_in(user, nil, true) } }
end
context 'medical copays index' do
stub_medical_copays(:index)
it 'validates the route' do
expect(subject).to validate(
:get,
'/v0/medical_copays',
200,
headers
)
end
end
context 'medical copays show' do
stub_medical_copays_show
it 'validates the route' do
expect(subject).to validate(
:get,
'/v0/medical_copays/{id}',
200,
headers.merge(
'id' => CGI.escape(id)
)
)
end
end
context 'medical copays get_pdf_statement_by_id' do
stub_medical_copays(:get_pdf_statement_by_id)
it 'validates the route' do
expect(subject).to validate(
:get,
'/v0/medical_copays/get_pdf_statement_by_id/{statement_id}',
200,
headers.merge(
'statement_id' => CGI.escape(statement_id)
)
)
end
end
context 'medical copays send_statement_notifications' do
let(:headers) do
{ '_headers' => { 'apiKey' => 'abcd1234abcd1234abcd1234abcd1234abcd1234' } }
end
it 'validates the route' do
expect(subject).to validate(
:post,
'/v0/medical_copays/send_statement_notifications',
200,
headers
)
end
end
end
context 'eFolder tests' do
let(:user) { build(:user, :loa3) }
let(:headers) do
{ '_headers' => { 'Cookie' => sign_in(user, nil, true) } }
end
context 'efolder index' do
stub_efolder_index_documents
it 'validates the route' do
expect(subject).to validate(
:get,
'/v0/efolder',
200,
headers
)
end
end
context 'efolder show' do
stub_efolder_show_document
it 'validates the route' do
expect(subject).to validate(
:get,
'/v0/efolder/{id}',
200,
headers.merge(
'id' => CGI.escape(document_id)
)
)
end
end
end
context 'Financial Status Reports' do
let(:user) { build(:user, :loa3) }
let(:headers) do
{ '_headers' => { 'Cookie' => sign_in(user, nil, true) } }
end
let(:fsr_data) { get_fixture('dmc/fsr_submission') }
context 'financial status report create' do
it 'validates the route' do
pdf_stub = class_double(PdfFill::Filler).as_stubbed_const
allow(pdf_stub).to receive(:fill_ancillary_form).and_return(Rails.root.join(
*'/spec/fixtures/dmc/5655.pdf'.split('/')
).to_s)
VCR.use_cassette('dmc/submit_fsr') do
VCR.use_cassette('bgs/people_service/person_data') do
expect(subject).to validate(
:post,
'/debts_api/v0/financial_status_reports',
200,
headers.merge(
'_data' => fsr_data
)
)
end
end
end
end
describe 'financial status report submissions' do
it 'supports getting financial status report submissions' do
expect(subject).to validate(
:get,
'/debts_api/v0/financial_status_reports/submissions',
200,
headers
)
end
end
end
context 'HCA tests' do
let(:login_required) { HCA::EnrollmentEligibility::Constants::LOGIN_REQUIRED }
let(:test_veteran) do
json_string = Rails.root.join('spec', 'fixtures', 'hca', 'veteran.json').read
json = JSON.parse(json_string)
json.delete('email')
json.to_json
end
let(:user) { build(:ch33_dd_user) }
let(:headers) do
{ '_headers' => { 'Cookie' => sign_in(user, nil, true) } }
end
it 'supports getting the disability rating' do
VCR.use_cassette('bgs/service/find_rating_data', VCR::MATCH_EVERYTHING) do
expect(subject).to validate(
:get,
'/v0/health_care_applications/rating_info',
200,
headers
)
end
end
context 'authorized user' do
it 'supports getting the hca enrollment status' do
expect(HealthCareApplication).to receive(:enrollment_status).with(
user.icn, true
).and_return(parsed_status: login_required)
expect(subject).to validate(
:get,
'/v0/health_care_applications/enrollment_status',
200,
headers
)
end
end
it 'supports getting the hca enrollment status with post call' do
expect(HealthCareApplication).to receive(:user_icn).and_return('123')
expect(HealthCareApplication).to receive(:enrollment_status).with(
'123', nil
).and_return(parsed_status: login_required)
expect(subject).to validate(
:post,
'/v0/health_care_applications/enrollment_status',
200,
'_data' => {
userAttributes: {
veteranFullName: {
first: 'First',
last: 'last'
},
veteranDateOfBirth: '1923-01-02',
veteranSocialSecurityNumber: '111-11-1234',
gender: 'F'
}
}
)
end
it 'supports getting the hca health check' do
VCR.use_cassette('hca/health_check', match_requests_on: [:body]) do
expect(subject).to validate(
:get,
'/v0/health_care_applications/healthcheck',
200
)
end
end
it 'supports submitting a hca attachment' do
expect(subject).to validate(
:post,
'/v0/hca_attachments',
200,
'_data' => {
'hca_attachment' => {
file_data: fixture_file_upload('spec/fixtures/pdf_fill/extras.pdf')
}
}
)
end
it 'returns 422 if the attachment is not an allowed type' do
expect(subject).to validate(
:post,
'/v0/hca_attachments',
422,
'_data' => {
'hca_attachment' => {
file_data: fixture_file_upload('invalid_idme_cert.crt')
}
}
)
end
it 'supports getting a health care application state' do
expect(subject).to validate(
:get,
'/v0/health_care_applications/{id}',
200,
'id' => create(:health_care_application).id
)
end
it 'returns a 400 if no attachment data is given' do
expect(subject).to validate(:post, '/v0/hca_attachments', 400, '')
end
it 'supports submitting a health care application', run_at: '2017-01-31' do
allow(HealthCareApplication).to receive(:user_icn).and_return('123')
VCR.use_cassette('hca/submit_anon', match_requests_on: [:body]) do
expect(subject).to validate(
:post,
'/v0/health_care_applications',
200,
'_data' => {
'form' => test_veteran
}
)
end
expect(subject).to validate(
:post,
'/v0/health_care_applications',
422,
'_data' => {
'form' => {}.to_json
}
)
allow_any_instance_of(HCA::Service).to receive(:submit_form) do
raise Common::Client::Errors::HTTPError, 'error message'
end
expect(subject).to validate(
:post,
'/v0/health_care_applications',
400,
'_data' => {
'form' => test_veteran
}
)
end
context ':hca_cache_facilities feature is off' do
before { allow(Flipper).to receive(:enabled?).with(:hca_cache_facilities).and_return(false) }
it 'supports returning list of active facilities' do
mock_job = instance_double(HCA::HealthFacilitiesImportJob)
expect(HCA::HealthFacilitiesImportJob).to receive(:new).and_return(mock_job)
expect(mock_job).to receive(:perform)
VCR.use_cassette('lighthouse/facilities/v1/200_facilities_facility_ids', match_requests_on: %i[method uri]) do
expect(subject).to validate(
:get,
'/v0/health_care_applications/facilities',
200,
{ '_query_string' => 'facilityIds[]=vha_757&facilityIds[]=vha_358' }
)
end
end
end
context ':hca_cache_facilities feature is on' do
before { allow(Flipper).to receive(:enabled?).with(:hca_cache_facilities).and_return(true) }
it 'supports returning list of active facilities' do
create(:health_facility, name: 'Test Facility', station_number: '123', postal_name: 'OH')
expect(subject).to validate(
:get,
'/v0/health_care_applications/facilities',
200,
{ '_query_string' => 'state=OH' }
)
end
end
end
context 'Form1010Ezr tests' do
let(:form) do
json_string = Rails.root.join('spec', 'fixtures', 'form1010_ezr', 'valid_form.json').read
json = JSON.parse(json_string)
json.to_json
end
let(:user) do
create(
:evss_user,
:loa3,
icn: '1013032368V065534',
birth_date: '1986-01-02',
first_name: 'FirstName',
middle_name: 'MiddleName',
last_name: 'ZZTEST',
suffix: 'Jr.',
ssn: '111111234',
gender: 'F'
)
end
let(:headers) { { '_headers' => { 'Cookie' => sign_in(user, nil, true) } } }
context 'attachments' do
context 'unauthenticated user' do
it 'returns unauthorized status code' do
expect(subject).to validate(
:post,
'/v0/form1010_ezr_attachments',
401
)
end
end
context 'authenticated' do
it 'supports submitting an ezr attachment' do
expect(subject).to validate(
:post,
'/v0/form1010_ezr_attachments',
200,
headers.merge(
'_data' => {
'form1010_ezr_attachment' => {
file_data: fixture_file_upload('spec/fixtures/pdf_fill/extras.pdf')
}
}
)
)
end
it 'returns 422 if the attachment is not an allowed type' do
expect(subject).to validate(
:post,
'/v0/form1010_ezr_attachments',
422,
headers.merge(
'_data' => {
'form1010_ezr_attachment' => {
file_data: fixture_file_upload('invalid_idme_cert.crt')
}
}
)
)
end
it 'returns a 400 if no attachment data is given' do
expect(subject).to validate(
:post,
'/v0/form1010_ezr_attachments',
400,
headers
)
end
context 'when a server error occurs' do
before do
allow(IO).to receive(:popen).and_return(nil)
end
it 'returns a 500' do
expect(subject).to validate(
:post,
'/v0/form1010_ezr_attachments',
500,
headers.merge(
'_data' => {
'form1010_ezr_attachment' => {
file_data: fixture_file_upload('spec/fixtures/pdf_fill/extras.pdf')
}
}
)
)
end
end
end
end
context 'submitting a 1010EZR form' do
context 'unauthenticated user' do
it 'returns unauthorized status code' do
expect(subject).to validate(:post, '/v0/form1010_ezrs', 401)
end
end
context 'authenticated' do
before do
allow_any_instance_of(
Form1010Ezr::VeteranEnrollmentSystem::Associations::Service
).to receive(:reconcile_and_update_associations).and_return(
{
status: 'success',
message: 'All associations were updated successfully',
timestamp: Time.current.iso8601
}
)
end
it 'supports submitting a 1010EZR application', run_at: 'Tue, 21 Nov 2023 20:42:44 GMT' do
VCR.use_cassette('form1010_ezr/authorized_submit_with_es_dev_uri', match_requests_on: [:body]) do
expect(subject).to validate(
:post,
'/v0/form1010_ezrs',
200,
headers.merge(
'_data' => {
'form' => form
}
)
)
end
end
it 'returns a 422 if form validation fails', run_at: 'Tue, 21 Nov 2023 20:42:44 GMT' do
VCR.use_cassette('form1010_ezr/authorized_submit_with_es_dev_uri', match_requests_on: [:body]) do
expect(subject).to validate(
:post,
'/v0/form1010_ezrs',
422,
headers.merge(
'_data' => {
'form' => {}.to_json
}
)
)
end
end
it 'returns a 400 if a backend service error occurs', run_at: 'Tue, 21 Nov 2023 20:42:44 GMT' do
VCR.use_cassette('form1010_ezr/authorized_submit', match_requests_on: [:body]) do
allow_any_instance_of(Form1010Ezr::Service).to receive(:submit_form) do
raise Common::Exceptions::BackendServiceException, 'error message'
end
expect(subject).to validate(
:post,
'/v0/form1010_ezrs',
400,
headers.merge(
'_data' => {
'form' => form
}
)
)
end
end
it 'returns a 500 if a server error occurs', run_at: 'Tue, 21 Nov 2023 20:42:44 GMT' do
VCR.use_cassette('form1010_ezr/authorized_submit', match_requests_on: [:body]) do
allow_any_instance_of(Form1010Ezr::Service).to receive(:submit_form) do
raise Common::Exceptions::InternalServerError, 'error message'
end
expect(subject).to validate(
:post,
'/v0/form1010_ezrs',
500,
headers.merge(
'_data' => {
'form' => form
}
)
)
end
end
end
end
context 'downloading a 1010EZR pdf form' do
context 'unauthenticated user' do
it 'returns unauthorized status code' do
expect(subject).to validate(:post, '/v0/form1010_ezrs/download_pdf', 401)
end
end
end
end
describe 'disability compensation' do
before do
create(:in_progress_form, form_id: FormProfiles::VA526ez::FORM_ID, user_uuid: mhv_user.uuid)
Flipper.disable('disability_compensation_prevent_submission_job')
Flipper.disable('disability_compensation_production_tester')
allow_any_instance_of(Auth::ClientCredentials::Service).to receive(:get_token).and_return('fake_token')
allow_any_instance_of(User).to receive(:icn).and_return('123498767V234859')
end
let(:form526v2) do
Rails.root.join('spec', 'support', 'disability_compensation_form', 'all_claims_fe_submission.json').read
end
it 'supports getting rated disabilities' do
expect(subject).to validate(:get, '/v0/disability_compensation_form/rated_disabilities', 401)
VCR.use_cassette('lighthouse/veteran_verification/disability_rating/200_response') do
expect(subject).to validate(:get, '/v0/disability_compensation_form/rated_disabilities', 200, headers)
end
VCR.use_cassette('lighthouse/veteran_verification/disability_rating/400_response') do
expect(subject).to validate(:get, '/v0/disability_compensation_form/rated_disabilities', 400, headers)
end
VCR.use_cassette('lighthouse/veteran_verification/disability_rating/502_response') do
expect(subject).to validate(:get, '/v0/disability_compensation_form/rated_disabilities', 502, headers)
end
end
context 'with a loa1 user' do
let(:mhv_user) { build(:user, :loa1) }
it 'returns error on getting rated disabilities without evss authorization' do
expect(subject).to validate(:get, '/v0/disability_compensation_form/rated_disabilities', 403, headers)
end
it 'returns error on getting separation_locations' do
expect(subject).to validate(:get, '/v0/disability_compensation_form/separation_locations', 403, headers)
end
it 'returns error on submit_all_claim' do
expect(subject).to validate(
:post,
'/v0/disability_compensation_form/submit_all_claim',
403,
headers.update(
'_data' => form526v2
)
)
end
it 'returns error on getting submission status' do
expect(subject).to validate(
:get,
'/v0/disability_compensation_form/submission_status/{job_id}',
403,
headers.update(
'_data' => form526v2,
'job_id' => 123
)
)
end
it 'returns error on getting rating info' do
expect(subject).to validate(:get, '/v0/disability_compensation_form/rating_info', 403, headers)
end
end
it 'supports getting separation_locations' do
expect(subject).to validate(:get, '/v0/disability_compensation_form/separation_locations', 401)
VCR.use_cassette('brd/separation_locations_502') do
expect(subject).to validate(:get, '/v0/disability_compensation_form/separation_locations', 502, headers)
end
VCR.use_cassette('brd/separation_locations_503') do
expect(subject).to validate(:get, '/v0/disability_compensation_form/separation_locations', 503, headers)
end
VCR.use_cassette('brd/separation_locations') do
expect(subject).to validate(:get, '/v0/disability_compensation_form/separation_locations', 200, headers)
end
end
it 'supports getting suggested conditions' do
create(:disability_contention_arrhythmia)
expect(subject).to validate(
:get,
'/v0/disability_compensation_form/suggested_conditions{params}',
401,
'params' => '?name_part=arr'
)
expect(subject).to validate(
:get,
'/v0/disability_compensation_form/suggested_conditions{params}',
200,
headers.merge('params' => '?name_part=arr')
)
end
it 'supports submitting the v2 form' do
allow(EVSS::DisabilityCompensationForm::SubmitForm526)
.to receive(:perform_async).and_return('57ca1a62c75e551fd2051ae9')
expect(subject).to validate(:post, '/v0/disability_compensation_form/submit_all_claim', 401)
expect(subject).to validate(:post, '/v0/disability_compensation_form/submit_all_claim', 422,
headers.update('_data' => '{ "form526": "foo"}'))
expect(subject).to validate(
:post,
'/v0/disability_compensation_form/submit_all_claim',
200,
headers.update('_data' => form526v2)
)
end
context 'with a submission and job status' do
let(:submission) { create(:form526_submission, submitted_claim_id: 61_234_567) }
let(:job_status) { create(:form526_job_status, form526_submission_id: submission.id) }
it 'supports getting submission status' do
expect(subject).to validate(
:get,
'/v0/disability_compensation_form/submission_status/{job_id}',
401,
'job_id' => job_status.job_id
)
expect(subject).to validate(
:get,
'/v0/disability_compensation_form/submission_status/{job_id}',
404,
headers.merge('job_id' => 'invalid_id')
)
expect(subject).to validate(
:get,
'/v0/disability_compensation_form/submission_status/{job_id}',
200,
headers.merge('job_id' => job_status.job_id)
)
end
end
context 'when calling EVSS' do
before do
# TODO: remove Flipper feature toggle when lighthouse provider is implemented
allow(Flipper).to receive(:enabled?).with(:profile_lighthouse_rating_info, instance_of(User))
.and_return(false)
end
it 'supports getting rating info' do
expect(subject).to validate(:get, '/v0/disability_compensation_form/rating_info', 401)
VCR.use_cassette('evss/disability_compensation_form/rating_info') do
expect(subject).to validate(:get, '/v0/disability_compensation_form/rating_info', 200, headers)
end
end
end
end
describe 'intent to file' do
let(:mhv_user) { create(:user, :loa3, :legacy_icn) }
before do
Flipper.disable('disability_compensation_production_tester')
allow_any_instance_of(Auth::ClientCredentials::Service).to receive(:get_token).and_return('fake_token')
end
it 'supports getting all intent to file' do
expect(subject).to validate(:get, '/v0/intent_to_file', 401)
VCR.use_cassette('lighthouse/benefits_claims/intent_to_file/200_response') do
expect(subject).to validate(:get, '/v0/intent_to_file', 200, headers)
end
end
it 'supports getting a specific type of intent to file' do
expect(subject).to validate(:get, '/v0/intent_to_file/{itf_type}', 401, 'itf_type' => 'pension')
VCR.use_cassette('lighthouse/benefits_claims/intent_to_file/200_response_pension') do
expect(subject).to validate(
:get,
'/v0/intent_to_file/{itf_type}',
200,
headers.update('itf_type' => 'pension')
)
end
end
it 'supports creating an active compensation intent to file' do
expect(subject).to validate(:post, '/v0/intent_to_file/{itf_type}', 401, 'itf_type' => 'compensation')
VCR.use_cassette('lighthouse/benefits_claims/intent_to_file/create_compensation_200_response') do
expect(subject).to validate(
:post,
'/v0/intent_to_file/{itf_type}',
200,
headers.update('itf_type' => 'compensation')
)
end
end
end
describe 'MVI Users' do
context 'when user is correct' do
let(:mhv_user) { build(:user_with_no_ids) }
it 'fails when invalid form id is passed' do
expect(subject).to validate(:post, '/v0/mvi_users/{id}', 403, headers.merge('id' => '12-1234'))
end
it 'when correct form id is passed, it supports creating mvi user' do
VCR.use_cassette('mpi/add_person/add_person_success') do
VCR.use_cassette('mpi/find_candidate/orch_search_with_attributes') do
VCR.use_cassette('mpi/find_candidate/find_profile_with_identifier') do
expect(subject).to validate(:post, '/v0/mvi_users/{id}', 200, headers.merge('id' => '21-0966'))
end
end
end
end
end
it 'fails when no user information is passed' do
expect(subject).to validate(:post, '/v0/mvi_users/{id}', 401, 'id' => '21-0966')
end
context 'when user is missing birls only' do
let(:mhv_user) { build(:user, :loa3, birls_id: nil) }
it 'fails with 422' do
expect(subject).to validate(:post, '/v0/mvi_users/{id}', 422, headers.merge('id' => '21-0966'))
end
end
end
describe 'supporting evidence upload' do
it 'supports uploading a file' do
expect(subject).to validate(
:post,
'/v0/upload_supporting_evidence',
200,
headers.update(
'_data' => {
'supporting_evidence_attachment' => {
'file_data' => fixture_file_upload('spec/fixtures/pdf_fill/extras.pdf')
}
}
)
)
end
it 'returns a 400 if no attachment data is given' do
expect(subject).to validate(
:post,
'/v0/upload_supporting_evidence',
400,
headers
)
end
it 'returns a 422 if a file is corrupted or invalid' do
expect(subject).to validate(
:post,
'/v0/upload_supporting_evidence',
422,
headers.update(
'_data' => {
'supporting_evidence_attachment' => {
'file_data' => fixture_file_upload('malformed-pdf.pdf')
}
}
)
)
end
end
describe 'gibct' do
describe 'yellow_ribbon_programs' do
describe 'index' do
it 'supports showing a list of yellow_ribbon_programs' do
VCR.use_cassette('gi_client/gets_yellow_ribbon_programs_search_results') do
expect(subject).to validate(:get, '/v0/gi/yellow_ribbon_programs', 200)
end
end
end
end
describe 'institutions' do
describe 'autocomplete' do
it 'supports autocomplete of institution names' do
VCR.use_cassette('gi_client/gets_a_list_of_institution_autocomplete_suggestions') do
expect(subject).to validate(
:get, '/v0/gi/institutions/autocomplete', 200, '_query_string' => 'term=university'
)
end
end
end
describe 'search' do
it 'supports autocomplete of institution names' do
VCR.use_cassette('gi_client/gets_institution_search_results') do
expect(subject).to validate(
:get, '/v0/gi/institutions/search', 200, '_query_string' => 'name=illinois'
)
end
end
end
describe 'show' do
context 'successful calls' do
it 'supports showing institution details' do
VCR.use_cassette('gi_client/gets_the_institution_details') do
expect(subject).to validate(:get, '/v0/gi/institutions/{id}', 200, 'id' => '11902614')
end
end
end
context 'unsuccessful calls' do
it 'returns error on refilling a prescription with bad id' do
VCR.use_cassette('gi_client/gets_institution_details_error') do
expect(subject).to validate(:get, '/v0/gi/institutions/{id}', 404, 'id' => 'splunge')
end
end
end
end
end
describe 'calculator_constants' do
it 'supports getting all calculator constants' do
VCR.use_cassette('gi_client/gets_the_calculator_constants') do
expect(subject).to validate(
:get, '/v0/gi/calculator_constants', 200
)
end
end
end
describe 'institution programs' do
describe 'autocomplete' do
it 'supports autocomplete of institution names' do
VCR.use_cassette('gi_client/gets_a_list_of_institution_program_autocomplete_suggestions') do
expect(subject).to validate(
:get, '/v0/gi/institution_programs/autocomplete', 200, '_query_string' => 'term=code'
)
end
end
end
describe 'search' do
it 'supports autocomplete of institution names' do
VCR.use_cassette('gi_client/gets_institution_program_search_results') do
expect(subject).to validate(
:get, '/v0/gi/institution_programs/search', 200, '_query_string' => 'name=code'
)
end
end
end
end
end
it 'supports getting the 200 user data' do
VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', match_requests_on: %i[body],
allow_playback_repeats: true) do
expect(subject).to validate(:get, '/v0/user', 200, headers)
end
end
it 'supports getting the 401 user data' do
VCR.use_cassette('va_profile/veteran_status/veteran_status_401_oid_blank', match_requests_on: %i[body],
allow_playback_repeats: true) do
expect(subject).to validate(:get, '/v0/user', 401)
end
end
context '/v0/user endpoint with some external service errors' do
let(:user) do
build(:user, middle_name: 'Lee', edipi: '1234567890', loa: { current: 3, highest: 3 })
end
let(:headers) { { '_headers' => { 'Cookie' => sign_in(user, nil, true) } } }
it 'supports getting user with some external errors', :skip_mvi do
expect(subject).to validate(:get, '/v0/user', 296, headers)
end
it 'returns 296 when VAProfile returns an error', :skip_mvi do
allow_any_instance_of(VAProfile::VeteranStatus::Service)
.to receive(:get_veteran_status)
.and_raise(StandardError.new('VAProfile error'))
expect(subject).to validate(:get, '/v0/user', 296, headers)
end
end
describe 'Lighthouse Benefits Reference Data' do
it 'gets disabilities data from endpoint' do
VCR.use_cassette('lighthouse/benefits_reference_data/200_disabilities_response') do
expect(subject).to validate(
:get,
'/v0/benefits_reference_data/{path}',
200,
headers.merge('path' => 'disabilities')
)
end
end
it 'gets intake-sites data from endpoint' do
VCR.use_cassette('lighthouse/benefits_reference_data/200_intake_sites_response') do
expect(subject).to validate(
:get,
'/v0/benefits_reference_data/{path}',
200,
headers.merge('path' => 'intake-sites')
)
end
end
end
describe 'Event Bus Gateway' do
include_context 'with service account authentication', 'eventbus',
['http://www.example.com/v0/event_bus_gateway/send_email',
'http://www.example.com/v0/event_bus_gateway/send_push',
'http://www.example.com/v0/event_bus_gateway/send_notifications'], { user_attributes: { participant_id: '1234' } }
context 'when sending emails' do
let(:params) do
{
template_id: '5678'
}
end
it 'documents an unauthenticated request' do
expect(subject).to validate(:post, '/v0/event_bus_gateway/send_email', 401)
end
it 'documents a success' do
expect(subject).to validate(
:post,
'/v0/event_bus_gateway/send_email',
200,
'_headers' => service_account_auth_header,
'_data' => params
)
end
end
context 'when sending push notifications' do
let(:params) do
{
template_id: '9999'
}
end
it 'documents an unauthenticated request' do
expect(subject).to validate(:post, '/v0/event_bus_gateway/send_push', 401)
end
it 'documents a success' do
expect(subject).to validate(
:post,
'/v0/event_bus_gateway/send_push',
200,
'_headers' => service_account_auth_header,
'_data' => params
)
end
end
context 'when sending notifications' do
let(:params) do
{
email_template_id: '1111',
push_template_id: '2222'
}
end
it 'documents an unauthenticated request' do
expect(subject).to validate(:post, '/v0/event_bus_gateway/send_notifications', 401)
end
it 'documents a success' do
expect(subject).to validate(
:post,
'/v0/event_bus_gateway/send_notifications',
200,
'_headers' => service_account_auth_header,
'_data' => params
)
end
end
end
describe 'appeals' do
it 'documents appeals 401' do
expect(subject).to validate(:get, '/v0/appeals', 401)
end
it 'documents appeals 200' do
VCR.use_cassette('/caseflow/appeals') do
expect(subject).to validate(:get, '/v0/appeals', 200, headers)
end
end
it 'documents appeals 403' do
VCR.use_cassette('/caseflow/forbidden') do
expect(subject).to validate(:get, '/v0/appeals', 403, headers)
end
end
it 'documents appeals 404' do
VCR.use_cassette('/caseflow/not_found') do
expect(subject).to validate(:get, '/v0/appeals', 404, headers)
end
end
it 'documents appeals 422' do
VCR.use_cassette('/caseflow/invalid_ssn') do
expect(subject).to validate(:get, '/v0/appeals', 422, headers)
end
end
it 'documents appeals 502' do
VCR.use_cassette('/caseflow/server_error') do
expect(subject).to validate(:get, '/v0/appeals', 502, headers)
end
end
end
describe 'Direct Deposit' do
let(:user) { create(:user, :loa3, :accountable, icn: '1012666073V986297') }
before do
token = 'abcdefghijklmnop'
allow_any_instance_of(DirectDeposit::Configuration).to receive(:access_token).and_return(token)
end
context 'GET' do
it 'returns a 200' do
headers = { '_headers' => { 'Cookie' => sign_in(user, nil, true) } }
VCR.use_cassette('lighthouse/direct_deposit/show/200_valid') do
expect(subject).to validate(:get, '/v0/profile/direct_deposits', 200, headers)
end
end
it 'returns a 400' do
headers = { '_headers' => { 'Cookie' => sign_in(user, nil, true) } }
VCR.use_cassette('lighthouse/direct_deposit/show/errors/400_invalid_icn') do
expect(subject).to validate(:get, '/v0/profile/direct_deposits', 400, headers)
end
end
it 'returns a 401' do
headers = { '_headers' => { 'Cookie' => sign_in(user, nil, true) } }
VCR.use_cassette('lighthouse/direct_deposit/show/errors/401_invalid_token') do
expect(subject).to validate(:get, '/v0/profile/direct_deposits', 401, headers)
end
end
it 'returns a 404' do
headers = { '_headers' => { 'Cookie' => sign_in(user, nil, true) } }
VCR.use_cassette('lighthouse/direct_deposit/show/errors/404_response') do
expect(subject).to validate(:get, '/v0/profile/direct_deposits', 404, headers)
end
end
end
context 'PUT' do
it 'returns a 200' do
headers = { '_headers' => { 'Cookie' => sign_in(user, nil, true) } }
params = {
payment_account: { account_number: '1234567890', account_type: 'Checking', routing_number: '031000503' }
}
VCR.use_cassette('lighthouse/direct_deposit/update/200_valid') do
expect(subject).to validate(:put,
'/v0/profile/direct_deposits',
200,
headers.merge('_data' => params))
end
end
it 'returns a 400' do
headers = { '_headers' => { 'Cookie' => sign_in(user, nil, true) } }
params = {
payment_account: { account_number: '1234567890', account_type: 'Checking', routing_number: '031000503' }
}
VCR.use_cassette('lighthouse/direct_deposit/update/400_routing_number_fraud') do
expect(subject).to validate(:put,
'/v0/profile/direct_deposits',
400,
headers.merge('_data' => params))
end
end
end
end
describe 'onsite notifications' do
let(:private_key) { OpenSSL::PKey::EC.new(File.read('spec/support/certificates/notification-private.pem')) }
before do
allow_any_instance_of(V0::OnsiteNotificationsController).to receive(:public_key).and_return(
OpenSSL::PKey::EC.new(
File.read('spec/support/certificates/notification-public.pem')
)
)
end
it 'supports onsite_notifications #index' do
create(:onsite_notification, va_profile_id: mhv_user.vet360_id)
expect(subject).to validate(:get, '/v0/onsite_notifications', 401)
expect(subject).to validate(:get, '/v0/onsite_notifications', 200, headers)
end
it 'supports updating onsite notifications' do
expect(subject).to validate(
:patch,
'/v0/onsite_notifications/{id}',
401,
'id' => '1'
)
onsite_notification = create(:onsite_notification, va_profile_id: mhv_user.vet360_id)
expect(subject).to validate(
:patch,
'/v0/onsite_notifications/{id}',
404,
headers.merge(
'id' => onsite_notification.id + 1
)
)
expect(subject).to validate(
:patch,
'/v0/onsite_notifications/{id}',
200,
headers.merge(
'id' => onsite_notification.id,
'_data' => {
onsite_notification: {
dismissed: true
}
}
)
)
# rubocop:disable Rails/SkipsModelValidations
onsite_notification.update_column(:template_id, '1')
# rubocop:enable Rails/SkipsModelValidations
expect(subject).to validate(
:patch,
'/v0/onsite_notifications/{id}',
422,
headers.merge(
'id' => onsite_notification.id,
'_data' => {
onsite_notification: {
dismissed: true
}
}
)
)
end
it 'supports creating onsite notifications' do
expect(subject).to validate(:post, '/v0/onsite_notifications', 403)
payload = { user: 'va_notify', iat: Time.current.to_i, exp: 1.minute.from_now.to_i }
expect(subject).to validate(
:post,
'/v0/onsite_notifications',
200,
'_headers' => {
'Authorization' => "Bearer #{JWT.encode(payload, private_key, 'ES256')}"
},
'_data' => {
onsite_notification: {
template_id: 'f9947b27-df3b-4b09-875c-7f76594d766d',
va_profile_id: '1'
}
}
)
payload = { user: 'va_notify', iat: Time.current.to_i, exp: 1.minute.from_now.to_i }
expect(subject).to validate(
:post,
'/v0/onsite_notifications',
422,
'_headers' => {
'Authorization' => "Bearer #{JWT.encode(payload, private_key, 'ES256')}"
},
'_data' => {
onsite_notification: {
template_id: '1',
va_profile_id: '1'
}
}
)
end
end
describe 'profiles', :initiate_vaprofile do
let(:mhv_user) { build(:user, :loa3, idme_uuid: 'b2fab2b5-6af0-45e1-a9e2-394347af91ef') }
before do
sign_in_as(mhv_user)
end
it 'supports getting service history data' do
allow(Flipper).to receive(:enabled?).with(:profile_show_military_academy_attendance, nil).and_return(false)
expect(subject).to validate(:get, '/v0/profile/service_history', 401)
VCR.use_cassette('va_profile/military_personnel/post_read_service_history_200') do
expect(subject).to validate(:get, '/v0/profile/service_history', 200, headers)
end
end
it 'supports getting personal information data' do
expect(subject).to validate(:get, '/v0/profile/personal_information', 401)
VCR.use_cassette('mpi/find_candidate/valid') do
VCR.use_cassette('va_profile/demographics/demographics') do
expect(subject).to validate(:get, '/v0/profile/personal_information', 200, headers)
end
end
end
it 'supports getting full name data' do
expect(subject).to validate(:get, '/v0/profile/full_name', 401)
user = build(:user, :loa3, middle_name: 'Robert')
headers = { '_headers' => { 'Cookie' => sign_in(user, nil, true) } }
expect(subject).to validate(:get, '/v0/profile/full_name', 200, headers)
end
it 'supports updating a va profile email' do
expect(subject).to validate(:post, '/v0/profile/email_addresses/create_or_update', 401)
VCR.use_cassette('va_profile/v2/contact_information/put_email_success') do
email_address = build(:email)
expect(subject).to validate(
:post,
'/v0/profile/email_addresses/create_or_update',
200,
headers.merge('_data' => email_address.as_json)
)
end
end
it 'supports posting va_profile email address data' do
expect(subject).to validate(:post, '/v0/profile/email_addresses', 401)
VCR.use_cassette('va_profile/v2/contact_information/post_email_success') do
email_address = build(:email)
expect(subject).to validate(
:post,
'/v0/profile/email_addresses',
200,
headers.merge('_data' => email_address.as_json)
)
end
end
it 'supports putting va_profile email address data' do
expect(subject).to validate(:put, '/v0/profile/email_addresses', 401)
VCR.use_cassette('va_profile/v2/contact_information/put_email_success') do
email_address = build(:email, id: 42)
expect(subject).to validate(
:put,
'/v0/profile/email_addresses',
200,
headers.merge('_data' => email_address.as_json)
)
end
end
it 'supports deleting va_profile email address data' do
expect(subject).to validate(:delete, '/v0/profile/email_addresses', 401)
VCR.use_cassette('va_profile/v2/contact_information/delete_email_success') do
email_address = build(:email, id: 42)
expect(subject).to validate(
:delete,
'/v0/profile/email_addresses',
200,
headers.merge('_data' => email_address.as_json)
)
end
end
it 'supports updating va_profile telephone data' do
expect(subject).to validate(:post, '/v0/profile/telephones/create_or_update', 401)
VCR.use_cassette('va_profile/v2/contact_information/put_telephone_success') do
telephone = build(:telephone)
expect(subject).to validate(
:post,
'/v0/profile/telephones/create_or_update',
200,
headers.merge('_data' => telephone.as_json)
)
end
end
it 'supports posting va_profile telephone data' do
expect(subject).to validate(:post, '/v0/profile/telephones', 401)
VCR.use_cassette('va_profile/v2/contact_information/post_telephone_success') do
telephone = build(:telephone)
expect(subject).to validate(
:post,
'/v0/profile/telephones',
200,
headers.merge('_data' => telephone.as_json)
)
end
end
it 'supports putting va_profile telephone data' do
expect(subject).to validate(:put, '/v0/profile/telephones', 401)
VCR.use_cassette('va_profile/v2/contact_information/put_telephone_success') do
telephone = build(:telephone, id: 42)
expect(subject).to validate(
:put,
'/v0/profile/telephones',
200,
headers.merge('_data' => telephone.as_json)
)
end
end
it 'supports deleting va_profile telephone data' do
expect(subject).to validate(:delete, '/v0/profile/telephones', 401)
VCR.use_cassette('va_profile/v2/contact_information/delete_telephone_success') do
telephone = build(:telephone, id: 42)
expect(subject).to validate(
:delete,
'/v0/profile/telephones',
200,
headers.merge('_data' => telephone.as_json)
)
end
end
it 'supports putting va_profile preferred-name data' do
expect(subject).to validate(:put, '/v0/profile/preferred_names', 401)
VCR.use_cassette('va_profile/demographics/post_preferred_name_success') do
preferred_name = VAProfile::Models::PreferredName.new(text: 'Pat')
expect(subject).to validate(
:put,
'/v0/profile/preferred_names',
200,
headers.merge('_data' => preferred_name.as_json)
)
end
end
it 'supports putting va_profile gender-identity data' do
expect(subject).to validate(:put, '/v0/profile/gender_identities', 401)
VCR.use_cassette('va_profile/demographics/post_gender_identity_success') do
gender_identity = VAProfile::Models::GenderIdentity.new(code: 'F')
expect(subject).to validate(
:put,
'/v0/profile/gender_identities',
200,
headers.merge('_data' => gender_identity.as_json)
)
end
end
context 'communication preferences' do
before do
allow_any_instance_of(User).to receive(:vet360_id).and_return('18277')
headers['_headers'].merge!(
'accept' => 'application/json',
'content-type' => 'application/json'
)
end
let(:valid_params) do
{
communication_item: {
id: 2,
communication_channel: {
id: 1,
communication_permission: {
allowed: true
}
}
}
}
end
it 'supports the communication preferences update response', run_at: '2021-03-24T23:46:17Z' do
path = '/v0/profile/communication_preferences/{communication_permission_id}'
expect(subject).to validate(:patch, path, 401, 'communication_permission_id' => 1)
VCR.use_cassette('va_profile/communication/put_communication_permissions', VCR::MATCH_EVERYTHING) do
expect(subject).to validate(
:patch,
path,
200,
headers.merge(
'_data' => valid_params.to_json,
'communication_permission_id' => 46
)
)
end
end
it 'supports the communication preferences create response', run_at: '2021-03-24T22:38:21Z' do
valid_params[:communication_item][:communication_channel][:communication_permission][:allowed] = false
path = '/v0/profile/communication_preferences'
expect(subject).to validate(:post, path, 401)
VCR.use_cassette('va_profile/communication/post_communication_permissions', VCR::MATCH_EVERYTHING) do
expect(subject).to validate(
:post,
path,
200,
headers.merge(
'_data' => valid_params.to_json
)
)
end
end
it 'supports the communication preferences index response' do
path = '/v0/profile/communication_preferences'
expect(subject).to validate(:get, path, 401)
VCR.use_cassette('va_profile/communication/get_communication_permissions', VCR::MATCH_EVERYTHING) do
VCR.use_cassette('va_profile/communication/communication_items', VCR::MATCH_EVERYTHING) do
expect(subject).to validate(
:get,
path,
200,
headers
)
end
end
end
end
it 'supports the address validation api' do
address = build(:va_profile_validation_address, :multiple_matches)
VCR.use_cassette(
'va_profile/address_validation/validate_match',
VCR::MATCH_EVERYTHING
) do
VCR.use_cassette(
'va_profile/v3/address_validation/candidate_multiple_matches',
VCR::MATCH_EVERYTHING
) do
expect(subject).to validate(
:post,
'/v0/profile/address_validation',
200,
headers.merge('_data' => { address: address.to_h })
)
end
end
end
it 'supports va_profile create or update address api' do
expect(subject).to validate(:post, '/v0/profile/addresses/create_or_update', 401)
VCR.use_cassette('va_profile/v2/contact_information/put_address_success') do
address = build(:va_profile_address, id: 15_035)
expect(subject).to validate(
:post,
'/v0/profile/addresses/create_or_update',
200,
headers.merge('_data' => address.as_json)
)
end
end
it 'supports posting va_profile address data' do
expect(subject).to validate(:post, '/v0/profile/addresses', 401)
VCR.use_cassette('va_profile/v2/contact_information/post_address_success') do
address = build(:va_profile_address)
expect(subject).to validate(
:post,
'/v0/profile/addresses',
200,
headers.merge('_data' => address.as_json)
)
end
end
it 'supports putting va_profile address data' do
expect(subject).to validate(:put, '/v0/profile/addresses', 401)
VCR.use_cassette('va_profile/v2/contact_information/put_address_success') do
address = build(:va_profile_address, id: 15_035)
expect(subject).to validate(
:put,
'/v0/profile/addresses',
200,
headers.merge('_data' => address.as_json)
)
end
end
it 'supports deleting va_profile address data' do
expect(subject).to validate(:delete, '/v0/profile/addresses', 401)
VCR.use_cassette('va_profile/v2/contact_information/delete_address_success') do
address = build(:va_profile_address, id: 15_035)
expect(subject).to validate(
:delete,
'/v0/profile/addresses',
200,
headers.merge('_data' => address.as_json)
)
end
end
it 'supports posting to initialize a vet360_id' do
expect(subject).to validate(:post, '/v0/profile/initialize_vet360_id', 401)
VCR.use_cassette('va_profile/v2/person/init_vet360_id_success') do
expect(subject).to validate(
:post,
'/v0/profile/initialize_vet360_id',
200,
headers.merge('_data' => {})
)
end
end
end
describe 'profile/status', :initiate_vaprofile do
let(:mhv_user) { build(:user, :loa3, idme_uuid: '9021914d-d4ab-4c49-b297-ac8e8a792ed7') }
before do
sign_in_as(mhv_user)
end
it 'supports GETting async transaction by ID' do
transaction = create(
:va_profile_address_transaction,
transaction_id: '0ea91332-4713-4008-bd57-40541ee8d4d4',
user_uuid: mhv_user.uuid
)
expect(subject).to validate(
:get,
'/v0/profile/status/{transaction_id}',
401,
'transaction_id' => transaction.transaction_id
)
VCR.use_cassette('va_profile/v2/contact_information/address_transaction_status') do
expect(subject).to validate(
:get,
'/v0/profile/status/{transaction_id}',
200,
headers.merge('transaction_id' => transaction.transaction_id)
)
end
end
it 'supports GETting async transactions by user' do
expect(subject).to validate(
:get,
'/v0/profile/status/',
401
)
VCR.use_cassette('va_profile/v2/contact_information/address_transaction_status') do
expect(subject).to validate(
:get,
'/v0/profile/status/',
200,
headers
)
end
end
end
describe 'profile/person/status/:transaction_id' do
let(:user_without_vet360_id) { build(:user, :loa3) }
let(:headers) { { '_headers' => { 'Cookie' => sign_in(user_without_vet360_id, nil, true) } } }
before do
sign_in_as(user_without_vet360_id)
end
it 'supports GETting async person transaction by transaction ID' do
transaction_id = '153536a5-8b18-4572-a3d9-4030bea3ab5c'
transaction = create(
:va_profile_initialize_person_transaction,
:init_vet360_id,
user_uuid: user_without_vet360_id.uuid,
transaction_id:
)
expect(subject).to validate(
:get,
'/v0/profile/person/status/{transaction_id}',
401,
'transaction_id' => transaction.transaction_id
)
VCR.use_cassette('va_profile/v2/contact_information/person_transaction_status') do
expect(subject).to validate(
:get,
'/v0/profile/person/status/{transaction_id}',
200,
headers.merge('transaction_id' => transaction.transaction_id)
)
end
end
end
describe 'profile/connected_applications' do
let(:token) { 'fa0f28d6-224a-4015-a3b0-81e77de269f2' }
let(:user) { create(:user, :loa3, :legacy_icn) }
let(:headers) { { '_headers' => { 'Cookie' => sign_in(user, token, true) } } }
before do
Session.create(uuid: user.uuid, token:)
end
it 'supports getting connected applications' do
expect(subject).to validate(:get, '/v0/profile/connected_applications', 401)
VCR.use_cassette('lighthouse/auth/client_credentials/connected_apps_200') do
expect(subject).to validate(:get, '/v0/profile/connected_applications', 200, headers)
end
end
it 'supports removing connected applications grants' do
parameters = { 'application_id' => '0oa2ey2m6kEL2897N2p7' }
expect(subject).to validate(:delete, '/v0/profile/connected_applications/{application_id}', 401, parameters)
VCR.use_cassette('lighthouse/auth/client_credentials/revoke_consent_204', allow_playback_repeats: true) do
expect(subject).to(
validate(
:delete,
'/v0/profile/connected_applications/{application_id}',
204,
headers.merge(parameters)
)
)
end
end
end
describe 'when MVI returns an unexpected response body' do
it 'supports returning a custom 502 response' do
allow_any_instance_of(UserIdentity).to receive(:sign_in).and_return({
service_name: 'oauth_IDME',
auth_broker: 'IDME'
})
allow_any_instance_of(MPI::Models::MviProfile).to receive(:gender).and_return(nil)
allow_any_instance_of(MPI::Models::MviProfile).to receive(:birth_date).and_return(nil)
VCR.use_cassette('mpi/find_candidate/missing_birthday_and_gender') do
VCR.use_cassette('va_profile/demographics/demographics') do
expect(subject).to validate(:get, '/v0/profile/personal_information', 502, headers)
end
end
end
end
describe 'when VA Profile returns an unexpected response body' do
it 'supports returning a custom 400 response' do
VCR.use_cassette('va_profile/military_personnel/post_read_service_history_500') do
expect(subject).to validate(:get, '/v0/profile/service_history', 400, headers)
end
end
end
describe 'search' do
before do
Flipper.disable(:search_use_v2_gsa)
end
context 'when successful' do
it 'supports getting search results data' do
VCR.use_cassette('search/success') do
expect(subject).to validate(:get, '/v0/search', 200, '_query_string' => 'query=benefits')
end
end
end
context 'with an empty search query' do
it 'returns a 400 with error details' do
VCR.use_cassette('search/empty_query') do
expect(subject).to validate(:get, '/v0/search', 400, '_query_string' => 'query=')
end
end
end
context 'when the Search.gov rate limit has been exceeded' do
it 'returns a 429 with error details' do
VCR.use_cassette('search/exceeds_rate_limit') do
expect(subject).to validate(:get, '/v0/search', 429, '_query_string' => 'query=benefits')
end
end
end
end
describe 'search click tracking' do
context 'when successful' do
# rubocop:disable Layout/LineLength
let(:params) { { 'position' => 0, 'query' => 'testQuery', 'url' => 'https%3A%2F%2Fwww.testurl.com', 'user_agent' => 'testUserAgent', 'module_code' => 'I14Y' } }
it 'sends data as query params' do
VCR.use_cassette('search_click_tracking/success') do
expect(subject).to validate(:post, '/v0/search_click_tracking/?position={position}&query={query}&url={url}&module_code={module_code}&user_agent={user_agent}', 204, params)
end
end
end
context 'with an empty search query' do
let(:params) { { 'position' => 0, 'query' => '', 'url' => 'https%3A%2F%2Fwww.testurl.com', 'user_agent' => 'testUserAgent', 'module_code' => 'I14Y' } }
it 'returns a 400 with error details' do
VCR.use_cassette('search_click_tracking/missing_parameter') do
expect(subject).to validate(:post, '/v0/search_click_tracking/?position={position}&query={query}&url={url}&module_code={module_code}&user_agent={user_agent}', 400, params)
end
# rubocop:enable Layout/LineLength
end
end
end
describe 'search typeahead' do
context 'when successful' do
it 'returns an array of suggestions' do
VCR.use_cassette('search_typeahead/success') do
expect(subject).to validate(:get, '/v0/search_typeahead', 200, '_query_string' => 'query=ebenefits')
end
end
end
context 'with an empty search query' do
it 'returns a 200 with empty results' do
VCR.use_cassette('search_typeahead/missing_query') do
expect(subject).to validate(:get, '/v0/search_typeahead', 200, '_query_string' => 'query=')
end
end
end
end
describe 'forms' do
context 'when successful' do
it 'supports getting form results data with a query' do
VCR.use_cassette('forms/200_form_query') do
expect(subject).to validate(:get, '/v0/forms', 200, '_query_string' => 'query=health')
end
end
it 'support getting form results without a query' do
VCR.use_cassette('forms/200_all_forms') do
expect(subject).to validate(:get, '/v0/forms', 200)
end
end
end
end
describe '1095-B' do
let(:user) { build(:user, :loa3, icn: '1012667145V762142') }
let(:headers) { { '_headers' => { 'Cookie' => sign_in(user, nil, true) } } }
let(:bad_headers) { { '_headers' => { 'Cookie' => sign_in(mhv_user, nil, true) } } }
before do
allow(Flipper).to receive(:enabled?).with(:fetch_1095b_from_enrollment_system, any_args).and_return(true)
Timecop.freeze(Time.zone.parse('2025-03-05T08:00:00Z'))
end
after { Timecop.return }
context 'available forms' do
it 'supports getting available forms' do
VCR.use_cassette('veteran_enrollment_system/enrollment_periods/get_success',
{ match_requests_on: %i[method uri] }) do
expect(subject).to validate(
:get,
'/v0/form1095_bs/available_forms',
200,
headers
)
end
end
it 'requires authorization' do
expect(subject).to validate(
:get,
'/v0/form1095_bs/available_forms',
401
)
end
end
end
describe 'contact us' do
before do
allow(Flipper).to receive(:enabled?).and_call_original
end
describe 'POST v0/contact_us/inquiries' do
let(:post_body) do
{
inquiry: {
form: JSON.generate(
{
personalInformation: {
first: 'Obi Wan',
last: 'Kenobi'
},
contactInformation: {
email: 'obi1kenobi@gmail.com',
address: {
country: 'USA'
},
phone: '1234567890'
},
topic: {
levelOne: 'Caregiver Support Program',
levelTwo: 'VA Supportive Services'
},
inquiryType: 'Question',
query: 'Can you help me?',
veteranStatus: {
veteranStatus: 'general'
},
preferredContactMethod: 'email'
}
)
}
}
end
it 'supports posting contact us form data' do
expect(Flipper).to receive(:enabled?).with(:get_help_ask_form).and_return(true)
expect(subject).to validate(
:post,
'/v0/contact_us/inquiries',
201,
headers.merge('_data' => post_body)
)
end
it 'supports validating posted contact us form data' do
expect(Flipper).to receive(:enabled?).with(:get_help_ask_form).and_return(true)
expect(subject).to validate(
:post,
'/v0/contact_us/inquiries',
422,
headers.merge(
'_data' => {
'inquiry' => {
'form' => {}.to_json
}
}
)
)
end
it 'supports 501 when feature is disabled' do
expect(Flipper).to receive(:enabled?).with(:get_help_ask_form).and_return(false)
expect(subject).to validate(
:post,
'/v0/contact_us/inquiries',
501,
headers.merge(
'_data' => {
'inquiry' => {
'form' => {}.to_json
}
}
)
)
end
end
describe 'GET v0/contact_us/inquiries' do
context 'logged in' do
let(:user) { build(:user, :loa3) }
let(:headers) do
{ '_headers' => { 'Cookie' => sign_in(user, nil, true) } }
end
it 'supports getting list of inquiries sent by user' do
expect(Flipper).to receive(:enabled?).with(:get_help_messages).and_return(true)
expect(subject).to validate(:get, '/v0/contact_us/inquiries', 200, headers)
end
end
context 'not logged in' do
it 'returns a 401' do
expect(subject).to validate(:get, '/v0/contact_us/inquiries', 401)
end
end
end
end
describe 'dependents applications' do
context 'default v2 form' do
let!(:user) { build(:user, ssn: '796043735') }
it 'supports getting dependent information' do
expect(subject).to validate(:get, '/v0/dependents_applications/show', 401)
VCR.use_cassette('bgs/claimant_web_service/dependents') do
expect(subject).to validate(:get, '/v0/dependents_applications/show', 200, headers)
end
end
it 'supports adding a dependency claim' do
allow_any_instance_of(SavedClaim::DependencyClaim).to receive(:submittable_686?).and_return(false)
allow_any_instance_of(SavedClaim::DependencyClaim).to receive(:submittable_674?).and_return(false)
allow_any_instance_of(BGS::PersonWebService).to receive(:find_by_ssn).and_return({ file_nbr: '796043735' })
VCR.use_cassette('bgs/dependent_service/submit_686c_form') do
expect(subject).to validate(
:post,
'/v0/dependents_applications',
200,
headers.merge(
'_data' => build(:dependency_claim).parsed_form
)
)
end
expect(subject).to validate(
:post,
'/v0/dependents_applications',
422,
headers.merge(
'_data' => {
'dependency_claim' => {
'invalid-form' => { invalid: true }.to_json
}
}
)
)
end
end
end
describe 'dependents verifications' do
it 'supports getting diary information' do
expect(subject).to validate(:get, '/v0/dependents_verifications', 401)
VCR.use_cassette('bgs/diaries/read') do
expect(subject).to validate(:get, '/v0/dependents_verifications', 200, headers)
end
end
it 'supports updating diaries' do
expect(subject).to validate(
:post,
'/v0/dependents_verifications',
200,
headers.merge(
'_data' => {
'dependency_verification_claim' => {
'form' => { 'update_diaries' => 'true' }
}
}
)
)
end
end
describe 'education career counseling claims' do
it 'supports adding a career counseling claim' do
expect(subject).to validate(
:post,
'/v0/education_career_counseling_claims',
200,
headers.merge(
'_data' => {
'education_career_counseling_claim' => {
form: build(:education_career_counseling_claim).form
}
}
)
)
expect(subject).to validate(
:post,
'/v0/education_career_counseling_claims',
422,
headers.merge(
'_data' => {
'education_career_counseling_claim' => {
'invalid-form' => { invalid: true }.to_json
}
}
)
)
end
end
describe 'veteran readiness employment claims' do
it 'supports adding veteran readiness employment claim' do
VCR.use_cassette('veteran_readiness_employment/send_to_vre') do
allow(ClaimsApi::VBMSUploader).to receive(:new) { OpenStruct.new(upload!: true) }
expect(subject).to validate(
:post,
'/v0/veteran_readiness_employment_claims',
200,
headers.merge(
'_data' => {
'veteran_readiness_employment_claim' => {
form: build(:veteran_readiness_employment_claim).form
}
}
)
)
end
end
it 'throws an error when adding veteran readiness employment claim' do
expect(subject).to validate(
:post,
'/v0/veteran_readiness_employment_claims',
422,
headers.merge(
'_data' => {
'veteran_readiness_employment_claim' => {
'invalid-form' => { invalid: true }.to_json
}
}
)
)
end
end
describe 'form 21-2680 house bound status' do
let(:saved_claim) { create(:form212680) }
before do
allow(Flipper).to receive(:enabled?).with(:form_2680_enabled, nil).and_return(true)
end
it 'supports submitting a form 21-2680' do
expect(subject).to validate(
:post,
'/v0/form212680',
200,
json_headers.merge('_data' => { form: VetsJsonSchema::EXAMPLES['21-2680'].to_json }.to_json)
)
end
it 'handles 400' do
expect(subject).to validate(
:post,
'/v0/form212680',
400,
json_headers.merge('_data' => { foo: :bar }.to_json)
)
end
it 'handles 422' do
expect(subject).to validate(
:post,
'/v0/form212680',
422,
json_headers.merge('_data' => { form: { foo: :bar }.to_json }.to_json)
)
end
it 'successfully downloads form212680 pdf', skip: 'swagger validation cannot handle binary PDF response' do
expect(subject).to validate(
:get,
'/v0/form212680/download_pdf/{guid}',
200,
'guid' => saved_claim.guid
)
end
it 'returns not found for bad guids' do
expect(subject).to validate(
:get,
'/v0/form212680/download_pdf/{guid}',
404,
'guid' => 'bad-guid'
)
end
context 'when feature toggle is disabled' do
before { allow(Flipper).to receive(:enabled?).with(:form_2680_enabled, nil).and_return(false) }
it 'handles 404 for create' do
expect(subject).to validate(
:post,
'/v0/form212680',
404,
json_headers.merge('_data' => { form: VetsJsonSchema::EXAMPLES['21-2680'].to_json }.to_json)
)
end
it 'handles 404 for download_pdf' do
expect(subject).to validate(
:get,
'/v0/form212680/download_pdf/{guid}',
404,
'guid' => saved_claim.guid
)
end
end
end
describe 'form 21-0779 nursing home information' do
let(:saved_claim) { create(:va210779) }
before do
allow(Flipper).to receive(:enabled?).with(:form_0779_enabled, nil).and_return(true)
end
it 'supports submitting a form 21-0779' do
expect(subject).to validate(
:post,
'/v0/form210779',
200,
json_headers.merge('_data' => { form: VetsJsonSchema::EXAMPLES['21-0779'].to_json }.to_json)
)
end
it 'handles 422' do
expect(subject).to validate(
:post,
'/v0/form210779',
422,
json_headers.merge('_data' => { form: { foo: :bar }.to_json }.to_json)
)
end
it 'handles 400' do
expect(subject).to validate(
:post,
'/v0/form210779',
400,
json_headers.merge('_data' => { foo: :bar }.to_json)
)
end
it 'successfully downloads form210779 pdf', skip: 'swagger validation cannot handle binary PDF response' do
expect(subject).to validate(
:get,
'/v0/form210779/download_pdf/{guid}',
200,
'guid' => saved_claim.guid
)
end
it 'handles 404' do
expect(subject).to validate(
:get,
'/v0/form210779/download_pdf/{guid}',
404,
'guid' => 'bad-id'
)
end
context 'when feature toggle is disabled' do
before { allow(Flipper).to receive(:enabled?).with(:form_0779_enabled, nil).and_return(false) }
it 'supports submitting a form 21-0779' do
expect(subject).to validate(
:post,
'/v0/form210779',
404,
json_headers.merge('_data' => { form: VetsJsonSchema::EXAMPLES['21-0779'].to_json }.to_json)
)
end
it 'handles 404' do
expect(subject).to validate(
:get,
'/v0/form210779/download_pdf/{guid}',
404,
'guid' => saved_claim.guid
)
end
end
end
describe 'va file number' do
it 'supports checking if a user has a veteran number' do
expect(subject).to validate(:get, '/v0/profile/valid_va_file_number', 401)
VCR.use_cassette('bgs/person_web_service/find_person_by_participant_id') do
expect(subject).to validate(:get, '/v0/profile/valid_va_file_number', 200, headers)
end
end
end
it "supports returning the vet's payment_history" do
expect(subject).to validate(:get, '/v0/profile/payment_history', 401)
VCR.use_cassette('bgs/payment_history/retrieve_payment_summary_with_bdn') do
expect(subject).to validate(:get, '/v0/profile/payment_history', 200, headers)
end
end
describe 'claim status tool' do
let!(:claim) do
create(:evss_claim, id: 1, evss_id: 189_625,
user_uuid: mhv_user.uuid, data: {})
end
it 'uploads a document to support a claim' do
expect(subject).to validate(
:post,
'/v0/evss_claims/{evss_claim_id}/documents',
202,
headers.merge('_data' => { file: fixture_file_upload('doctors-note.pdf', 'application/pdf'),
tracked_item_id: 33,
document_type: 'L023' }, 'evss_claim_id' => 189_625)
)
end
it 'rejects a malformed document' do
expect(subject).to validate(
:post,
'/v0/evss_claims/{evss_claim_id}/documents',
422,
headers.merge('_data' => { file: fixture_file_upload('malformed-pdf.pdf',
'application/pdf'),
tracked_item_id: 33,
document_type: 'L023' }, 'evss_claim_id' => 189_625)
)
end
end
describe 'claim letters' do
it 'retrieves a list of claim letters metadata' do
allow(Flipper).to receive(:enabled?)
.with(:cst_claim_letters_use_lighthouse_api_provider, anything)
.and_return(false)
# Response comes from fixture: spec/fixtures/claim_letter/claim_letter_list.json
expect(subject).to validate(:get, '/v0/claim_letters', 200, headers)
expect(subject).to validate(:get, '/v0/claim_letters', 401)
end
end
describe 'benefits claims' do
let(:user) { create(:user, :loa3, :accountable, :legacy_icn, uuid: 'b2fab2b5-6af0-45e1-a9e2-394347af91ef') }
let(:invalid_user) { create(:user, :loa3, :accountable, :legacy_icn, participant_id: nil) }
let(:user_account) { create(:user_account, id: user.uuid) }
let(:claim_id) { 600_383_363 }
let(:headers) { { '_headers' => { 'Cookie' => sign_in(user, nil, true) } } }
let(:invalid_headers) { { '_headers' => { 'Cookie' => sign_in(invalid_user, nil, true) } } }
describe 'GET /v0/benefits_claims/failed_upload_evidence_submissions' do
before do
user.user_account_uuid = user_account.id
user.save!
end
context 'when the user is not signed in' do
it 'returns a status of 401' do
expect(subject).to validate(:get, '/v0/benefits_claims/failed_upload_evidence_submissions', 401)
end
end
context 'when the user is signed in, but does not have valid credentials' do
it 'returns a status of 403' do
expect(subject).to validate(:get, '/v0/benefits_claims/failed_upload_evidence_submissions', 403,
invalid_headers)
end
end
context 'when the user is signed in and has valid credentials' do
before do
token = 'fake_access_token'
allow_any_instance_of(BenefitsClaims::Configuration).to receive(:access_token).and_return(token)
create(:bd_lh_evidence_submission_failed_type2_error, claim_id:, user_account:)
end
context 'when the ICN is not found' do
it 'returns a status of 404' do
VCR.use_cassette('lighthouse/benefits_claims/show/404_response') do
expect(subject).to validate(:get, '/v0/benefits_claims/failed_upload_evidence_submissions', 404,
headers)
end
end
end
context 'when there is a gateway timeout' do
it 'returns a status of 504' do
VCR.use_cassette('lighthouse/benefits_claims/show/504_response') do
expect(subject).to validate(:get, '/v0/benefits_claims/failed_upload_evidence_submissions', 504,
headers)
end
end
end
context 'when Lighthouse takes too long to respond' do
it 'returns a status of 504' do
allow_any_instance_of(BenefitsClaims::Configuration).to receive(:get).and_raise(Faraday::TimeoutError)
expect(subject).to validate(:get, '/v0/benefits_claims/failed_upload_evidence_submissions', 504, headers)
end
end
it 'returns a status of 200' do
VCR.use_cassette('lighthouse/benefits_claims/show/200_response') do
expect(subject).to validate(:get, '/v0/benefits_claims/failed_upload_evidence_submissions', 200, headers)
end
end
end
end
end
describe 'coe' do
# The vcr_cassettes used in spec/requests/v0/lgy_coe_request_spec.rb
# rely on this specific user's edipi and icn, and we are using those
# cassettes below.
let(:mhv_user) { create(:evss_user, :loa3, :legacy_icn, edipi: '1007697216') }
describe 'GET /v0/coe/status' do
it 'validates the route' do
VCR.use_cassette 'lgy/determination_eligible' do
VCR.use_cassette 'lgy/application_not_found' do
expect(subject).to validate(:get, '/v0/coe/status', 200, headers)
end
end
end
end
describe '/v0/coe/documents' do
it 'validates the route' do
allow_any_instance_of(User).to receive(:icn).and_return('123498767V234859')
allow_any_instance_of(User).to receive(:edipi).and_return('1007697216')
VCR.use_cassette 'lgy/documents_list' do
expect(subject).to validate(:get, '/v0/coe/documents', 200, headers)
end
end
end
describe '/v0/coe/submit_coe_claim' do
it 'validates the route' do
VCR.use_cassette 'lgy/application_put' do
# rubocop:disable Layout/LineLength
params = { lgy_coe_claim: { form: '{"files":[{"name":"Example.pdf","size":60217, "confirmationCode":"a7b6004e-9a61-4e94-b126-518ec9ec9ad0", "isEncrypted":false,"attachmentType":"Discharge or separation papers (DD214)"}],"relevantPriorLoans": [{"dateRange": {"from":"2002-05-01T00:00:00.000Z","to":"2003-01-01T00:00:00. 000Z"},"propertyAddress":{"propertyAddress1":"123 Faker St", "propertyAddress2":"2","propertyCity":"Fake City", "propertyState":"AL","propertyZip":"11111"}, "vaLoanNumber":"111222333444","propertyOwned":true,"intent":"ONETIMERESTORATION"}], "vaLoanIndicator":true,"periodsOfService": [{"serviceBranch":"Air National Guard","dateRange": {"from":"2001-01-01T00:00:00.000Z","to":"2002-02-02T00:00:00. 000Z"}}],"identity":"ADSM","contactPhone":"2222222222", "contactEmail":"veteran@example.com","applicantAddress": {"country":"USA","street":"140 FAKER ST","street2":"2", "city":"FAKE CITY","state":"MT","postalCode":"80129"}, "fullName":{"first":"Alexander","middle":"Guy", "last":"Cook","suffix":"Jr."},"dateOfBirth":"1950-01-01","privacyAgreementAccepted":true}' } }
# rubocop:enable Layout/LineLength
expect(subject).to validate(:post, '/v0/coe/submit_coe_claim', 200, headers.merge({ '_data' => params }))
end
end
end
describe '/v0/coe/document_upload' do
context 'successful upload' do
it 'validates the route' do
VCR.use_cassette 'lgy/document_upload' do
params = {
'files' => [{
'file' => Base64.encode64(File.read('spec/fixtures/files/lgy_file.pdf')),
'document_type' => 'VA home loan documents',
'file_type' => 'pdf',
'file_name' => 'lgy_file.pdf'
}]
}
expect(subject).to validate(:post, '/v0/coe/document_upload', 200, headers.merge({ '_data' => params }))
end
end
end
context 'failed upload' do
it 'validates the route' do
VCR.use_cassette 'lgy/document_upload_504' do
params = {
'files' => [{
'file' => Base64.encode64(File.read('spec/fixtures/files/lgy_file.pdf')),
'document_type' => 'VA home loan documents',
'file_type' => 'pdf',
'file_name' => 'lgy_file.pdf'
}]
}
expect(subject).to validate(:post, '/v0/coe/document_upload', 500, headers.merge({ '_data' => params }))
end
end
end
end
end
describe '/v0/profile/contacts' do
context 'unauthenticated user' do
it 'returns unauthorized status code' do
expect(subject).to validate(:get, '/v0/profile/contacts', 401)
end
end
context 'loa1 user' do
let(:mhv_user) { build(:user, :loa1) }
it 'returns forbidden status code' do
expect(subject).to validate(:get, '/v0/profile/contacts', 403, headers)
end
end
context 'loa3 user' do
let(:idme_uuid) { 'dd681e7d6dea41ad8b80f8d39284ef29' }
let(:mhv_user) { build(:user, :loa3, idme_uuid:) }
it 'returns ok status code' do
VCR.use_cassette('va_profile/profile/v3/health_benefit_bio_200') do
expect(subject).to validate(:get, '/v0/profile/contacts', 200, headers)
end
end
end
end
end
describe 'travel pay' do
context 'index' do
let(:mhv_user) { build(:user, :loa3) }
it 'returns unauthorized for unauthed user' do
expect(subject).to validate(:get, '/travel_pay/v0/claims', 401)
end
it 'returns 400 for invalid request' do
headers = { '_headers' => { 'Cookie' => sign_in(mhv_user, nil, true) } }
VCR.use_cassette('travel_pay/400_claims', match_requests_on: %i[host path method]) do
expect(subject).to validate(:get, '/travel_pay/v0/claims', 400, headers)
end
end
it 'returns 200 for successful response' do
headers = { '_headers' => { 'Cookie' => sign_in(mhv_user, nil, true) } }
VCR.use_cassette('travel_pay/200_search_claims_by_appt_date_range', match_requests_on: %i[host path method]) do
expect(subject).to validate(:get, '/travel_pay/v0/claims', 200, headers)
end
end
end
context 'show' do
let(:mhv_user) { build(:user, :loa3) }
it 'returns unauthorized for unauthed user' do
expect(subject).to validate(
:get,
'/travel_pay/v0/claims/{id}',
401,
{}.merge('id' => '24e227ea-917f-414f-b60d-48b7743ee95d')
)
end
# Returns 400 for now, but should be 404
it 'returns 400 for missing claim' do
headers = { '_headers' => { 'Cookie' => sign_in(mhv_user, nil, true) } }
VCR.use_cassette('travel_pay/404_claim_details', match_requests_on: %i[path method]) do
expect(subject).to validate(
:get,
'/travel_pay/v0/claims/{id}',
400,
headers.merge('id' => 'aa0f63e0-5fa7-4d74-a17a-a6f510dbf69e')
)
end
end
it 'returns 400 for invalid request' do
headers = { '_headers' => { 'Cookie' => sign_in(mhv_user, nil, true) } }
VCR.use_cassette('travel_pay/show/success_details', match_requests_on: %i[path method]) do
expect(subject).to validate(
:get,
'/travel_pay/v0/claims/{id}',
400,
headers.merge('id' => '8656')
)
end
end
it 'returns 200 for successful response' do
headers = { '_headers' => { 'Cookie' => sign_in(mhv_user, nil, true) } }
claim_id = '3fa85f64-5717-4562-b3fc-2c963f66afa6'
VCR.use_cassette('travel_pay/show/success_details', match_requests_on: %i[path method]) do
expect(subject).to validate(
:get,
'/travel_pay/v0/claims/{id}',
200,
headers.merge('id' => claim_id)
)
end
end
end
context 'create' do
let(:mhv_user) { build(:user, :loa3, :with_terms_of_use_agreement) }
before do
allow(Flipper).to receive(:enabled?).with(:travel_pay_appt_add_v4_upgrade, instance_of(User)).and_return(false)
end
it 'returns unauthorized for unauthorized user' do
expect(subject).to validate(:post, '/travel_pay/v0/claims', 401)
end
it 'returns bad request for missing appointment date time' do
headers = { '_headers' => { 'Cookie' => sign_in(mhv_user, nil, true) } }
VCR.use_cassette('travel_pay/submit/success', match_requests_on: %i[path method]) do
expect(subject).to validate(
:post,
'/travel_pay/v0/claims',
400,
headers
)
end
end
it 'returns 201 for successful response' do
headers = { '_headers' => { 'Cookie' => sign_in(mhv_user, nil, true) } }
params = {
'_data' => {
'appointment_date_time' => '2024-01-01T16:45:34.465Z',
'facility_station_number' => '123',
'appointment_type' => 'Other',
'is_complete' => false
}
}
VCR.use_cassette('travel_pay/submit/success', match_requests_on: %i[path method]) do
expect(subject).to validate(
:post,
'/travel_pay/v0/claims',
201,
headers.merge(params)
)
end
end
end
context 'documents' do
# doc summaries included in claim details
context 'show' do
it 'returns unauthorized for unauthed user' do
expect(subject).to validate(
:get,
'/travel_pay/v0/claims/{claimId}/documents/{docId}',
401,
{
'claimId' => 'claim-123',
'docId' => 'doc-456'
}
)
end
end
end
end
describe 'banners' do
describe 'GET /v0/banners' do
it 'requires path parameter' do
expect(subject).to validate(:get, '/v0/banners', 422, '_query_string' => 'type=full_width_banner_alert')
end
context 'when the service successfully returns banners' do
it 'supports getting banners without type parameter' do
VCR.use_cassette('banners/get_banners_success') do
expect(subject).to validate(:get, '/v0/banners', 200, '_query_string' => 'path=/some-va-path')
end
end
it 'supports getting banners with path and type parameters' do
VCR.use_cassette('banners/get_banners_with_type_success') do
expect(subject).to validate(
:get,
'/v0/banners',
200,
'_query_string' => 'path=full-va-path&type=full_width_banner_alert'
)
end
end
end
end
end
describe 'submission statuses' do
context 'loa3 user' do
let(:user) { build(:user, :loa3, :with_terms_of_use_agreement) }
let(:headers) { { '_headers' => { 'Cookie' => sign_in(user, nil, true) } } }
before do
create(:form_submission, :with_form214142, user_account_id: user.user_account_uuid)
create(:form_submission, :with_form210845, user_account_id: user.user_account_uuid)
create(:form_submission, :with_form_blocked, user_account_id: user.user_account_uuid)
end
it 'submission statuses 200' do
VCR.use_cassette('forms/submission_statuses/200_valid') do
expect(subject).to validate(:get, '/v0/my_va/submission_statuses', 200, headers)
end
end
it 'submission statuses 296' do
VCR.use_cassette('forms/submission_statuses/413_invalid') do
expect(subject).to validate(:get, '/v0/my_va/submission_statuses', 296, headers)
end
end
end
end
describe 'vet verification status' do
let(:user) { create(:user, :loa3, icn: '1012667145V762142') }
let(:headers) { { '_headers' => { 'Cookie' => sign_in(user, nil, true) } } }
before do
allow_any_instance_of(VeteranVerification::Configuration).to receive(:access_token).and_return('blahblech')
end
context 'unauthenticated user' do
it 'returns unauthorized status code' do
VCR.use_cassette('lighthouse/veteran_verification/status/401_response') do
expect(subject).to validate(:get, '/v0/profile/vet_verification_status', 401)
end
end
end
context 'loa3 user' do
it 'returns ok status code' do
VCR.use_cassette('lighthouse/veteran_verification/status/200_show_response') do
expect(subject).to validate(:get, '/v0/profile/vet_verification_status', 200, headers)
end
end
end
end
describe 'DatadogAction endpoint' do
it 'records a front-end metric and returns 204 No Content' do
body = {
'metric' => DatadogMetrics::ALLOWLIST.first, # e.g. 'labs_and_tests_list'
'tags' => []
}
expect(subject).to validate(
:post,
'/v0/datadog_action',
204,
'_data' => body
)
end
end
context 'and' do
before do
allow(HealthCareApplication).to receive(:user_icn).and_return('123')
end
it 'tests all documented routes' do
# exclude these route as they return binaries
subject.untested_mappings.delete('/v0/letters/{id}')
subject.untested_mappings.delete('/debts_api/v0/financial_status_reports/download_pdf')
subject.untested_mappings.delete('/v0/form1095_bs/download_pdf/{tax_year}')
subject.untested_mappings.delete('/v0/form1095_bs/download_txt/{tax_year}')
subject.untested_mappings.delete('/v0/claim_letters/{document_id}')
subject.untested_mappings.delete('/v0/coe/download_coe')
subject.untested_mappings.delete('/v0/coe/document_download/{id}')
subject.untested_mappings.delete('/v0/caregivers_assistance_claims/download_pdf')
subject.untested_mappings.delete('/v0/health_care_applications/download_pdf')
subject.untested_mappings['/v0/form210779/download_pdf/{guid}']['get'].delete('200')
subject.untested_mappings['/v0/form212680/download_pdf/{guid}']['get'].delete('200')
subject.untested_mappings.delete('/v0/form0969')
subject.untested_mappings.delete('/travel_pay/v0/claims/{claimId}/documents/{docId}')
# SiS methods that involve forms & redirects
subject.untested_mappings.delete('/v0/sign_in/authorize')
subject.untested_mappings.delete('/v0/sign_in/callback')
subject.untested_mappings.delete('/v0/sign_in/logout')
expect(subject).to validate_all_paths
end
end
end
RSpec.describe 'the v1 API documentation', order: :defined, type: %i[apivore request] do
include AuthenticatedSessionHelper
subject { Apivore::SwaggerChecker.instance_for('/v1/apidocs.json') }
let(:mhv_user) { build(:user, :mhv, middle_name: 'Bob', icn: '1012667145V762142') }
context 'has valid paths' do
let(:headers) { { '_headers' => { 'Cookie' => sign_in(mhv_user, nil, true) } } }
context 'GI Bill Status' do
it 'supports getting Gi Bill Status' do
expect(subject).to validate(:get, '/v1/post911_gi_bill_status', 401)
VCR.use_cassette('lighthouse/benefits_education/200_response') do
expect(subject).to validate(:get, '/v1/post911_gi_bill_status', 200, headers)
end
Timecop.return
end
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/requests/breakers_integration_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'Breakers Integration', type: :request do
before do
breakers_configuration = Class.new(Common::Client::Configuration::REST) do
def base_path
'http://example.com'
end
def service_name
'breakers'
end
def breakers_error_threshold
80
end
def connection
Faraday.new(base_path) do |faraday|
faraday.use(:breakers, service_name:)
faraday.response :raise_custom_error, error_prefix: service_name
end
end
end
stub_const('BreakersConfiguration', breakers_configuration)
breakers_client = Class.new(Common::Client::Base) do
configuration BreakersConfiguration
def client_route
perform(:get, '/some-route', nil)
end
Breakers.client.services << BreakersConfiguration.instance.breakers_service
end
stub_const('BreakersClient', breakers_client)
breakers_controller = Class.new(ApplicationController) do
skip_before_action :authenticate
def breakers_test
BreakersClient.new.client_route
head :ok
end
end
stub_const('BreakersController', breakers_controller)
Rails.application.routes.draw do
get '/breakers_test' => 'breakers#breakers_test'
end
end
after do
Rails.application.reload_routes!
Breakers.client.services.delete(BreakersConfiguration.instance.breakers_service)
end
context 'integration test for breakers' do
it 'raises a breakers exception failure rate' do
now = Time.current
start_time = now - 120
Timecop.freeze(start_time)
stub_request(:get, 'http://example.com/some-route').to_return(status: 200)
20.times do
response = get '/breakers_test'
expect(response).to eq(200)
end
stub_request(:get, 'http://example.com/some-route').to_return(status: 500)
80.times do
response = get '/breakers_test'
expect(response).to eq(500)
end
expect do
get '/breakers_test'
end.to trigger_statsd_increment('api.external_http_request.breakers.skipped', times: 1, value: 1)
response = get '/breakers_test'
expect(response).to eq(503)
Timecop.freeze(now)
stub_request(:get, 'http://example.com/some-route').to_return(status: 200)
response = get '/breakers_test'
expect(response).to eq(200)
Timecop.return
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/requests/root_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'root', type: :request do
it 'Provides a welcome message at root' do
get '/'
assert_response :success
end
it 'Provides a welcome message at root even with unsafe host' do
host! 'unsafe.com'
get '/'
assert_response :success
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/requests/http_method_not_allowed_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
class MockRackApp
def initialize
@request_headers = {}
end
def call(_env)
[200, { 'Content-Type' => 'text/plain' }, ['OK']]
end
end
RSpec.describe HttpMethodNotAllowed, type: :request do
subject { described_class.new(app) }
let(:app) { MockRackApp.new }
let(:r) { Rack::MockRequest.new(subject) }
it 'responds with 200 for allowed method' do
get '/'
expect(response).to have_http_status(:ok)
end
it 'responds with 405 with unsupported method' do
response = r.request(:foo, '/')
expect(response.status).to equal(405)
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/requests/filter_parameter_logging_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'stringio'
RSpec.describe 'Filter Parameter Logging', type: :request do
let(:logger) { SemanticLogger::Test::CaptureLogEvents.new }
before do
Rails.application.routes.draw do
post '/test_params', to: 'test_params#create'
end
allow(TestParamsController).to receive(:logger).and_return(logger)
end
after do
Rails.application.reload_routes!
end
it 'filters uploaded file parameters but logs HTTP upload object' do
file = fixture_file_upload(
Rails.root.join('spec', 'fixtures', 'files', 'test_file_with_pii.txt'), 'text/plain'
)
post '/test_params', params: { attachment: file }
logs = logger.events.to_json
puts "DEBUG LOG OUTPUT TEST 1: #{logs}"
expect(logs).to include('"attachment"')
expect(logs).not_to include('test_file_with_pii.txt')
expect(logs).not_to include('John Doe')
expect(logs).not_to include('123-45-6789')
expect(logs).not_to include('johndoe@example.com')
expect(logs).to include('"original_filename":"[FILTERED!]"')
expect(logs).to include('"headers":"[FILTERED!]"')
end
it 'filters file parameters when represented as a hash' do
file_params = {
'content_type' => 'application/pdf',
'file' => 'sensitive binary content',
'original_filename' => 'private_file.docx',
'headers' => 'Content-Disposition: form-data; name="attachment"; filename="private_file.docx"',
# NOTE: tempfile and content_type are explicitly allowed to pass unfiltered:
'tempfile' => '#<Tempfile:/tmp/RackMultipart20241231-96-nixrw6.pdf (closed)>',
'metadata' => { 'extra' => 'should_be_filtered' } # Nested hash
}
post '/test_params', params: { attachment: file_params }
logs = logger.events.to_json
puts "DEBUG LOG OUTPUT TEST 2: #{logs}"
expect(logs).not_to include('private_file.docx')
expect(logs).not_to include('sensitive binary content')
expect(logs).to include('"file":"[FILTERED]"')
expect(logs).to include('"original_filename":"[FILTERED]"')
expect(logs).to include('"headers":"[FILTERED]"')
expect(logs).to include('"metadata":{"extra":"[FILTERED]"}')
expect(logs).to include('"attachment"')
end
it 'filters SSN from logs' do
sensitive_params = {
name: 'John Doe',
ssn: '123-45-6789',
email: 'johndoe@example.com'
}
post '/test_params', params: sensitive_params
logs = logger.events.to_json
puts "DEBUG LOG OUTPUT 3: #{logs}" # Debugging output
expect(logs).not_to include('123-45-6789') # SSN should be wiped out
expect(logs).not_to include('johndoe@example.com') # Ensure emails are also wiped
expect(logs).to include('"ssn":"[FILTERED]"') # Confirm it's being replaced
end
end
class TestParamsController < ActionController::API
def create
render json: { status: 'ok' }, status: :ok
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/requests/csrf_request_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'CSRF scenarios' do
# ActionController::Base.allow_forgery_protection = false in the 'test' environment
# We explicitly enable it for this spec
before do
allow(Settings.sentry).to receive(:dsn).and_return('truthy')
@original_val = ActionController::Base.allow_forgery_protection
allow(ActionController::Base).to receive(:allow_forgery_protection).and_return(true)
# innocuous route chosen for setting the CSRF token in the response header
get(v0_maintenance_windows_path)
@token = response.headers['X-CSRF-Token']
end
describe 'CSRF protection' do
before do
Rails.application.routes.draw do
namespace :v0, defaults: { format: 'json' } do
resources :maintenance_windows, only: [:index]
end
match 'csrf_test', to: 'v0/example#index', via: :all
end
end
after(:all) do
Rails.application.reload_routes!
end
%i[post put patch delete].each do |verb|
context "for #{verb.upcase} requests" do
context 'without a CSRF token present' do
it 'raises an exception' do
send(verb, '/csrf_test')
expect(response).to have_http_status :forbidden
expect(response.body).to match(/Invalid Authenticity Token/)
end
end
context 'with a CSRF token present' do
it 'succeeds' do
send(verb, '/csrf_test', headers: { 'X-CSRF-Token' => @token })
expect(response).to have_http_status :ok
end
end
end
end
context 'for GET requests' do
context 'without a CSRF token present' do
it 'succeeds' do
get '/csrf_test'
expect(response).to have_http_status :ok
end
end
context 'with a CSRF token present' do
it 'succeeds' do
get '/csrf_test', headers: { 'X-CSRF-Token' => @token }
expect(response).to have_http_status :ok
end
end
end
end
# SAML callback
describe 'POST SAML callback' do
context 'without a CSRF token' do
it 'does not raise an error' do
post(v1_sessions_callback_path)
expect(response.body).not_to match(/Invalid Authenticity Token/)
end
end
end
describe 'unknown route' do
it 'skips CSRF validation' do
post '/non_existent_route'
expect(response).to have_http_status(:not_found)
expect(response.body).to match(/There are no routes matching your request/)
end
end
end
|
0
|
code_files/vets-api-private/spec
|
code_files/vets-api-private/spec/requests/statsd_middleware_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'statsd_middleware'
RSpec.describe StatsdMiddleware, type: :request do
before do
statsd_controller = Class.new(ApplicationController) do
skip_before_action :authenticate
def statsd_test
head :ok
end
end
stub_const('StatsdController', statsd_controller)
Rails.application.routes.draw do
get '/statsd_test' => 'statsd#statsd_test'
match '*path', to: 'application#routing_error', via: %i[get post put patch delete]
end
Timecop.freeze
end
after do
Rails.application.reload_routes!
Timecop.return
end
it 'sends status data to statsd' do
tags = %w[controller:statsd action:statsd_test source_app:not_provided status:200]
expect do
get '/statsd_test'
end.to trigger_statsd_increment(StatsdMiddleware::STATUS_KEY, tags:, times: 1, value: 1)
end
it 'sends duration data to statsd' do
tags = %w[controller:statsd action:statsd_test source_app:not_provided]
expect do
get '/statsd_test'
end.to trigger_statsd_measure(StatsdMiddleware::DURATION_KEY, tags:, times: 1, value: 0.0)
end
it 'sends duration distribution data to statsd' do
tags = %w[controller:statsd action:statsd_test source_app:not_provided]
expect(StatsD).to receive(:distribution)
.with(StatsdMiddleware::DURATION_DISTRIBUTION_KEY, 0.0, tags:)
get '/statsd_test'
end
it 'sends db_runtime data to statsd' do
tags = %w[controller:statsd action:statsd_test status:200]
expect do
get '/statsd_test'
end.to trigger_statsd_measure('api.request.db_runtime', tags:, times: 1, value: be_between(0, 100))
end
it 'sends view_runtime data to statsd' do
tags = %w[controller:statsd action:statsd_test status:200]
expect do
get '/statsd_test'
end.to trigger_statsd_measure('api.request.view_runtime', tags:, times: 1, value: be_between(0, 100))
end
it 'handles a missing route correctly' do
tags = %w[controller:application action:routing_error source_app:not_provided status:404]
expect do
get '/v0/blahblah'
end.to trigger_statsd_increment(StatsdMiddleware::STATUS_KEY, tags:, times: 1, value: 1)
end
it 'provides duration for missing routes' do
tags = %w[controller:application action:routing_error source_app:not_provided]
expect do
get '/v0/blahblah'
end.to trigger_statsd_measure(StatsdMiddleware::DURATION_KEY, tags:, times: 1, value: 0.0)
end
it 'provides duration distribution for missing routes' do
tags = %w[controller:application action:routing_error source_app:not_provided]
expect(StatsD).to receive(:distribution)
.with(StatsdMiddleware::DURATION_DISTRIBUTION_KEY, 0.0, tags:)
get '/v0/blahblah'
end
it 'sends source_app to statsd' do
tags = %w[controller:statsd action:statsd_test source_app:profile status:200]
expect do
get '/statsd_test', headers: { 'Source-App-Name' => 'profile' }
end.to trigger_statsd_increment(StatsdMiddleware::STATUS_KEY, tags:, times: 1)
end
it 'sends undefined to statsd when source_app is undefined' do
tags = %w[controller:statsd action:statsd_test source_app:undefined status:200]
expect do
get '/statsd_test', headers: { 'Source-App-Name' => 'undefined' }
end.to trigger_statsd_increment(StatsdMiddleware::STATUS_KEY, tags:, times: 1)
end
it 'uses not_in_allowlist for source_app when the value is not in allow list' do
tags = %w[controller:statsd action:statsd_test source_app:not_in_allowlist status:200]
expect do
get '/statsd_test', headers: { 'Source-App-Name' => 'foo' }
end.to trigger_statsd_increment(StatsdMiddleware::STATUS_KEY, tags:, times: 1)
end
it 'logs a warning for unrecognized source_app_name headers' do
expect(Rails.logger).to receive(:warn).once.with(
'Unrecognized value for HTTP_SOURCE_APP_NAME request header... [foo]'
)
get '/statsd_test', headers: { 'Source-App-Name' => 'foo' }
end
it 'emits distribution metric with the same tags as the measure metric' do
expected_tags = %w[controller:statsd action:statsd_test source_app:not_provided]
tags_from_measure = nil
tags_from_distribution = nil
allow(StatsD).to receive(:measure).and_wrap_original do |m, *args, **kwargs|
tags_from_measure = kwargs[:tags]
m.call(*args, **kwargs)
end
allow(StatsD).to receive(:distribution).and_wrap_original do |m, *args, **kwargs|
tags_from_distribution = kwargs[:tags]
m.call(*args, **kwargs)
end
get '/statsd_test'
expect(StatsD).to have_received(:measure)
.with(StatsdMiddleware::DURATION_KEY, kind_of(Numeric), tags: expected_tags)
expect(StatsD).to have_received(:distribution)
.with(StatsdMiddleware::DURATION_DISTRIBUTION_KEY, kind_of(Numeric), tags: expected_tags)
expect(tags_from_distribution).to match_array(tags_from_measure)
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v1/medical_copays_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V1::MedicalCopays', type: :request do
let(:current_user) { build(:user, :loa3, icn: 123) }
before do
sign_in_as(current_user)
end
describe 'index', skip: 'temporarily skipped' do
it 'returns a formatted hash response' do
VCR.use_cassette('lighthouse/hcc/invoice_list_success') do
allow(Auth::ClientCredentials::JWTGenerator).to receive(:generate_token).and_return('fake-jwt')
get '/v1/medical_copays'
response_body = JSON.parse(response.body)
meta = response_body['meta']
copay_summary = meta['copay_summary']
data_element = response_body['data'].first
expect(copay_summary.keys).to eq(%w[total_current_balance copay_bill_count last_updated_on])
expect(meta.keys).to eq(%w[total page per_page copay_summary])
expect(data_element['attributes'].keys).to match_array(
%w[
url
facility
externalId
latestBillingRef
currentBalance
previousBalance
previousUnpaidBalance
]
)
end
end
it 'handles auth error' do
VCR.use_cassette('lighthouse/hcc/auth_error') do
allow(Auth::ClientCredentials::JWTGenerator).to receive(:generate_token).and_return('fake-jwt')
get '/v1/medical_copays'
response_body = JSON.parse(response.body)
errors = response_body['errors']
expect(errors.first.keys).to eq(%w[error error_description status code title detail])
end
end
it 'handles no records returned' do
VCR.use_cassette('lighthouse/hcc/no_records') do
allow(Auth::ClientCredentials::JWTGenerator).to receive(:generate_token).and_return('fake-jwt')
get '/v1/medical_copays'
response_body = JSON.parse(response.body)
expect(response_body['data']).to eq([])
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v1/post911_gi_bill_status_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V1::Post911GIBillStatus', type: :request do
include SchemaMatchers
let(:user) { create(:user, icn: '1012667145V762142') }
before do
sign_in_as(user)
allow(Settings.evss).to receive(:mock_gi_bill_status).and_return(false)
end
context 'with a 200 response' do
it 'GET /v1/post911_gi_bill_status returns proper json' do
VCR.use_cassette('lighthouse/benefits_education/gi_bill_status/200_response') do
get v1_post911_gi_bill_status_url, params: nil
expect(response).to match_response_schema('post911_gi_bill_status')
assert_response :success
end
end
end
context 'with deprecated GibsNotFoundUser class' do
it 'loads the class for coverage', skip: 'No expectation in this example' do
GibsNotFoundUser
end
end
end
|
0
|
code_files/vets-api-private/spec/requests/v1
|
code_files/vets-api-private/spec/requests/v1/gi/version_public_exports_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V1::GI::VersionPublicExportsController', type: :request do
describe 'GET v1/gi/public_exports' do
let(:service) { GI::LCPE::Client.new(v_client:, lcpe_type:) }
context 'when export exists' do
it 'bypasses versioning and returns lacs with 200 response' do
VCR.use_cassette('gi/public_export_found') do
get v1_gi_version_public_export_url(id: 'latest')
expect(response).to have_http_status(:ok)
expect(response.headers['Content-Type']).to eq('application/x-gzip')
expect(response.headers['Content-Disposition']).to match(/attachment/)
end
end
end
context 'when export does not exist' do
it 'passes through the response' do
VCR.use_cassette('gi/public_export_missing') do
get v1_gi_version_public_export_url(id: '1234')
expect(response).to have_http_status(:not_found)
expect(response.headers['Content-Type']).to match(%r{application/json})
expect(JSON.parse(response.body)).to have_key('errors')
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests/v1/gi
|
code_files/vets-api-private/spec/requests/v1/gi/lcpe/lacs_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'gi/lcpe/client'
require 'gi/lcpe/response'
RSpec.describe 'V1::GI::LCPE::Lacs', type: :request do
include SchemaMatchers
let(:v_fresh) { '3' }
let(:v_stale) { '2' }
let(:enriched_id) { "1v#{v_client}" }
describe 'GET v1/gi/lcpe/lacs' do
let(:lcpe_type) { 'lacs' }
let(:lcpe_cache) { LCPERedis.new(lcpe_type:) }
let(:service) { GI::LCPE::Client.new(v_client:, lcpe_type:) }
context 'when filter params present' do
it 'bypasses versioning and returns lacs with 200 response' do
VCR.use_cassette('gi/lcpe/get_lacs_versioning_disabled') do
get v1_gi_lcpe_lacs_url, params: { state: 'MT' }
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('gi/lcpe/lacs')
expect(response.headers['Etag']).not_to match(%r{W/"\d+"})
end
end
end
context 'when versioning enabled' do
context 'when client nil and cache nil' do
it 'returns 200 response with fresh version' do
VCR.use_cassette('gi/lcpe/get_lacs_cache_nil') do
get v1_gi_lcpe_lacs_url
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('gi/lcpe/lacs_with_version')
expect(response.headers['Etag']).to eq("W/\"#{v_fresh}\"")
end
end
end
context 'when client stale and cache stale' do
let(:v_client) { v_stale }
before do
# generate stale cache
VCR.use_cassette('gi/lcpe/get_lacs_cache_nil') do
service.get_licenses_and_certs_v1({})
body = lcpe_cache.cached_response.body.merge(version: v_stale)
lcpe_cache.cache(lcpe_type, GI::LCPE::Response.new(status: 200, body:))
end
end
it 'returns 200 response with fresh version' do
VCR.use_cassette('gi/lcpe/get_lacs_cache_stale') do
get v1_gi_lcpe_lacs_url, headers: { 'If-None-Match' => "W/\"#{v_client}\"" }
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('gi/lcpe/lacs_with_version')
expect(response.headers['Etag']).to eq("W/\"#{v_fresh}\"")
end
end
end
context 'when client stale and cache fresh' do
let(:v_client) { v_stale }
before do
# generate fresh cache
VCR.use_cassette('gi/lcpe/get_lacs_cache_nil') do
service.get_licenses_and_certs_v1({})
end
end
it 'returns 200 response with fresh version' do
VCR.use_cassette('gi/lcpe/get_lacs_cache_fresh') do
get v1_gi_lcpe_lacs_url, headers: { 'If-None-Match' => "W/'#{v_client}'" }
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('gi/lcpe/lacs_with_version')
expect(response.headers['Etag']).to eq("W/\"#{v_fresh}\"")
end
end
end
context 'when client fresh and cache fresh' do
let(:v_client) { v_fresh }
before do
# generate fresh cache
VCR.use_cassette('gi/lcpe/get_lacs_cache_nil') do
service.get_licenses_and_certs_v1({})
end
end
it 'returns 304 response with fresh version' do
VCR.use_cassette('gi/lcpe/get_lacs_cache_fresh') do
get v1_gi_lcpe_lacs_url, headers: { 'If-None-Match' => "W/\"#{v_client}\"" }
expect(response).to have_http_status(:not_modified)
expect(response.headers['Etag']).to eq("W/\"#{v_client}\"")
end
end
end
end
end
describe 'GET v1/gi/lcpe/lacs/:id' do
context 'when client requests details with stale cache' do
let(:v_client) { v_stale }
it 'returns 409 conflict' do
VCR.use_cassette('gi/lcpe/get_lacs_cache_stale') do
get "#{v1_gi_lcpe_lacs_url}/#{enriched_id}"
expect(response).to have_http_status(:conflict)
end
end
end
context 'when client requests details with fresh cache' do
let(:v_client) { v_fresh }
it 'returns 200 response with lac details' do
VCR.use_cassette('gi/lcpe/get_lacs_cache_fresh') do
VCR.use_cassette('gi/lcpe/get_lac_details') do
get "#{v1_gi_lcpe_lacs_url}/#{enriched_id}"
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('gi/lcpe/lac')
end
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests/v1/gi
|
code_files/vets-api-private/spec/requests/v1/gi/lcpe/exams_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'gi/lcpe/client'
require 'gi/lcpe/response'
RSpec.describe 'V1::GI::LCPE::Exams', type: :request do
include SchemaMatchers
let(:v_fresh) { '3' }
let(:v_stale) { '2' }
let(:enriched_id) { "1v#{v_client}" }
describe 'GET v1/gi/lcpe/exams' do
let(:lcpe_type) { 'exams' }
let(:lcpe_cache) { LCPERedis.new(lcpe_type:) }
let(:service) { GI::LCPE::Client.new(v_client:, lcpe_type:) }
context 'when filter params present' do
it 'bypasses versioning and returns lacs with 200 response' do
VCR.use_cassette('gi/lcpe/get_exams_versioning_disabled') do
get v1_gi_lcpe_exams_url, params: { state: 'MT' }
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('gi/lcpe/exams')
expect(response.headers['Etag']).not_to match(%r{W/"\d+"})
end
end
end
context 'when versioning enabled' do
context 'when client nil and cache nil' do
it 'returns 200 response with fresh version' do
VCR.use_cassette('gi/lcpe/get_exams_cache_nil') do
get v1_gi_lcpe_exams_url
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('gi/lcpe/exams_with_version')
expect(response.headers['Etag']).to eq("W/\"#{v_fresh}\"")
end
end
end
context 'when client stale and cache stale' do
let(:v_client) { v_stale }
before do
# generate stale cache
VCR.use_cassette('gi/lcpe/get_exams_cache_nil') do
service.get_exams_v1({})
body = lcpe_cache.cached_response.body.merge(version: v_stale)
lcpe_cache.cache(lcpe_type, GI::LCPE::Response.new(status: 200, body:))
end
end
it 'returns 200 response with fresh version' do
VCR.use_cassette('gi/lcpe/get_exams_cache_stale') do
get v1_gi_lcpe_exams_url, headers: { 'If-None-Match' => "W/\"#{v_client}\"" }
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('gi/lcpe/exams_with_version')
expect(response.headers['Etag']).to eq("W/\"#{v_fresh}\"")
end
end
end
context 'when client stale and cache fresh' do
let(:v_client) { v_stale }
before do
# generate fresh cache
VCR.use_cassette('gi/lcpe/get_exams_cache_nil') do
service.get_exams_v1({})
end
end
it 'returns 200 response with fresh version' do
VCR.use_cassette('gi/lcpe/get_exams_cache_fresh') do
get v1_gi_lcpe_exams_url, headers: { 'If-None-Match' => "W/\"#{v_client}\"" }
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('gi/lcpe/exams_with_version')
expect(response.headers['Etag']).to eq("W/\"#{v_fresh}\"")
end
end
end
context 'when client fresh and cache fresh' do
let(:v_client) { v_fresh }
before do
# generate fresh cache
VCR.use_cassette('gi/lcpe/get_exams_cache_nil') do
service.get_exams_v1({})
end
end
it 'returns 304 response with fresh version' do
VCR.use_cassette('gi/lcpe/get_exams_cache_fresh') do
get v1_gi_lcpe_exams_url, headers: { 'If-None-Match' => "W/\"#{v_client}\"" }
expect(response).to have_http_status(:not_modified)
expect(response.headers['Etag']).to eq("W/\"#{v_client}\"")
end
end
end
end
end
describe 'GET v1/gi/lcpe/exams/:id' do
context 'when client requests details with stale cache' do
let(:v_client) { v_stale }
it 'returns 409 conflict' do
VCR.use_cassette('gi/lcpe/get_exams_cache_stale') do
get "#{v1_gi_lcpe_exams_url}/#{enriched_id}"
expect(response).to have_http_status(:conflict)
end
end
end
context 'when client requests details with fresh cache' do
let(:v_client) { v_fresh }
it 'returns 200 response with lac details' do
VCR.use_cassette('gi/lcpe/get_exams_cache_fresh') do
VCR.use_cassette('gi/lcpe/get_exam_details') do
get "#{v1_gi_lcpe_exams_url}/#{enriched_id}"
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('gi/lcpe/exam')
end
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests/v1
|
code_files/vets-api-private/spec/requests/v1/apidoc/apidoc_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
Dir.glob(File.expand_path('shared_examples/*.rb', __dir__)).each(&method(:require))
RSpec.describe 'API V1 doc validations', type: :request do
context 'json validation' do
it 'has valid json' do
get '/v1/apidocs.json'
json = response.body
JSON.parse(json).to_yaml
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/search_click_tracking_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'support/error_details'
require 'uri'
Rspec.describe 'V0::SearchClickTracking', type: :request do
include ErrorDetails
describe 'POST /v0/search_click_tracking' do
context 'on a successfull post request' do
let(:query_params) do
URI.encode_www_form(
{
position: 0,
query: 'testQuery',
url: 'https://www.testurl.com',
user_agent: 'testUserAgent',
module_code: 'I14Y'
}
)
end
it 'returns a response of 204 No Content', :aggregate_failures do
VCR.use_cassette('search_click_tracking/success') do
post "/v0/search_click_tracking/?#{query_params}"
expect(response).to have_http_status(:no_content)
expect(response.body).to eq ''
end
end
end
context 'with a missing parameter' do
let(:query_params) do
URI.encode_www_form(
{
position: 0,
query: '',
url: 'https://www.testurl.com',
user_agent: 'testUserAgent',
module_code: 'I14Y'
}
)
end
it 'returns a 400', :aggregate_failures do
VCR.use_cassette('search_click_tracking/missing_parameter') do
post "/v0/search_click_tracking/?#{query_params}"
expect(response).to have_http_status(:bad_request)
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/mvi_users_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'support/controller_spec_helper'
RSpec.describe 'V0::MVIUsers', type: :request do
describe 'POST #submit' do
let(:user) { build(:user_with_no_ids) }
before do
sign_in_as(user)
end
# sad path, wrong form id
it 'with invalid form id parameter, return 403' do
invalid_form_id = '21-686C'
post "/v0/mvi_users/#{invalid_form_id}"
expect(response).to have_http_status(:forbidden)
expect(JSON.parse(response.body)['errors'].first['detail'])
.to eq("Action is prohibited with id parameter #{invalid_form_id}")
end
context('with valid form id parameter') do
valid_form_id = '21-526EZ'
# sad path, missing birls only which means we have big problems
context('when user is missing birls_id only') do
let(:user) { build(:user, :loa3, birls_id: nil) }
before do
sign_in_as(user)
end
it 'return 422' do
post "/v0/mvi_users/#{valid_form_id}"
expect(response).to have_http_status(:unprocessable_entity)
expect(JSON.parse(response.body)['errors'].first['detail'])
.to eq('No birls_id while participant_id present')
end
end
# sad path, user has proper ids, can not proxy add
context('when user has partipant_id and birls_id') do
let(:user) { build(:user, :loa3) }
before do
sign_in_as(user)
end
it 'return 403' do
post "/v0/mvi_users/#{valid_form_id}"
expect(response).to have_http_status(:forbidden)
end
end
# happy path, make proxy add
context('when user is missing birls_id and participant_id') do
let(:user) { build(:user_with_no_ids) }
before do
sign_in_as(user)
end
it 'return 200, add user to MPI' do
VCR.use_cassette('mpi/add_person/add_person_success') do
VCR.use_cassette('mpi/find_candidate/orch_search_with_attributes') do
VCR.use_cassette('mpi/find_candidate/find_profile_with_identifier') do
# expect success to be achieved by calling MPI's add_person_proxy
expect_any_instance_of(MPIData).to receive(:add_person_proxy).once.and_call_original
post "/v0/mvi_users/#{valid_form_id}"
expect(response).to have_http_status(:ok)
end
end
end
end
end
context 'when MPI return an error' do
let(:user) { build(:user_with_no_ids) }
let(:expected_error_message) { 'MPI add_person_proxy error' }
let(:expected_log_message) { '[V0][MPIUsersController] submit error' }
before do
sign_in_as(user)
allow(Rails.logger).to receive(:error)
end
it 'returns a 422 with the expected errors' do
VCR.use_cassette('mpi/add_person/add_person_internal_error_request') do
post "/v0/mvi_users/#{valid_form_id}"
json_response = JSON.parse(response.body)
expect(response).to have_http_status(:unprocessable_entity)
expect(json_response['errors'].first['error_message']).to eq(expected_error_message)
expect(Rails.logger).to have_received(:error).with(expected_log_message,
error_message: expected_error_message).once
end
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/debts_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::Debts', type: :request do
include SchemaMatchers
let(:user_details) do
{
first_name: 'Greg',
last_name: 'Anderson',
middle_name: 'A',
birth_date: '1991-04-05',
ssn: '796043735'
}
end
let(:user) { build(:user, :loa3, user_details) }
before do
sign_in_as(user)
end
describe 'GET /v0/debts' do
context 'with a veteran who has debts' do
it 'returns a 200 with the array of debts' do
VCR.use_cassette('bgs/people_service/person_data') do
VCR.use_cassette('debts/get_letters', VCR::MATCH_EVERYTHING) do
get '/v0/debts'
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('debts')
end
end
end
end
end
context 'with a veteran with empty ssn' do
it 'returns an error' do
VCR.use_cassette('debts/get_letters_empty_ssn', VCR::MATCH_EVERYTHING) do
get '/v0/debts'
expect(response).to have_http_status(:internal_server_error)
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/form1095_bs_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::Form1095Bs', type: :request do
let(:user) { build(:user, :loa3, icn: '1012667145V762142') }
let(:invalid_user) { build(:user, :loa1) }
before do
allow(Flipper).to receive(:enabled?).with(:fetch_1095b_from_enrollment_system, any_args).and_return(true)
Timecop.freeze(Time.zone.parse('2025-03-05T08:00:00Z'))
end
after { Timecop.return }
describe 'GET /download_pdf' do
context 'with valid user' do
before do
sign_in_as(user)
end
it 'returns http success' do
VCR.use_cassette('veteran_enrollment_system/form1095_b/get_form_success',
{ match_requests_on: %i[method uri] }) do
get '/v0/form1095_bs/download_pdf/2024'
expect(response).to have_http_status(:success)
end
end
it 'returns a PDF form' do
VCR.use_cassette('veteran_enrollment_system/form1095_b/get_form_success',
{ match_requests_on: %i[method uri] }) do
get '/v0/form1095_bs/download_pdf/2024'
expect(response.content_type).to eq('application/pdf')
end
end
it 'returns error from enrollment system' do
VCR.use_cassette('veteran_enrollment_system/form1095_b/get_form_not_found',
{ match_requests_on: %i[method uri] }) do
get '/v0/form1095_bs/download_pdf/2024'
expect(response).to have_http_status(:not_found)
end
end
# this will be irrelevant after we add the template
it 'throws 422 when template is not available' do
get '/v0/form1095_bs/download_pdf/2023'
expect(response).to have_http_status(:unprocessable_entity)
end
# 2021 is the one unsupported year for which we have a template
it 'throws 422 when requested year is not in supported range' do
get '/v0/form1095_bs/download_pdf/2021'
expect(response).to have_http_status(:unprocessable_entity)
end
end
context 'with invalid user' do
before do
sign_in_as(invalid_user)
end
it 'returns http 403' do
get '/v0/form1095_bs/download_pdf/2021'
expect(response).to have_http_status(:forbidden)
end
end
context 'when user is not logged in' do
it 'returns http 401' do
get '/v0/form1095_bs/download_pdf/2021'
expect(response).to have_http_status(:unauthorized)
end
end
end
describe 'GET /download_txt for valid user' do
context 'with valid user' do
before do
sign_in_as(user)
end
it 'returns http success' do
VCR.use_cassette('veteran_enrollment_system/form1095_b/get_form_success',
{ match_requests_on: %i[method uri] }) do
get '/v0/form1095_bs/download_txt/2024'
expect(response).to have_http_status(:success)
end
end
it 'returns a txt form' do
VCR.use_cassette('veteran_enrollment_system/form1095_b/get_form_success',
{ match_requests_on: %i[method uri] }) do
get '/v0/form1095_bs/download_txt/2024'
expect(response.content_type).to eq('text/plain')
end
end
it 'returns error from enrollment system' do
VCR.use_cassette('veteran_enrollment_system/form1095_b/get_form_not_found',
{ match_requests_on: %i[method uri] }) do
get '/v0/form1095_bs/download_txt/2024'
expect(response).to have_http_status(:not_found)
end
end
# this will be irrelevant after we add the template
it 'throws 422 when template is not available' do
get '/v0/form1095_bs/download_txt/2023'
expect(response).to have_http_status(:unprocessable_entity)
end
# 2021 is the one unsupported year for which we have a template
it 'throws 422 when requested year is not in supported range' do
get '/v0/form1095_bs/download_txt/2021'
expect(response).to have_http_status(:unprocessable_entity)
end
end
context 'with invalid user' do
before do
sign_in_as(invalid_user)
end
it 'returns http 403' do
get '/v0/form1095_bs/download_txt/2021'
expect(response).to have_http_status(:forbidden)
end
end
context 'when user is not logged in' do
it 'returns http 401' do
get '/v0/form1095_bs/download_txt/2021'
expect(response).to have_http_status(:unauthorized)
end
end
end
describe 'GET /available_forms' do
context 'with valid user' do
before do
sign_in_as(user)
end
it 'returns success with list of available form years during allowed date range' do
VCR.use_cassette('veteran_enrollment_system/enrollment_periods/get_success',
{ match_requests_on: %i[method uri] }) do
get '/v0/form1095_bs/available_forms'
end
expect(response).to have_http_status(:success)
expect(response.parsed_body.deep_symbolize_keys).to eq(
{ available_forms: [
{ year: 2024,
last_updated: nil }
] }
)
end
context 'when user not found on enrollment system' do
it 'returns success with an empty list' do
VCR.use_cassette('veteran_enrollment_system/enrollment_periods/get_not_found',
{ match_requests_on: %i[method uri] }) do
get '/v0/form1095_bs/available_forms'
end
expect(response).to have_http_status(:success)
expect(response.parsed_body.deep_symbolize_keys).to eq(
{ available_forms: [] }
)
end
end
context 'when user was not enrolled during allowed date range' do
# per the vcr cassette, user was not enrolled in 2023
before { Timecop.freeze(Time.zone.parse('2024-03-05T08:00:00Z')) }
after { Timecop.return }
it 'returns an empty array' do
VCR.use_cassette('veteran_enrollment_system/enrollment_periods/get_success',
{ match_requests_on: %i[method uri] }) do
get '/v0/form1095_bs/available_forms'
end
expect(response).to have_http_status(:success)
expect(response.parsed_body.deep_symbolize_keys).to eq(
{ available_forms: [] }
)
end
end
context 'when an error is received from the enrollment system' do
it 'returns appropriate error status' do
# stubbing instead of using cassette because I haven't been able to produce errors other than 404 on
# enrollment system
upstream_response = OpenStruct.new(status: 400)
allow_any_instance_of(VeteranEnrollmentSystem::EnrollmentPeriods::Service).to \
receive(:perform).and_return(upstream_response)
get '/v0/form1095_bs/available_forms'
expect(response).to have_http_status(:bad_request)
end
end
end
context 'with invalid user' do
before do
sign_in_as(invalid_user)
end
it 'returns http 403' do
get '/v0/form1095_bs/available_forms'
expect(response).to have_http_status(:forbidden)
end
end
context 'when user is not logged in' do
it 'returns http 401' do
get '/v0/form1095_bs/available_forms'
expect(response).to have_http_status(:unauthorized)
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/disability_compensation_in_progress_forms_controller_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'support/controller_spec_helper'
require 'disability_compensation/factories/api_provider_factory'
# Because of the shared_example this is behaving like a controller and request spec
RSpec.describe V0::DisabilityCompensationInProgressFormsController do
it_behaves_like 'a controller that does not log 404 to Sentry'
context 'with a user' do
let(:loa3_user) { build(:disabilities_compensation_user) }
let(:loa1_user) { build(:user, :loa1) }
describe '#show' do
before do
allow(Flipper).to receive(:enabled?).with(:disability_compensation_sync_modern_0781_flow, instance_of(User))
allow(Flipper).to receive(:enabled?).with(:intent_to_file_lighthouse_enabled, instance_of(User))
end
context 'using the Lighthouse Rated Disabilities Provider' do
let(:rated_disabilities_from_lighthouse) do
[{ 'name' => 'Diabetes mellitus0',
'ratedDisabilityId' => '1',
'ratingDecisionId' => '0',
'diagnosticCode' => 5238,
'decisionCode' => 'SVCCONNCTED',
'decisionText' => 'Service Connected',
'ratingPercentage' => 50,
'maximumRatingPercentage' => nil }]
end
let(:lighthouse_user) { build(:evss_user, icn: '123498767V234859') }
let!(:in_progress_form_lighthouse) do
form_json = JSON.parse(
File.read(
'spec/support/disability_compensation_form/' \
'526_in_progress_form_minimal_lighthouse_rated_disabilities.json'
)
)
create(:in_progress_form,
user_uuid: lighthouse_user.uuid,
form_id: '21-526EZ',
form_data: form_json['formData'],
metadata: form_json['metadata'])
end
before do
allow_any_instance_of(Auth::ClientCredentials::Service).to receive(:get_token).and_return('blahblech')
sign_in_as(lighthouse_user)
end
context 'when a form is found and rated_disabilities have updates' do
it 'returns the form as JSON' do
# change form data
fd = JSON.parse(in_progress_form_lighthouse.form_data)
fd['ratedDisabilities'].first['diagnosticCode'] = '111'
in_progress_form_lighthouse.update(form_data: fd)
VCR.use_cassette('lighthouse/veteran_verification/disability_rating/200_response') do
VCR.use_cassette('disability_max_ratings/max_ratings') do
get v0_disability_compensation_in_progress_form_url(in_progress_form_lighthouse.form_id), params: nil
end
end
expect(response).to have_http_status(:ok)
json_response = JSON.parse(response.body)
expect(json_response['formData']['ratedDisabilities'])
.to eq(
JSON.parse(in_progress_form_lighthouse.form_data)['ratedDisabilities']
)
expect(json_response['formData']['updatedRatedDisabilities']).to eq(rated_disabilities_from_lighthouse)
expect(json_response['metadata']['returnUrl']).to eq('/disabilities/rated-disabilities')
end
it 'returns an unaltered form if Lighthouse returns an error' do
rated_disabilities_before = JSON.parse(in_progress_form_lighthouse.form_data)['ratedDisabilities']
VCR.use_cassette('lighthouse/veteran_verification/disability_rating/503_response') do
get v0_disability_compensation_in_progress_form_url(in_progress_form_lighthouse.form_id), params: nil
end
expect(response).to have_http_status(:ok)
json_response = JSON.parse(response.body)
expect(json_response['formData']['ratedDisabilities']).to eq(rated_disabilities_before)
expect(json_response['formData']['updatedRatedDisabilities']).to be_nil
expect(json_response['metadata']['returnUrl']).to eq('/va-employee')
end
end
context 'when a form is found and rated_disabilities are unchanged' do
it 'returns the form as JSON' do
VCR.use_cassette('lighthouse/veteran_verification/disability_rating/200_response') do
get v0_disability_compensation_in_progress_form_url(in_progress_form_lighthouse.form_id), params: nil
end
expect(response).to have_http_status(:ok)
json_response = JSON.parse(response.body)
expect(json_response['formData']['ratedDisabilities'])
.to eq(
JSON.parse(in_progress_form_lighthouse.form_data)['ratedDisabilities']
)
expect(json_response['formData']['updatedRatedDisabilities']).to be_nil
expect(json_response['metadata']['returnUrl']).to eq('/va-employee')
end
end
context 'when toxic exposure' do
it 'returns startedFormVersion as 2019 for existing InProgressForms' do
VCR.use_cassette('lighthouse/veteran_verification/disability_rating/200_response') do
get v0_disability_compensation_in_progress_form_url(in_progress_form_lighthouse.form_id), params: nil
end
expect(response).to have_http_status(:ok)
json_response = JSON.parse(response.body)
expect(json_response['formData']['startedFormVersion']).to eq('2019')
end
end
context 'prefills formData when user does not have an InProgressForm pending submission' do
let(:user) { loa1_user }
let!(:form_id) { '21-526EZ' }
before do
sign_in_as(user)
end
it 'adds default startedFormVersion for new InProgressForm' do
get v0_disability_compensation_in_progress_form_url(form_id), params: nil
json_response = JSON.parse(response.body)
expect(json_response['formData']['startedFormVersion']).to eq('2022')
end
it 'returns 2022 when existing IPF with 2022 as startedFormVersion' do
parsed_form_data = JSON.parse(in_progress_form_lighthouse.form_data)
parsed_form_data['startedFormVersion'] = '2022'
in_progress_form_lighthouse.form_data = parsed_form_data.to_json
in_progress_form_lighthouse.save!
VCR.use_cassette('lighthouse/veteran_verification/disability_rating/200_response') do
get v0_disability_compensation_in_progress_form_url(in_progress_form_lighthouse.form_id), params: nil
expect(response).to have_http_status(:ok)
json_response = JSON.parse(response.body)
expect(json_response['formData']['startedFormVersion']).to eq('2022')
end
end
end
end
describe '#update' do
let(:update_user) { loa3_user }
let(:new_form) { build(:in_progress_form, form_id: FormProfiles::VA526ez::FORM_ID) }
let(:flipper0781) { :disability_compensation_sync_modern0781_flow_metadata }
before do
sign_in_as(update_user)
end
it 'inserts the form', run_at: '2017-01-01' do
expect do
put v0_disability_compensation_in_progress_form_url(new_form.form_id), params: {
formData: new_form.form_data,
metadata: new_form.metadata
}.to_json, headers: { 'CONTENT_TYPE' => 'application/json' }
end.to change(InProgressForm, :count).by(1)
expect(response).to have_http_status(:ok)
end
it 'adds 0781 metadata if flipper enabled' do
allow(Flipper).to receive(:enabled?).with(flipper0781).and_return(true)
put v0_in_progress_form_url(new_form.form_id),
params: {
form_data: { greeting: 'Hello!' },
metadata: new_form.metadata
}.to_json,
headers: { 'CONTENT_TYPE' => 'application/json' }
# Checking key present, it will be false regardless due to prefill not running
expect(JSON.parse(response.body)['data']['attributes']['metadata'].key?('sync_modern0781_flow')).to be(true)
expect(response).to have_http_status(:ok)
end
it 'does not add 0781 metadata if form and flipper disabled' do
allow(Flipper).to receive(:enabled?).with(flipper0781).and_return(false)
put v0_in_progress_form_url(new_form.form_id),
params: {
form_data: { greeting: 'Hello!' },
metadata: new_form.metadata
}.to_json,
headers: { 'CONTENT_TYPE' => 'application/json' }
expect(JSON.parse(response.body)['data']['attributes']['metadata'].key?('sync_modern0781_flow')).to be(false)
expect(response).to have_http_status(:ok)
end
end
context 'without a user' do
describe '#show' do
let(:in_progress_form) { create(:in_progress_form) }
it 'returns a 401' do
get v0_disability_compensation_in_progress_form_url(in_progress_form.form_id), params: nil
expect(response).to have_http_status(:unauthorized)
end
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/efolder_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'support/stub_efolder_documents'
RSpec.describe 'VO::Efolder', type: :request do
let(:user) { build(:user, :loa3) }
before do
sign_in_as(user)
end
describe 'GET /v0/efolder' do
stub_efolder_index_documents
let(:expected_response) do
[
{ 'document_id' => '{73CD7B28-F695-4337-BBC1-2443A913ACF6}',
'doc_type' => '702',
'type_description' => 'Disability Benefits Questionnaire (DBQ) - Veteran Provided',
'received_at' => '2024-09-13' },
{ 'document_id' => '{EF7BF420-7E49-4FA9-B14C-CE5F6225F615}',
'doc_type' => '45',
'type_description' => 'Military Personnel Record',
'received_at' => '2024-09-13' }
]
end
it 'shows all documents available to the veteran' do
get '/v0/efolder'
expect(JSON.parse(response.body)).to eq(expected_response)
end
end
describe 'GET /v0/efolder/{id}' do
stub_efolder_show_document
it 'sends the doc pdf' do
get "/v0/efolder/#{CGI.escape(document_id)}", params: { filename: 'test.pdf' }
expect(response.body).to eq(content)
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/in_progress_forms_controller_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'support/controller_spec_helper'
# Because of the shared_example this is behaving like a controller and request spec
RSpec.describe V0::InProgressFormsController do
it_behaves_like 'a controller that does not log 404 to Sentry'
context 'with a user' do
let(:loa3_user) { build(:user, :loa3, :with_terms_of_use_agreement) }
let(:loa1_user) { build(:user, :loa1, :with_terms_of_use_agreement, icn: nil) }
before do
sign_in_as(user)
enabled_forms = FormProfile.prefill_enabled_forms << 'FAKEFORM'
allow(FormProfile).to receive(:prefill_enabled_forms).and_return(enabled_forms)
allow(FormProfile).to receive(:load_form_mapping).and_call_original
allow(FormProfile).to receive(:load_form_mapping).with('FAKEFORM').and_return(
'veteran_full_name' => %w[identity_information full_name],
'gender' => %w[identity_information gender],
'veteran_date_of_birth' => %w[identity_information date_of_birth],
'veteran_social_security_number' => %w[identity_information ssn],
'veteran_address' => %w[contact_information address],
'home_phone' => %w[contact_information home_phone]
)
end
describe '#index' do
subject { get v0_in_progress_forms_url, params: nil }
let(:user) { loa3_user }
let!(:in_progress_form_edu) do
create(:in_progress_form, :with_nested_metadata, form_id: '22-1990', user_uuid: user.uuid)
end
let!(:in_progress_form_hca) { create(:in_progress_form, form_id: '1010ez', user_uuid: user.uuid) }
context 'when the user is not loa3' do
let(:user) { loa1_user }
let(:response_body) { JSON.parse(response.body) }
let(:top_level_keys) { response_body.keys }
let(:data) { response_body['data'] }
let(:in_progress_form_with_nested_hash) { data.find { |ipf| ipf['attributes']['metadata']['howNow'] } }
let(:metadata_returned_with_the_request) { in_progress_form_with_nested_hash['attributes']['metadata'] }
let(:metadata_before_the_request) { in_progress_form_edu.metadata }
it 'returns a 200' do
subject
expect(response).to have_http_status(:ok)
end
it 'has the correct shape (JSON:API), and has camelCase keys all the way down to attributes' do
subject
expect(response_body).to be_a Hash
expect(top_level_keys).to contain_exactly 'data'
expect(data).to be_an Array
expect(data.count).to be > 1
data.each do |ipf|
expect(ipf.keys).to contain_exactly('id', 'type', 'attributes')
expect(ipf['type']).to eq 'in_progress_forms'
expect(ipf['attributes'].keys).to contain_exactly('formId', 'createdAt', 'updatedAt', 'metadata')
end
end
it 'does NOT transform keys inside attributes' do
subject
expect(metadata_returned_with_the_request['howNow']['brown-cow']).to be_present
end
it 'does NOT corrupt complicated keys' do
subject
expect(metadata_before_the_request['howNow']['brown-cow']['-an eas-i-ly corRupted KEY.'])
.to be_present
expect(metadata_returned_with_the_request['howNow']['brown-cow']['-an eas-i-ly corRupted KEY.'])
.to be_present
end
context 'with OliveBranch' do
subject do
get(
v0_in_progress_forms_url,
headers: { 'X-Key-Inflection' => 'camel', 'Content-Type' => 'application/json' }
)
end
let(:in_progress_form_with_nested_hash) { data.find { |ipf| ipf['attributes']['metadata']['howNow'] } }
it 'has camelCase keys' do
subject
expect(response_body).to be_a Hash
expect(top_level_keys).to contain_exactly 'data'
expect(data).to be_an Array
expect(data.count).to be > 1
data.each do |ipf|
expect(ipf.keys).to contain_exactly('id', 'type', 'attributes')
expect(ipf['type']).to eq 'in_progress_forms'
expect(ipf['attributes'].keys).to contain_exactly('formId', 'createdAt', 'updatedAt', 'metadata')
end
end
it 'camelCased keys *inside* attributes' do
subject
expect(metadata_returned_with_the_request['howNow']['brownCow']).to be_present
end
it 'corrupts complicated keys' do
subject
expect(metadata_before_the_request['howNow']['brown-cow']['-an eas-i-ly corRupted KEY.'])
.to be_present
expect(metadata_returned_with_the_request['howNow']['brownCow']).to be_present
expect(metadata_returned_with_the_request['howNow']['brownCow']['-an eas-i-ly corRupted KEY.'])
.not_to be_present
end
end
end
context 'when the user is not a test account' do
let(:user) { build(:user, :loa3, ssn: '000010002') }
it 'returns a 200' do
subject
expect(response).to have_http_status(:ok)
end
end
it 'returns details about saved forms' do
subject
items = JSON.parse(response.body)['data']
expect(items.size).to eq(2)
expect(items.dig(0, 'attributes', 'formId')).to be_a(String)
end
end
describe '#show' do
let(:user) { build(:user, :loa3, address: build(:mpi_profile_address)) }
let!(:in_progress_form) { create(:in_progress_form, :with_nested_metadata, user_uuid: user.uuid) }
context 'when the user is not loa3' do
let(:user) { loa1_user }
it 'returns a 200' do
get v0_in_progress_form_url(in_progress_form.form_id), params: nil
expect(response).to have_http_status(:ok)
end
end
context 'when a form is found' do
it 'returns the form as JSON' do
get v0_in_progress_form_url(in_progress_form.form_id), params: nil
expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body)).to eq(
'formData' => JSON.parse(in_progress_form.form_data),
'metadata' => in_progress_form.metadata
)
end
context 'with the x key inflection header set' do
it 'converts the json keys' do
form_data = { 'view:hasVaMedicalRecords' => true }
in_progress_form.update(form_data:)
get v0_in_progress_form_url(in_progress_form.form_id),
headers: { 'HTTP_X_KEY_INFLECTION' => 'camel' }
body = JSON.parse(response.body)
expect(body.keys).to include('formData', 'metadata')
expect(body['formData'].keys).to include('view:hasVaMedicalRecords')
expect(body['formData']['view:hasVaMedicalRecords']).to eq form_data['view:hasVaMedicalRecords']
expect(body['formData'].keys).not_to include('Hello, there Sam-I -Am!')
expect(body['metadata']['howNow']['brownCow']).to be_present
expect(body['metadata']['howNow']['brownCow']['-an eas-i-ly corRupted KEY.']).not_to be_present
end
end
context 'without the inflection header' do
it 'has camelCase top-level keys, but does not transform nested keys' do
form_data = {
'view:hasVaMedicalRecords' => true,
'Hello, there Sam-I -Am!' => true
}
in_progress_form.update(form_data:)
get v0_in_progress_form_url(in_progress_form.form_id)
body = JSON.parse(response.body)
expect(body.keys).to include('formData', 'metadata')
expect(body['formData'].keys).to include('view:hasVaMedicalRecords')
expect(body['formData']['view:hasVaMedicalRecords']).to eq form_data['view:hasVaMedicalRecords']
expect(body['formData'].keys).to include('Hello, there Sam-I -Am!')
expect(body['formData']['Hello, there Sam-I -Am!']).to eq form_data['Hello, there Sam-I -Am!']
expect(body['metadata']['howNow']['brown-cow']['-an eas-i-ly corRupted KEY.']).to be_present
expect(body['metadata']).to eq in_progress_form.metadata
end
end
end
context 'for an MDOT form sans addresses' do
let(:user_details) do
{
first_name: 'Greg',
last_name: 'Anderson',
middle_name: 'A',
birth_date: '19910405',
ssn: '000550237'
}
end
let(:user) { build(:user, :loa3, user_details) }
it 'returns the form as JSON' do
VCR.insert_cassette(
'mdot/get_supplies_null_addresses_200',
match_requests_on: %i[method uri headers],
erb: { icn: user.icn }
)
get v0_in_progress_form_url('MDOT'), params: nil
expect(response).to have_http_status(:ok)
VCR.eject_cassette
end
end
context 'when a form is not found' do
let(:street_check) { build(:street_check) }
let(:expected_data) do
{
'veteranFullName' => {
'first' => user.first_name&.capitalize,
'last' => user.last_name&.capitalize
},
'gender' => user.gender,
'veteranDateOfBirth' => user.birth_date,
'veteranSocialSecurityNumber' => user.ssn.to_s,
'veteranAddress' => {
'street' => '140 Rock Creek Rd',
'city' => 'Washington',
'state' => 'DC',
'country' => 'USA',
'postalCode' => '20011'
},
'homePhone' => '3035551234'
}
end
it 'returns pre-fill data' do
expected_data
get v0_in_progress_form_url('FAKEFORM'), params: nil
expected_data['veteranFullName']['suffix'] = user.normalized_suffix if user.normalized_suffix.present?
check_case_of_keys_recursively = lambda do |value|
case value
when Hash
value.each_key do |key|
expect(key).not_to include '_' # ensure all keys are camelCase
check_case_of_keys_recursively.call(value[key])
end
when Array
value.each { |v| check_case_of_keys_recursively.call(v) }
end
end
check_case_of_keys_recursively.call(JSON.parse(response.body))
expect(JSON.parse(response.body)['formData']).to eq(expected_data)
end
it 'returns pre-fill data the same way, with or without the Inflection heaader' do
expected_data
get v0_in_progress_form_url('FAKEFORM')
without_inflection_header = JSON.parse(response.body)
get v0_in_progress_form_url('FAKEFORM'),
headers: { 'X-Key-Inflection' => 'camel', 'Content-Type' => 'application/json' }
with_inflection_header = JSON.parse(response.body)
expect(without_inflection_header).to eq with_inflection_header
end
end
context 'when a form mapping is not found' do
it 'returns a 500' do
allow(FormProfile).to receive(:prefill_enabled_forms).and_return(['FOO'])
get v0_in_progress_form_url('foo'), params: nil
expect(response).to have_http_status(:internal_server_error)
end
end
end
describe '#update' do
let(:user) { loa3_user }
before do
allow(Flipper).to receive(:enabled?).with(:intent_to_file_lighthouse_enabled,
instance_of(User)).and_return(true)
end
context 'with a new form' do
let(:new_form) { create(:in_progress_form, user_uuid: user.uuid, user_account: user.user_account) }
context 'when handling race condition' do
context 'with in_progress_form_atomicity flipper on' do
before do
allow(Flipper).to receive(:enabled?).with(:in_progress_form_atomicity,
instance_of(User)).and_return(true)
end
it 'handles concurrent requests creating the same form' do
form_id = '22-1990'
form_data = { test: 'data' }.to_json
metadata = { version: 1 }
# Simulate race condition: two concurrent requests both find no existing form
# then both try to create one
allow(InProgressForm).to receive(:form_for_user).and_return(nil).twice
# First request should succeed with create_or_find_by!
expect do
put v0_in_progress_form_url(form_id), params: {
form_data:,
metadata:
}.to_json, headers: { 'CONTENT_TYPE' => 'application/json' }
end.to change(InProgressForm, :count).by(1)
expect(response).to have_http_status(:ok)
# Second concurrent request should not raise duplicate key error
# It should find the existing form or handle the constraint violation
expect do
put v0_in_progress_form_url(form_id), params: {
form_data: { test: 'updated_data' }.to_json,
metadata:
}.to_json, headers: { 'CONTENT_TYPE' => 'application/json' }
end.not_to change(InProgressForm, :count)
expect(response).to have_http_status(:ok)
# Verify the form was updated with the second request's data
updated_form = InProgressForm.find_by(form_id:, user_uuid: user.uuid)
expect(JSON.parse(updated_form.form_data)).to eq({ 'test' => 'updated_data' })
end
end
context 'with in_progress_form_atomicity flipper off' do
before do
allow(Flipper).to receive(:enabled?).with(:in_progress_form_atomicity,
instance_of(User)).and_return(false)
end
it 'fails when concurrent requests create the same form' do
form_id = '22-1990'
form_data = { test: 'data' }.to_json
metadata = { version: 1 }
# Simulate race condition: two concurrent requests both find no existing form
# then both try to create one
allow(InProgressForm).to receive(:form_for_user).and_return(nil).twice
# First request should succeed
expect do
put v0_in_progress_form_url(form_id), params: {
form_data:,
metadata:
}.to_json, headers: { 'CONTENT_TYPE' => 'application/json' }
end.to change(InProgressForm, :count).by(1)
expect(response).to have_http_status(:ok)
# Second concurrent request will raise duplicate key error
# since the non-atomic path does not handle it
expect do
put v0_in_progress_form_url(form_id), params: {
form_data: { test: 'updated_data' }.to_json,
metadata:
}.to_json, headers: { 'CONTENT_TYPE' => 'application/json' }
end.not_to change(InProgressForm, :count)
expect(response).to have_http_status(:internal_server_error)
# Verify the form was not updated with the second request's data
updated_form = InProgressForm.find_by(form_id:, user_uuid: user.uuid)
expect(JSON.parse(updated_form.form_data)).to eq({ 'test' => 'data' })
end
end
end
context 'when the user is not loa3' do
let(:user) { loa1_user }
it 'returns a 200 with camelCases JSON' do
put v0_in_progress_form_url(new_form.form_id), params: {
form_data: new_form.form_data,
metadata: new_form.metadata
}.to_json, headers: { 'CONTENT_TYPE' => 'application/json' }
expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body)['data']['attributes'].keys)
.to contain_exactly('formId', 'createdAt', 'updatedAt', 'metadata')
end
end
it 'runs the LogEmailDiffJob job' do
new_form.form_id = '1010ez'
allow(HCA::LogEmailDiffJob).to receive(:perform_async)
new_form.save!
expect(HCA::LogEmailDiffJob).to receive(:perform_async).with(new_form.id, user.uuid,
user.user_account_uuid)
put v0_in_progress_form_url(new_form.form_id), params: {
formData: new_form.form_data,
metadata: new_form.metadata
}.to_json, headers: { 'CONTENT_TYPE' => 'application/json' }
end
it 'inserts the form', run_at: '2017-01-01' do
expect do
put v0_in_progress_form_url(new_form.form_id), params: {
formData: new_form.form_data,
metadata: new_form.metadata
}.to_json, headers: { 'CONTENT_TYPE' => 'application/json' }
end.to change(InProgressForm, :count).by(1)
expect(response).to have_http_status(:ok)
in_progress_form = InProgressForm.last
expect(in_progress_form.form_data).to eq(new_form.form_data)
expect(in_progress_form.metadata).to eq(
'version' => 1,
'return_url' => 'foo.com', # <- the factory uses snake_case (as most forms are still using OliveBranch)
'createdAt' => 1_483_228_800,
'expiresAt' => 1_488_412_800, # <- these are inserted by the model on access, and will always be camelCase
'lastUpdated' => 1_483_228_800, # now so that the front end will always receive camelCase (with or without
'inProgressFormId' => in_progress_form.id, # the inflection header)
'submission' => { 'status' => false, 'error_message' => false, 'id' => false, 'timestamp' => false,
'has_attempted_submit' => false }
)
end
it 'sets expires_at to 60 days from now for regular forms', run_at: '2017-01-01' do
put v0_in_progress_form_url(new_form.form_id), params: {
formData: new_form.form_data,
metadata: new_form.metadata
}.to_json, headers: { 'CONTENT_TYPE' => 'application/json' }
expect(response).to have_http_status(:ok)
in_progress_form = InProgressForm.last
expect(in_progress_form.expires_at.to_i).to eq(1_488_412_800)
end
it 'preserves existing expires_at for form526 (skippable form)', run_at: '2017-01-01' do
form526 = create(:in_progress_526_form, user_uuid: user.uuid, user_account: user.user_account)
# Factory sets expires_at to 1 year from now
initial_expires_at = form526.expires_at
put v0_in_progress_form_url(form526.form_id), params: {
formData: form526.form_data,
metadata: form526.metadata
}.to_json, headers: { 'CONTENT_TYPE' => 'application/json' }
expect(response).to have_http_status(:ok)
in_progress_form = InProgressForm.find_by(form_id: form526.form_id, user_uuid: user.uuid)
# expires_at should be preserved, not updated to current time
expect(in_progress_form.expires_at).to eq(initial_expires_at)
end
it 'can have nil metadata' do
put v0_in_progress_form_url(new_form.form_id),
params: { form_data: { greeting: 'Hello!' } }.to_json,
headers: { 'CONTENT_TYPE' => 'application/json' }
expect(response).to have_http_status(:ok)
end
it "can't have nil formData" do
put v0_in_progress_form_url(new_form.form_id)
expect(response).to have_http_status(:error)
end
it "can't have non-hash formData" do
put v0_in_progress_form_url(new_form.form_id),
params: { form_data: '' }.to_json,
headers: { 'CONTENT_TYPE' => 'application/json' }
expect(response).to have_http_status(:error)
end
it "can't have an empty hash for formData" do
put v0_in_progress_form_url(new_form.form_id),
params: {}.to_json,
headers: { 'CONTENT_TYPE' => 'application/json' }
expect(response).to have_http_status(:error)
end
context 'when an error occurs' do
it 'returns an error response' do
allow_any_instance_of(InProgressForm).to receive(:update!).and_raise(ActiveRecord::ActiveRecordError)
put v0_in_progress_form_url(new_form.form_id), params: { form_data: new_form.form_data }
expect(response).to have_http_status(:internal_server_error)
expect(Oj.load(response.body)['errors'].first['detail']).to eq('Internal server error')
end
end
context 'when form type is pension' do
it 'creates pension form successfully' do
put v0_in_progress_form_url('21P-527EZ'),
params: {
formData: new_form.form_data,
metadata: new_form.metadata
}.to_json,
headers: { 'CONTENT_TYPE' => 'application/json' }
expect(response).to have_http_status(:ok)
latest_form = InProgressForm.last
expect(latest_form.form_id).to eq('21P-527EZ')
end
end
end
context 'with an existing form' do
let!(:other_existing_form) { create(:in_progress_form, form_id: 'jksdfjk') }
let(:existing_form) { create(:in_progress_form, user_uuid: user.uuid, user_account: user.user_account) }
let(:form_data) { { some_form_data: 'form-data' }.to_json }
it 'updates the right form' do
put v0_in_progress_form_url(existing_form.form_id), params: { form_data: }
expect(response).to have_http_status(:ok)
expect(existing_form.reload.form_data).to eq(form_data)
end
it 'updates expires_at on each update', run_at: '2017-01-01' do
# Set initial expires_at to a different time
existing_form.update!(expires_at: Time.zone.parse('2017-02-01'))
initial_expires_at = existing_form.expires_at
put v0_in_progress_form_url(existing_form.form_id), params: { form_data: }
expect(response).to have_http_status(:ok)
existing_form.reload
# expires_at should be updated to 60 days from 2017-01-01 = 1488412800
expect(existing_form.expires_at.to_i).to eq(1_488_412_800)
expect(existing_form.expires_at).not_to eq(initial_expires_at)
end
it 'preserves expires_at for form526 on update', run_at: '2017-01-01' do
form526 = create(:in_progress_526_form, user_uuid: user.uuid, user_account: user.user_account)
# Set a specific expires_at
form526.update!(expires_at: Time.zone.parse('2018-06-01'))
initial_expires_at = form526.expires_at
form_data = { updated: 'data' }.to_json
put v0_in_progress_form_url(form526.form_id), params: { form_data: }
expect(response).to have_http_status(:ok)
form526.reload
# expires_at should remain unchanged for form526 (skippable form)
expect(form526.expires_at).to eq(initial_expires_at)
end
context 'has checked \'One or more of my rated conditions that have gotten worse\'' do
let!(:existing_form) { create(:in_progress_526_form, user_uuid: user.uuid) }
let(:form_data) do
{ 'view:claim_type': {
'view:claiming_increase': true
},
rated_disabilities: [
{ name: 'Hypertension',
diagnostic_code: ClaimFastTracking::DiagnosticCodes::HYPERTENSION }
] }.to_json
end
before { allow(StatsD).to receive(:increment) }
context 'has no ratings with maximum_rating_percentage' do
it 'updates form with cfiMetric metadata but does not call StatsD' do
put v0_in_progress_form_url(existing_form.form_id),
params: { form_data:, metadata: existing_form.metadata }
expect(response).to have_http_status(:ok)
expect(existing_form.reload.metadata.keys).to include('cfiMetric')
expect(StatsD).to have_received(:increment).with('api.max_cfi.on_rated_disabilities',
tags: ['has_max_rated:false']).once
expect(StatsD).not_to have_received(:increment).with('api.max_cfi.rated_disabilities', anything)
end
end
context 'has rated disability with maximum_rating_percentage' do
let(:form_data) do
{ 'view:claim_type': {
'view:claiming_increase': true
},
rated_disabilities: [
{ name: 'Tinnitus',
diagnostic_code: ClaimFastTracking::DiagnosticCodes::TINNITUS,
rating_percentage: 10,
maximum_rating_percentage: 10 },
{ name: 'Hypertension',
diagnostic_code: ClaimFastTracking::DiagnosticCodes::HYPERTENSION,
rating_percentage: 20 }
] }.to_json
end
it 'updates form and includes cfiMetric in metadata, and logs metric' do
put v0_in_progress_form_url(existing_form.form_id),
params: { form_data:, metadata: existing_form.metadata }
expect(response).to have_http_status(:ok)
expect(existing_form.reload.metadata.keys).to include('cfiMetric')
expect(StatsD).to have_received(:increment).with('api.max_cfi.on_rated_disabilities',
tags: ['has_max_rated:true']).once
expect(StatsD).to have_received(:increment).with('api.max_cfi.rated_disabilities',
tags: ['diagnostic_code:6260']).once
expect(StatsD).not_to have_received(:increment).with('api.max_cfi.rated_disabilities',
tags: ['diagnostic_code:7101'])
end
context 'if updated twice' do
it 'only logs metric once' do
put v0_in_progress_form_url(existing_form.form_id),
params: { form_data:, metadata: existing_form.metadata }
expect(response).to have_http_status(:ok)
expect(existing_form.reload.metadata.keys).to include('cfiMetric')
put v0_in_progress_form_url(existing_form.form_id),
params: { form_data:, metadata: existing_form.metadata }
expect(response).to have_http_status(:ok)
expect(existing_form.reload.metadata.keys).to include('cfiMetric')
expect(StatsD).to have_received(:increment).with('api.max_cfi.on_rated_disabilities',
tags: ['has_max_rated:true']).once
expect(StatsD).to have_received(:increment).with('api.max_cfi.rated_disabilities',
tags: ['diagnostic_code:6260']).once
expect(StatsD).not_to have_received(:increment).with('api.max_cfi.rated_disabilities',
tags: ['diagnostic_code:7101'])
end
end
end
end
context 'has not checked \'One or more of my rated conditions that have gotten worse\'' do
before { allow(StatsD).to receive(:increment) }
let(:existing_form) { create(:in_progress_526_form, user_uuid: user.uuid) }
it 'updates form with cfiMetric metadata but does not call StatsD' do
put v0_in_progress_form_url(existing_form.form_id),
params: { form_data:, metadata: existing_form.metadata }
expect(response).to have_http_status(:ok)
expect(existing_form.reload.metadata.keys).to include('cfiMetric')
expect(StatsD).not_to have_received(:increment).with('api.max_cfi.on_rated_disabilities', anything)
end
end
end
end
describe '#destroy' do
let(:user) { loa3_user }
let!(:in_progress_form) { create(:in_progress_form, user_uuid: user.uuid) }
context 'when the user is not loa3' do
let(:user) { loa1_user }
it 'returns a 200 with camelCase JSON' do
delete v0_in_progress_form_url(in_progress_form.form_id), params: nil
expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body)['data']['attributes'].keys)
.to contain_exactly('formId', 'createdAt', 'updatedAt', 'metadata')
end
end
context 'when a form is not found' do
subject do
delete v0_in_progress_form_url('ksdjfkjdf'), params: nil
end
it 'returns a 404' do
subject
expect(response).to have_http_status(:not_found)
end
end
context 'when a form is found' do
subject do
delete v0_in_progress_form_url(in_progress_form.form_id), params: nil
end
it 'returns the deleted form id' do
expect { subject }.to change(InProgressForm, :count).by(-1)
expect(response).to have_http_status(:ok)
end
end
end
end
context 'without a user' do
describe '#show' do
let(:in_progress_form) { create(:in_progress_form) }
it 'returns a 401' do
get v0_in_progress_form_url(in_progress_form.form_id), params: nil
expect(response).to have_http_status(:unauthorized)
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/form212680_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::Form212680', type: :request do
include StatsD::Instrument::Helpers
let(:form_data) { { form: VetsJsonSchema::EXAMPLES['21-2680'].to_json }.to_json }
let(:saved_claim) { create(:form212680) }
describe 'POST /v0/form212680' do
context 'when inflection header provided' do
it 'returns a success' do
metrics = capture_statsd_calls do
post(
'/v0/form212680',
params: form_data,
headers: {
'Content-Type' => 'application/json',
'X-Key-Inflection' => 'camel',
'HTTP_SOURCE_APP_NAME' => '21-2680-house-bound-status'
}
)
end
expect(response).to have_http_status(:ok)
expect(metrics.collect(&:source)).to include(
'saved_claim.create:1|c|#form_id:21-2680,doctype:540',
'api.form212680.success:1|c',
'api.rack.request:1|c|#controller:v0/form212680,action:create,' \
'source_app:21-2680-house-bound-status,status:200'
)
end
end
end
describe 'GET /v0/form212680/download_pdf' do
it 'returns a success' do
metrics = capture_statsd_calls do
get("/v0/form212680/download_pdf/#{saved_claim.guid}", headers: {
'Content-Type' => 'application/json',
'HTTP_SOURCE_APP_NAME' => '21-2680-house-bound-status'
})
end
expect(metrics.collect(&:source)).to include(
'saved_claim.create:1|c|#form_id:21-2680,doctype:540',
'api.rack.request:1|c|#controller:v0/form212680,action:download_pdf,' \
'source_app:21-2680-house-bound-status,status:200'
)
expect(response).to have_http_status(:ok)
expect(response.content_type).to eq('application/pdf')
end
it 'returns 500 when to_pdf returns error' do
allow_any_instance_of(SavedClaim::Form212680).to receive(:to_pdf).and_raise(StandardError, 'PDF generation error')
metrics = capture_statsd_calls do
get("/v0/form212680/download_pdf/#{saved_claim.guid}", headers: {
'Content-Type' => 'application/json',
'HTTP_SOURCE_APP_NAME' => '21-2680-house-bound-status'
})
end
expect(metrics.collect(&:source)).to include(
'api.rack.request:1|c|#controller:v0/form212680,action:download_pdf,' \
'source_app:21-2680-house-bound-status,status:500'
)
expect(response).to have_http_status(:internal_server_error)
expect(JSON.parse(response.body)['errors']).to be_present
expect(JSON.parse(response.body)['errors'].first['status']).to eq('500')
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/health_care_applications_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'hca/service'
require 'bgs/service'
RSpec.describe 'V0::HealthCareApplications', type: %i[request serializer] do
let(:test_veteran) do
JSON.parse(
Rails.root.join('spec', 'fixtures', 'hca', 'veteran.json').read
)
end
let(:headers) do
{
'ACCEPT' => 'application/json',
'CONTENT_TYPE' => 'application/json',
'HTTP_X_KEY_INFLECTION' => 'camel'
}
end
describe 'GET rating_info' do
let(:current_user) { build(:ch33_dd_user) }
before do
allow(Flipper).to receive(:enabled?).with(:hca_disable_bgs_service).and_return(false)
sign_in_as(current_user)
end
it 'returns the users rating info' do
VCR.use_cassette('bgs/service/find_rating_data', VCR::MATCH_EVERYTHING) do
get(rating_info_v0_health_care_applications_path)
end
expect(JSON.parse(response.body)['data']['attributes']).to eq(
{ 'user_percent_of_disability' => 100 }
)
end
context 'hca_disable_bgs_service enabled' do
before do
allow(Flipper).to receive(:enabled?).with(:hca_disable_bgs_service).and_return(true)
end
it 'does not call the BGS Service and returns the rating info as 0' do
expect_any_instance_of(BGS::Service).not_to receive(:find_rating_data)
get(rating_info_v0_health_care_applications_path)
expect(JSON.parse(response.body)['data']['attributes']).to eq(
{ 'user_percent_of_disability' => 0 }
)
end
end
context 'User not found' do
before do
error404 = Common::Exceptions::RecordNotFound.new(1)
allow_any_instance_of(BGS::Service).to receive(:find_rating_data).and_raise(error404)
end
it 'returns a 404 if user not found' do
get(rating_info_v0_health_care_applications_path)
errors = JSON.parse(response.body)['errors']
expect(errors.first['title']).to eq('Record not found')
expect(response).to have_http_status(:not_found)
end
end
context 'with an loa1 user' do
let(:current_user) { build(:user, :loa1) }
it 'errors if user is not loa3' do
get(rating_info_v0_health_care_applications_path)
errors = JSON.parse(response.body)['errors']
expect(errors.first['title']).to eq('Forbidden')
end
end
end
describe 'GET healthcheck' do
subject do
get(healthcheck_v0_health_care_applications_path)
end
let(:body) do
{ 'formSubmissionId' => 377_609_264,
'timestamp' => '2024-08-20T11:38:44.535-05:00' }
end
let(:es_stub) { double(health_check: { up: true }) }
it 'calls ES' do
VCR.use_cassette('hca/health_check', match_requests_on: [:body]) do
subject
expect(JSON.parse(response.body)).to eq(body)
end
end
end
describe 'enrollment_status' do
let(:success_response) do
{ application_date: '2018-01-24T00:00:00.000-06:00',
enrollment_date: nil,
preferred_facility: '987 - CHEY6',
parsed_status: HCA::EnrollmentEligibility::Constants::INELIG_CHARACTER_OF_DISCHARGE,
primary_eligibility: 'SC LESS THAN 50%',
can_submit_financial_info: true }
end
let(:loa1_response) do
{ parsed_status: HCA::EnrollmentEligibility::Constants::LOGIN_REQUIRED }
end
context 'GET enrollment_status' do
context 'with user attributes' do
let(:user_attributes) do
{
userAttributes: build(:health_care_application).parsed_form.slice(
'veteranFullName', 'veteranDateOfBirth',
'veteranSocialSecurityNumber', 'gender'
)
}
end
it 'returns 404 unless signed in' do
allow(HealthCareApplication).to receive(:user_icn).and_return('123')
allow(HealthCareApplication).to receive(:enrollment_status).with(
'123', nil
).and_return(loa1_response)
get(enrollment_status_v0_health_care_applications_path, params: user_attributes)
expect(response).to have_http_status(:not_found)
end
end
context 'with a signed in user' do
let(:current_user) { build(:user, :loa3) }
before do
sign_in_as(current_user)
end
context 'with a user with no icn' do
before do
allow_any_instance_of(User).to receive(:icn).and_return(nil)
end
it 'returns 404' do
get(enrollment_status_v0_health_care_applications_path)
expect(response).to have_http_status(:not_found)
end
end
context 'without user passed attributes' do
let(:enrolled) { HCA::EnrollmentEligibility::Constants::ENROLLED }
let(:success_response) do
{
application_date: '2018-12-27T00:00:00.000-06:00',
enrollment_date: '2018-12-27T17:15:39.000-06:00',
preferred_facility: '988 - DAYT20',
effective_date: '2019-01-02T21:58:55.000-06:00',
primary_eligibility: 'SC LESS THAN 50%',
priority_group: 'Group 3',
can_submit_financial_info: true,
parsed_status: enrolled
}
end
before do
allow_any_instance_of(User).to receive(:icn).and_return('1013032368V065534')
end
it 'returns the enrollment status data' do
VCR.use_cassette('hca/ee/lookup_user', erb: true) do
get(enrollment_status_v0_health_care_applications_path)
expect(response.body).to eq(success_response.to_json)
end
end
end
end
end
context 'POST enrollment_status' do
let(:headers) do
{
'ACCEPT' => 'application/json',
'CONTENT_TYPE' => 'application/json'
}
end
context 'with user attributes' do
let(:params) do
{
user_attributes: build(:health_care_application).parsed_form.deep_transform_keys(&:underscore).slice(
'veteran_full_name', 'veteran_date_of_birth',
'veteran_social_security_number', 'gender'
)
}.to_json
end
it 'logs user loa' do
allow(Sentry).to receive(:set_extras)
expect(Sentry).to receive(:set_extras).with(user_loa: nil)
post(enrollment_status_v0_health_care_applications_path, params:, headers:)
end
it 'returns the enrollment status data' do
expect(HealthCareApplication).to receive(:user_icn).and_return('123')
expect(HealthCareApplication).to receive(:enrollment_status).with(
'123', nil
).and_return(loa1_response)
post(enrollment_status_v0_health_care_applications_path, params:, headers:)
expect(response.body).to eq(loa1_response.to_json)
end
context 'when the request is rate limited' do
it 'returns 429' do
expect(HCA::RateLimitedSearch).to receive(
:create_rate_limited_searches
).and_raise(RateLimitedSearch::RateLimitedError)
post(enrollment_status_v0_health_care_applications_path, params:, headers:)
expect(response).to have_http_status(:too_many_requests)
end
end
end
context 'with a signed in user' do
let(:current_user) { build(:user, :loa3) }
let(:params) { { userAttributes: build(:health_care_application).parsed_form }.to_json }
before do
sign_in_as(current_user)
end
context 'with a user with no icn' do
before do
allow_any_instance_of(User).to receive(:icn).and_return(nil)
end
it 'returns 404' do
post(
enrollment_status_v0_health_care_applications_path,
params:,
headers:
)
expect(response).to have_http_status(:not_found)
end
end
context 'with user passed attributes' do
it 'returns the enrollment status data' do
expect(HealthCareApplication).to receive(:enrollment_status).with(
current_user.icn, true
).and_return(success_response)
post(
enrollment_status_v0_health_care_applications_path,
params:,
headers:
)
expect(response.body).to eq(success_response.to_json)
end
end
context 'without user passed attributes' do
let(:enrolled) { HCA::EnrollmentEligibility::Constants::ENROLLED }
let(:success_response) do
{
application_date: '2018-12-27T00:00:00.000-06:00',
enrollment_date: '2018-12-27T17:15:39.000-06:00',
preferred_facility: '988 - DAYT20',
effective_date: '2019-01-02T21:58:55.000-06:00',
primary_eligibility: 'SC LESS THAN 50%',
priority_group: 'Group 3',
can_submit_financial_info: true,
parsed_status: enrolled
}
end
it 'returns the enrollment status data' do
allow_any_instance_of(User).to receive(:icn).and_return('1013032368V065534')
VCR.use_cassette('hca/ee/lookup_user', erb: true) do
post(enrollment_status_v0_health_care_applications_path)
expect(response.body).to eq(success_response.to_json)
end
end
end
end
end
end
describe 'GET show' do
let(:health_care_application) { create(:health_care_application) }
it 'shows a health care application' do
get(v0_health_care_application_path(id: health_care_application.id))
expect(JSON.parse(response.body)).to eq(
'data' => {
'id' => health_care_application.id.to_s,
'type' => 'health_care_applications',
'attributes' => {
'state' => 'pending',
'form_submission_id' => nil,
'timestamp' => nil
}
}
)
end
end
describe 'GET facilities' do
it 'triggers HCA::StdInstitutionImportJob when the HealthFacility table is empty' do
HealthFacility.delete_all
import_job = instance_double(HCA::StdInstitutionImportJob)
expect(HCA::StdInstitutionImportJob).to receive(:new).and_return(import_job)
expect(import_job).to receive(:import_facilities).with(run_sync: true)
get(facilities_v0_health_care_applications_path(state: 'OH'))
end
it 'does not trigger HCA::StdInstitutionImportJob when HealthFacility table is populated' do
create(:health_facility, name: 'Test Facility', station_number: '123', postal_name: 'OH')
expect(HCA::StdInstitutionImportJob).not_to receive(:new)
get(facilities_v0_health_care_applications_path(state: 'OH'))
end
it 'responds with serialized facilities data for supported facilities' do
mock_facilities = [
{ name: 'My VA Facility', station_number: '123', postal_name: 'OH' },
{ name: 'A VA Facility', station_number: '222', postal_name: 'OH' },
{ name: 'My Other VA Facility', station_number: '231', postal_name: 'NH' }
]
mock_facilities.each { |attrs| create(:health_facility, attrs) }
get(facilities_v0_health_care_applications_path(state: 'OH'))
expect(response).to have_http_status(:ok)
expect(response.parsed_body).to contain_exactly({
'id' => mock_facilities[0][:station_number],
'name' => mock_facilities[0][:name]
}, {
'id' => mock_facilities[1][:station_number],
'name' => mock_facilities[1][:name]
})
end
end
describe 'POST create' do
subject do
post(
v0_health_care_applications_path,
params: params.to_json,
headers:
)
end
context 'with invalid params' do
before do
allow(Settings.sentry).to receive(:dsn).and_return('asdf')
end
let(:params) do
{
form: test_veteran.except('privacyAgreementAccepted').to_json
}
end
it 'shows the validation errors' do
subject
expect(response).to have_http_status(:unprocessable_entity)
expect(
JSON.parse(response.body)['errors'][0]['detail'].include?(
'form - object at root is missing required properties: privacyAgreementAccepted'
)
).to be(true)
end
end
context 'with valid params' do
let(:params) do
{
form: test_veteran.to_json
}
end
def self.expect_async_submit
it 'submits async' do
subject
body = JSON.parse(response.body)
expect(body).to eq(
'data' => {
'id' => HealthCareApplication.last.id.to_s,
'type' => 'health_care_applications',
'attributes' => {
'state' => 'pending',
'formSubmissionId' => nil,
'timestamp' => nil
}
}
)
end
end
context 'anonymously' do
let(:body) do
{
'formSubmissionId' => 436_426_165,
'timestamp' => '2024-08-20T12:08:06.729-05:00',
'success' => true
}
end
context 'with an email set' do
before do
expect(HealthCareApplication).to receive(:user_icn).and_return('123')
end
expect_async_submit
end
context 'with no email set' do
before do
test_veteran.delete('email')
end
it 'increments statsd' do
expect { subject }.to trigger_statsd_increment('api.1010ez.submission_attempt')
end
context 'with a short form submission' do
before do
test_veteran.delete('lastServiceBranch')
end
it 'increments statsd' do
expect { subject }.to trigger_statsd_increment('api.1010ez.submission_attempt_short_form')
end
end
it 'renders success', run_at: '2017-01-31' do
expect(HealthCareApplication).to receive(:user_icn).twice.and_return('123')
VCR.use_cassette('hca/submit_anon', match_requests_on: [:body]) do
subject
expect(JSON.parse(response.body)).to eq(body)
end
end
end
end
context 'while authenticated', :skip_mvi do
let!(:in_progress_form) { create(:in_progress_form, user_uuid: current_user.uuid, form_id: '1010ez') }
let(:current_user) { build(:user, :mhv) }
let(:body) do
{
'formSubmissionId' => 436_426_340,
'timestamp' => '2024-08-20T12:26:48.275-05:00',
'success' => true
}
end
before do
sign_in_as(current_user)
test_veteran.delete('email')
end
it 'renders success and enqueues job to delete InProgressForm', run_at: '2017-01-31' do
VCR.use_cassette('hca/submit_auth', match_requests_on: [:body]) do
expect_any_instance_of(HealthCareApplication).to receive(:prefill_fields)
expect(DeleteInProgressFormJob).to receive(:perform_in).with(
5.minutes,
'1010ez',
current_user.uuid
)
subject
expect(JSON.parse(response.body)).to eq(body)
end
end
end
context 'with an invalid discharge date' do
let(:discharge_date) { Time.zone.today + 181.days }
let(:params) do
test_veteran['lastDischargeDate'] = discharge_date.strftime('%Y-%m-%d')
test_veteran.delete('email')
{
form: test_veteran.to_json
}
end
let(:body) do
{
'errors' => [
{
'title' => 'Invalid field value',
'detail' => "\"#{discharge_date.strftime('%Y-%m-%d')}\" is not a valid value for \"lastDischargeDate\"",
'code' => '103',
'status' => '400'
}
]
}
end
it 'raises an invalid field value error' do
expect(HealthCareApplication).to receive(:user_icn).twice.and_return('123')
VCR.use_cassette('hca/submit_anon', match_requests_on: [:body]) do
subject
expect(JSON.parse(response.body)).to eq(body)
end
end
end
context 'when hca service raises an error' do
before do
test_veteran.delete('email')
allow_any_instance_of(HCA::Service).to receive(:submit_form) do
raise error
end
end
context 'with a validation error' do
let(:error) { HCA::SOAPParser::ValidationError.new }
it 'renders error message' do
expect(HealthCareApplication).to receive(:user_icn).twice.and_return('123')
subject
expect(response).to have_http_status(:unprocessable_entity)
expect(JSON.parse(response.body)).to eq(
'errors' => [
{
'title' => 'Operation failed',
'detail' => 'Validation error',
'code' => 'HCA422',
'status' => '422'
}
]
)
end
end
context 'with a SOAP error' do
let(:error) { Common::Client::Errors::HTTPError.new('error message') }
before do
allow(Settings.sentry).to receive(:dsn).and_return('asdf')
end
it 'renders error message' do
expect(HealthCareApplication).to receive(:user_icn).twice.and_return('123')
subject
expect(response).to have_http_status(:bad_request)
expect(JSON.parse(response.body)).to eq(
'errors' => [
{
'title' => 'Operation failed',
'detail' => 'error message',
'code' => 'VA900',
'status' => '400'
}
]
)
end
end
end
context 'with an arbitrary medical facility ID' do
let(:current_user) { create(:user) }
let(:params) do
test_veteran['vaMedicalFacility'] = '000'
{
form: test_veteran.to_json
}
end
let(:body) do
{
'formSubmissionId' => nil,
'timestamp' => nil,
'state' => 'pending'
}
end
before do
sign_in_as(current_user)
end
it 'does not error on vaMedicalFacility validation' do
subject
expect(JSON.parse(response.body)['errors']).to be_blank
expect(JSON.parse(response.body)['data']['attributes']).to eq(body)
end
end
end
end
describe 'POST /v0/health_care_applications/download_pdf' do
subject do
post('/v0/health_care_applications/download_pdf', params: body, headers:)
end
let(:endpoint) { '/v0/health_care_applications/download_pdf' }
let(:response_pdf) { Rails.root.join 'tmp', 'pdfs', '10-10EZ_from_response.pdf' }
let(:expected_pdf) { Rails.root.join 'spec', 'fixtures', 'pdf_fill', '10-10EZ', 'unsigned', 'simple.pdf' }
let!(:form_data) { get_fixture('pdf_fill/10-10EZ/simple').to_json }
let!(:health_care_application) { build(:health_care_application, form: form_data) }
let(:body) { { form: form_data, asyncCompatible: true }.to_json }
before do
allow(SecureRandom).to receive(:uuid).and_return('saved-claim-guid', 'file-name-uuid')
allow(HealthCareApplication).to receive(:new)
.with(hash_including('form' => form_data))
.and_return(health_care_application)
end
after do
FileUtils.rm_f(response_pdf)
end
it 'returns a completed PDF' do
subject
expect(response).to have_http_status(:ok)
veteran_full_name = health_care_application.parsed_form['veteranFullName']
expected_filename = "10-10EZ_#{veteran_full_name['first']}_#{veteran_full_name['last']}.pdf"
expect(response.headers['Content-Disposition']).to include("filename=\"#{expected_filename}\"")
expect(response.content_type).to eq('application/pdf')
expect(response.body).to start_with('%PDF')
end
it 'ensures the tmp file is deleted when send_data fails' do
allow_any_instance_of(ApplicationController).to receive(:send_data).and_raise(StandardError, 'send_data failed')
subject
expect(response).to have_http_status(:internal_server_error)
expect(
File.exist?('tmp/pdfs/10-10EZ_file-name-uuid.pdf')
).to be(false)
end
it 'ensures the tmp file is deleted when fill_form fails after retries' do
expect(PdfFill::Filler).to receive(:fill_form).exactly(3).times.and_raise(StandardError, 'error filling form')
subject
expect(response).to have_http_status(:internal_server_error)
expect(
File.exist?('tmp/pdfs/10-10EZ_file-name-uuid.pdf')
).to be(false)
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/search_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'support/error_details'
Rspec.describe 'V0::Search', type: :request do
include SchemaMatchers
include ErrorDetails
let(:inflection_header) { { 'X-Key-Inflection' => 'camel' } }
before do
Flipper.disable(:search_use_v2_gsa)
end
describe 'GET /v0/search' do
context 'with a 200 response' do
it 'matches the search schema', :aggregate_failures do
VCR.use_cassette('search/success') do
get '/v0/search', params: { query: 'benefits' }
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('search')
end
end
it 'matches the search schema when camel-inflected', :aggregate_failures do
VCR.use_cassette('search/success') do
get '/v0/search', params: { query: 'benefits' }, headers: inflection_header
expect(response).to have_http_status(:ok)
expect(response).to match_camelized_response_schema('search')
end
end
it 'returns an array of hash search results in its body', :aggregate_failures do
VCR.use_cassette('search/success') do
get '/v0/search', params: { query: 'benefits' }
body = JSON.parse response.body
results = body.dig('data', 'attributes', 'body', 'web', 'results')
result = results.first
expect(results.class).to eq Array
expect(result.class).to eq Hash
expect(result.keys).to contain_exactly 'title', 'url', 'snippet', 'publication_date'
end
end
end
context 'with an empty query string' do
it 'matches the errors schema', :aggregate_failures do
VCR.use_cassette('search/empty_query') do
get '/v0/search', params: { query: '' }
expect(response).to have_http_status(:bad_request)
expect(response).to match_response_schema('errors')
end
end
it 'matches the errors schema when camel-inflected', :aggregate_failures do
VCR.use_cassette('search/empty_query') do
get '/v0/search', params: { query: '' }, headers: inflection_header
expect(response).to have_http_status(:bad_request)
expect(response).to match_camelized_response_schema('errors')
end
end
end
context 'with un-sanitized parameters' do
it 'sanitizes the input, stripping all tags and attributes that are not allowlisted' do
VCR.use_cassette('search/success') do
dirty_params = '<script>alert(document.cookie);</script>'
sanitized_params = 'alert(document.cookie);'
expect(Search::Service).to receive(:new).with(sanitized_params, '2')
get '/v0/search', params: { query: dirty_params, page: 2 }
end
end
end
context 'with pagination' do
let(:query_term) { 'benefits' }
context "the endpoint's response" do
it 'returns pagination meta data', :aggregate_failures do
VCR.use_cassette('search/page_1') do
get '/v0/search', params: { query: query_term, page: 1 }
pagination = pagination_for(response)
expect(pagination['current_page']).to be_present
expect(pagination['per_page']).to be_present
expect(pagination['total_pages']).to be_present
expect(pagination['total_entries']).to be_present
end
end
context 'when a specific page number is requested' do
it 'current_page should be equal to the requested page number' do
VCR.use_cassette('search/page_2') do
get '/v0/search', params: { query: query_term, page: 2 }
pagination = pagination_for(response)
expect(pagination['current_page']).to eq 2
end
end
end
end
context 'when the endpoint is being called' do
context 'with a page' do
it 'passes the page request to the search service object' do
expect(Search::Service).to receive(:new).with(query_term, '2')
get '/v0/search', params: { query: query_term, page: 2 }
end
end
context 'with no page present' do
it 'passes page=nil to the search service object' do
expect(Search::Service).to receive(:new).with(query_term, nil)
get '/v0/search', params: { query: query_term }
end
end
end
end
end
end
def pagination_for(response)
body = JSON.parse response.body
body.dig('meta', 'pagination')
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/upload_supporting_evidence_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::UploadSupportingEvidence', type: :request do
include SchemaMatchers
let(:user) { build(:disabilities_compensation_user) }
let(:pdf_file) do
fixture_file_upload('doctors-note.pdf', 'application/pdf')
end
let(:encrypted_pdf_file) do
fixture_file_upload('password_is_test.pdf', 'application/pdf')
end
before do
sign_in_as(user)
end
describe 'Post /v0/upload_supporting_evidence' do
context 'with valid parameters' do
it 'returns a 200 and an upload guid' do
post '/v0/upload_supporting_evidence',
params: { supporting_evidence_attachment: { file_data: pdf_file } }
expect(response).to have_http_status(:ok)
sea = SupportingEvidenceAttachment.last
expect(JSON.parse(response.body)['data']['attributes']['guid']).to eq sea.guid
expect(sea.get_file&.read).not_to be_nil
end
end
context 'with valid encrypted parameters' do
it 'returns a 200 and an upload guid' do
post '/v0/upload_supporting_evidence',
params: { supporting_evidence_attachment: { file_data: encrypted_pdf_file, password: 'test' } }
expect(response).to have_http_status(:ok)
sea = SupportingEvidenceAttachment.last
expect(JSON.parse(response.body)['data']['attributes']['guid']).to eq sea.guid
expect(sea.get_file&.read).not_to be_nil
end
it 'returns a 422 for a pdf with an incorrect password' do
post '/v0/upload_supporting_evidence',
params: { supporting_evidence_attachment: { file_data: encrypted_pdf_file, password: 'bad pwd' } }
expect(response).to have_http_status(:unprocessable_entity)
err = JSON.parse(response.body)['errors'][0]
expect(err['title']).to eq 'Unprocessable Entity'
end
it 'returns a 200 for a pdf with a password that was not encrypted' do
post '/v0/upload_supporting_evidence',
params: { supporting_evidence_attachment: { file_data: pdf_file, password: 'unnecessary' } }
expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body)['data']['attributes']['guid']).to eq SupportingEvidenceAttachment.last.guid
end
it 'returns a 422 for a malformed pdf' do
post '/v0/upload_supporting_evidence',
params: { supporting_evidence_attachment: { file_data: fixture_file_upload('malformed-pdf.pdf') } }
expect(response).to have_http_status(:unprocessable_entity)
err = JSON.parse(response.body)['errors'][0]
expect(err['title']).to eq 'Unprocessable Entity'
expect(err['detail']).to eq I18n.t('errors.messages.uploads.pdf.invalid')
end
it 'returns a 422 for an unallowed file type' do
post '/v0/upload_supporting_evidence',
params: { supporting_evidence_attachment:
{ file_data: fixture_file_upload('invalid_idme_cert.crt') } }
expect(response).to have_http_status(:unprocessable_entity)
err = JSON.parse(response.body)['errors'][0]
expect(err['title']).to eq 'Unprocessable Entity'
expect(err['detail']).to eq(
I18n.t('errors.messages.extension_allowlist_error',
extension: '"crt"',
allowed_types: SupportingEvidenceAttachmentUploader.new('a').extension_allowlist.join(', '))
)
end
it 'returns a 422 for a file that is too small' do
post '/v0/upload_supporting_evidence',
params: { supporting_evidence_attachment:
{ file_data: fixture_file_upload('empty_file.txt') } }
expect(response).to have_http_status(:unprocessable_entity)
err = JSON.parse(response.body)['errors'][0]
expect(err['title']).to eq 'Unprocessable Entity'
expect(err['detail']).to eq(I18n.t('errors.messages.min_size_error', min_size: '1 Byte'))
end
end
context 'with invalid parameters' do
it 'returns a 400 with no parameters' do
post '/v0/upload_supporting_evidence', params: nil
expect(response).to have_http_status(:bad_request)
end
it 'returns a 400 with no file_data' do
post '/v0/upload_supporting_evidence', params: { supporting_evidence_attachment: {} }
expect(response).to have_http_status(:bad_request)
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/caregivers_assistance_claims_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'lighthouse/facilities/v1/client'
RSpec.describe 'V0::CaregiversAssistanceClaims', type: :request do
let(:uri) { 'http://localhost:3000' }
let(:headers) do
{
'ACCEPT' => 'application/json',
'CONTENT_TYPE' => 'application/json',
'HTTP_X_KEY_INFLECTION' => 'camel'
}
end
let(:build_valid_form_submission) { -> { VetsJsonSchema::EXAMPLES['10-10CG'].clone } }
let(:get_schema) { -> { VetsJsonSchema::SCHEMAS['10-10CG'].clone } }
before do
allow_any_instance_of(Form1010cg::Auditor).to receive(:record)
allow_any_instance_of(Form1010cg::Auditor).to receive(:record_caregivers)
allow(Rails.logger).to receive(:error)
end
describe 'POST /v0/caregivers_assistance_claims' do
subject do
post('/v0/caregivers_assistance_claims', params: body, headers:)
end
let(:valid_form_data) { get_fixture('pdf_fill/10-10CG/simple').to_json }
let(:invalid_form_data) { '{}' }
let(:claim) { {} }
before do
allow(SavedClaim::CaregiversAssistanceClaim).to receive(:new)
.and_return(claim) # Ensure the same claim instance is used
end
context 'when the claim is valid' do
let(:body) { { caregivers_assistance_claim: { form: valid_form_data } }.to_json }
let(:claim) { build(:caregivers_assistance_claim, form: valid_form_data) }
before do
allow_any_instance_of(Form1010cg::Service).to receive(:assert_veteran_status)
allow(Form1010cg::SubmissionJob).to receive(:perform_async)
end
context 'assert_veteran_status is successful' do
it 'creates a new claim, enqueues a submission job, and returns claim id' do
expect_any_instance_of(Form1010cg::Auditor).to receive(:record).with(:submission_attempt)
expect_any_instance_of(Form1010cg::Auditor).to receive(:record_caregivers).with(claim)
expect { subject }.to change(SavedClaim::CaregiversAssistanceClaim, :count).by(1)
expect(Form1010cg::SubmissionJob).to have_received(:perform_async).with(claim.id)
expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body)['data']['id']).to eq(SavedClaim::CaregiversAssistanceClaim.last.id.to_s)
expect(JSON.parse(response.body)['data']['type']).to eq('claim')
end
context 'when an unexpected error occurs saving claim' do
let(:error_message) { 'Some unexpected error' }
before do
allow(claim).to receive(:save!).and_raise(StandardError.new(error_message))
end
it 'logs the error and re-raises it' do
expect(Rails.logger).to receive(:error).with(
'CaregiverAssistanceClaim: error submitting claim',
{ saved_claim_guid: claim.guid, error: kind_of(StandardError) }
)
subject
expect(response).to have_http_status(:internal_server_error)
end
end
end
context 'assert_veteran_status error' do
before do
allow_any_instance_of(Form1010cg::Service).to receive(
:assert_veteran_status
).and_raise(Form1010cg::Service::InvalidVeteranStatus)
end
it 'returns backend service exception' do
expect(Rails.logger).not_to receive(:error).with(
'CaregiverAssistanceClaim: error submitting claim',
{ saved_claim_guid: claim.guid, error: instance_of(Form1010cg::Service::InvalidVeteranStatus) }
)
subject
expect(response).to have_http_status(:service_unavailable)
expect(JSON.parse(response.body)['errors'][0]['detail']).to eq(
'Backend Service Outage'
)
end
end
end
context 'when the claim is invalid' do
let(:body) { { caregivers_assistance_claim: { form: invalid_form_data } }.to_json }
let(:claim) { build(:caregivers_assistance_claim, form: invalid_form_data) }
before do
allow(PersonalInformationLog).to receive(:create!)
end
it 'logs the error and returns unprocessable entity' do
expect_any_instance_of(Form1010cg::Auditor).to receive(:record).with(:submission_attempt)
expect_any_instance_of(Form1010cg::Auditor).to receive(:record).with(
:submission_failure_client_data,
{
claim_guid: claim.guid,
errors: [
' object at root is missing required properties: primaryCaregiver',
' object at root is missing required properties: secondaryCaregiverOne',
' object at root is missing required properties: veteran'
]
}
)
expect(Rails.logger).not_to receive(:error).with(
'CaregiverAssistanceClaim: error submitting claim',
{ saved_claim_guid: claim.guid,
error: instance_of(Common::Exceptions::ValidationErrors) }
)
subject
expect(PersonalInformationLog).to have_received(:create!).with(
data: { form: claim.parsed_form },
error_class: '1010CGValidationError'
)
expect(response).to have_http_status(:unprocessable_entity)
res_body = JSON.parse(response.body)
expected_errors = [
{ title: ' object at root is missing required properties: primaryCaregiver',
detail: ' - object at root is missing required properties: primaryCaregiver',
code: '100',
source: { pointer: 'data/attributes/' },
status: '422' },
{ title: ' object at root is missing required properties: secondaryCaregiverOne',
detail: ' - object at root is missing required properties: secondaryCaregiverOne',
code: '100',
source: { pointer: 'data/attributes/' },
status: '422' },
{ title: ' object at root is missing required properties: veteran',
detail: ' - object at root is missing required properties: veteran',
code: '100',
source: { pointer: 'data/attributes/' },
status: '422' }
]
expect(res_body['errors']).to be_present
expect(res_body['errors'].size).to eq(expected_errors.size)
expected_errors.each_with_index do |expected_error, index|
actual_error = res_body['errors'][index]
expect(actual_error['title']).to include(expected_error[:title])
expect(actual_error['code']).to eq(expected_error[:code])
expect(actual_error['status']).to eq(expected_error[:status])
end
end
end
context 'when an unexpected error' do
let(:body) { { caregivers_assistance_claim: { form: valid_form_data } }.to_json }
let(:claim) { build(:caregivers_assistance_claim, form: valid_form_data) }
let(:error_message) { 'Some unexpected error' }
before do
allow(claim).to receive(:valid?).and_raise(StandardError.new(error_message))
end
it 'logs the error and re-raises it' do
expect(Rails.logger).to receive(:error).with(
'CaregiverAssistanceClaim: error submitting claim',
{ saved_claim_guid: claim.guid, error: kind_of(StandardError) }
)
subject
expect(response).to have_http_status(:internal_server_error)
end
end
context 'when missing params: caregivers_assistance_claim' do
let(:body) { {}.to_json }
it 'logs the error and re-raises it' do
expect_any_instance_of(Form1010cg::Auditor).to receive(:record).with(:submission_attempt)
expect_any_instance_of(Form1010cg::Auditor).to receive(:record).with(
:submission_failure_client_data,
errors: ['param is missing or the value is empty: caregivers_assistance_claim']
)
subject
end
end
context 'when missing params: form' do
let(:body) { { caregivers_assistance_claim: { form: nil } }.to_json }
it 'logs the error and re-raises it' do
expect_any_instance_of(Form1010cg::Auditor).to receive(:record).with(:submission_attempt)
expect_any_instance_of(Form1010cg::Auditor).to receive(:record).with(
:submission_failure_client_data,
errors: ['param is missing or the value is empty: form']
)
subject
end
end
end
describe 'POST /v0/caregivers_assistance_claims/download_pdf' do
subject do
post('/v0/caregivers_assistance_claims/download_pdf', params: body, headers:)
end
before do
allow(SecureRandom).to receive(:uuid).and_return('saved-claim-guid', 'file-name-uuid')
expect(SavedClaim::CaregiversAssistanceClaim).to receive(:new).with(
form: form_data
).and_return(claim)
end
let(:endpoint) { '/v0/caregivers_assistance_claims/download_pdf' }
let(:response_pdf) { Rails.root.join 'tmp', 'pdfs', '10-10CG_from_response.pdf' }
let(:expected_pdf) { Rails.root.join 'spec', 'fixtures', 'pdf_fill', '10-10CG', 'unsigned', 'simple.pdf' }
let(:form_data) { get_fixture('pdf_fill/10-10CG/simple').to_json }
let(:claim) { build(:caregivers_assistance_claim, form: form_data) }
let(:body) { { caregivers_assistance_claim: { form: form_data } }.to_json }
after do
FileUtils.rm_f(response_pdf)
end
it 'returns a completed PDF' do
expect_any_instance_of(Form1010cg::Auditor).to receive(:record).with(:pdf_download)
subject
veteran_full_name = claim.veteran_data['fullName']
expected_filename = "10-10CG_#{veteran_full_name['first']}_#{veteran_full_name['last']}.pdf"
expect(response).to have_http_status(:ok)
expect(response.headers['Content-Disposition']).to include("filename=\"#{expected_filename}\"")
expect(response.headers['Content-Type']).to eq('application/pdf')
expect(response.body).to start_with('%PDF')
expect(
File.exist?('tmp/pdfs/10-10CG_file-name-uuid.pdf')
).to be(false)
end
it 'ensures the tmp file is deleted when send_data fails' do
allow_any_instance_of(ApplicationController).to receive(:send_data).and_raise(StandardError, 'send_data failed')
expect_any_instance_of(Form1010cg::Auditor).to receive(:record).with(:pdf_download)
subject
expect(response).to have_http_status(:internal_server_error)
expect(
File.exist?('tmp/pdfs/10-10CG_file-name-uuid.pdf')
).to be(false)
end
it 'ensures the tmp file is deleted when fill_form fails after retries' do
allow(PdfFill::Filler).to receive(:fill_form).and_raise(StandardError, 'error filling form')
expect(claim).to receive(:to_pdf).exactly(3).times.and_raise(StandardError, 'error filling form')
expect_any_instance_of(ApplicationController).not_to receive(:send_data)
expect_any_instance_of(Form1010cg::Auditor).not_to receive(:record).with(:pdf_download)
subject
expect(response).to have_http_status(:internal_server_error)
expect(
File.exist?('tmp/pdfs/10-10CG_file-name-uuid.pdf')
).to be(false)
end
end
describe 'POST /v0/caregivers_assistance_claims/facilities' do
subject do
post('/v0/caregivers_assistance_claims/facilities', params: params.to_json, headers:)
end
let(:headers) do
{
'ACCEPT' => 'application/json',
'CONTENT_TYPE' => 'application/json'
}
end
let(:unmodified_params) do
{
zip: '90210',
state: 'CA',
lat: 34.0522,
long: -118.2437,
radius: 50,
visn: '1',
type: '1',
mobile: true,
page: 1,
per_page: 10,
services: ['1'],
bbox: [2]
}
end
let(:params) do
unmodified_params.merge(facility_ids: 'vha_123,vha_456')
end
let(:mock_facility_response) do
{
'data' => [
{ 'id' => 'vha_123', 'attributes' => { 'name' => 'Facility 1' } },
{ 'id' => 'vha_456', 'attributes' => { 'name' => 'Facility 2' } }
]
}
end
let(:lighthouse_service) { double('FacilitiesApi::V2::Lighthouse::Client') }
before do
allow(FacilitiesApi::V2::Lighthouse::Client).to receive(:new).and_return(lighthouse_service)
allow(lighthouse_service).to receive(:get_paginated_facilities).and_return(mock_facility_response)
end
it 'returns the response as JSON' do
subject
expect(response).to have_http_status(:ok)
expect(response.body).to eq(mock_facility_response.to_json)
end
it 'calls the Lighthouse facilities service with the permitted params' do
subject
expected_params = unmodified_params.merge(facilityIds: 'vha_123,vha_456')
expect(lighthouse_service).to have_received(:get_paginated_facilities)
.with(expected_params)
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/search_typeahead_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'support/error_details'
require 'uri'
Rspec.describe 'V0::SearchTypeahead', type: :request do
include ErrorDetails
describe 'GET /v0/search_typeahead' do
context 'on a successful get' do
it 'has an array of responses', :aggregate_failures do
VCR.use_cassette('search_typeahead/success') do
get '/v0/search_typeahead', params: { query: 'ebenefits' }
expect(response).to have_http_status(:ok)
# rubocop:disable Layout/LineLength
expect(response.body).to include '["ebenefits direct deposit","ebenefits disability compensation","ebenefits update contact information","ebenefits your records","ebenefits"]'
# rubocop:enable Layout/LineLength
end
end
end
context 'with an empty string query' do
it 'has an empty response body', :aggregate_failures do
VCR.use_cassette('search_typeahead/missing_query') do
get '/v0/search_typeahead', params: { query: '' }
expect(response).to have_http_status(:ok)
expect(response.body).to eq ''
end
end
it 'has an null response body', :aggregate_failures do
VCR.use_cassette('search_typeahead/missing_query') do
get '/v0/search_typeahead', params: { query: nil }
expect(response).to have_http_status(:ok)
expect(response.body).to eq ''
end
end
end
context 'when a timeout error occurs' do
before do
allow_any_instance_of(SearchTypeahead::Service).to receive(:suggestions).and_return(
OpenStruct.new(body: { error: 'The request timed out. Please try again.' }.to_json, status: 504)
)
end
it 'returns a 504 status with a timeout error message' do
get '/v0/search_typeahead', params: { query: 'ebenefits' }
expect(response).to have_http_status(:gateway_timeout)
parsed = JSON.parse(response.body)
expect(parsed['error']).to eq 'The request timed out. Please try again.'
end
end
context 'when a connection error occurs' do
before do
allow_any_instance_of(SearchTypeahead::Service).to receive(:suggestions).and_return(
OpenStruct.new(body: { error: 'Unable to connect to the search service. Please try again later.' }.to_json,
status: 502)
)
end
it 'returns a 502 status with a connection error message' do
get '/v0/search_typeahead', params: { query: 'ebenefits' }
expect(response).to have_http_status(:bad_gateway)
parsed = JSON.parse(response.body)
expect(parsed['error']).to eq 'Unable to connect to the search service. Please try again later.'
end
end
context 'when an unexpected error occurs' do
before do
allow_any_instance_of(SearchTypeahead::Service).to receive(:suggestions).and_return(
OpenStruct.new(body: { error: 'An unexpected error occurred.' }.to_json, status: 500)
)
end
it 'returns a 500 status with an unexpected error message' do
get '/v0/search_typeahead', params: { query: 'ebenefits' }
expect(response).to have_http_status(:internal_server_error)
parsed = JSON.parse(response.body)
expect(parsed['error']).to eq 'An unexpected error occurred.'
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/coe_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'lgy/service'
Rspec.describe 'V0::Coe', type: :request do
context 'when user is signed in' do
let(:user) { create(:evss_user, :loa3, icn: '123498767V234859') }
before { sign_in_as user }
describe 'GET v0/coe/status' do
context 'when determination is eligible and application is 404' do
it 'response code is 200' do
VCR.use_cassette 'lgy/determination_eligible' do
VCR.use_cassette 'lgy/application_not_found' do
get '/v0/coe/status'
expect(response).to have_http_status(:ok)
end
end
end
it 'response is in JSON format' do
VCR.use_cassette 'lgy/determination_eligible' do
VCR.use_cassette 'lgy/application_not_found' do
get '/v0/coe/status'
expect(response.content_type).to eq('application/json; charset=utf-8')
end
end
end
it 'response status key is ELIGIBLE' do
VCR.use_cassette 'lgy/determination_eligible' do
VCR.use_cassette 'lgy/application_not_found' do
get '/v0/coe/status'
json_body = JSON.parse(response.body)
expect(json_body['data']['attributes']).to include 'status' => 'ELIGIBLE'
end
end
end
end
end
describe 'GET v0/coe/download' do
context 'when COE file exists' do
before do
@lgy_service = double('LGY Service')
# Simulate http response object
@res = OpenStruct.new(body: File.read('spec/fixtures/files/lgy_file.pdf'))
allow(@lgy_service).to receive(:get_coe_file).and_return @res
allow_any_instance_of(V0::CoeController).to receive(:lgy_service) { @lgy_service }
end
it 'response code is 200' do
get '/v0/coe/download_coe'
expect(response).to have_http_status(:ok)
end
it 'response is in PDF format' do
get '/v0/coe/download_coe'
expect(response.content_type).to eq('application/pdf')
end
it 'response body is correct' do
get '/v0/coe/download_coe'
expect(response.body).to eq @res.body
end
end
end
describe 'POST v0/coe/document_upload' do
context 'when uploading attachments' do
it 'uploads the file successfully' do
VCR.use_cassette 'lgy/document_upload' do
attachments = {
'files' => [{
'file' => Base64.encode64(File.read('spec/fixtures/files/lgy_file.pdf')),
'document_type' => 'VA home loan documents',
'file_type' => 'pdf',
'file_name' => 'lgy_file.pdf'
}]
}
post('/v0/coe/document_upload', params: attachments)
expect(response).to have_http_status :ok
expect(response.body).to eq '201'
end
end
end
context 'when receiving 504 from LGY post_document' do
it 'adds an attachment tag to the document\'s description' do
VCR.use_cassette 'lgy/document_upload_504' do
attachments = {
'files' => [{
'file' => Base64.encode64(File.read('spec/fixtures/files/lgy_file.pdf')),
'document_type' => 'VA home loan documents',
'file_type' => 'pdf',
'file_name' => 'lgy_file.pdf'
}]
}
expect(Rails.logger).to receive(:info)
post('/v0/coe/document_upload', params: attachments)
expect(response).to have_http_status(:server_error)
end
end
end
it 'adds an attachment tag to the document\'s description' do
attachments = {
'files' => [{
'file' => Base64.encode64(File.read('spec/fixtures/files/lgy_file.pdf')),
'document_type' => 'VA home loan documents',
'file_type' => 'pdf',
'file_name' => 'lgy_file.pdf'
}]
}
expected_payload = {
'documentType' => 'pdf',
'description' => 'VA home loan documents',
'contentsBase64' => Base64.encode64(File.read('spec/fixtures/files/lgy_file.pdf')),
'fileName' => 'lgy_file.pdf'
}
expected_response = double(:fake_response, status: 201)
expect_any_instance_of(LGY::Service).to receive(:post_document).with(payload: expected_payload)
.and_return(expected_response)
post('/v0/coe/document_upload', params: attachments)
expect(response).to have_http_status(:ok)
expect(response.body).to eq '201'
end
end
describe 'GET v0/coe/document_download' do
context 'when document exists' do
before do
@lgy_service = double('LGY Service')
# Simulate http response object
@res = OpenStruct.new(body: File.read('spec/fixtures/files/lgy_file.pdf'))
lgy_documents_response_body = [{
'id' => 123_456_789,
'document_type' => '705',
'create_date' => 1_670_530_714_000,
'description' => nil,
'mime_type' => 'COE Application First Returned.pdf'
}]
lgy_documents_response = double(:lgy_documents_response, body: lgy_documents_response_body)
allow(@lgy_service).to receive_messages(get_document: @res, get_coe_documents: lgy_documents_response)
allow_any_instance_of(V0::CoeController).to receive(:lgy_service) { @lgy_service }
end
it 'response code is 200' do
get '/v0/coe/document_download/123456789'
expect(response).to have_http_status(:ok)
end
it 'response is in PDF format' do
get '/v0/coe/document_download/123456789'
expect(response.content_type).to eq('application/pdf')
end
it 'response body is correct' do
get '/v0/coe/document_download/123456789'
expect(response.body).to eq @res.body
end
end
context 'requested document id not associated with user' do
before do
lgy_documents_response_body = [{
'id' => 23_929_115,
'document_type' => '252',
'create_date' => 1_670_530_715_000,
'description' => '',
'mime_type' => 'example.png'
}, {
'id' => 10_101_010,
'document_type' => '705',
'create_date' => 1_670_530_714_000,
'description' => nil,
'mime_type' => 'COE Application First Returned.pdf'
}]
lgy_documents_response = double(:lgy_documents_response, body: lgy_documents_response_body)
expect_any_instance_of(LGY::Service).to receive(:get_coe_documents).and_return(lgy_documents_response)
end
it '404s' do
# Note that this ID is not present in lgy_documents_response_body above.
get '/v0/coe/document_download/12341234'
expect(response).to have_http_status(:not_found)
expect(response.content_type).to eq('application/json; charset=utf-8')
expect(response.body).to include('Record not found')
end
end
end
describe 'GET v0/coe/documents' do
it 'returns notification letters only' do
lgy_documents_response_body = [{
'id' => 23_929_115,
'document_type' => 'Veteran Correspondence',
'create_date' => 1_670_530_715_000,
'description' => '',
'mime_type' => 'example.png'
}, {
'id' => 10_101_010,
'document_type' => 'COE Application First Returned',
'create_date' => 1_670_530_714_000,
'description' => nil,
'mime_type' => 'COE Application First Returned.pdf'
}]
lgy_documents_response = double(:lgy_documents_response, body: lgy_documents_response_body)
expect_any_instance_of(LGY::Service).to receive(:get_coe_documents).and_return(lgy_documents_response)
get '/v0/coe/documents'
expected_response_body = {
'data' => {
'attributes' => [{
'id' => 10_101_010,
'document_type' => 'COE Application First Returned',
'create_date' => 1_670_530_714_000,
'description' => nil,
'mime_type' => 'COE Application First Returned.pdf'
}]
}
}.to_json
expect(response.body).to eq(expected_response_body)
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/benefits_claims_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::BenefitsClaims', type: :request do
include SchemaMatchers
let(:user) { create(:user, :loa3, :accountable, :legacy_icn, uuid: 'b2fab2b5-6af0-45e1-a9e2-394347af91ef') }
let(:user_account) { create(:user_account, id: user.uuid) }
let(:claim_id) { 600_383_363 } # This is the claim in the vcr cassettes that we are using
describe 'GET /v0/benefits_claims/failed_upload_evidence_submissions' do
subject do
get '/v0/benefits_claims/failed_upload_evidence_submissions'
end
context 'when the cst_show_document_upload_status is enabled' do
before do
allow(Flipper).to receive(:enabled?).with(
:cst_show_document_upload_status,
instance_of(User)
).and_return(true)
end
context 'when unsuccessful' do
context 'when the user is not signed in' do
it 'returns a status of 401' do
subject
expect(response).to have_http_status(:unauthorized)
end
end
context 'when the user is signed in, but does not have valid credentials' do
let(:invalid_user) { create(:user, :loa3, :accountable, :legacy_icn, participant_id: nil) }
before do
sign_in_as(invalid_user)
end
it 'returns a status of 403' do
subject
expect(response).to have_http_status(:forbidden)
end
end
context 'when the user is signed in and has valid credentials' do
before do
sign_in_and_set_access_token(user)
create(:bd_lh_evidence_submission_failed_type2_error, claim_id:, user_account:)
end
context 'when the ICN is not found' do
it 'returns a status of 404' do
VCR.use_cassette('lighthouse/benefits_claims/show/404_response') do
subject
end
expect(response).to have_http_status(:not_found)
end
end
context 'when there is a gateway timeout' do
it 'returns a status of 504' do
VCR.use_cassette('lighthouse/benefits_claims/show/504_response') do
subject
end
expect(response).to have_http_status(:gateway_timeout)
end
end
context 'when Lighthouse takes too long to respond' do
it 'returns a status of 504' do
allow_any_instance_of(BenefitsClaims::Configuration).to receive(:get).and_raise(Faraday::TimeoutError)
subject
expect(response).to have_http_status(:gateway_timeout)
end
end
end
end
context 'when successful' do
before do
sign_in_and_set_access_token(user)
create(:bd_lh_evidence_submission_success, claim_id:, user_account:)
create(:bd_lh_evidence_submission_failed_type1_error, claim_id:, user_account:)
create(:bd_lh_evidence_submission_failed_type2_error, claim_id:, user_account:)
end
it 'returns an array of only the failed evidence submissions' do
VCR.use_cassette('lighthouse/benefits_claims/show/200_response') do
subject
end
expect(response).to have_http_status(:ok)
parsed_response = JSON.parse(response.body)
expect(parsed_response['data'].size).to eq(2)
expect(parsed_response['data'].first['document_type']).to eq('Birth Certificate')
expect(parsed_response['data'].second['document_type']).to eq('Birth Certificate')
end
context 'when multiple claims are returned for the evidence submission records' do
before do
create(:bd_lh_evidence_submission_failed_type1_error, claim_id: 600_229_972, user_account:)
end
it 'returns evidence submissions for all claims' do
VCR.use_cassette('lighthouse/benefits_claims/show/200_response') do
VCR.use_cassette('lighthouse/benefits_claims/show/200_death_claim_response') do
subject
end
end
expect(response).to have_http_status(:ok)
parsed_response = JSON.parse(response.body)
expect(parsed_response['data'].size).to eq(3)
end
end
context 'when no failed submissions exist' do
before do
EvidenceSubmission.destroy_all
end
it 'returns an empty array' do
VCR.use_cassette('lighthouse/benefits_claims/show/200_response') do
subject
end
expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body)).to eq({ 'data' => [] })
end
end
end
end
context 'when the cst_show_document_upload_status is disabled' do
before do
allow(Flipper).to receive(:enabled?).with(
:cst_show_document_upload_status,
instance_of(User)
).and_return(false)
end
context 'when unsuccessful' do
context 'when the user is not signed in' do
it 'returns a status of 401' do
subject
expect(response).to have_http_status(:unauthorized)
end
end
context 'when the user is signed in, but does not have valid credentials' do
let(:invalid_user) { create(:user, :loa3, :accountable, :legacy_icn, participant_id: nil) }
before do
sign_in_as(invalid_user)
end
it 'returns a status of 403' do
subject
expect(response).to have_http_status(:forbidden)
end
end
context 'when the user is signed in and has valid credentials' do
before do
sign_in_and_set_access_token(user)
end
it 'returns an empty array' do
VCR.use_cassette('lighthouse/benefits_claims/show/200_response') do
subject
end
expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body)).to eq({ 'data' => [] })
end
end
end
context 'when successful' do
before do
sign_in_and_set_access_token(user)
end
it 'returns an empty array' do
VCR.use_cassette('lighthouse/benefits_claims/show/200_response') do
subject
end
expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body)).to eq({ 'data' => [] })
end
end
end
end
def sign_in_and_set_access_token(user)
user.user_account_uuid = user_account.id
user.save!
sign_in_as(user)
token = 'fake_access_token'
allow_any_instance_of(BenefitsClaims::Configuration).to receive(:access_token).and_return(token)
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/evss_claims_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::EVSSClaims', type: :request do
include SchemaMatchers
let(:user) { create(:user, :loa3, edipi: nil) }
let(:evss_user) { create(:evss_user) }
let(:inflection_header) { { 'X-Key-Inflection' => 'camel' } }
context 'for a user without evss attrs' do
it 'returns a 403' do
sign_in_as(user)
profile = build(:mpi_profile, edipi: nil)
stub_mpi(profile)
get '/v0/evss_claims'
expect(response).to have_http_status(:forbidden)
end
end
it 'lists all Claims', run_at: 'Tue, 12 Dec 2017 03:09:06 GMT' do
sign_in_as(evss_user)
VCR.use_cassette('evss/claims/claims', match_requests_on: %i[uri method body]) do
get '/v0/evss_claims'
expect(response).to match_response_schema('evss_claims')
end
end
it 'lists all Claims when camel-inflected', run_at: 'Tue, 12 Dec 2017 03:09:06 GMT' do
sign_in_as(evss_user)
VCR.use_cassette('evss/claims/claims', match_requests_on: %i[uri method body]) do
get '/v0/evss_claims', headers: inflection_header
expect(response).to match_camelized_response_schema('evss_claims')
end
end
context 'for a single claim' do
let!(:claim) do
create(:evss_claim, id: 1, evss_id: 600_118_851,
user_uuid: evss_user.uuid)
end
it 'sets 5103 waiver when requesting a decision' do
sign_in_as(evss_user)
expect do
post '/v0/evss_claims/600118851/request_decision'
end.to change(EVSS::RequestDecision.jobs, :size).by(1)
expect(response).to have_http_status(:accepted)
expect(JSON.parse(response.body)['job_id']).to eq(EVSS::RequestDecision.jobs.first['jid'])
end
it 'shows a single Claim', run_at: 'Wed, 13 Dec 2017 03:28:23 GMT' do
sign_in_as(evss_user)
VCR.use_cassette('evss/claims/claim', match_requests_on: %i[uri method body]) do
get '/v0/evss_claims/600118851'
expect(response).to match_response_schema('evss_claim')
end
end
it 'shows a single Claim when camel-inflected', run_at: 'Wed, 13 Dec 2017 03:28:23 GMT' do
sign_in_as(evss_user)
VCR.use_cassette('evss/claims/claim', match_requests_on: %i[uri method body]) do
get '/v0/evss_claims/600118851', headers: inflection_header
expect(response).to match_camelized_response_schema('evss_claim')
end
end
it 'user cannot access claim of another user' do
sign_in_as(evss_user)
create(:evss_claim, id: 2, evss_id: 189_625,
user_uuid: 'xyz')
# check tagging of EVSSClaimsController.show RecordNotFound error
allow(Sentry).to receive(:set_tags)
expect(Sentry).to receive(:set_tags).with(team: 'benefits-memorial-1')
get '/v0/evss_claims/2'
expect(response).to have_http_status(:not_found)
end
context '5103 waiver has not been submitted yet' do
it 'has waiver_submitted set after requesting a decision' do
sign_in_as(evss_user)
claim.requested_decision = false
claim.save
expect(claim.requested_decision).to be(false)
post '/v0/evss_claims/600118851/request_decision'
expect(claim.reload.requested_decision).to be(true)
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/appeals_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::Appeals', type: :request do
include SchemaMatchers
appeals_endpoint = '/v0/appeals'
before { sign_in_as(user) }
context 'with a loa1 user' do
let(:user) { create(:user, :loa1, ssn: '111223333') }
it 'returns a forbidden error' do
get appeals_endpoint
expect(response).to have_http_status(:forbidden)
end
end
context 'with a loa3 user without a ssn' do
let(:user) { create(:user, :loa1, ssn: nil) }
it 'returns a forbidden error' do
get appeals_endpoint
expect(response).to have_http_status(:forbidden)
end
end
context 'with a loa3 user' do
let(:user) { create(:user, :loa3, ssn: '111223333') }
context 'with a valid response' do
it 'returns a successful response' do
VCR.use_cassette('caseflow/appeals') do
get appeals_endpoint
expect(response).to have_http_status(:ok)
expect(response.body).to be_a(String)
expect(response).to match_response_schema('appeals')
end
end
it 'allows null issue descriptions' do
VCR.use_cassette('caseflow/appeals') do
get appeals_endpoint
expect(response).to have_http_status(:ok)
response_data = JSON.parse(response.body)
# Add a null description to the first issue of the first appeal
response_data['data'].first['attributes']['issues'].first['description'] = nil
# Validate that the modified response still matches the schema
expect(response_data).to match_schema('appeals')
end
end
end
context 'with a not authorized response' do
it 'returns a 502 and logs an error level message' do
VCR.use_cassette('caseflow/not_authorized') do
get appeals_endpoint
expect(response).to have_http_status(:bad_gateway)
expect(response).to match_response_schema('errors')
end
end
end
context 'with a not found response' do
it 'returns a 404 and logs an info level message' do
VCR.use_cassette('caseflow/not_found') do
get appeals_endpoint
expect(response).to have_http_status(:not_found)
expect(response).to match_response_schema('errors')
end
end
end
context 'with an unprocessible entity response' do
it 'returns a 422 and logs an info level message' do
VCR.use_cassette('caseflow/invalid_ssn') do
get appeals_endpoint
expect(response).to have_http_status(:unprocessable_entity)
expect(response).to match_response_schema('errors')
end
end
end
context 'with a server error' do
it 'returns a 502 and logs an error level message' do
VCR.use_cassette('caseflow/server_error') do
get appeals_endpoint
expect(response).to have_http_status(:bad_gateway)
expect(response).to match_response_schema('errors')
end
end
end
context 'with an invalid JSON body in the response' do
it 'returns a 502 and logs an error level message' do
VCR.use_cassette('caseflow/invalid_body') do
get appeals_endpoint
expect(response).to have_http_status(:internal_server_error)
end
end
end
context 'with a null eta' do
it 'returns a successful response' do
VCR.use_cassette('caseflow/appeals_null_eta') do
get appeals_endpoint
expect(response).to have_http_status(:ok)
expect(response.body).to be_a(String)
expect(response).to match_response_schema('appeals')
end
end
end
context 'with no alert details due_date' do
it 'returns a successful response' do
VCR.use_cassette('caseflow/appeals_no_alert_details_due_date') do
get appeals_endpoint
expect(response).to have_http_status(:ok)
expect(response.body).to be_a(String)
expect(response).to match_response_schema('appeals')
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/enrollment_periods_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::EnrollmentPeriods', type: :request do
let(:user) { build(:user, :loa3, icn: '1012667145V762142') }
let(:invalid_user) { build(:user, :loa1) }
describe 'GET /index' do
context 'with valid signed in user' do
before do
sign_in_as(user)
end
it 'returns http success' do
VCR.use_cassette('veteran_enrollment_system/enrollment_periods/get_success',
match_requests_on: %i[uri method body]) do
get '/v0/enrollment_periods'
expect(response).to have_http_status(:success)
expect(response.parsed_body).to eq({ 'enrollment_periods' => [
{ 'startDate' => '2024-03-05',
'endDate' => '2024-03-05' },
{ 'startDate' => '2019-03-05',
'endDate' => '2022-03-05' },
{ 'startDate' => '2010-03-05',
'endDate' => '2015-03-05' }
] })
end
end
it 'returns appropriate error code' do
VCR.use_cassette('veteran_enrollment_system/enrollment_periods/get_not_found',
match_requests_on: %i[uri method body]) do
get '/v0/enrollment_periods'
expect(response).to have_http_status(:not_found)
end
end
end
context 'with invalid user' do
before do
sign_in_as(invalid_user)
end
it 'returns http 403' do
get '/v0/enrollment_periods'
expect(response).to have_http_status(:forbidden)
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/claim_documents_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::ClaimDocuments', type: :request do
before do
allow(Rails.logger).to receive(:info)
allow(Rails.logger).to receive(:error)
allow(Common::VirusScan).to receive(:scan).and_return(true)
allow_any_instance_of(Common::VirusScan).to receive(:scan).and_return(true)
end
context 'with a valid file' do
let(:file) do
fixture_file_upload('doctors-note.pdf')
end
it 'uploads a file' do
VCR.use_cassette('uploads/validate_document') do
params = { file:, form_id: '21P-000' }
expect do
post('/v0/claim_documents', params:)
end.to change(PersistentAttachment, :count).by(1)
expect(response).to have_http_status(:ok)
resp = JSON.parse(response.body)
expect(resp['data']['attributes'].keys.sort).to eq(%w[confirmation_code name size])
expect(PersistentAttachment.last).to be_a(PersistentAttachments::ClaimEvidence)
end
end
it 'uploads a file to the alternate route' do
VCR.use_cassette('uploads/validate_document') do
params = { file:, form_id: '21P-000' }
expect do
post('/v0/claim_attachments', params:)
end.to change(PersistentAttachment, :count).by(1)
expect(response).to have_http_status(:ok)
resp = JSON.parse(response.body)
expect(resp['data']['attributes'].keys.sort).to eq(%w[confirmation_code name size])
expect(PersistentAttachment.last).to be_a(PersistentAttachments::ClaimEvidence)
end
end
it 'logs a successful upload' do
VCR.use_cassette('uploads/validate_document') do
expect(Rails.logger).to receive(:info).with('Creating PersistentAttachment FormID=21P-000', instance_of(Hash))
expect(Rails.logger).to receive(:info).with(
/^Success creating PersistentAttachment FormID=21P-000 AttachmentID=\d+/, instance_of(Hash)
)
expect(Rails.logger).not_to receive(:error).with(
'Error creating PersistentAttachment FormID=21P-000 AttachmentID= Common::Exceptions::ValidationErrors'
)
params = { file:, form_id: '21P-000' }
expect do
post('/v0/claim_documents', params:)
end.to change(PersistentAttachment, :count).by(1)
end
end
end
context 'with an invalid file' do
let(:file) { fixture_file_upload('empty-file.jpg') }
it 'does not upload the file' do
VCR.use_cassette('uploads/validate_document') do
params = { file:, form_id: '21P-000' }
expect do
post('/v0/claim_attachments', params:)
end.not_to change(PersistentAttachment, :count)
expect(response).to have_http_status(:unprocessable_entity)
resp = JSON.parse(response.body)
expect(resp['errors'][0]['detail']).to eq('File size must not be less than 1.0 KB')
end
end
it 'logs the error' do
VCR.use_cassette('uploads/validate_document') do
expect(Rails.logger).to receive(:info).with('Creating PersistentAttachment FormID=21P-000',
hash_including(statsd: 'api.claim_documents.attempt'))
expect(Rails.logger).not_to receive(:info).with(
/^Success creating PersistentAttachment FormID=21P-000 AttachmentID=\d+/
)
expect(Rails.logger).to receive(:error).with(
'Input error creating PersistentAttachment ' \
'FormID=21P-000 AttachmentID= Common::Exceptions::UnprocessableEntity',
instance_of(Hash)
)
params = { file:, form_id: '21P-000' }
post('/v0/claim_attachments', params:)
end
end
end
context 'with a password protected file' do
let(:file) do
fixture_file_upload('password_is_test.pdf')
end
it 'does not raise an error when password is correct' do
VCR.use_cassette('uploads/validate_document') do
params = { file:, form_id: '26-1880', password: 'test' }
post('/v0/claim_attachments', params:)
expect(response).to have_http_status(:ok)
end
end
it 'raises an error when password is incorrect' do
params = { file:, form_id: '26-1880', password: 'bad_password' }
post('/v0/claim_attachments', params:)
expect(response).to have_http_status(:unprocessable_entity)
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/disability_compensation_form_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'lighthouse/auth/client_credentials/service'
require 'lighthouse/service_exception'
require 'disability_compensation/factories/api_provider_factory'
require 'disability_compensation/loggers/monitor'
RSpec.describe 'V0::DisabilityCompensationForm', type: :request do
include SchemaMatchers
let(:user) { build(:disabilities_compensation_user, icn: '123498767V234859') }
let(:headers) { { 'CONTENT_TYPE' => 'application/json' } }
let(:headers_with_camel) { headers.merge('X-Key-Inflection' => 'camel') }
before do
Flipper.disable('disability_compensation_prevent_submission_job')
sign_in_as(user)
end
describe 'Get /v0/disability_compensation_form/rated_disabilities' do
context 'Lighthouse api provider' do
before do
allow_any_instance_of(Auth::ClientCredentials::Service).to receive(:get_token).and_return('blahblech')
end
context 'with a valid 200 lighthouse response' do
it 'matches the rated disabilities schema' do
VCR.use_cassette('lighthouse/veteran_verification/disability_rating/200_response') do
get('/v0/disability_compensation_form/rated_disabilities', params: nil, headers:)
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('rated_disabilities')
end
end
it 'matches the rated disabilities schema when camel-inflected' do
VCR.use_cassette('lighthouse/veteran_verification/disability_rating/200_response') do
get '/v0/disability_compensation_form/rated_disabilities', params: nil, headers: headers_with_camel
expect(response).to have_http_status(:ok)
expect(response).to match_camelized_response_schema('rated_disabilities')
end
end
end
context 'error handling tests' do
cassettes_directory = 'lighthouse/veteran_verification/disability_rating'
Lighthouse::ServiceException::ERROR_MAP.except(422, 499, 501).each_key do |status|
cassette_path = "#{cassettes_directory}/#{status == 404 ? '404_ICN' : status}_response"
it "returns #{status} response" do
expect(test_error(
cassette_path,
status,
headers
)).to be(true)
end
it "returns a #{status} response with camel-inflection" do
expect(test_error(
cassette_path,
status,
headers_with_camel
)).to be(true)
end
end
def test_error(cassette_path, status, headers)
VCR.use_cassette(cassette_path) do
get('/v0/disability_compensation_form/rated_disabilities', params: nil, headers:)
expect(response).to have_http_status(status)
expect(response).to match_response_schema('evss_errors', strict: false)
end
end
end
end
end
describe 'Post /v0/disability_compensation_form/suggested_conditions/:name_part' do
before do
create(:disability_contention_arrhythmia)
create(:disability_contention_arteriosclerosis)
create(:disability_contention_arthritis)
end
let(:conditions) { JSON.parse(response.body)['data'] }
it 'returns matching conditions', :aggregate_failures do
get('/v0/disability_compensation_form/suggested_conditions?name_part=art', params: nil, headers:)
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('suggested_conditions')
expect(conditions.count).to eq 3
end
it 'returns matching conditions with camel-inflection', :aggregate_failures do
get '/v0/disability_compensation_form/suggested_conditions?name_part=art',
params: nil,
headers: headers_with_camel
expect(response).to have_http_status(:ok)
expect(response).to match_camelized_response_schema('suggested_conditions')
expect(conditions.count).to eq 3
end
it 'returns an empty array when no conditions match', :aggregate_failures do
get('/v0/disability_compensation_form/suggested_conditions?name_part=xyz', params: nil, headers:)
expect(response).to have_http_status(:ok)
expect(conditions.count).to eq 0
end
it 'returns a 500 when name_part is missing' do
get('/v0/disability_compensation_form/suggested_conditions', params: nil, headers:)
expect(response).to have_http_status(:bad_request)
end
end
describe 'Post /v0/disability_compensation_form/submit_all_claim' do
before do
VCR.insert_cassette('va_profile/military_personnel/post_read_service_history_200')
VCR.insert_cassette('lighthouse/direct_deposit/show/200_valid')
VCR.insert_cassette('lighthouse/direct_deposit/update/200_valid')
end
after do
VCR.eject_cassette('lighthouse/direct_deposit/update/200_valid')
VCR.eject_cassette('va_profile/military_personnel/post_read_service_history_200')
VCR.eject_cassette('lighthouse/direct_deposit/show/200_valid')
VCR.eject_cassette('lighthouse/direct_deposit/update/200_valid')
end
context 'with a valid 200 evss response' do
let(:jid) { "JID-#{SecureRandom.base64}" }
before do
allow(EVSS::DisabilityCompensationForm::SubmitForm526AllClaim).to receive(:perform_async).and_return(jid)
create(:in_progress_form, form_id: FormProfiles::VA526ez::FORM_ID, user_uuid: user.uuid)
end
context 'with an `all claims` claim' do
let(:all_claims_form) { File.read 'spec/support/disability_compensation_form/all_claims_fe_submission.json' }
it 'matches the rated disabilities schema' do
post('/v0/disability_compensation_form/submit_all_claim', params: all_claims_form, headers:)
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('submit_disability_form')
end
describe 'temp_toxic_exposure_optional_dates_fix' do
# Helper that handles POST + response check + returning the submission form
def post_and_get_submission(payload)
post('/v0/disability_compensation_form/submit_all_claim',
params: JSON.generate(payload),
headers:)
expect(response).to have_http_status(:ok)
Form526Submission.last.form
end
# Helper to build the "optional_xx_dates" mapping
def build_optional_xx_dates
Form526Submission::TOXIC_EXPOSURE_DETAILS_MAPPING.transform_values do |exposures|
if exposures.empty?
{
'description' => 'some description or fallback field',
'startDate' => 'XXXX-03-XX',
'endDate' => 'XXXX-01-XX'
}
else
exposures.index_with do
{
'startDate' => 'XXXX-03-XX',
'endDate' => 'XXXX-01-XX'
}
end
end
end
end
context 'when flipper feature disability_compensation_temp_toxic_exposure_optional_dates_fix is enabled' do
before do
allow(Flipper).to receive(:enabled?)
.with(:disability_compensation_temp_toxic_exposure_optional_dates_fix, anything)
.and_return(true)
# make sure the submission job is triggered even if there are bad dates in the toxic exposure section
expect(EVSS::DisabilityCompensationForm::SubmitForm526AllClaim).to receive(:perform_async).once
end
it 'maximal' do
parsed_payload = JSON.parse(all_claims_form)
# Replace the toxicExposure section with all "XXXX-XX-XX" data
parsed_payload['form526']['toxicExposure'] = build_optional_xx_dates
submission = post_and_get_submission(parsed_payload)
toxic_exposure = submission.dig('form526', 'form526', 'toxicExposure')
toxic_exposure.each do |tek, tev|
tev.each_value do |value|
# Expect all optional date attributes to be removed, leaving an empty hash
# except for otherHerbicideLocations / specifyOtherExposures which keep description
expect(value).to eq({}) unless %w[otherHerbicideLocations specifyOtherExposures].include?(tek)
end
if %w[otherHerbicideLocations specifyOtherExposures].include?(tek)
expect(tev).to eq({ 'description' => 'some description or fallback field' })
end
end
end
it 'minimal' do
parsed_payload = JSON.parse(all_claims_form)
# Only one date is "XXXX-03-XX", the rest are valid
parsed_payload['form526']['toxicExposure']['gulfWar1990Details']['iraq'] = {
'startDate' => 'XXXX-03-XX',
'endDate' => '1991-01-01'
}
submission = post_and_get_submission(parsed_payload)
toxic_exposure = submission.dig('form526', 'form526', 'toxicExposure')
gulf_war_details_iraq = toxic_exposure['gulfWar1990Details']['iraq']
# It should have only removed the malformed startDate
expect(gulf_war_details_iraq).to eq({ 'endDate' => '1991-01-01' })
# The rest remain untouched
gulf_war_details_qatar = toxic_exposure['gulfWar1990Details']['qatar']
expect(gulf_war_details_qatar).to eq({
'startDate' => '1991-02-12',
'endDate' => '1991-06-01'
})
end
end
context 'when flipper feature disability_compensation_temp_toxic_exposure_optional_dates_fix is disabled' do
before do
allow(Flipper).to receive(:enabled?)
.with(:disability_compensation_temp_toxic_exposure_optional_dates_fix, anything)
.and_return(false)
end
it 'fails validation' do
parsed_payload = JSON.parse(all_claims_form)
# Replace the toxicExposure section with all "XXXX-XX-XX" data
parsed_payload['form526']['toxicExposure'] = build_optional_xx_dates
post('/v0/disability_compensation_form/submit_all_claim',
params: JSON.generate(parsed_payload),
headers:)
expect(response).to have_http_status(:unprocessable_entity)
end
end
end
context 'with a lot of VA Facility Treatments' do
let(:parsed_payload) { JSON.parse(all_claims_form) }
let(:large_array_of_treatments) { Array.new(149) { |i| "treatment_#{i + 1}" } }
it 'does not fail to submit' do
parsed_payload['form526']['vaTreatmentFacilities'][0]['treatedDisabilityNames'] = large_array_of_treatments
post('/v0/disability_compensation_form/submit_all_claim', params: JSON.generate(parsed_payload), headers:)
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('submit_disability_form')
expect(Form526Submission.count).to eq(1)
form = Form526Submission.last.form
treatments = form.dig('form526', 'form526', 'treatments')
expect(treatments).not_to be_nil
expect(treatments).not_to be_empty
expect(treatments[0]['treatedDisabilityNames'].size).to eq(149)
end
end
context 'where the startedFormVersion indicator is true' do
it 'creates a submission that includes a toxic exposure component' do
post('/v0/disability_compensation_form/submit_all_claim', params: all_claims_form, headers:)
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('submit_disability_form')
expect(Form526Submission.count).to eq(1)
form = Form526Submission.last.form
expect(form.dig('form526', 'form526', 'startedFormVersion')).not_to be_nil
end
end
context 'where the startedFormVersion indicator is false' do
it 'does not create a submission that includes a toxic exposure component' do
json_object = JSON.parse(all_claims_form)
json_object['form526']['startedFormVersion'] = nil
updated_form = JSON.generate(json_object)
post('/v0/disability_compensation_form/submit_all_claim', params: updated_form, headers:)
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('submit_disability_form')
expect(Form526Submission.count).to eq(1)
form = Form526Submission.last.form
expect(form.dig('form526', 'form526', 'startedFormVersion')).to eq('2019')
end
end
describe 'toxic exposure purge tracking' do
let(:monitor) { instance_double(DisabilityCompensation::Loggers::Monitor) }
let(:parsed_payload) { JSON.parse(all_claims_form) }
before do
allow(DisabilityCompensation::Loggers::Monitor).to receive(:new).and_return(monitor)
allow(monitor).to receive(:track_saved_claim_save_success)
allow(monitor).to receive(:track_526_submission_with_banking_info)
allow(monitor).to receive(:track_526_submission_without_banking_info)
allow(Flipper).to receive(:enabled?)
.with(:disability_526_toxic_exposure_opt_out_data_purge, anything)
.and_return(true)
end
context 'when toxic exposure keys are removed' do
it 'logs the removal' do
# Update InProgressForm with snake_case (Rails transforms save-in-progress to snake_case)
in_progress_form = InProgressForm.form_for_user(FormProfiles::VA526ez::FORM_ID, user)
in_progress_form_data = JSON.parse(in_progress_form.form_data)
in_progress_form_data['toxic_exposure'] = {
'conditions' => { 'arthritis' => true },
'gulf_war_1990' => { 'iraq' => true },
'gulf_war_2001' => { 'djibouti' => true }
}
in_progress_form.update!(form_data: in_progress_form_data.to_json)
# Submit with only gulfWar1990 (gulfWar2001 removed)
parsed_payload['form526']['toxicExposure'] = {
'conditions' => { 'arthritis' => true },
'gulfWar1990' => { 'iraq' => true }
}
expect(monitor).to receive(:track_toxic_exposure_changes).with(
hash_including(
in_progress_form:,
submitted_claim: kind_of(SavedClaim::DisabilityCompensation::Form526AllClaim),
submission: kind_of(Form526Submission)
)
)
post('/v0/disability_compensation_form/submit_all_claim',
params: JSON.generate(parsed_payload),
headers:)
expect(response).to have_http_status(:ok)
end
end
context 'when toxic exposure is completely removed' do
it 'logs the complete removal' do
# Update InProgressForm with snake_case (Rails transforms save-in-progress to snake_case)
in_progress_form = InProgressForm.form_for_user(FormProfiles::VA526ez::FORM_ID, user)
in_progress_form_data = JSON.parse(in_progress_form.form_data)
in_progress_form_data['toxic_exposure'] = {
'conditions' => { 'arthritis' => true },
'gulf_war_1990' => { 'iraq' => true }
}
in_progress_form.update!(form_data: in_progress_form_data.to_json)
# Submit without any toxic exposure
parsed_payload['form526'].delete('toxicExposure')
expect(monitor).to receive(:track_toxic_exposure_changes)
post('/v0/disability_compensation_form/submit_all_claim',
params: JSON.generate(parsed_payload),
headers:)
expect(response).to have_http_status(:ok)
end
end
context 'when toxic exposure is unchanged' do
it 'does not log' do
# Update InProgressForm with snake_case (Rails transforms save-in-progress to snake_case)
in_progress_form = InProgressForm.form_for_user(FormProfiles::VA526ez::FORM_ID, user)
in_progress_form_data = JSON.parse(in_progress_form.form_data)
in_progress_form_data['toxic_exposure'] = {
'conditions' => { 'arthritis' => true },
'gulf_war_1990' => { 'iraq' => true }
}
in_progress_form.update!(form_data: in_progress_form_data.to_json)
# Submit with same toxic exposure
parsed_payload['form526']['toxicExposure'] = {
'conditions' => { 'arthritis' => true },
'gulfWar1990' => { 'iraq' => true }
}
# track_toxic_exposure_changes will still be called, but monitor.submit_event should not
# (the method returns early if no changes)
allow(monitor).to receive(:track_toxic_exposure_changes)
expect(monitor).not_to receive(:submit_event)
post('/v0/disability_compensation_form/submit_all_claim',
params: JSON.generate(parsed_payload),
headers:)
expect(response).to have_http_status(:ok)
end
end
context 'when no toxic exposure in InProgressForm' do
it 'does not log' do
# Update InProgressForm to have no toxic exposure (delete snake_case key)
in_progress_form = InProgressForm.form_for_user(FormProfiles::VA526ez::FORM_ID, user)
in_progress_form_data = JSON.parse(in_progress_form.form_data)
in_progress_form_data.delete('toxic_exposure')
in_progress_form_data.delete('toxicExposure') # Delete both just in case
in_progress_form.update!(form_data: in_progress_form_data.to_json)
allow(monitor).to receive(:track_toxic_exposure_changes)
expect(monitor).not_to receive(:submit_event)
post('/v0/disability_compensation_form/submit_all_claim',
params: all_claims_form,
headers:)
expect(response).to have_http_status(:ok)
end
end
context 'when flipper flag is disabled' do
it 'does not call track_toxic_exposure_changes' do
# Disable toxic exposure purge flag to prevent logging
allow(Flipper).to receive(:enabled?)
.with(:disability_526_toxic_exposure_opt_out_data_purge, anything)
.and_return(false)
expect(monitor).not_to receive(:track_toxic_exposure_changes)
post('/v0/disability_compensation_form/submit_all_claim',
params: all_claims_form,
headers:)
expect(response).to have_http_status(:ok)
end
end
context 'when logging raises an error' do
it 'does not fail the submission' do
# Simulate an error in the logging method
allow(monitor).to receive(:track_toxic_exposure_changes).and_raise(StandardError, 'Logging failed')
# Expect the error to be logged
expect(Rails.logger).to receive(:error).with(
'Error logging toxic exposure changes',
hash_including(
user_uuid: user.uuid,
error: 'Logging failed'
)
)
# Submission should still succeed
post('/v0/disability_compensation_form/submit_all_claim',
params: all_claims_form,
headers:)
expect(response).to have_http_status(:ok)
end
end
end
describe 'toxic exposure allowlist integration test' do
it 'does not filter out allowlisted toxic exposure tracking keys in the full end-to-end flow' do
# Parse the payload
parsed_payload = JSON.parse(all_claims_form)
# Set up InProgressForm with toxic exposure data
in_progress_form = InProgressForm.form_for_user(FormProfiles::VA526ez::FORM_ID, user)
in_progress_form_data = JSON.parse(in_progress_form.form_data)
in_progress_form_data['toxic_exposure'] = {
'conditions' => { 'arthritis' => true },
'gulf_war_1990' => { 'iraq' => true },
'gulf_war_2001' => { 'djibouti' => true }
}
in_progress_form.update!(form_data: in_progress_form_data.to_json)
# Submit with only gulfWar1990 (gulfWar2001 removed)
parsed_payload['form526']['toxicExposure'] = {
'conditions' => { 'arthritis' => true },
'gulfWar1990' => { 'iraq' => true }
}
# Enable the flipper flag
allow(Flipper).to receive(:enabled?)
.with(:disability_526_toxic_exposure_opt_out_data_purge, anything)
.and_return(true)
# Capture all info log calls with their keyword arguments
logged_calls = []
allow(Rails.logger).to receive(:info) do |message, **kwargs|
logged_calls << { message:, kwargs: }
end
post('/v0/disability_compensation_form/submit_all_claim',
params: JSON.generate(parsed_payload),
headers:)
expect(response).to have_http_status(:ok)
# Find the toxic exposure log call
toxic_exposure_call = logged_calls.find do |call|
call[:message].is_a?(String) && call[:message].include?('toxic exposure orphaned dates purged')
end
# Verify the call was made
expect(toxic_exposure_call).not_to be_nil
# Get the context from the logged call
context = toxic_exposure_call[:kwargs][:context]
expect(context).not_to be_nil
# Verify the context contains unfiltered values (not [FILTERED])
expect(context[:submission_id]).to be_a(Integer)
expect(context[:submission_id]).to be > 0
expect(context[:completely_removed]).to be(false)
expect(context[:removed_keys]).to eq(['gulfWar2001'])
expect(context[:tags]).to eq(['form_id:21-526EZ-ALLCLAIMS'])
# Verify none of the values are filtered
expect(context[:submission_id]).not_to eq('[FILTERED]')
expect(context[:completely_removed]).not_to eq('[FILTERED]')
expect(context[:removed_keys]).not_to eq('[FILTERED]')
expect(context[:tags]).not_to eq('[FILTERED]')
end
end
it 'matches the rated disabilities schema with camel-inflection' do
post '/v0/disability_compensation_form/submit_all_claim', params: all_claims_form, headers: headers_with_camel
expect(response).to have_http_status(:ok)
expect(response).to match_camelized_response_schema('submit_disability_form')
end
it 'starts the submit job' do
expect(EVSS::DisabilityCompensationForm::SubmitForm526AllClaim).to receive(:perform_async).once
post '/v0/disability_compensation_form/submit_all_claim', params: all_claims_form, headers:
end
end
context 'with an `bdd` claim' do
let(:bdd_form) { File.read 'spec/support/disability_compensation_form/bdd_fe_submission.json' }
let(:user) do
build(:disabilities_compensation_user, :with_terms_of_use_agreement, icn: '1012666073V986297',
idme_uuid: SecureRandom.uuid)
end
before do
allow_any_instance_of(Auth::ClientCredentials::Service).to receive(:get_token).and_return('fake_token')
end
it 'matches the rated disabilities schema' do
post('/v0/disability_compensation_form/submit_all_claim', params: bdd_form, headers:)
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('submit_disability_form')
end
it 'matches the rated disabilities schema with camel-inflection' do
post '/v0/disability_compensation_form/submit_all_claim', params: bdd_form, headers: headers_with_camel
expect(response).to have_http_status(:ok)
expect(response).to match_camelized_response_schema('submit_disability_form')
end
end
end
context 'with invalid json body' do
it 'returns a 422' do
post('/v0/disability_compensation_form/submit_all_claim', params: { 'form526' => nil }.to_json, headers:)
expect(response).to have_http_status(:unprocessable_entity)
end
it 'returns a 422 when no new or increase disabilities are submitted' do
all_claims_form = File.read 'spec/support/disability_compensation_form/all_claims_fe_submission.json'
json_object = JSON.parse(all_claims_form)
json_object['form526'].delete('newPrimaryDisabilities')
json_object['form526'].delete('newSecondaryDisabilities')
updated_form = JSON.generate(json_object)
post('/v0/disability_compensation_form/submit_all_claim', params: updated_form, headers:)
expect(response).to have_http_status(:unprocessable_entity)
end
end
end
describe 'SavedClaim::DisabilityCompensation::Form526AllClaim save error logging' do
let(:form_params) { File.read 'spec/support/disability_compensation_form/all_claims_fe_submission.json' }
let(:claim_with_save_error) do
claim = SavedClaim::DisabilityCompensation::Form526AllClaim.new
errors = ActiveModel::Errors.new(claim)
errors.add(:form, 'Mock form validation error')
allow(claim).to receive_messages(errors:, save: false)
claim
end
let!(:in_progress_form) { create(:in_progress_form, form_id: FormProfiles::VA526ez::FORM_ID, user_uuid: user.uuid) }
context 'when the disability_526_track_saved_claim_error Flipper is enabled' do
before do
allow(Flipper).to receive(:enabled?).with(:disability_526_track_saved_claim_error).and_return(true)
end
after do
allow(Flipper).to receive(:enabled?).with(:disability_526_track_saved_claim_error).and_return(false)
end
context 'when the claim fails to save' do
before do
allow(SavedClaim::DisabilityCompensation::Form526AllClaim).to receive(:from_hash)
.and_return(claim_with_save_error)
end
it 'logs save errors for the claim and still returns a 422' do
expect_any_instance_of(DisabilityCompensation::Loggers::Monitor).to receive(:track_saved_claim_save_error)
.with(
claim_with_save_error.errors.errors,
in_progress_form.id,
user.uuid
)
post('/v0/disability_compensation_form/submit_all_claim', params: form_params, headers:)
expect(response).to have_http_status(:unprocessable_entity)
end
end
context 'when the claim saves successfully' do
it 'does not track an error and returns a 200 response' do
expect_any_instance_of(DisabilityCompensation::Loggers::Monitor)
.not_to receive(:track_saved_claim_save_error)
post('/v0/disability_compensation_form/submit_all_claim', params: form_params, headers:)
expect(response).to have_http_status(:ok)
end
end
end
context 'when the disability_526_track_saved_claim_error Flipper is disabled' do
before do
allow(Flipper).to receive(:enabled?).with(:disability_526_track_saved_claim_error).and_return(false)
allow(SavedClaim::DisabilityCompensation::Form526AllClaim).to receive(:from_hash)
.and_return(claim_with_save_error)
end
it 'does not log save errors and still returns a 422' do
expect_any_instance_of(DisabilityCompensation::Loggers::Monitor)
.not_to receive(:track_saved_claim_save_error)
post('/v0/disability_compensation_form/submit_all_claim', params: form_params, headers:)
expect(response).to have_http_status(:unprocessable_entity)
end
end
end
describe 'Get /v0/disability_compensation_form/submission_status' do
context 'with a success status' do
let(:submission) { create(:form526_submission, submitted_claim_id: 61_234_567) }
let(:job_status) { create(:form526_job_status, form526_submission_id: submission.id) }
let!(:ancillary_job_status) do
create(:form526_job_status,
form526_submission_id: submission.id,
job_class: 'AncillaryForm')
end
it 'returns the job status and response', :aggregate_failures do
get("/v0/disability_compensation_form/submission_status/#{job_status.job_id}", params: nil, headers:)
expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body)).to match(
'data' => {
'id' => '',
'type' => 'form526_job_statuses',
'attributes' => {
'claim_id' => 61_234_567,
'job_id' => job_status.job_id,
'submission_id' => submission.id,
'status' => 'success',
'ancillary_item_statuses' => [
a_hash_including('id' => ancillary_job_status.id,
'job_id' => ancillary_job_status.job_id,
'job_class' => 'AncillaryForm',
'status' => 'success',
'error_class' => nil,
'error_message' => nil,
'updated_at' => ancillary_job_status.updated_at.iso8601(3))
]
}
}
)
end
end
context 'with a retryable_error status' do
let(:submission) { create(:form526_submission) }
let(:job_status) { create(:form526_job_status, :retryable_error, form526_submission_id: submission.id) }
it 'returns the job status and response', :aggregate_failures do
get("/v0/disability_compensation_form/submission_status/#{job_status.job_id}", params: nil, headers:)
expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body)).to have_deep_attributes(
'data' => {
'id' => '',
'type' => 'form526_job_statuses',
'attributes' => {
'claim_id' => nil,
'job_id' => job_status.job_id,
'submission_id' => submission.id,
'status' => 'retryable_error',
'ancillary_item_statuses' => []
}
}
)
end
end
context 'with a non_retryable_error status' do
let(:submission) { create(:form526_submission) }
let(:job_status) { create(:form526_job_status, :non_retryable_error, form526_submission_id: submission.id) }
it 'returns the job status and response', :aggregate_failures do
get("/v0/disability_compensation_form/submission_status/#{job_status.job_id}", params: nil, headers:)
expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body)).to have_deep_attributes(
'data' => {
'id' => '',
'type' => 'form526_job_statuses',
'attributes' => {
'claim_id' => nil,
'job_id' => job_status.job_id,
'submission_id' => submission.id,
'status' => 'non_retryable_error',
'ancillary_item_statuses' => []
}
}
)
end
end
context 'when no record is found' do
it 'returns the async submit transaction status and response', :aggregate_failures do
get('/v0/disability_compensation_form/submission_status/123', params: nil, headers:)
expect(response).to have_http_status(:not_found)
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/medical_copays_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::MedicalCopays', type: :request do
let(:current_user) { build(:user, :loa3) }
before do
sign_in_as(current_user)
end
describe 'GET medical_copays#index' do
let(:copays) { { data: [], status: 200 } }
it 'returns a formatted hash response' do
allow_any_instance_of(MedicalCopays::VBS::Service).to receive(:get_copays).and_return(copays)
get '/v0/medical_copays'
expect(Oj.load(response.body)).to eq({ 'data' => [], 'status' => 200 })
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/education_benefits_claims_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::EducationBenefitsClaims', type: %i[request serializer] do
describe 'POST create' do
subject do
post(path,
params: params.to_json,
headers: { 'CONTENT_TYPE' => 'application/json', 'HTTP_X_KEY_INFLECTION' => 'camel' })
end
let(:path) { v0_education_benefits_claims_path }
context 'with a form_type passed in' do
let(:form_type) { '1995' }
let(:params) do
{
educationBenefitsClaim: {
form: build(:va1995).form
}
}
end
let(:path) do
form_type_v0_education_benefits_claims_path(form_type:)
end
it 'creates a 1995 form' do
expect { subject }.to change(EducationBenefitsClaim, :count).by(1)
expect(EducationBenefitsClaim.last.form_type).to eq(form_type)
end
it 'returns the expected serialized data' do
subject
ebc = EducationBenefitsClaim.first
response_data = JSON.parse(response.body)['data']
expect(response_data['id']).to eq(ebc.token)
expect(response_data['type']).to eq('education_benefits_claim')
expect(response_data['attributes']['confirmationNumber']).to eq(ebc.confirmation_number)
end
it 'increments statsd' do
expect { subject }.to trigger_statsd_increment('api.education_benefits_claim.create.221995.success')
end
end
context 'with valid params' do
let(:params) do
{
educationBenefitsClaim: {
form: {
privacyAgreementAccepted: true,
veteranFullName: {
first: 'Mark',
last: 'Olson'
},
preferredContactMethod: 'mail'
}.to_json
}
}
end
it 'creates a new model' do
expect { subject }.to change(EducationBenefitsClaim, :count).by(1)
expect(EducationBenefitsClaim.last.parsed_form['preferredContactMethod']).to eq('mail')
end
it 'clears the saved form' do
expect_any_instance_of(ApplicationController).to receive(:clear_saved_form).with('22-1990').once
subject
end
it 'renders json of the new model' do
subject
expect(response.body).to eq(
JSON.parse(
serialize(EducationBenefitsClaim.last)
).deep_transform_keys { |key| key.underscore.camelize(:lower) }.to_json
)
end
it 'increments statsd' do
expect { subject }.to trigger_statsd_increment('api.education_benefits_claim.create.221990.success')
end
end
context 'with invalid params' do
let(:params) do
{
educationBenefitsClaim: { form: nil }
}
end
before { allow(Settings.sentry).to receive(:dsn).and_return('asdf') }
it 'renders json of the errors' do
subject
expect(response).to have_http_status(:unprocessable_entity)
expect(JSON.parse(response.body)['errors'][0]['detail']).to eq(
"form - can't be blank"
)
end
it 'increments statsd' do
expect { subject }.to trigger_statsd_increment('api.education_benefits_claim.create.221990.failure')
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/map_services_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::MapServices', type: :request do
describe 'POST /v0/map_services/token' do
subject(:call_endpoint) do
post v0_map_services_token_path(application:), headers: service_account_auth_header
end
context 'when MAP STS client is not configured for use by the service account' do
let(:application) { 'foobar' }
include_context 'with service account authentication', 'foobar', ['http://www.example.com/v0/map_services/foobar/token'], { user_attributes: { icn: 42 } }
it 'responds with error details in response body' do
call_endpoint
expect(JSON.parse(response.body)).to eq(
{
'error' => 'invalid_request',
'error_description' => 'Application mismatch detected.'
}
)
end
it 'returns HTTP status bad_request' do
call_endpoint
expect(response).to have_http_status(:bad_request)
end
end
context 'when MAP STS client is configured for use by the service account' do
let(:application) { 'chatbot' }
context 'when service account access token does not have a user_attributes claim with ICN' do
include_context 'with service account authentication', 'chatbot', ['http://www.example.com/v0/map_services/chatbot/token']
it 'responds with error details in response body' do
call_endpoint
expect(JSON.parse(response.body)).to eq(
{
'error' => 'invalid_request',
'error_description' => 'Service account access token does not contain an ICN in `user_attributes` claim.'
}
)
end
it 'returns HTTP status bad_request' do
call_endpoint
expect(response).to have_http_status(:bad_request)
end
end
context 'when service account access token contains user_attributes claim with ICN' do
include_context 'with service account authentication', 'chatbot', ['http://www.example.com/v0/map_services/chatbot/token'], { user_attributes: { icn: 42 } }
context 'when MAP STS client raises a client error',
vcr: { cassette_name: 'map/security_token_service_401_response' } do
it 'responds with error details in response body' do
call_endpoint
expect(JSON.parse(response.body)).to eq(
{
'error' => 'server_error',
'error_description' => 'STS failed to return a valid token.'
}
)
end
it 'returns HTTP status bad_gateway' do
call_endpoint
expect(response).to have_http_status(:bad_gateway)
end
end
context 'when MAP STS client raises a gateway timeout error' do
before do
stub_request(:post, 'https://veteran.apps-staging.va.gov/sts/oauth/v1/token').to_raise(Net::ReadTimeout)
end
it 'responds with error details in response body' do
call_endpoint
expect(JSON.parse(response.body)).to eq(
{
'error' => 'server_error',
'error_description' => 'STS failed to return a valid token.'
}
)
end
it 'returns HTTP status bad_gateway' do
call_endpoint
expect(response).to have_http_status(:bad_gateway)
end
end
context 'when MAP STS client returns an invalid token',
vcr: { cassette_name: 'map/security_token_service_200_invalid_token' } do
it 'responds with error details in response body' do
call_endpoint
expect(JSON.parse(response.body)).to eq(
{
'error' => 'server_error',
'error_description' => 'STS failed to return a valid token.'
}
)
end
it 'returns HTTP status bad_gateway' do
call_endpoint
expect(response).to have_http_status(:bad_gateway)
end
end
context 'when MAP STS client returns a valid access token',
vcr: { cassette_name: 'map/security_token_service_200_response' } do
it 'responds with STS-issued token in response body' do
call_endpoint
expect(JSON.parse(response.body)).to include('access_token' => anything, 'expiration' => anything)
end
it 'returns HTTP status ok' do
call_endpoint
expect(response).to have_http_status(:ok)
end
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/legacy_form1095_bs_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::Form1095Bs', type: :request do
subject { create(:form1095_b) }
let(:user) { build(:user, :loa3, icn: subject.veteran_icn) }
let(:invalid_user) { build(:user, :loa1, icn: subject.veteran_icn) }
before do
allow(Flipper).to receive(:enabled?).with(:fetch_1095b_from_enrollment_system, any_args).and_return(false)
end
describe 'GET /download_pdf for valid user' do
before do
sign_in_as(user)
end
it 'returns http success' do
get '/v0/form1095_bs/download_pdf/2021'
expect(response).to have_http_status(:success)
end
it 'returns a PDF form' do
get '/v0/form1095_bs/download_pdf/2021'
expect(response.content_type).to eq('application/pdf')
end
it 'throws 404 when form not found' do
get '/v0/form1095_bs/download_pdf/2018'
expect(response).to have_http_status(:not_found)
end
it 'throws 422 when no template exists for requested year' do
create(:form1095_b, tax_year: 2018)
get '/v0/form1095_bs/download_pdf/2018'
expect(response).to have_http_status(:unprocessable_entity)
end
end
describe 'GET /download_pdf for invalid user' do
before do
sign_in_as(invalid_user)
end
it 'returns http 403' do
get '/v0/form1095_bs/download_pdf/2021'
expect(response).to have_http_status(:forbidden)
end
end
describe 'GET /download_txt for valid user' do
before do
sign_in_as(user)
end
it 'returns http success' do
get '/v0/form1095_bs/download_txt/2021'
expect(response).to have_http_status(:success)
end
it 'returns a txt form' do
get '/v0/form1095_bs/download_txt/2021'
expect(response.content_type).to eq('text/plain')
end
it 'throws 404 when form not found' do
get '/v0/form1095_bs/download_txt/2018'
expect(response).to have_http_status(:not_found)
end
it 'throws 422 when no template exists for requested year' do
create(:form1095_b, tax_year: 2018)
get '/v0/form1095_bs/download_txt/2018'
expect(response).to have_http_status(:unprocessable_entity)
end
end
describe 'GET /download_txt for invalid user' do
before do
sign_in_as(invalid_user)
end
it 'returns http 403' do
get '/v0/form1095_bs/download_txt/2021'
expect(response).to have_http_status(:forbidden)
end
end
describe 'GET /available_forms' do
before do
sign_in_as(user)
end
it 'returns success with only the most recent tax year form data' do
this_year = Date.current.year
last_year_form = create(:form1095_b, tax_year: this_year - 1)
create(:form1095_b, tax_year: this_year)
create(:form1095_b, tax_year: this_year - 2)
get '/v0/form1095_bs/available_forms'
expect(response).to have_http_status(:success)
expect(response.parsed_body.deep_symbolize_keys).to eq(
{ available_forms: [{ year: last_year_form.tax_year,
last_updated: last_year_form.updated_at.strftime('%Y-%m-%dT%H:%M:%S.%LZ') }] }
)
end
it 'returns success with no available forms' do
get '/v0/form1095_bs/available_forms'
expect(response).to have_http_status(:success)
expect(response.parsed_body.symbolize_keys).to eq(
{ available_forms: [] }
)
end
end
describe 'GET /available_forms for invalid user' do
before do
sign_in_as(invalid_user)
end
it 'returns http 403' do
get '/v0/form1095_bs/available_forms'
expect(response).to have_http_status(:forbidden)
end
end
describe 'GET /available_forms when not logged in' do
it 'returns http 401' do
get '/v0/form1095_bs/available_forms'
expect(response).to have_http_status(:unauthorized)
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/intent_to_file_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'disability_compensation/factories/api_provider_factory'
require 'lighthouse/benefits_claims/intent_to_file/monitor'
RSpec.describe 'V0::IntentToFile', type: :request do
include SchemaMatchers
let(:user) { build(:disabilities_compensation_user, icn: '123498767V234859') }
let(:camel_inflection_header) { { 'X-Key-Inflection' => 'camel' } }
let(:headers) { { 'CONTENT_TYPE' => 'application/json' } }
let(:headers_with_camel) { headers.merge('X-Key-Inflection' => 'camel') }
let(:monitor) { double('monitor') }
before do
sign_in_as(user)
Flipper.disable(:disability_compensation_production_tester)
allow(BenefitsClaims::IntentToFile::Monitor).to receive(:new).and_return(monitor)
end
describe 'GET /v0/intent_to_file' do
context 'Lighthouse api provider' do
before do
allow_any_instance_of(Auth::ClientCredentials::Service).to receive(:get_token).and_return('test_token')
end
context 'with a valid Lighthouse response' do
it 'matches the intent to files schema' do
VCR.use_cassette('lighthouse/benefits_claims/intent_to_file/200_response') do
get '/v0/intent_to_file'
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('intent_to_files')
end
end
it 'matches the intent to files schema when camel-inflected' do
VCR.use_cassette('lighthouse/benefits_claims/intent_to_file/200_response') do
get '/v0/intent_to_file', headers: camel_inflection_header
expect(response).to have_http_status(:ok)
expect(response).to match_camelized_response_schema('intent_to_files')
end
end
it 'does not throw a 403 when user is missing birls_id and edipi' do
# Stub blank birls_id and blank edipi
allow(user.identity).to receive(:edipi).and_return(nil)
allow(user).to receive_messages(edipi_mpi: nil, birls_id: nil)
VCR.use_cassette('lighthouse/benefits_claims/intent_to_file/200_response') do
get '/v0/intent_to_file'
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('intent_to_files')
end
end
end
context 'for non-compensation ITF types' do
let(:intent_to_file) do
{
'data' => {
'id' => '193685',
'type' => 'intent_to_file',
'attributes' => {
'creationDate' => '2021-03-16T19:15:21.000-05:00',
'expirationDate' => '2022-03-16T19:15:20.000-05:00',
'type' => itf_type,
'status' => 'active'
}
}
}
end
before do
expect_any_instance_of(BenefitsClaims::Service).to receive(:get_intent_to_file)
.with(itf_type, anything, nil).and_return(intent_to_file)
end
context 'with a pension ITF type' do
let(:itf_type) { 'pension' }
it 'matches the intent to files schema' do
expect(monitor).to receive(:track_show_itf)
get '/v0/intent_to_file/pension'
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('intent_to_files')
expect(JSON.parse(response.body)['data']['attributes']['intent_to_file'][0]['type']).to eq itf_type
end
end
context 'with a survivor ITF type' do
let(:itf_type) { 'survivor' }
it 'matches the intent to files schema' do
expect(monitor).to receive(:track_show_itf)
get '/v0/intent_to_file/survivor'
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('intent_to_files')
expect(JSON.parse(response.body)['data']['attributes']['intent_to_file'][0]['type']).to eq itf_type
end
end
end
context 'error handling tests' do
[:'404'].each do |status, _error_class|
error_status = status.to_s.to_i
cassette_path = "lighthouse/benefits_claims/intent_to_file/#{status}_response"
it "returns #{status} response" do
expect(test_error(
cassette_path,
error_status,
headers
)).to be(true)
end
it "returns a #{status} response with camel-inflection" do
expect(test_error(
cassette_path,
error_status,
headers_with_camel
)).to be(true)
end
end
def test_error(cassette_path, status, headers)
VCR.use_cassette(cassette_path) do
expect(monitor).to receive(:track_itf_controller_error)
get('/v0/intent_to_file', params: nil, headers:)
expect(response).to have_http_status(status)
expect(response).to match_response_schema('evss_errors', strict: false)
end
end
end
context 'data validation and monitoring' do
subject { V0::IntentToFilesController.new }
before do
allow(monitor).to receive(:track_missing_user_icn_itf_controller)
allow(monitor).to receive(:track_missing_user_pid_itf_controller)
allow(monitor).to receive(:track_invalid_itf_type_itf_controller)
end
it 'raises MissingICNError' do
user_no_icn = build(:disabilities_compensation_user, icn: nil)
expect { subject.send(:validate_data, user_no_icn, 'post', 'form_id', 'pension') }
.to raise_error V0::IntentToFilesController::MissingICNError
expect(monitor).to have_received(:track_missing_user_icn_itf_controller)
end
it 'tracks missing participant ID' do
user_no_pid = build(:disabilities_compensation_user, participant_id: nil)
expect { subject.send(:validate_data, user_no_pid, 'get', '21P-534EZ', 'survivor') }
.not_to raise_error
expect(monitor).to have_received(:track_missing_user_pid_itf_controller)
end
it 'raises InvalidITFTypeError' do
expect { subject.send(:validate_data, user, 'get', nil, 'survivor') }
.to raise_error V0::IntentToFilesController::InvalidITFTypeError
expect(monitor).to have_received(:track_invalid_itf_type_itf_controller)
end
it 'logs validation data when pension_itf_validate_data_logger flipper is enabled' do
allow(Flipper).to receive(:enabled?).with(:pension_itf_validate_data_logger, user).and_return(true)
expect(Rails.logger).to receive(:info).with(
'IntentToFilesController ITF Validate Data',
{
user_icn_present: true,
user_participant_id_present: true,
itf_type: 'pension',
user_uuid: user.uuid
}
)
subject.send(:validate_data, user, 'get', '21P-527EZ', 'pension')
end
it 'does not log validation data when pension_itf_validate_data_logger flipper is disabled' do
allow(Flipper).to receive(:enabled?).with(:pension_itf_validate_data_logger, user).and_return(false)
expect(Rails.logger).not_to receive(:info).with('IntentToFilesController ITF Validate Data', anything)
subject.send(:validate_data, user, 'get', '21P-527EZ', 'pension')
end
end
end
end
describe 'POST /v0/intent_to_file' do
before do
allow_any_instance_of(Auth::ClientCredentials::Service).to receive(:get_token).and_return('test_token')
end
shared_examples 'create intent to file with specified itf type' do
let(:intent_to_file) do
{
'data' => {
'id' => '193685',
'type' => 'intent_to_file',
'attributes' => {
'creationDate' => '2021-03-16T19:15:21.000-05:00',
'expirationDate' => '2022-03-16T19:15:20.000-05:00',
'type' => itf_type,
'status' => 'active'
}
}
}
end
it 'matches the respective intent to file schema' do
expect_any_instance_of(BenefitsClaims::Service).to receive(:create_intent_to_file)
.with(itf_type, user.ssn, nil).and_return(intent_to_file)
form_id = { 'pension' => '21P-527EZ', 'survivor' => '21P-534EZ' }[itf_type]
expect(monitor).to receive(:track_submit_itf).with(form_id, itf_type, user.uuid)
post "/v0/intent_to_file/#{itf_type}"
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('intent_to_file')
expect(JSON.parse(response.body)['data']['attributes']['intent_to_file']['type']).to eq itf_type
end
end
context 'when an ITF create request is submitted' do
it_behaves_like 'create intent to file with specified itf type' do
let(:itf_type) { 'pension' }
end
it_behaves_like 'create intent to file with specified itf type' do
let(:itf_type) { 'survivor' }
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/status_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'admin/redis_health_checker'
RSpec.describe 'V0::Status', type: :request do
before do
allow(RedisHealthChecker).to receive_messages(redis_up: true, app_data_redis_up: true, rails_cache_up: true,
sidekiq_redis_up: true)
end
it 'Provides a status page with status OK, git SHA, and connectivity statuses' do
get '/v0/status'
assert_response :success
json = JSON.parse(response.body)
git_rev = AppInfo::GIT_REVISION
pg_up = DatabaseHealthChecker.postgres_up
expect(response.headers['X-Git-SHA']).to eq(git_rev)
expect(json['git_revision']).to eq(git_rev)
expect(json['postgres_up']).to eq(pg_up)
expect(json['redis_up']).to be(true)
expect(json['redis_details']).to eq({
'app_data_redis' => true,
'rails_cache' => true,
'sidekiq_redis' => true
})
end
context 'when Redis services are down' do
before do
allow(RedisHealthChecker).to receive_messages(redis_up: false, app_data_redis_up: false, rails_cache_up: true,
sidekiq_redis_up: false)
end
it 'reflects the correct Redis statuses' do
get '/v0/status'
assert_response :success
json = JSON.parse(response.body)
expect(json['redis_up']).to be(false)
expect(json['redis_details']).to eq({
'app_data_redis' => false,
'rails_cache' => true,
'sidekiq_redis' => false
})
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/maintenance_windows_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::MaintenanceWindows', type: :request do
context 'with no upcoming windows' do
it 'returns an empty list' do
get '/v0/maintenance_windows'
assert_response :success
expect(JSON.parse(response.body)['data']).to eq([])
end
end
context 'with upcoming window' do
before do
MaintenanceWindow.create(
[
{
pagerduty_id: 'asdf1234',
external_service: 'foo',
start_time: Time.zone.now.yesterday,
end_time: Time.zone.now.yesterday,
description: 'maintenance from yesterday'
},
{
pagerduty_id: 'asdf12345',
external_service: 'foo',
start_time: Time.zone.now.tomorrow,
end_time: Time.zone.now.tomorrow,
description: 'maintenance for tomorrow'
}
]
)
end
it 'returns only future maintenance windows' do
get '/v0/maintenance_windows'
assert_response :success
expect(JSON.parse(response.body)['data'][0]['attributes']['description']).to eq('maintenance for tomorrow')
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/tsa_letter_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'support/stub_efolder_documents'
RSpec.describe 'VO::TsaLetter', type: :request do
let(:user) { build(:user, :loa3) }
before do
sign_in_as(user)
end
describe 'GET /v0/tsa_letter' do
let(:tsa_letters) do
[
OpenStruct.new(
document_id: '{73CD7B28-F695-4337-BBC1-2443A913ACF6}',
doc_type: '34',
type_description: 'Correspondence',
received_at: Date.new(2024, 9, 13)
)
]
end
before do
expect(efolder_service).to receive(:list_tsa_letters).and_return(tsa_letters)
end
it 'returns the tsa letter metadata' do
expected_response = { 'data' =>
[{ 'id' => '',
'type' => 'tsa_letter',
'attributes' => { 'document_id' => '{73CD7B28-F695-4337-BBC1-2443A913ACF6}', 'doc_type' => '34',
'type_description' => 'Correspondence', 'received_at' => '2024-09-13' } }] }
get '/v0/tsa_letter'
expect(response.body).to eq(expected_response.to_json)
end
end
describe 'GET /v0/tsa_letter/:id' do
let(:document_id) { '{93631483-E9F9-44AA-BB55-3552376400D8}' }
let(:content) { File.read('spec/fixtures/files/error_message.txt') }
before do
expect(efolder_service).to receive(:get_tsa_letter).with(document_id).and_return(content)
end
it 'sends the doc pdf' do
get "/v0/tsa_letter/#{CGI.escape(document_id)}"
expect(response.body).to eq(content)
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/event_bus_gateway_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::EventBusGateway', type: :request do
include_context 'with service account authentication', 'eventbus', [
'http://www.example.com/v0/event_bus_gateway/send_email',
'http://www.example.com/v0/event_bus_gateway/send_notifications',
'http://www.example.com/v0/event_bus_gateway/send_push'
], { user_attributes: { participant_id: '1234' } }
describe 'POST /v0/event_bus_gateway/send_email' do
let(:params) do
{
template_id: '5678'
}
end
context 'with the authentication header included' do
it 'invokes the email-sending job' do
expect(EventBusGateway::LetterReadyEmailJob).to receive(:perform_async).with('1234', '5678')
post '/v0/event_bus_gateway/send_email', params:, headers: service_account_auth_header
expect(response).to have_http_status(:ok)
end
end
context 'without the authentication header' do
it 'returns an unauthorized response' do
post '/v0/event_bus_gateway/send_email', params:, headers: nil
expect(response).to have_http_status(:unauthorized)
end
end
end
describe 'POST /v0/event_bus_gateway/send_notifications' do
let(:params) do
{
email_template_id: '5678',
push_template_id: '9012'
}
end
context 'with the authentication header included' do
it 'invokes the notification-sending job with both templates' do
expect(EventBusGateway::LetterReadyNotificationJob).to receive(:perform_async).with('1234', '5678', '9012')
post '/v0/event_bus_gateway/send_notifications', params:, headers: service_account_auth_header
expect(response).to have_http_status(:ok)
end
it 'invokes the notification-sending job with only email template' do
params_email_only = { email_template_id: '5678' }
expect(EventBusGateway::LetterReadyNotificationJob).to receive(:perform_async).with('1234', '5678', nil)
post '/v0/event_bus_gateway/send_notifications', params: params_email_only, headers: service_account_auth_header
expect(response).to have_http_status(:ok)
end
it 'invokes the notification-sending job with only push template' do
params_push_only = { push_template_id: '9012' }
expect(EventBusGateway::LetterReadyNotificationJob).to receive(:perform_async).with('1234', nil, '9012')
post '/v0/event_bus_gateway/send_notifications', params: params_push_only, headers: service_account_auth_header
expect(response).to have_http_status(:ok)
end
end
context 'without the authentication header' do
it 'returns an unauthorized response' do
post '/v0/event_bus_gateway/send_notifications', params:, headers: nil
expect(response).to have_http_status(:unauthorized)
end
end
end
describe 'POST /v0/event_bus_gateway/send_push' do
let(:params) do
{
template_id: '5678'
}
end
context 'with the authentication header included' do
it 'invokes the push-sending job' do
expect(EventBusGateway::LetterReadyPushJob).to receive(:perform_async).with('1234', '5678')
post '/v0/event_bus_gateway/send_push', params:, headers: service_account_auth_header
expect(response).to have_http_status(:ok)
end
end
context 'without the authentication header' do
it 'returns an unauthorized response' do
post '/v0/event_bus_gateway/send_push', params:, headers: nil
expect(response).to have_http_status(:unauthorized)
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/user_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'support/sm_client_helpers'
RSpec.describe 'V0::User', type: :request do
include SchemaMatchers
include SM::ClientHelpers
context 'GET /v0/user - when an LOA 3 user is logged in' do
let(:mhv_user) { build(:user, :mhv) }
let(:v0_user_request_headers) { {} }
let(:edipi) { '1005127153' }
let!(:mhv_user_verification) { create(:mhv_user_verification, mhv_uuid: mhv_user.mhv_credential_uuid) }
before do
allow(SM::Client).to receive(:new).and_return(authenticated_client)
allow_any_instance_of(MHVAccountTypeService).to receive(:mhv_account_type).and_return('Premium')
allow_any_instance_of(User).to receive(:mhv_user_account).and_return(build(:mhv_user_account))
sign_in_as(mhv_user)
allow_any_instance_of(User).to receive(:edipi).and_return(edipi)
VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', allow_playback_repeats: true) do
get v0_user_url, params: nil, headers: v0_user_request_headers
end
end
context 'dont stub mpi' do
let(:mhv_user) { build(:user, :mhv, :no_mpi_profile) }
it 'GET /v0/user - returns proper json' do
assert_response :success
expect(response).to match_response_schema('user_loa3')
end
end
it 'gives me the list of available prefill forms' do
num_enabled = 2
FormProfile::ALL_FORMS.each { |type, form_list| num_enabled += form_list.length if Settings[type].prefill }
expect(JSON.parse(response.body)['data']['attributes']['prefills_available'].length).to be(num_enabled)
end
it 'gives me the list of available services' do
expect(JSON.parse(response.body)['data']['attributes']['services'].sort).to eq(
[
BackendServices::FACILITIES,
BackendServices::HCA,
BackendServices::EDUCATION_BENEFITS,
BackendServices::EVSS_CLAIMS,
BackendServices::LIGHTHOUSE,
BackendServices::FORM526,
BackendServices::USER_PROFILE,
BackendServices::RX,
BackendServices::MESSAGING,
BackendServices::MEDICAL_RECORDS,
BackendServices::HEALTH_RECORDS,
BackendServices::ID_CARD,
# BackendServices::MHV_AC, this will be false if mhv account is premium
BackendServices::FORM_PREFILL,
BackendServices::SAVE_IN_PROGRESS,
BackendServices::APPEALS_STATUS,
BackendServices::IDENTITY_PROOFED,
BackendServices::VET360,
BackendServices::DGI
].sort
)
end
it 'gives me va profile cerner data' do
va_profile = JSON.parse(response.body)['data']['attributes']['va_profile']
expect(va_profile['is_cerner_patient']).to be false
expect(va_profile['facilities']).to contain_exactly({ 'facility_id' => '358', 'is_cerner' => false })
end
it 'returns patient status' do
va_profile = JSON.parse(response.body)['data']['attributes']['va_profile']
expect(va_profile['va_patient']).to be true
end
it 'returns mhv account state info' do
va_profile = JSON.parse(response.body)['data']['attributes']['va_profile']
expect(va_profile['mhv_account_state']).to eq('OK')
end
context 'with camel header inflection' do
let(:v0_user_request_headers) { { 'X-Key-Inflection' => 'camel' } }
let(:mhv_user) { build(:user, :mhv, :no_mpi_profile) }
it 'GET /v0/user - returns proper json' do
assert_response :success
expect(response).to match_camelized_response_schema('user_loa3')
end
end
context 'with deactivated MHV account' do
let(:mpi_profile) do
build(:mpi_profile,
mhv_ids: %w[12345 67890],
active_mhv_ids: ['12345'])
end
let(:mhv_user) { build(:user, :mhv) }
before do
stub_mpi(mpi_profile)
sign_in_as(mhv_user)
get v0_user_url, params: nil
end
it 'returns deactivated mhv account state info' do
va_profile = JSON.parse(response.body)['data']['attributes']['va_profile']
expect(va_profile['mhv_account_state']).to eq('DEACTIVATED')
end
end
context 'with multiple MHV accounts' do
let(:mpi_profile) do
build(:mpi_profile,
mhv_ids: %w[12345 67890],
active_mhv_ids: %w[12345 67890])
end
let(:mhv_user) { build(:user, :mhv) }
before do
stub_mpi(mpi_profile)
sign_in_as(mhv_user)
get v0_user_url, params: nil
end
it 'returns multiple mhv account state' do
va_profile = JSON.parse(response.body)['data']['attributes']['va_profile']
expect(va_profile['mhv_account_state']).to eq('MULTIPLE')
end
end
context 'with missing MHV accounts' do
let(:mhv_user) { build(:user, :mhv, mhv_ids: nil, active_mhv_ids: nil, mhv_credential_uuid: nil) }
let!(:mhv_user_verification) { create(:mhv_user_verification, backing_idme_uuid: mhv_user.idme_uuid) }
before do
allow_any_instance_of(User).to receive(:mhv_user_account).and_return(nil)
sign_in_as(mhv_user)
get v0_user_url, params: nil
end
it 'returns none mhv account state' do
va_profile = JSON.parse(response.body)['data']['attributes']['va_profile']
expect(va_profile['mhv_account_state']).to eq('NONE')
end
end
context 'for non VA patient' do
let(:mhv_user) { build(:user, :mhv, :no_vha_facilities, va_patient: false) }
before do
sign_in_as(mhv_user)
get v0_user_url, params: nil
end
it 'returns patient status correctly' do
va_profile = JSON.parse(response.body)['data']['attributes']['va_profile']
expect(va_profile['va_patient']).to be false
end
end
context 'with an error from a 503 raised by VAProfile::ContactInformation::V2::Service#get_person',
:skip_va_profile_user do
before do
exception = 'the server responded with status 503'
error_body = { 'status' => 'some service unavailable status' }
allow_any_instance_of(VAProfile::Service).to receive(:perform).and_raise(
Common::Client::Errors::ClientError.new(exception, 503, error_body)
)
get v0_user_url, params: nil
end
let(:body) { JSON.parse(response.body) }
it 'returns a status of 296' do
expect(response).to have_http_status(296)
end
it 'sets the vet360_contact_information to nil' do
expect(body.dig('data', 'attributes', 'vet360_contact_information')).to be_nil
end
it 'returns meta.errors information', :aggregate_failures do
error = body.dig('meta', 'errors').first
expect(error['external_service']).to eq 'VAProfile'
expect(error['description']).to be_present
expect(error['status']).to eq 502
end
end
end
context 'GET /v0/user - when an LOA 1 user is logged in', :skip_mvi do
let(:v0_user_request_headers) { {} }
let(:edipi) { '1005127153' }
before do
user = new_user(:loa1)
sign_in_as(user)
create(:user_verification, idme_uuid: user.idme_uuid)
allow_any_instance_of(User).to receive(:edipi).and_return(edipi)
VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', allow_playback_repeats: true) do
get v0_user_url, params: nil, headers: v0_user_request_headers
end
end
it 'returns proper json' do
expect(response).to match_response_schema('user_loa1')
end
it 'returns a status of 200 and no errors (VAProfile suppressed for LOA1)', :aggregate_failures do
body = JSON.parse(response.body)
errors = body.dig('meta', 'errors')
expect(response).to have_http_status :ok
expect(errors).to eq([]).or be_nil
end
context 'with camel inflection' do
let(:v0_user_request_headers) { { 'X-Key-Inflection' => 'camel' } }
it 'returns proper json' do
expect(response).to match_camelized_response_schema('user_loa1')
end
end
end
context 'GET /v0/user - when an LOA 1 user is logged in - no edipi', :skip_mvi do
let(:v0_user_request_headers) { {} }
before do
user = new_user(:loa1)
sign_in_as(user)
create(:user_verification, idme_uuid: user.idme_uuid)
get v0_user_url, params: nil, headers: v0_user_request_headers
end
it 'gives me the list of available services' do
expect(JSON.parse(response.body)['data']['attributes']['services'].sort).to eq(
[
BackendServices::FACILITIES,
BackendServices::HCA,
BackendServices::EDUCATION_BENEFITS,
BackendServices::USER_PROFILE,
BackendServices::SAVE_IN_PROGRESS,
BackendServices::FORM_PREFILL
].sort
)
end
end
context 'GET /v0/user - MVI Integration', :skip_mvi do
let(:user) { create(:user, :loa3, :no_mpi_profile) }
let(:edipi) { '1005127153' }
before do
VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', allow_playback_repeats: true) do
sign_in_as(user)
allow_any_instance_of(User).to receive(:edipi).and_return(edipi)
end
end
it 'MVI error should only make a request to MVI one time per request!', :aggregate_failures do
stub_mpi_failure
expect { get v0_user_url, params: nil }
.to trigger_statsd_increment('api.external_http_request.MVI.failed', times: 1, value: 1)
.and not_trigger_statsd_increment('api.external_http_request.MVI.skipped')
.and not_trigger_statsd_increment('api.external_http_request.MVI.success')
body = JSON.parse(response.body)
error = body.dig('meta', 'errors').first
expect(body['data']['attributes']['va_profile']).to be_nil
expect(response).to have_http_status 296
expect(error['external_service']).to eq 'MVI'
expect(error['description']).to be_present
expect(error['status']).to eq 500
end
it 'MVI RecordNotFound should only make a request to MVI one time per request!', :aggregate_failures do
stub_mpi_record_not_found
expect { get v0_user_url, params: nil }
.to trigger_statsd_increment('api.external_http_request.MVI.success', times: 1, value: 1)
.and not_trigger_statsd_increment('api.external_http_request.MVI.skipped')
.and not_trigger_statsd_increment('api.external_http_request.MVI.failed')
body = JSON.parse(response.body)
error = body.dig('meta', 'errors').first
expect(body['data']['attributes']['va_profile']).to be_nil
expect(response).to have_http_status 296
expect(error['external_service']).to eq 'MVI'
expect(error['description']).to be_present
expect(error['status']).to eq 404
end
it 'MVI DuplicateRecords should only make a request to MVI one time per request!', :aggregate_failures do
stub_mpi_duplicate_record
expect { get v0_user_url, params: nil }
.to trigger_statsd_increment('api.external_http_request.MVI.success', times: 1, value: 1)
.and not_trigger_statsd_increment('api.external_http_request.MVI.skipped')
.and not_trigger_statsd_increment('api.external_http_request.MVI.failed')
body = JSON.parse(response.body)
error = body.dig('meta', 'errors').first
expect(body['data']['attributes']['va_profile']).to be_nil
expect(response).to have_http_status 296
expect(error['external_service']).to eq 'MVI'
expect(error['description']).to be_present
expect(error['status']).to eq 404
end
it 'MVI success should only make a request to MVI one time per multiple requests!' do
stub_mpi_success
expect_any_instance_of(Common::Client::Base).to receive(:perform).once.and_call_original
expect { get v0_user_url, params: nil }
.to trigger_statsd_increment('api.external_http_request.MVI.success', times: 1, value: 1)
expect { get v0_user_url, params: nil }
.not_to trigger_statsd_increment('api.external_http_request.MVI.success', times: 1, value: 1)
expect { get v0_user_url, params: nil }
.not_to trigger_statsd_increment('api.external_http_request.MVI.success', times: 1, value: 1)
end
context 'when breakers is used' do
let(:user2) { create(:user, :loa3, :no_mpi_profile, icn: SecureRandom.uuid) }
let(:edipi) { '1005127153' }
before do
allow_any_instance_of(User).to receive(:edipi).and_return(edipi)
end
it 'MVI raises a breakers exception after 50% failure rate', :aggregate_failures do
VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', allow_playback_repeats: true) do
now = Time.current
start_time = now - 120
Timecop.freeze(start_time)
# starts out successful
stub_mpi_success
sign_in_as(user)
expect { get v0_user_url, params: nil }
.to trigger_statsd_increment('api.external_http_request.MVI.success', times: 1, value: 1)
.and not_trigger_statsd_increment('api.external_http_request.MVI.failed')
.and not_trigger_statsd_increment('api.external_http_request.MVI.skipped')
# encounters failure and breakers kicks in
stub_mpi_failure
sign_in_as(user2)
expect { get v0_user_url, params: nil }
.to trigger_statsd_increment('api.external_http_request.MVI.failed', times: 1, value: 1)
.and not_trigger_statsd_increment('api.external_http_request.MVI.skipped')
.and not_trigger_statsd_increment('api.external_http_request.MVI.success')
expect(MPI::Configuration.instance.breakers_service.latest_outage.start_time.to_i).to eq(start_time.to_i)
# skipped because breakers is active
stub_mpi_success
sign_in_as(user2)
expect { get v0_user_url, params: nil }
.to trigger_statsd_increment('api.external_http_request.MVI.skipped', times: 1, value: 1)
.and not_trigger_statsd_increment('api.external_http_request.MVI.failed')
.and not_trigger_statsd_increment('api.external_http_request.MVI.success')
expect(MPI::Configuration.instance.breakers_service.latest_outage.ended?).to be(false)
Timecop.freeze(now)
# sufficient time has elapsed that new requests are made, resulting in success
sign_in_as(user2)
expect { get v0_user_url, params: nil }
.to trigger_statsd_increment('api.external_http_request.MVI.success', times: 1, value: 1)
.and not_trigger_statsd_increment('api.external_http_request.MVI.skipped')
.and not_trigger_statsd_increment('api.external_http_request.MVI.failed')
expect(response).to have_http_status(:ok)
expect(MPI::Configuration.instance.breakers_service.latest_outage.ended?).to be(true)
Timecop.return
end
end
end
end
def new_user(type = :loa3)
build(:user, type, icn: SecureRandom.uuid, uuid: rand(1000..100_000))
end
def stub_mpi_failure
stub_mpi_external_request File.read('spec/support/mpi/find_candidate_soap_fault.xml')
end
def stub_mpi_record_not_found
stub_mpi_external_request File.read('spec/support/mpi/find_candidate_no_subject_response.xml')
end
def stub_mpi_duplicate_record
stub_mpi_external_request File.read('spec/support/mpi/find_candidate_multiple_match_response.xml')
end
def stub_mpi_success
stub_mpi_external_request File.read('spec/support/mpi/find_candidate_response.xml')
end
def stub_mpi_external_request(file)
stub_request(:post, IdentitySettings.mvi.url)
.to_return(status: 200, headers: { 'Content-Type' => 'text/xml' }, body: file)
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/csrf_token_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'CSRF Token Refresh', type: :request do
describe 'HEAD /v0/csrf_token' do
before do
allow(ActionController::Base).to receive(:allow_forgery_protection).and_return(true)
end
it 'returns a 200 status and sets the X-CSRF-Token header' do
head '/v0/csrf_token'
expect(response).to have_http_status(:no_content)
expect(response.headers['X-CSRF-Token']).to be_present
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/form210779_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::Form210779',
type: :request do
include StatsD::Instrument::Helpers
let(:form_data) { { form: VetsJsonSchema::EXAMPLES['21-0779'].to_json }.to_json }
let(:saved_claim) { create(:va210779) }
describe 'POST /v0/form210779' do
context 'when inflection header provided' do
it 'returns a success' do
metrics = capture_statsd_calls do
post(
'/v0/form210779',
params: form_data,
headers: {
'Content-Type' => 'application/json',
'X-Key-Inflection' => 'camel',
'HTTP_SOURCE_APP_NAME' => '21-0779-nursing-home-information'
}
)
end
expect(response).to have_http_status(:ok)
expect(metrics.collect(&:source)).to include(
'saved_claim.create:1|c|#form_id:21-0779,doctype:222',
'shared.sidekiq.default.Lighthouse_SubmitBenefitsIntakeClaim.enqueue:1|c',
'api.form210779.success:1|c',
'api.rack.request:1|c|#controller:v0/form210779,action:create,source_app:21-0779-nursing-home-information,' \
'status:200'
)
end
end
end
describe 'GET /v0/form210779/download_pdf' do
it 'returns a success' do
metrics = capture_statsd_calls do
get("/v0/form210779/download_pdf/#{saved_claim.guid}", headers: {
'Content-Type' => 'application/json',
'HTTP_SOURCE_APP_NAME' => '21-0779-nursing-home-information'
})
end
expect(metrics.collect(&:source)).to include(
'api.rack.request:1|c|#controller:v0/form210779,action:download_pdf,' \
'source_app:21-0779-nursing-home-information,status:200'
)
expect(response).to have_http_status(:ok)
expect(response.content_type).to eq('application/pdf')
end
it 'returns 500 when to_pdf returns error' do
allow_any_instance_of(SavedClaim::Form210779).to receive(:to_pdf).and_raise(StandardError, 'PDF generation error')
metrics = capture_statsd_calls do
get("/v0/form210779/download_pdf/#{saved_claim.guid}", headers: {
'Content-Type' => 'application/json',
'HTTP_SOURCE_APP_NAME' => '21-0779-nursing-home-information'
})
end
expect(metrics.collect(&:source)).to include(
'api.rack.request:1|c|#controller:v0/form210779,action:download_pdf,' \
'source_app:21-0779-nursing-home-information,status:500'
)
expect(response).to have_http_status(:internal_server_error)
expect(JSON.parse(response.body)['errors']).to be_present
expect(JSON.parse(response.body)['errors'].first['status']).to eq('500')
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/form1010_ezrs_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'form1010_ezr/veteran_enrollment_system/associations/service'
RSpec.describe 'V0::Form1010Ezrs', type: :request do
let(:form) do
File.read('spec/fixtures/form1010_ezr/valid_form.json')
end
let(:headers) do
{
'CONTENT_TYPE' => 'application/json',
'HTTP_X_KEY_INFLECTION' => 'camel'
}
end
describe 'POST create' do
subject do
post(
v0_form1010_ezrs_path,
params: params.to_json,
headers:
)
end
context 'while unauthenticated' do
let(:params) do
{ form: }
end
it 'returns an error in the response body' do
subject
expect(response).to have_http_status(:unauthorized)
expect(JSON.parse(response.body)['errors'][0]['detail']).to eq('Not authorized')
end
end
context 'while authenticated', :skip_mvi do
let(:current_user) { build(:evss_user, :loa3, icn: '1013032368V065534') }
before do
sign_in_as(current_user)
end
context 'when no error occurs' do
before do
allow_any_instance_of(
Form1010Ezr::VeteranEnrollmentSystem::Associations::Service
).to receive(:reconcile_and_update_associations).and_return(
{
status: 'success',
message: 'All associations were updated successfully',
timestamp: Time.current.iso8601
}
)
end
let(:params) do
{ form: }
end
let(:body) do
{
'formSubmissionId' => nil,
'timestamp' => nil,
'success' => true
}
end
it 'increments statsd' do
expect { subject }.to trigger_statsd_increment('api.1010ezr.submission_attempt')
end
it 'renders a successful response and deletes the saved form' do
VCR.use_cassette(
'form1010_ezr/authorized_submit_async',
{ match_requests_on: %i[method uri body], erb: true }
) do
expect_any_instance_of(ApplicationController).to receive(:clear_saved_form).with('10-10EZR').once
subject
expect(JSON.parse(response.body)).to eq(body)
end
end
end
context "when the 'ezr_emergency_contacts_enabled' flipper is enabled" do
before do
allow(Flipper).to receive(:enabled?).with(:ezr_emergency_contacts_enabled, instance_of(User)).and_return(true)
end
context 'when an error occurs in the associations service' do
let(:form) do
File.read('spec/fixtures/form1010_ezr/valid_form_with_next_of_kin_and_emergency_contact.json')
end
let(:params) do
{ form: }
end
before do
allow_any_instance_of(
Form1010Ezr::VeteranEnrollmentSystem::Associations::Service
).to receive(:get_associations).and_raise(
Common::Exceptions::ResourceNotFound.new(detail: 'No record found for a person with the specified ICN')
)
end
it 'returns an error response', run_at: 'Tue, 21 Nov 2023 20:42:44 GMT' do
VCR.use_cassette(
'form1010_ezr/authorized_submit',
{ match_requests_on: %i[method uri body], erb: true }
) do
subject
expect(response).to have_http_status(:not_found)
expect(JSON.parse(response.body)['errors'][0]['detail']).to eq(
'No record found for a person with the specified ICN'
)
end
end
end
end
end
end
describe 'POST download_pdf' do
subject do
post(
v0_form1010_ezrs_download_pdf_path,
params: params.to_json,
headers:
)
end
let(:params) { { form: } }
context 'while unauthenticated' do
it 'returns an error in the response body' do
subject
expect(response).to have_http_status(:unauthorized)
expect(JSON.parse(response.body)['errors'][0]['detail']).to eq('Not authorized')
end
end
context 'while authenticated', :skip_mvi do
let(:current_user) { build(:evss_user, :loa3, icn: '1013032368V065534') }
let(:response_pdf) { Rails.root.join 'tmp', 'pdfs', '10-10EZ_from_response.pdf' }
let(:expected_pdf) { Rails.root.join 'spec', 'fixtures', 'pdf_fill', '10-10EZR', 'unsigned', 'simple.pdf' }
let(:body) { { form: }.to_json }
before do
allow(SecureRandom).to receive(:uuid).and_return('file-name-uuid')
sign_in_as(current_user)
end
after do
FileUtils.rm_f(response_pdf)
end
it 'returns a completed PDF' do
subject
expect(response).to have_http_status(:ok)
veteran_full_name = JSON.parse(form)['veteranFullName']
expected_filename = "10-10EZR_#{veteran_full_name['first']}_#{veteran_full_name['last']}.pdf"
expect(response).to have_http_status(:ok)
expect(response.headers['Content-Disposition']).to include("filename=\"#{expected_filename}\"")
expect(response.content_type).to eq('application/pdf')
expect(response.body).to start_with('%PDF')
end
it 'ensures the tmp file is deleted when send_data fails' do
allow_any_instance_of(ApplicationController).to receive(:send_data).and_raise(StandardError, 'send_data failed')
subject
expect(response).to have_http_status(:internal_server_error)
expect(
File.exist?('tmp/pdfs/10-10EZR_file-name-uuid.pdf')
).to be(false)
end
it 'ensures the tmp file is deleted when fill_form fails after retries' do
expect(PdfFill::Filler).to receive(:fill_ancillary_form).exactly(3).times.and_raise(StandardError,
'error filling form')
subject
expect(response).to have_http_status(:internal_server_error)
expect(
File.exist?('tmp/pdfs/10-10EZR_file-name-uuid.pdf')
).to be(false)
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/backend_status_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
require 'support/pagerduty/services/spec_setup'
RSpec.describe 'V0::BackendStatus', type: :request do
include SchemaMatchers
let(:user) { build(:user, :loa3) }
describe 'GET /v0/backend_statuses' do
before { sign_in_as(user) }
context 'happy path' do
include_context 'simulating Redis caching of PagerDuty#get_services'
it 'matches the backend_statuses schema', :aggregate_failures do
get '/v0/backend_statuses'
expect(response).to have_http_status(:ok)
expect(response).to match_response_schema('backend_statuses')
end
it 'matches the backend_statuses schema when camel-inflected', :aggregate_failures do
get '/v0/backend_statuses', headers: { 'X-Key-Inflection' => 'camel' }
expect(response).to have_http_status(:ok)
expect(response).to match_camelized_response_schema('backend_statuses')
end
end
context 'when the PagerDuty API rate limit has been exceeded' do
it 'returns a 429 error', :aggregate_failures do
VCR.use_cassette('pagerduty/external_services/get_services_429', VCR::MATCH_EVERYTHING) do
get '/v0/backend_statuses'
body = JSON.parse(response.body)
error = body['errors'].first
expect(response.status).to be_a(Integer).and eq 429
expect(error['code']).to be_a(String).and eq 'PAGERDUTY_429'
expect(error['title']).to be_a(String).and eq 'Exceeded rate limit'
end
end
end
context 'when there are maintenance windows' do
include_context 'simulating Redis caching of PagerDuty#get_services'
let!(:maintenance_window) do
create(:maintenance_window, start_time: 1.day.ago, end_time: 1.day.from_now)
end
it 'returns the maintenance windows', :aggregate_failures do
get '/v0/backend_statuses'
body = JSON.parse(response.body)
maintenance_windows = body['data']['attributes']['maintenance_windows']
expect(maintenance_windows).to be_an(Array)
expect(maintenance_windows.first).to eq(maintenance_window.as_json(only: %i[id external_service start_time
end_time description]))
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests
|
code_files/vets-api-private/spec/requests/v0/test_account_user_emails_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::TestAccountUserEmails', type: :request do
describe 'POST #create' do
subject { post '/v0/test_account_user_email', params: }
let(:email) { 'some-email' }
let(:email_redis_key) { Digest::SHA256.hexdigest(email) }
let(:params) { { email: } }
let(:rendered_error) { { 'errors' => 'invalid params' } }
before do
allow(Rails.logger).to receive(:info)
end
shared_context 'bad_request' do
it 'responds with bad request status' do
subject
assert_response :bad_request
end
it 'responds with error' do
subject
expect(JSON.parse(response.body)).to eq(rendered_error)
end
end
context 'when params does not include email' do
let(:params) { { some_params: 'some-params' } }
it_behaves_like 'bad_request'
end
context 'when params include email' do
let(:params) { { email: } }
context 'and email param is empty' do
let(:email) { '' }
it_behaves_like 'bad_request'
end
context 'and email param is not empty' do
let(:email) { 'some-email' }
let(:expected_log_message) { "[V0][TestAccountUserEmailsController] create, key:#{email_redis_key}" }
it 'responds with created status' do
subject
assert_response :created
end
it 'responds with test_account_user_email_uuid' do
subject
expect(JSON.parse(response.body)['test_account_user_email_uuid']).to eq(email_redis_key)
end
it 'makes a create log to rails logger' do
subject
expect(Rails.logger).to have_received(:info).with(expected_log_message)
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests/v0
|
code_files/vets-api-private/spec/requests/v0/id_card/attributes_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::IdCard::Attributes', type: :request do
let(:token) { 'fa0f28d6-224a-4015-a3b0-81e77de269f2' }
let(:auth_header) { { 'Authorization' => "Token token=#{token}" } }
let(:current_user) { build(:user, :loa3) }
before do
allow(Settings.vic).to receive(:signing_key_path)
.and_return(Rails.root.join(*'/spec/support/certificates/vic-signing-key.pem'.split('/')).to_s)
sign_in_as(current_user)
end
describe '#show /v0/id_card/attributes' do
context 'VAProfile and Military Information' do
let(:service_episodes) { [build(:prefill_service_episode)] }
it 'returns a signed redirect URL' do
VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', match_requests_on: [:method],
allow_playback_repeats: true) do
allow(VAProfile::Configuration::SETTINGS.veteran_status).to receive(:cache_enabled).and_return(true)
expect_any_instance_of(
VAProfileRedis::VeteranStatus
).to receive(:title38_status).at_least(:once).and_return('V1')
get '/v0/id_card/attributes', headers: auth_header
expect(response).to have_http_status(:ok)
json = JSON.parse(response.body)
url = json['url']
expect(url).to be_truthy
traits = json['traits']
expect(traits).to be_key('edipi')
expect(traits).to be_key('firstname')
expect(traits).to be_key('lastname')
expect(traits).to be_key('title38status')
expect(traits).to be_key('branchofservice')
expect(traits).to be_key('dischargetype')
expect(traits).to be_key('timestamp')
expect(traits).to be_key('signature')
end
end
it 'returns VA Profile discharge codes for all service episodes' do
VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', match_requests_on: [:method],
allow_playback_repeats: true) do
VCR.use_cassette('va_profile/military_personnel/service_history_200_many_episodes',
allow_playback_repeats: true) do
allow(VAProfile::Configuration::SETTINGS.veteran_status).to receive(:cache_enabled).and_return(true)
expect_any_instance_of(
VAProfileRedis::VeteranStatus
).to receive(:title38_status).at_least(:once).and_return('V1')
get '/v0/id_card/attributes', headers: auth_header
expect(response).to have_http_status(:ok)
json = JSON.parse(response.body)
url = json['url']
expect(url).to be_truthy
traits = json['traits']
expect(traits['dischargetype']).to eq('B')
end
end
end
it 'returns an empty string from VA Profile if no discharge type' do
VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', match_requests_on: [:method],
allow_playback_repeats: true) do
VCR.use_cassette('va_profile/military_personnel/post_read_service_histories_200') do
allow(VAProfile::Configuration::SETTINGS.veteran_status).to receive(:cache_enabled).and_return(true)
expect_any_instance_of(
VAProfileRedis::VeteranStatus
).to receive(:title38_status).at_least(:once).and_return('V1')
get '/v0/id_card/attributes', headers: auth_header
expect(response).to have_http_status(:ok)
json = JSON.parse(response.body)
url = json['url']
expect(url).to be_truthy
traits = json['traits']
expect(traits['dischargetype']).to eq('')
end
end
end
it 'returns VA Profile discharge codes for single service episode' do
VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', match_requests_on: [:method],
allow_playback_repeats: true) do
VCR.use_cassette('va_profile/military_personnel/post_read_service_history_200',
allow_playback_repeats: true) do
allow(VAProfile::Configuration::SETTINGS.veteran_status).to receive(:cache_enabled).and_return(true)
expect_any_instance_of(
VAProfileRedis::VeteranStatus
).to receive(:title38_status).at_least(:once).and_return('V1')
get '/v0/id_card/attributes', headers: auth_header
expect(response).to have_http_status(:ok)
json = JSON.parse(response.body)
url = json['url']
expect(url).to be_truthy
traits = json['traits']
expect(traits['dischargetype']).to eq('B')
end
end
end
it 'returns Bad Gateway if military information not retrievable' do
VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', match_requests_on: [:method],
allow_playback_repeats: true) do
allow(VAProfile::Configuration::SETTINGS.veteran_status).to receive(:cache_enabled).and_return(true)
expect_any_instance_of(
VAProfileRedis::VeteranStatus
).to receive(:title38_status).at_least(:once).and_return('V1')
expect_any_instance_of(VAProfile::Prefill::MilitaryInformation)
.to receive(:service_episodes_by_date).and_raise(StandardError)
get '/v0/id_card/attributes', headers: auth_header
expect(response).to have_http_status(:bad_gateway)
end
end
end
it 'returns VIC002 if title38status is not retrievable' do
VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', match_requests_on: [:method],
allow_playback_repeats: true) do
allow(VAProfile::Configuration::SETTINGS.veteran_status).to receive(:cache_enabled).and_return(true)
expect_any_instance_of(
VAProfileRedis::VeteranStatus
).to receive(:title38_status).and_return(nil)
get '/v0/id_card/attributes', headers: auth_header
expect(JSON.parse(response.body)['errors'][0]['code']).to eq(
'VIC002'
)
end
end
it 'returns Forbidden for non-veteran user' do
VCR.use_cassette('va_profile/veteran_status/va_profile_veteran_status_200', match_requests_on: [:method],
allow_playback_repeats: true) do
allow(VAProfile::Configuration::SETTINGS.veteran_status).to receive(:cache_enabled).and_return(true)
expect_any_instance_of(
VAProfileRedis::VeteranStatus
).to receive(:title38_status).at_least(:once).and_return('V2')
get '/v0/id_card/attributes', headers: auth_header
expect(response).to have_http_status(:forbidden)
expect(JSON.parse(response.body)['errors'][0]['code']).to eq(
'VICV2'
)
end
end
it 'returns Forbidden when veteran status not retrievable' do
VCR.use_cassette('va_profile/veteran_status/veteran_status_400', match_requests_on: [:method],
allow_playback_repeats: true) do
allow(VAProfile::Configuration::SETTINGS.veteran_status).to receive(:cache_enabled).and_return(true)
allow_any_instance_of(VAProfileRedis::VeteranStatus)
.to receive(:title38_status).and_raise(StandardError)
get '/v0/id_card/attributes', headers: auth_header
expect(response).to have_http_status(:forbidden)
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests/v0
|
code_files/vets-api-private/spec/requests/v0/id_card/announcement_subscription_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::IdCard::AnnouncementSubscription', type: :request do
def email
params[:id_card_announcement_subscription][:email]
end
describe 'with valid params' do
let(:params) do
{
id_card_announcement_subscription: {
email: 'test@example.com'
}
}
end
it 'creates the subscription' do
post('/v0/id_card/announcement_subscription', params:)
expect(response).to have_http_status(:accepted)
expect(IdCardAnnouncementSubscription.find_by(email:)).to be_present
end
end
describe 'with a non-unique address' do
let(:params) do
{
id_card_announcement_subscription: {
email: 'test@example.com'
}
}
end
before do
IdCardAnnouncementSubscription.create(email:)
end
it 'creates the subscription' do
post('/v0/id_card/announcement_subscription', params:)
expect(response).to have_http_status(:accepted)
end
end
describe 'with invalid params' do
let(:params) do
{
id_card_announcement_subscription: {
email: 'test'
}
}
end
it 'responds with unprocessable entity and validation error' do
post('/v0/id_card/announcement_subscription', params:)
expect(response).to have_http_status(:unprocessable_entity)
expect(response.body).to be_a(String)
json = JSON.parse(response.body)
expect(json['errors'][0]['title']).to eq('Email is invalid')
end
end
describe 'with missing params' do
it 'responds with bad request' do
post '/v0/id_card/announcement_subscription'
expect(response).to have_http_status(:bad_request)
end
end
end
|
0
|
code_files/vets-api-private/spec/requests/v0
|
code_files/vets-api-private/spec/requests/v0/in_progress_forms/5655_spec.rb
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'V0::InProgressForms::5655' do
let(:user_loa3) { build(:user, :loa3, :legacy_icn) }
let(:vcr_options) { { match_requests_on: %i[path query] } }
def with_vcr(&block)
VCR.use_cassette('bgs/people_service/person_data', vcr_options) do
block.call
end
end
describe '/v0/in_progress_forms/5655' do
let(:endpoint) { '/v0/in_progress_forms/5655' }
let(:comp_and_pen_payments) do
[
{ payment_date: DateTime.now - 2.months, payment_amount: '1500' },
{ payment_date: DateTime.now - 10.days, payment_amount: '3000' }
]
end
before do
sign_in_as(user_loa3)
allow_any_instance_of(DebtManagementCenter::PaymentsService).to(
receive(:compensation_and_pension).and_return(comp_and_pen_payments)
)
allow_any_instance_of(DebtManagementCenter::PaymentsService).to(
receive(:education).and_return(nil)
)
end
context 'with payments' do
let(:expected_payments) { [{ 'veteranOrSpouse' => 'VETERAN', 'compensationAndPension' => '3000' }] }
it 'returns a pre-filled form' do
with_vcr do
get endpoint
expect(response).to have_http_status(:ok)
expect(JSON.parse(response.body)['formData']['income']).to eq(expected_payments)
end
end
end
end
end
|
0
|
code_files/vets-api-private/spec/requests/v0
|
code_files/vets-api-private/spec/requests/v0/gi/zipcode_rates_spec.rb
|
# frozen_string_literal: false
require 'rails_helper'
RSpec.describe 'V0::GI::ZipcodeRates', type: :request do
include SchemaMatchers
it 'responds to GET #show' do
VCR.use_cassette('gi_client/gets_the_zipcode_rate') do
get '/v0/gi/zipcode_rates/20001'
end
expect(response).to be_successful
expect(response.body).to be_a(String)
expect(response).to match_response_schema('gi/zipcode_rate')
end
it 'responds to GET #show when camel-inflected' do
VCR.use_cassette('gi_client/gets_the_zipcode_rate') do
get '/v0/gi/zipcode_rates/20001', headers: { 'X-Key-Inflection' => 'camel' }
end
expect(response).to be_successful
expect(response.body).to be_a(String)
expect(response).to match_camelized_response_schema('gi/zipcode_rate')
end
it 'responds with appropriate not found' do
VCR.use_cassette('gi_client/gets_zip_code_rate_error') do
get '/v0/gi/zipcode_rates/splunge'
end
expect(response).to have_http_status(:not_found)
json = JSON.parse(response.body)
expect(json['errors'].length).to eq(1)
expect(json['errors'][0]['title']).to eq('Record not found')
expect(json['errors'][0]['detail']).to eq('Record with the specified code was not found')
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.