id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
11,700
cmd_result.py
andreafrancia_trash-cli/tests/support/run/cmd_result.py
from tests.support.help.help_reformatting import reformat_help_message from tests.support.text.last_line_of import last_line_of class CmdResult: def __init__(self, stdout, # type: str stderr, # type: str exit_code, # type: int ): # (...) -> None self.stdout = stdout self.stderr = stderr self.exit_code = exit_code self.all = (stdout, stderr, exit_code) def all_lines(self): return set(self.stderr.splitlines() + self.stdout.splitlines()) def __str__(self): return str(self.all) def output(self): return self._format([self.stdout, self.stderr]) def last_line_of_stderr(self): return last_line_of(self.stderr) def last_line_of_stdout(self): return last_line_of(self.stdout) def reformatted_help(self): return reformat_help_message(self.stdout) @staticmethod def _format(outs): outs = [out for out in outs if out != ""] return "".join([out.rstrip("\n") + "\n" for out in outs])
1,089
Python
.py
28
30.428571
71
0.60076
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,701
run_command.py
andreafrancia_trash-cli/tests/support/run/run_command.py
import os import subprocess import sys from tests.support.dicts import merge_dicts from tests.support.make_scripts import script_path_for from tests.support.project_root import project_root from tests.support.run.cmd_result import CmdResult def run_command(cwd, command, args=None, input='', env=None): if env is None: env = {} if args is None: args = [] command_full_path = script_path_for(command) env['PYTHONPATH'] = project_root() process = subprocess.Popen([sys.executable, command_full_path] + args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, env=merge_dicts(os.environ, env)) stdout, stderr = process.communicate(input=input.encode('utf-8')) return CmdResult(stdout.decode('utf-8'), stderr.decode('utf-8'), process.returncode)
1,016
Python
.py
24
31.125
74
0.600202
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,702
last_line_of.py
andreafrancia_trash-cli/tests/support/text/last_line_of.py
def last_line_of(stdout): if len(stdout.splitlines()) > 0: return stdout.splitlines()[-1] else: return ''
130
Python
.py
5
20.2
38
0.592
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,703
grep.py
andreafrancia_trash-cli/tests/support/text/grep.py
def grep(stream, pattern): # type: (str, str) -> str return ''.join([line for line in stream.splitlines(True) if pattern in line])
176
Python
.py
4
32
55
0.52907
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,704
list_trash_dir.py
andreafrancia_trash-cli/tests/support/trash_dirs/list_trash_dir.py
from tests.support.dirs.list_file_in_subdir import list_files_in_subdir def list_trash_dir(trash_dir_path): return (list_files_in_subdir(trash_dir_path, 'info') + list_files_in_subdir(trash_dir_path, 'files'))
228
Python
.py
4
51.5
71
0.716216
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,705
__init__.py
andreafrancia_trash-cli/tests/support/asserts/__init__.py
import unittest def assert_equals_with_unidiff(expected, actual): def unidiff(expected, actual): import difflib expected = expected.splitlines(1) actual = actual.splitlines(1) diff = difflib.unified_diff(expected, actual, fromfile='Expected', tofile='Actual', lineterm='\n', n=10) return ''.join(diff) assert expected == actual, ("\n" "Expected:%s\n" % repr(expected) + " Actual:%s\n" % repr(actual) + unidiff(expected, actual)) def assert_starts_with(actual, expected): class Dummy(unittest.TestCase): def nop(self): pass _t = Dummy('nop') _t.assertEqual(actual[:len(expected)], expected)
847
Python
.py
20
28.55
73
0.527473
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,706
restore_fake_fs.py
andreafrancia_trash-cli/tests/test_restore/support/restore_fake_fs.py
import os from typing import Iterable from trashcli.restore.file_system import FileReader from trashcli.restore.file_system import ListingFileSystem class RestoreFakeFs(FileReader, ListingFileSystem): def __init__(self, fs, # type FakeFs ): self.fs = fs def contents_of(self, path): return self.fs.read(path) def list_files_in_dir(self, path): # type: (str) -> Iterable[str] for entry in self.fs.listdir(path): result = os.path.join(path, entry) yield result
561
Python
.py
15
29.733333
70
0.651852
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,707
fake_logger.py
andreafrancia_trash-cli/tests/test_restore/support/fake_logger.py
from __future__ import print_function from trashcli.restore.trashed_files import RestoreLogger class FakeLogger(RestoreLogger): def __init__(self, out): self.out = out def warning(self, message): print("WARN: %s" % message, file=self.out)
266
Python
.py
7
33.142857
56
0.703125
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,708
test_restore2.py
andreafrancia_trash-cli/tests/test_restore/cmd/test_restore2.py
import datetime import unittest from tests.support.py2mock import Mock, call from tests.support.restore.fake_restore_fs import FakeRestoreFs from tests.support.restore.restore_user import RestoreUser from trashcli.restore.file_system import RestoreWriteFileSystem class TestRestore2(unittest.TestCase): def setUp(self): self.write_fs = Mock(spec=RestoreWriteFileSystem) self.fs = FakeRestoreFs() self.user = RestoreUser( environ={'XDG_DATA_HOME': '/data_home'}, uid=1000, file_reader=self.fs, read_fs=self.fs, write_fs=self.write_fs, listing_file_system=self.fs, version='1.2.3', volumes=self.fs, ) def test_should_print_version(self): res = self.cmd_run(['trash-restore', '--version']) assert 'trash-restore 1.2.3\n' == res.stdout def test_with_no_args_and_no_files_in_trashcan(self): res = self.cmd_run(['trash-restore'], from_dir='cwd') assert ("No files trashed from current dir ('cwd')\n" == res.stdout) def test_restore_operation(self): self.fs.add_trash_file('/cwd/parent/foo.txt', '/data_home/Trash', datetime.datetime(2016, 1, 1), 'boo') res = self.cmd_run(['trash-restore'], reply='0', from_dir='/cwd') assert '' == res.stderr assert ([call.mkdirs('/cwd/parent'), call.move('/data_home/Trash/files/foo.txt', '/cwd/parent/foo.txt'), call.remove_file('/data_home/Trash/info/foo.txt.trashinfo')] == self.write_fs.mock_calls) def test_restore_operation_when_dest_exists(self): self.fs.add_trash_file('/cwd/parent/foo.txt', '/data_home/Trash', datetime.datetime(2016, 1, 1), 'boo') self.fs.add_file('/cwd/parent/foo.txt') res = self.cmd_run(['trash-restore'], reply='0', from_dir='/cwd') assert 'Refusing to overwrite existing file "foo.txt".\n' == res.stderr assert ([] == self.write_fs.mock_calls) def test_when_user_reply_with_empty_string(self): self.fs.add_trash_file('/cwd/parent/foo.txt', '/data_home/Trash', datetime.datetime(2016, 1, 1), 'boo') res = self.cmd_run(['trash-restore'], reply='', from_dir='/cwd') assert res.last_line_of_stdout() == 'No files were restored' def test_when_user_reply_with_not_number(self): self.fs.add_trash_file('/cwd/parent/foo.txt', '/data_home/Trash', datetime.datetime(2016, 1, 1), 'boo') res = self.cmd_run(['trash-restore'], reply='non numeric', from_dir='/cwd') assert res.last_line_of_stderr() == \ 'Invalid entry: not an index: non numeric' assert 1 == res.exit_code def cmd_run(self, args, reply=None, from_dir=None): return self.user.run_restore(args, reply=reply, from_dir=from_dir)
3,020
Python
.py
58
41.051724
83
0.598436
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,709
test_restore_with_real_fs.py
andreafrancia_trash-cli/tests/test_restore/cmd/test_restore_with_real_fs.py
import os import unittest import pytest from tests.support.asserts.assert_that import assert_that from tests.support.dirs.my_path import MyPath from tests.support.restore.a_trashed_file import ATrashedFile from tests.support.restore.has_been_restored_matcher import \ has_been_restored from tests.support.restore.restore_file_fixture import RestoreFileFixture from tests.support.restore.restore_user import RestoreUser from trashcli.fs import RealExists from trashcli.fstab.volumes import FakeVolumes from trashcli.restore.file_system import RealFileReader, \ RealRestoreReadFileSystem, RealRestoreWriteFileSystem, RealListingFileSystem @pytest.mark.slow class TestRestoreTrash(unittest.TestCase): def setUp(self): self.tmp_dir = MyPath.make_temp_dir() self.fixture = RestoreFileFixture(self.tmp_dir / 'XDG_DATA_HOME') self.fs = RealExists() self.cwd = self.tmp_dir / "cwd" XDG_DATA_HOME = self.tmp_dir / 'XDG_DATA_HOME' self.trash_dir = XDG_DATA_HOME / 'Trash' self.user = RestoreUser(environ={'XDG_DATA_HOME': XDG_DATA_HOME}, uid=os.getuid(), file_reader=RealFileReader(), read_fs=RealRestoreReadFileSystem(), write_fs=RealRestoreWriteFileSystem(), listing_file_system=RealListingFileSystem(), version='0.0.0', volumes=FakeVolumes([])) def test_it_does_nothing_when_no_file_have_been_found_in_current_dir(self): res = self.user.run_restore(from_dir='/') self.assertEqual("No files trashed from current dir ('/')\n", res.output()) def test_gives_an_error_on_not_a_number_input(self): self.fixture.having_a_trashed_file('/foo/bar') res = self.user.run_restore(reply='+@notanumber', from_dir='/foo') self.assertEqual('Invalid entry: not an index: +@notanumber\n', res.stderr) def test_it_gives_error_when_user_input_is_too_small(self): self.fixture.having_a_trashed_file('/foo/bar') res = self.user.run_restore(reply='1', from_dir='/foo') self.assertEqual('Invalid entry: out of range 0..0: 1\n', res.stderr) def test_it_gives_error_when_user_input_is_too_large(self): self.fixture.having_a_trashed_file('/foo/bar') res = self.user.run_restore(reply='1', from_dir='/foo') self.assertEqual('Invalid entry: out of range 0..0: 1\n', res.stderr) def test_it_shows_the_file_deleted_from_the_current_dir(self): self.fixture.having_a_trashed_file('/foo/bar') res = self.user.run_restore(reply='', from_dir='/foo') self.assertEqual(' 0 2000-01-01 00:00:01 /foo/bar\n' 'No files were restored\n', res.output()) self.assertEqual('', res.stderr) def test_it_restores_the_file_selected_by_the_user(self): self.fixture.having_a_trashed_file(self.cwd / 'foo') self.user.run_restore(reply='0', from_dir=self.cwd) self.fixture.file_should_have_been_restored(self.cwd / 'foo') def test_it_refuses_overwriting_existing_file(self): self.fixture.having_a_trashed_file(self.cwd / 'foo') self.fixture.make_file(self.cwd / "foo") res = self.user.run_restore(reply='0', from_dir=self.cwd) self.assertEqual('Refusing to overwrite existing file "foo".\n', res.stderr) def test_it_restores_the_file_and_delete_the_trash_info(self): a_trashed_file = self.make_trashed_file() res = self.user.run_restore(reply='0', from_dir=self.cwd) assert res.stderr == '' assert_that(a_trashed_file, has_been_restored(self.fs)) def make_trashed_file(self): # type: () -> ATrashedFile original_location = self.cwd / 'parent/path' backup_copy = self.trash_dir / 'files/path' info_file = self.trash_dir / 'info/path.trashinfo' self.fixture.make_file(info_file, '[Trash Info]\n' 'Path=%s\n' % original_location + 'DeletionDate=2000-01-01T00:00:01\n') self.fixture.make_empty_file(backup_copy) return ATrashedFile( trashed_from=self.cwd / 'parent/path', info_file=self.trash_dir / 'info/path.trashinfo', backup_copy=self.trash_dir / 'files/path', ) def tearDown(self): self.tmp_dir.clean_up()
4,661
Python
.py
87
42.068966
80
0.622056
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,710
test_end_to_end_restore.py
andreafrancia_trash-cli/tests/test_restore/cmd/test_end_to_end_restore.py
import os import unittest from datetime import datetime from os.path import exists as file_exists from os.path import join as pj import pytest from tests.support.fakes.fake_trash_dir import FakeTrashDir from tests.support.dirs.my_path import MyPath from tests.support.run.run_command import run_command from trashcli.fs import read_file @pytest.mark.slow class TestEndToEndRestore(unittest.TestCase): def setUp(self): self.tmp_dir = MyPath.make_temp_dir() self.curdir = self.tmp_dir / "cwd" self.trash_dir = self.tmp_dir / "trash-dir" os.makedirs(self.curdir) self.fake_trash_dir = FakeTrashDir(self.trash_dir) def test_no_file_trashed(self): result = self.run_command("trash-restore") self.assertEqual("""\ No files trashed from current dir ('%s') """ % self.curdir, result.output()) def test_original_file_not_existing(self): self.fake_trash_dir.add_trashinfo3("foo", "/path", datetime(2000,1,1,0,0,1)) result = self.run_command("trash-restore", ["/"], input='0') self.assertEqual(" 0 2000-01-01 00:00:01 /path\n" "What file to restore [0..0]: \n" "[Errno 2] No such file or directory: '%s/files/foo'\n" % self.trash_dir, result.output()) def test_restore_happy_path(self): self.fake_trash_dir.add_trashed_file( "file1", pj(self.curdir, "path", "to", "file1"), "contents") self.fake_trash_dir.add_trashed_file( "file2", pj(self.curdir, "path", "to", "file2"), "contents") self.assertEqual(True, file_exists(pj(self.trash_dir, "info", "file2.trashinfo"))) self.assertEqual(True, file_exists(pj(self.trash_dir, "files", "file2"))) result = self.run_command("trash-restore", ["/", '--sort=path'], input='1') self.assertEqual("""\ 0 2000-01-01 00:00:01 %(curdir)s/path/to/file1 1 2000-01-01 00:00:01 %(curdir)s/path/to/file2 What file to restore [0..1]: """ % { 'curdir': self.curdir}, result.stdout) self.assertEqual("", result.stderr) self.assertEqual("contents", read_file(pj(self.curdir, "path/to/file2"))) self.assertEqual(False, file_exists(pj(self.trash_dir, "info", "file2.trashinfo"))) self.assertEqual(False, file_exists(pj(self.trash_dir, "files", "file2"))) def test_restore_with_relative_path(self): self.fake_trash_dir.add_trashed_file( "file1", pj(self.curdir, "path", "to", "file1"), "contents") self.assertEqual(True, file_exists(pj(self.trash_dir, "info", "file1.trashinfo"))) self.assertEqual(True, file_exists(pj(self.trash_dir, "files", "file1"))) result = self.run_command("trash-restore", ["%(curdir)s" % {'curdir': "."}, '--sort=path'], input='0') self.assertEqual("""\ 0 2000-01-01 00:00:01 %(curdir)s/path/to/file1 What file to restore [0..0]: """ % {'curdir': self.curdir}, result.stdout) self.assertEqual("", result.stderr) self.assertEqual("contents", read_file(pj(self.curdir, "path/to/file1"))) self.assertEqual(False, file_exists(pj(self.trash_dir, "info", "file1.trashinfo"))) self.assertEqual(False, file_exists(pj(self.trash_dir, "files", "file1"))) def run_command(self, command, args=None, input=''): if args is None: args = [] return run_command(self.curdir, command, ["--trash-dir", self.trash_dir] + args, input) def tearDown(self): self.tmp_dir.clean_up()
3,702
Python
.py
71
42.619718
91
0.610127
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,711
test_listing_in_restore_cmd.py
andreafrancia_trash-cli/tests/test_restore/cmd/test_listing_in_restore_cmd.py
import unittest from tests.support.py2mock import Mock from six import StringIO from trashcli.restore.file_system import FakeReadCwd from trashcli.restore.handler import Handler from trashcli.restore.restore_cmd import RestoreCmd from trashcli.restore.trashed_file import TrashedFile from trashcli.restore.trashed_files import TrashedFiles class TestListingInRestoreCmd(unittest.TestCase): def setUp(self): self.logger = Mock(spec=[]) self.trashed_files = Mock(spec=TrashedFiles) self.trashed_files.all_trashed_files = Mock() self.original_locations = [] self.fake_handler = FakeHandler(self.original_locations) self.cmd = RestoreCmd(stdout=StringIO(), version="0.0.0", trashed_files=self.trashed_files, read_cwd=FakeReadCwd("dir"), handler=self.fake_handler) def test_with_no_args_and_files_in_trashcan(self): self.trashed_files.all_trashed_files.return_value = [ a_trashed_file('dir/location'), a_trashed_file('dir/location'), a_trashed_file('anotherdir/location') ] self.cmd.run(['trash-restore']) assert [ 'dir/location', 'dir/location' ] == self.original_locations def test_with_no_args_and_files_in_trashcan_2(self): self.trashed_files.all_trashed_files.return_value = [ a_trashed_file('/dir/location'), a_trashed_file('/dir/location'), a_trashed_file('/specific/path'), ] self.cmd.run(['trash-restore', '/specific/path']) assert self.original_locations == ['/specific/path'] def test_with_with_path_prefix_bug(self): self.trashed_files.all_trashed_files.return_value = [ a_trashed_file('/prefix'), a_trashed_file('/prefix-with-other'), ] self.cmd.run(['trash-restore', '/prefix']) assert self.original_locations == ['/prefix'] def a_trashed_file(original_location): return TrashedFile(original_location=original_location, deletion_date="a date", info_file="", original_file="") class FakeHandler(Handler): def __init__(self, original_locations): self.original_locations = original_locations def handle_trashed_files(self, trashed_files, _overwrite): for trashed_file in trashed_files: self.original_locations.append(trashed_file.original_location)
2,611
Python
.py
57
35.052632
74
0.625394
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,712
test_trashed_file_restore_integration.py
andreafrancia_trash-cli/tests/test_restore/cmd/test_trashed_file_restore_integration.py
import os import unittest from tests.support.py2mock import Mock from six import StringIO from tests.support.files import make_empty_file from tests.support.dirs.my_path import MyPath from trashcli.lib.my_input import HardCodedInput from trashcli.restore.file_system import RealRestoreWriteFileSystem, \ FakeReadCwd, RealRestoreReadFileSystem from trashcli.restore.restore_cmd import RestoreCmd from trashcli.restore.trashed_file import TrashedFile from trashcli.restore.trashed_files import TrashedFiles class TestTrashedFileRestoreIntegration(unittest.TestCase): def setUp(self): self.stdout = StringIO() self.stderr = StringIO() self.input = HardCodedInput() self.temp_dir = MyPath.make_temp_dir() cwd = self.temp_dir self.logger = Mock(spec=[]) self.trashed_files = Mock(spec=TrashedFiles) self.cmd = RestoreCmd.make(stdout=self.stdout, stderr=self.stderr, exit=lambda _: None, input=self.input, version="0.0.0", trashed_files=self.trashed_files, read_fs=RealRestoreReadFileSystem(), write_fs=RealRestoreWriteFileSystem(), read_cwd=FakeReadCwd(cwd)) def test_restore(self): trashed_file = TrashedFile(self.temp_dir / 'parent/path', None, self.temp_dir / 'info_file', self.temp_dir / 'orig') make_empty_file(self.temp_dir / 'orig') make_empty_file(self.temp_dir / 'info_file') self.input.set_reply('0') self.trashed_files.all_trashed_files.return_value = [trashed_file] self.cmd.run(['trash-restore']) assert os.path.exists(self.temp_dir / 'parent/path') assert not os.path.exists(self.temp_dir / 'info_file') assert not os.path.exists(self.temp_dir / 'orig') def test_restore_over_existing_file(self): trashed_file = TrashedFile(self.temp_dir / 'path', None, None, None) make_empty_file(self.temp_dir / 'path') self.input.set_reply('0') self.trashed_files.all_trashed_files.return_value = [trashed_file] self.cmd.run(['trash-restore']) assert self.stderr.getvalue() == 'Refusing to overwrite existing file "path".\n' def tearDown(self): self.temp_dir.clean_up()
2,574
Python
.py
52
36.807692
88
0.606531
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,713
test_restore.py
andreafrancia_trash-cli/tests/test_restore/cmd/test_restore.py
import datetime from tests.support.asserts.assert_that import assert_that from tests.support.restore.fake_restore_fs import FakeRestoreFs from tests.support.restore.has_been_restored_matcher import \ has_been_restored, has_not_been_restored from tests.support.restore.restore_user import RestoreUser class TestSearcher: def setup_method(self): self.fs = FakeRestoreFs() self.user = RestoreUser(environ={'HOME': '/home/user'}, uid=123, file_reader=self.fs, read_fs=self.fs, write_fs=self.fs, listing_file_system=self.fs, version='1.0', volumes=self.fs) def test_will_not_detect_trashed_file_in_dirs_other_than_cur_dir(self): self.fs.add_volume('/disk1') self.fs.add_file('/disk1/.Trash-123/info/not_a_trashinfo') self.fs.add_trash_file("/foo", '/home/user/.local/share/Trash', date_at(2018, 1, 1), '') self.fs.add_trash_file("/disk1/bar", '/disk1/.Trash-123', date_at(2018, 1, 1), '') res = self.run_restore([], from_dir='/home/user') assert (res.output() == "No files trashed from current dir ('/home/user')\n") def test_will_show_file_in_cur_dir(self): self.fs.add_trash_file("/home/user/foo", '/home/user/.local/share/Trash', date_at(2018, 1, 1), '') res = self.run_restore([], from_dir='/home/user') assert (res.output() == ' 0 2018-01-01 00:00:00 /home/user/foo\n' 'No files were restored\n') def test_actual_restore(self): trashed_file = self.fs.make_trashed_file("/home/user/foo", '/home/user/.local/share/Trash', date_at(2018, 1, 1), "contents of foo\n") assert_that(trashed_file, has_not_been_restored(self.fs)) res = self.run_restore([], reply="0", from_dir='/home/user') assert (res.output() == ' 0 2018-01-01 00:00:00 /home/user/foo\n') assert_that(trashed_file, has_been_restored(self.fs)) assert (self.fs.contents_of('/home/user/foo') == "contents of foo\n") def test_will_sort_by_date_by_default(self): self.add_file_trashed_at("/home/user/third", date_at(2013, 1, 1)) self.add_file_trashed_at("/home/user/second", date_at(2012, 1, 1)) self.add_file_trashed_at("/home/user/first", date_at(2011, 1, 1)) res = self.run_restore([], from_dir='/home/user') assert (res.output() == ' 0 2011-01-01 00:00:00 /home/user/first\n' ' 1 2012-01-01 00:00:00 /home/user/second\n' ' 2 2013-01-01 00:00:00 /home/user/third\n' 'No files were restored\n') def test_will_sort_by_path(self): self.add_file_trashed_at("/home/user/ccc", date_at(2011, 1, 1)) self.add_file_trashed_at("/home/user/bbb", date_at(2011, 1, 1)) self.add_file_trashed_at("/home/user/aaa", date_at(2011, 1, 1)) res = self.run_restore(['trash-restore', '--sort=path'], from_dir='/home/user') assert (res.output() == ' 0 2011-01-01 00:00:00 /home/user/aaa\n' ' 1 2011-01-01 00:00:00 /home/user/bbb\n' ' 2 2011-01-01 00:00:00 /home/user/ccc\n' 'No files were restored\n') def run_restore(self, args, reply='', from_dir=None): return self.user.run_restore(args, reply, from_dir) def add_file_trashed_at(self, original_location, deletion_date): self.fs.make_trashed_file(original_location, '/home/user/.local/share/Trash', deletion_date, '') def date_at(year, month, day): return datetime.datetime(year, month, day, 0, 0)
4,114
Python
.py
73
41.452055
87
0.539935
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,714
test_restore_arg_parser.py
andreafrancia_trash-cli/tests/test_restore/components/arg_parser/test_restore_arg_parser.py
import unittest from trashcli.lib.print_version import PrintVersionArgs from trashcli.restore.args import RunRestoreArgs, Sort from trashcli.restore.restore_arg_parser import RestoreArgParser class TestRestoreArgs(unittest.TestCase): def setUp(self): self.parser = RestoreArgParser() def test_default_path(self): args = self.parser.parse_restore_args([''], "curdir") self.assertEqual(RunRestoreArgs(path='curdir', sort=Sort.ByDate, trash_dir=None, overwrite=False), args) def test_path_specified_relative_path(self): args = self.parser.parse_restore_args(['', 'path'], "curdir") self.assertEqual(RunRestoreArgs(path='curdir/path', sort=Sort.ByDate, trash_dir=None, overwrite=False), args) def test_path_specified_fullpath(self): args = self.parser.parse_restore_args(['', '/a/path'], "ignored") self.assertEqual(RunRestoreArgs(path='/a/path', sort=Sort.ByDate, trash_dir=None, overwrite=False), args) def test_show_version(self): args = self.parser.parse_restore_args(['program', '--version'], "ignored") self.assertEqual(PrintVersionArgs(argv0='program'), args)
1,647
Python
.py
32
32.21875
73
0.511845
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,715
test_sequences.py
andreafrancia_trash-cli/tests/test_restore/components/collaborators/test_sequences.py
import unittest from trashcli.restore.restore_asking_the_user import parse_indexes class TestSequences(unittest.TestCase): def test(self): sequences = parse_indexes("1-5,7", 10) result = [index for index in sequences.all_indexes()] self.assertEqual([1, 2, 3, 4, 5, 7], result)
308
Python
.py
7
38.571429
66
0.701342
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,716
test_all_trash_directories.py
andreafrancia_trash-cli/tests/test_restore/components/collaborators/test_all_trash_directories.py
import unittest from trashcli.fstab.volumes import FakeVolumes2 from trashcli.restore.trash_directories import TrashDirectories1 class TestTrashDirectories(unittest.TestCase): def setUp(self): environ = {'HOME': '~'} self.volumes = FakeVolumes2("volume_of(%s)", []) self.trash_directories = TrashDirectories1(self.volumes, 123, environ) def test_list_all_directories(self): self.volumes.set_volumes(['/', '/mnt']) result = list(self.trash_directories.all_trash_directories()) assert ([ ('~/.local/share/Trash', 'volume_of(~/.local/share/Trash)'), ('/.Trash/123', '/'), ('/.Trash-123', '/'), ('/mnt/.Trash/123', '/mnt'), ('/mnt/.Trash-123', '/mnt')] == result)
838
Python
.py
18
35.666667
80
0.570025
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,717
test_trash_directories2.py
andreafrancia_trash-cli/tests/test_restore/components/collaborators/test_trash_directories2.py
import unittest import pytest from tests.support.py2mock import Mock, call from tests.support.fakes.stub_volume_of import StubVolumeOf from trashcli.restore.trash_directories import TrashDirectories2 @pytest.mark.slow class TestTrashDirectories2(unittest.TestCase): def setUp(self): self.trash_directories = Mock(spec=['all_trash_directories']) self.volumes = StubVolumeOf() self.trash_directories2 = TrashDirectories2( self.volumes, self.trash_directories, ) def test_when_user_dir_is_none(self): self.trash_directories.all_trash_directories.return_value = \ "os-trash-directories" result = self.trash_directories2.trash_directories_or_user(None) self.assertEqual([call.all_trash_directories()], self.trash_directories.mock_calls) self.assertEqual('os-trash-directories', result) def test_when_user_dir_is_specified(self): self.trash_directories.all_trash_directories.return_value = \ "os-trash-directories" result = self.trash_directories2.trash_directories_or_user( 'user-trash_dir') self.assertEqual([], self.trash_directories.mock_calls) self.assertEqual([('user-trash_dir', 'volume_of user-trash_dir')], result)
1,346
Python
.py
29
37.551724
74
0.683244
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,718
test_is_trashed_from_path.py
andreafrancia_trash-cli/tests/test_restore/components/collaborators/test_is_trashed_from_path.py
import unittest from trashcli.restore.run_restore_action import original_location_matches_path class TestOriginalLocationMatchesPath(unittest.TestCase): def test1(self): assert original_location_matches_path("/full/path", "/full") == True def test2(self): assert original_location_matches_path("/full/path", "/full/path") == True def test3(self): assert original_location_matches_path("/prefix-extension", "/prefix") == False def test_root(self): assert original_location_matches_path("/any/path", "/") == True
565
Python
.py
11
45.454545
86
0.711679
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,719
test_restore_asking_the_user.py
andreafrancia_trash-cli/tests/test_restore/components/collaborators/test_restore_asking_the_user.py
import unittest from tests.support.py2mock import Mock, call from trashcli.lib.my_input import HardCodedInput from trashcli.restore.output_event import Quit from trashcli.restore.output_recorder import OutputRecorder from trashcli.restore.restore_asking_the_user import RestoreAskingTheUser from trashcli.restore.restorer import Restorer class TestRestoreAskingTheUser(unittest.TestCase): def setUp(self): self.input = HardCodedInput() self.restorer = Mock(spec=Restorer) self.output = OutputRecorder() self.asking_user = RestoreAskingTheUser(self.input, self.restorer, self.output) def test(self): self.input.set_reply('0') self.asking_user.restore_asking_the_user(['trashed_file1', 'trashed_file2'], False) self.assertEqual('What file to restore [0..1]: ', self.input.last_prompt()) self.assertEqual([call.restore_trashed_file('trashed_file1', False)], self.restorer.mock_calls) self.assertEqual([], self.output.events) def test2(self): self.input.raise_exception(KeyboardInterrupt) self.asking_user.restore_asking_the_user(['trashed_file1', 'trashed_file2'], False) self.assertEqual('What file to restore [0..1]: ', self.input.last_prompt()) self.assertEqual([], self.restorer.mock_calls) self.assertEqual([Quit()], self.output.events)
1,644
Python
.py
32
37.71875
77
0.611111
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,720
test_parse_indexes.py
andreafrancia_trash-cli/tests/test_restore/components/collaborators/test_parse_indexes.py
import unittest import six from trashcli.restore.range import Range from trashcli.restore.restore_asking_the_user import InvalidEntry, parse_indexes from trashcli.restore.sequences import Sequences from trashcli.restore.single import Single class TestParseIndexes(unittest.TestCase): def test_non_numeric(self): with six.assertRaisesRegex(self, InvalidEntry, "^not an index: a$"): parse_indexes("a", 10) def test(self): with six.assertRaisesRegex(self, InvalidEntry, "^out of range 0..9: 10$"): parse_indexes("10", 10) def test2(self): self.assertEqual(Sequences([Single(9)]), parse_indexes("9", 10)) def test3(self): self.assertEqual(Sequences([Single(0)]), parse_indexes("0", 10)) def test4(self): assert Sequences([Range(1, 4)]) == parse_indexes("1-4", 10) def test5(self): self.assertEqual(Sequences([Single(1), Single(2), Single(3), Single(4)]), parse_indexes("1,2,3,4", 10)) def test_interval_without_start(self): with six.assertRaisesRegex(self, InvalidEntry, "^open interval: -1$"): parse_indexes("-1", 10) def test_interval_without_end(self): with six.assertRaisesRegex(self, InvalidEntry, "^open interval: 1-$"): parse_indexes("1-", 10) def test_complex(self): indexes = parse_indexes("1-5,7", 10) self.assertEqual(Sequences([Range(1, 5), Single(7)]), indexes)
1,580
Python
.py
34
36.382353
82
0.614733
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,721
test_trash_directory.py
andreafrancia_trash-cli/tests/test_restore/components/collaborators/test_trash_directory.py
import unittest import pytest import six from tests.support.files import make_file, require_empty_dir from tests.support.dirs.my_path import MyPath from trashcli.restore.file_system import RealListingFileSystem from trashcli.restore.info_files import InfoFiles @pytest.mark.slow class TestTrashDirectory(unittest.TestCase): def setUp(self): self.temp_dir = MyPath.make_temp_dir() require_empty_dir(self.temp_dir / 'trash-dir') self.info_files = InfoFiles(RealListingFileSystem()) def test_should_list_a_trashinfo(self): make_file(self.temp_dir / 'trash-dir/info/foo.trashinfo') result = self.list_trashinfos() assert [('trashinfo', self.temp_dir / 'trash-dir/info/foo.trashinfo')] == result def test_should_list_multiple_trashinfo(self): make_file(self.temp_dir / 'trash-dir/info/foo.trashinfo') make_file(self.temp_dir / 'trash-dir/info/bar.trashinfo') make_file(self.temp_dir / 'trash-dir/info/baz.trashinfo') result = self.list_trashinfos() six.assertCountEqual(self, [('trashinfo', self.temp_dir / 'trash-dir/info/foo.trashinfo'), ('trashinfo', self.temp_dir / 'trash-dir/info/baz.trashinfo'), ('trashinfo', self.temp_dir / 'trash-dir/info/bar.trashinfo')], result) def test_non_trashinfo_should_reported_as_a_warn(self): make_file(self.temp_dir / 'trash-dir/info/not-a-trashinfo') result = self.list_trashinfos() six.assertCountEqual(self, [('non_trashinfo', self.temp_dir / 'trash-dir/info/not-a-trashinfo')], result) def list_trashinfos(self): return list(self.info_files.all_info_files(self.temp_dir / 'trash-dir')) def tearDown(self): self.temp_dir.clean_up()
1,943
Python
.py
38
40.289474
93
0.632275
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,722
test_trashed_files.py
andreafrancia_trash-cli/tests/test_restore/components/trashed_files/test_trashed_files.py
import datetime import unittest from six import StringIO from tests.support.put.fake_fs.fake_fs import FakeFs from tests.test_restore.support.fake_logger import FakeLogger from tests.test_restore.support.restore_fake_fs import RestoreFakeFs from trashcli.restore.info_dir_searcher import InfoDirSearcher from trashcli.restore.info_files import InfoFiles from trashcli.restore.trash_directories import TrashDirectories from trashcli.restore.trashed_file import TrashedFile from trashcli.restore.trashed_files import TrashedFiles class TestTrashedFiles(unittest.TestCase): def setUp(self): self.fs = FakeFs() self.out = StringIO() self.logger = FakeLogger(self.out) class FakeTrashDirectories(TrashDirectories): def list_trash_dirs(self, trash_dir_from_cli): return [('/trash-dir', '/')] self.searcher = InfoDirSearcher(FakeTrashDirectories(), InfoFiles(RestoreFakeFs(self.fs))) self.trashed_files = TrashedFiles(self.logger, RestoreFakeFs(self.fs), self.searcher) self.fs.mkdir_p("/trash-dir/info") def test(self): self.fs.write_file('/trash-dir/info/info_path.trashinfo', 'Path=name\n' 'DeletionDate=2001-01-01T10:10:10') trashed_files = list(self.trashed_files.all_trashed_files(None)) assert { 'trashed_files': trashed_files, 'out': self.out.getvalue()} == { 'trashed_files': [ TrashedFile('/name', datetime.datetime(2001, 1, 1, 10, 10, 10), '/trash-dir/info/info_path.trashinfo', '/trash-dir/files/info_path'), ], 'out': '' } def test_on_non_trashinfo(self): self.fs.touch('/trash-dir/info/info_path.non-trashinfo') trashed_files = list(self.trashed_files.all_trashed_files(None)) assert { 'trashed_files': trashed_files, 'out': self.out.getvalue()} == { 'trashed_files': [], 'out': 'WARN: Non .trashinfo file in info dir\n' } def test_on_non_parsable_trashinfo(self): self.fs.write_file('/trash-dir/info/info_path.trashinfo', '') trashed_files = list(self.trashed_files.all_trashed_files(None)) assert { 'trashed_files': trashed_files, 'out': self.out.getvalue()} == { 'trashed_files': [], 'out': 'WARN: Non parsable trashinfo file: ' '/trash-dir/info/info_path.trashinfo, because ' 'Unable to parse Path\n' } def test_on_io_error(self): self.fs.mkdir_p('/trash-dir/info/info_path.trashinfo') trashed_files = list(self.trashed_files.all_trashed_files(None)) assert { 'trashed_files': trashed_files, 'out': self.out.getvalue() } == { 'trashed_files': [], 'out': "WARN: IOErrorReadingTrashInfo(" "path='/trash-dir/info/info_path.trashinfo', " "error='Unable to read: " "/trash-dir/info/info_path.trashinfo')\n" }
3,700
Python
.py
77
31.662338
74
0.521775
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,723
test_trashed_files_integration.py
andreafrancia_trash-cli/tests/test_restore/components/trashed_files/test_trashed_files_integration.py
import datetime import unittest from tests.support.py2mock import Mock from tests.support.files import make_file, require_empty_dir from tests.support.dirs.remove_dir_if_exists import remove_dir_if_exists from trashcli.fs import remove_file from trashcli.restore.file_system import RealFileReader from trashcli.restore.info_dir_searcher import InfoDirSearcher, FileFound from trashcli.restore.trashed_files import TrashedFiles class TestTrashedFilesIntegration(unittest.TestCase): def setUp(self): self.logger = Mock(spec=[]) self.searcher = Mock(spec=InfoDirSearcher) self.trashed_files = TrashedFiles(self.logger, RealFileReader(), self.searcher) def test(self): require_empty_dir('info') self.searcher.all_file_in_info_dir.return_value = [ FileFound('trashinfo', 'info/info_path.trashinfo', '/volume') ] make_file('info/info_path.trashinfo', 'Path=name\nDeletionDate=2001-01-01T10:10:10') trashed_files = list(self.trashed_files.all_trashed_files(None)) trashed_file = trashed_files[0] assert '/volume/name' == trashed_file.original_location assert (datetime.datetime(2001, 1, 1, 10, 10, 10) == trashed_file.deletion_date) assert 'info/info_path.trashinfo' == trashed_file.info_file assert 'files/info_path' == trashed_file.original_file def tearDown(self): remove_file('info/info_path.trashinfo') remove_dir_if_exists('info')
1,600
Python
.py
33
39.30303
73
0.672867
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,724
test_mock_dir_reader.py
andreafrancia_trash-cli/tests/test_support/test_mock_dir_reader.py
import unittest from tests.support.fakes.mock_dir_reader import MockDirReader class TestMockDirReader(unittest.TestCase): def setUp(self): self.fs = MockDirReader() def test_empty(self): result = self.fs.entries_if_dir_exists('/') self.assertEqual([], result) def test_add_file_in_root(self): self.fs.add_file('/foo') result = self.fs.entries_if_dir_exists('/') self.assertEqual(['foo'], result) def test_mkdir(self): self.fs.mkdir('/foo') result = self.fs.entries_if_dir_exists('/') self.assertEqual(['foo'], result) def test_add_file_in_dir(self): self.fs.mkdir('/foo') self.fs.add_file('/foo/bar') result = self.fs.entries_if_dir_exists('/') self.assertEqual(['foo'], result) result = self.fs.entries_if_dir_exists('/foo') self.assertEqual(['bar'], result)
907
Python
.py
23
32.043478
61
0.624857
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,725
test_fake_file_system.py
andreafrancia_trash-cli/tests/test_support/test_fake_file_system.py
# Copyright (C) 2011-2021 Andrea Francia Bereguardo(PV) Italy import unittest from tests.support.fakes.fake_file_system import FakeFileSystem class TestFakeFileSystem(unittest.TestCase): def setUp(self): self.fs = FakeFileSystem() def test_you_can_read_from_files(self): self.fs.create_fake_file('/path/to/file', "file contents") assert 'file contents' == self.fs.contents_of('/path/to/file') def test_when_creating_a_fake_file_it_creates_also_the_dir(self): self.fs.create_fake_file('/dir/file') assert set(('file',)) == set(self.fs.entries_if_dir_exists('/dir')) def test_you_can_create_multiple_fake_file(self): self.fs.create_fake_file('/path/to/file1', "one") self.fs.create_fake_file('/path/to/file2', "two") assert 'one' == self.fs.contents_of('/path/to/file1') assert 'two' == self.fs.contents_of('/path/to/file2') def test_no_file_exists_at_beginning(self): assert not self.fs.exists('/filename') def test_after_a_creation_the_file_exists(self): self.fs.create_fake_file('/filename') assert self.fs.exists('/filename') def test_create_fake_dir(self): self.fs.create_fake_dir('/etc', 'passwd', 'shadow', 'hosts') assert (set(['passwd', 'shadow', 'hosts']) == set(self.fs.entries_if_dir_exists('/etc')))
1,377
Python
.py
26
45.576923
75
0.654735
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,726
test_fake_fstab.py
andreafrancia_trash-cli/tests/test_support/test_fake_fstab.py
import unittest from tests.support.fakes.fake_volume_of import FakeVolumeOf class TestFakeFstab(unittest.TestCase): def test_default(self): volumes = FakeVolumeOf() assert ["/"] == only_mount_points(volumes, ["/"]) def test_it_should_accept_fake_mount_points(self): volumes = FakeVolumeOf() volumes.add_volume('/fake') assert ['/', '/fake'] == only_mount_points(volumes, ['/', '/fake']) def test_something(self): volumes = FakeVolumeOf() volumes.add_volume("/fake") assert '/fake' == volumes.volume_of('/fake/foo') def only_mount_points(volumes, paths): return [p for p in paths if p == volumes.volume_of(p)]
696
Python
.py
16
37.0625
75
0.649331
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,727
test_filesystem.py
andreafrancia_trash-cli/tests/test_support/test_filesystem.py
# Copyright (C) 2008-2021 Andrea Francia Bereguardo(PV) Italy import os import unittest import pytest from trashcli.fs import has_sticky_bit, mkdirs, is_sticky_dir from tests.support.files import make_empty_file, set_sticky_bit, unset_sticky_bit from tests.support.dirs.my_path import MyPath @pytest.mark.slow class TestWithInSandbox(unittest.TestCase): def setUp(self): self.temp_dir = MyPath.make_temp_dir() def test_mkdirs_with_default_mode(self): mkdirs(self.temp_dir / "test-dir/sub-dir") assert os.path.isdir(self.temp_dir / "test-dir/sub-dir") def test_has_sticky_bit_returns_true(self): make_empty_file(self.temp_dir / "sticky") set_sticky_bit(self.temp_dir / "sticky") assert has_sticky_bit(self.temp_dir / 'sticky') def test_has_sticky_bit_returns_false(self): make_empty_file(self.temp_dir / "non-sticky") set_sticky_bit(self.temp_dir / "non-sticky") unset_sticky_bit(self.temp_dir / "non-sticky") assert not has_sticky_bit(self.temp_dir / "non-sticky") def tearDown(self): self.temp_dir.clean_up() class Test_is_sticky_dir(unittest.TestCase): def setUp(self): self.temp_dir = MyPath.make_temp_dir() def test_dir_non_sticky(self): mkdirs(self.temp_dir / 'dir') assert not is_sticky_dir(self.temp_dir / 'dir') def test_dir_sticky(self): mkdirs(self.temp_dir / 'dir') set_sticky_bit(self.temp_dir / 'dir') assert is_sticky_dir(self.temp_dir / 'dir') def test_non_dir_but_sticky(self): make_empty_file(self.temp_dir / 'dir') set_sticky_bit(self.temp_dir / 'dir') assert not is_sticky_dir(self.temp_dir / 'dir') def tearDown(self): self.temp_dir.clean_up()
1,795
Python
.py
41
37.146341
81
0.671288
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,728
test_partitions.py
andreafrancia_trash-cli/tests/test_support/test_partitions.py
import unittest from trashcli.fstab.mount_points_listing import Partitions class MockPartition: def __init__(self, device=None, mountpoint=None, fstype=None): self.device = device self.mountpoint = mountpoint self.fstype = fstype class TestOsMountPoints(unittest.TestCase): def setUp(self): self.partitions = Partitions(['realfs']) def test_a_physical_fs(self): result = self.partitions.should_used_by_trashcli( MockPartition(fstype='realfs')) assert True == result def test_virtual_fs(self): result = self.partitions.should_used_by_trashcli( MockPartition(fstype='virtual_fs')) assert False == result def test_tmpfs(self): result = self.partitions.should_used_by_trashcli( MockPartition( device='tmpfs', mountpoint='/tmp', fstype='tmpfs')) assert True == result
958
Python
.py
25
29.52
66
0.642082
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,729
test_tox_version_matches.py
andreafrancia_trash-cli/tests/test_support/test_tox_version_matches.py
import os import sys def test_tox_version_matched(): env_name = os.getenv('TOX_ENV_NAME', None) version = sys.version_info assert (env_name, version.major, version.minor) in [ ('py27', 2, 7), ('py310', 3, 10), (None, version.major, version.minor) ]
291
Python
.py
10
23.9
56
0.616487
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,730
test_fake_volume_of.py
andreafrancia_trash-cli/tests/test_support/test_fake_volume_of.py
import pytest from tests.support.fakes.fake_volume_of import FakeVolumeOf class TestFakeVolumeOf: @pytest.fixture def volumes(self): return FakeVolumeOf() def test_return_the_containing_volume(self, volumes): volumes.add_volume('/fake-vol') assert '/fake-vol' == volumes.volume_of('/fake-vol/foo') def test_with_file_that_are_outside(self, volumes): volumes.add_volume('/fake-vol') assert '/' == volumes.volume_of('/foo') def test_it_work_also_with_relative_mount_point(self, volumes): volumes.add_volume('relative-fake-vol') assert 'relative-fake-vol' == volumes.volume_of( 'relative-fake-vol/foo')
697
Python
.py
16
36.5
67
0.677083
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,731
test_joining_paths.py
andreafrancia_trash-cli/tests/test_support/test_joining_paths.py
# Copyright (C) 2011 Andrea Francia Trivolzio(PV) Italy def test_how_path_joining_works(): from os.path import join assert '/another-absolute' == join('/absolute', '/another-absolute') assert '/absolute/relative' == join('/absolute', 'relative') assert '/absolute' == join('relative', '/absolute') assert 'relative/relative' == join('relative', 'relative') assert '/absolute' == join('', '/absolute')
426
Python
.py
8
49.125
72
0.673861
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,732
test_fake_ismount.py
andreafrancia_trash-cli/tests/test_support/test_fake_ismount.py
import unittest from tests.support.fakes.fake_is_mount import FakeIsMount class TestOnDefault(unittest.TestCase): def setUp(self): self.ismount = FakeIsMount([]) def test_by_default_root_is_mount(self): assert self.ismount.is_mount('/') def test_while_by_default_any_other_is_not_a_mount_point(self): assert not self.ismount.is_mount('/any/other') class WhenOneFakeVolumeIsDefined(unittest.TestCase): def setUp(self): self.ismount = FakeIsMount(['/fake-vol']) def test_accept_fake_mount_point(self): assert self.ismount.is_mount('/fake-vol') def test_other_still_are_not_mounts(self): assert not self.ismount.is_mount('/other') def test_dont_get_confused_by_traling_slash(self): assert self.ismount.is_mount('/fake-vol/') class TestWhenMultipleFakesMountPoints(unittest.TestCase): def setUp(self): self.ismount = FakeIsMount(['/vol1', '/vol2']) def test_recognize_both(self): assert self.ismount.is_mount('/vol1') assert self.ismount.is_mount('/vol2') assert not self.ismount.is_mount('/other') def test_should_handle_relative_volumes(): ismount = FakeIsMount(['fake-vol']) assert ismount.is_mount('fake-vol')
1,261
Python
.py
28
38.642857
67
0.699341
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,733
test_has_been_restored.py
andreafrancia_trash-cli/tests/test_support/test_has_been_restored.py
import unittest from tests.support.put.fake_fs.fake_fs import FakeFs from tests.support.restore.a_trashed_file import a_trashed_file from tests.support.restore.has_been_restored_matcher import \ has_been_restored class TestHasBeenRestored(unittest.TestCase): def setUp(self): self.fs = FakeFs() self.trashed_file = a_trashed_file(trashed_from='/original_location', info_file='/info_path.trashinfo', backup_copy='/backup_copy') def test_fail_if_original_location_does_not_exists(self): result = has_been_restored(self.fs).describe_mismatch(self.trashed_file, focus_on='original_location') assert result == ( "Expected file to be restore but it has not:\n" " - FAIL original_location should exists but it does not: '/original_location'\n" ) def test_ok_if_original_location_does_not_exists(self): self.fs.make_file('/original_location') result = has_been_restored(self.fs).describe_mismatch(self.trashed_file, focus_on='original_location') assert result == ( "Expected file to be restore but it has not:\n" " - OK original_location should exists and it does: '/original_location'\n" ) def test_fail_if_info_file_exists(self): self.fs.make_file('/info_path.trashinfo') result = has_been_restored(self.fs).describe_mismatch(self.trashed_file, focus_on='info_file') assert result == ( "Expected file to be restore but it has not:\n" " - FAIL info_file should not exists but it does: '/info_path.trashinfo'\n" ) def test_ok_if_info_file_does_not_exists(self): result = has_been_restored(self.fs).describe_mismatch(self.trashed_file, focus_on='info_file') assert result == ( "Expected file to be restore but it has not:\n" " - OK info_file should not exists and it does not: '/info_path.trashinfo'\n" ) def test_fail_if_backup_copy_exists(self): self.fs.make_file('/backup_copy') result = has_been_restored(self.fs).describe_mismatch(self.trashed_file, focus_on='backup_copy') assert result == ( "Expected file to be restore but it has not:\n" " - FAIL backup_copy should not exists but it does: '/backup_copy'\n" ) def test_ok_if_backup_copy_does_not_exists(self): result = has_been_restored(self.fs).describe_mismatch(self.trashed_file, focus_on='backup_copy') assert result == ( "Expected file to be restore but it has not:\n" " - OK backup_copy should not exists and it does not: '/backup_copy'\n" ) def test_fail_if_not_yet_restored(self): self.fs.make_file('/info_path.trashinfo') self.fs.make_file('/backup_copy') result = has_been_restored(self.fs).describe_mismatch(self.trashed_file) assert result == ( "Expected file to be restore but it has not:\n" " - FAIL original_location should exists but it does not: '/original_location'\n" " - FAIL info_file should not exists but it does: '/info_path.trashinfo'\n" " - FAIL backup_copy should not exists but it does: '/backup_copy'\n" ) def test_ok_if_restored(self): self.fs.make_file('/original_location') result = has_been_restored(self.fs).describe_mismatch(self.trashed_file) assert result == ( "Expected file to be restore but it has not:\n" " - OK original_location should exists and it does: '/original_location'\n" " - OK info_file should not exists and it does not: '/info_path.trashinfo'\n" " - OK backup_copy should not exists and it does not: '/backup_copy'\n" )
4,240
Python
.py
75
42.133333
94
0.57559
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,734
test_make_unreadable_file.py
andreafrancia_trash-cli/tests/test_support/files/test_make_unreadable_file.py
import unittest import pytest from trashcli.fs import read_file from ...support.files import make_unreadable_file from tests.support.dirs.my_path import MyPath @pytest.mark.slow class Test_make_unreadable_file(unittest.TestCase): def setUp(self): self.tmp_dir = MyPath.make_temp_dir() def test(self): path = self.tmp_dir / "unreadable" make_unreadable_file(self.tmp_dir / "unreadable") with self.assertRaises(IOError): read_file(path) def tearDown(self): self.tmp_dir.clean_up()
550
Python
.py
16
29
57
0.704545
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,735
test_make_unreadable_dir.py
andreafrancia_trash-cli/tests/test_support/files/test_make_unreadable_dir.py
import errno import os import shutil import unittest from trashcli.fs import remove_file2 from ...support.files import make_unreadable_dir, \ make_readable from tests.support.dirs.my_path import MyPath class Test_make_unreadable_dir(unittest.TestCase): def setUp(self): self.tmp_dir = MyPath.make_temp_dir() self.unreadable_dir = self.tmp_dir / 'unreadable-dir' make_unreadable_dir(self.unreadable_dir) def test_the_directory_has_been_created(self): assert os.path.exists(self.unreadable_dir) def test_and_can_not_be_removed(self): try: remove_file2(self.unreadable_dir) self.fail() except OSError as e: self.assertEqual(errno.errorcode[e.errno], 'EACCES') def tearDown(self): make_readable(self.unreadable_dir) shutil.rmtree(self.unreadable_dir) self.tmp_dir.clean_up()
907
Python
.py
25
29.84
64
0.694508
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,736
test_split_paragraphs.py
andreafrancia_trash-cli/tests/test_support/test_help_reformatting/test_split_paragraphs.py
from parameterized import parameterized # type: ignore from tests.support.help.help_reformatting import split_paragraphs @parameterized.expand([ ('one line', ['one line']), ('one line\n', ['one line\n']), ('one\ntwo\n', ['one\ntwo\n']), ('one\n\ntwo\n', ['one\n', 'two\n']), ('one\n \ntwo\n', ['one\n', 'two\n']), ]) def test_split_paragraphs(text, expected_result): assert split_paragraphs(text) == expected_result
447
Python
.py
11
37.181818
65
0.648961
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,737
test_parse_help.py
andreafrancia_trash-cli/tests/test_support/test_help_reformatting/test_parse_help.py
from tests.support.help.help_reformatting import reformat_help_message, split_paragraphs class TestParseHelp: def test_format_help_message(self): assert reformat_help_message(self.help_message) == ( 'usage: trash-list [-h] [--print-completion {bash,zsh,tcsh}] [--version] ' '[--volumes] [--trash-dirs] [--trash-dir TRASH_DIRS] ' '[--all-users]\n' '\n' 'List trashed files\n' '\n' 'options:\n' ' -h, --help show this help message and exit\n' ' --print-completion {bash,zsh,tcsh}\n' ' print shell completion script\n' " --version show program's version number and exit\n" ' --volumes list volumes\n' ' --trash-dirs list trash dirs\n' ' --trash-dir TRASH_DIRS\n' ' specify the trash directory to use\n' ' --all-users list trashcans of all the users\n' '\n' 'Report bugs to https://github.com/andreafrancia/trash-cli/issues\n') def test_first(self): assert split_paragraphs(self.help_message)[0] == ( 'usage: trash-list [-h] [--print-completion {bash,zsh,tcsh}] [--version]\n' ' [--volumes] [--trash-dirs] [--trash-dir TRASH_DIRS]\n' ' [--all-users]\n') def test_second(self): assert split_paragraphs(self.help_message)[1] == ( 'List trashed files\n') def test_third(self): assert split_paragraphs(self.help_message)[2] == ( 'options:\n' ' -h, --help show this help message and exit\n' ' --print-completion {bash,zsh,tcsh}\n' ' print shell completion script\n' " --version show program's version number and exit\n" ' --volumes list volumes\n' ' --trash-dirs list trash dirs\n' ' --trash-dir TRASH_DIRS\n' ' specify the trash directory to use\n' ' --all-users list trashcans of all the users\n') def test_fourth(self): assert split_paragraphs(self.help_message)[3] == ( 'Report bugs to https://github.com/andreafrancia/trash-cli/issues\n' ) def test_only_four(self): assert len(split_paragraphs(self.help_message)) == 4 help_message = """\ usage: trash-list [-h] [--print-completion {bash,zsh,tcsh}] [--version] [--volumes] [--trash-dirs] [--trash-dir TRASH_DIRS] [--all-users] List trashed files options: -h, --help show this help message and exit --print-completion {bash,zsh,tcsh} print shell completion script --version show program's version number and exit --volumes list volumes --trash-dirs list trash dirs --trash-dir TRASH_DIRS specify the trash directory to use --all-users list trashcans of all the users Report bugs to https://github.com/andreafrancia/trash-cli/issues """
3,272
Python
.py
65
40.276923
88
0.531289
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,738
test_normalize_spaces.py
andreafrancia_trash-cli/tests/test_support/test_help_reformatting/test_normalize_spaces.py
from tests.support.help.help_reformatting import normalize_spaces class TestNormalizeSpaces: def test(self): text = """usage: trash-list [-h] [--print-completion {bash,zsh,tcsh}] [--version] [--volumes] [--trash-dirs] [--trash-dir TRASH_DIRS] [--all-users]""" assert normalize_spaces(text) == ( "usage: trash-list [-h] [--print-completion {bash,zsh,tcsh}] " "[--version] [--volumes] [--trash-dirs] [--trash-dir TRASH_DIRS] " "[--all-users]")
537
Python
.py
10
43.2
89
0.570611
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,739
test_trash_list.py
andreafrancia_trash-cli/tests/test_list/cmd/test_trash_list.py
# Copyright (C) 2011-2024 Andrea Francia Trivolzio(PV) Italy from tests.test_list.cmd.support.trash_list_user import trash_list_user user = trash_list_user class TestTrashList: def test_should_output_nothing_when_trashcan_is_empty(self, user): output = user.run_trash_list() assert output.whole_output() == '' def test_should_output_deletion_date_and_path(self, user): user.home_trash_dir().add_trashinfo4('/absolute/path', "2001-02-03 23:55:59") output = user.run_trash_list() assert (output.whole_output() == "2001-02-03 23:55:59 /absolute/path\n") def test_should_output_info_for_multiple_files(self, user): user.home_trash_dir().add_trashinfo4('/file1', "2000-01-01 00:00:01") user.home_trash_dir().add_trashinfo4('/file2', "2000-01-01 00:00:02") user.home_trash_dir().add_trashinfo4('/file3', "2000-01-01 00:00:03") output = user.run_trash_list() assert output.all_lines() == {"2000-01-01 00:00:01 /file1", "2000-01-01 00:00:02 /file2", "2000-01-01 00:00:03 /file3"} def test_should_output_unknown_dates_with_question_marks(self, user): user.home_trash_dir().add_trashinfo_without_date('without-date') output = user.run_trash_list() assert output.whole_output() == "????-??-?? ??:??:?? /without-date\n" def test_should_output_invalid_dates_using_question_marks(self, user): user.home_trash_dir().add_trashinfo_wrong_date('with-invalid-date', 'Wrong date') output = user.run_trash_list() assert (output.whole_output() == "????-??-?? ??:??:?? /with-invalid-date\n") def test_should_warn_about_empty_trashinfos(self, user): user.home_trash_dir().add_trashinfo_content('empty', '') output = user.run_trash_list() assert output.err_and_out() == ( "Parse Error: /xdg-data-home/Trash/info/empty.trashinfo: Unable " "to parse Path.\n", '') def test_should_warn_about_unreadable_trashinfo(self, user): user.home_trash_dir().add_unreadable_trashinfo('unreadable') output = user.run_trash_list() assert output.err_and_out() == ( "[Errno 13] Permission denied: " "'/xdg-data-home/Trash/info/unreadable.trashinfo'\n", '') def test_should_warn_about_unexistent_path_entry(self, user): user.home_trash_dir().add_trashinfo_without_path("foo") output = user.run_trash_list() assert output.err_and_out() == ( "Parse Error: /xdg-data-home/Trash/info/foo.trashinfo: " "Unable to parse Path.\n", '')
2,830
Python
.py
50
44.68
80
0.592229
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,740
test_list_uses_volume_trash_dirs.py
andreafrancia_trash-cli/tests/test_list/cmd/test_list_uses_volume_trash_dirs.py
# Copyright (C) 2011 Andrea Francia Trivolzio(PV) Italy import pytest from tests.test_list.cmd.support.trash_list_user import trash_list_user # noqa class TestListUsesVolumeTrashDirs: @pytest.fixture def user(self, trash_list_user): u = trash_list_user u.set_fake_uid(123) u.add_disk("disk") return u def test_it_should_lists_content_from_method_1_trash_dir(self, user): user.trash_dir1("disk").make_parent_sticky() user.trash_dir1("disk").add_trashinfo4('file', "2000-01-01") result = user.run_trash_list() assert result.stdout == "2000-01-01 00:00:00 /disk/file\n" def test_it_should_lists_content_from_method_2_trash_dir(self, user): user.trash_dir2("disk").add_trashinfo4('file', "2000-01-01") result = user.run_trash_list() assert result.stdout == "2000-01-01 00:00:00 /disk/file\n"
902
Python
.py
19
40.526316
79
0.669336
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,741
test_end_to_end_list.py
andreafrancia_trash-cli/tests/test_list/cmd/test_end_to_end_list.py
import datetime import unittest import pytest from tests.support.fakes.fake_trash_dir import FakeTrashDir from tests.support.help.help_reformatting import reformat_help_message from tests.support.dirs.my_path import MyPath from tests.support.run.run_command import run_command @pytest.mark.slow class TestEndToEndList(unittest.TestCase): def setUp(self): self.temp_dir = MyPath.make_temp_dir() self.trash_dir = self.temp_dir / 'trash-dir' self.fake_trash_dir = FakeTrashDir(self.trash_dir) def test_list(self): self.fake_trash_dir.add_trashinfo4("/file1", '2000-01-01 00:00:01') self.fake_trash_dir.add_trashinfo4("/file2", '2000-01-01 00:00:02') result = run_command(self.temp_dir, "trash-list", ['--trash-dir', self.trash_dir]) assert result.all_lines() == {'2000-01-01 00:00:01 /file1', '2000-01-01 00:00:02 /file2', } def test_list_trash_dirs(self): result = run_command(self.temp_dir, "trash-list", ['--trash-dirs', '--trash-dir=/home/user/.local/share/Trash']) assert result.all == ('/home/user/.local/share/Trash\n', '', 0) def test_list_with_paths(self): self.fake_trash_dir.add_trashinfo3("base1", "/file1", datetime.datetime(2000, 1, 1, 0, 0, 1)) self.fake_trash_dir.add_trashinfo3("base2", "/file2", datetime.datetime(2000, 1, 1, 0, 0, 1)) result = run_command(self.temp_dir, "trash-list", ['--trash-dir', self.trash_dir, '--files']) assert ('', [ '2000-01-01 00:00:01 /file1 -> %s/files/base1' % self.trash_dir, '2000-01-01 00:00:01 /file2 -> %s/files/base2' % self.trash_dir, ]) == (result.stderr, sorted(result.stdout.splitlines())) def test_help(self): result = run_command(self.temp_dir, "trash-list", ['--help']) self.assertEqual(reformat_help_message("""\ usage: trash-list [-h] [--print-completion {bash,zsh,tcsh}] [--version] [--volumes] [--trash-dirs] [--trash-dir TRASH_DIRS] [--all-users] List trashed files options: -h, --help show this help message and exit --print-completion {bash,zsh,tcsh} print shell completion script --version show program's version number and exit --volumes list volumes --trash-dirs list trash dirs --trash-dir TRASH_DIRS specify the trash directory to use --all-users list trashcans of all the users Report bugs to https://github.com/andreafrancia/trash-cli/issues """), result.stderr + result.reformatted_help()) def tearDown(self): self.temp_dir.clean_up()
2,980
Python
.py
58
39.758621
78
0.574036
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,742
test_with_a_top_trash_dir.py
andreafrancia_trash-cli/tests/test_list/cmd/test_with_a_top_trash_dir.py
# Copyright (C) 2011-2024 Andrea Francia Trivolzio(PV) Italy import pytest from tests.test_list.cmd.support.trash_list_user import trash_list_user # noqa class TestWithATopTrashDir: @pytest.fixture def user(self, trash_list_user): u = trash_list_user u.set_fake_uid(123) u.add_disk("topdir") return u def test_should_list_its_contents_if_parent_is_sticky(self, user): user.trash_dir1("topdir").make_parent_sticky() user.trash_dir1("topdir").add_a_valid_trashinfo() output = user.run_trash_list() assert output.whole_output() == "2000-01-01 00:00:00 /topdir/file1\n" def test_and_should_warn_if_parent_is_not_sticky(self, user): user.trash_dir1("topdir").make_parent_unsticky() user.trash_dir1("topdir").make_dir() output = user.run_trash_list() assert output.whole_output() == ( "TrashDir skipped because parent not sticky: /topdir/.Trash/123\n") def test_but_it_should_not_warn_when_the_parent_is_unsticky_but_there_is_no_trashdir( self, user): user.trash_dir1("topdir").make_parent_unsticky() user.trash_dir1("topdir").does_not_exist() output = user.run_trash_list() assert output.whole_output() == '' def test_should_ignore_trash_from_a_unsticky_topdir(self, user): user.trash_dir1("topdir").make_parent_unsticky() user.trash_dir1("topdir").add_a_valid_trashinfo() output = user.run_trash_list() assert output.whole_output() == ( 'TrashDir skipped because parent not sticky: /topdir/.Trash/123\n') def test_it_should_skip_a_symlink(self, user): user.trash_dir1("topdir").make_parent_symlink() user.trash_dir1("topdir").add_a_valid_trashinfo() output = user.run_trash_list() assert output.err_and_out() == ( 'TrashDir skipped because parent not sticky: /topdir/.Trash/123\n', '')
1,981
Python
.py
40
41.075
89
0.649506
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,743
test_list_volumes.py
andreafrancia_trash-cli/tests/test_list/cmd/test_list_volumes.py
from tests.test_list.cmd.support.trash_list_user import trash_list_user # noqa user = trash_list_user class TestListVolumes: def test(self, user): user.add_disk("/disk1") user.add_disk("/disk2") user.add_disk("/disk3") output = user.run_trash_list('--volumes') assert output.whole_output() == ('/disk1\n' '/disk2\n' '/disk3\n')
461
Python
.py
11
28.909091
79
0.524775
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,744
test_adjust_for_root.py
andreafrancia_trash-cli/tests/test_list/cmd/test_adjust_for_root.py
from tests.test_list.cmd.support.trash_list_user import adjust_for_root class TestAdjustForRoot: def test(self): assert adjust_for_root("disk") == "disk" assert adjust_for_root("/disk") == "disk" assert adjust_for_root("//disk") == "disk"
269
Python
.py
6
38.833333
71
0.662835
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,745
test_version.py
andreafrancia_trash-cli/tests/test_list/cmd/test_version.py
# Copyright (C) 2011-2024 Andrea Francia Trivolzio(PV) Italy from tests.test_list.cmd.support.trash_list_user import trash_list_user user = trash_list_user class TestVersion: def test_should_output_the_version(self, user): user.set_version('1.2.3') output = user.run_trash_list('--version') assert output.whole_output() == 'trash-list 1.2.3\n'
378
Python
.py
8
42
71
0.708791
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,746
trash_list_user.py
andreafrancia_trash-cli/tests/test_list/cmd/support/trash_list_user.py
import os import pytest from six import StringIO from tests.support.dirs.my_path import MyPath from tests.support.fakes.fake_trash_dir import FakeTrashDir from tests.support.fakes.stub_volume_of import StubVolumeOf from tests.support.files import make_empty_dir from trashcli.empty.main import FileSystemContentReader from trashcli.empty.top_trash_dir_rules_file_system_reader import \ RealTopTrashDirRulesReader from trashcli.file_system_reader import FileSystemReader from trashcli.fstab.volume_listing import FixedVolumesListing from trashcli.lib.dir_reader import RealDirReader from trashcli.list.main import ListCmd from .run_result import RunResult @pytest.fixture def trash_list_user(): temp_dir = MyPath.make_temp_dir() yield TrashListUser(temp_dir) temp_dir.clean_up() def adjust_for_root(path): if path.startswith("/"): return os.path.relpath(path, "/") return path class TrashListUser: def __init__(self, root): self.root = root self.xdg_data_home = root / 'xdg-data-home' self.environ = {'XDG_DATA_HOME': self.xdg_data_home} self.fake_uid = None self.volumes = [] self.version = None def run_trash_list(self, *args): # type: (...) -> RunResult file_reader = FileSystemReader() file_reader.list_volumes = lambda: self.volumes stdout = StringIO() stderr = StringIO() ListCmd( out=stdout, err=stderr, environ=self.environ, volumes_listing=FixedVolumesListing(self.volumes), uid=self.fake_uid, volumes=StubVolumeOf(), dir_reader=RealDirReader(), file_reader=RealTopTrashDirRulesReader(), content_reader=FileSystemContentReader(), version=self.version ).run(['trash-list'] + list(args)) return RunResult(clean(stdout.getvalue(), self.root), clean(stderr.getvalue(), self.root)) def set_fake_uid(self, uid): self.fake_uid = uid def add_disk(self, disk_name): top_dir = self.root / adjust_for_root(disk_name) make_empty_dir(top_dir) self.volumes.append(top_dir) def trash_dir1(self, disk_name): return FakeTrashDir( self._trash_dir1_parent(disk_name) / str(self.fake_uid)) def trash_dir2(self, disk_name): return FakeTrashDir(self.root / disk_name / '.Trash-%s' % self.fake_uid) def _trash_dir1_parent(self, disk_name): return self.root / disk_name / '.Trash' def home_trash_dir(self): return FakeTrashDir(self.xdg_data_home / "Trash") def set_version(self, version): self.version = version def clean(stream, xdg_data_home): return stream.replace(xdg_data_home, '')
2,795
Python
.py
70
32.885714
80
0.673809
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,747
run_result.py
andreafrancia_trash-cli/tests/test_list/cmd/support/run_result.py
from typing import NamedTuple from tests.support.text.sort_lines import sort_lines class RunResult(NamedTuple("RunResult", [ ('stdout', str), ('stderr', str), ])): def whole_output(self): return self.stderr + self.stdout def sorted_whole_output(self): return sort_lines(self.whole_output()) def all_lines(self): return set(self.whole_output().splitlines()) def err_and_out(self): return self.stderr, self.stdout
474
Python
.py
14
28.428571
52
0.682819
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,748
test_trash_list_parser.py
andreafrancia_trash-cli/tests/test_list/components/test_trash_list_parser.py
import unittest import trashcli.list import trashcli.list.main import trashcli.list.parser from trashcli.lib.print_version import PrintVersionArgs class TestTrashListParser(unittest.TestCase): def setUp(self): self.parser = trashcli.list.parser.Parser("trash-list") def test_version(self): args = self.parse(['--version']) assert PrintVersionArgs == type(args) def test_trash_dir_not_specified(self): args = self.parse([]) assert [] == args.trash_dirs def test_trash_dir_specified(self): args = self.parse(['--trash-dir=foo']) assert ['foo'] == args.trash_dirs def test_size_off(self): args = self.parse([]) assert 'deletion_date' == args.attribute_to_print def test_size_on(self): args = self.parse(['--size']) assert 'size' == args.attribute_to_print def test_files_off(self): args = self.parse([]) assert False == args.show_files def test_files_on(self): args = self.parse(['--files']) assert True == args.show_files def parse(self, args): return self.parser.parse_list_args(args, 'trash-list')
1,180
Python
.py
31
31.193548
63
0.648099
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,749
test_trash_dirs_selector.py
andreafrancia_trash-cli/tests/test_list/components/test_trash_dirs_selector.py
import unittest from tests.support.fakes.stub_volume_of import StubVolumeOf from trashcli.list.trash_dir_selector import TrashDirsSelector from trashcli.trash_dirs_scanner import trash_dir_found class MockScanner: def __init__(self, name): self.name = name def scan_trash_dirs(self, environ, uid): return [self.name, environ, uid] class TestTrashDirsSelector(unittest.TestCase): def setUp(self): volumes = StubVolumeOf() self.selector = TrashDirsSelector(MockScanner("user"), MockScanner("all"), volumes) def test_default(self): result = list(self.selector.select(False, [], 'environ', 'uid')) assert result == ['user', 'environ', 'uid'] def test_user_specified(self): result = list(self.selector.select(False, ['user-specified-dirs'], 'environ', 'uid')) assert result == [(trash_dir_found, ('user-specified-dirs', 'volume_of user-specified-dirs'))] def test_all_user_specified(self): result = list(self.selector.select(True, ['user-specified-dirs'], 'environ', 'uid')) assert result == ['all', 'environ', 'uid']
1,344
Python
.py
27
36.518519
79
0.575479
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,750
test_deletion_date_extractor.py
andreafrancia_trash-cli/tests/test_list/components/test_deletion_date_extractor.py
import datetime import unittest from trashcli.list.extractors import DeletionDateExtractor class TestDeletionDateExtractor(unittest.TestCase): def setUp(self): self.extractor = DeletionDateExtractor() def test_extract_attribute_default(self): result = self.extractor.extract_attribute(None, "DeletionDate=") assert result == '????-??-?? ??:??:??' def test_extract_attribute_value(self): result = self.extractor.extract_attribute(None, "DeletionDate=2001-01-01T10:10:10") assert result == datetime.datetime(2001, 1, 1, 10, 10, 10)
587
Python
.py
12
43.166667
91
0.715789
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,751
test_file_size.py
andreafrancia_trash-cli/tests/test_list/components/test_file_size.py
from tests.support.dirs.temp_dir import temp_dir # noqa from tests.support.files import make_file from trashcli import fs class TestFileSize: def test(self, temp_dir): make_file(temp_dir / 'a-file', '123') result = fs.file_size(temp_dir / 'a-file') assert 3 == result
300
Python
.py
8
32.625
56
0.685121
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,752
test_move.py
andreafrancia_trash-cli/tests/test_fs/test_move.py
import unittest from tests.support.files import make_file from tests.support.dirs.my_path import MyPath from trashcli.fs import move, read_file class TestMove(unittest.TestCase): def setUp(self): self.tmp_dir = MyPath.make_temp_dir() def test_two_files(self): make_file(self.tmp_dir / 'a', "AAAA") make_file(self.tmp_dir / 'b', "BBBB") result = read_file(self.tmp_dir / 'b') assert result == 'BBBB' def test_move(self): make_file(self.tmp_dir / 'a', "AAAA") make_file(self.tmp_dir / 'b', "BBBB") move(self.tmp_dir / 'a', self.tmp_dir / 'b') result = read_file(self.tmp_dir / 'b') assert result == 'AAAA' def tearDown(self): self.tmp_dir.clean_up()
763
Python
.py
20
31.4
52
0.618852
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,753
test_list_of_created_scripts.py
andreafrancia_trash-cli/tests/test_dev_tools/test_make_scripts/test_list_of_created_scripts.py
from tests.support.py2mock import Mock from tests.support.make_scripts import Scripts from tests.support.make_scripts import script_path_without_base_dir_for class TestListOfCreatedScripts: def setup_method(self): self.bindir = Scripts(make_file_executable=Mock(), write_file=Mock()) def test_is_empty_on_start_up(self): assert self.bindir.created_scripts == [] def test_collect_added_script(self): self.bindir.add_script('foo-command', 'foo-module', 'main') assert self.bindir.created_scripts == [ script_path_without_base_dir_for('foo-command')]
609
Python
.py
12
44.666667
77
0.721284
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,754
test_make_script.py
andreafrancia_trash-cli/tests/test_dev_tools/test_make_scripts/test_make_script.py
from textwrap import dedent from tests.support import py2mock as mock from tests.support.py2mock import Mock from tests.support.make_scripts import Scripts from tests.support.make_scripts import script_path_for class TestMakeScript: def setup_method(self): self.make_file_executable = Mock() self.write_file = Mock() def capture(name, contents): self.name = name self.contents = contents self.write_file.side_effect = capture bindir = Scripts( make_file_executable=self.make_file_executable, write_file=self.write_file) bindir.add_script('trash-put', 'trashcli_module', 'put') def test_should_set_executable_permission(self): self.make_file_executable.assert_called_with(script_path_for('trash-put')) def test_should_write_the_script(self): self.write_file.assert_called_with(script_path_for('trash-put'), mock.ANY) def test_the_script_should_call_the_right_function_from_the_right_module(self): args, kwargs = self.write_file.call_args (_, contents) = args expected = dedent("""\ #!/usr/bin/env python from __future__ import absolute_import import sys from trashcli_module import put as main sys.exit(main()) """) assert expected == contents, ("Expected:\n---\n%s---\n" "Actual :\n---\n%s---\n" % (expected, contents))
1,582
Python
.py
35
33.885714
83
0.60052
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,755
test_generate_scripts.py
andreafrancia_trash-cli/tests/test_dev_tools/test_make_scripts/test_generate_scripts.py
import pytest from tests.support.make_scripts import make_scripts @pytest.mark.slow class TestGenerateScripts: def test(self): scripts = make_scripts() scripts.add_script('trash', 'trashcli.put.main', 'main') scripts.add_script('trash-put', 'trashcli.put.main', 'main') scripts.add_script('trash-list', 'trashcli.list.main', 'main') scripts.add_script('trash-restore', 'trashcli.restore.main', 'main') scripts.add_script('trash-empty', 'trashcli.empty.main', 'main') scripts.add_script('trash-rm', 'trashcli.rm.main', 'main') assert scripts.created_scripts == ['trash', 'trash-put', 'trash-list', 'trash-restore', 'trash-empty', 'trash-rm']
929
Python
.py
18
34.611111
76
0.516556
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,756
fake_cal.py
andreafrancia_trash-cli/tests/test_dev_tools/support/fake_cal.py
from tests.support.tools.core.cal import Cal from tests.support.trashinfo.parse_date import parse_date class FakeCal(Cal): def __init__(self, today): self._today = parse_date(today) def today(self): return self._today
246
Python
.py
7
30.142857
57
0.710638
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,757
fake_system.py
andreafrancia_trash-cli/tests/test_dev_tools/support/fake_system.py
class FakeSystem: def __init__(self): self.clean = False self.os_system_calls = [] def set_dirty(self): self.clean = False def set_clean(self): self.clean = True def os_system(self, cmd): self.os_system_calls.append(cmd) if cmd == 'git diff-index --quiet HEAD' and self.clean: return 0
365
Python
.py
12
22.833333
63
0.58
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,758
run_set_dev_version.py
andreafrancia_trash-cli/tests/test_dev_tools/support/run_set_dev_version.py
from io import StringIO from typing import NamedTuple from typing import Optional from tests.support.capture_exit_code import capture_exit_code from tests.support.put.fake_fs.fake_fs import FakeFs from tests.support.tools.set_dev_version import SetDevVersionCmd from tests.test_dev_tools.cmds.test_bump_cmd import FakeCal class RunSetDevVersion: def __init__(self, fs): self.fs = fs def run_cmd(self, args, capsys): stdout = StringIO() stderr = StringIO() cmd = SetDevVersionCmd(self.fs, stdout, stderr, FakeCal("2024-05-13")) code = capture_exit_code( lambda: cmd.run_set_dev_version(['prg'] + args, "/")) capture = capsys.readouterr() result = Result(stdout.getvalue() + capture.out, stderr.getvalue() + capture.err, code) return situation(result, self.fs) class Result(NamedTuple('Result', [ ('out', str), ('err', str), ('exit_code', Optional[int]), ])): pass def situation(result, # type: Result fs, # type: FakeFs ): # type: (...) -> str return ("exit code: %s\n" % result.exit_code + "stderr: %s\n" % result.err + "stdout: %s\n" % result.out + "filesystem:\n" + "\n".join([ " %s: %s" % (path, content) for path, content in fs.read_all_files() ]) )
1,430
Python
.py
38
29.473684
78
0.588406
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,759
test_set_dev_version_cmd.py
andreafrancia_trash-cli/tests/test_dev_tools/cmds/test_set_dev_version_cmd.py
from tests.support.put.fake_fs.fake_fs import FakeFs from tests.test_dev_tools.support.run_set_dev_version import RunSetDevVersion def adjust_py27(output): return output.replace("prg: error: too few arguments\n", 'prg: error: the following arguments ' 'are required: ref, sha\n') class TestSetDevVersionCmd: def setup_method(self): self.fs = FakeFs() self.run = RunSetDevVersion(self.fs) def test_when_no_args_fails(self, capsys): result = adjust_py27(self.run.run_cmd([], capsys)) assert result == ( 'exit code: 2\n' 'stderr: usage: prg [-h] ref sha\n' 'prg: error: the following arguments are required: ref, sha\n' '\n' 'stdout: \n' 'filesystem:\n') def test_happy_path(self, capsys): self.fs.mkdir("trashcli") self.fs.write_file("trashcli/trash.py", "version = ...") result = self.run.run_cmd(['master', '12345b'], capsys) assert result == ( 'exit code: None\n' 'stderr: \n' 'stdout: \n' 'filesystem:\n' " /trashcli/trash.py: version = '0.24.5.13.dev0+git.master.12345b'" ) def test(self, capsys): self.fs.mkdir("trashcli") self.fs.write_file("trashcli/trash.py", "version = ...") result = self.run.run_cmd(['-', '12345b'], capsys) assert result == ( 'exit code: 1\n' "stderr: Ref cannot contain '-': -\n" "The reason is because any '-' will be converted to '.' by " "setuptools during the egg_info phase that will result in an " "error in scripts/make-scripts because it will be not able to " "find the .tar.gz file\n\n" 'stdout: \n' 'filesystem:\n' ' /trashcli/trash.py: version = ...')
1,922
Python
.py
44
32.954545
80
0.557342
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,760
test_bump_cmd.py
andreafrancia_trash-cli/tests/test_dev_tools/cmds/test_bump_cmd.py
from tests.support.capture_exit_code import capture_exit_code from tests.support.put.fake_fs.fake_fs import FakeFs from tests.support.tools.bump_cmd import BumpCmd from tests.test_dev_tools.support.fake_cal import FakeCal from tests.test_dev_tools.support.fake_system import FakeSystem class TestBumpCmd: def setup_method(self): self.system = FakeSystem() self.print_calls = [] self.fs = FakeFs() self.cmd = BumpCmd(self.system.os_system, self.print_calls.append, self.fs, FakeCal("2024-05-01")) def test_when_dirty(self): exit_code = capture_exit_code(lambda: self.cmd.run_bump("/", [])) assert exit_code == 1 assert self.print_calls == ['Dirty'] assert self.system.os_system_calls == ['git diff-index --quiet HEAD'] def test_when_clean(self): self.system.set_clean() self.fs.mkdir('trashcli') self.fs.make_file('trashcli/trash.py', "version=x.y.x") exit_code = capture_exit_code(lambda: self.cmd.run_bump("/", [])) assert exit_code == None assert self.print_calls == [] assert self.system.os_system_calls == [ 'git diff-index --quiet HEAD', 'git commit -m "Bump version to \'0.24.5.1\'" -a'] assert self.fs.read_all_files() == [ ('/trashcli/trash.py', "version = '0.24.5.1'")] def test_when_clean_and_dry_run(self): self.system.set_clean() self.fs.mkdir('trashcli') self.fs.make_file('trashcli/trash.py', "version=x.y.x") exit_code = capture_exit_code( lambda: self.cmd.run_bump("/", ['--dry-run'])) assert exit_code == None assert self.print_calls == [ 'git commit -m "Bump version to \'0.24.5.1\'" -a'] assert self.system.os_system_calls == [ 'git diff-index --quiet HEAD'] assert self.fs.read_all_files() == [ ('/trashcli/trash.py', "version=x.y.x")]
1,985
Python
.py
42
38.428571
77
0.605794
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,761
test_save_new_version.py
andreafrancia_trash-cli/tests/test_dev_tools/components/test_save_new_version.py
from tests.support.dirs.my_path import MyPath from tests.support.files import make_file from tests.support.tools.version_saver import VersionSaver from trashcli.fs import read_file from trashcli.put.fs.real_fs import RealFs class TestSaveNewVersion: def setup_method(self): self.tmp_dir = MyPath.make_temp_dir() self.saver = VersionSaver(RealFs()) def test(self): make_file(self.tmp_dir / 'trash.py', """\ somecode before version="0.20.1.20" somecode after dont change this line: version="0.20.1.20" """) self.saver.save_new_version('0.21.5.11', self.tmp_dir / 'trash.py') result = read_file(self.tmp_dir / "trash.py") assert result == """\ somecode before version = '0.21.5.11' somecode after dont change this line: version="0.20.1.20" """ def test2(self): make_file(self.tmp_dir / 'trash.py', """\ somecode before version="0.20.1.20" somecode after """) self.saver.save_new_version('0.21.5.11', self.tmp_dir / 'trash.py') result = read_file(self.tmp_dir / "trash.py") assert result == """\ somecode before version="0.20.1.20" somecode after """ def teardown_method(self): self.tmp_dir.clean_up()
1,219
Python
.py
39
27.153846
75
0.677199
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,762
test_version_from_date.py
andreafrancia_trash-cli/tests/test_dev_tools/components/test_version_from_date.py
import datetime from tests.support.tools.version_from_date import version_from_date class TestVersionFromDate: def test(self): today = datetime.date(2021, 5, 11) result = version_from_date(today) assert result == '0.21.5.11'
259
Python
.py
7
31.142857
67
0.707317
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,763
recording_backend.py
andreafrancia_trash-cli/tests/test_put/support/recording_backend.py
from typing import IO from typing import List from tests.test_put.support.logs import Logs from tests.test_put.support.log_line import LogLine from trashcli.put.core.logs import LogData from trashcli.put.core.logs import LogEntry from trashcli.put.my_logger import LoggerBackend from trashcli.put.my_logger import StreamBackend class RecordingBackend(LoggerBackend): def __init__(self, stderr, # type: IO[str] ): self.stderr = stderr self.logs = [] # type: List[LogLine] def write_message(self, log_entry, # type: LogEntry log_data, # type: LogData ): StreamBackend(self.stderr).write_message(log_entry, log_data) for message in log_entry.resolve_messages(): self.logs.append(LogLine(log_entry.level, log_data.verbose, log_data.program_name, message, log_entry.tag)) def collected(self): return Logs(self.logs)
1,133
Python
.py
27
29.185185
69
0.576364
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,764
result.py
andreafrancia_trash-cli/tests/test_put/support/result.py
from typing import List from typing import Tuple from tests.test_put.support.logs import Logs from trashcli.put.core.logs import LogTag class Result: def __init__(self, stderr, # type: List[str] err, # type: str exit_code, # type: int collected_logs, # type: Logs ): self.stderr = stderr self.err = err self.exit_code = exit_code self.collected_logs = collected_logs def exit_code_and_stderr(self): return [self.exit_code, self.stderr] def exit_code_and_logs(self, log_tag, # type: LogTag ): # type: (...) -> Tuple[int, List[str]] return (self.exit_code, self.collected_logs.with_tag(log_tag))
836
Python
.py
23
25.086957
69
0.533416
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,765
log_line.py
andreafrancia_trash-cli/tests/test_put/support/log_line.py
from typing import NamedTuple from trashcli.put.core.logs import Level from trashcli.put.core.logs import LogTag class LogLine(NamedTuple('LogLine', [ ('level', Level), ('verbose', int), ('program_name', str), ('message', str), ('tag', LogTag) ])): pass
281
Python
.py
11
22.090909
41
0.677903
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,766
logs.py
andreafrancia_trash-cli/tests/test_put/support/logs.py
from typing import List from typing import NamedTuple from tests.test_put.support.log_line import LogLine from trashcli.put.core.logs import LogTag from trashcli.put.my_logger import is_right_for_level class Logs(NamedTuple('Logs', [ ('logs', List[LogLine]) ])): def as_stderr_lines(self): return ["%s: %s" % (line.program_name, line.message) for line in self.logs if is_right_for_level(line.verbose, line.level)] def with_tag(self, log_tag, # type: LogTag ): # type: (...) -> List[str] return ["%s" % line.message for line in self.logs if log_tag == line.tag ]
712
Python
.py
19
28.684211
64
0.58952
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,767
test_put.py
andreafrancia_trash-cli/tests/test_put/cmd/test_put.py
import os from typing import List from typing import Optional import flexmock from six import StringIO from tests.support.fakes.fake_is_mount import FakeIsMount from tests.support.put.dummy_clock import FixedClock from tests.support.put.dummy_clock import jan_1st_2024 from tests.support.put.fake_fs.failing_fake_fs import FailingFakeFs from tests.support.put.fake_random import FakeRandomInt from tests.test_put.support.recording_backend import RecordingBackend from tests.test_put.support.result import Result from trashcli.fstab.volume_of_impl import VolumeOfImpl from trashcli.lib.environ import Environ from trashcli.lib.exit_codes import EX_IOERR from trashcli.lib.exit_codes import EX_OK from trashcli.lib.my_input import HardCodedInput from trashcli.put.core.logs import LogTag from trashcli.put.main import make_cmd from trashcli.put.parser import ensure_int class TestPut: def setup_method(self): self.fs = FailingFakeFs() self.user_input = HardCodedInput('y') self.randint = FakeRandomInt([]) def add_mount(self, path): self.fs.add_volume(path) def test_when_needs_a_different_suffix(self): self.fs.touch("/foo") self.fs.fail_atomic_create_unless("foo_1.trashinfo") self.run_cmd(['trash-put', '/foo']) assert self.fs.ls_aa('/.Trash-123/files') == ['foo_1'] def test_when_needs_a_random_suffix(self): self.fs.touch("/foo") self.fs.fail_atomic_create_unless("foo_123.trashinfo") self.randint.set_reply(123) self.run_cmd(['trash-put', '/foo']) assert self.fs.ls_aa('/.Trash-123/files') == ['foo_123'] def test_when_a_trashinfo_file_already_exists(self): def touch_and_trash(path): self.fs.touch(path) self.run_cmd(['trash-put', path]) touch_and_trash("/foo") touch_and_trash("/foo") touch_and_trash("/foo") assert self.fs.ls_aa('/.Trash-123/info') == [ 'foo.trashinfo', 'foo_1.trashinfo', 'foo_2.trashinfo' ] def test_when_moving_file_in_trash_dir_fails(self): self.fs.touch("foo") self.fs.fail_move_on("/foo") result = self.run_cmd(['trash-put', '-v', '/foo']) assert result.exit_code_and_stderr() == [EX_IOERR, [ "trash-put: cannot trash regular empty file '/foo' (from volume '/')", 'trash-put: `- failed to trash /foo in /.Trash/123, because trash dir cannot be created because its parent does not exists, trash-dir: /.Trash/123, parent: /.Trash', 'trash-put: `- failed to trash /foo in /.Trash-123, because failed to move /foo in /.Trash-123/files: move failed']] def test_should_not_trash_dot_entry(self): result = self.run_cmd(['trash-put', '.']) assert result.exit_code_and_stderr() == [ EX_IOERR, ["trash-put: cannot trash directory '.'"]] def test_should_not_trash_dot_dot_entry(self): result = self.run_cmd(['trash-put', '..']) assert result.exit_code_and_stderr() == [ EX_IOERR, ["trash-put: cannot trash directory '..'"]] def test_user_reply_no(self): self.fs.touch("foo") self.user_input.set_reply('n') result = self.run_cmd(['trash-put', '-i', 'foo']) assert result.exit_code_and_stderr() + [self.user_input.last_prompt(), self.fs.ls_existing( ["foo"])] == [ EX_OK, [], "trash-put: trash regular empty file 'foo'? ", ['foo'], ] def test_user_reply_yes(self): self.fs.touch("foo") self.user_input.set_reply('y') result = self.run_cmd(['trash-put', '-i', 'foo']) assert result.exit_code_and_stderr() + [self.user_input.last_prompt(), self.fs.ls_existing( ["foo"])] == [ EX_OK, [], "trash-put: trash regular empty file 'foo'? ", [] ] def test_when_file_does_not_exist(self): result = self.run_cmd(['trash-put', 'non-existent'], {"HOME": "/home/user"}, 123) assert result.exit_code_and_stderr() == [ EX_IOERR, ["trash-put: cannot trash non existent 'non-existent'"]] def test_when_file_does_not_exist_with_force(self): result = self.run_cmd(['trash-put', '-f', 'non-existent'], {"HOME": "/home/user"}, 123) assert result.exit_code_and_stderr() == [EX_OK, []] def test_put_does_not_try_to_trash_non_existing_file(self): result = self.run_cmd(['trash-put', '-vvv', 'non-existing'], {"HOME": "/home/user"}, 123) assert result.exit_code_and_stderr() == \ [ EX_IOERR, ["trash-put: cannot trash non existent 'non-existing'"] ] def test_when_file_cannot_be_trashed(self): self.fs.touch("foo") self.fs.fail_move_on("foo") result = self.run_cmd(['trash-put', 'foo']) assert (result.exit_code_and_logs(LogTag.trash_failed) == (74, [ "cannot trash regular empty file 'foo' (from volume '/')", ' `- failed to trash foo in /.Trash/123, because trash dir ' 'cannot be created because its parent does not exists, ' 'trash-dir: /.Trash/123, parent: /.Trash', ' `- failed to trash foo in /.Trash-123, because failed to ' 'move foo in /.Trash-123/files: move failed', ])) def test_exit_code_will_be_0_when_trash_succeeds(self): self.fs.touch("pippo") result = self.run_cmd(['trash-put', 'pippo']) assert result.exit_code == EX_OK def test_exit_code_will_be_non_0_when_trash_fails(self): self.fs.assert_does_not_exist("a") result = self.run_cmd(['trash-put', 'a']) assert result.exit_code == EX_IOERR def test_exit_code_will_be_non_0_when_just_one_trash_fails(self): self.fs.touch("a") self.fs.assert_does_not_exist("b") self.fs.touch("c") result = self.run_cmd(['trash-put', 'a', 'b', 'c']) assert result.exit_code == EX_IOERR def test_when_there_is_no_working_trash_dir(self): self.fs.make_file("pippo") self.fs.makedirs('/.Trash-123', 0o000) result = self.run_cmd(['trash-put', '-v', 'pippo'], {}, 123) assert result.exit_code_and_stderr() == [ EX_IOERR, [ "trash-put: cannot trash regular empty file 'pippo' (from volume '/')", 'trash-put: `- failed to trash pippo in /.Trash/123, because trash dir cannot be created because its parent does not exists, trash-dir: /.Trash/123, parent: /.Trash', "trash-put: `- failed to trash pippo in /.Trash-123, because error during directory creation: [Errno 13] Permission denied: '/.Trash-123/files'" ] ] def test_multiple_volumes(self): self.fs.makedirs('/disk1', 0o700) self.fs.makedirs('/disk1/.Trash-123', 0o000) self.fs.make_file("/disk1/pippo") self.add_mount('/disk1') result = self.run_cmd(['trash-put', '-v', '--home-fallback', '/disk1/pippo'], {'HOME': '/home/user'}, 123) assert result.stderr == [ "trash-put: cannot trash regular empty file '/disk1/pippo' (from volume '/disk1')", 'trash-put: `- failed to trash /disk1/pippo in /home/user/.local/share/Trash, because trash dir and file to be trashed are not in the same volume, trash-dir volume: /, file volume: /disk1', 'trash-put: `- failed to trash /disk1/pippo in /disk1/.Trash/123, because trash dir cannot be created because its parent does not exists, trash-dir: /disk1/.Trash/123, parent: /disk1/.Trash', "trash-put: `- failed to trash /disk1/pippo in /disk1/.Trash-123, because error during directory creation: [Errno 13] Permission denied: '/disk1/.Trash-123/files'", 'trash-put: `- failed to trash /disk1/pippo in /home/user/.local/share/Trash, because home fallback not enabled'] def test_when_it_fails_to_prepare_trash_info_data(self): flexmock.flexmock(self.fs).should_receive('parent_realpath2'). \ and_raise(IOError, 'Corruption') self.fs.make_file("foo") result = self.run_cmd(['trash-put', '-v', 'foo'], {"HOME": "/home/user"}, 123) assert result.exit_code_and_stderr() == [ EX_IOERR, [ "trash-put: cannot trash regular empty file 'foo' (from volume '/')", 'trash-put: `- failed to trash foo in /home/user/.local/share/Trash, because failed to generate trashinfo content: Corruption', 'trash-put: `- failed to trash foo in /.Trash/123, because trash dir cannot be created because its parent does not exists, trash-dir: /.Trash/123, parent: /.Trash', 'trash-put: `- failed to trash foo in /.Trash-123, because failed to generate trashinfo content: Corruption']] def test_make_file(self): self.fs.make_file("pippo", 'content') assert True == self.fs.exists("pippo") def test_when_file_exists(self): self.fs.make_file("pippo", 'content') result = self.run_cmd(['trash-put', 'pippo'], {"HOME": "/home/user"}, 123) actual = { 'file_pippo_exists': self.fs.exists("pippo"), 'exit_code': result.exit_code, 'files_in_info_dir': self.fs.ls_aa( '/home/user/.local/share/Trash/info'), "content_of_trashinfo": self.fs.read( '/home/user/.local/share/Trash/info/pippo.trashinfo' ).decode('utf-8'), 'files_in_files_dir': self.fs.ls_aa( '/home/user/.local/share/Trash/files'), "content_of_trashed_file": self.fs.read( '/home/user/.local/share/Trash/files/pippo'), } assert actual == {'content_of_trashed_file': 'content', 'content_of_trashinfo': '[Trash Info]\nPath=/pippo\nDeletionDate=2014-01-01T00:00:00\n', 'exit_code': 0, 'file_pippo_exists': False, 'files_in_files_dir': ['pippo'], 'files_in_info_dir': ['pippo.trashinfo']} def test_when_file_move_fails(self): flexmock.flexmock(self.fs).should_receive('move'). \ and_raise(IOError, 'No space left on device') self.fs.make_file("pippo", 'content') result = self.run_cmd(['trash-put', 'pippo'], {"HOME": "/home/user"}, 123) actual = { 'file_pippo_exists': self.fs.exists("pippo"), 'exit_code': result.exit_code, 'stderr': result.stderr, 'files_in_info_dir': self.fs.ls_aa( '/home/user/.local/share/Trash/info'), "content_of_trashinfo": self.fs.read_null( '/home/user/.local/share/Trash/info/pippo.trashinfo'), 'files_in_files_dir': self.fs.ls_aa( '/home/user/.local/share/Trash/files'), "content_of_trashed_file": self.fs.read_null( '/home/user/.local/share/Trash/files/pippo'), } assert actual == {'content_of_trashed_file': None, 'content_of_trashinfo': None, 'exit_code': EX_IOERR, 'stderr': [ "trash-put: cannot trash regular file 'pippo' (from volume '/')", 'trash-put: `- failed to trash pippo in /home/user/.local/share/Trash, because failed to move pippo in /home/user/.local/share/Trash/files: No space left on device', 'trash-put: `- failed to trash pippo in /.Trash/123, because trash dir cannot be created because its parent does not exists, trash-dir: /.Trash/123, parent: /.Trash', 'trash-put: `- failed to trash pippo in /.Trash-123, because failed to move pippo in /.Trash-123/files: No space left on device'], 'file_pippo_exists': True, 'files_in_files_dir': [], 'files_in_info_dir': []} def test_when_a_error_during_move(self): self.fs.make_file("pippo", 'content') result = self.run_cmd(['trash-put', 'pippo'], {"HOME": "/home/user"}, 123) assert False == self.fs.exists("pippo") assert EX_OK == result.exit_code assert ['pippo.trashinfo'] == self.fs.ls_aa( '/home/user/.local/share/Trash/info') trash_info = self.fs.read( '/home/user/.local/share/Trash/info/pippo.trashinfo' ).decode('utf-8') assert trash_info == '[Trash Info]\nPath=/pippo\nDeletionDate=2014-01-01T00:00:00\n' assert ['pippo'] == self.fs.ls_aa( '/home/user/.local/share/Trash/files') assert self.fs.read('/home/user/.local/share/Trash/files/pippo') \ == 'content' def run_cmd(self, args, # type: List[str] environ=None, # type: Optional[Environ] uid=None, # type: Optional[int] ): # type: (...) -> Result environ = environ or {} uid = uid or 123 err = None exit_code = None stderr = StringIO() clock = FixedClock(jan_1st_2024()) backend = RecordingBackend(stderr) cmd = make_cmd(clock=clock, fs=self.fs, user_input=self.user_input, randint=self.randint, backend=backend) try: exit_code = cmd.run_put(args, environ, uid) except IOError as e: err = e stderr_lines = stderr.getvalue().splitlines() return Result(stderr_lines, str(err), ensure_int(exit_code), backend.collected())
14,433
Python
.py
268
40.955224
204
0.56156
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,768
test_put_script.py
andreafrancia_trash-cli/tests/test_put/cmd/test_put_script.py
import unittest import pytest from tests.support.run.run_command import run_command @pytest.mark.slow class TestRmScript(unittest.TestCase): def test_trash_put_works(self): result = run_command('.', 'trash-put') assert ("usage: trash-put [OPTION]... FILE..." in result.stderr.splitlines()) def test_trash_put_touch_filesystem(self): result = run_command('.', 'trash-put', ['non-existent']) assert ("trash-put: cannot trash non existent 'non-existent'\n" == result.stderr)
549
Python
.py
13
35.307692
74
0.655367
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,769
test_on_dot_arguments.py
andreafrancia_trash-cli/tests/test_put/cmd/e2e/test_on_dot_arguments.py
import pytest from tests.support.dirs.temp_dir import temp_dir from tests.support.files import mkdir_p from tests.test_put.cmd.e2e.run_trash_put import run_trash_put from trashcli.lib.exit_codes import EX_IOERR temp_dir = temp_dir @pytest.mark.slow class TestWhenFedWithDotArguments: def test_dot_argument_is_skipped(self, temp_dir): result = run_trash_put(temp_dir, ["."]) # the dot directory shouldn't be operated, but a diagnostic message # shall be written on stderr assert result.combined() == [ "trash-put: cannot trash directory '.'\n", EX_IOERR] def test_dot_dot_argument_is_skipped(self, temp_dir): result = run_trash_put(temp_dir, [".."]) # the dot directory shouldn't be operated, but a diagnostic message # shall be written on stderr assert result.combined() == [ "trash-put: cannot trash directory '..'\n", EX_IOERR] def test_dot_argument_is_skipped_even_in_subdirs(self, temp_dir): sandbox = temp_dir / 'sandbox' mkdir_p(sandbox) result = run_trash_put(temp_dir, ["%s/." % sandbox]) # the dot directory shouldn't be operated, but a diagnostic message # shall be written on stderr assert result.combined() + temp_dir.existence_of(sandbox) == [ "trash-put: cannot trash '.' directory '/sandbox/.'\n", EX_IOERR, "/sandbox: exists"] def test_dot_dot_argument_is_skipped_even_in_subdirs(self, temp_dir): sandbox = temp_dir / 'sandbox' mkdir_p(sandbox) result = run_trash_put(temp_dir, ["%s/.." % sandbox]) # the dot directory shouldn't be operated, but a diagnostic message # shall be written on stderr assert result.combined() + temp_dir.existence_of(sandbox) == [ "trash-put: cannot trash '..' directory '/sandbox/..'\n", EX_IOERR, "/sandbox: exists"]
1,925
Python
.py
38
42.763158
75
0.648158
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,770
test_on_links_to_dirs.py
andreafrancia_trash-cli/tests/test_put/cmd/e2e/test_on_links_to_dirs.py
import pytest from tests.support.dirs.temp_dir import temp_dir from tests.test_put.cmd.e2e.run_trash_put.directory_layout import \ DirectoriesLayout from trashcli.put.fs.real_fs import RealFs temp_dir = temp_dir @pytest.mark.slow class TestOnLinksToDirs: def test_link_to_dir_without_slashes(self, temp_dir): layout = DirectoriesLayout(temp_dir, RealFs()) layout.make_cur_dir() layout.mkdir_in_cur_dir('a-dir') layout.touch_in_cur_dir('a-file') layout.symlink_in_cur_dir('a-dir', 'link-to-dir') result = layout.run_trash_put(['link-to-dir']) assert result.status() == { 'command output': "trash-put: 'link-to-dir' trashed in /trash-dir", 'file left in current_dir': ['/a-dir', '/a-file'], 'file in trash dir': ['/files', '/files/link-to-dir', '/info', '/info/link-to-dir.trashinfo'], } def test_link_to_dir_with_slashes(self, temp_dir): layout = DirectoriesLayout(temp_dir, RealFs()) layout.make_cur_dir() layout.mkdir_in_cur_dir("a-dir") layout.touch_in_cur_dir("a-file") layout.symlink_in_cur_dir('a-dir', 'link-to-dir') result = layout.run_trash_put(['link-to-dir/']) assert result.status() == { 'command output': "trash-put: 'link-to-dir/' trashed in /trash-dir", 'file left in current_dir': ['/a-dir', '/a-file'], 'file in trash dir': ['/files', '/files/link-to-dir', '/info', '/info/link-to-dir.trashinfo'], }
1,741
Python
.py
38
33.631579
80
0.544864
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,771
test_on_symbolic_links.py
andreafrancia_trash-cli/tests/test_put/cmd/e2e/test_on_symbolic_links.py
import os import pytest from tests.support.dirs.temp_dir import temp_dir from tests.support.files import make_file from tests.support.dirs.my_path import MyPath from tests.test_put.cmd.e2e.run_trash_put import run_trash_put from trashcli.put.fs.real_fs import RealFs fs = RealFs() temp_dir = temp_dir def _make_connected_link(path): # type: (MyPath) -> None make_file(path.parent / 'link-target') os.symlink('link-target', path) def _make_dangling_link(path): # type: (MyPath) -> None os.symlink('non-existent', path) @pytest.mark.slow class TestOnSymbolicLinks: def test_trashes_dangling_symlink(self, temp_dir): _make_dangling_link(temp_dir / 'link') output = run_trash_put(temp_dir, ['link'], env={"TRASH_PUT_DISABLE_SHRINK": "1"}) assert output.stderr.lines() == [ "trash-put: 'link' trashed in /trash-dir"] assert not os.path.lexists(temp_dir / 'link') assert os.path.lexists(temp_dir / 'trash-dir' / 'files' / 'link') def test_trashes_connected_symlink(self, temp_dir): _make_connected_link(temp_dir / 'link') output = run_trash_put(temp_dir, ['link'], env={"TRASH_PUT_DISABLE_SHRINK": "1"}) assert output.stderr.lines() == ["trash-put: 'link' trashed in /trash-dir"] assert not os.path.lexists(temp_dir / 'link') assert os.path.lexists(temp_dir / 'trash-dir' / 'files' / 'link')
1,475
Python
.py
31
40.548387
83
0.6471
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,772
test_on_non_existent_file.py
andreafrancia_trash-cli/tests/test_put/cmd/e2e/test_on_non_existent_file.py
import pytest from tests.test_put.cmd.e2e.run_trash_put import run_trash_put from tests.test_put.cmd.e2e.test_end_to_end_put import temp_dir from trashcli.lib.exit_codes import EX_IOERR temp_dir = temp_dir @pytest.mark.slow class TestOnNonExistentFile: def test_fails(self, temp_dir): result = run_trash_put(temp_dir, ['non-existent']) assert (result.combined() == ["trash-put: cannot trash non existent 'non-existent'\n", EX_IOERR])
490
Python
.py
12
35.166667
73
0.694737
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,773
test_on_trashing_a_file.py
andreafrancia_trash-cli/tests/test_put/cmd/e2e/test_on_trashing_a_file.py
import pytest from tests.support.files import make_empty_file from tests.test_put.cmd.e2e.run_trash_put import run_trash_put2 from tests.support.dirs.temp_dir import temp_dir temp_dir = temp_dir @pytest.mark.slow class TestOnTrashingAFile: def test_in_verbose_mode_should_tell_where_a_file_is_trashed(self, temp_dir): env = {'XDG_DATA_HOME': temp_dir / 'XDG_DATA_HOME', 'HOME': temp_dir / 'home'} make_empty_file(temp_dir / "foo") result = run_trash_put2(temp_dir, ["-v", temp_dir / "foo"], env) assert [result.both().cleaned(), result.exit_code] == [ "trash-put: '/foo' trashed in /XDG_DATA_HOME/Trash\n", 0 ]
766
Python
.py
17
34.941176
75
0.591644
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,774
test_on_existing_file.py
andreafrancia_trash-cli/tests/test_put/cmd/e2e/test_on_existing_file.py
# Copyright (C) 2009-2020 Andrea Francia Trivolzio(PV) Italy import pytest from tests.support.dirs.temp_dir import temp_dir from tests.support.files import make_empty_file from tests.test_put.cmd.e2e.run_trash_put import run_trash_put2 temp_dir = temp_dir @pytest.mark.slow class TestOnExistingFile: def test_it_should_be_trashed(self, temp_dir): make_empty_file(temp_dir / 'foo') result = run_trash_put2(temp_dir, [temp_dir / "foo"], self._with_xdg_data_dir(temp_dir)) assert self._status_of_trash(temp_dir) + result.status() == [ '/foo: does not exist', '/XDG_DATA_HOME/Trash/info/foo.trashinfo: exists', '/XDG_DATA_HOME/Trash/files/foo: exists', 'output is empty', 'exit code is 0', ] @staticmethod def _status_of_trash(temp_dir): return temp_dir.existence_of('foo', 'XDG_DATA_HOME/Trash/info/foo.trashinfo', 'XDG_DATA_HOME/Trash/files/foo') @staticmethod def _with_xdg_data_dir(temp_dir): return {'XDG_DATA_HOME': temp_dir / 'XDG_DATA_HOME'}
1,189
Python
.py
27
34.037037
78
0.60451
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,775
test_end_to_end_put.py
andreafrancia_trash-cli/tests/test_put/cmd/e2e/test_end_to_end_put.py
# Copyright (C) 2021 Andrea Francia Bereguardo(PV) Italy from textwrap import dedent import pytest from tests.support.dirs.my_path import MyPath from tests.support.dirs.temp_dir import temp_dir from tests.test_put.cmd.e2e.run_trash_put import run_trash_put from trashcli.lib.exit_codes import EX_IOERR temp_dir = temp_dir @pytest.mark.slow class TestEndToEndPut: def setup_method(self): self.tmp_dir = MyPath.make_temp_dir() def test_last_line_of_help(self, temp_dir): result = run_trash_put(temp_dir, ['--help']) assert result.stdout.last_line() == \ 'Report bugs to https://github.com/andreafrancia/trash-cli/issues' def test_without_args(self, temp_dir): result = run_trash_put(temp_dir, []) assert ([result.stderr.first_line(), result.exit_code] == ['usage: trash-put [OPTION]... FILE...', 2]) def test_wrong_option(self, temp_dir): result = run_trash_put(temp_dir, ['--wrong-option']) assert [result.stderr.last_line(), result.exit_code] == \ ['trash-put: error: unrecognized arguments: --wrong-option', 2] def test_on_help(self, temp_dir): result = run_trash_put(temp_dir, ['--help']) assert [result.help_message(), result.exit_code] == \ [dedent('''\ usage: trash-put [OPTION]... FILE... Put files in trash positional arguments: files options: -h, --help show this help message and exit --print-completion {bash,zsh,tcsh} print shell completion script -d, --directory ignored (for GNU rm compatibility) -f, --force silently ignore nonexistent files -i, --interactive prompt before every removal -r, -R, --recursive ignored (for GNU rm compatibility) --trash-dir TRASHDIR use TRASHDIR as trash folder -v, --verbose explain what is being done --version show program's version number and exit all trash-cli commands: trash-put trash files and directories. trash-empty empty the trashcan(s). trash-list list trashed files. trash-restore restore a trashed file. trash-rm remove individual files from the trashcan To remove a file whose name starts with a '-', for example '-foo', use one of these commands: trash -- -foo trash ./-foo Report bugs to https://github.com/andreafrancia/trash-cli/issues '''), 0] def test_it_should_skip_dot_entry(self, temp_dir): result = run_trash_put(temp_dir, ['.']) assert result.combined() == \ ["trash-put: cannot trash directory '.'\n", EX_IOERR] def test_it_should_skip_dotdot_entry(self, temp_dir): result = run_trash_put(temp_dir, ['..']) assert result.combined() == \ ["trash-put: cannot trash directory '..'\n", EX_IOERR] def test_it_should_print_usage_on_no_argument(self, temp_dir): result = run_trash_put(temp_dir, []) assert result.combined() == \ ['usage: trash-put [OPTION]... FILE...\n' 'trash-put: error: Please specify the files to trash.\n', 2] def test_it_should_skip_missing_files(self, temp_dir): result = run_trash_put(temp_dir, ['-f', 'this_file_does_not_exist', 'nor_does_this_file']) assert result.combined() == ['', 0]
3,897
Python
.py
75
38.84
82
0.549842
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,776
test_unsecure_trash_dir_messages.py
andreafrancia_trash-cli/tests/test_put/cmd/e2e/test_unsecure_trash_dir_messages.py
# Copyright (C) 2009-2020 Andrea Francia Trivolzio(PV) Italy import os import pytest from tests.support.files import make_empty_file from tests.support.files import make_sticky_dir from tests.support.files import require_empty_dir from tests.test_put.cmd.e2e.run_trash_put import run_trashput_with_vol from tests.support.dirs.temp_dir import temp_dir temp_dir = temp_dir @pytest.mark.slow class TestUnsecureTrashDirMessages: @pytest.fixture def fake_vol(self, temp_dir): return temp_dir / 'fake-vol' def test_when_is_unsticky(self, temp_dir, fake_vol): require_empty_dir(fake_vol) make_empty_file(fake_vol / 'foo') require_empty_dir(fake_vol / '.Trash') output = run_trashput_with_vol(temp_dir, fake_vol, [fake_vol / 'foo']) assert output.grep("/.Trash/123").stream == ( 'trash-put: `- failed to trash /vol/foo in /vol/.Trash/123, because trash ' 'dir is insecure, its parent should be sticky, trash-dir: /vol/.Trash/123, ' 'parent: /vol/.Trash\n' ) def test_when_it_is_not_a_dir(self, fake_vol, temp_dir): require_empty_dir(fake_vol) make_empty_file(fake_vol / 'foo') make_empty_file(fake_vol / '.Trash') output = run_trashput_with_vol(temp_dir, fake_vol, [fake_vol / 'foo']) assert output.grep("/.Trash/123").stream == ( 'trash-put: `- failed to trash /vol/foo in /vol/.Trash/123, because trash ' 'dir cannot be created as its parent is a file instead of being a directory, ' 'trash-dir: /vol/.Trash/123, parent: /vol/.Trash\n' ) def test_when_is_a_symlink(self, fake_vol, temp_dir): require_empty_dir(fake_vol) make_empty_file(fake_vol / 'foo') make_sticky_dir(fake_vol / 'link-destination') os.symlink('link-destination', fake_vol / '.Trash') output = run_trashput_with_vol(temp_dir, fake_vol, [fake_vol / 'foo']) assert output.grep("insecure").stream == ( 'trash-put: `- failed to trash /vol/foo in /vol/.Trash/123, because ' 'trash dir is insecure, its parent should not be a symlink, trash-dir: ' '/vol/.Trash/123, parent: /vol/.Trash\n')
2,244
Python
.py
44
43.295455
90
0.643478
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,777
put_result.py
andreafrancia_trash-cli/tests/test_put/cmd/e2e/run_trash_put/put_result.py
from typing import NamedTuple from tests.support.run.cmd_result import CmdResult from tests.support.help.help_reformatting import reformat_help_message from tests.support.dirs.my_path import MyPath from tests.test_put.cmd.e2e.run_trash_put.stream import Stream class PutResult(NamedTuple('Output', [ ('stderr', Stream), ('stdout', Stream), ('exit_code', int), ('temp_dir', MyPath), ])): def help_message(self): return reformat_help_message(self.stdout.stream) def combined(self): return [self.stderr.cleaned() + self.stdout.cleaned(), self.exit_code] def status(self): return ["output is %s" % self.both().describe_stream(), "exit code is %s" % self.exit_code] def both(self): return Stream(stream=self.stderr.stream + self.stdout.stream, temp_dir=self.temp_dir) def make_put_result(result, # type: CmdResult temp_dir, # type: MyPath ): # type: (...) -> PutResult return PutResult(stdout=Stream(stream=result.stdout, temp_dir=temp_dir), stderr=Stream(stream=result.stderr, temp_dir=temp_dir), exit_code=result.exit_code, temp_dir=temp_dir)
1,291
Python
.py
30
33.766667
76
0.621212
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,778
stream.py
andreafrancia_trash-cli/tests/test_put/cmd/e2e/run_trash_put/stream.py
from typing import NamedTuple from tests.support.text.grep import grep from tests.support.dirs.my_path import MyPath class Stream(NamedTuple('Output', [ ('stream', str), ('temp_dir', MyPath) ])): def lines(self): return self.stream.replace(self.temp_dir, '').splitlines() def last_line(self): return self.lines()[-1] def first_line(self): return self.lines()[0] def cleaned(self): return self.stream.replace(self.temp_dir, '') def describe_stream(self): # type: () -> str if len(self.stream) == 0: return "empty" else: return repr(self.stream) def grep(self, pattern): return Stream(stream=grep(self.stream, pattern), temp_dir=self.temp_dir) def replace(self, old, new): return Stream(stream=self.stream.replace(old, new), temp_dir=self.temp_dir)
925
Python
.py
26
27.769231
66
0.614607
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,779
directory_layout.py
andreafrancia_trash-cli/tests/test_put/cmd/e2e/run_trash_put/directory_layout.py
from tests.test_put.cmd.e2e.run_trash_put import PutResult from tests.test_put.cmd.e2e.run_trash_put import run_trash_put4 class Result: def __init__(self, layout, # type: DirectoriesLayout output, # type: PutResult ): self.output = output self.layout = layout def status(self): return { 'command output': "\n".join(self.output.stderr.lines()), 'file left in current_dir': self.layout.cur_dir.list_all_files_sorted(), 'file in trash dir': self.layout.trash_dir.list_all_files_sorted(), } class DirectoriesLayout: def __init__(self, root_dir, fs): self.root_dir = root_dir self.fs = fs @property def cur_dir(self): return self.root_dir / 'cur-dir' @property def trash_dir(self): return self.root_dir / 'trash-dir' def make_cur_dir(self): self.fs.mkdir(self.cur_dir) def run_trash_put(self, args, # type: list[str] ): # type: (...) -> Result output = run_trash_put4(self.root_dir, self.cur_dir, self.trash_dir, args, env={}) return Result(self, output) def mkdir_in_cur_dir(self, relative_path): self.fs.mkdir(self.cur_dir / relative_path) def touch_in_cur_dir(self, relative_path): self.fs.touch(self.cur_dir / "a-file") def symlink_in_cur_dir(self, src, dest): self.fs.symlink(self.cur_dir / src, self.cur_dir / dest)
1,589
Python
.py
40
29.55
84
0.56864
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,780
__init__.py
andreafrancia_trash-cli/tests/test_put/cmd/e2e/run_trash_put/__init__.py
from typing import List from typing import Optional from tests.support.run.run_command import run_command from tests.support.dirs.my_path import MyPath from tests.test_put.cmd.e2e.run_trash_put.put_result import PutResult from tests.test_put.cmd.e2e.run_trash_put.put_result import make_put_result from tests.test_put.cmd.e2e.run_trash_put.stream import Stream from trashcli.lib.environ import Environ def run_trash_put(tmp_dir, # type: MyPath args, # type: List[str] env=None, # type: Optional[Environ] ): # type: (...) -> PutResult env = env or {} root_dir = tmp_dir cur_dir = tmp_dir trash_dir = tmp_dir / 'trash-dir' return run_trash_put4(root_dir, cur_dir, trash_dir, args, env) def run_trash_put3(cur_dir, # type: MyPath trash_dir, # type: MyPath args, # type: List[str] ): # type: (...) -> PutResult return run_trash_put4(cur_dir, cur_dir, trash_dir, args, env={}) def run_trash_put4(root_dir, # type: MyPath cur_dir, # type: MyPath trash_dir, # type: MyPath args, # type: List[str] env, # type: Environ ): # type: (...) -> PutResult extra_args = [ '-v', '--trash-dir', trash_dir, ] args = extra_args + args return run_trash_put23(root_dir, cur_dir, args, env) def run_trashput_with_vol(temp_dir, # type: MyPath fake_vol, # type: MyPath args, # type: List[str] ): # type: (...) -> Stream result = run_trash_put2(temp_dir, ["--force-volume=%s" % fake_vol, '-v'] + args, env=with_uid(123)) output = result.both().replace(fake_vol, "/vol") return output def run_trash_put2(cur_dir, # type: MyPath args, # type: List[str] env, # type: Environ ): # type: (...) -> PutResult return run_trash_put23(cur_dir, cur_dir, args, env) def run_trash_put23(root_dir, # type: MyPath cur_dir, # type: MyPath args, # type: List[str] env, # type: Environ ): # type: (...) -> PutResult result = run_command(cur_dir, 'trash-put', args, env=env) return make_put_result(result, root_dir) def with_uid(uid): return {'TRASH_PUT_FAKE_UID_FOR_TESTING': str(uid)}
2,654
Python
.py
61
31.278689
75
0.52
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,781
test_describer_integration.py
andreafrancia_trash-cli/tests/test_put/components/test_describer_integration.py
# Copyright (C) 2011-2022 Andrea Francia Bereguardo(PV) Italy import os import unittest import pytest from tests.support.files import make_empty_file, make_file, require_empty_dir from tests.support.dirs.my_path import MyPath from trashcli.put.describer import Describer from trashcli.put.fs.real_fs import RealFs @pytest.mark.slow class TestDescriber(unittest.TestCase): def setUp(self): self.temp_dir = MyPath.make_temp_dir() self.describer = Describer(RealFs()) def test_on_directories(self): require_empty_dir(self.temp_dir / 'a-dir') assert "directory" == self.describer.describe('.') assert "directory" == self.describer.describe("..") assert "directory" == self.describer.describe(self.temp_dir / 'a-dir') def test_on_dot_directories(self): require_empty_dir(self.temp_dir / 'a-dir') assert "'.' directory" == self.describer.describe( self.temp_dir / "a-dir/.") assert "'.' directory" == self.describer.describe("./.") def test_on_dot_dot_directories(self): require_empty_dir(self.temp_dir / 'a-dir') assert "'..' directory" == self.describer.describe("./..") assert "'..' directory" == self.describer.describe(self.temp_dir / "a-dir/..") def test_name_for_regular_files_non_empty_files(self): make_file(self.temp_dir / "non-empty", "contents") assert "regular file" == self.describer.describe(self.temp_dir / "non-empty") def test_name_for_empty_file(self): make_empty_file(self.temp_dir / 'empty') assert "regular empty file" == self.describer.describe(self.temp_dir / "empty") def test_name_for_symbolic_links(self): os.symlink('nowhere', self.temp_dir / "symlink") assert "symbolic link" == self.describer.describe(self.temp_dir / "symlink") def test_name_for_non_existent_entries(self): assert not os.path.exists(self.temp_dir / 'non-existent') assert "non existent" == self.describer.describe(self.temp_dir / 'non-existent') def tearDown(self): self.temp_dir.clean_up()
2,118
Python
.py
41
44.926829
88
0.672983
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,782
test_move_file.py
andreafrancia_trash-cli/tests/test_put/components/test_move_file.py
import pytest from tests.support.dirs.my_path import MyPath from trashcli.put.fs.real_fs import RealFs from trashcli.put.janitor_tools.put_trash_dir import move_file from tests.support.dirs.temp_dir import temp_dir temp_dir = temp_dir class TestMoveFile: @pytest.mark.slow def test_delete_when_traling_slash(self, temp_dir): # type: (MyPath) -> None fs = RealFs() temp_dir.mkdir_rel("dir") temp_dir.symlink_rel("dir", "link-to-dir") move_file(fs, temp_dir / "link-to-dir/", temp_dir / "trash-location") assert temp_dir.list_all_files_sorted() == ['/dir', '/trash-location']
668
Python
.py
15
37.333333
78
0.655332
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,783
test_user.py
andreafrancia_trash-cli/tests/test_put/components/test_user.py
import unittest from typing import cast import flexmock from trashcli.lib.my_input import HardCodedInput from trashcli.put.describer import Describer from trashcli.put.user import ( User, parse_user_reply, user_replied_no, user_replied_yes, ) class TestUser(unittest.TestCase): def setUp(self): self.my_input = HardCodedInput("y") self.describer = flexmock.Mock(spec=Describer) self.describer.should_receive('describe').and_return("description!") self.user = User(self.my_input, cast(Describer, self.describer)) def test_yes(self): result = self.user.ask_user_about_deleting_file('prg', "file") assert result == 'user_replied_yes' class Test_parse_user_reply(unittest.TestCase): def test_y(self): assert parse_user_reply('y') == user_replied_yes def test_Y(self): assert parse_user_reply('Y') == user_replied_yes def test_n(self): assert parse_user_reply('n') == user_replied_no def test_N(self): assert parse_user_reply('N') == user_replied_no def test_other(self): assert parse_user_reply('other') == user_replied_no
1,120
Python
.py
26
38.192308
77
0.710599
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,784
test_trash_directories_finder.py
andreafrancia_trash-cli/tests/test_put/components/test_trash_directories_finder.py
import unittest from tests.support.py2mock import Mock from trashcli.put.core.candidate import Candidate from trashcli.put.core.check_type import NoCheck, TopTrashDirCheck from trashcli.put.core.path_maker_type import PathMakerType from trashcli.put.gate import Gate from trashcli.put.trash_directories_finder import TrashDirectoriesFinder class TestTrashDirectoriesFinder(unittest.TestCase): def setUp(self): volumes = Mock(spec=[]) volumes.volume_of = lambda x: 'volume_of(%s)' % x self.environ = {'HOME': "~"} self.finder = TrashDirectoriesFinder(volumes) def test_no_specific_user_dir(self): result = self.finder.possible_trash_directories_for('/volume', None, self.environ, 123, True) assert result == [ Candidate(trash_dir_path='~/.local/share/Trash', volume='volume_of(~/.local/share/Trash)', path_maker_type=PathMakerType.AbsolutePaths, check_type=NoCheck, gate=Gate.SameVolume), Candidate(trash_dir_path='/volume/.Trash/123', volume='/volume', path_maker_type=PathMakerType.RelativePaths, check_type=TopTrashDirCheck, gate=Gate.SameVolume), Candidate(trash_dir_path='/volume/.Trash-123', volume='/volume', path_maker_type=PathMakerType.RelativePaths, check_type=NoCheck, gate=Gate.SameVolume), Candidate(trash_dir_path='~/.local/share/Trash', volume='volume_of(~/.local/share/Trash)', path_maker_type=PathMakerType.AbsolutePaths, check_type=NoCheck, gate=Gate.HomeFallback), ] def test_specific_user_dir(self): result = self.finder.possible_trash_directories_for('/volume', 'user_dir', self.environ, 123, True) assert result == [('user_dir', 'volume_of(user_dir)', PathMakerType.RelativePaths, NoCheck, Gate.SameVolume)]
2,458
Python
.py
44
36.045455
78
0.528263
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,785
test_make_parser.py
andreafrancia_trash-cli/tests/test_put/components/test_make_parser.py
import unittest from trashcli.put.core.mode import Mode from trashcli.put.parser import make_parser class Test_make_parser(unittest.TestCase): def setUp(self): self.parser = make_parser("program-name") def test(self): options = self.parser.parse_args([]) assert options.verbose == 0 def test2(self): options = self.parser.parse_args(['-v']) assert options.verbose == 1 def test3(self): options = self.parser.parse_args(['-vv']) assert options.verbose == 2 def test_trash_dir_not_specified(self): options = self.parser.parse_args([]) assert options.trashdir is None def test_trash_dir_specified(self): options = self.parser.parse_args(['--trash-dir', '/MyTrash']) assert options.trashdir == '/MyTrash' def test_force_volume_off(self): options = self.parser.parse_args([]) assert options.forced_volume is None def test_force_volume_on(self): options = self.parser.parse_args(['--force-volume', '/fake-vol']) assert options.forced_volume == '/fake-vol' def test_force_option_default(self): options = self.parser.parse_args([]) assert options.mode == Mode.mode_unspecified def test_force_option(self): options = self.parser.parse_args(['-f']) assert options.mode == Mode.mode_force def test_interactive_override_force_option(self): options = self.parser.parse_args(['-f', '-i']) assert options.mode == Mode.mode_interactive def test_interactive_option(self): options = self.parser.parse_args(['-i']) assert options.mode == Mode.mode_interactive
1,698
Python
.py
39
35.948718
73
0.654835
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,786
test_original_location.py
andreafrancia_trash-cli/tests/test_put/components/test_original_location.py
import os import unittest from parameterized import parameterized # type: ignore from tests.support.put.fake_fs.fake_fs import FakeFs from trashcli.put.core.path_maker_type import PathMakerType from trashcli.put.original_location import OriginalLocation AbsolutePaths = PathMakerType.AbsolutePaths RelativePaths = PathMakerType.RelativePaths class TestOriginalLocation(unittest.TestCase): def setUp(self): self.original_location = OriginalLocation(FakeFsWithRealpath()) @parameterized.expand([ ('/volume', '/file', AbsolutePaths, '/file',), ('/volume', '/file/././', AbsolutePaths, '/file',), ('/volume', '/dir/../file', AbsolutePaths, '/file'), ('/volume', '/dir/../././file', AbsolutePaths, '/file'), ('/volume', '/outside/file', AbsolutePaths, '/outside/file'), ('/volume', '/volume/file', AbsolutePaths, '/volume/file',), ('/volume', '/volume/dir/file', AbsolutePaths, '/volume/dir/file'), ('/volume', '/file', RelativePaths, '/file'), ('/volume', '/dir/../file', RelativePaths, '/file'), ('/volume', '/outside/file', RelativePaths, '/outside/file'), ('/volume', '/volume/file', RelativePaths, 'file'), ('/volume', '/volume/dir/file', RelativePaths, 'dir/file'), ]) def test_original_location(self, volume, file_to_be_trashed, path_type, expected_result): result = self.original_location.for_file(file_to_be_trashed, path_type, volume) assert expected_result == result class FakeFsWithRealpath(FakeFs): def parent_realpath2(self, path): return os.path.dirname(path)
1,708
Python
.py
33
43.575758
79
0.638655
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,787
test_octal.py
andreafrancia_trash-cli/tests/test_put/components/test_octal.py
from trashcli.put.octal import octal class TestOctal: def test(self): assert octal(16877) == '0o40755'
116
Python
.py
4
24.75
40
0.711712
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,788
test_stat_mode.py
andreafrancia_trash-cli/tests/test_put/components/test_stat_mode.py
import os from trashcli.put.fs.real_fs import RealFs from trashcli.put.octal import octal from tests.support.dirs.temp_dir import temp_dir temp_dir = temp_dir class TestStatMode: def setup_method(self): self.fs = RealFs() self.old_umask = os.umask(0o777 - 0o755) def teardown_method(self): os.umask(self.old_umask) def test_mode_for_a_dir(self, temp_dir): self.fs.mkdir_with_mode(temp_dir / 'foo', 0o755) stat = self.fs.lstat(temp_dir / 'foo') assert octal(stat.mode) == '0o40755' def test_mode_for_a_file(self, temp_dir): self.fs.touch(temp_dir / 'foo') stat = self.fs.lstat(temp_dir / 'foo') assert octal(stat.mode) == '0o100644' def test_mode_for_a_symlink(self, temp_dir): os.umask(0o777 - 0o777) self.fs.symlink(temp_dir / 'foo', temp_dir / 'bar') stat = self.fs.lstat(temp_dir / 'bar') assert octal(stat.mode) == '0o120777'
961
Python
.py
24
33.583333
59
0.64086
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,789
test_gentle_stat_read.py
andreafrancia_trash-cli/tests/test_put/components/test_gentle_stat_read.py
import grp import os import pwd from tests.support.files import make_file from trashcli.put.reporting.stats_reader import gentle_stat_read from tests.support.dirs.temp_dir import temp_dir temp_dir = temp_dir class TestGentleStatRead: def test_file_non_found(self, temp_dir): result = gentle_stat_read(temp_dir / 'not-existent') assert (result.replace(temp_dir, '...') == "[Errno 2] No such file or directory: '.../not-existent'") def test_file(self, temp_dir): make_file(temp_dir / 'pippo.txt') os.chmod(temp_dir / 'pippo.txt', 0o531) result = gentle_stat_read(temp_dir / 'pippo.txt') assert result == '531 %s %s' % ( self.current_user(), self.current_group() ) @staticmethod def current_user(): return pwd.getpwuid(os.getuid()).pw_name @staticmethod def current_group(): return grp.getgrgid(os.getgid()).gr_name
947
Python
.py
25
31.52
74
0.652412
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,790
test_suffix.py
andreafrancia_trash-cli/tests/test_put/components/test_suffix.py
from trashcli.put.core.int_generator import IntGenerator from trashcli.put.suffix import Suffix class TestSuffix: def setup_method(self): self.suffix = Suffix(InlineFakeIntGen(lambda x, y: "%s,%s" % (x, y))) def test_first_attempt(self): assert self.suffix.suffix_for_index(0) == '' def test_second_attempt(self): assert self.suffix.suffix_for_index(1) == '_1' def test_hundredth_attempt(self): assert self.suffix.suffix_for_index(100) == '_0,65535' class InlineFakeIntGen(IntGenerator): def __init__(self, func): self.func = func def new_int(self, a, b): return self.func(a, b)
659
Python
.py
16
35.1875
77
0.670866
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,791
test_parent_path.py
andreafrancia_trash-cli/tests/test_put/components/test_parent_path.py
import os import unittest import pytest from trashcli.put.fs.parent_realpath import ParentRealpathFs from trashcli.put.fs.real_fs import RealFs from tests.support.files import make_empty_file, require_empty_dir from tests.support.dirs.my_path import MyPath def parent_path(path): return ParentRealpathFs(RealFs()).parent_realpath(path) @pytest.mark.slow class Test_parent_path(unittest.TestCase): def setUp(self): self.tmp_dir = MyPath.make_temp_dir() def test(self): require_empty_dir(self.tmp_dir / 'other_dir/dir') os.symlink(self.tmp_dir / 'other_dir/dir', self.tmp_dir / 'dir') make_empty_file(self.tmp_dir / 'dir/foo') assert (self.tmp_dir / 'other_dir/dir' == parent_path( self.tmp_dir / 'dir/foo')) def test2(self): require_empty_dir(self.tmp_dir / 'test-disk/dir') os.symlink(self.tmp_dir / 'test-disk/non-existent', self.tmp_dir / 'link-to-non-existent') assert parent_path(self.tmp_dir / 'link-to-non-existent') == \ self.tmp_dir def test3(self): require_empty_dir(self.tmp_dir / 'foo') require_empty_dir(self.tmp_dir / 'bar') os.symlink('../bar/zap', self.tmp_dir / 'foo/zap') assert parent_path(self.tmp_dir / 'foo/zap') == \ os.path.join(self.tmp_dir, 'foo') def test4(self): require_empty_dir(self.tmp_dir / 'foo') require_empty_dir(self.tmp_dir / 'bar') os.symlink('../bar/zap', self.tmp_dir / 'foo/zap') make_empty_file(self.tmp_dir / 'bar/zap') assert parent_path(self.tmp_dir / 'foo/zap') == \ os.path.join(self.tmp_dir, 'foo') def tearDown(self): self.tmp_dir.clean_up()
1,750
Python
.py
40
36.275
72
0.631548
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,792
test_gate.py
andreafrancia_trash-cli/tests/test_put/components/test_gate.py
from trashcli.put.gate import Gate class TestGate: def test_gate(self): assert repr(Gate.SameVolume) == 'Gate.SameVolume' assert str(Gate.SameVolume) == 'Gate.SameVolume' assert repr(Gate.HomeFallback) == 'Gate.HomeFallback' assert str(Gate.HomeFallback) == 'Gate.HomeFallback'
316
Python
.py
7
38.714286
61
0.700326
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,793
test_ensure_dir.py
andreafrancia_trash-cli/tests/test_put/components/test_ensure_dir.py
import unittest from tests.support.put.fake_fs.fake_fs import FakeFs from tests.support.put.format_mode import format_mode from trashcli.put.dir_maker import DirMaker class TestEnsureDir(unittest.TestCase): def setUp(self): self.fs = FakeFs('/') self.dir_maker = DirMaker(self.fs) def test_happy_path(self): self.dir_maker.mkdir_p('/foo', 0o755) assert [self.fs.isdir('/foo'), format_mode(self.fs.get_mod('/foo'))] == [True, '0o755'] def test_makedirs_honor_permissions(self): self.fs.makedirs('/foo', 0o000) assert [format_mode(self.fs.get_mod('/foo'))] == ['0o000'] def test_bug_when_no_permissions_it_overrides_the_permissions(self): self.fs.makedirs('/foo', 0o000) self.dir_maker.mkdir_p('/foo', 0o755) assert [self.fs.isdir('/foo'), format_mode(self.fs.get_mod('/foo'))] == [True, '0o000']
924
Python
.py
20
38.75
72
0.641341
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,794
test_trash_dir_volume.py
andreafrancia_trash-cli/tests/test_put/components/test_trash_dir_volume.py
import unittest from tests.support.fakes.fake_volume_of import FakeVolumeOf from tests.support.put.fake_fs.fake_fs import FakeFs from trashcli.put.trash_dir_volume_reader import TrashDirVolumeReader class TestTrashDirVolume(unittest.TestCase): def setUp(self): fs = FakeFs() fs.add_volume('/disk1') fs.add_volume('/disk2') self.reader = TrashDirVolumeReader(fs) def test(self): result = self.reader.volume_of_trash_dir('/disk1/trash_dir_path') assert result == '/disk1'
530
Python
.py
13
35.153846
73
0.719298
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,795
test_atomic_write.py
andreafrancia_trash-cli/tests/test_put/components/test_atomic_write.py
import errno import os import unittest import pytest from trashcli.fs import ( atomic_write, open_for_write_in_exclusive_and_create_mode, read_file, ) from tests.support.dirs.my_path import MyPath @pytest.mark.slow class Test_atomic_write(unittest.TestCase): def setUp(self): self.temp_dir = MyPath.make_temp_dir() def test_the_second_open_should_fail(self): path = self.temp_dir / "a" file_handle = open_for_write_in_exclusive_and_create_mode(path) try: open_for_write_in_exclusive_and_create_mode(path) self.fail() except OSError as e: assert e.errno == errno.EEXIST os.close(file_handle) def test_short_filename(self): path = self.temp_dir / 'a' atomic_write(path, b'contents') assert 'contents' == read_file(path) def test_too_long_filename(self): path = self.temp_dir / ('a' * 2000) try: atomic_write(path, b'contents') self.fail() except OSError as e: assert e.errno == errno.ENAMETOOLONG def test_filename_already_taken(self): atomic_write(self.temp_dir / "a", b'contents') try: atomic_write(self.temp_dir / "a", b'contents') self.fail() except OSError as e: assert e.errno == errno.EEXIST def tearDown(self): self.temp_dir.clean_up()
1,427
Python
.py
43
25.55814
71
0.619256
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,796
test_stat_user.py
andreafrancia_trash-cli/tests/test_put/components/test_stat_user.py
import os from trashcli.put.fs.real_fs import RealFs from tests.support.dirs.temp_dir import temp_dir temp_dir = temp_dir class TestStatMode: def setup_method(self): self.fs = RealFs() def test_user(self, temp_dir): self.fs.touch(temp_dir / 'foo') stat = self.fs.lstat(temp_dir / 'foo') assert stat.uid == os.getuid() def test_group(self, temp_dir): self.fs.touch(temp_dir / 'foo') stat = self.fs.lstat(temp_dir / 'foo') assert stat.gid == os.getgid()
526
Python
.py
15
29.133333
48
0.639604
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,797
test_persist_trashinfo.py
andreafrancia_trash-cli/tests/test_put/components/test_persist_trashinfo.py
# Copyright (C) 2008-2021 Andrea Francia Trivolzio(PV) Italy import unittest import pytest from six import StringIO from trashcli.fs import read_file from trashcli.put.fs.real_fs import RealFs from trashcli.put.janitor_tools.info_file_persister import InfoFilePersister from trashcli.put.janitor_tools.info_file_persister import TrashinfoData from trashcli.put.my_logger import LogData from trashcli.put.my_logger import MyLogger from trashcli.put.my_logger import StreamBackend from trashcli.put.suffix import Suffix from tests.support.put.fake_random import FakeRandomInt from tests.support.dirs.my_path import MyPath @pytest.mark.slow class TestPersistTrashInfo(unittest.TestCase): def setUp(self): self.path = MyPath.make_temp_dir() self.fs = RealFs() self.stderr = StringIO() self.backend = StreamBackend(self.stderr) self.logger = MyLogger(self.backend) self.suffix = Suffix(FakeRandomInt([0,1])) self.info_dir = InfoFilePersister(self.fs, self.logger, self.suffix) def test_persist_trash_info_first_time(self): trash_info_file = self._persist_trash_info('dummy-path', b'content') assert self.path / 'dummy-path.trashinfo' == trash_info_file assert 'content' == read_file(trash_info_file) def test_persist_trash_info_first_100_times(self): self.test_persist_trash_info_first_time() trash_info_file = self._persist_trash_info('dummy-path', b'content') assert self.path / 'dummy-path_1.trashinfo' == trash_info_file assert 'content' == read_file(trash_info_file) def tearDown(self): self.path.clean_up() def _persist_trash_info(self, basename, content): log_data = LogData('trash-cli', 2) data = TrashinfoData(basename, content, self.path) return self.info_dir.create_trashinfo_file(data, log_data).trashinfo_path
1,945
Python
.py
40
41.95
81
0.713154
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,798
test_create_trashinfo_basename.py
andreafrancia_trash-cli/tests/test_put/components/test_create_trashinfo_basename.py
from trashcli.put.janitor_tools.info_file_persister import \ create_trashinfo_basename class TestCreateTrashinfoBasename: def test_when_file_name_is_not_too_long(self): assert 'basename_1.trashinfo' == create_trashinfo_basename('basename', '_1', False) def test_when_file_name_too_long(self): assert '12345678_1.trashinfo' == create_trashinfo_basename( '12345678901234567890', '_1', True) def test_when_file_name_too_long_with_big_suffix(self): assert '12345_9999.trashinfo' == create_trashinfo_basename( '12345678901234567890', '_9999', True)
746
Python
.py
13
40.846154
78
0.577503
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)
11,799
test_candidate_shrink_user.py
andreafrancia_trash-cli/tests/test_put/components/test_candidate_shrink_user.py
import unittest from trashcli.put.core.candidate import Candidate class TestCandidateShrinkUser(unittest.TestCase): def setUp(self): self.environ = {} def test_should_substitute_tilde_in_place_of_home_dir(self): self.environ['HOME'] = '/home/user' self.trash_dir = "/home/user/.local/share/Trash" self.assert_name_is('~/.local/share/Trash') def test_should_not_substitute(self): self.environ['HOME'] = '/home/user' self.environ['TRASH_PUT_DISABLE_SHRINK'] = '1' self.trash_dir = "/home/user/.local/share/Trash" self.assert_name_is('/home/user/.local/share/Trash') def test_when_not_in_home_dir(self): self.environ['HOME'] = '/home/user' self.trash_dir = "/not-in-home/Trash" self.assert_name_is('/not-in-home/Trash') def test_tilde_works_also_with_trailing_slash(self): self.environ['HOME'] = '/home/user/' self.trash_dir = "/home/user/.local/share/Trash" self.assert_name_is('~/.local/share/Trash') def test_str_uses_tilde_with_many_slashes(self): self.environ['HOME'] = '/home/user////' self.trash_dir = "/home/user/.local/share/Trash" self.assert_name_is('~/.local/share/Trash') def test_dont_get_confused_by_empty_home_dir(self): self.environ['HOME'] = '' self.trash_dir = "/foo/Trash" self.assert_name_is('/foo/Trash') def test_should_work_even_if_HOME_does_not_exists(self): self.trash_dir = "/foo/Trash" self.assert_name_is('/foo/Trash') def assert_name_is(self, expected_name): self.candidate = Candidate(self.trash_dir, '', '', '', None) shrinked = self.candidate.shrink_user(self.environ) assert expected_name == shrinked
1,779
Python
.py
37
40.405405
68
0.64067
andreafrancia/trash-cli
3,580
179
62
GPL-2.0
9/5/2024, 5:11:26 PM (Europe/Amsterdam)