Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: Create the directory automatically if it doesn't exist #70 #73

Merged
merged 5 commits into from
Feb 19, 2024
Merged
Show file tree
Hide file tree
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
20 changes: 19 additions & 1 deletion target_csv/serialization.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,26 @@
import csv # noqa: D100
from pathlib import Path
from typing import Any, List
from typing import Any, List, Callable
import os


def create_folder_if_not_exists(func: Any) -> Callable[..., int]:
"""Decorator to create folder if it does not exist."""

def wrapper(*args: Any, **kwargs: Any) -> int:
try:
filepath = kwargs["filepath"]
except KeyError:
filepath = args[0]
folder = os.path.dirname(filepath)
if not os.path.exists(folder) and folder != "":
os.makedirs(folder)
return func(*args, **kwargs)

return wrapper


@create_folder_if_not_exists
def write_csv(filepath: Path, records: List[dict], schema: dict, **kwargs: Any) -> int:
"""Write a CSV file."""
if "properties" not in schema:
Expand Down
19 changes: 19 additions & 0 deletions tests/test_csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,30 @@ def output_filepath(output_dir) -> Path:
return result


@pytest.fixture
def test_file_paths(output_dir) -> List[Path]:
paths = []
for dir in range(4):
path = Path(output_dir / f"test-dir-{dir}/csv-test-output-{dir}.csv")
if path.exists():
path.unlink()

paths.append(path)

return paths


def test_csv_write(output_filepath) -> None:
for schema, records in SAMPLE_DATASETS:
write_csv(filepath=output_filepath, records=records, schema=schema)


def test_csv_write_if_not_exists(test_file_paths) -> None:
for path in test_file_paths:
for schema, records in SAMPLE_DATASETS:
write_csv(filepath=path, records=records, schema=schema)


def test_csv_roundtrip(output_filepath) -> None:
for schema, records in SAMPLE_DATASETS:
write_csv(filepath=output_filepath, records=records, schema=schema)
Expand Down