AWS S3 Ruby SDK的存根响应

时间:2019-11-18 20:25:26

标签: ruby amazon-s3 aws-sdk aws-sdk-ruby

我正在寻找一种方法来测试依赖于AWS​​ S3的代码。我找到了Advanced Client Stubbing tutorial,但是我只能找到从list_objects直接存根Aws::S3::Client的正确方法。

我不想重构代码,因为我将SDK与Aws::S3::Resource结合使用(一种更加面向对象的方式):

s3_resource = Aws::S3::Resource.new(options)
objs = s3_resource.bucket(bucket_name).objects

到目前为止,我一直可以找到成功获得存根响应的唯一方法是:

s3_client = Aws::S3::Client.new(stub_responses: true)
stubbed_objs = {
  contents: [
    { key: 'image.jpeg' },
    { key: 'test/image.jpeg' },
    { key: 'test/backup_2019-03-01T143129.sql.gz' },
    { key: 'test/backup_2019-04-01T143129.sql.gz' },
    { key: 'test/backup_2019-05-01T143129.sql.gz' },
    { key: 'test/image2.jpeg' },
    { key: 'backup_2019-06-01T143129.sql.gz' },
    { key: 'backup_2019-07-01T143129.sql.gz' },
    { key: 'backup_2019-08-01T143129.sql.gz' }
  ]
}
s3_client.stub_responses(:list_objects, stubbed_objs)
res = s3_client.list_objects({ bucket: "examplebucket" })

# Check the stubbed response
res.contents.map(&:key)
# => ["image.jpeg", "test/image.jpeg", "test/backup_2019-03-01T143129.sql.gz", "test/backup_2019-04-01T143129.sql.gz", "test/backup_2019-05-01T143129.sql.gz", "test/image2.jpeg", "backup_2019-06-01T143129.sql.gz", "backup_2019-07-01T143129.sql.gz", "backup_2019-08-01T143129.sql.gz"]

我尝试将Aws::S3::Client传递给Aws::S3::Resource初始化程序,但是我没有从存根中获取响应对象:

s3_client = Aws::S3::Client.new(stub_responses: true)

...

s3_resource = Aws::S3::Resource.new({ client: s3_client })
objs = s3_resource.bucket(bucket_name).objects
# => Returns 0 objects

我正在考虑s3_resource.bucket(bucket_name).objects进行多次调用,这就是失败的原因,或者使用Aws::S3::Resource与直接Aws::S3::Client调用时,存根响应格式是不同的。

无论哪种方式,对此的任何帮助都将受到赞赏。

1 个答案:

答案 0 :(得分:0)

使用list_objects_v2而不是list_objects进行存根响应 会起作用的

    s3_client = Aws::S3::Client.new(stub_responses: true)
    stubbed_objs = {
      contents: [
        { key: 'image.jpeg' },
        { key: 'test/image.jpeg' },
        { key: 'test/backup_2019-03-01T143129.sql.gz' },
        { key: 'test/backup_2019-04-01T143129.sql.gz' },
        { key: 'test/backup_2019-05-01T143129.sql.gz' },
        { key: 'test/image2.jpeg' },
        { key: 'backup_2019-06-01T143129.sql.gz' },
        { key: 'backup_2019-07-01T143129.sql.gz' },
        { key: 'backup_2019-08-01T143129.sql.gz' }
      ]
    }
    s3_client.stub_responses(:list_objects_v2, stubbed_objs)