Add makedirs to file operations (#3289)

* Add makedirs to file operations

* Add new directory tests for file operations

* Fix wrong setUp test error

* Simplify makedirs and use correct nested path

* Fix linter error

---------

Co-authored-by: Nicholas Tindle <nick@ntindle.com>
Co-authored-by: James Collins <collijk@uw.edu>
pull/3387/head^2
Montana Flynn 2023-04-27 23:12:24 +07:00 committed by GitHub
parent 9e17a304de
commit 7cd76b8d8e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 10 deletions

View File

@ -142,8 +142,7 @@ def write_to_file(filename: str, text: str) -> str:
return "Error: File has already been updated."
try:
directory = os.path.dirname(filename)
if not os.path.exists(directory):
os.makedirs(directory)
os.makedirs(directory, exist_ok=True)
with open(filename, "w", encoding="utf-8") as f:
f.write(text)
log_operation("write", filename)
@ -167,6 +166,8 @@ def append_to_file(filename: str, text: str, should_log: bool = True) -> str:
str: A message indicating success or failure
"""
try:
directory = os.path.dirname(filename)
os.makedirs(directory, exist_ok=True)
with open(filename, "a") as f:
f.write(text)
@ -236,6 +237,8 @@ def download_file(url, filename):
filename (str): Filename to save the file as
"""
try:
directory = os.path.dirname(filename)
os.makedirs(directory, exist_ok=True)
message = f"{Fore.YELLOW}Downloading file from {Back.LIGHTBLUE_EX}{url}{Back.RESET}{Fore.RESET}"
with Spinner(message) as spinner:
session = requests.Session()

View File

@ -33,6 +33,7 @@ class TestFileOperations(unittest.TestCase):
self.test_file = str(self.workspace.get_path("test_file.txt"))
self.test_file2 = "test_file2.txt"
self.test_directory = str(self.workspace.get_path("test_directory"))
self.test_nested_file = str(self.workspace.get_path("nested/test_file.txt"))
self.file_content = "This is a test file.\n"
self.file_logger_logs = "file_logger.txt"
@ -69,21 +70,23 @@ class TestFileOperations(unittest.TestCase):
def test_write_to_file(self):
new_content = "This is new content.\n"
write_to_file(self.test_file, new_content)
with open(self.test_file, "r") as f:
write_to_file(self.test_nested_file, new_content)
with open(self.test_nested_file, "r") as f:
content = f.read()
self.assertEqual(content, new_content)
def test_append_to_file(self):
with open(self.test_file, "r") as f:
content_before = f.read()
append_text = "This is appended text.\n"
append_to_file(self.test_file, append_text)
with open(self.test_file, "r") as f:
append_to_file(self.test_nested_file, append_text)
with open(self.test_nested_file, "r") as f:
content = f.read()
self.assertEqual(content, content_before + append_text)
append_to_file(self.test_nested_file, append_text)
with open(self.test_nested_file, "r") as f:
content_after = f.read()
self.assertEqual(content_after, append_text + append_text)
def test_delete_file(self):
delete_file(self.test_file)