-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathtest_file_service.py
More file actions
432 lines (369 loc) · 14.9 KB
/
test_file_service.py
File metadata and controls
432 lines (369 loc) · 14.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
"""Unit tests for the FileService."""
from datetime import datetime
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from src.services.file import FileService
@pytest.fixture
def mock_s3_client():
"""Mock S3 client."""
client = MagicMock()
client.head_bucket = MagicMock(return_value={})
client.put_object = MagicMock()
client.get_object = MagicMock()
client.delete_object = MagicMock()
client.head_object = MagicMock(return_value={"ContentLength": 1024})
return client
@pytest.fixture
def mock_redis_client():
"""Mock Redis client."""
client = AsyncMock()
client.hgetall = AsyncMock(return_value={})
client.hset = AsyncMock()
client.hget = AsyncMock(return_value=None)
client.sadd = AsyncMock()
client.srem = AsyncMock()
client.smembers = AsyncMock(return_value=set())
client.expire = AsyncMock()
client.delete = AsyncMock()
client.close = AsyncMock()
return client
@pytest.fixture
def file_service(mock_s3_client, mock_redis_client):
"""Create FileService with mocked clients."""
with patch("src.config.s3.S3Config.make_client", return_value=mock_s3_client):
with patch("src.services.file.redis.from_url") as mock_redis_from_url:
mock_redis_from_url.return_value = mock_redis_client
service = FileService()
service.s3_client = mock_s3_client
service.redis_client = mock_redis_client
return service
class TestUpdateFileContent:
"""Tests for update_file_content method."""
@pytest.mark.asyncio
async def test_update_file_content_rejects_read_only_file(
self, file_service, mock_s3_client, mock_redis_client
):
"""Read-only linked aliases must not overwrite the source object."""
session_id = "test-session"
file_id = "linked-file"
mock_redis_client.hgetall.return_value = {
"file_id": file_id,
"filename": "report.csv",
"object_key": "sessions/source/uploads/source-file",
"content_type": "text/csv",
"is_read_only": "1",
}
result = await file_service.update_file_content(
session_id=session_id,
file_id=file_id,
content=b"modified",
)
assert result is False
mock_s3_client.put_object.assert_not_called()
@pytest.mark.asyncio
async def test_update_file_content_success(
self, file_service, mock_s3_client, mock_redis_client
):
"""Test that update_file_content overwrites file in S3."""
session_id = "test-session-123"
file_id = "test-file-456"
new_content = b"modified file content"
# Mock existing file metadata
mock_redis_client.hgetall.return_value = {
"file_id": file_id,
"filename": "test.txt",
"object_key": f"sessions/{session_id}/uploads/{file_id}",
"content_type": "text/plain",
}
result = await file_service.update_file_content(
session_id=session_id,
file_id=file_id,
content=new_content,
)
assert result is True
mock_s3_client.put_object.assert_called_once()
mock_redis_client.hset.assert_called()
@pytest.mark.asyncio
async def test_update_file_content_updates_metadata(
self, file_service, mock_s3_client, mock_redis_client
):
"""Test that update_file_content updates file size metadata."""
session_id = "test-session-123"
file_id = "test-file-456"
new_content = b"new content with some data"
mock_redis_client.hgetall.return_value = {
"file_id": file_id,
"filename": "data.txt",
"object_key": f"sessions/{session_id}/uploads/{file_id}",
"content_type": "text/plain",
}
result = await file_service.update_file_content(
session_id=session_id,
file_id=file_id,
content=new_content,
)
assert result is True
# Check that hset was called with correct updates
hset_call = mock_redis_client.hset.call_args
mapping = hset_call.kwargs.get("mapping")
assert mapping is not None
assert mapping["size"] == len(new_content)
@pytest.mark.asyncio
async def test_update_file_content_file_not_found(
self, file_service, mock_redis_client
):
"""Test graceful handling of missing file."""
session_id = "test-session"
file_id = "nonexistent-file"
# Mock file not found
mock_redis_client.hgetall.return_value = {}
result = await file_service.update_file_content(
session_id=session_id,
file_id=file_id,
content=b"content",
)
assert result is False
@pytest.mark.asyncio
async def test_update_file_content_no_object_key(
self, file_service, mock_redis_client
):
"""Test handling of metadata without object_key."""
session_id = "test-session"
file_id = "file-no-key"
# Mock metadata without object_key
mock_redis_client.hgetall.return_value = {
"file_id": file_id,
"filename": "test.txt",
# object_key is missing
}
result = await file_service.update_file_content(
session_id=session_id,
file_id=file_id,
content=b"content",
)
assert result is False
@pytest.mark.asyncio
async def test_update_file_content_s3_error(
self, file_service, mock_s3_client, mock_redis_client
):
"""Test handling of S3 error during update."""
session_id = "test-session"
file_id = "file-id"
mock_redis_client.hgetall.return_value = {
"file_id": file_id,
"filename": "test.txt",
"object_key": f"sessions/{session_id}/uploads/{file_id}",
"content_type": "text/plain",
}
mock_s3_client.put_object.side_effect = Exception("S3 connection error")
result = await file_service.update_file_content(
session_id=session_id,
file_id=file_id,
content=b"content",
)
assert result is False
@pytest.mark.asyncio
async def test_update_file_content_preserves_content_type(
self, file_service, mock_s3_client, mock_redis_client
):
"""Test that content_type is preserved from original metadata."""
session_id = "test-session"
file_id = "image-file"
new_content = b"\x89PNG\r\n\x1a\n..." # PNG bytes
mock_redis_client.hgetall.return_value = {
"file_id": file_id,
"filename": "image.png",
"object_key": f"sessions/{session_id}/uploads/{file_id}",
"content_type": "image/png",
}
result = await file_service.update_file_content(
session_id=session_id,
file_id=file_id,
content=new_content,
)
assert result is True
put_call = mock_s3_client.put_object.call_args
assert put_call.kwargs.get("ContentType") == "image/png"
@pytest.mark.asyncio
async def test_update_file_content_only_updates_size(
self, file_service, mock_s3_client, mock_redis_client
):
"""Test that update_file_content only updates size metadata."""
session_id = "test-session"
file_id = "file-id"
mock_redis_client.hgetall.return_value = {
"file_id": file_id,
"filename": "test.txt",
"object_key": f"sessions/{session_id}/uploads/{file_id}",
"content_type": "text/plain",
}
result = await file_service.update_file_content(
session_id=session_id,
file_id=file_id,
content=b"just content, no state",
)
assert result is True
hset_call = mock_redis_client.hset.call_args
mapping = hset_call.kwargs.get("mapping")
assert mapping == {"size": len(b"just content, no state")}
class TestLinkedFiles:
"""Tests for linked-input alias behavior."""
@pytest.mark.asyncio
async def test_link_file_into_session_creates_read_only_alias(
self, file_service, mock_redis_client
):
"""Linking should create a current-session alias to the source object."""
mock_redis_client.smembers.return_value = set()
mock_redis_client.hgetall.side_effect = [
{
"file_id": "source-file",
"filename": "report.csv",
"content_type": "text/csv",
"object_key": "sessions/source-session/uploads/source-file",
"session_id": "source-session",
"created_at": datetime.utcnow().isoformat(),
"size": "12",
"path": "/report.csv",
"type": "upload",
}
]
linked_file = await file_service.link_file_into_session(
"target-session", "source-session", "source-file"
)
assert linked_file is not None
assert linked_file.filename == "report.csv"
hset_call = mock_redis_client.hset.call_args_list[0]
metadata = hset_call.kwargs["mapping"]
assert metadata["type"] == "linked_input"
assert metadata["source_session_id"] == "source-session"
assert metadata["source_file_id"] == "source-file"
assert metadata["object_key"] == "sessions/source-session/uploads/source-file"
assert metadata["is_read_only"] == "1"
@pytest.mark.asyncio
async def test_link_file_into_session_reuses_existing_alias(
self, file_service, mock_redis_client
):
"""Repeated linking of the same source file should reuse the alias."""
existing_created_at = datetime.utcnow().isoformat()
mock_redis_client.smembers.return_value = {"linked-file"}
mock_redis_client.hgetall.side_effect = [
{
"file_id": "source-file",
"filename": "report.csv",
"content_type": "text/csv",
"object_key": "sessions/source/uploads/source-file",
"session_id": "source-session",
"created_at": datetime.utcnow().isoformat(),
"size": "12",
"path": "/report.csv",
"type": "upload",
},
{
"file_id": "linked-file",
"filename": "report.csv",
"content_type": "text/csv",
"object_key": "sessions/source/uploads/source-file",
"session_id": "target-session",
"created_at": existing_created_at,
"size": "12",
"path": "/report.csv",
"type": "linked_input",
"source_session_id": "source-session",
"source_file_id": "source-file",
"is_read_only": "1",
},
{
"file_id": "linked-file",
"filename": "report.csv",
"content_type": "text/csv",
"object_key": "sessions/source/uploads/source-file",
"session_id": "target-session",
"created_at": existing_created_at,
"size": "12",
"path": "/report.csv",
"type": "linked_input",
"source_session_id": "source-session",
"source_file_id": "source-file",
"is_read_only": "1",
},
]
linked_file = await file_service.link_file_into_session(
"target-session", "source-session", "source-file"
)
assert linked_file is not None
assert linked_file.file_id == "linked-file"
assert len(mock_redis_client.hset.call_args_list) == 0
@pytest.mark.asyncio
async def test_delete_linked_file_only_removes_metadata(
self, file_service, mock_s3_client, mock_redis_client
):
"""Deleting a linked alias must not delete the shared object."""
mock_redis_client.hgetall.return_value = {
"file_id": "linked-file",
"filename": "report.csv",
"content_type": "text/csv",
"object_key": "sessions/source/uploads/source-file",
"session_id": "target-session",
"created_at": datetime.utcnow().isoformat(),
"size": "12",
"path": "/report.csv",
"type": "linked_input",
"source_session_id": "source-session",
"source_file_id": "source-file",
"is_read_only": "1",
}
result = await file_service.delete_file("target-session", "linked-file")
assert result is True
mock_s3_client.delete_object.assert_not_called()
mock_redis_client.delete.assert_called_once()
assert mock_redis_client.srem.call_count == 2
@pytest.mark.asyncio
async def test_delete_source_file_keeps_object_when_aliases_exist(
self, file_service, mock_s3_client, mock_redis_client
):
"""Deleting the source metadata must not delete a shared object still referenced by aliases."""
mock_redis_client.hgetall.return_value = {
"file_id": "source-file",
"filename": "report.csv",
"content_type": "text/csv",
"object_key": "sessions/source/uploads/source-file",
"session_id": "source-session",
"created_at": datetime.utcnow().isoformat(),
"size": "12",
"path": "/report.csv",
"type": "upload",
}
mock_redis_client.smembers.return_value = {"target-session:linked-file"}
result = await file_service.delete_file("source-session", "source-file")
assert result is True
mock_s3_client.delete_object.assert_not_called()
mock_redis_client.delete.assert_called_once()
@pytest.mark.asyncio
async def test_delete_last_linked_file_cleans_orphaned_shared_object(
self, file_service, mock_s3_client, mock_redis_client
):
"""The final alias cleanup should delete the shared object once the source is gone."""
mock_redis_client.hgetall.side_effect = [
{
"file_id": "linked-file",
"filename": "report.csv",
"content_type": "text/csv",
"object_key": "sessions/source/uploads/source-file",
"session_id": "target-session",
"created_at": datetime.utcnow().isoformat(),
"size": "12",
"path": "/report.csv",
"type": "linked_input",
"source_session_id": "source-session",
"source_file_id": "source-file",
"is_read_only": "1",
},
{},
]
mock_redis_client.smembers.return_value = set()
result = await file_service.delete_file("target-session", "linked-file")
assert result is True
mock_s3_client.delete_object.assert_called_once_with(
Bucket=file_service.bucket_name,
Key="sessions/source/uploads/source-file",
)