0

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

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')```

BVSKanth
  • 111
  • 2
  • 16

1 Answers1

2
    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'
BVSKanth
  • 111
  • 2
  • 16
  • I tried this code and I am still getting the exception given in the question. Did this work for anyone, if yes please share some details. – shweta dixit Jun 04 '20 at 14:34
  • 1
    The question and answer was done by the same person. Also, it was accepted by the same person ... Is this allowed ? – Shubhankar Raj Jan 20 '21 at 08:45
  • For me, where downstream code would instantiate the mocked storage client into an object, `storage_client.get_bucket.return_value = mock_bucket` either needs to read `storage_client().get_bucket.return_value = mock_bucket` (note the parentheses in `storage_client()`, to mock _the object_ that code may have instantiated from the mocked _class_) or `storage_client.return_value.get_bucket.return_value = mock_bucket`. See [Python returns MagicMock object instead of return_value](https://stackoverflow.com/a/38199345). – Arjan Apr 06 '23 at 13:48