|
| 1 | +from datetime import datetime |
| 2 | +from unittest.mock import mock_open, patch |
| 3 | + |
| 4 | +from lims_utils.tables import BLSession |
| 5 | + |
| 6 | +VALID_FILE = b"\x00" * 208 + b"\x4d\x41\x50" |
| 7 | + |
| 8 | + |
| 9 | +def active_mock(_): |
| 10 | + return BLSession( |
| 11 | + startDate=datetime(year=2022, month=1, day=1), |
| 12 | + sessionId=27464088, |
| 13 | + beamLineName="m12", |
| 14 | + ) |
| 15 | + |
| 16 | + |
| 17 | +@patch("pato.crud.sessions._validate_session_active", new=active_mock) |
| 18 | +@patch("builtins.open", new_callable=mock_open()) |
| 19 | +@patch("pato.crud.sessions.os.path.isdir", new=lambda _: True) |
| 20 | +def test_post(_, mock_permissions, client): |
| 21 | + """Should write file successfully if file matches expected signature""" |
| 22 | + resp = client.post( |
| 23 | + "/proposals/cm31111/sessions/5/initialModel", |
| 24 | + files={"file": ("mrc.mrc", VALID_FILE, "application/octet-stream")}, |
| 25 | + ) |
| 26 | + |
| 27 | + assert resp.status_code == 200 |
| 28 | + |
| 29 | + |
| 30 | +@patch("pato.crud.sessions._validate_session_active", new=active_mock) |
| 31 | +@patch("builtins.open", new_callable=mock_open()) |
| 32 | +def test_invalid_file_signature(_, mock_permissions, client): |
| 33 | + """Should raise exception if file signature doesn't match MRC file signature""" |
| 34 | + resp = client.post( |
| 35 | + "/proposals/cm31111/sessions/5/initialModel", |
| 36 | + files={"file": ("not-mrc.mrc", b"\x01\x02", "application/octet-stream")}, |
| 37 | + ) |
| 38 | + |
| 39 | + assert resp.status_code == 415 |
| 40 | + |
| 41 | + |
| 42 | +@patch("pato.crud.sessions._validate_session_active", new=active_mock) |
| 43 | +@patch("builtins.open", side_effect=OSError("Write Error")) |
| 44 | +def test_write_error(_, mock_permissions, client): |
| 45 | + """Should return 500 if there was an error writing the file""" |
| 46 | + resp = client.post( |
| 47 | + "/proposals/cm31111/sessions/5/initialModel", |
| 48 | + files={"file": ("mrc.mrc", VALID_FILE, "application/octet-stream")}, |
| 49 | + ) |
| 50 | + |
| 51 | + assert resp.status_code == 500 |
| 52 | + |
| 53 | + |
| 54 | +@patch("pato.crud.sessions._validate_session_active", new=active_mock) |
| 55 | +@patch("builtins.open", side_effect=OSError("Write Error")) |
| 56 | +@patch("pato.crud.sessions.os.path.isdir", new=lambda _: False) |
| 57 | +def test_dir_does_not_exist(_, mock_permissions, client): |
| 58 | + """Should return 500 if directory does not exist""" |
| 59 | + resp = client.post( |
| 60 | + "/proposals/cm31111/sessions/5/initialModel", |
| 61 | + files={"file": ("mrc.mrc", VALID_FILE, "application/octet-stream")}, |
| 62 | + ) |
| 63 | + |
| 64 | + assert resp.status_code == 500 |
0 commit comments