Files
slic/tests/test_utils_path.py
T
tligui_y f5bd461401
Run CI Tests / test (push) Has been cancelled
Update tests/test_utils_path.py
2025-07-29 20:22:55 +02:00

105 lines
2.8 KiB
Python

import os
from pathlib import Path
import tempfile
import shutil
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from slic.utils.path import *
import slic.utils.ask_yes_no
# Tests when user says yes to delete if the file exists
def test_can_create_all_files_user_says_yes():
slic.utils.ask_yes_no.ask_yes_no = lambda msg, **kwargs: True
tmp_dir = tempfile.mkdtemp()
f1 = os.path.join(tmp_dir, "a.txt") # exists
f2 = os.path.join(tmp_dir, "b.txt") # does not exist
f3 = os.path.join(tmp_dir, "c.txt") # exists
Path(f1).touch()
Path(f3).touch()
assert os.path.isfile(f1)
assert not os.path.exists(f2)
assert os.path.isfile(f3)
result = can_create_all_files([f1, f2, f3])
assert result is True
assert not os.path.exists(f1)
assert not os.path.exists(f3)
assert not os.path.exists(f2)
shutil.rmtree(tmp_dir)
# Tests when user says no to delete if the file exists
def test_can_create_all_files_user_says_no():
slic.utils.ask_yes_no.ask_yes_no = lambda msg, **kwargs: False
tmp_dir = tempfile.mkdtemp()
f1 = os.path.join(tmp_dir, "file1.txt") # exists
f2 = os.path.join(tmp_dir, "file2.txt") # doesn't exist
Path(f1).touch()
result = can_create_all_files([f1, f2])
assert result is False
assert os.path.exists(f1) # File must still exist
shutil.rmtree(tmp_dir)
# Directory creation test
def test_make_missing_dir_creates_folder():
tmp_dir = tempfile.mkdtemp()
new_folder = os.path.join(tmp_dir, "nested/dir")
assert not os.path.exists(new_folder)
make_missing_dir(new_folder)
assert os.path.isdir(new_folder)
shutil.rmtree(tmp_dir)
# glob_files()
def test_glob_files_returns_matching_files_only():
tmp_dir = tempfile.mkdtemp()
Path(os.path.join(tmp_dir, "a.txt")).touch()
Path(os.path.join(tmp_dir, "l.log")).touch()
Path(os.path.join(tmp_dir, "b.txt")).touch()
Path(os.path.join(tmp_dir, "note.md")).touch()
os.mkdir(os.path.join(tmp_dir, "folder"))
result = list(glob_files(tmp_dir, "*.txt"))
result_names = sorted([f.name for f in result])
assert result_names == ["a.txt", "b.txt"]
shutil.rmtree(tmp_dir)
# filter_files()
def test_filter_files_excludes_directories():
tmp_dir = tempfile.mkdtemp()
f1 = Path(os.path.join(tmp_dir, "x.txt"))
f3 = Path(os.path.join(tmp_dir, "y.log"))
f2 = Path(os.path.join(tmp_dir, "y.txt"))
d1 = Path(os.path.join(tmp_dir, "dir"))
f4 = Path(os.path.join(tmp_dir, "y.json"))
f1.touch()
f3.touch()
f2.touch()
d1.mkdir()
f4.touch()
result = filter_files([f1, f3, f2, d1, f4])
result_names = sorted([p.name for p in result])
assert result_names == ["x.txt", "y.json", "y.log", "y.txt"]
shutil.rmtree(tmp_dir)