Skip to content

Commit

Permalink
add a separate class FileManager
Browse files Browse the repository at this point in the history
  • Loading branch information
MAfarrag committed Jan 4, 2025
1 parent 06c07d6 commit 74c7c63
Show file tree
Hide file tree
Showing 3 changed files with 111 additions and 1 deletion.
5 changes: 5 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@ max-line-length = 88
max-complexity = 18
select = "B,C,E,F,W,T4"

[tool.isort]
profile = "black"
multi_line_output = 3
line_length = 88


[tool.pytest.ini_options]
markers = [
Expand Down
59 changes: 59 additions & 0 deletions src/Hapi/parameters/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import json
import os
from pathlib import Path
from typing import Dict, List, Optional, Union
from urllib.request import urlretrieve

Expand Down Expand Up @@ -509,3 +510,61 @@ def list_article_versions(self, article_id: int) -> List[Dict[str, int]]:
"""
endpoint = f"articles/{article_id}/versions"
return self.send_request("GET", endpoint)


class FileManager:
"""
Handle file operations such as downloading and saving files.
Methods
-------
download_file(url: str, dest_path: Path):
Download a file from the specified URL to the destination path.
clear_directory(directory: Path):
Clears all files in the specified directory.
Examples
--------
>>> FileManager.download_file("http://example.com/file", Path("./downloads/file.txt"))
>>> FileManager.clear_directory(Path("./downloads"))
"""

@staticmethod
def download_file(url: str, dest_path: Path):
"""
Download a file from the specified URL to the destination path.
Parameters
----------
url : str
The URL of the file to download.
dest_path : Path
The local file path where the file will be saved.
Examples
--------
>>> FileManager.download_file("http://example.com/file", Path("./downloads/file.txt"))
"""
dest_path.parent.mkdir(parents=True, exist_ok=True)
urlretrieve(url, dest_path)
logger.info(f"File downloaded: {dest_path}")

@staticmethod
def clear_directory(directory: Path):
"""
Clear all files in the specified directory.
Parameters
----------
directory : Path
The directory to clear.
Examples
--------
>>> FileManager.clear_directory(Path("./downloads"))
"""
if directory.exists():
for file in directory.iterdir():
if file.is_file():
file.unlink()
logger.info(f"Cleared directory: {directory}")
48 changes: 47 additions & 1 deletion tests/rrm/parameters/test_parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import pytest

from Hapi.parameters.parameters import FigshareAPIClient, Parameter
from Hapi.parameters.parameters import FigshareAPIClient, FileManager, Parameter


def test_constructor():
Expand Down Expand Up @@ -176,3 +176,49 @@ def test_figshare_api_client_no_content(self):

assert response is not None, "Response should not be None."
assert isinstance(response, list), "Response should be a list."


class TestFileManager:

@pytest.fixture
def temp_directory(self, tmp_path):
"""Fixture to create a temporary directory for testing."""
return tmp_path

def test_directory_creation(self, temp_directory):
"""Test that a directory is created if it doesn't exist."""
new_dir = temp_directory / "new_subdir"
file_path = new_dir / "example.txt"

FileManager.download_file("https://www.example.com", file_path)

assert new_dir.exists(), "The directory should be created."
assert file_path.exists(), "The file should be created in the new directory."

def test_clear_directory(self, temp_directory):
"""Test clearing all files in a directory."""
# Create sample files
for i in range(3):
(temp_directory / f"file_{i}.txt").write_text(f"Content {i}")

FileManager.clear_directory(temp_directory)

assert not any(
temp_directory.iterdir()
), "The directory should be empty after clearing."

def test_clear_empty_directory(self, temp_directory):
"""Test clearing an already empty directory."""
FileManager.clear_directory(temp_directory)

assert not any(temp_directory.iterdir()), "The directory should remain empty."

def test_clear_nonexistent_directory(self):
"""Test clearing a directory that doesn't exist."""
non_existent_dir = Path("./non_existent_directory")

FileManager.clear_directory(non_existent_dir)

assert (
not non_existent_dir.exists()
), "The directory should not exist and should not cause errors."

0 comments on commit 74c7c63

Please sign in to comment.