سؤال

I have a small service class which simply copies some images around S3. To simplify this question, it looks a bit, but not exactly, like this:

class BadgeUpdateJob < Struct.new(:badge)
    def perform
       source_filename = generate_source_filename
       dest_filename   = generate_dest_filename
       storage         = Fog::Storage.new({:provider => 'AWS', :aws_access_key_id => ENV['S3_KEY'], :aws_secret_access_key => ENV['S3_SECRET'] })
       dir = storage.directories.get(s3_bucket_key)
       source_file = dir.files.get(source_filename)
       if source_file
         source_file.copy(dir.key, dest_filename)
       else
         # Notify dev team, something is horribly wrong.
       end
    end  
 end

I can see a couple of obvious errors - bucket might not exist, source file might not exist, but I know how I want to test these - I’ll just set mocked Fog up in a way which causes these errors to occur naturally.

Other thing I can see going wrong is a timeout… There are at least 4 network operations in the above snippet, and any could fail/time out. I want to handle this gracefully.

Is there a ‘right’ way of doing this? Any suggestions on the ‘best’ way if not?

هل كانت مفيدة؟

المحلول

If it's not implemented by Fog's mocking layer, you can always use good, old-fashioned RSpec mocks.

describe 'BadgeUpdateJob' do
  describe 'timeouts' do
    it 'catches timeouts on authentication' do
      Fog::Storage.stub(:new).and_raise(Excon::Errors::Timeout)
      # ... expect(your code).to handle_it_properly
    end

    it 'catches timeouts on directories.get' do
      Fog::Storage::AWS::Directories.any_instance.stub(:get).and_raise(Excon::Errors::Timeout)
      # ...
    end

  end
end
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top