Skip to content

Commit

Permalink
Add unit tests for extract_and_translate function
Browse files Browse the repository at this point in the history
  • Loading branch information
gda committed Nov 11, 2024
1 parent 0ae1f2a commit 144503d
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 0 deletions.
Empty file added app/backend_gcf/__init__.py
Empty file.
Empty file.
40 changes: 40 additions & 0 deletions app/backend_gcf/tests/test_main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import pytest
from unittest.mock import patch, MagicMock # To mock external API calls
from flask import Flask, request # To simulate HTTP requests
from io import BytesIO

# Import the function from main.py
from backend_gcf.main import extract_and_translate

@pytest.fixture
def app():
""" Fixture for Flask app context, for creating HTTP requests """
app = Flask(__name__)
return app

# Use patch to replace the Google clients with mock objects
@patch('backend_gcf.main.vision_client')
@patch('backend_gcf.main.translate_client')
def test_extract_and_translate_with_posted_image(mock_translate_client, mock_vision_client, app: Flask):
with app.test_request_context(
method='POST',
data={
'uploaded': (BytesIO(b'sample image data'), 'test_image.jpg'),
'to_lang': 'en'
},
content_type='multipart/form-data'
):
# Mock Vision API response
mock_vision_client.text_detection.return_value = MagicMock(
text_annotations=[MagicMock(description="Put a glass of rice and three glasses of water in a saucepan")]
)

# Mock Translate API response
mock_translate_client.detect_language.return_value = {"language": "uk"}
mock_translate_client.translate.return_value = {"translatedText": "Put a glass of rice and three glasses of water in a saucepan"}

# Call the function
response = extract_and_translate(request)

# Check the result
assert response == "Put a glass of rice and three glasses of water in a saucepan"
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ proto-plus==1.23.0
protobuf==4.25.3
pyasn1==0.6.0
pyasn1_modules==0.4.0
pytest
requests==2.32.3
rsa==4.9
urllib3==2.2.1
Expand Down

0 comments on commit 144503d

Please sign in to comment.