def test_issue_8766(self): # "import encodings" emits a warning whereas the warnings is not loaded # or not completely loaded (warnings imports indirectly encodings by # importing linecache) yet with support.temp_cwd() as cwd, support.temp_cwd('encodings'): # encodings loaded by initfsencoding() assert_python_ok('-c', 'pass', PYTHONPATH=cwd) # Use -W to load warnings module at startup assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd)
def test_relpath(self): tester('ntpath.relpath("a")', 'a') tester('ntpath.relpath(os.path.abspath("a"))', 'a') tester('ntpath.relpath("a/b")', 'a\\b') tester('ntpath.relpath("../a/b")', '..\\a\\b') with support.temp_cwd(support.TESTFN) as cwd_dir: currentdir = os.path.basename(cwd_dir) tester('ntpath.relpath("a", "../b")', '..\\' + currentdir + '\\a') tester('ntpath.relpath("a/b", "../c")', '..\\' + currentdir + '\\a\\b') tester('ntpath.relpath("a", "b/c")', '..\\..\\a') tester('ntpath.relpath("c:/foo/bar/bat", "c:/x/y")', '..\\..\\foo\\bar\\bat') tester( 'ntpath.relpath("//conky/mountpoint/a", "//conky/mountpoint/b/c")', '..\\..\\a') tester('ntpath.relpath("a", "a")', '.') tester('ntpath.relpath("/foo/bar/bat", "/x/y/z")', '..\\..\\..\\foo\\bar\\bat') tester('ntpath.relpath("/foo/bar/bat", "/foo/bar")', 'bat') tester('ntpath.relpath("/foo/bar/bat", "/")', 'foo\\bar\\bat') tester('ntpath.relpath("/", "/foo/bar/bat")', '..\\..\\..') tester('ntpath.relpath("/foo/bar/bat", "/x")', '..\\foo\\bar\\bat') tester('ntpath.relpath("/x", "/foo/bar/bat")', '..\\..\\..\\x') tester('ntpath.relpath("/", "/")', '.') tester('ntpath.relpath("/a", "/a")', '.') tester('ntpath.relpath("/a/b", "/a/b")', '.') tester('ntpath.relpath("c:/foo", "C:/FOO")', '.')
def test_readrc_kwarg(self): script = textwrap.dedent(""" import pdb; pdb.Pdb(readrc=False).set_trace() print('hello') """) save_home = os.environ.pop('HOME', None) try: with support.temp_cwd(): with open('.pdbrc', 'w') as f: f.write("invalid\n") with open('main.py', 'w') as f: f.write(script) cmd = [sys.executable, 'main.py'] proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, ) with proc: stdout, stderr = proc.communicate(b'q\n') self.assertNotIn( "NameError: name 'invalid' is not defined", stdout.decode()) finally: if save_home is not None: os.environ['HOME'] = save_home
def test_temp_cwd__name_none(self): """Test passing None to temp_cwd().""" original_cwd = os.getcwd() with support.temp_cwd(name=None) as new_cwd: self.assertNotEqual(new_cwd, original_cwd) self.assertTrue(os.path.isdir(new_cwd)) self.assertEqual(os.getcwd(), new_cwd) self.assertEqual(os.getcwd(), original_cwd)
def test_reload_namespace_changed(self): name = 'spam' with support.temp_cwd(None) as cwd: with test_util.uncache('spam'): with support.DirsOnSysPath(cwd): # Start as a namespace package. self.init.invalidate_caches() bad_path = os.path.join(cwd, name, '__init.py') cached = self.util.cache_from_source(bad_path) expected = { '__name__': name, '__package__': name, '__doc__': None, } os.mkdir(name) with open(bad_path, 'w') as init_file: init_file.write('eggs = None') module = self.init.import_module(name) ns = vars(module).copy() loader = ns.pop('__loader__') path = ns.pop('__path__') spec = ns.pop('__spec__') ns.pop('__builtins__', None) # An implementation detail. self.assertEqual(spec.name, name) self.assertIs(spec.loader, None) self.assertIsNot(loader, None) self.assertEqual(set(path), set([os.path.dirname(bad_path)])) with self.assertRaises(AttributeError): # a NamespaceLoader loader.path self.assertEqual(ns, expected) # Change to a regular 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, 'eggs': None, } os.rename(bad_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.assertEqual(ns, expected)
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_POT_Creation_Date(self): """ Match the date format from xgettext for POT-Creation-Date """ from datetime import datetime with temp_cwd(None) as cwd: assert_python_ok(self.script) with open('messages.pot') as fp: data = fp.read() header = self.get_header(data) creationDate = header['POT-Creation-Date'] # peel off the escaped newline at the end of string if creationDate.endswith('\\n'): creationDate = creationDate[:-len('\\n')] # This will raise if the date format does not exactly match. datetime.strptime(creationDate, '%Y-%m-%d %H:%M%z')
def test_nonascii_abspath(self): if (support.TESTFN_UNDECODABLE # Mac OS X denies the creation of a directory with an invalid # UTF-8 name. Windows allows creating a directory with an # arbitrary bytes name, but fails to enter this directory # (when the bytes name is used). and sys.platform not in ('win32', 'darwin')): name = support.TESTFN_UNDECODABLE elif support.TESTFN_NONASCII: name = support.TESTFN_NONASCII else: self.skipTest("need support.TESTFN_NONASCII") with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) with support.temp_cwd(name): self.test_abspath()
def test_abspath_issue3426(self): # Check that abspath returns unicode when the arg is unicode # with both ASCII and non-ASCII cwds. abspath = self.pathmodule.abspath for path in ('', 'fuu', 'f\xf9\xf9', '/fuu', 'U:\\'): self.assertIsInstance(abspath(path), str) unicwd = '\xe7w\xf0' try: os.fsencode(unicwd) except (AttributeError, UnicodeEncodeError): # FS encoding is probably ASCII pass else: with support.temp_cwd(unicwd): for path in ('', 'fuu', 'f\xf9\xf9', '/fuu', 'U:\\'): self.assertIsInstance(abspath(path), str)
def test_header(self): """Make sure the required fields are in the header, according to: http://www.gnu.org/software/gettext/manual/gettext.html#Header-Entry """ with temp_cwd(None) as cwd: assert_python_ok(self.script) with open('messages.pot') as fp: data = fp.read() header = self.get_header(data) self.assertIn("Project-Id-Version", header) self.assertIn("POT-Creation-Date", header) self.assertIn("PO-Revision-Date", header) self.assertIn("Last-Translator", header) self.assertIn("Language-Team", header) self.assertIn("MIME-Version", header) self.assertIn("Content-Type", header) self.assertIn("Content-Transfer-Encoding", header) self.assertIn("Generated-By", header)
def setUp(self): # Create a simple test environment # Note that we're making changes to sys.path super(BuildExtTestCase, self).setUp() self.tmp_dir = self.mkdtemp() self.sys_path = sys.path, sys.path[:] sys.path.append(self.tmp_dir) import site self.old_user_base = site.USER_BASE site.USER_BASE = self.mkdtemp() from distutils.command import build_ext build_ext.USER_BASE = site.USER_BASE # bpo-30132: On Windows, a .pdb file may be created in the current # working directory. Create a temporary working directory to cleanup # everything at the end of the test. self.temp_cwd = support.temp_cwd() self.temp_cwd.__enter__() self.addCleanup(self.temp_cwd.__exit__, None, None, None)
def temp_module(name, content='', *, pkg=False): conflicts = [n for n in sys.modules if n.partition('.')[0] == name] with support.temp_cwd(None) as cwd: with uncache(name, *conflicts): with support.DirsOnSysPath(cwd): invalidate_caches() location = os.path.join(cwd, name) if pkg: modpath = os.path.join(location, '__init__.py') os.mkdir(name) else: modpath = location + '.py' if content is None: # Make sure the module file gets created. content = '' if content is not None: # not a namespace package with open(modpath, 'w') as modfile: modfile.write(content) yield location
def main(self, tests=None, **kwargs): global TEMPDIR if sysconfig.is_python_build(): try: os.mkdir(TEMPDIR) except FileExistsError: pass # Define a writable temp dir that will be used as cwd while running # the tests. The name of the dir includes the pid to allow parallel # testing (see the -j option). test_cwd = 'test_python_{}'.format(os.getpid()) test_cwd = os.path.join(TEMPDIR, test_cwd) # Run the tests in a context manager that temporarily changes the CWD to a # temporary and writable directory. If it's not possible to create or # change the CWD, the original CWD will be used. The original CWD is # available from support.SAVEDCWD. with support.temp_cwd(test_cwd, quiet=True): self._main(tests, kwargs)
def test_temp_cwd(self): here = os.getcwd() with support.temp_cwd(name=TESTFN): self.assertEqual(os.path.basename(os.getcwd()), TESTFN) self.assertFalse(os.path.exists(TESTFN)) self.assertTrue(os.path.basename(os.getcwd()), here)
def test_bug7732(self): with support.temp_cwd(): source = support.TESTFN + '.py' os.mkdir(source) self.assertRaisesRegex(ImportError, '^No module', imp.find_module, support.TESTFN, ["."])