Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions utilities.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import os
from os.path import join, normpath
from typing import Optional

def create_directory(path: str, permission: Optional[int] = None) -> None:
"""
Create a new directory with optional permission settings.

:param path: The path to create the directory.
:param permission: The permission mode to set on the directory, e.g., 0o755.
If None, the default permission mode is used.
:raises FileExistsError: If the directory already exists.
:raises PermissionError: If there are insufficient permissions to create the directory.
"""
path = normpath(path)
if not path.endswith(os.sep):
path += os.sep

if os.path.exists(path):
raise FileExistsError(f"Directory '{path}' already exists.")

try:
os.makedirs(path, exist_ok=False, mode=permission)
except PermissionError as e:
raise PermissionError(f"Insufficient permissions to create directory '{path}'.") from e


# Test cases
def test_create_directory():
import tempfile
import stat

# Verify the function creates a directory successfully
test_dir = tempfile.TemporaryDirectory()
create_directory(test_dir.name)
assert os.path.exists(test_dir.name)
test_dir.cleanup()

# Check error handling when creating a directory that already exists
with tempfile.TemporaryDirectory() as test_dir:
create_directory(test_dir.name)
with pytest.raises(FileExistsError):
create_directory(test_dir.name)

# Test creating directories with different permission levels
with tempfile.TemporaryDirectory() as test_dir:
create_directory(test_dir.name, permission=stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
assert os.stat(test_dir.name).st_mode & 0o777 == stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR

create_directory(test_dir.name, permission=0o755)
assert os.stat(test_dir.name).st_mode & 0o777 == 0o755

# Validate input path handling and normalization
with tempfile.TemporaryDirectory() as test_dir:
test_path = join(test_dir.name, "sub", "directory")
create_directory(test_path)
assert os.path.exists(test_path)

# Ensure proper error handling for invalid or unauthorized paths
with pytest.raises(PermissionError):
create_directory("/root")

with pytest.raises(PermissionError):
create_directory("C:\\Windows\\System32")