如何模拟谷歌云存储桶并将其链接到客户端对象? [英] How to mock google cloud storage bucket and link it to client object?

查看:97
本文介绍了如何模拟谷歌云存储桶并将其链接到客户端对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在云运行中有一个功能,并尝试在Python中使用模拟进行测试.如何模拟带有Blob的存储桶并将其附加到存储客户端?断言失败,并且以这种格式显示输出

I have a function in cloud run and trying to test using mock in Python. How can I mock bucket with a blob and attach it to storage client? Assert fails and it's displaying output in this format

显示文件内容:< MagicMock名称='mock.get_bucket().get_blob().download_as_string().decode()'id ='140590658508168'>

# test 
  def test_read_sql(self):
      storage_client = mock.create_autospec(storage.Client)
      mock_bucket = storage_client.get_bucket('test-bucket')
      mock_blob = mock_bucket.blob('blob1')
      mock_blob.upload_from_string("file_content")
      read_content = main.read_sql(storage_client, mock_bucket, mock_blob)
      print('File content: {}'.format(read_content))
      assert read_content == 'file_content'

# actual method
 def read_sql(gcs_client, bucket_id, file_name):
    bucket = gcs_client.get_bucket(bucket_id)
    blob = bucket.get_blob(file_name)
    contents = blob.download_as_string()
    return contents.decode('utf-8')```

推荐答案

    def test_read_sql(self):
        storage_client = mock.create_autospec(storage.Client)
        mock_bucket = mock.create_autospec(storage.Bucket)
        mock_blob = mock.create_autospec(storage.Blob)
        mock_bucket.return_value = mock_blob
        storage_client.get_bucket.return_value = mock_bucket
        mock_bucket.get_blob.return_value = mock_blob
        mock_blob.download_as_string.return_value.decode.return_value = "file_content"
        read_content = main.read_sql(storage_client, 'test_bucket', 'test_blob')
        assert read_content == 'file_content'

这篇关于如何模拟谷歌云存储桶并将其链接到客户端对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆