Skip to content

Commit ca37842

Browse files
authored
Merge pull request #61 from TaskarCenterAtUW/feature-download-issue
Fixed No such file or directory issue
2 parents b700bf2 + 5b5517b commit ca37842

File tree

4 files changed

+68
-24
lines changed

4 files changed

+68
-24
lines changed

src/config.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import os
2+
import uuid
23
from dotenv import load_dotenv
34
from pydantic import BaseSettings
45

@@ -11,3 +12,6 @@ class Settings(BaseSettings):
1112
response_topic_name: str = os.environ.get('RESPONSE_TOPIC', None)
1213
request_subscription: str = os.environ.get('REQUEST_SUBSCRIPTION', None)
1314
storage_container_name: str = os.environ.get('CONTAINER_NAME', 'gtfsflex')
15+
16+
def get_unique_id(self) -> str:
17+
return str(uuid.uuid4())

src/gtfs_flex_validation.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@
2323

2424
class GTFSFlexValidation:
2525
def __init__(self, file_path=None, storage_client=None):
26-
settings = Settings()
27-
self.container_name = settings.storage_container_name
26+
self.settings = Settings()
27+
self.container_name = self.settings.storage_container_name
2828
self.storage_client = storage_client
2929
self.file_path = file_path
3030
self.file_relative_path = file_path.split('/')[-1]
@@ -44,9 +44,9 @@ def is_gtfs_flex_valid(self) -> tuple[Union[bool, Any], Union[str, Any]]:
4444
validation_message = ''
4545
root, ext = os.path.splitext(self.file_relative_path)
4646
if ext and ext.lower() == '.zip':
47+
downloaded_file_path = self.download_single_file(self.file_path)
48+
logger.info(f' Downloaded file path: {downloaded_file_path}')
4749
try:
48-
downloaded_file_path = self.download_single_file(self.file_path)
49-
logger.info(f' Downloaded file path: {downloaded_file_path}')
5050
gcv_test_release.test_release(DATA_TYPE, SCHEMA_VERSION, downloaded_file_path)
5151
is_valid = True
5252
except Exception as err:
@@ -67,17 +67,23 @@ def download_single_file(self, file_upload_path=None) -> str:
6767
if not is_exists:
6868
os.makedirs(DOWNLOAD_FILE_PATH)
6969

70+
unique_folder = self.settings.get_unique_id()
71+
dl_folder_path = os.path.join(DOWNLOAD_FILE_PATH, unique_folder)
72+
73+
# Ensure the unique folder path is created
74+
os.makedirs(dl_folder_path, exist_ok=True)
75+
7076
file = self.storage_client.get_file_from_url(self.container_name, file_upload_path)
7177
try:
7278
if file.file_path:
7379
file_path = os.path.basename(file.file_path)
74-
with open(f'{DOWNLOAD_FILE_PATH}/{file_path}', 'wb') as blob:
80+
with open(f'{dl_folder_path}/{file_path}', 'wb') as blob:
7581
blob.write(file.get_stream())
76-
logger.info(f' File downloaded to location: {DOWNLOAD_FILE_PATH}/{file_path}')
77-
return f'{DOWNLOAD_FILE_PATH}/{file_path}'
82+
logger.info(f' File downloaded to location: {dl_folder_path}/{file_path}')
83+
return f'{dl_folder_path}/{file_path}'
7884
else:
7985
logger.info(' File not found!')
80-
raise Exception('File not found!')
86+
raise Exception('File not found!')
8187
except Exception as e:
8288
traceback.print_exc()
8389
logger.error(e)

test_report.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
# Define your test cases
55
from tests.unit_tests.test_gtfs_flex_serializer import TestGTFSFlexUpload, TestGTFSFlexUploadData, TestRequest, \
66
TestMeta, TestResponse
7-
from tests.unit_tests.test_gtfs_flex_validation import TestSuccessGTFSFlexValidation, TestFailureGTFSFlexValidation, TestSuccessWithWithMacOSFile
7+
from tests.unit_tests.test_gtfs_flex_validation import TestSuccessGTFSFlexValidation, TestFailureGTFSFlexValidation, TestSuccessWithMacOSFile
88
from tests.unit_tests.test_gtfx_flex_validator import TestGTFSFlexValidator
99
from tests.unit_tests.test_file_upload_msg import TestFileUploadMsg
1010
from tests.unit_tests.test_main import TestApp
@@ -19,7 +19,7 @@
1919
test_suite.addTest(unittest.makeSuite(TestMeta))
2020
test_suite.addTest(unittest.makeSuite(TestResponse))
2121
test_suite.addTest(unittest.makeSuite(TestSuccessGTFSFlexValidation))
22-
test_suite.addTest(unittest.makeSuite(TestSuccessWithWithMacOSFile))
22+
test_suite.addTest(unittest.makeSuite(TestSuccessWithMacOSFile))
2323
test_suite.addTest(unittest.makeSuite(TestFailureGTFSFlexValidation))
2424
test_suite.addTest(unittest.makeSuite(TestGTFSFlexValidator))
2525
test_suite.addTest(unittest.makeSuite(TestApp))

tests/unit_tests/test_gtfs_flex_validation.py

Lines changed: 48 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from pathlib import Path
55
from unittest.mock import patch, MagicMock
66
from src.gtfs_flex_validation import GTFSFlexValidation
7+
from src.config import Settings
78

89
DOWNLOAD_FILE_PATH = f'{Path.cwd()}/downloads'
910
SAVED_FILE_PATH = f'{Path.cwd()}/tests/unit_tests/test_files'
@@ -16,7 +17,7 @@
1617
SCHEMA_VERSION = 'v2.0'
1718

1819

19-
class TestSuccessWithWithMacOSFile(unittest.TestCase):
20+
class TestSuccessWithMacOSFile(unittest.TestCase):
2021
@patch.object(GTFSFlexValidation, 'download_single_file')
2122
def setUp(self, mock_download_single_file):
2223
os.makedirs(DOWNLOAD_FILE_PATH, exist_ok=True)
@@ -33,6 +34,7 @@ def setUp(self, mock_download_single_file):
3334
self.validator.file_path = file_path
3435
self.validator.file_relative_path = MAC_SUCCESS_FILE_NAME
3536
self.validator.container_name = None
37+
self.validator.settings = Settings()
3638
mock_download_single_file.return_value = file_path
3739

3840
def tearDown(self):
@@ -47,11 +49,11 @@ def test_validate_with_valid_file(self):
4749

4850
# Act
4951
is_valid, _ = self.validator.validate()
50-
(is_valid)
5152

5253
# Assert
5354
self.assertTrue(is_valid)
5455

56+
5557
class TestSuccessGTFSFlexValidation(unittest.TestCase):
5658

5759
@patch.object(GTFSFlexValidation, 'download_single_file')
@@ -64,13 +66,16 @@ def setUp(self, mock_download_single_file):
6466
shutil.copyfile(source, destination)
6567

6668
file_path = f'{DOWNLOAD_FILE_PATH}/{SUCCESS_FILE_NAME}'
69+
dl_folder_path = os.path.join(DOWNLOAD_FILE_PATH, 'dummy-uuid') # Mock the UUID generation
70+
os.makedirs(dl_folder_path, exist_ok=True) # Ensure this directory is created in the test
6771

6872
with patch.object(GTFSFlexValidation, '__init__', return_value=None):
6973
self.validator = GTFSFlexValidation(file_path=file_path, storage_client=MagicMock())
7074
self.validator.file_path = file_path
7175
self.validator.file_relative_path = SUCCESS_FILE_NAME
7276
self.validator.container_name = None
73-
mock_download_single_file.return_value = file_path
77+
self.validator.settings = Settings()
78+
mock_download_single_file.return_value = os.path.join(dl_folder_path, SUCCESS_FILE_NAME)
7479

7580
def tearDown(self):
7681
pass
@@ -123,6 +128,33 @@ def test_download_single_file(self):
123128
content = f.read()
124129
self.assertEqual(content, b'file_content')
125130

131+
def test_download_multiple_file_with_same_name(self):
132+
# Arrange
133+
file_upload_path = DOWNLOAD_FILE_PATH
134+
self.validator.storage_client = MagicMock()
135+
self.validator.storage_client.get_file_from_url = MagicMock()
136+
file = MagicMock()
137+
file.file_path = 'text_file.txt'
138+
file.get_stream = MagicMock(return_value=b'file_content')
139+
self.validator.storage_client.get_file_from_url.return_value = file
140+
141+
# Act
142+
first_downloaded_file_path = self.validator.download_single_file(file_upload_path=file_upload_path)
143+
second_downloaded_file_path = self.validator.download_single_file(file_upload_path=file_upload_path)
144+
145+
# Assert
146+
self.assertNotEqual(first_downloaded_file_path, second_downloaded_file_path,
147+
"The downloaded file paths should be different for files with the same name.")
148+
149+
# Check if the get_file_from_url was called for both download attempts
150+
self.assertEqual(self.validator.storage_client.get_file_from_url.call_count, 2,
151+
"get_file_from_url should be called twice for two downloads.")
152+
file.get_stream.assert_called()
153+
154+
# Additional assertions to verify that the paths indeed point to different locations
155+
self.assertTrue(first_downloaded_file_path.startswith(DOWNLOAD_FILE_PATH))
156+
self.assertTrue(second_downloaded_file_path.startswith(DOWNLOAD_FILE_PATH))
157+
126158
def test_clean_up_file(self):
127159
# Arrange
128160
file_upload_path = DOWNLOAD_FILE_PATH
@@ -149,7 +181,7 @@ def test_clean_up_folder(self):
149181
GTFSFlexValidation.clean_up = MagicMock()
150182

151183
# Assert
152-
# self.assertFalse(os.path.exists(directory_name))
184+
self.assertFalse(os.path.exists(directory_name))
153185

154186

155187
class TestFailureGTFSFlexValidation(unittest.TestCase):
@@ -170,6 +202,7 @@ def setUp(self, mock_download_single_file):
170202
self.validator.file_path = file_path
171203
self.validator.file_relative_path = FAILURE_FILE_NAME
172204
self.validator.container_name = None
205+
self.validator.settings = MagicMock()
173206
mock_download_single_file.return_value = file_path
174207

175208
def tearDown(self):
@@ -223,19 +256,20 @@ def test_download_single_file_exception(self):
223256
self.validator.storage_client.get_file_from_url = MagicMock()
224257
file = MagicMock()
225258
file.file_path = 'text_file.txt'
226-
file.get_stream = MagicMock(return_value=b'file_content')
259+
file.get_stream = MagicMock(side_effect=FileNotFoundError("Mocked FileNotFoundError"))
227260
self.validator.storage_client.get_file_from_url.return_value = file
228261

229-
# Act
230-
downloaded_file_path = self.validator.download_single_file(file_upload_path=file_upload_path)
262+
# Create the mock folder that would be used
263+
unique_id = "mocked-uuid"
264+
self.validator.settings.get_unique_id = MagicMock()
265+
self.validator.settings.get_unique_id.return_value = unique_id
231266

232-
# Assert
233-
self.validator.storage_client.get_file_from_url.assert_called_once_with(self.validator.container_name,
234-
file_upload_path)
235-
file.get_stream.assert_called_once()
236-
with open(downloaded_file_path, 'rb') as f:
237-
content = f.read()
238-
self.assertEqual(content, b'file_content')
267+
dl_folder_path = os.path.join(DOWNLOAD_FILE_PATH, unique_id)
268+
os.makedirs(dl_folder_path, exist_ok=True)
269+
270+
# Act & Assert
271+
with self.assertRaises(FileNotFoundError):
272+
self.validator.download_single_file(file_upload_path=file_upload_path)
239273

240274

241275
if __name__ == '__main__':

0 commit comments

Comments
 (0)