我正在寻找一种方法来测试依赖于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
调用时,存根响应格式是不同的。
无论哪种方式,对此的任何帮助都将受到赞赏。
答案 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)