diff --git a/app/services/s3_query_service.rb b/app/services/s3_query_service.rb index c37161915..93e0a8cf6 100644 --- a/app/services/s3_query_service.rb +++ b/app/services/s3_query_service.rb @@ -332,7 +332,15 @@ def md5(io:) def count_objects(bucket_name: self.bucket_name, prefix: self.prefix) responses = s3_responses(bucket_name:, prefix:) total_key_count = responses.reduce(0) { |total, resp| total + resp.key_count } - total_key_count - 1 # s3 always sends back the bucket key as the first response, so we should not count it + if total_key_count == 0 + # if the bucket does not exist + # it will return 0 + 0 + else + # if the bucket does exist + # s3 always sends back the bucket key as the first response, so we should not count it + total_key_count - 1 + end end private diff --git a/spec/services/s3_query_service_spec.rb b/spec/services/s3_query_service_spec.rb index 0c09431bd..3c764822f 100644 --- a/spec/services/s3_query_service_spec.rb +++ b/spec/services/s3_query_service_spec.rb @@ -401,6 +401,17 @@ expect(s3_query_service.count_objects).to eq(7) # do not count the bucket the first time end end + + context "an empty response" do + before do + fake_s3_resp.stub(:key_count).and_return(0) + fake_s3_resp.stub(:is_truncated).and_return(false) + end + + it "returns all the objects" do + expect(s3_query_service.count_objects).to eq(0) + end + end end end