def _add_pkg_dir(self, pkg_dir, namespace=False): os.mkdir(pkg_dir) if namespace: return None pkg_fname = os.path.join(pkg_dir, "__init__.py") create_empty_file(pkg_fname) return pkg_fname
def setUp(self): self.test_dir = tempfile.mkdtemp() sys.path.append(self.test_dir) self.package_dir = os.path.join(self.test_dir, self.package_name) os.mkdir(self.package_dir) create_empty_file(os.path.join(self.package_dir, '__init__.py')) self.module_path = os.path.join(self.package_dir, 'foo.py')
def test_package___file__(self): try: m = __import__('pep3147') except ImportError: pass else: self.fail("pep3147 module already exists: %r" % (m, )) # Test that a package's __file__ points to the right source directory. os.mkdir('pep3147') sys.path.insert(0, os.curdir) def cleanup(): if sys.path[0] == os.curdir: del sys.path[0] shutil.rmtree('pep3147') self.addCleanup(cleanup) # Touch the __init__.py file. support.create_empty_file('pep3147/__init__.py') importlib.invalidate_caches() expected___file__ = os.sep.join(('.', 'pep3147', '__init__.py')) m = __import__('pep3147') self.assertEqual( m.__file__, expected___file__, (m.__file__, m.__path__, sys.path, sys.path_importer_cache)) # Ensure we load the pyc file. support.unload('pep3147') m = __import__('pep3147') support.unload('pep3147') self.assertEqual( m.__file__, expected___file__, (m.__file__, m.__path__, sys.path, sys.path_importer_cache))
def test_package___file__(self): try: m = __import__('pep3147') except ImportError: pass else: self.fail("pep3147 module already exists: %r" % (m,)) # Test that a package's __file__ points to the right source directory. os.mkdir('pep3147') sys.path.insert(0, os.curdir) def cleanup(): if sys.path[0] == os.curdir: del sys.path[0] shutil.rmtree('pep3147') self.addCleanup(cleanup) # Touch the __init__.py file. support.create_empty_file('pep3147/__init__.py') importlib.invalidate_caches() expected___file__ = os.sep.join(('.', 'pep3147', '__init__.py')) m = __import__('pep3147') self.assertEqual(m.__file__, expected___file__, (m.__file__, m.__path__, sys.path, sys.path_importer_cache)) # Ensure we load the pyc file. support.unload('pep3147') m = __import__('pep3147') support.unload('pep3147') self.assertEqual(m.__file__, expected___file__, (m.__file__, m.__path__, sys.path, sys.path_importer_cache))
def setUp(self): self.test_dir = tempfile.mkdtemp() sys.path.append(self.test_dir) self.package_dir = os.path.join(self.test_dir, self.package_name) os.mkdir(self.package_dir) create_empty_file(os.path.join(self.package_dir, "__init__.py")) self.module_path = os.path.join(self.package_dir, "foo.py")
def _test_pathname(self, path, cmp_path=None, dir=False): # Create a tarfile with an empty member named path # and compare the stored name with the original. foo = os.path.join(TEMPDIR, "foo") if not dir: support.create_empty_file(foo) else: os.mkdir(foo) tar = tarfile.open(tmpname, self.mode) try: tar.add(foo, arcname=path) finally: tar.close() tar = tarfile.open(tmpname, "r") try: t = tar.next() finally: tar.close() if not dir: support.unlink(foo) else: support.rmdir(foo) self.assertEqual(t.name, cmp_path or path.replace(os.sep, "/"))
def test_filter(self): tempdir = os.path.join(TEMPDIR, "filter") os.mkdir(tempdir) try: for name in ("foo", "bar", "baz"): name = os.path.join(tempdir, name) support.create_empty_file(name) def filter(tarinfo): if os.path.basename(tarinfo.name) == "bar": return tarinfo.uid = 123 tarinfo.uname = "foo" return tarinfo tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1") try: tar.add(tempdir, arcname="empty_dir", filter=filter) finally: tar.close() # Verify that filter is a keyword-only argument with self.assertRaises(TypeError): tar.add(tempdir, "empty_dir", True, None, filter) tar = tarfile.open(tmpname, "r") try: for tarinfo in tar: self.assertEqual(tarinfo.uid, 123) self.assertEqual(tarinfo.uname, "foo") self.assertEqual(len(tar.getmembers()), 3) finally: tar.close() finally: support.rmtree(tempdir)
def test_exclude(self): tempdir = os.path.join(TEMPDIR, "exclude") os.mkdir(tempdir) try: for name in ("foo", "bar", "baz"): name = os.path.join(tempdir, name) support.create_empty_file(name) exclude = os.path.isfile tar = tarfile.open(tmpname, self.mode, encoding="iso8859-1") try: # with support.check_warnings(("use the filter argument", # DeprecationWarning)): if True: ### tar.add(tempdir, arcname="empty_dir", exclude=exclude) finally: tar.close() tar = tarfile.open(tmpname, "r") try: self.assertEqual(len(tar.getmembers()), 1) self.assertEqual(tar.getnames()[0], "empty_dir") finally: tar.close() finally: support.rmtree(tempdir)
def _add_relative_modules(self, base_dir, source, depth): if depth <= 1: raise ValueError("Relative module test needs depth > 1") pkg_name = "__runpy_pkg__" module_dir = base_dir for i in range(depth): parent_dir = module_dir module_dir = os.path.join(module_dir, pkg_name) # Add sibling module sibling_fname = os.path.join(module_dir, "sibling.py") create_empty_file(sibling_fname) if verbose > 1: print(" Added sibling module:", sibling_fname) # Add nephew module uncle_dir = os.path.join(parent_dir, "uncle") self._add_pkg_dir(uncle_dir) if verbose > 1: print(" Added uncle package:", uncle_dir) cousin_dir = os.path.join(uncle_dir, "cousin") self._add_pkg_dir(cousin_dir) if verbose > 1: print(" Added cousin package:", cousin_dir) nephew_fname = os.path.join(cousin_dir, "nephew.py") create_empty_file(nephew_fname) if verbose > 1: print(" Added nephew module:", nephew_fname)
def test_module(self): self._check_path_limitations(self.pkgname) create_empty_file(os.path.join(self.subpkgname, self.pkgname + '.py')) importlib.invalidate_caches() from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import areallylongpackageandmodulenametotestreprtruncation module = areallylongpackageandmodulenametotestreprtruncation self.assertEqual(repr(module), "<module %r from %r>" % (module.__name__, module.__file__)) self.assertEqual(repr(sys), "<module 'sys' (built-in)>")
def test_chown(self): # raise an OSError if the file does not exist os.unlink(support.TESTFN) self.assertRaises(OSError, posix.chown, support.TESTFN, -1, -1) # re-create the file support.create_empty_file(support.TESTFN) self._test_all_chown_common(posix.chown, support.TESTFN, getattr(posix, "stat", None))
def test_chown_dir_fd(self): support.unlink(support.TESTFN) support.create_empty_file(support.TESTFN) f = posix.open(posix.getcwd(), posix.O_RDONLY) try: posix.chown(support.TESTFN, os.getuid(), os.getgid(), dir_fd=f) finally: posix.close(f)
def test_chown(self): # raise an OSError if the file does not exist os.unlink(support.TESTFN) self.assertRaises(OSError, posix.chown, support.TESTFN, -1, -1) # re-create the file support.create_empty_file(support.TESTFN) self._test_all_chown_common(posix.chown, support.TESTFN)
def test_module(self): self.maxDiff = None self._check_path_limitations(self.pkgname) create_empty_file(os.path.join(self.subpkgname, self.pkgname + '.py')) importlib.invalidate_caches() from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import areallylongpackageandmodulenametotestreprtruncation module = areallylongpackageandmodulenametotestreprtruncation self.assertEqual(repr(module), "<module %r from %r>" % (module.__name__, module.__file__)) self.assertEqual(repr(sys), "<module 'sys' (built-in)>")
def test_fchownat(self): support.unlink(support.TESTFN) support.create_empty_file(support.TESTFN) f = posix.open(posix.getcwd(), posix.O_RDONLY) try: posix.fchownat(f, support.TESTFN, os.getuid(), os.getgid()) finally: posix.close(f)
def test_reload_location_changed(self): name = "spam" with support.temp_cwd(None) as cwd: with test_util.uncache("spam"): with support.DirsOnSysPath(cwd): # Start as a plain module. self.init.invalidate_caches() path = os.path.join(cwd, name + ".py") cached = self.util.cache_from_source(path) expected = { "__name__": name, "__package__": "", "__file__": path, "__cached__": cached, "__doc__": None, } support.create_empty_file(path) module = self.init.import_module(name) ns = vars(module).copy() loader = ns.pop("__loader__") spec = ns.pop("__spec__") ns.pop("__builtins__", None) # An implementation detail. self.assertEqual(spec.name, name) self.assertEqual(spec.loader, loader) self.assertEqual(loader.path, path) self.assertEqual(ns, expected) # Change to a package. self.init.invalidate_caches() init_path = os.path.join(cwd, name, "__init__.py") cached = self.util.cache_from_source(init_path) expected = { "__name__": name, "__package__": name, "__file__": init_path, "__cached__": cached, "__path__": [os.path.dirname(init_path)], "__doc__": None, } os.mkdir(name) os.rename(path, init_path) reloaded = self.init.reload(module) ns = vars(reloaded).copy() loader = ns.pop("__loader__") spec = ns.pop("__spec__") ns.pop("__builtins__", None) # An implementation detail. self.assertEqual(spec.name, name) self.assertEqual(spec.loader, loader) self.assertIs(reloaded, module) self.assertEqual(loader.path, init_path) self.maxDiff = None self.assertEqual(ns, expected)
def test_reload_location_changed(self): name = 'spam' with support.temp_cwd(None) as cwd: with util.uncache('spam'): with support.DirsOnSysPath(cwd): # Start as a plain module. self.init.invalidate_caches() path = os.path.join(cwd, name + '.py') cached = self.util.cache_from_source(path) expected = { '__name__': name, '__package__': '', '__file__': path, '__cached__': cached, '__doc__': None, '__builtins__': __builtins__, } support.create_empty_file(path) module = self.init.import_module(name) ns = vars(module) loader = ns.pop('__loader__') spec = ns.pop('__spec__') self.assertEqual(spec.name, name) self.assertEqual(spec.loader, loader) self.assertEqual(loader.path, path) self.assertEqual(ns, expected) # Change to a package. self.init.invalidate_caches() init_path = os.path.join(cwd, name, '__init__.py') cached = self.util.cache_from_source(init_path) expected = { '__name__': name, '__package__': name, '__file__': init_path, '__cached__': cached, '__path__': [os.path.dirname(init_path)], '__doc__': None, '__builtins__': __builtins__, } os.mkdir(name) os.rename(path, init_path) reloaded = self.init.reload(module) ns = vars(reloaded) loader = ns.pop('__loader__') spec = ns.pop('__spec__') self.assertEqual(spec.name, name) self.assertEqual(spec.loader, loader) self.assertIs(reloaded, module) self.assertEqual(loader.path, init_path) self.maxDiff = None self.assertEqual(ns, expected)
def test_unlink_dir_fd(self): f = posix.open(posix.getcwd(), posix.O_RDONLY) support.create_empty_file(support.TESTFN + 'del') posix.stat(support.TESTFN + 'del') # should not raise exception try: posix.unlink(support.TESTFN + 'del', dir_fd=f) except: support.unlink(support.TESTFN + 'del') raise else: self.assertRaises(OSError, posix.stat, support.TESTFN + 'link') finally: posix.close(f)
def test_rename_dir_fd(self): support.unlink(support.TESTFN) support.create_empty_file(support.TESTFN + 'ren') f = posix.open(posix.getcwd(), posix.O_RDONLY) try: posix.rename(support.TESTFN + 'ren', support.TESTFN, src_dir_fd=f, dst_dir_fd=f) except: posix.rename(support.TESTFN + 'ren', support.TESTFN) raise else: posix.stat(support.TESTFN) # should not raise exception finally: posix.close(f)
def _test_single(self, filename): remove_if_exists(filename) create_empty_file(filename) try: self._do_single(filename) finally: os.unlink(filename) self.assertTrue(not os.path.exists(filename)) f = os.open(filename, os.O_CREAT) os.close(f) try: self._do_single(filename) finally: os.unlink(filename)
def test_reload_location_changed(self): name = 'spam' with support.temp_cwd(None) as cwd: with util.uncache('spam'): with support.DirsOnSysPath(cwd): # Start as a plain module. self.init.invalidate_caches() path = os.path.join(cwd, name + '.py') cached = self.util.cache_from_source(path) expected = {'__name__': name, '__package__': '', '__file__': path, '__cached__': cached, '__doc__': None, '__builtins__': __builtins__, } support.create_empty_file(path) module = self.init.import_module(name) ns = vars(module) loader = ns.pop('__loader__') spec = ns.pop('__spec__') self.assertEqual(spec.name, name) self.assertEqual(spec.loader, loader) self.assertEqual(loader.path, path) self.assertEqual(ns, expected) # Change to a package. self.init.invalidate_caches() init_path = os.path.join(cwd, name, '__init__.py') cached = self.util.cache_from_source(init_path) expected = {'__name__': name, '__package__': name, '__file__': init_path, '__cached__': cached, '__path__': [os.path.dirname(init_path)], '__doc__': None, '__builtins__': __builtins__, } os.mkdir(name) os.rename(path, init_path) reloaded = self.init.reload(module) ns = vars(reloaded) loader = ns.pop('__loader__') spec = ns.pop('__spec__') self.assertEqual(spec.name, name) self.assertEqual(spec.loader, loader) self.assertIs(reloaded, module) self.assertEqual(loader.path, init_path) self.maxDiff = None self.assertEqual(ns, expected)
def _test_single(self, filename): remove_if_exists(filename) create_empty_file(filename) try: self._do_single(filename) finally: os.unlink(filename) self.assertTrue(not os.path.exists(filename)) # and again with os.open. f = os.open(filename, os.O_CREAT) os.close(f) try: self._do_single(filename) finally: os.unlink(filename)
def setUp(self): self.pkgname = os.path.join(self.longname) self.subpkgname = os.path.join(self.longname, self.longname) # Make the package and subpackage shutil.rmtree(self.pkgname, ignore_errors=True) os.mkdir(self.pkgname) create_empty_file(os.path.join(self.pkgname, '__init__.py')) shutil.rmtree(self.subpkgname, ignore_errors=True) os.mkdir(self.subpkgname) create_empty_file(os.path.join(self.subpkgname, '__init__.py')) # Remember where we are self.here = os.getcwd() sys.path.insert(0, self.here) # When regrtest is run with its -j option, this command alone is not # enough. importlib.invalidate_caches()
def test_selflink(self): tempdir = TESTFN + "_dir" os.makedirs(tempdir) self.addCleanup(shutil.rmtree, tempdir) with change_cwd(tempdir): os.makedirs('dir') create_empty_file(os.path.join('dir', 'file')) os.symlink(os.curdir, os.path.join('dir', 'link')) results = glob.glob('**', recursive=True) self.assertEqual(len(results), len(set(results))) results = set(results) depth = 0 while results: path = os.path.join(*(['dir'] + ['link'] * depth)) self.assertIn(path, results) results.remove(path) if not results: break path = os.path.join(path, 'file') self.assertIn(path, results) results.remove(path) depth += 1 results = glob.glob(os.path.join('**', 'file'), recursive=True) self.assertEqual(len(results), len(set(results))) results = set(results) depth = 0 while results: path = os.path.join(*(['dir'] + ['link'] * depth + ['file'])) self.assertIn(path, results) results.remove(path) depth += 1 results = glob.glob(os.path.join('**', ''), recursive=True) self.assertEqual(len(results), len(set(results))) results = set(results) depth = 0 while results: path = os.path.join(*(['dir'] + ['link'] * depth + [''])) self.assertIn(path, results) results.remove(path) depth += 1
def test_selflink(self): tempdir = TESTFN + "_dir" os.makedirs(tempdir) self.addCleanup(shutil.rmtree, tempdir) with change_cwd(tempdir): os.makedirs("dir") create_empty_file(os.path.join("dir", "file")) os.symlink(os.curdir, os.path.join("dir", "link")) results = glob.glob("**", recursive=True) self.assertEqual(len(results), len(set(results))) results = set(results) depth = 0 while results: path = os.path.join(*(["dir"] + ["link"] * depth)) self.assertIn(path, results) results.remove(path) if not results: break path = os.path.join(path, "file") self.assertIn(path, results) results.remove(path) depth += 1 results = glob.glob(os.path.join("**", "file"), recursive=True) self.assertEqual(len(results), len(set(results))) results = set(results) depth = 0 while results: path = os.path.join(*(["dir"] + ["link"] * depth + ["file"])) self.assertIn(path, results) results.remove(path) depth += 1 results = glob.glob(os.path.join("**", ""), recursive=True) self.assertEqual(len(results), len(set(results))) results = set(results) depth = 0 while results: path = os.path.join(*(["dir"] + ["link"] * depth + [""])) self.assertIn(path, results) results.remove(path) depth += 1
def test_creation_mode(self): mask = 0o022 with temp_umask(mask): sys.path.insert(0, os.curdir) try: fname = TESTFN + os.extsep + "py" create_empty_file(fname) fn = imp.cache_from_source(fname) unlink(fn) importlib.invalidate_caches() __import__(TESTFN) if not os.path.exists(fn): self.fail("__import__ did not result in creation of " "either a .pyc or .pyo file") s = os.stat(fn) # Check that the umask is respected, and the executable bits # aren't set. self.assertEqual(stat.S_IMODE(s.st_mode), 0o666 & ~mask) finally: del sys.path[0] remove_files(TESTFN) unload(TESTFN)
def test_on_error(self): self.errorState = 0 os.mkdir(TESTFN) self.childpath = os.path.join(TESTFN, 'a') support.create_empty_file(self.childpath) old_dir_mode = os.stat(TESTFN).st_mode old_child_mode = os.stat(self.childpath).st_mode # Make unwritable. os.chmod(self.childpath, stat.S_IREAD) os.chmod(TESTFN, stat.S_IREAD) shutil.rmtree(TESTFN, onerror=self.check_args_to_onerror) # Test whether onerror has actually been called. self.assertEqual(self.errorState, 2, "Expected call to onerror function did not happen.") # Make writable again. os.chmod(TESTFN, old_dir_mode) os.chmod(self.childpath, old_child_mode) # Clean up. shutil.rmtree(TESTFN)
def _add_relative_modules(self, base_dir, source, depth): if depth <= 1: raise ValueError('Relative module test needs depth > 1') pkg_name = '__runpy_pkg__' module_dir = base_dir for i in range(depth): parent_dir = module_dir module_dir = os.path.join(module_dir, pkg_name) sibling_fname = os.path.join(module_dir, 'sibling.py') create_empty_file(sibling_fname) if verbose > 1: print(' Added sibling module:', sibling_fname) uncle_dir = os.path.join(parent_dir, 'uncle') self._add_pkg_dir(uncle_dir) if verbose > 1: print(' Added uncle package:', uncle_dir) cousin_dir = os.path.join(uncle_dir, 'cousin') self._add_pkg_dir(cousin_dir) if verbose > 1: print(' Added cousin package:', cousin_dir) nephew_fname = os.path.join(cousin_dir, 'nephew.py') create_empty_file(nephew_fname) if verbose > 1: print(' Added nephew module:', nephew_fname)
def testEmptyFile(self): support.unlink(TESTMOD) support.create_empty_file(TESTMOD) self.assertZipFailure(TESTMOD)
def mktemp(self, *parts): filename = self.norm(*parts) base, file = os.path.split(filename) if not os.path.exists(base): os.makedirs(base) create_empty_file(filename)
def _add_pkg_dir(self, pkg_dir): os.mkdir(pkg_dir) pkg_fname = os.path.join(pkg_dir, "__init__.py") create_empty_file(pkg_fname) return pkg_fname
def test_chown(self): os.unlink(support.TESTFN) self.assertRaises(OSError, posix.chown, support.TESTFN, -1, -1) support.create_empty_file(support.TESTFN) self._test_all_chown_common(posix.chown, support.TESTFN, getattr(posix, 'stat', None))