diff options
| author | Xinhui | 2017-08-25 17:13:24 +0200 |
|---|---|---|
| committer | Xinhui | 2017-08-25 17:13:24 +0200 |
| commit | 0777d35ff4460cf07c34e69ee7c10c0270a446bf (patch) | |
| tree | b2d850bbce3c8669ee6c636fa93e91c5a6a662bc /spec | |
| parent | 5dda0f5286043823acab68a73d84437a3cbd803f (diff) | |
| parent | 1d7db2b6c254ac55105c08ee177580036b0377f3 (diff) | |
| download | chouette-core-0777d35ff4460cf07c34e69ee7c10c0270a446bf.tar.bz2 | |
Merge branch 'master' into staging
Diffstat (limited to 'spec')
63 files changed, 1346 insertions, 358 deletions
diff --git a/spec/concerns/configurable_spec.rb b/spec/concerns/configurable_spec.rb new file mode 100644 index 000000000..330241b72 --- /dev/null +++ b/spec/concerns/configurable_spec.rb @@ -0,0 +1,35 @@ +RSpec.describe Configurable do + + subject do + Class.new do + include Configurable + end + end + + let( :something ){ double('something') } + + it 'can be configured' do + expect{ subject.config.anything }.to raise_error(NoMethodError) + + subject.config.something = something + + expect( subject.config.something ).to eq(something) + # Instances delegate to the class + expect( subject.new.send(:config).something ).to eq(something) + # **All** instances delegate to the class + expect( subject.new.send(:config).something ).to eq(something) + end + + it 'can be configured with a block' do + + subject.config do | c | + c.something = something + end + + expect( subject.config.something ).to eq(something) + # Instances delegate to the class + expect( subject.new.send(:config).something ).to eq(something) + # **All** instances delegate to the class + expect( subject.new.send(:config).something ).to eq(something) + end +end diff --git a/spec/controllers/api/v1/iboo_controller_spec.rb b/spec/controllers/api/v1/iboo_controller_spec.rb new file mode 100644 index 000000000..64a929d1a --- /dev/null +++ b/spec/controllers/api/v1/iboo_controller_spec.rb @@ -0,0 +1,12 @@ +require 'rails_helper' + +RSpec.describe Api::V1::IbooController, type: :controller do + context '#authenticate' do + include_context 'iboo authenticated api user' + + it 'should set current organisation' do + controller.send(:authenticate) + expect(assigns(:current_organisation)).to eq api_key.organisation + end + end +end diff --git a/spec/controllers/api/v1/imports_controller_spec.rb b/spec/controllers/api/v1/imports_controller_spec.rb new file mode 100644 index 000000000..266b25486 --- /dev/null +++ b/spec/controllers/api/v1/imports_controller_spec.rb @@ -0,0 +1,38 @@ +require 'rails_helper' + +RSpec.describe Api::V1::ImportsController, type: :controller do + let(:workbench) { create :workbench, organisation: organisation } + + context 'unauthenticated' do + include_context 'iboo wrong authorisation api user' + + describe 'GET #index' do + it 'should not be successful' do + get :index, workbench_id: workbench.id + expect(response).not_to be_success + end + end + end + + context 'authenticated' do + include_context 'iboo authenticated api user' + + describe 'GET #index' do + it 'should be successful' do + get :index, workbench_id: workbench.id + expect(response).to be_success + end + end + + describe 'POST #create' do + let(:file) { fixture_file_upload('multiple_references_import.zip') } + + it 'should be successful' do + expect { + post :create, workbench_id: workbench.id, workbench_import: {file: file, creator: 'test'}, format: :json + }.to change{WorkbenchImport.count}.by(1) + expect(response).to be_success + end + end + end +end diff --git a/spec/controllers/api/v1/workbenches_controller_spec.rb b/spec/controllers/api/v1/workbenches_controller_spec.rb new file mode 100644 index 000000000..7780da142 --- /dev/null +++ b/spec/controllers/api/v1/workbenches_controller_spec.rb @@ -0,0 +1,25 @@ +require 'rails_helper' + +RSpec.describe Api::V1::WorkbenchesController, type: :controller do + context 'unauthenticated' do + include_context 'iboo wrong authorisation api user' + + describe 'GET #index' do + it 'should not be successful' do + get :index + expect(response).not_to be_success + end + end + end + + context 'authenticated' do + include_context 'iboo authenticated api user' + + describe 'GET #index' do + it 'should be successful' do + get :index + expect(response).to be_success + end + end + end +end diff --git a/spec/controllers/imports_controller_spec.rb b/spec/controllers/imports_controller_spec.rb index 7b575ab61..f07190496 100644 --- a/spec/controllers/imports_controller_spec.rb +++ b/spec/controllers/imports_controller_spec.rb @@ -15,6 +15,7 @@ RSpec.describe ImportsController, :type => :controller do it 'should be successful' do get :download, workbench_id: workbench.id, id: import.id, token: import.token_download expect(response).to be_success + expect( response.body ).to eq(import.file.read) end end end diff --git a/spec/decorators/api_key_decorator_spec.rb b/spec/decorators/api_key_decorator_spec.rb new file mode 100644 index 000000000..9451a3974 --- /dev/null +++ b/spec/decorators/api_key_decorator_spec.rb @@ -0,0 +1,4 @@ +require 'spec_helper' + +describe ApiKeyDecorator do +end diff --git a/spec/factories/api_keys.rb b/spec/factories/api_keys.rb new file mode 100644 index 000000000..963938c64 --- /dev/null +++ b/spec/factories/api_keys.rb @@ -0,0 +1,8 @@ +FactoryGirl.define do + factory :api_key, class: Api::V1::ApiKey do + name { SecureRandom.urlsafe_base64 } + token { "#{referential_id}-#{organisation_id}-#{SecureRandom.hex}" } + referential + organisation + end +end diff --git a/spec/factories/chouette_journey_pattern.rb b/spec/factories/chouette_journey_pattern.rb index bf55b286f..62241f313 100644 --- a/spec/factories/chouette_journey_pattern.rb +++ b/spec/factories/chouette_journey_pattern.rb @@ -1,14 +1,14 @@ FactoryGirl.define do - + factory :journey_pattern_common, :class => Chouette::JourneyPattern do sequence(:name) { |n| "jp name #{n}" } sequence(:published_name) { |n| "jp publishedname #{n}" } sequence(:comment) { |n| "jp comment #{n}" } sequence(:registration_number) { |n| "jp registration_number #{n}" } sequence(:objectid) { |n| "test:JourneyPattern:#{n}" } - + association :route, :factory => :route - + factory :journey_pattern do after(:create) do |j| j.stop_point_ids = j.route.stop_points.map(&:id) @@ -16,7 +16,7 @@ FactoryGirl.define do j.arrival_stop_point_id = j.route.stop_points.last.id end end - + factory :journey_pattern_odd do after(:create) do |j| j.stop_point_ids = j.route.stop_points.select { |sp| sp.position%2==0}.map(&:id) @@ -24,7 +24,7 @@ FactoryGirl.define do j.arrival_stop_point_id = j.stop_point_ids.last end end - + factory :journey_pattern_even do after(:create) do |j| j.stop_point_ids = j.route.stop_points.select { |sp| sp.position%2==1}.map(&:id) diff --git a/spec/factories/chouette_routes.rb b/spec/factories/chouette_routes.rb index c1a9423c5..a707bcbf6 100644 --- a/spec/factories/chouette_routes.rb +++ b/spec/factories/chouette_routes.rb @@ -18,6 +18,7 @@ FactoryGirl.define do after(:create) do |route, evaluator| create_list(:stop_point, evaluator.stop_points_count, route: route) + route.reload end factory :route_with_journey_patterns do diff --git a/spec/factories/chouette_time_table.rb b/spec/factories/chouette_time_table.rb index 6480df79d..b410d4ab8 100644 --- a/spec/factories/chouette_time_table.rb +++ b/spec/factories/chouette_time_table.rb @@ -1,12 +1,4 @@ FactoryGirl.define do - - factory :time_table_date, :class => Chouette::TimeTableDate do - association :time_table, :factory => :time_table - end - - factory :time_table_period, :class => Chouette::TimeTablePeriod do - end - factory :time_table, :class => Chouette::TimeTable do sequence(:comment) { |n| "Timetable #{n}" } sequence(:objectid) { |n| "test:Timetable:#{n}" } diff --git a/spec/factories/chouette_time_table_dates.rb b/spec/factories/chouette_time_table_dates.rb new file mode 100644 index 000000000..62fdb3917 --- /dev/null +++ b/spec/factories/chouette_time_table_dates.rb @@ -0,0 +1,5 @@ +FactoryGirl.define do + factory :time_table_date, class: Chouette::TimeTableDate do + association :time_table + end +end diff --git a/spec/factories/chouette_time_table_periods.rb b/spec/factories/chouette_time_table_periods.rb new file mode 100644 index 000000000..66640bbcc --- /dev/null +++ b/spec/factories/chouette_time_table_periods.rb @@ -0,0 +1,7 @@ +FactoryGirl.define do + factory :time_table_period, class: Chouette::TimeTablePeriod do + association :time_table + period_start { Date.today } + period_end { Date.today + 1.month } + end +end diff --git a/spec/factories/chouette_vehicle_journey.rb b/spec/factories/chouette_vehicle_journey.rb index e7ecb79ac..d1e00cd1d 100644 --- a/spec/factories/chouette_vehicle_journey.rb +++ b/spec/factories/chouette_vehicle_journey.rb @@ -11,6 +11,7 @@ FactoryGirl.define do end factory :vehicle_journey do + association :company, factory: :company transient do stop_arrival_time '01:00:00' stop_departure_time '03:00:00' diff --git a/spec/factories/chouette_vehicle_journey_at_stop.rb b/spec/factories/chouette_vehicle_journey_at_stop.rb index c452a1317..831e347d4 100644 --- a/spec/factories/chouette_vehicle_journey_at_stop.rb +++ b/spec/factories/chouette_vehicle_journey_at_stop.rb @@ -1,8 +1,9 @@ FactoryGirl.define do - factory :vehicle_journey_at_stop, :class => Chouette::VehicleJourneyAtStop do association :vehicle_journey, :factory => :vehicle_journey + departure_day_offset { 0 } + departure_time { Time.now } + arrival_time { Time.now - 1.hour } end - end diff --git a/spec/factories/clean_up_results.rb b/spec/factories/clean_up_results.rb deleted file mode 100644 index 6d3818eff..000000000 --- a/spec/factories/clean_up_results.rb +++ /dev/null @@ -1,9 +0,0 @@ -FactoryGirl.define do - factory :clean_up_result do - criticity 1 -message_key "MyString" -message_attributs "" -cleanup nil - end - -end diff --git a/spec/factories/import_messages.rb b/spec/factories/import_messages.rb deleted file mode 100644 index 1101107d2..000000000 --- a/spec/factories/import_messages.rb +++ /dev/null @@ -1,11 +0,0 @@ -FactoryGirl.define do - factory :import_message do - criticity 1 - message_key "MyString" - message_attributs "" - import nil - resource nil - resource_attributes {} - end - -end diff --git a/spec/factories/import_tasks.rb b/spec/factories/import_tasks.rb deleted file mode 100644 index 9ca6db899..000000000 --- a/spec/factories/import_tasks.rb +++ /dev/null @@ -1,10 +0,0 @@ -FactoryGirl.define do - factory :import_task do |f| - user_name "dummy" - user_id 123 - no_save false - format "Neptune" - resources { Rack::Test::UploadedFile.new 'spec/fixtures/neptune.zip', 'application/zip', false } - referential { Referential.find_by_slug("first") } - end -end diff --git a/spec/factories/imports.rb b/spec/factories/imports.rb index fc8668606..2c53106c3 100644 --- a/spec/factories/imports.rb +++ b/spec/factories/imports.rb @@ -9,5 +9,10 @@ FactoryGirl.define do status :new started_at nil ended_at nil + creator 'rspec' + + after(:build) do |import| + import.class.skip_callback(:create, :before, :initialize_fields) + end end end diff --git a/spec/factories/netex_imports.rb b/spec/factories/netex_imports.rb new file mode 100644 index 000000000..057e47730 --- /dev/null +++ b/spec/factories/netex_imports.rb @@ -0,0 +1,5 @@ +FactoryGirl.define do + factory :netex_import, class: NetexImport, parent: :import do + file { File.open(Rails.root.join('spec', 'fixtures', 'terminated_job.json')) } + end +end diff --git a/spec/factories/workbench_imports.rb b/spec/factories/workbench_imports.rb new file mode 100644 index 000000000..5cdcfd15f --- /dev/null +++ b/spec/factories/workbench_imports.rb @@ -0,0 +1,5 @@ +FactoryGirl.define do + factory :workbench_import, class: WorkbenchImport, parent: :import do + file { File.open(Rails.root.join('spec', 'fixtures', 'terminated_job.json')) } + end +end diff --git a/spec/fixtures/multiple_references_import.zip b/spec/fixtures/multiple_references_import.zip Binary files differnew file mode 100644 index 000000000..28ddff198 --- /dev/null +++ b/spec/fixtures/multiple_references_import.zip diff --git a/spec/fixtures/neptune.zip b/spec/fixtures/neptune.zip Binary files differdeleted file mode 100644 index 86b688b51..000000000 --- a/spec/fixtures/neptune.zip +++ /dev/null diff --git a/spec/fixtures/nozip.zip b/spec/fixtures/nozip.zip new file mode 100644 index 000000000..505bd213a --- /dev/null +++ b/spec/fixtures/nozip.zip @@ -0,0 +1 @@ +no zip file diff --git a/spec/fixtures/single_reference_import.zip b/spec/fixtures/single_reference_import.zip Binary files differnew file mode 100644 index 000000000..4aee23614 --- /dev/null +++ b/spec/fixtures/single_reference_import.zip diff --git a/spec/javascripts/time_table/actions_spec.js b/spec/javascripts/time_table/actions_spec.js index 9756e797f..3e0c38c4b 100644 --- a/spec/javascripts/time_table/actions_spec.js +++ b/spec/javascripts/time_table/actions_spec.js @@ -157,33 +157,39 @@ describe('actions', () => { let modalProps = {} let timeTablePeriods = [] let metas = {} + let timetableInDates = [] const expectedAction = { type: 'VALIDATE_PERIOD_FORM', modalProps, timeTablePeriods, - metas + metas, + timetableInDates } - expect(actions.validatePeriodForm(modalProps, timeTablePeriods, metas)).toEqual(expectedAction) + expect(actions.validatePeriodForm(modalProps, timeTablePeriods, metas, timetableInDates)).toEqual(expectedAction) }) it('should create an action to include date in period', () => { let index = 1 + let date = actions.formatDate(new Date) const expectedAction = { type: 'INCLUDE_DATE_IN_PERIOD', index, - dayTypes + dayTypes, + date } - expect(actions.includeDateInPeriod(index, dayTypes)).toEqual(expectedAction) + expect(actions.includeDateInPeriod(index, dayTypes, date)).toEqual(expectedAction) }) it('should create an action to exclude date from period', () => { let index = 1 + let date = actions.formatDate(new Date) const expectedAction = { type: 'EXCLUDE_DATE_FROM_PERIOD', index, - dayTypes + dayTypes, + date } - expect(actions.excludeDateFromPeriod(index, dayTypes)).toEqual(expectedAction) + expect(actions.excludeDateFromPeriod(index, dayTypes, date)).toEqual(expectedAction) }) it('should create an action to open confirm modal', () => { diff --git a/spec/javascripts/time_table/reducers/modal_spec.js b/spec/javascripts/time_table/reducers/modal_spec.js index 4246027b8..160f3955f 100644 --- a/spec/javascripts/time_table/reducers/modal_spec.js +++ b/spec/javascripts/time_table/reducers/modal_spec.js @@ -170,12 +170,14 @@ describe('modal reducer', () => { } let ttperiods = [] + let ttdates = [] expect( modalReducer(state, { type: 'VALIDATE_PERIOD_FORM', modalProps : modProps, - timeTablePeriods: ttperiods + timeTablePeriods: ttperiods, + timetableInDates: ttdates }) ).toEqual(Object.assign({}, state, {modalProps: newModalProps})) }) @@ -222,6 +224,8 @@ describe('modal reducer', () => { {id: 265, period_start: '2017-05-14', period_end: '2017-05-24'} ] + let ttdates2 = [] + let newModalProps2 = { active: true, begin: { @@ -242,8 +246,74 @@ describe('modal reducer', () => { modalReducer(state2, { type: 'VALIDATE_PERIOD_FORM', modalProps : modProps2, - timeTablePeriods: ttperiods2 + timeTablePeriods: ttperiods2, + timetableInDates: ttdates2 }) ).toEqual(Object.assign({}, state2, {modalProps: newModalProps2})) }) + + it('should handle VALIDATE_PERIOD_FORM and throw error if period overlaps date', () => { + let state3 = { + confirmModal: {}, + modalProps: { + active: false, + begin: { + day: '01', + month: '08', + year: '2017' + }, + end: { + day: '09', + month: '08', + year: '2017' + }, + index: false, + error: '' + }, + type: '' + } + let modProps3 = { + active: false, + begin: { + day: '01', + month: '08', + year: '2017' + }, + end: { + day: '09', + month: '08', + year: '2017' + }, + index: false, + error: '' + } + let ttperiods3 = [] + + let ttdates3 = [{date: "2017-08-04", include_date: true}] + + let newModalProps3 = { + active: true, + begin: { + day: '01', + month: '08', + year: '2017' + }, + end: { + day: '09', + month: '08', + year: '2017' + }, + index: false, + error: "Une période ne peut chevaucher une date dans un calendrier" + } + + expect( + modalReducer(state3, { + type: 'VALIDATE_PERIOD_FORM', + modalProps : modProps3, + timeTablePeriods: ttperiods3, + timetableInDates: ttdates3 + }) + ).toEqual(Object.assign({}, state3, {modalProps: newModalProps3})) + }) }) diff --git a/spec/javascripts/time_table/reducers/timetable_spec.js b/spec/javascripts/time_table/reducers/timetable_spec.js index 0b418a52e..805a29b5f 100644 --- a/spec/javascripts/time_table/reducers/timetable_spec.js +++ b/spec/javascripts/time_table/reducers/timetable_spec.js @@ -12,12 +12,15 @@ let current_month = [{"day":"lundi","date":"2017-05-01","wday":1,"wnumber":"18", let newCurrentMonth = [{"day":"lundi","date":"2017-05-01","wday":1,"wnumber":"18","mday":1,"include_date":false,"excluded_date":false,"in_periods":true},{"day":"mardi","date":"2017-05-02","wday":2,"wnumber":"18","mday":2,"include_date":false,"excluded_date":false,"in_periods":true},{"day":"mercredi","date":"2017-05-03","wday":3,"wnumber":"18","mday":3,"include_date":false,"excluded_date":false,"in_periods":true},{"day":"jeudi","date":"2017-05-04","wday":4,"wnumber":"18","mday":4,"include_date":false,"excluded_date":false,"in_periods":true},{"day":"vendredi","date":"2017-05-05","wday":5,"wnumber":"18","mday":5,"include_date":false,"excluded_date":false,"in_periods":false},{"day":"samedi","date":"2017-05-06","wday":6,"wnumber":"18","mday":6,"include_date":false,"excluded_date":false,"in_periods":false},{"day":"dimanche","date":"2017-05-07","wday":0,"wnumber":"18","mday":7,"include_date":false,"excluded_date":false,"in_periods":false},{"day":"lundi","date":"2017-05-08","wday":1,"wnumber":"19","mday":8,"include_date":false,"excluded_date":false,"in_periods":false},{"day":"mardi","date":"2017-05-09","wday":2,"wnumber":"19","mday":9,"include_date":false,"excluded_date":false,"in_periods":false},{"day":"mercredi","date":"2017-05-10","wday":3,"wnumber":"19","mday":10,"include_date":false,"excluded_date":false,"in_periods":false},{"day":"jeudi","date":"2017-05-11","wday":4,"wnumber":"19","mday":11,"include_date":false,"excluded_date":false,"in_periods":false},{"day":"vendredi","date":"2017-05-12","wday":5,"wnumber":"19","mday":12,"include_date":false,"excluded_date":false,"in_periods":false},{"day":"samedi","date":"2017-05-13","wday":6,"wnumber":"19","mday":13,"include_date":false,"excluded_date":false,"in_periods":false},{"day":"dimanche","date":"2017-05-14","wday":0,"wnumber":"19","mday":14,"include_date":false,"excluded_date":false,"in_periods":true},{"day":"lundi","date":"2017-05-15","wday":1,"wnumber":"20","mday":15,"include_date":false,"excluded_date":false,"in_periods":true},{"day":"mardi","date":"2017-05-16","wday":2,"wnumber":"20","mday":16,"include_date":false,"excluded_date":false,"in_periods":true},{"day":"mercredi","date":"2017-05-17","wday":3,"wnumber":"20","mday":17,"include_date":false,"excluded_date":false,"in_periods":true},{"day":"jeudi","date":"2017-05-18","wday":4,"wnumber":"20","mday":18,"include_date":false,"excluded_date":false,"in_periods":true},{"day":"vendredi","date":"2017-05-19","wday":5,"wnumber":"20","mday":19,"include_date":false,"excluded_date":false,"in_periods":true},{"day":"samedi","date":"2017-05-20","wday":6,"wnumber":"20","mday":20,"include_date":false,"excluded_date":false,"in_periods":true},{"day":"dimanche","date":"2017-05-21","wday":0,"wnumber":"20","mday":21,"include_date":false,"excluded_date":false,"in_periods":true},{"day":"lundi","date":"2017-05-22","wday":1,"wnumber":"21","mday":22,"include_date":false,"excluded_date":false,"in_periods":true},{"day":"mardi","date":"2017-05-23","wday":2,"wnumber":"21","mday":23,"include_date":false,"excluded_date":false,"in_periods":true},{"day":"mercredi","date":"2017-05-24","wday":3,"wnumber":"21","mday":24,"include_date":false,"excluded_date":false,"in_periods":true},{"day":"jeudi","date":"2017-05-25","wday":4,"wnumber":"21","mday":25,"include_date":false,"excluded_date":false,"in_periods":false},{"day":"vendredi","date":"2017-05-26","wday":5,"wnumber":"21","mday":26,"include_date":false,"excluded_date":false,"in_periods":false},{"day":"samedi","date":"2017-05-27","wday":6,"wnumber":"21","mday":27,"include_date":false,"excluded_date":false,"in_periods":false},{"day":"dimanche","date":"2017-05-28","wday":0,"wnumber":"21","mday":28,"include_date":false,"excluded_date":false,"in_periods":false},{"day":"lundi","date":"2017-05-29","wday":1,"wnumber":"22","mday":29,"include_date":false,"excluded_date":false,"in_periods":false},{"day":"mardi","date":"2017-05-30","wday":2,"wnumber":"22","mday":30,"include_date":false,"excluded_date":false,"in_periods":false},{"day":"mercredi","date":"2017-05-31","wday":3,"wnumber":"22","mday":31,"include_date":false,"excluded_date":false,"in_periods":false}] +let time_table_dates = [] + let json = { current_month: current_month, current_periode_range: current_periode_range, periode_range: periode_range, time_table_periods: time_table_periods, - day_types: strDayTypes + day_types: strDayTypes, + time_table_dates: time_table_dates } describe('timetable reducer with empty state', () => { @@ -26,7 +29,8 @@ describe('timetable reducer with empty state', () => { current_month: [], current_periode_range: "", periode_range: [], - time_table_periods: [] + time_table_periods: [], + time_table_dates: [] } }) @@ -42,6 +46,7 @@ describe('timetable reducer with empty state', () => { current_periode_range: current_periode_range, periode_range: periode_range, time_table_periods: time_table_periods, + time_table_dates: time_table_dates } expect( timetableReducer(state, { @@ -59,6 +64,7 @@ describe('timetable reducer with filled state', () => { current_periode_range: current_periode_range, periode_range: periode_range, time_table_periods: time_table_periods, + time_table_dates: time_table_dates } }) @@ -130,45 +136,79 @@ describe('timetable reducer with filled state', () => { ).toEqual(state) }) - it('should handle INCLUDE_DATE_IN_PERIOD', () => { + it('should handle INCLUDE_DATE_IN_PERIOD and add in_day if TT doesnt have it', () => { + let newDates = state.time_table_dates.concat({date: "2017-05-05", in_out: true}) + let newState = Object.assign({}, state, {time_table_dates: newDates}) state.current_month[4].include_date = true expect( timetableReducer(state, { type: 'INCLUDE_DATE_IN_PERIOD', index: 4, - dayTypes: arrDayTypes + dayTypes: arrDayTypes, + date: "2017-05-05" }) - ).toEqual(state) + ).toEqual(newState) + }) + + it('should handle INCLUDE_DATE_IN_PERIOD and remove in_day if TT has it', () => { + state.current_month[4].include_date = true + state.time_table_dates.push({date: "2017-05-05", in_out: true}) + let newState = Object.assign({}, state, {time_table_dates: []}) + expect( + timetableReducer(state, { + type: 'INCLUDE_DATE_IN_PERIOD', + index: 4, + dayTypes: arrDayTypes, + date: "2017-05-05" + }) + ).toEqual(newState) }) - it('should handle EXCLUDE_DATE_FROM_PERIOD', () => { + it('should handle EXCLUDE_DATE_FROM_PERIOD and add out_day if TT doesnt have it', () => { + let newDates = state.time_table_dates.concat({date: "2017-05-01", in_out: false}) + let newState = Object.assign({}, state, {time_table_dates: newDates}) state.current_month[0].excluded_date = true expect( timetableReducer(state, { type: 'EXCLUDE_DATE_FROM_PERIOD', index: 0, - dayTypes: arrDayTypes + dayTypes: arrDayTypes, + date: "2017-05-01" }) - ).toEqual(state) + ).toEqual(newState) + }) + + it('should handle EXCLUDE_DATE_FROM_PERIOD and remove out_day if TT has it', () => { + state.time_table_dates = [{date: "2017-05-01", in_out: false}] + state.current_month[0].excluded_date = true + let newState = Object.assign({}, state, {time_table_dates: []}) + expect( + timetableReducer(state, { + type: 'EXCLUDE_DATE_FROM_PERIOD', + index: 0, + dayTypes: arrDayTypes, + date: "2017-05-01" + }) + ).toEqual(newState) }) - it('should handle VALIDATE_PERIOD_FORM', () => { - state.current_month[13].in_periods = false - state.time_table_periods[4].period_start = '2017-05-15' + it('should handle VALIDATE_PERIOD_FORM and add period if modalProps index = false', () => { + let newPeriods = state.time_table_periods.concat({"period_start": "2018-05-15", "period_end": "2018-05-24"}) + let newState = Object.assign({}, state, {time_table_periods: newPeriods}) let modalProps = { active: false, begin: { day: '15', month: '05', - year: '2017' + year: '2018' }, end: { day: '24', month: '05', - year: '2017' + year: '2018' }, error: '', - index: 4 + index: false } expect( timetableReducer(state, { @@ -177,8 +217,9 @@ describe('timetable reducer with filled state', () => { timeTablePeriods: state.time_table_periods, metas: { day_types: arrDayTypes - } + }, + timetableInDates: state.time_table_dates.filter(d => d.in_out == true) }) - ).toEqual(state) + ).toEqual(newState) }) }) diff --git a/spec/javascripts/vehicle_journeys/actions_spec.js b/spec/javascripts/vehicle_journeys/actions_spec.js index d96baf8ef..707ae22cb 100644 --- a/spec/javascripts/vehicle_journeys/actions_spec.js +++ b/spec/javascripts/vehicle_journeys/actions_spec.js @@ -165,12 +165,12 @@ describe('when updating vjas time', () => { }) describe('when clicking on validate button inside shifting modal', () => { it('should create an action to shift a vehiclejourney schedule', () => { - const data = {} + const addtionalTime = 0 const expectedAction = { type: 'SHIFT_VEHICLEJOURNEY', - data + addtionalTime } - expect(actions.shiftVehicleJourney(data)).toEqual(expectedAction) + expect(actions.shiftVehicleJourney(addtionalTime)).toEqual(expectedAction) }) }) describe('when clicking on validate button inside editing modal', () => { @@ -187,14 +187,16 @@ describe('when clicking on validate button inside editing modal', () => { }) describe('when clicking on validate button inside duplicating modal', () => { it('should create an action to duplicate a vehiclejourney schedule', () => { - const data = {} + const addtionalTime = 0 const departureDelta = 0 + const duplicateNumber = 1 const expectedAction = { type: 'DUPLICATE_VEHICLEJOURNEY', - data, + addtionalTime, + duplicateNumber, departureDelta } - expect(actions.duplicateVehicleJourney(data, departureDelta)).toEqual(expectedAction) + expect(actions.duplicateVehicleJourney(addtionalTime, duplicateNumber, departureDelta)).toEqual(expectedAction) }) }) describe('when clicking on edit notes modal', () => { @@ -432,3 +434,16 @@ describe('when using select2 to pick a company', () => { expect(actions.select2Company(selectedCompany)).toEqual(expectedAction) }) }) +describe('when using select2 to unselect a company', () => { + it('should create an action to unselect a company inside modal', () => { + let selectedCompany = { + id: 1, + objectid: 2, + name: 'test', + } + const expectedAction = { + type: 'UNSELECT_CP_EDIT_MODAL' + } + expect(actions.unselect2Company()).toEqual(expectedAction) + }) +}) diff --git a/spec/javascripts/vehicle_journeys/reducers/modal_spec.js b/spec/javascripts/vehicle_journeys/reducers/modal_spec.js index c016812da..4530b5ee7 100644 --- a/spec/javascripts/vehicle_journeys/reducers/modal_spec.js +++ b/spec/javascripts/vehicle_journeys/reducers/modal_spec.js @@ -167,4 +167,13 @@ describe('modal reducer', () => { }) ).toEqual(Object.assign({}, state, {modalProps: newModalProps})) }) + + it('should handle UNSELECT_CP_EDIT_MODAL', () => { + let newModalProps = {selectedCompany : undefined} + expect( + modalReducer(state, { + type: 'UNSELECT_CP_EDIT_MODAL' + }) + ).toEqual(Object.assign({}, state, {modalProps: newModalProps})) + }) }) diff --git a/spec/javascripts/vehicle_journeys/reducers/vehicle_journeys_spec.js b/spec/javascripts/vehicle_journeys/reducers/vehicle_journeys_spec.js index 620e2ffdd..3b2137a2a 100644 --- a/spec/javascripts/vehicle_journeys/reducers/vehicle_journeys_spec.js +++ b/spec/javascripts/vehicle_journeys/reducers/vehicle_journeys_spec.js @@ -198,15 +198,12 @@ describe('vehicleJourneys reducer', () => { }, stop_area_object_id : "FR:92024:ZDE:420553:STIF" }] - let fakeData = { - objectid: {value : '11'}, - additional_time: {value: '5'} - } + let addtionalTime = 5 let newVJ = Object.assign({}, state[0], {vehicle_journey_at_stops: newVJAS}) expect( vjReducer(state, { type: 'SHIFT_VEHICLEJOURNEY', - data: fakeData + addtionalTime }) ).toEqual([newVJ, state[1]]) }) @@ -225,17 +222,17 @@ describe('vehicleJourneys reducer', () => { stop_area_object_id : "FR:92024:ZDE:420553:STIF" }] let departureDelta = 1 - let fakeData = { - duplicate_number: {value : 1}, - additional_time: {value: '5'} - } + let addtionalTime = 5 + let duplicateNumber = 1 + let newVJ = Object.assign({}, state[0], {vehicle_journey_at_stops: newVJAS, selected: false}) newVJ.published_journey_name = state[0].published_journey_name + '-0' delete newVJ['objectid'] expect( vjReducer(state, { type: 'DUPLICATE_VEHICLEJOURNEY', - data: fakeData, + addtionalTime, + duplicateNumber, departureDelta }) ).toEqual([state[0], newVJ, state[1]]) diff --git a/spec/lib/result_spec.rb b/spec/lib/result_spec.rb new file mode 100644 index 000000000..949de163c --- /dev/null +++ b/spec/lib/result_spec.rb @@ -0,0 +1,20 @@ +RSpec.describe Result do + + context 'is a wrapper of a value' do + it { expect( described_class.ok('hello').value ).to eq('hello') } + it { expect( described_class.error('hello').value ).to eq('hello') } + end + + context 'it has status information' do + it { expect( described_class.ok('hello') ).to be_ok } + it { expect( described_class.ok('hello').status ).to eq(:ok) } + + it { expect( described_class.error('hello') ).not_to be_ok } + it { expect( described_class.error('hello').status ).to eq(:error) } + end + + context 'nil is just another value' do + it { expect( described_class.ok(nil) ).to be_ok } + it { expect( described_class.ok(nil).value ).to be_nil } + end +end diff --git a/spec/models/api/v1/api_key_spec.rb b/spec/models/api/v1/api_key_spec.rb index eb8826c0e..b700429d3 100644 --- a/spec/models/api/v1/api_key_spec.rb +++ b/spec/models/api/v1/api_key_spec.rb @@ -1,13 +1,25 @@ -require 'spec_helper' +require 'rails_helper' -describe Api::V1::ApiKey, :type => :model do - let!(:referential){create(:referential)} - subject { Api::V1::ApiKey.create( :name => "test", :referential => referential)} +RSpec.describe Api::V1::ApiKey, type: :model do + subject { create(:api_key) } - it "test" do - expect(subject).to be_valid - expect(subject.referential).to eq(referential) + it { should validate_presence_of :organisation } + it 'should have a valid factory' do + expect(build(:api_key)).to be_valid + end + + describe '#referential_from_token' do + it 'should return referential' do + referential = Api::V1::ApiKey.referential_from_token(subject.token) + expect(referential).to eq(subject.referential) + end end -end + describe '#organisation_from_token' do + it 'should return organisation' do + organisation = Api::V1::ApiKey.organisation_from_token(subject.token) + expect(organisation).to eq(subject.organisation) + end + end +end diff --git a/spec/models/chouette/footnote_spec.rb b/spec/models/chouette/footnote_spec.rb index 5c09e3931..98d751499 100644 --- a/spec/models/chouette/footnote_spec.rb +++ b/spec/models/chouette/footnote_spec.rb @@ -1,9 +1,22 @@ require 'spec_helper' -describe Chouette::Footnote do - - subject { build(:footnote) } +describe Chouette::Footnote, type: :model do + let(:footnote) { create(:footnote) } it { should validate_presence_of :line } + describe 'checksum' do + it_behaves_like 'checksum support', :footnote + + context '#checksum_attributes' do + it 'should return code and label' do + expected = [footnote.code, footnote.label] + expect(footnote.checksum_attributes).to include(*expected) + end + + it 'should not return other atrributes' do + expect(footnote.checksum_attributes).to_not include(footnote.updated_at) + end + end + end end diff --git a/spec/models/chouette/journey_pattern_spec.rb b/spec/models/chouette/journey_pattern_spec.rb index 26d220056..047022ade 100644 --- a/spec/models/chouette/journey_pattern_spec.rb +++ b/spec/models/chouette/journey_pattern_spec.rb @@ -1,6 +1,9 @@ require 'spec_helper' describe Chouette::JourneyPattern, :type => :model do + describe 'checksum' do + it_behaves_like 'checksum support', :journey_pattern + end # context 'validate minimum stop_points size' do # let(:journey_pattern) { create :journey_pattern } diff --git a/spec/models/chouette/route/route_base_spec.rb b/spec/models/chouette/route/route_base_spec.rb index 08f201022..c93b311ff 100644 --- a/spec/models/chouette/route/route_base_spec.rb +++ b/spec/models/chouette/route/route_base_spec.rb @@ -1,6 +1,9 @@ RSpec.describe Chouette::Route, :type => :model do subject { create(:route) } + describe 'checksum' do + it_behaves_like 'checksum support', :route + end describe '#objectid' do subject { super().objectid } @@ -62,8 +65,4 @@ RSpec.describe Chouette::Route, :type => :model do end end end - end - - - diff --git a/spec/models/chouette/routing_constraint_zone_spec.rb b/spec/models/chouette/routing_constraint_zone_spec.rb index 0165c369d..054cfb9e6 100644 --- a/spec/models/chouette/routing_constraint_zone_spec.rb +++ b/spec/models/chouette/routing_constraint_zone_spec.rb @@ -9,6 +9,10 @@ describe Chouette::RoutingConstraintZone, type: :model do # shoulda matcher to validate length of array ? xit { is_expected.to validate_length_of(:stop_point_ids).is_at_least(2) } + describe 'checksum' do + it_behaves_like 'checksum support', :routing_constraint_zone + end + describe 'validations' do it 'validates the presence of route_id' do expect { diff --git a/spec/models/chouette/time_table_period_spec.rb b/spec/models/chouette/time_table_period_spec.rb index 07dc602cb..cc1a3ae09 100644 --- a/spec/models/chouette/time_table_period_spec.rb +++ b/spec/models/chouette/time_table_period_spec.rb @@ -4,11 +4,15 @@ describe Chouette::TimeTablePeriod, :type => :model do let!(:time_table) { create(:time_table)} subject { create(:time_table_period ,:time_table => time_table, :period_start => Date.new(2014,6,30), :period_end => Date.new(2014,7,6) ) } - let!(:p2) {create(:time_table_period ,:time_table => time_table, :period_start => Date.new(2014,7,6), :period_end => Date.new(2014,7,14) ) } + let!(:p2) {create(:time_table_period ,:time_table => time_table, :period_start => Date.new(2014,7,6), :period_end => Date.new(2014,7,14) ) } it { is_expected.to validate_presence_of :period_start } it { is_expected.to validate_presence_of :period_end } - + + describe 'checksum' do + it_behaves_like 'checksum support', :time_table_period + end + describe "#overlap" do context "when periods intersect, " do it "should detect period overlap" do diff --git a/spec/models/chouette/time_table_spec.rb b/spec/models/chouette/time_table_spec.rb index f13e13d52..c4eaeaaf0 100644 --- a/spec/models/chouette/time_table_spec.rb +++ b/spec/models/chouette/time_table_spec.rb @@ -840,252 +840,15 @@ end :period_end => Date.new(2013, 05, 30)) expect(time_table.intersects([ Date.new(2013, 05, 27), Date.new(2013, 05, 28)])).to eq([ Date.new(2013, 05, 27), Date.new(2013, 05, 28)]) end - - - end - - describe "#include_day?" do - it "should return true if a date equal day" do - time_table = Chouette::TimeTable.create!(:comment => "Test", :objectid => "test:Timetable:1") - time_table.dates << Chouette::TimeTableDate.new( :date => Date.today, :in_out => true) - expect(time_table.include_day?(Date.today)).to eq(true) - end - - it "should return true if a period include day" do - time_table = Chouette::TimeTable.create!(:comment => "Test", :objectid => "test:Timetable:1", :int_day_types => 12) # Day type monday and tuesday - time_table.periods << Chouette::TimeTablePeriod.new( - :period_start => Date.new(2013, 05, 27), - :period_end => Date.new(2013, 05, 29)) - expect(time_table.include_day?( Date.new(2013, 05, 27))).to eq(true) - end - end - - describe "#include_in_dates?" do - it "should return true if a date equal day" do - time_table = Chouette::TimeTable.create!(:comment => "Test", :objectid => "test:Timetable:1") - time_table.dates << Chouette::TimeTableDate.new( :date => Date.today, :in_out => true) - expect(time_table.include_in_dates?(Date.today)).to eq(true) - end - - it "should return false if a period include day but that is exclued" do - time_table = Chouette::TimeTable.create!(:comment => "Test", :objectid => "test:Timetable:1", :int_day_types => 12) # Day type monday and tuesday - excluded_date = Date.new(2013, 05, 27) - time_table.dates << Chouette::TimeTableDate.new( :date => excluded_date, :in_out => false) - expect(time_table.include_in_dates?( excluded_date)).to be_falsey - end - end - - describe "#include_in_periods?" do - it "should return true if a period include day" do - time_table = Chouette::TimeTable.create!(:comment => "Test", :objectid => "test:Timetable:1", :int_day_types => 4) - time_table.periods << Chouette::TimeTablePeriod.new( - :period_start => Date.new(2012, 1, 1), - :period_end => Date.new(2012, 01, 30)) - expect(time_table.include_in_periods?(Date.new(2012, 1, 2))).to eq(true) - end - - it "should return false if a period include day but that is exclued" do - time_table = Chouette::TimeTable.create!(:comment => "Test", :objectid => "test:Timetable:1", :int_day_types => 12) # Day type monday and tuesday - excluded_date = Date.new(2013, 05, 27) - time_table.dates << Chouette::TimeTableDate.new( :date => excluded_date, :in_out => false) - time_table.periods << Chouette::TimeTablePeriod.new( - :period_start => Date.new(2013, 05, 27), - :period_end => Date.new(2013, 05, 29)) - expect(time_table.include_in_periods?( excluded_date)).to be_falsey - end - end - - describe "#include_in_overlap_dates?" do - it "should return true if a day is included in overlap dates" do - time_table = Chouette::TimeTable.create!(:comment => "Test", :objectid => "test:Timetable:1", :int_day_types => 4) - time_table.periods << Chouette::TimeTablePeriod.new( - :period_start => Date.new(2012, 1, 1), - :period_end => Date.new(2012, 01, 30)) - time_table.dates << Chouette::TimeTableDate.new( :date => Date.new(2012, 1, 2), :in_out => true) - expect(time_table.include_in_overlap_dates?(Date.new(2012, 1, 2))).to eq(true) - end - it "should return false if the day is excluded" do - time_table = Chouette::TimeTable.create!(:comment => "Test", :objectid => "test:Timetable:1", :int_day_types => 4) - time_table.periods << Chouette::TimeTablePeriod.new( - :period_start => Date.new(2012, 1, 1), - :period_end => Date.new(2012, 01, 30)) - time_table.dates << Chouette::TimeTableDate.new( :date => Date.new(2012, 1, 2), :in_out => false) - expect(time_table.include_in_overlap_dates?(Date.new(2012, 1, 2))).to be_falsey - end - end - - describe "#dates" do - it "should have with position 0" do - expect(subject.dates.first.position).to eq(0) - end - context "when first date has been removed" do - before do - subject.dates.first.destroy - end - it "should begin with position 0" do - expect(subject.dates.first.position).to eq(0) - end - end - end - describe "#validity_out_between?" do - let(:empty_tm) {build(:time_table)} - it "should be false if empty calendar" do - expect(empty_tm.validity_out_between?( Date.today, Date.today + 7.day)).to be_falsey - end - it "should be true if caldendar is out during start_date and end_date period" do - start_date = subject.bounding_dates.max - 2.day - end_date = subject.bounding_dates.max + 2.day - expect(subject.validity_out_between?( start_date, end_date)).to be_truthy - end - it "should be false if calendar is out on start date" do - start_date = subject.bounding_dates.max - end_date = subject.bounding_dates.max + 2.day - expect(subject.validity_out_between?( start_date, end_date)).to be_falsey - end - it "should be false if calendar is out on end date" do - start_date = subject.bounding_dates.max - 2.day - end_date = subject.bounding_dates.max - expect(subject.validity_out_between?( start_date, end_date)).to be_truthy - end - it "should be false if calendar is out after start_date" do - start_date = subject.bounding_dates.max + 2.day - end_date = subject.bounding_dates.max + 4.day - expect(subject.validity_out_between?( start_date, end_date)).to be_falsey - end - end - describe "#validity_out_from_on?" do - let(:empty_tm) {build(:time_table)} - it "should be false if empty calendar" do - expect(empty_tm.validity_out_from_on?( Date.today)).to be_falsey - end - it "should be true if caldendar ends on expected date" do - expected_date = subject.bounding_dates.max - expect(subject.validity_out_from_on?( expected_date)).to be_truthy - end - it "should be true if calendar ends before expected date" do - expected_date = subject.bounding_dates.max + 30.day - expect(subject.validity_out_from_on?( expected_date)).to be_truthy - end - it "should be false if calendars ends after expected date" do - expected_date = subject.bounding_dates.max - 30.day - expect(subject.validity_out_from_on?( expected_date)).to be_falsey - end - end - describe "#bounding_dates" do - context "when timetable contains only periods" do - before do - subject.dates = [] - subject.save - end - it "should retreive periods.period_start.min and periods.period_end.max" do - expect(subject.bounding_dates.min).to eq(subject.periods.map(&:period_start).min) - expect(subject.bounding_dates.max).to eq(subject.periods.map(&:period_end).max) - end - end - context "when timetable contains only dates" do - before do - subject.periods = [] - subject.save - end - it "should retreive dates.min and dates.max" do - expect(subject.bounding_dates.min).to eq(subject.dates.map(&:date).min) - expect(subject.bounding_dates.max).to eq(subject.dates.map(&:date).max) - end - end - it "should contains min date" do - min_date = subject.bounding_dates.min - subject.dates.each do |tm_date| - expect(min_date <= tm_date.date).to be_truthy - end - subject.periods.each do |tm_period| - expect(min_date <= tm_period.period_start).to be_truthy - end - - end - it "should contains max date" do - max_date = subject.bounding_dates.max - subject.dates.each do |tm_date| - expect(tm_date.date <= max_date).to be_truthy - end - subject.periods.each do |tm_period| - expect(tm_period.period_end <= max_date).to be_truthy - end - - end - end - describe "#periods" do - it "should begin with position 0" do - expect(subject.periods.first.position).to eq(0) - end - context "when first period has been removed" do - before do - subject.periods.first.destroy - end - it "should begin with position 0" do - expect(subject.periods.first.position).to eq(0) - end - end - it "should have period_start before period_end" do - period = Chouette::TimeTablePeriod.new - period.period_start = Date.today - period.period_end = Date.today + 10 - expect(period.valid?).to be_truthy - end - it "should not have period_start after period_end" do - period = Chouette::TimeTablePeriod.new - period.period_start = Date.today - period.period_end = Date.today - 10 - expect(period.valid?).to be_falsey - end - it "should not have period_start equal to period_end" do - period = Chouette::TimeTablePeriod.new - period.period_start = Date.today - period.period_end = Date.today - expect(period.valid?).to be_falsey - end end - describe "#effective_days_of_periods" do - before do - subject.periods.clear - subject.periods << Chouette::TimeTablePeriod.new( - :period_start => Date.new(2014, 6, 30), - :period_end => Date.new(2014, 7, 6)) - subject.int_day_types = 4|8|16 - end - it "should return monday to wednesday" do - expect(subject.effective_days_of_periods.size).to eq(3) - expect(subject.effective_days_of_periods[0]).to eq(Date.new(2014, 6, 30)) - expect(subject.effective_days_of_periods[1]).to eq(Date.new(2014, 7, 1)) - expect(subject.effective_days_of_periods[2]).to eq(Date.new(2014, 7, 2)) - end - it "should return thursday" do - expect(subject.effective_days_of_periods(Chouette::TimeTable.valid_days(32)).size).to eq(1) - expect(subject.effective_days_of_periods(Chouette::TimeTable.valid_days(32))[0]).to eq(Date.new(2014, 7, 3)) - end - - end + # it { is_expected.to validate_presence_of :comment } + # it { is_expected.to validate_uniqueness_of :objectid } - describe "#included_days" do - before do - subject.dates.clear - subject.dates << Chouette::TimeTableDate.new( :date => Date.new(2014,7,16), :in_out => true) - subject.dates << Chouette::TimeTableDate.new( :date => Date.new(2014,7,17), :in_out => false) - subject.dates << Chouette::TimeTableDate.new( :date => Date.new(2014,7,18), :in_out => true) - subject.dates << Chouette::TimeTableDate.new( :date => Date.new(2014,7,19), :in_out => false) - subject.dates << Chouette::TimeTableDate.new( :date => Date.new(2014,7,20), :in_out => true) - end - it "should return 3 dates" do - days = subject.included_days - expect(days.size).to eq(3) - expect(days[0]).to eq(Date.new(2014, 7, 16)) - expect(days[1]).to eq(Date.new(2014,7, 18)) - expect(days[2]).to eq(Date.new(2014, 7,20)) - end + describe 'checksum' do + it_behaves_like 'checksum support', :time_table end - - describe "#excluded_days" do before do subject.dates.clear @@ -1223,5 +986,4 @@ end expect(subject.tag_list.size).to eq(2) end end - end diff --git a/spec/models/chouette/vehicle_journey_at_stop_spec.rb b/spec/models/chouette/vehicle_journey_at_stop_spec.rb index d999ed1a8..4f9d12730 100644 --- a/spec/models/chouette/vehicle_journey_at_stop_spec.rb +++ b/spec/models/chouette/vehicle_journey_at_stop_spec.rb @@ -1,6 +1,21 @@ require 'spec_helper' RSpec.describe Chouette::VehicleJourneyAtStop, type: :model do + describe 'checksum' do + let(:at_stop) { build_stubbed(:vehicle_journey_at_stop) } + + it_behaves_like 'checksum support', :vehicle_journey_at_stop + + context '#checksum_attributes' do + it 'should return attributes' do + expected = [at_stop.departure_time.to_s(:time), at_stop.arrival_time.to_s(:time)] + expected << at_stop.departure_day_offset.to_s + expected << at_stop.arrival_day_offset.to_s + expect(at_stop.checksum_attributes).to include(*expected) + end + end + end + describe "#day_offset_outside_range?" do let (:at_stop) { build_stubbed(:vehicle_journey_at_stop) } diff --git a/spec/models/chouette/vehicle_journey_spec.rb b/spec/models/chouette/vehicle_journey_spec.rb index 3c04a77cc..52f2ab42d 100644 --- a/spec/models/chouette/vehicle_journey_spec.rb +++ b/spec/models/chouette/vehicle_journey_spec.rb @@ -17,8 +17,13 @@ describe Chouette::VehicleJourney, :type => :model do expect(vehicle_journey).to be_valid end + describe 'checksum' do + it_behaves_like 'checksum support', :vehicle_journey + end + describe "vjas_departure_time_must_be_before_next_stop_arrival_time", skip: "Validation currently commented out because it interferes with day offsets" do + let(:vehicle_journey) { create :vehicle_journey } let(:vjas) { vehicle_journey.vehicle_journey_at_stops } diff --git a/spec/models/import_spec.rb b/spec/models/import_spec.rb index a2855d086..76f945871 100644 --- a/spec/models/import_spec.rb +++ b/spec/models/import_spec.rb @@ -1,10 +1,158 @@ -require 'rails_helper' - RSpec.describe Import, :type => :model do + it { should belong_to(:referential) } it { should belong_to(:workbench) } + it { should belong_to(:parent) } - it { should enumerize(:status).in(:new, :pending, :successful, :failed, :canceled, :running, :aborted ) } + it { should enumerize(:status).in("aborted", "canceled", "failed", "new", "pending", "running", "successful") } it { should validate_presence_of(:file) } + it { should validate_presence_of(:workbench) } + it { should validate_presence_of(:creator) } + + let(:workbench_import) { build_stubbed(:workbench_import) } + let(:workbench_import_with_completed_steps) do + workbench_import = build_stubbed( + :workbench_import, + total_steps: 2, + current_step: 2 + ) + end + + let(:netex_import) do + netex_import = build_stubbed( + :netex_import, + parent: workbench_import + ) + end + + describe "#notify_parent" do + it "must call #child_change on its parent" do + allow(netex_import).to receive(:update) + + expect(workbench_import).to receive(:child_change).with(netex_import) + + netex_import.notify_parent + end + + it "must update the :notified_parent_at field of the child import" do + allow(workbench_import).to receive(:child_change) + + Timecop.freeze(DateTime.now) do + expect(netex_import).to receive(:update).with( + notified_parent_at: DateTime.now + ) + + netex_import.notify_parent + end + end + end + + describe "#child_change" do + shared_examples( + "updates :status to failed when child status indicates failure" + ) do |failure_status| + it "updates :status to failed when child status indicates failure" do + allow(workbench_import).to receive(:update) + + netex_import = build_stubbed( + :netex_import, + parent: workbench_import, + status: failure_status + ) + + expect(workbench_import).to receive(:update).with(status: 'failed') + + workbench_import.child_change(netex_import) + end + end + + include_examples( + "updates :status to failed when child status indicates failure", + "failed" + ) + include_examples( + "updates :status to failed when child status indicates failure", + "aborted" + ) + include_examples( + "updates :status to failed when child status indicates failure", + "canceled" + ) + + it "updates :status to successful when #ready?" do + expect(workbench_import).to receive(:update).with(status: 'successful') + + workbench_import.child_change(netex_import) + end + + it "updates :status to failed when #ready? and child is failed" do + netex_import = build_stubbed( + :netex_import, + parent: workbench_import, + status: :failed + ) + + expect(workbench_import).to receive(:update).with(status: 'failed') + + workbench_import.child_change(netex_import) + end + + shared_examples( + "doesn't update :status if parent import status is finished" + ) do |finished_status| + it "doesn't update :status if parent import status is finished" do + workbench_import = build_stubbed( + :workbench_import, + total_steps: 2, + current_step: 2, + status: finished_status + ) + child = double('Import') + + expect(workbench_import).not_to receive(:update) + + workbench_import.child_change(child) + end + end + + include_examples( + "doesn't update :status if parent import status is finished", + "successful" + ) + include_examples( + "doesn't update :status if parent import status is finished", + "failed" + ) + include_examples( + "doesn't update :status if parent import status is finished", + "aborted" + ) + include_examples( + "doesn't update :status if parent import status is finished", + "canceled" + ) + end + + describe "#ready?" do + it "returns true if #current_step == #total_steps" do + import = build_stubbed( + :import, + total_steps: 4, + current_step: 4 + ) + + expect(import.ready?).to be true + end + + it "returns false if #current_step != #total_steps" do + import = build_stubbed( + :import, + total_steps: 6, + current_step: 3 + ) + + expect(import.ready?).to be false + end + end end diff --git a/spec/models/organisation_spec.rb b/spec/models/organisation_spec.rb index 527f71015..b16324a56 100644 --- a/spec/models/organisation_spec.rb +++ b/spec/models/organisation_spec.rb @@ -1,5 +1,3 @@ -require 'spec_helper' - describe Organisation, :type => :model do it { should validate_presence_of(:name) } it { should validate_uniqueness_of(:code) } @@ -17,7 +15,7 @@ describe Organisation, :type => :model do let(:conf) { Rails.application.config.stif_portail_api } before :each do stub_request(:get, "#{conf[:url]}/api/v1/organizations"). - with(headers: { 'Authorization' => "Token token=\"#{conf[:key]}\"" }). + with(stub_headers(authorization_token: conf[:key])). to_return(body: File.open(File.join(Rails.root, 'spec', 'fixtures', 'organizations.json')), status: 200) end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 3a9ae37e9..51ccfccd3 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -67,7 +67,7 @@ RSpec.describe User, :type => :model do let(:conf) { Rails.application.config.stif_portail_api } before :each do stub_request(:get, "#{conf[:url]}/api/v1/users"). - with(headers: { 'Authorization' => "Token token=\"#{conf[:key]}\"" }). + with(stub_headers(authorization_token: conf[:key])). to_return(body: File.open(File.join(Rails.root, 'spec', 'fixtures', 'users.json')), status: 200) end diff --git a/spec/policies/api_key_policy_spec.rb b/spec/policies/api_key_policy_spec.rb new file mode 100644 index 000000000..5b9d59fa3 --- /dev/null +++ b/spec/policies/api_key_policy_spec.rb @@ -0,0 +1,28 @@ +require 'rails_helper' + +RSpec.describe ApiKeyPolicy do + + let(:user) { User.new } + + subject { described_class } + + permissions ".scope" do + pending "add some examples to (or delete) #{__FILE__}" + end + + permissions :show? do + pending "add some examples to (or delete) #{__FILE__}" + end + + permissions :create? do + pending "add some examples to (or delete) #{__FILE__}" + end + + permissions :update? do + pending "add some examples to (or delete) #{__FILE__}" + end + + permissions :destroy? do + pending "add some examples to (or delete) #{__FILE__}" + end +end diff --git a/spec/requests/api/v1/netex_import_spec.rb b/spec/requests/api/v1/netex_import_spec.rb new file mode 100644 index 000000000..fd5f6d497 --- /dev/null +++ b/spec/requests/api/v1/netex_import_spec.rb @@ -0,0 +1,100 @@ +RSpec.describe "NetexImport", type: :request do + + describe 'POST netex_imports' do + + let( :referential ){ create :referential } + let( :workbench ){ referential.workbench } + + + let( :file_path ){ fixtures_path 'single_reference_import.zip' } + let( :file ){ fixture_file_upload( file_path ) } + + let( :post_request ) do + -> (attributes) do + post api_v1_netex_imports_path(format: :json), + attributes, + authorization + end + end + + let( :legal_attributes ) do + { + name: 'hello world', + file: file, + workbench_id: workbench.id + } + end + + + context 'with correct credentials and correct request' do + let( :authorization ){ authorization_token_header( get_api_key.token ) } + + it 'succeeds' do + post_request.(netex_import: legal_attributes) + expect( response ).to be_success + expect( json_response_body ).to eq( + 'id' => NetexImport.last.id, + 'referential_id' => Referential.last.id, + 'workbench_id' => workbench.id + ) + end + + it 'creates a NetexImport object in the DB' do + expect{ post_request.(netex_import: legal_attributes) }.to change{NetexImport.count}.by(1) + end + + it 'creates a correct Referential' do + legal_attributes # force object creation for correct to change behavior + expect{post_request.(netex_import: legal_attributes)}.to change{Referential.count}.by(1) + Referential.last.tap do | ref | + expect( ref.workbench_id ).to eq(workbench.id) + expect( ref.organisation_id ).to eq(workbench.organisation_id) + end + end + end + + + context 'with incorrect credentials and correct request' do + let( :authorization ){ authorization_token_header( "#{referential.id}-incorrect_token") } + + it 'does not create any DB object and does not succeed' do + legal_attributes # force object creation for correct to change behavior + expect{ post_request.(netex_import: legal_attributes) }.not_to change{Referential.count} + expect( response.status ).to eq(401) + end + + end + + context 'with correct credentials and incorrect request' do + let( :authorization ){ authorization_token_header( get_api_key.token ) } + + shared_examples_for 'illegal attributes' do |bad_attribute, illegal_value=nil, referential_count: 0| + context "missing #{bad_attribute}" do + let!( :illegal_attributes ){ legal_attributes.merge( bad_attribute => illegal_value ) } + it 'does not succeed' do + post_request.(netex_import: illegal_attributes) + expect( response.status ).to eq(406) + expect( json_response_body['errors'][bad_attribute.to_s] ).not_to be_empty + end + + it 'does not create an Import object' do + expect{ post_request.(netex_import: illegal_attributes) }.not_to change{Import.count} + end + + it 'might create a referential' do + expect{ post_request.(netex_import: illegal_attributes) }.to change{Referential.count}.by(referential_count) + end + end + end + + it_behaves_like 'illegal attributes', :file, referential_count: 1 + it_behaves_like 'illegal attributes', :workbench_id + context 'name already taken' do + before do + create :referential, name: 'already taken' + end + it_behaves_like 'illegal attributes', :name, 'already taken' + end + end + end +end diff --git a/spec/routing/api/v1/access_links_routes_spec.rb b/spec/routing/api/v1/access_links_routes_spec.rb new file mode 100644 index 000000000..9164d3f05 --- /dev/null +++ b/spec/routing/api/v1/access_links_routes_spec.rb @@ -0,0 +1,9 @@ +RSpec.describe Api::V1::AccessLinksController, type: :controller do + + it 'routes to index' do + expect( get: '/api/v1/access_links' ).to route_to( + controller: 'api/v1/access_links', + action: 'index' + ) + end +end diff --git a/spec/routing/group_of_lines_spec.rb b/spec/routing/group_of_lines_spec.rb index 2a7262893..01ebeefe4 100644 --- a/spec/routing/group_of_lines_spec.rb +++ b/spec/routing/group_of_lines_spec.rb @@ -1,6 +1,4 @@ -require 'spec_helper' - -describe GroupOfLinesController do +RSpec.describe GroupOfLinesController do describe "routing" do it "not recognize #routes" do expect(get( "/line_referentials/1/group_of_lines/2/routes")).not_to route_to( diff --git a/spec/services/http_service_spec.rb b/spec/services/http_service_spec.rb new file mode 100644 index 000000000..8c8af480c --- /dev/null +++ b/spec/services/http_service_spec.rb @@ -0,0 +1,74 @@ +RSpec.describe HTTPService do + + subject{ described_class } + + %i{host params path result}.each do |param| + let(param){ double(param) } + end + let( :token ){ SecureRandom.hex } + + let( :faraday_connection ){ double('faraday_connection') } + let( :headers ){ {} } + + + context 'get_resource' do + let( :params ){ double('params') } + + it 'sets authorization and returns result' do + expect(Faraday).to receive(:new).with(url: host).and_yield(faraday_connection) + expect(faraday_connection).to receive(:adapter).with(Faraday.default_adapter) + expect(faraday_connection).to receive(:headers).and_return headers + expect(faraday_connection).to receive(:get).with(path, params).and_return(result) + + expect(subject.get_resource(host: host, path: path, token: token, params: params)).to eq(result) + expect(headers['Authorization']).to eq( "Token token=#{token.inspect}" ) + end + end + + context 'post_resource' do + %i{as_name mime_type name upload_io value}.each do | param | + let( param ){ double(param) } + end + + let( :upload_list ){ [value, mime_type, as_name] } + + it 'sets authorization and posts data' do + expect(Faraday::UploadIO).to receive(:new).with(*upload_list).and_return upload_io + expect(params).to receive(:update).with(name => upload_io) + + expect(Faraday).to receive(:new).with(url: host).and_yield(faraday_connection) + expect(faraday_connection).to receive(:adapter).with(Faraday.default_adapter) + expect(faraday_connection).to receive(:headers).and_return headers + expect(faraday_connection).to receive(:request).with(:multipart) + expect(faraday_connection).to receive(:request).with(:url_encoded) + + expect(faraday_connection).to receive(:post).with(path, params).and_return(result) + + expect(subject.post_resource( + host: host, + path: path, + token: token, + params: params, + upload: {name => upload_list} )).to eq(result) + expect(headers['Authorization']).to eq( "Token token=#{token.inspect}" ) + end + + end + + context 'get_json_resource' do + + let( :content ){ SecureRandom.hex } + + it 'delegates an parses the response' do + expect_it.to receive(:get_resource) + .with(host: host, path: path, token: token, params: params) + .and_return(double(body: {content: content}.to_json, status: 200)) + + expect( subject.get_json_resource( + host: host, + path: path, + token: token, + params: params) ).to eq('content' => content) + end + end +end diff --git a/spec/services/parent_import_notifier_spec.rb b/spec/services/parent_import_notifier_spec.rb new file mode 100644 index 000000000..3ab505f88 --- /dev/null +++ b/spec/services/parent_import_notifier_spec.rb @@ -0,0 +1,90 @@ +RSpec.describe ParentImportNotifier do + let(:workbench_import) { create(:workbench_import) } + + describe ".notify_when_finished" do + it "calls #notify_parent on finished imports" do + workbench_import = build_stubbed(:workbench_import) + + finished_statuses = [:failed, :successful, :aborted, :canceled] + netex_imports = [] + + finished_statuses.each do |status| + netex_imports << build_stubbed( + :netex_import, + parent: workbench_import, + status: status + ) + end + + netex_imports.each do |netex_import| + expect(netex_import).to receive(:notify_parent) + end + + ParentImportNotifier.notify_when_finished(netex_imports) + end + + it "doesn't call #notify_parent if its `notified_parent_at` is set" do + netex_import = create( + :netex_import, + parent: workbench_import, + status: :failed, + notified_parent_at: DateTime.now + ) + + expect(netex_import).not_to receive(:notify_parent) + + ParentImportNotifier.notify_when_finished + end + end + + describe ".imports_pending_notification" do + it "includes imports with a parent and `notified_parent_at` unset" do + netex_import = create( + :netex_import, + parent: workbench_import, + status: :successful, + notified_parent_at: nil + ) + + expect( + ParentImportNotifier.imports_pending_notification + ).to eq([netex_import]) + end + + it "doesn't include imports without a parent" do + create(:import, parent: nil) + + expect( + ParentImportNotifier.imports_pending_notification + ).to be_empty + end + + it "doesn't include imports that aren't finished" do + [:new, :pending, :running].each do |status| + create( + :netex_import, + parent: workbench_import, + status: status, + notified_parent_at: nil + ) + end + + expect( + ParentImportNotifier.imports_pending_notification + ).to be_empty + end + + it "doesn't include imports that have already notified their parent" do + create( + :netex_import, + parent: workbench_import, + status: :successful, + notified_parent_at: DateTime.now + ) + + expect( + ParentImportNotifier.imports_pending_notification + ).to be_empty + end + end +end diff --git a/spec/services/retry_service_spec.rb b/spec/services/retry_service_spec.rb new file mode 100644 index 000000000..bb3416373 --- /dev/null +++ b/spec/services/retry_service_spec.rb @@ -0,0 +1,137 @@ +RSpec.describe RetryService do + subject { described_class.new delays: [2, 3], rescue_from: [NameError, ArgumentError] } + + context 'no retry necessary' do + before do + expect( subject ).not_to receive(:sleep) + end + + it 'returns an ok result' do + expect( subject.execute { 42 } ).to eq(Result.ok(42)) + end + it 'does not fail on nil' do + expect( subject.execute { nil } ).to eq(Result.ok(nil)) + end + + it 'fails wihout retries if raising un unregistered exception' do + expect{ subject.execute{ raise KeyError } }.to raise_error(KeyError) + end + + end + + context 'all retries fail' do + before do + expect( subject ).to receive(:sleep).with(2) + expect( subject ).to receive(:sleep).with(3) + end + it 'fails after raising a registered exception n times' do + result = subject.execute{ raise ArgumentError } + expect( result.status ).to eq(:error) + expect( result.value ).to be_kind_of(ArgumentError) + end + it 'fails with an explicit try again (automatically registered exception)' do + result = subject.execute{ raise RetryService::Retry } + expect( result.status ).to eq(:error) + expect( result.value ).to be_kind_of(RetryService::Retry) + end + end + + context "if at first you don't succeed" do + before do + @count = 0 + expect( subject ).to receive(:sleep).with(2) + end + + it 'succeeds the second time' do + expect( subject.execute{ succeed_later(ArgumentError){ 42 } } ).to eq(Result.ok(42)) + end + + it 'succeeds the second time with try again (automatically registered exception)' do + expect( subject.execute{ succeed_later(RetryService::Retry){ 42 } } ).to eq(Result.ok(42)) + end + end + + context 'last chance' do + before do + @count = 0 + expect( subject ).to receive(:sleep).with(2) + expect( subject ).to receive(:sleep).with(3) + end + it 'succeeds the third time with try again (automatically registered exception)' do + result = subject.execute{ succeed_later(RetryService::Retry, count: 2){ 42 } } + expect( result ).to eq( Result.ok(42) ) + end + end + + context 'failure callback once' do + subject do + described_class.new delays: [2, 3], rescue_from: [NameError, ArgumentError] do |reason, count| + @reason=reason + @callback_count=count + @failures += 1 + end + end + + before do + @failures = 0 + @count = 0 + expect( subject ).to receive(:sleep).with(2) + end + + it 'succeeds the second time and calls the failure_callback once' do + subject.execute{ succeed_later(RetryService::Retry){ 42 } } + expect( @failures ).to eq(1) + end + it '... and the failure is passed into the callback' do + subject.execute{ succeed_later(RetryService::Retry){ 42 } } + expect( @reason ).to be_a(RetryService::Retry) + expect( @callback_count ).to eq(1) + end + end + + context 'failure callback twice' do + subject do + described_class.new delays: [2, 3], rescue_from: [NameError, ArgumentError] do |_reason, _count| + @failures += 1 + end + end + + before do + @failures = 0 + @count = 0 + expect( subject ).to receive(:sleep).with(2) + expect( subject ).to receive(:sleep).with(3) + end + + it 'succeeds the third time and calls the failure_callback twice' do + subject.execute{ succeed_later(NameError, count: 2){ 42 } } + expect( @failures ).to eq(2) + end + end + + context 'failure callback in constructor' do + subject do + described_class.new(delays: [1, 2], &method(:add2failures)) + end + before do + @failures = [] + @count = 0 + expect( subject ).to receive(:sleep).with(1) + expect( subject ).to receive(:sleep).with(2) + end + it 'succeeds the second time and calls the failure_callback once' do + subject.execute{ succeed_later(RetryService::Retry, count: 2){ 42 } } + expect( @failures ).to eq([1,2]) + end + end + + def add2failures( e, c) + @failures << c + end + + def succeed_later error, count: 1, &blk + return blk.() unless @count < count + @count += 1 + raise error, 'error' + end +end diff --git a/spec/services/zip_service/zip_entry_data_spec.rb b/spec/services/zip_service/zip_entry_data_spec.rb new file mode 100644 index 000000000..2a7226eb4 --- /dev/null +++ b/spec/services/zip_service/zip_entry_data_spec.rb @@ -0,0 +1,32 @@ +RSpec.describe ZipService do + + subject{ described_class.new(read_fixture('multiple_references_import.zip')) } + + it 'can group all entries' do + expect( subject.entry_groups.keys ).to eq(%w{ref1 ref2}) + end + + context 'creates correct zip data for each subdir' do + it 'e.g. reference1' do + reference1_stream = subject.entry_group_streams['ref1'] + control_stream = Zip::InputStream.open( reference1_stream ) + control_entries = described_class.entries(control_stream) + expect( control_entries.map{ |e| [e.name, e.get_input_stream.read]}.force ).to eq([ + ["multiref/ref1/", ""], + ["multiref/ref1/datum-1", "multi-ref1-datum1\n"], + ["multiref/ref1/datum-2", "multi-ref1-datum2\n"] + ]) + end + it 'e.g. reference2' do + reference2_stream = subject.entry_group_streams['ref2'] + control_stream = Zip::InputStream.open( reference2_stream ) + control_entries = described_class.entries(control_stream) + expect( control_entries.map{ |e| [e.name, e.get_input_stream.read]}.force ).to eq([ + ["multiref/ref2/", ""], + ["multiref/ref2/datum-1", "multi-ref2-datum1\n"], + ["multiref/ref2/datum-2", "multi-ref2-datum2\n"] + ]) + end + end + +end diff --git a/spec/services/zip_service/zip_entry_dirs_spec.rb b/spec/services/zip_service/zip_entry_dirs_spec.rb new file mode 100644 index 000000000..8ca1b0f1a --- /dev/null +++ b/spec/services/zip_service/zip_entry_dirs_spec.rb @@ -0,0 +1,33 @@ +RSpec.describe ZipService do + + let( :zip_service ){ described_class } + + let( :zip_data ){ File.read zip_file } + + shared_examples_for 'a correct zip entry reader' do + it 'gets all entries of the zip file' do + expect( zip_service.new(zip_data).entry_groups.keys ).to eq(expected) + end + end + + context 'single entry' do + let( :zip_file ){ fixtures_path 'multiple_references_import.zip' } + let( :expected ){ %w{ref1 ref2} } + + it_behaves_like 'a correct zip entry reader' + end + + context 'more entries' do + let( :zip_file ){ fixtures_path 'single_reference_import.zip' } + let( :expected ){ %w{ref} } + + it_behaves_like 'a correct zip entry reader' + end + + context 'illegal file' do + let( :zip_file ){ fixtures_path 'nozip.zip' } + let( :expected ){ [] } + + it_behaves_like 'a correct zip entry reader' + end +end diff --git a/spec/services/zip_service/zip_output_streams_spec.rb b/spec/services/zip_service/zip_output_streams_spec.rb new file mode 100644 index 000000000..742f9b996 --- /dev/null +++ b/spec/services/zip_service/zip_output_streams_spec.rb @@ -0,0 +1,8 @@ +RSpec.describe ZipService do + + subject{ described_class.new(read_fixture('multiple_references_import.zip')) } + + it "exposes its size" do + expect( subject.entry_group_streams.size ).to eq(2) + end +end diff --git a/spec/support/api_key.rb b/spec/support/api_key.rb index 9353fac15..cc08cd7f1 100644 --- a/spec/support/api_key.rb +++ b/spec/support/api_key.rb @@ -1,20 +1,28 @@ module ApiKeyHelper + def authorization_token_header(key) + {'Authorization' => "Token token=#{key}"} + end + def get_api_key - Api::V1::ApiKey.first_or_create( :referential_id => referential.id, :name => "test") + Api::V1::ApiKey.first_or_create(referential: referential, organisation: organisation) end + def config_formatted_request_with_authorization( format) request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Token.encode_credentials( get_api_key.token) request.accept = format end + def config_formatted_request_with_dummy_authorization( format) request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Token.encode_credentials( "dummy") request.accept = format end + def config_formatted_request_without_authorization( format) request.env['HTTP_AUTHORIZATION'] = nil request.accept = format end + def json_xml_format? request.accept == "application/json" || request.accept == "application/xml" end diff --git a/spec/support/checksum_support.rb b/spec/support/checksum_support.rb new file mode 100644 index 000000000..14ea3c55e --- /dev/null +++ b/spec/support/checksum_support.rb @@ -0,0 +1,53 @@ +shared_examples 'checksum support' do |factory_name| + let(:instance) { create(factory_name) } + + describe '#current_checksum_source' do + let(:attributes) { ['code_value', 'label_value'] } + let(:seperator) { ChecksumSupport::SEPARATOR } + let(:nil_value) { ChecksumSupport::VALUE_FOR_NIL_ATTRIBUTE } + + before do + allow_any_instance_of(instance.class).to receive(:checksum_attributes).and_return(attributes) + end + + it 'should separate attribute by seperator' do + expect(instance.current_checksum_source).to eq("code_value#{seperator}label_value") + end + + context 'nil value' do + let(:attributes) { ['code_value', nil] } + + it 'should replace nil attributes by default value' do + source = "code_value#{seperator}#{nil_value}" + expect(instance.current_checksum_source).to eq(source) + end + end + + context 'empty array' do + let(:attributes) { ['code_value', []] } + + it 'should convert to nil' do + source = "code_value#{seperator}#{nil_value}" + expect(instance.current_checksum_source).to eq(source) + end + end + end + + it 'should save checksum on create' do + expect(instance.checksum).to_not be_nil + end + + it 'should save checksum_source' do + expect(instance.checksum_source).to_not be_nil + end + + it 'should trigger set_current_checksum_source on save' do + expect(instance).to receive(:set_current_checksum_source) + instance.save + end + + it 'should trigger update_checksum on save' do + expect(instance).to receive(:update_checksum) + instance.save + end +end diff --git a/spec/support/fixtures_helper.rb b/spec/support/fixtures_helper.rb new file mode 100644 index 000000000..20963261b --- /dev/null +++ b/spec/support/fixtures_helper.rb @@ -0,0 +1,18 @@ +module Support + module FixturesHelper + def fixtures_path *segments + Rails.root.join( fixture_path, *segments ) + end + + def open_fixture *segments + File.open(fixtures_path(*segments)) + end + def read_fixture *segments + File.read(fixtures_path(*segments)) + end + end +end + +RSpec.configure do |c| + c.include Support::FixturesHelper +end diff --git a/spec/support/json_helper.rb b/spec/support/json_helper.rb new file mode 100644 index 000000000..a383981a0 --- /dev/null +++ b/spec/support/json_helper.rb @@ -0,0 +1,11 @@ +module Support + module JsonHelper + def json_response_body + JSON.parse(response.body) + end + end +end + +RSpec.configure do | config | + config.include Support::JsonHelper, type: :request +end diff --git a/spec/support/referential.rb b/spec/support/referential.rb index 57b510f69..c431856b8 100644 --- a/spec/support/referential.rb +++ b/spec/support/referential.rb @@ -12,6 +12,7 @@ module ReferentialHelper base.class_eval do extend ClassMethods alias_method :referential, :first_referential + alias_method :organisation, :first_organisation end end diff --git a/spec/support/shared_context.rb b/spec/support/shared_context.rb new file mode 100644 index 000000000..e9b0025a2 --- /dev/null +++ b/spec/support/shared_context.rb @@ -0,0 +1,15 @@ +shared_context 'iboo authenticated api user' do + let(:api_key) { create(:api_key, organisation: organisation) } + + before do + request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials(api_key.organisation.code, api_key.token) + end +end + +shared_context 'iboo wrong authorisation api user' do + let(:api_key) { create(:api_key, organisation: organisation) } + + before do + request.env['HTTP_AUTHORIZATION'] = ActionController::HttpAuthentication::Basic.encode_credentials('fake code', api_key.token) + end +end diff --git a/spec/support/webmock/helpers.rb b/spec/support/webmock/helpers.rb new file mode 100644 index 000000000..fc6c77850 --- /dev/null +++ b/spec/support/webmock/helpers.rb @@ -0,0 +1,18 @@ +module Support + module Webmock + module Helpers + def stub_headers(*args) + {headers: make_headers(*args)} + end + + def make_headers(headers={}, authorization_token:) + headers.merge('Authorization' => "Token token=#{authorization_token.inspect}") + end + end + end +end + +RSpec.configure do | conf | + conf.include Support::Webmock::Helpers, type: :model + conf.include Support::Webmock::Helpers, type: :worker +end diff --git a/spec/tasks/reflex_rake_spec.rb b/spec/tasks/reflex_rake_spec.rb index 04c5886aa..6ece223d2 100644 --- a/spec/tasks/reflex_rake_spec.rb +++ b/spec/tasks/reflex_rake_spec.rb @@ -5,7 +5,7 @@ describe 'reflex:sync' do before(:each) do ['getOP', 'getOR'].each do |method| stub_request(:get, "#{Rails.application.config.reflex_api_url}/?format=xml&idRefa=0&method=#{method}"). - to_return(body: File.open("#{fixture_path}/reflex.zip"), status: 200) + to_return(body: open_fixture('reflex.zip'), status: 200) end stop_area_ref = create(:stop_area_referential, name: 'Reflex') @@ -43,7 +43,7 @@ describe 'reflex:sync' do before(:each) do ['getOP', 'getOR'].each do |method| stub_request(:get, "#{Rails.application.config.reflex_api_url}/?format=xml&idRefa=0&method=#{method}"). - to_return(body: File.open("#{fixture_path}/reflex_updated.zip"), status: 200) + to_return(body: open_fixture('reflex_updated.zip'), status: 200) end Stif::ReflexSynchronization.synchronize end diff --git a/spec/workers/stop_area_referential_sync_worker_spec.rb b/spec/workers/stop_area_referential_sync_worker_spec.rb index 48b64e55e..50c7cf45f 100644 --- a/spec/workers/stop_area_referential_sync_worker_spec.rb +++ b/spec/workers/stop_area_referential_sync_worker_spec.rb @@ -1,4 +1,3 @@ -require 'rails_helper' RSpec.describe StopAreaReferentialSyncWorker, type: :worker do let!(:stop_area_referential_sync) { create :stop_area_referential_sync } diff --git a/spec/workers/workbench_import_worker_spec.rb b/spec/workers/workbench_import_worker_spec.rb new file mode 100644 index 000000000..b719cbb98 --- /dev/null +++ b/spec/workers/workbench_import_worker_spec.rb @@ -0,0 +1,119 @@ +RSpec.describe WorkbenchImportWorker, type: [:worker, :request] do + + let( :worker ) { described_class.new } + let( :import ){ build_stubbed :import, token_download: download_token, file: zip_file } + + let( :workbench ){ import.workbench } + let( :referential ){ import.referential } + let( :api_key ){ build_stubbed :api_key, referential: referential, token: "#{referential.id}-#{SecureRandom.hex}" } + let( :params ) do + { netex_import: + { referential_id: referential.id, workbench_id: workbench.id } + } + end + + # http://www.example.com/workbenches/:workbench_id/imports/:id/download + let( :host ){ Rails.configuration.rails_host } + let( :path ){ download_workbench_import_path(workbench, import) } + + let( :downloaded_zip ){ double("downloaded zip") } + let( :download_zip_response ){ OpenStruct.new( body: downloaded_zip ) } + let( :download_token ){ SecureRandom.urlsafe_base64 } + + + let( :upload_path ) { api_v1_netex_imports_path(format: :json) } + + let( :entry_group_streams ) do + entry_count.times.map{ |i| double( "entry group stream #{i}" ) } + end + let( :entry_groups ) do + entry_count.times.map do | i | + {"entry_group_name#{i}" => entry_group_streams[i] } + end + end + + let( :zip_service ){ double("zip service") } + let( :zip_file ){ open_fixture('multiple_references_import.zip') } + + let( :post_response_ok ){ double(status: 201, body: "{}") } + + before do + # Silence Logger + allow_any_instance_of(Logger).to receive(:info) + allow_any_instance_of(Logger).to receive(:warn) + + # That should be `build_stubbed's` job, no? + allow(Import).to receive(:find).with(import.id).and_return(import) + + allow(Api::V1::ApiKey).to receive(:from).and_return(api_key) + allow(ZipService).to receive(:new).with(downloaded_zip).and_return zip_service + expect(zip_service).to receive(:entry_group_streams).and_return(entry_groups) + expect( import ).to receive(:update_attributes).with(status: 'running') + end + + + context 'multireferential zipfile, no errors' do + let( :entry_count ){ 2 } + + it 'downloads a zip file, cuts it, and uploads all pieces' do + + expect(HTTPService).to receive(:get_resource) + .with(host: host, path: path, params: {token: download_token}) + .and_return( download_zip_response ) + + entry_groups.each do | entry_group_name, entry_group_stream | + mock_post entry_group_name, entry_group_stream, post_response_ok + end + + expect( import ).to receive(:update_attributes).with(total_steps: 2) + expect( import ).to receive(:update_attributes).with(current_step: 1) + expect( import ).to receive(:update_attributes).with(current_step: 2) + + worker.perform import.id + + end + end + + context 'multireferential zipfile with error' do + let( :entry_count ){ 3 } + let( :post_response_failure ){ double(status: 406, body: {error: 'What was you thinking'}) } + + it 'downloads a zip file, cuts it, and uploads some pieces' do + expect(HTTPService).to receive(:get_resource) + .with(host: host, path: path, params: {token: download_token}) + .and_return( download_zip_response ) + + # First entry_group succeeds + entry_groups[0..0].each do | entry_group_name, entry_group_stream | + mock_post entry_group_name, entry_group_stream, post_response_ok + end + + # Second entry_group fails (M I S E R A B L Y) + entry_groups[1..1].each do | entry_group_name, entry_group_stream | + mock_post entry_group_name, entry_group_stream, post_response_failure + WorkbenchImportWorker::RETRY_DELAYS.each do | delay | + mock_post entry_group_name, entry_group_stream, post_response_failure + expect_any_instance_of(RetryService).to receive(:sleep).with(delay) + end + end + + expect( import ).to receive(:update_attributes).with(total_steps: 3) + expect( import ).to receive(:update_attributes).with(current_step: 1) + expect( import ).to receive(:update_attributes).with(current_step: 2) + expect( import ).to receive(:update_attributes).with(current_step: 3, status: 'failed') + + worker.perform import.id + + end + end + + def mock_post entry_group_name, entry_group_stream, response + expect( HTTPService ).to receive(:post_resource) + .with(host: host, + path: upload_path, + token: api_key.token, + params: params, + upload: {file: [entry_group_stream, 'application/zip', entry_group_name]}) + .and_return(response) + end +end |
