11from __future__ import annotations
22
3- from time import sleep
43from typing import TYPE_CHECKING
54from uuid import uuid4
65
76import pytest
87
8+ from supabase import StorageException
9+
910if TYPE_CHECKING :
1011 from pathlib import Path
1112 from typing import Any , Callable , Dict , List
1213
1314 from supabase import Client , StorageFileAPI , SupabaseStorageClient
1415
1516
16- UUID_PREFIX = "pytest-"
17+ # Global variable to track the ids from the buckets created in the tests run
18+ temp_test_buckets_ids = []
1719
1820
1921@pytest .fixture (scope = "module" )
2022def uuid_factory () -> Callable [[], str ]:
2123 def method () -> str :
22- """Generate a UUID"""
23- uuid = uuid4 ().hex [:8 ] # Get the first 8 digits part to make it shorter
24- return f"{ UUID_PREFIX } { uuid } "
24+ """Generate a 8 digits long UUID"""
25+ return uuid4 ().hex [:8 ]
2526
2627 return method
2728
@@ -36,19 +37,19 @@ def storage_client(supabase: Client) -> SupabaseStorageClient:
3637def delete_left_buckets (
3738 request : pytest .FixtureRequest , storage_client : SupabaseStorageClient
3839):
39- """Ensures no test buckets are left"""
40+ """Ensures no test buckets are left when a test that created a bucket fails """
4041
4142 def finalizer ():
42- # Sleep 15 seconds in order to let buckets be deleted before the double-check
43- sleep (15 )
44- buckets_list = storage_client .list_buckets ()
45- if not buckets_list :
46- return
47-
48- for bucket in buckets_list :
49- if bucket .id .startswith (UUID_PREFIX ):
43+ for bucket in temp_test_buckets_ids :
44+ try :
5045 storage_client .empty_bucket (bucket .id )
5146 storage_client .delete_bucket (bucket .id )
47+ except StorageException as e :
48+ # Ignore 404 responses since they mean the bucket was already deleted
49+ response = e .args [0 ]
50+ if response ["statusCode" ] != 404 :
51+ raise e
52+ continue
5253
5354 request .addfinalizer (finalizer )
5455
@@ -59,13 +60,20 @@ def bucket(
5960) -> str :
6061 """Creates a test bucket which will be used in the whole storage tests run and deleted at the end"""
6162 bucket_id = uuid_factory ()
63+
64+ # Store bucket_id in global list
65+ global temp_test_buckets_ids
66+ temp_test_buckets_ids .append (bucket_id )
67+
6268 storage_client .create_bucket (id = bucket_id )
6369
6470 yield bucket_id
6571
6672 storage_client .empty_bucket (bucket_id )
6773 storage_client .delete_bucket (bucket_id )
6874
75+ temp_test_buckets_ids .remove (bucket_id )
76+
6977
7078@pytest .fixture (scope = "module" )
7179def storage_file_client (
0 commit comments