|
| 1 | +import pytest |
| 2 | +from unittest.mock import patch, MagicMock |
| 3 | +from fastapi.testclient import TestClient |
| 4 | +from backend.main import app |
| 5 | +import ssl |
| 6 | + |
| 7 | +client = TestClient(app) |
| 8 | + |
| 9 | + |
| 10 | +@pytest.mark.parametrize("skip_verify", ["0", "1"]) |
| 11 | +def test_download_tutorial_ssl_context(skip_verify, monkeypatch): |
| 12 | + """ |
| 13 | + Test that the SSL context is correctly configured based on TEMOA_SKIP_CERT_VERIFY. |
| 14 | + This test is parametrized to ensure deterministic behavior. |
| 15 | + """ |
| 16 | + monkeypatch.setenv("TEMOA_SKIP_CERT_VERIFY", skip_verify) |
| 17 | + |
| 18 | + # Patch targets must be on the module that USES the functions |
| 19 | + with patch("backend.main.urllib.request.urlopen") as mock_urlopen, patch( |
| 20 | + "backend.main.shutil.copyfileobj" |
| 21 | + ), patch("backend.main.open", new_callable=MagicMock): |
| 22 | + # Configure the mock response |
| 23 | + mock_response = MagicMock() |
| 24 | + mock_urlopen.return_value.__enter__.return_value = mock_response |
| 25 | + |
| 26 | + response = client.post("/api/download_tutorial") |
| 27 | + |
| 28 | + assert response.status_code == 200 |
| 29 | + assert response.json()["status"] == "ok" |
| 30 | + |
| 31 | + # Verify SSL context |
| 32 | + _, kwargs = mock_urlopen.call_args |
| 33 | + assert "context" in kwargs |
| 34 | + ctx = kwargs["context"] |
| 35 | + assert isinstance(ctx, ssl.SSLContext) |
| 36 | + |
| 37 | + if skip_verify == "1": |
| 38 | + assert ctx.check_hostname is False |
| 39 | + assert ctx.verify_mode == ssl.CERT_NONE |
| 40 | + else: |
| 41 | + assert ctx.check_hostname is True |
| 42 | + assert ctx.verify_mode == ssl.CERT_REQUIRED |
| 43 | + |
| 44 | + |
| 45 | +def test_download_tutorial_failure(): |
| 46 | + # Patch on the actual module to ensure it's intercepted |
| 47 | + with patch( |
| 48 | + "backend.main.urllib.request.urlopen", side_effect=Exception("Network error") |
| 49 | + ): |
| 50 | + response = client.post("/api/download_tutorial") |
| 51 | + assert response.status_code == 500 |
| 52 | + assert "Download failed" in response.json()["detail"] |
0 commit comments