def test_tilde_expansion(mock_exists, mock_samefile, mock_move, mock_trash, mock_mkdir): mock_exists.return_value = False mock_samefile.return_value = False move = Move(dest="~/newname.py", overwrite=False) updates = move.run(**ARGS) mock_mkdir.assert_called_with(exist_ok=True, parents=True) mock_exists.assert_called_with() mock_trash.assert_not_called() mock_move.assert_called_with(src=os.path.join(USER_DIR, "test.py"), dst=os.path.join(USER_DIR, "newname.py")) assert updates == {"path": Path("~/newname.py").expanduser()}
def test_into_folder(mock_exists, mock_samefile, mock_move, mock_trash, mock_mkdir): mock_exists.return_value = False mock_samefile.return_value = False move = Move(dest="~/somefolder/", overwrite=False) updates = move.run(**ARGS) mock_mkdir.assert_called_with(exist_ok=True, parents=True) mock_exists.assert_called_with() mock_trash.assert_not_called() mock_move.assert_called_with( src=os.path.join(USER_DIR, "test.py"), dst=os.path.join(USER_DIR, "somefolder", "test.py"), ) assert updates == {"path": Path(USER_DIR) / "somefolder" / "test.py"}
def _created(self, path: Path) -> pendulum.DateTime: # see https://stackoverflow.com/a/39501288/300783 stat = path.stat() time = 0 # type: SupportsFloat if sys.platform.startswith("win"): time = stat.st_ctime else: try: time = stat.st_birthtime except AttributeError: # We're probably on Linux. No easy way to get creation dates here, # so we'll settle for when its content was last modified. time = stat.st_mtime return pendulum.from_timestamp(float(time))
def test_extension_result(): path = Path("~/somefile.TxT") extension = Extension("txt") assert extension.matches(path) result = extension.run(path=path)["extension"] assert str(result) == "TxT" assert result.lower == "txt" assert result.upper == "TXT" extension = Extension(".txt") assert extension.matches(path) result = extension.run(path=path)["extension"] assert str(result) == "TxT" assert result.lower == "txt" assert result.upper == "TXT"
def create_filesystem(tmp_path, files, config): # create files for f in files: try: name, content = f except Exception: name = f content = "" p = tmp_path / "files" / Path(name) p.parent.mkdir(parents=True, exist_ok=True) with p.open("w") as ptr: ptr.write(content) # create config with (tmp_path / "config.yaml").open("w") as f: f.write(config) # change working directory os.chdir(str(tmp_path))
def matches(self, path: Path) -> Union[bool, ExifDict]: # NOTE: This should return Union[Literal[False], ExifDict] but Literal is only # available in Python>=3.8. with path.open("rb") as f: exiftags = exifread.process_file(f, details=False) # type: Dict if not exiftags: return False tags = {k.lower(): v.printable for k, v in exiftags.items()} # no match if expected tag is not found normkey = lambda k: k.replace(".", " ").lower() for key in self.args: if normkey(key) not in tags: return False # no match if tag has not expected value for key, value in self.kwargs.items(): key = normkey(key) if not (key in tags and tags[key].lower() == value.lower()): return False return self.category_dict(tags)
from organize.compat import Path from organize.filters import Regex from organize.utils import DotDict TESTDATA = [ (Path("~/Invoices/RG123456123456-sig.pdf"), True, "123456123456"), (Path("~/Invoices/RG002312321542-sig.pdf"), True, "002312321542"), (Path("~/Invoices/RG002312321542.pdf"), False, None), ] def test_regex_backslash(): regex = Regex(r"^\.pdf$") assert regex.matches(Path(".pdf")) assert not regex.matches(Path("+pdf")) assert not regex.matches(Path("/pdf")) assert not regex.matches(Path("\\pdf")) def test_regex_basic(): regex = Regex(r"^RG(\d{12})-sig\.pdf$") for path, match, _ in TESTDATA: assert bool(regex.matches(path)) == match def test_regex_return(): regex = Regex(r"^RG(?P<the_number>\d{12})-sig\.pdf$") for path, valid, result in TESTDATA: if valid: dct = regex.run(path=path) assert dct == {"regex": {"the_number": result}}
import os from organize.actions import Rename from organize.compat import Path USER_DIR = os.path.expanduser("~") ARGS = { "basedir": Path.home(), "path": Path.home() / "test.py", "simulate": False } def test_tilde_expansion(mock_exists, mock_samefile, mock_rename, mock_trash): mock_exists.return_value = False mock_samefile.return_value = False rename = Rename(name="newname.py", overwrite=False) new_path = rename.run(**ARGS) assert mock_exists.call_count > 0 mock_trash.assert_not_called() expected_path = (Path.home() / "newname.py").expanduser() mock_rename.assert_called_with(expected_path) assert new_path == expected_path def test_overwrite(mock_exists, mock_samefile, mock_rename, mock_trash): mock_exists.return_value = True mock_samefile.return_value = False rename = Rename(name="{path.stem} Kopie.py", overwrite=True) new_path = rename.run(**ARGS)
def test_trash(mock_trash): trash = Trash() trash.run(path=Path.home() / "this" / "file.tar.gz", simulate=False) mock_trash.assert_called_with(os.path.join(USER_DIR, "this", "file.tar.gz"))
def _last_modified(self, path: Path) -> datetime: return datetime.fromtimestamp(path.stat().st_mtime)
def test_print_substitution(): with patch.object(Python, "print") as mock_print: python = Python("print('Hello World')") python.run(path=Path.home(), simulate=False) mock_print.assert_called_with("Hello World")
def test_shell_basic(): with patch("subprocess.call") as m: shell = Shell("echo 'Hello World'") shell.run(path=Path.home(), simulate=False) m.assert_called_with("echo 'Hello World'", shell=True)
def test_extension_empty(): extension = Extension() assert extension.matches(Path("~/test.txt"))
def test_filename_contains(): filename = Filename(contains="begin") assert filename.matches(Path("~/here/beginhere.pdf")) assert filename.matches(Path("~/here/.beginhere.pdf")) assert filename.matches(Path("~/here/herebegin.begin")) assert not filename.matches(Path("~/here/other.begin"))
def test_echo_path(): echo = Echo("{path.stem} for {year}") with patch.object(echo, "print") as m: echo.run(simulate=False, path=Path("/this/isafile.txt"), year=2017) m.assert_called_with("isafile for 2017")
def assertdir(path, *files): os.chdir(str(path / "files")) assert set(files) == set( str(x) for x in Path(".").glob("**/*") if x.is_file())
def _last_modified(self, path: Path) -> pendulum.DateTime: return pendulum.from_timestamp(float(path.stat().st_mtime))
def test_filename_list_case_sensitive(): filename = Filename( startswith="_", contains=["1", "A", "3", "7"], endswith=["5", "6"], case_sensitive=True, ) assert filename.matches(Path("~/_15.dpf")) assert filename.matches(Path("~/_A5.dpf")) assert filename.matches(Path("~/_A6.dpf")) assert not filename.matches(Path("~/_a6.dpf")) assert filename.matches(Path("~/_35.dpf")) assert filename.matches(Path("~/_36.dpf")) assert filename.matches(Path("~/_somethingA56")) assert not filename.matches(Path("~/_6")) assert not filename.matches(Path("~/_a5.dpf")) assert not filename.matches(Path("~/-A5.dpf")) assert not filename.matches(Path("~/")) assert not filename.matches(Path("~/_a5"))
def test_filename_startswith(): filename = Filename(startswith="begin") assert filename.matches(Path("~/here/beginhere.pdf")) assert not filename.matches(Path("~/here/.beginhere.pdf")) assert not filename.matches(Path("~/here/herebegin.begin"))
def test_filename_endswith(): filename = Filename(endswith="end") assert filename.matches(Path("~/here/hereend.pdf")) assert not filename.matches(Path("~/here/end.tar.gz")) assert not filename.matches(Path("~/here/theendishere.txt"))
import os from organize.actions import Move from organize.compat import Path from organize.utils import DotDict USER_DIR = os.path.expanduser("~") ARGS = DotDict(basedir=Path.home(), path=Path.home() / "test.py", simulate=False) def test_tilde_expansion(mock_exists, mock_samefile, mock_move, mock_trash, mock_mkdir): mock_exists.return_value = False mock_samefile.return_value = False move = Move(dest="~/newname.py", overwrite=False) updates = move.run(**ARGS) mock_mkdir.assert_called_with(exist_ok=True, parents=True) mock_exists.assert_called_with() mock_trash.assert_not_called() mock_move.assert_called_with(src=os.path.join(USER_DIR, "test.py"), dst=os.path.join(USER_DIR, "newname.py")) assert updates == {"path": Path("~/newname.py").expanduser()} def test_into_folder(mock_exists, mock_samefile, mock_move, mock_trash, mock_mkdir): mock_exists.return_value = False mock_samefile.return_value = False
def test_regex_backslash(): regex = Regex(r"^\.pdf$") assert regex.matches(Path(".pdf")) assert not regex.matches(Path("+pdf")) assert not regex.matches(Path("/pdf")) assert not regex.matches(Path("\\pdf"))
def test_echo_args(): echo = Echo("This is the year {year}") with patch.object(echo, "print") as m: echo.run(path=Path('~'), simulate=False, year=2017) m.assert_called_with("This is the year 2017")
def test_regex_umlaut(): regex = Regex(r"^Erträgnisaufstellung-(?P<year>\d*)\.pdf") doc = Path("~/Documents/Erträgnisaufstellung-1998.pdf") assert regex.matches(doc) dct = regex.run(path=doc) assert dct == {"regex": {"year": "1998"}}
def test_echo_basic(): echo = Echo("Hello World") with patch.object(echo, "print") as m: echo.run(path=Path('~'), simulate=False) m.assert_called_with("Hello World")
def test_shell_args(): with patch("subprocess.call") as m: shell = Shell("echo {year}") shell.run(path=Path.home(), year=2017, simulate=False) m.assert_called_with("echo 2017", shell=True)