|
| 1 | +from unittest.mock import patch, MagicMock |
| 2 | +from fastapi.testclient import TestClient |
| 3 | +from backend.main import app |
| 4 | +import ssl |
| 5 | + |
| 6 | +client = TestClient(app) |
| 7 | + |
| 8 | + |
| 9 | +def test_download_tutorial_success(): |
| 10 | + # Mock urllib.request.urlopen and shutil.copyfileobj |
| 11 | + with patch("urllib.request.urlopen") as mock_urlopen, patch( |
| 12 | + "shutil.copyfileobj" |
| 13 | + ), patch("builtins.open", new_callable=MagicMock): |
| 14 | + # Configure the mock response |
| 15 | + mock_response = MagicMock() |
| 16 | + mock_urlopen.return_value.__enter__.return_value = mock_response |
| 17 | + |
| 18 | + response = client.post("/api/download_tutorial") |
| 19 | + |
| 20 | + assert response.status_code == 200 |
| 21 | + assert response.json()["status"] == "ok" |
| 22 | + assert "tutorial_database.sqlite" in response.json()["path"] |
| 23 | + |
| 24 | + # Verify URL and SSL context |
| 25 | + args, kwargs = mock_urlopen.call_args |
| 26 | + assert ( |
| 27 | + args[0] |
| 28 | + == "https://raw.githubusercontent.com/TemoaProject/temoa-web-gui/main/assets/tutorial_database.sqlite" |
| 29 | + ) |
| 30 | + assert "context" in kwargs |
| 31 | + ctx = kwargs["context"] |
| 32 | + assert isinstance(ctx, ssl.SSLContext) |
| 33 | + |
| 34 | + # The SSL context should be secure by default (using certifi) |
| 35 | + # unless TEMOA_SKIP_CERT_VERIFY is set. |
| 36 | + import os |
| 37 | + |
| 38 | + if os.environ.get("TEMOA_SKIP_CERT_VERIFY") == "1": |
| 39 | + assert ctx.check_hostname is False |
| 40 | + assert ctx.verify_mode == ssl.CERT_NONE |
| 41 | + else: |
| 42 | + # By default it should be secure |
| 43 | + assert ctx.check_hostname is True |
| 44 | + assert ctx.verify_mode == ssl.CERT_REQUIRED |
| 45 | + |
| 46 | + |
| 47 | +def test_download_tutorial_failure(): |
| 48 | + # Patch on the actual module to ensure it's intercepted |
| 49 | + with patch( |
| 50 | + "backend.main.urllib.request.urlopen", side_effect=Exception("Network error") |
| 51 | + ): |
| 52 | + response = client.post("/api/download_tutorial") |
| 53 | + assert response.status_code == 500 |
| 54 | + assert "Download failed" in response.json()["detail"] |
0 commit comments