如何模拟谷歌云存储桶并将其链接到客户端对象?

我在云运行中有一个函数,并尝试在 Python 中使用模拟进行测试。如何使用 blob 模拟存储桶并将其附加到存储客户端?断言失败,它以这种格式显示输出


Display File content: <MagicMock name='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')```


吃鸡游戏
浏览 135回答 1
1回答

holdtom

&nbsp;&nbsp;def&nbsp;test_read_sql(self): &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;storage_client&nbsp;=&nbsp;mock.create_autospec(storage.Client) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mock_bucket&nbsp;=&nbsp;mock.create_autospec(storage.Bucket) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mock_blob&nbsp;=&nbsp;mock.create_autospec(storage.Blob) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mock_bucket.return_value&nbsp;=&nbsp;mock_blob &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;storage_client.get_bucket.return_value&nbsp;=&nbsp;mock_bucket &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mock_bucket.get_blob.return_value&nbsp;=&nbsp;mock_blob &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;mock_blob.download_as_string.return_value.decode.return_value&nbsp;=&nbsp;"file_content" &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;read_content&nbsp;=&nbsp;main.read_sql(storage_client,&nbsp;'test_bucket',&nbsp;'test_blob') &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;assert&nbsp;read_content&nbsp;==&nbsp;'file_content'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python