|
| 1 | +import io |
| 2 | +import os |
| 3 | + |
| 4 | +import pytest |
| 5 | + |
| 6 | +from mpt_api_client.http.file_utils import declare_content_type |
| 7 | + |
| 8 | +NDJSON = "application/x-ndjson" |
| 9 | +CSV = "text/csv" |
| 10 | + |
| 11 | + |
| 12 | +@pytest.mark.parametrize( |
| 13 | + ("file_part", "expected"), |
| 14 | + [ |
| 15 | + pytest.param( |
| 16 | + b'{"id": 1}\n', |
| 17 | + ("upload", b'{"id": 1}\n', NDJSON), |
| 18 | + id="bytes without a name", |
| 19 | + ), |
| 20 | + pytest.param( |
| 21 | + ("journal.jsonl", b'{"id": 1}\n'), |
| 22 | + ("journal.jsonl", b'{"id": 1}\n', NDJSON), |
| 23 | + id="filename and content", |
| 24 | + ), |
| 25 | + pytest.param( |
| 26 | + ("journal.jsonl", b'{"id": 1}\n', None), |
| 27 | + ("journal.jsonl", b'{"id": 1}\n', NDJSON), |
| 28 | + id="content type left unset", |
| 29 | + ), |
| 30 | + pytest.param( |
| 31 | + ("journal.jsonl", b'{"id": 1}\n', CSV), |
| 32 | + ("journal.jsonl", b'{"id": 1}\n', CSV), |
| 33 | + id="content type declared by the caller", |
| 34 | + ), |
| 35 | + pytest.param( |
| 36 | + ("journal.jsonl", b'{"id": 1}\n', ""), |
| 37 | + ("journal.jsonl", b'{"id": 1}\n', NDJSON), |
| 38 | + id="blank content type treated as absent", |
| 39 | + ), |
| 40 | + pytest.param( |
| 41 | + ("journal.jsonl", b'{"id": 1}\n', None, {"X-Trace": "1"}), |
| 42 | + ("journal.jsonl", b'{"id": 1}\n', NDJSON, {"X-Trace": "1"}), |
| 43 | + id="extra headers preserved", |
| 44 | + ), |
| 45 | + pytest.param( |
| 46 | + (None, b'{"id": 1}\n'), |
| 47 | + (None, b'{"id": 1}\n', NDJSON), |
| 48 | + id="form field without a filename", |
| 49 | + ), |
| 50 | + ], |
| 51 | +) |
| 52 | +def test_declare_content_type(file_part, expected): |
| 53 | + result = declare_content_type(file_part, NDJSON) |
| 54 | + |
| 55 | + assert result == expected |
| 56 | + |
| 57 | + |
| 58 | +def test_filename_taken_from_file_object(tmp_path): |
| 59 | + file_path = tmp_path / "journal.jsonl" |
| 60 | + file_path.write_bytes(b'{"id": 1}\n') |
| 61 | + |
| 62 | + with file_path.open("rb") as file_obj: |
| 63 | + result = declare_content_type(file_obj, NDJSON) |
| 64 | + |
| 65 | + assert result == ("journal.jsonl", file_obj, NDJSON) |
| 66 | + |
| 67 | + |
| 68 | +def test_filename_falls_back_without_name(): |
| 69 | + file_obj = io.BytesIO(b'{"id": 1}\n') |
| 70 | + |
| 71 | + result = declare_content_type(file_obj, NDJSON) |
| 72 | + |
| 73 | + assert result == ("upload", file_obj, NDJSON) |
| 74 | + |
| 75 | + |
| 76 | +def test_filename_from_file_descriptor(tmp_path): |
| 77 | + file_path = tmp_path / "journal.jsonl" |
| 78 | + file_path.write_bytes(b'{"id": 1}\n') |
| 79 | + descriptor = os.open(file_path, os.O_RDONLY) |
| 80 | + |
| 81 | + with os.fdopen(descriptor, "rb") as file_obj: |
| 82 | + result = declare_content_type(file_obj, NDJSON) |
| 83 | + |
| 84 | + assert result == (str(descriptor), file_obj, NDJSON) |
0 commit comments