[Python] how to unit test flask method using google cloud storage library

Discussão em 'Python' iniciado por Stack, Julho 9, 2025.

  1. Stack

    Stack Membro Participativo

    Im trying to create unit tests for this method but im getting the error saying credentials not found

    from io import BytesIO

    from google.auth.exceptions import DefaultCredentialsError
    from google.cloud import storage
    from fastapi import HTTPException

    storage_client = storage.Client()
    bucket_name = "stupid-bucket-name-1234567890"

    async def upload_to_gcs(file, file_name: str) -> str:

    try:
    bucket = storage_client.bucket(bucket_name)
    blob = bucket.blob(file_name)
    binary_data = await file.read()
    blob.upload_from_file(BytesIO(binary_data), content_type=file.content_type)
    file_url = blob.public_url
    return file_url
    except DefaultCredentialsError as exe:
    raise HTTPException(status_code=500, detail=str(exe))
    except Exception as e:
    raise HTTPException(status_code=500, detail=str(e))


    now here is my unit test code

    import sys
    import pytest
    from unittest.mock import patch, MagicMock, AsyncMock
    from fastapi import HTTPException
    from google.auth.exceptions import DefaultCredentialsError

    # Patch BEFORE importing cloud_service
    with patch("package.svc.cloud.storage.Client") as mock_client:
    mock_storage_client = mock_client.return_value
    mock_bucket = MagicMock()
    mock_blob = MagicMock()
    mock_storage_client.bucket.return_value = mock_bucket
    mock_bucket.blob.return_value = mock_blob
    mock_blob.public_url = "https://fake-url.com/file.txt"
    import importlib
    cloud_service = importlib.import_module("package.svc.cloud")

    @pytest.mark.asyncio
    async def test_upload_file_to_gcs_success():
    mock_file = AsyncMock()
    mock_file.read.return_value = b"test data"
    mock_file.content_type = "text/plain"
    url = await cloud_service.upload_file_to_gcs(mock_file, "file.txt")
    assert url == "https://fake-url.com/file.txt"
    cloud_service.storage_client.bucket.return_value.blob.return_value.upload_from_file.assert_called_once()


    but when I run this, it says: Failed to load service account credentials from ... No key could be found

    I don't understand why it is looking for the actual keys even though I have already mocked the lines in the code that would return the Client object.

    Continue reading...

Compartilhe esta Página