0

我正在寻找一种方法来测试我依赖于 AWS S3 的代码。我找到了高级客户端存根教程,但我只能list_objectsAws::S3::Client直接找到存根的正确方法。

我不想重构我的代码,因为我正在使用 SDK Aws::S3::Resource(一种更 OOP 的方式):

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::ClientAws::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::Resourcevs 直接Aws::S3::Client调用时存根响应格式可能不同。

无论哪种方式,对此的任何帮助表示赞赏。

4

1 回答 1

0

使用 list_objects_v2 制作一个 stub_responses,而不是 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)
于 2020-04-29T07:44:09.493 回答