def test_invalid(self): """ Files cannot escalate above their Base """ with self.assertRaises( rel.RelError, msg="Failed to catch dangerous file escalation!"): rel.SanitizedRelFile(base='C://Users', file_path='t/../../nope.txt') self.assertEqual( '_', rel.SanitizedRelFile(base='C://Users', file_path=' \t\n ../ ./ . \\ ').relative())
def copy_file(self, og_file_path, relative_path): """ Copy the file at the given absolute path into the relative path given, relative to the base_dir. """ rf = rel_file.SanitizedRelFile(base=self.new_save_base, file_path=relative_path) rf.mkdirs() rf.set_ext(og_file_path.split('.')[-1].strip()) print("\t\tRelFile:", rf) shutil.copyfile(og_file_path, rf.absolute()) return rf.relative()
def test_rel(self): """ Paths should be collapsed """ rf = rel.SanitizedRelFile(base="/Users/./", file_path="t/./test/[title].txt") self.assertEqual(norm("/Users/t/test/[title].txt"), rf.absolute(), 'Invalid absolute path!') self.assertEqual('t/test/[title].txt', rf.relative(), 'Invalid relative path!')
def test_sanitize(self): """ Certain special characters should be stripped """ r = rel.SanitizedRelFile( "/Fake\\", './test\\!@#$%^&*()_+-=.../...\\.1234567890abcd...file..') self.assertEqual(r.relative(), 'test/!@#$%^&_()_+-=/1234567890abcd...file', 'The crazy (valid) file failed!')
def test_binary(self): """ Download a binary file """ file = rel.SanitizedRelFile(self.dir, 'test_file') prog = DownloaderProgress() res = http.download_binary(url='https://i.imgur.com/8770jp0.png', rel_file=file, prog=prog, handler_id='test-run') self.assertTrue(res.success, "The test file failed to download!") self.assertTrue(file.exists(), "Failed to download the test binary!") self.assertIn('.png', file.absolute(), "Downloaded invalid filetype!") # Downloaded a PNG. self.assertEqual('100', prog.get_percent(), 'Download did not reach 100%!')
def test_sanitized_formatting(self): """ Formatting strings should be sanitized """ r = rel.SanitizedRelFile(base="/Users", file_path="/test/[title] %s yep.txt") with self.assertRaises(TypeError, msg="Failed to sanitize formatting character from file name!"): print(r.absolute() % 1)
def test_hash_path(self): """ Hashed paths should reliably work """ r = rel.SanitizedRelFile(base="/Users", file_path="/test/[title].txt") self.assertTrue(r.abs_hashed(), msg='abs_hashed() returned an invalid value!')
def test_relative(self): """ Relative files should not include path prefixes """ r = rel.SanitizedRelFile('./base', '../../1/2/file.txt') self.assertEqual('1/2/file.txt', r.relative())
def test_path_concat(self): """ Leading directory dots should be stripped in full paths """ self.assertEqual(norm('/Users/nope.txt'), rel.SanitizedRelFile(base='/Users', file_path='../nope.txt').absolute())