-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_client.py
More file actions
897 lines (763 loc) · 31 KB
/
Copy pathapi_client.py
File metadata and controls
897 lines (763 loc) · 31 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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
from __future__ import annotations
# Standard library imports
from dataclasses import dataclass
from logging import Logger, getLogger
from typing import Any, Dict, List, Optional, Tuple
# Third-party imports
import httpx
DEFAULT_BASE_URL = "http://localhost:8000"
DEFAULT_TIMEOUT = 30.0
@dataclass
class ScenarioReport:
"""Outcome of an end-to-end scenario run.
Attributes:
base_url (str): Base URL the client targeted.
username (str): Username the scenario authenticated as.
uploaded (int): Number of files uploaded during the scenario.
downloaded (int): Number of files downloaded and verified.
deleted (int): Number of files deleted, including any leftovers
from prior runs that the cleanup step removed.
"""
base_url: str
username: str
uploaded: int
downloaded: int
deleted: int
@dataclass
class FullScenarioReport:
"""Outcome of a multi-scenario suite run.
Attributes:
base_url (str): Base URL the suite targeted.
primary_username (str): Username of the main scenario user.
secondary_username (str): Username of the sibling user used for
cross-user isolation checks.
scenarios_run (int): Number of sub-scenarios executed.
scenarios_passed (int): Number of sub-scenarios that passed.
details (List[Tuple[str, str]]): Ordered ``(name, status)`` pairs,
where ``status`` is either ``"PASS"`` or ``"FAIL: <reason>"``.
"""
base_url: str
primary_username: str
secondary_username: str
scenarios_run: int
scenarios_passed: int
details: List[Tuple[str, str]]
class APIClient:
"""Synchronous HTTP client for the fmanagement API.
Attributes:
base_url (str): Base URL the client is bound to.
logger (Logger): Logger instance.
Notes:
The client tracks the bearer token returned by :meth:`login` and
attaches it to every authenticated request. The same instance can
be reused across :meth:`run_scenario` invocations; each invocation
leaves the server in the same observable state (the test user
exists; the test user owns zero files).
Notes:
Wraps every public endpoint exposed by the running docker-compose stack
and offers a high-level, idempotent end-to-end scenario runner.
"""
def __init__(
self,
base_url: str = DEFAULT_BASE_URL,
timeout: float = DEFAULT_TIMEOUT,
logger: Optional[Logger] = None,
) -> None:
"""Initialize the client.
Args:
base_url (str): Base URL of the API (default
``http://localhost:8000``).
timeout (float): Per-request timeout in seconds.
logger (Optional[Logger]): Optional logger instance.
"""
self.base_url = base_url
self.logger = logger if logger else getLogger(__name__)
self._http = httpx.Client(base_url=base_url, timeout=timeout)
self._token: Optional[str] = None
####################
# Internal methods #
####################
def _auth_headers(self) -> Dict[str, str]:
"""Return the ``Authorization`` header for an authenticated request.
Returns:
Dict[str, str]: ``{"Authorization": "Bearer <token>"}``.
Raises:
RuntimeError: If :meth:`login` has not been called.
"""
if not self._token:
raise RuntimeError("Not authenticated; call login() first.")
return {"Authorization": f"Bearer {self._token}"}
def _safe_json(self, response: httpx.Response) -> Dict[str, Any]:
"""Return ``response.json()`` or an empty dict when the body isn't JSON.
Args:
response (httpx.Response): The HTTP response.
Returns:
Dict[str, Any]: Parsed body, or ``{}`` on a non-JSON response.
"""
try:
return response.json()
except ValueError:
return {}
####################
# Raw access #
####################
def raw_request(
self,
method: str,
path: str,
*,
authenticated: bool = True,
**kwargs: Any,
) -> httpx.Response:
"""Issue an HTTP request and return the raw response, no raising.
Args:
method (str): HTTP verb.
path (str): Path relative to ``base_url``.
authenticated (bool): If True (default), attach the bearer
``Authorization`` header for the user this client is
logged in as. Set to False to send no token.
**kwargs (Any): Forwarded to :meth:`httpx.Client.request`.
Returns:
httpx.Response: The raw response. Status is **not** checked;
scenario code is expected to inspect ``status_code`` directly.
Raises:
RuntimeError: If ``authenticated=True`` but :meth:`login` has
not been called.
"""
if authenticated:
headers = dict(kwargs.pop("headers", {}) or {})
headers.update(self._auth_headers())
kwargs["headers"] = headers
return self._http.request(method, path, **kwargs)
####################
# Lifecycle #
####################
def close(self) -> None:
"""Release the underlying HTTP connection pool."""
self._http.close()
def __enter__(self) -> APIClient:
"""Enter the context manager.
Returns:
APIClient: This client instance.
"""
return self
def __exit__(self, *_: Any) -> None:
"""Close the client on context exit."""
self.close()
####################
# Auth endpoints #
####################
def register(
self, username: str, email: str, password: str
) -> Tuple[int, Dict[str, Any]]:
"""Register a new user.
Args:
username (str): Desired username.
email (str): User's email address.
password (str): Plaintext password (server-side hashed with bcrypt).
Returns:
Tuple[int, Dict[str, Any]]: The HTTP status code and the JSON
body. ``201`` indicates a fresh registration; ``409`` indicates
the user already exists. The scenario runner treats both as
success, which is what makes the scenario idempotent.
"""
response = self._http.post(
"/api/v1/auth/register",
json={
"username": username,
"email": email,
"password": password,
},
)
return response.status_code, self._safe_json(response)
def login(self, username: str, password: str) -> str:
"""Authenticate and stash the bearer token on this client.
Args:
username (str): Username.
password (str): Plaintext password.
Returns:
str: The signed JWT access token.
Raises:
httpx.HTTPStatusError: If the credentials are rejected.
"""
response = self._http.post(
"/api/v1/auth/login",
data={"username": username, "password": password},
)
response.raise_for_status()
token = response.json()["access_token"]
self._token = token
return token
def logout(self) -> None:
"""Stateless logout. Clears the local token after the server ack.
Raises:
httpx.HTTPStatusError: If the bearer header is rejected.
RuntimeError: If :meth:`login` has not been called.
"""
response = self._http.post(
"/api/v1/auth/logout", headers=self._auth_headers()
)
response.raise_for_status()
self._token = None
####################
# File endpoints #
####################
def upload_file(
self,
name: str,
content: bytes,
content_type: str = "application/octet-stream",
) -> Dict[str, Any]:
"""Upload a single file as multipart/form-data.
Args:
name (str): Filename to store on the server.
content (bytes): Raw file payload.
content_type (str): MIME type advertised in the multipart part.
Returns:
Dict[str, Any]: The ``file`` block of the upload response,
i.e. the persisted file metadata.
Raises:
httpx.HTTPStatusError: If the upload is rejected (e.g. 415 for
an unsupported MIME type).
RuntimeError: If :meth:`login` has not been called.
"""
response = self._http.post(
"/api/v1/files",
headers=self._auth_headers(),
files={"file": (name, content, content_type)},
)
response.raise_for_status()
return response.json()["file"]
def list_files(
self, page: int = 1, size: int = 50
) -> Dict[str, Any]:
"""List one page of the authenticated user's files.
Args:
page (int): 1-indexed page number.
size (int): Page size (1..200 server-side).
Returns:
Dict[str, Any]: A ``{"files": [...], "page": int, "size": int,
"total": int}`` payload.
Raises:
httpx.HTTPStatusError: If the bearer header is missing or the
query parameters are out of range (422).
RuntimeError: If :meth:`login` has not been called.
"""
response = self._http.get(
"/api/v1/files",
headers=self._auth_headers(),
params={"page": page, "size": size},
)
response.raise_for_status()
return response.json()
def list_all_files(self, page_size: int = 50) -> List[Dict[str, Any]]:
"""List every file owned by the user, paginating until exhausted.
Args:
page_size (int): Page size used for each underlying request.
Returns:
List[Dict[str, Any]]: All file metadata entries owned by the
authenticated user.
Notes:
Pagination terminates either when an empty page is returned or
when the accumulated count reaches the server-reported total.
"""
files: List[Dict[str, Any]] = []
page = 1
while True:
payload = self.list_files(page=page, size=page_size)
chunk = payload.get("files", [])
files.extend(chunk)
total = payload.get("total", len(files))
if not chunk or len(files) >= total:
return files
page += 1
def download_file(self, file_id: str) -> bytes:
"""Download a file by id.
Args:
file_id (str): Document id of the file to fetch.
Returns:
bytes: The raw file content.
Raises:
httpx.HTTPStatusError: 404 if missing, 403 if owned by another
user.
RuntimeError: If :meth:`login` has not been called.
"""
response = self._http.get(
f"/api/v1/files/{file_id}", headers=self._auth_headers()
)
response.raise_for_status()
return response.content
def delete_file(self, file_id: str) -> Dict[str, Any]:
"""Delete a file by id.
Args:
file_id (str): Document id of the file to remove.
Returns:
Dict[str, Any]: The ``{"id": ..., "deleted": True}`` ack body.
Raises:
httpx.HTTPStatusError: 404 if missing, 403 if owned by another
user.
RuntimeError: If :meth:`login` has not been called.
"""
response = self._http.delete(
f"/api/v1/files/{file_id}", headers=self._auth_headers()
)
response.raise_for_status()
return response.json()
####################
# Scenarios #
####################
def ensure_user(
self, username: str, email: str, password: str
) -> str:
"""Register the user if needed, then log in.
Args:
username (str): Desired username.
email (str): User's email address.
password (str): Plaintext password.
Returns:
str: The signed JWT access token.
Raises:
RuntimeError: If the register call returns an unexpected status.
Notes:
Idempotency: a second invocation with the same credentials hits
the 409 path on register, falls through to login, and leaves
the server state unchanged.
"""
status, _ = self.register(username, email, password)
if status not in (201, 409):
raise RuntimeError(
f"Unexpected register status {status} for {username!r}"
)
return self.login(username, password)
def purge_files(self) -> int:
"""Delete every file owned by the authenticated user.
Returns:
int: The number of files deleted. Zero on a clean run; non-zero
when leftovers from a previous run are reaped.
Notes:
Safe to call repeatedly: each call ends with the user owning
zero files, regardless of starting state.
"""
files = self.list_all_files()
for entry in files:
self.delete_file(entry["_id"])
return len(files)
def run_scenario(
self,
username: str = "scenario_user",
email: str = "scenario_user@example.com",
password: str = "scenario-pass-12345",
sample_files: Optional[List[Tuple[str, bytes, str]]] = None,
) -> ScenarioReport:
"""Exercise every endpoint in an idempotent end-to-end flow.
Args:
username (str): Username used for the scenario user.
email (str): Email used when the scenario user has to be
registered.
password (str): Plaintext password for the scenario user.
sample_files (Optional[List[Tuple[str, bytes, str]]]): Triples of
``(name, content, content_type)`` to upload. When ``None``,
a small default fixture covering text, JSON, and binary
payloads is used.
Returns:
ScenarioReport: A summary of what was executed.
Raises:
AssertionError: If a server response disagrees with what the
client just performed (listing mismatch, content drift,
non-empty cleanup state).
Notes:
Steps performed, in order:
1. Register (or pass-through on 409) and log in.
2. Purge any files left over from a previous run.
3. Upload the sample files.
4. List, then download and verify each file.
5. Delete every uploaded file.
6. Confirm the user owns zero files.
7. Logout.
Idempotency: the user is reused; step 2 cleans before, step 5
cleans after, so successive runs leave the server in the same
observable state.
"""
if sample_files is None:
sample_files = [
("alpha.txt", b"alpha contents\n", "text/plain"),
("beta.json", b'{"k":"v"}\n', "application/json"),
("gamma.csv", b"a,b,c\n1,2,3\n", "text/csv"),
]
self.ensure_user(username, email, password)
purged = self.purge_files()
self.logger.info("Purged %d leftover file(s)", purged)
uploaded_ids: List[str] = []
for name, content, content_type in sample_files:
entry = self.upload_file(name, content, content_type)
uploaded_ids.append(entry["_id"])
self.logger.info("Uploaded %d file(s)", len(uploaded_ids))
listing = self.list_all_files()
listed_ids = {entry["_id"] for entry in listing}
if listed_ids != set(uploaded_ids):
raise AssertionError(
f"Listing mismatch: expected {sorted(uploaded_ids)}, "
f"got {sorted(listed_ids)}"
)
downloaded = 0
for (_, expected_content, _), file_id in zip(
sample_files, uploaded_ids
):
data = self.download_file(file_id)
if data != expected_content:
raise AssertionError(
f"Download mismatch for {file_id}: "
f"got {len(data)} bytes, "
f"expected {len(expected_content)} bytes"
)
downloaded += 1
self.logger.info("Downloaded and verified %d file(s)", downloaded)
deleted = 0
for file_id in uploaded_ids:
self.delete_file(file_id)
deleted += 1
leftover = self.list_all_files()
if leftover:
raise AssertionError(
f"Expected zero files after cleanup, got {len(leftover)}"
)
self.logout()
self.logger.info("Scenario complete for user %r", username)
return ScenarioReport(
base_url=str(self._http.base_url),
username=username,
uploaded=len(uploaded_ids),
downloaded=downloaded,
deleted=deleted + purged,
)
####################
# Sub-scenarios #
####################
def _expect_status(
self, response: httpx.Response, expected: int, label: str
) -> None:
"""Assert ``response.status_code`` matches ``expected`` exactly.
Args:
response (httpx.Response): The HTTP response to check.
expected (int): The expected status code.
label (str): Human-readable label used in the assertion message.
Raises:
AssertionError: If the status code does not match.
"""
if response.status_code != expected:
body = self._safe_json(response)
raise AssertionError(
f"{label}: expected HTTP {expected}, got "
f"{response.status_code}; body={body!r}"
)
def scenario_unauthenticated_access(self) -> None:
"""Every files endpoint and ``/auth/logout`` must return 401 without a token."""
cases = [
("POST", "/api/v1/files"),
("GET", "/api/v1/files"),
("GET", "/api/v1/files/507f1f77bcf86cd799439011"),
("DELETE", "/api/v1/files/507f1f77bcf86cd799439011"),
("POST", "/api/v1/auth/logout"),
]
for method, path in cases:
response = self._http.request(method, path)
self._expect_status(
response, 401, f"{method} {path} without token"
)
def scenario_auth_failures(
self, username: str, email: str, password: str
) -> None:
"""Bad register/login attempts return the documented status codes.
Args:
username (str): Username of an already-registered scenario user.
email (str): Email of that scenario user.
password (str): Plaintext password of that scenario user.
Raises:
AssertionError: If any of the expected status codes is missed.
"""
status, _ = self.register(username, email, password)
if status != 409:
raise AssertionError(
f"Duplicate register expected 409, got {status}"
)
wrong = self._http.post(
"/api/v1/auth/login",
data={"username": username, "password": "definitely-wrong-pw"},
)
self._expect_status(wrong, 401, "login wrong password")
unknown = self._http.post(
"/api/v1/auth/login",
data={"username": "_ghost_user_xyz_", "password": "whatever12"},
)
self._expect_status(unknown, 401, "login unknown user")
garbage = self._http.get(
"/api/v1/files",
headers={"Authorization": "Bearer not-a-real-token"},
)
self._expect_status(garbage, 401, "list with garbage token")
def scenario_upload_disallowed_mime(self) -> None:
"""A PE-executable upload is rejected with 415 by magic-byte sniffing."""
pe_bytes = (
b"MZ\x90\x00\x03\x00\x00\x00\x04\x00\x00\x00\xff\xff\x00\x00"
)
response = self._http.post(
"/api/v1/files",
headers=self._auth_headers(),
files={"file": ("evil.exe", pe_bytes, "text/plain")},
)
self._expect_status(response, 415, "upload disallowed MIME (PE)")
def scenario_upload_missing_field(self) -> None:
"""Multipart POST without the ``file`` part returns 422."""
response = self._http.post(
"/api/v1/files", headers=self._auth_headers()
)
self._expect_status(response, 422, "upload missing 'file' field")
def scenario_upload_duplicate_name(self) -> None:
"""A second upload reusing ``(owner, name)`` returns 409."""
name = "_dup_scenario.txt"
first = self.upload_file(name, b"first body\n", "text/plain")
try:
response = self._http.post(
"/api/v1/files",
headers=self._auth_headers(),
files={"file": (name, b"second body\n", "text/plain")},
)
self._expect_status(response, 409, "duplicate filename")
finally:
self.delete_file(first["_id"])
def scenario_list_query_validation(self) -> None:
"""Out-of-range ``page`` / ``size`` query parameters return 422."""
cases = [
({"page": 0, "size": 10}, "page < 1"),
({"page": 1, "size": 0}, "size < 1"),
({"page": 1, "size": 201}, "size > 200"),
]
for params, label in cases:
response = self._http.get(
"/api/v1/files",
headers=self._auth_headers(),
params=params,
)
self._expect_status(response, 422, f"list {label}")
def scenario_pagination(self) -> None:
"""Paged listings respect ``page``/``size`` and report the total.
Raises:
AssertionError: On totals mismatch, page-size drift, duplicate
IDs across pages, or non-empty pages past the end.
Notes:
Calls :meth:`purge_files` before and after, so any pre-existing
files for the scenario user are wiped.
"""
self.purge_files()
names = [f"_page_{i}.txt" for i in range(5)]
for name in names:
self.upload_file(name, b"x", "text/plain")
page1 = self.list_files(page=1, size=2)
page2 = self.list_files(page=2, size=2)
page3 = self.list_files(page=3, size=2)
page4 = self.list_files(page=4, size=2)
if page1["total"] != 5 or page3["total"] != 5:
raise AssertionError(
f"Pagination total drift: p1={page1['total']} p3={page3['total']}"
)
if len(page1["files"]) != 2 or len(page2["files"]) != 2:
raise AssertionError(
f"Full pages should have size=2, got "
f"{len(page1['files'])}, {len(page2['files'])}"
)
if len(page3["files"]) != 1:
raise AssertionError(
f"Tail page should have 1 file, got {len(page3['files'])}"
)
if page4["files"]:
raise AssertionError(
f"Page beyond total should be empty, got {page4['files']}"
)
seen = {
entry["_id"]
for page in (page1, page2, page3)
for entry in page["files"]
}
if len(seen) != 5:
raise AssertionError(
f"Pagination produced overlap or gaps: distinct ids={len(seen)}"
)
self.purge_files()
def scenario_unknown_id(self) -> None:
"""Download/delete of a well-formed-but-missing id returns 404."""
bogus = "507f1f77bcf86cd799439099"
download = self._http.get(
f"/api/v1/files/{bogus}", headers=self._auth_headers()
)
self._expect_status(download, 404, "download unknown id")
delete = self._http.delete(
f"/api/v1/files/{bogus}", headers=self._auth_headers()
)
self._expect_status(delete, 404, "delete unknown id")
def scenario_delete_then_404(self) -> None:
"""After delete, both download and a second delete return 404."""
entry = self.upload_file(
"_deleted_then.txt", b"bye\n", "text/plain"
)
file_id = entry["_id"]
self.delete_file(file_id)
download = self._http.get(
f"/api/v1/files/{file_id}", headers=self._auth_headers()
)
self._expect_status(download, 404, "download after delete")
delete = self._http.delete(
f"/api/v1/files/{file_id}", headers=self._auth_headers()
)
self._expect_status(delete, 404, "double delete")
def scenario_cross_user_isolation(self, sibling: "APIClient") -> None:
"""Confirm files are partitioned per-owner.
Args:
sibling (APIClient): A second client already authenticated as a
different user.
Raises:
AssertionError: If listings leak across users, or if reads/
deletes against another owner's file do not return 403.
Notes:
Both users are purged before and after, so this scenario leaves
them owning zero files regardless of starting state.
"""
self.purge_files()
sibling.purge_files()
a_entry = self.upload_file("_iso_a.txt", b"alpha\n", "text/plain")
sibling.upload_file("_iso_b.txt", b"bravo\n", "text/plain")
try:
a_names = {entry["name"] for entry in self.list_all_files()}
b_names = {entry["name"] for entry in sibling.list_all_files()}
if a_names != {"_iso_a.txt"} or b_names != {"_iso_b.txt"}:
raise AssertionError(
f"Cross-user listing leak: a={a_names} b={b_names}"
)
cross_download = sibling.raw_request(
"GET", f"/api/v1/files/{a_entry['_id']}"
)
self._expect_status(
cross_download, 403, "B downloads A's file"
)
cross_delete = sibling.raw_request(
"DELETE", f"/api/v1/files/{a_entry['_id']}"
)
self._expect_status(cross_delete, 403, "B deletes A's file")
still = self.download_file(a_entry["_id"])
if still != b"alpha\n":
raise AssertionError(
"A's file was mutated by B's failed attempts"
)
finally:
self.purge_files()
sibling.purge_files()
def scenario_happy_path(self) -> None:
"""Upload, list, download-and-verify, then delete a single file."""
self.purge_files()
payload = b"happy path body\n"
entry = self.upload_file("_happy.txt", payload, "text/plain")
listing = self.list_all_files()
if {f["_id"] for f in listing} != {entry["_id"]}:
raise AssertionError("Happy-path listing drift")
downloaded = self.download_file(entry["_id"])
if downloaded != payload:
raise AssertionError(
f"Happy-path content drift: "
f"got {len(downloaded)}, expected {len(payload)} bytes"
)
self.delete_file(entry["_id"])
if self.list_all_files():
raise AssertionError("Happy-path cleanup left files behind")
def run_full_scenarios(
self,
username: str = "scenario_user",
email: str = "scenario_user@example.com",
password: str = "scenario-pass-12345",
secondary_username: str = "scenario_user_2",
secondary_email: str = "scenario_user_2@example.com",
secondary_password: str = "scenario-pass-67890",
) -> FullScenarioReport:
"""Run every sub-scenario and report a per-scenario PASS/FAIL summary.
Args:
username (str): Primary scenario user.
email (str): Email used when the primary user has to be registered.
password (str): Primary user's plaintext password.
secondary_username (str): Sibling user for cross-user isolation.
secondary_email (str): Email used when the sibling has to be
registered.
secondary_password (str): Sibling's plaintext password.
Returns:
FullScenarioReport: Aggregate report. ``scenarios_passed ==
scenarios_run`` indicates a fully-green run.
Notes:
Each sub-scenario is executed independently: a failure in one
does not abort the rest. The state for both users is purged at
entry, between disruptive scenarios, and again at exit.
"""
self.ensure_user(username, email, password)
sibling = APIClient(base_url=self.base_url, logger=self.logger)
sibling.ensure_user(
secondary_username, secondary_email, secondary_password
)
try:
scenarios: List[Tuple[str, Any]] = [
(
"unauthenticated_access",
self.scenario_unauthenticated_access,
),
(
"auth_failures",
lambda: self.scenario_auth_failures(
username, email, password
),
),
(
"upload_disallowed_mime",
self.scenario_upload_disallowed_mime,
),
(
"upload_missing_field",
self.scenario_upload_missing_field,
),
(
"upload_duplicate_name",
self.scenario_upload_duplicate_name,
),
(
"list_query_validation",
self.scenario_list_query_validation,
),
("pagination", self.scenario_pagination),
("unknown_id_404", self.scenario_unknown_id),
("delete_then_404", self.scenario_delete_then_404),
(
"cross_user_isolation",
lambda: self.scenario_cross_user_isolation(sibling),
),
("happy_path", self.scenario_happy_path),
]
details: List[Tuple[str, str]] = []
for name, fn in scenarios:
try:
fn()
details.append((name, "PASS"))
self.logger.info("[PASS] %s", name)
except (AssertionError, httpx.HTTPStatusError) as exc:
details.append((name, f"FAIL: {exc}"))
self.logger.error("[FAIL] %s: %s", name, exc)
self.purge_files()
sibling.purge_files()
passed = sum(1 for _, status in details if status == "PASS")
return FullScenarioReport(
base_url=str(self._http.base_url),
primary_username=username,
secondary_username=secondary_username,
scenarios_run=len(details),
scenarios_passed=passed,
details=details,
)
finally:
try:
sibling.logout()
except (httpx.HTTPError, RuntimeError):
pass
sibling.close()