|
| 1 | +import os |
| 2 | +from pathlib import Path |
| 3 | +import uuid |
| 4 | + |
| 5 | +from fastapi.testclient import TestClient |
| 6 | +import pytest |
| 7 | + |
| 8 | +from tests.helpers import access_token_cookie, create_test_user |
| 9 | + |
| 10 | + |
| 11 | +@pytest.fixture |
| 12 | +def client(): |
| 13 | + from ubiblio.main import app |
| 14 | + |
| 15 | + with TestClient(app) as c: |
| 16 | + yield c |
| 17 | + |
| 18 | + |
| 19 | +class TestDownloadEbook: |
| 20 | + @pytest.fixture |
| 21 | + def ebook_path(self): |
| 22 | + ebook_dir = Path("./static/eBooks") |
| 23 | + ebook_dir.mkdir(parents=True, exist_ok=True) |
| 24 | + name = f"test_ebook_{uuid.uuid4().hex}.txt" |
| 25 | + path = f"{ebook_dir}/{name}" |
| 26 | + |
| 27 | + return path |
| 28 | + |
| 29 | + def test_download_ebook_happy_path(self, client, ebook_path): |
| 30 | + # Arrange |
| 31 | + name = os.path.basename(ebook_path) |
| 32 | + content = b"hello ebook" |
| 33 | + |
| 34 | + with open(ebook_path, "wb") as f: |
| 35 | + f.write(content) |
| 36 | + |
| 37 | + try: |
| 38 | + # Act |
| 39 | + with create_test_user() as user: |
| 40 | + with access_token_cookie(client, user): |
| 41 | + r = client.get(f"/downloadEbook/{name}") |
| 42 | + |
| 43 | + # Assert |
| 44 | + assert r.status_code == 200 |
| 45 | + assert r.content == content |
| 46 | + assert "application/octet-stream" in ( |
| 47 | + r.headers.get("content-type")) |
| 48 | + assert name in (r.headers.get("content-disposition") or "") |
| 49 | + finally: |
| 50 | + # Cleanup |
| 51 | + if os.path.exists(ebook_path): |
| 52 | + os.remove(ebook_path) |
| 53 | + |
| 54 | + def test_download_ebook_missing_file(self, client): |
| 55 | + # Arrange |
| 56 | + name = f"missing_{uuid.uuid4().hex}.epub" |
| 57 | + |
| 58 | + # Act |
| 59 | + with create_test_user() as user: |
| 60 | + with access_token_cookie(client, user): |
| 61 | + r = client.get(f"/downloadEbook/{name}") |
| 62 | + |
| 63 | + # Assert |
| 64 | + assert r.status_code == 200 |
| 65 | + print(r.text) |
| 66 | + assert r.text == "Failed to download ebook." |
0 commit comments