本文整理汇总了Python中test.support.temp_cwd函数的典型用法代码示例。如果您正苦于以下问题:Python temp_cwd函数的具体用法?Python temp_cwd怎么用?Python temp_cwd使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了temp_cwd函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_issue_8766
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)
示例2: test_issue_8766
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"):
env = os.environ.copy()
env["PYTHONPATH"] = cwd
# encodings loaded by initfsencoding()
retcode = subprocess.call([sys.executable, "-c", "pass"], env=env)
self.assertEqual(retcode, 0)
# Use -W to load warnings module at startup
retcode = subprocess.call([sys.executable, "-c", "pass", "-W", "always"], env=env)
self.assertEqual(retcode, 0)
示例3: test_set_pycache_prefix
def test_set_pycache_prefix(self):
# sys.pycache_prefix can be set from either -X pycache_prefix or
# PYTHONPYCACHEPREFIX env var, with the former taking precedence.
NO_VALUE = object() # `-X pycache_prefix` with no `=PATH`
cases = [
# (PYTHONPYCACHEPREFIX, -X pycache_prefix, sys.pycache_prefix)
(None, None, None),
('foo', None, 'foo'),
(None, 'bar', 'bar'),
('foo', 'bar', 'bar'),
('foo', '', None),
('foo', NO_VALUE, None),
]
for envval, opt, expected in cases:
exp_clause = "is None" if expected is None else f'== "{expected}"'
code = f"import sys; sys.exit(not sys.pycache_prefix {exp_clause})"
args = ['-c', code]
env = {} if envval is None else {'PYTHONPYCACHEPREFIX': envval}
if opt is NO_VALUE:
args[:0] = ['-X', 'pycache_prefix']
elif opt is not None:
args[:0] = ['-X', f'pycache_prefix={opt}']
with self.subTest(envval=envval, opt=opt):
with support.temp_cwd():
assert_python_ok(*args, **env)
示例4: test_readrc_kwarg
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
示例5: test_empty
def test_empty(self):
# Switch to an existing, but safe, working directory to let the
# cleanup code do its thing without permission errors.
with support.temp_cwd(path=path.dirname(sys.executable)):
empty = path.join(path.dirname(__file__), "empty.vbs")
startfile(empty)
startfile(empty, "open")
示例6: test_options_no_site_import
def test_options_no_site_import(self):
with support.temp_cwd() as temp_cwd:
self.assertEqual(
subprocess.check_output(
[sys.executable, "-S", "-c",
"import sys; print sorted(sys.modules.keys())"]).strip(),
"['__builtin__', '__main__', 'exceptions', 'sys']")
示例7: test_compileall
def test_compileall(self):
with temp_cwd():
PACKAGE = os.path.realpath("./greetings")
PYC_GREETER = os.path.join(PACKAGE, "greeter.pyc")
PYCLASS_GREETER = os.path.join(PACKAGE, "greeter$py.class")
PYCLASS_TEST = os.path.join(PACKAGE, "test$py.class")
os.mkdir(PACKAGE)
self.write_code(
PACKAGE, "greeter.py",
"""
def greet():
print 'Hello world!'
""")
self.write_code(
PACKAGE, "test.py",
"""
from greeter import greet
greet()
""")
# pretend we have a Python bytecode compiler by touching this file
open(PYC_GREETER, "a").close()
compileall.compile_dir(PACKAGE, quiet=True)
self.assertTrue(os.path.exists(PYC_GREETER)) # still exists
self.assertTrue(os.path.exists(PYCLASS_TEST)) # along with these new compiled files
self.assertTrue(os.path.exists(PYCLASS_GREETER))
# verify we can work with just compiled files
os.unlink(os.path.join(PACKAGE, "greeter.py"))
self.assertEqual(
subprocess.check_output([sys.executable, os.path.join(PACKAGE, "test.py")]).rstrip(),
"Hello world!")
示例8: test_temp_cwd__chdir_warning
def test_temp_cwd__chdir_warning(self):
"""Check the warning message when os.chdir() fails."""
path = TESTFN + '_does_not_exist'
with support.check_warnings() as recorder:
with support.temp_cwd(path=path, quiet=True):
pass
messages = [str(w.message) for w in recorder.warnings]
self.assertEqual(messages, ['tests may fail, unable to change the CWD to ' + path])
示例9: test_property_no_site_import
def test_property_no_site_import(self):
# only the minimal set of modules are imported
with support.temp_cwd() as temp_cwd:
self.assertEqual(
subprocess.check_output(
[sys.executable, "-Dpython.import.site=false", "-c",
"import sys; print sorted(sys.modules.keys())"]).strip(),
"['__builtin__', '__main__', 'exceptions', 'sys']")
示例10: test_abspath
def test_abspath(self):
tester('ntpath.abspath("C:\\")', "C:\\")
with support.temp_cwd(support.TESTFN) as cwd_dir: # bpo-31047
tester('ntpath.abspath("")', cwd_dir)
tester('ntpath.abspath(" ")', cwd_dir + "\\ ")
tester('ntpath.abspath("?")', cwd_dir + "\\?")
drive, _ = ntpath.splitdrive(cwd_dir)
tester('ntpath.abspath("/abc/")', drive + "\\abc")
示例11: test_temp_cwd__name_none
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)
示例12: test_directory
def test_directory(self):
dirname = os.path.join(support.TESTFN, 'Gr\xfc\xdf-\u66e8\u66e9\u66eb')
filename = '\xdf-\u66e8\u66e9\u66eb'
with support.temp_cwd(dirname):
with open(filename, 'wb') as f:
f.write((filename + '\n').encode("utf-8"))
os.access(filename,os.R_OK)
os.remove(filename)
示例13: test_reload_namespace_changed
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,
'__file__': 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.assertIsNotNone(spec.loader)
self.assertIsNotNone(loader)
self.assertEqual(spec.loader, loader)
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)
示例14: test_empty_python_home
def test_empty_python_home(self):
# http://bugs.jython.org/issue2283
with support.temp_cwd() as temp_cwd:
# using a new directory ensures no Lib/ directory is available
self.assertEqual(
subprocess.check_output(
[sys.executable, "-Dpython.home=", "-c",
"import os; os.system('echo 42'); os.system('echo 47')"])\
.replace("\r", ""), # in case of running on Windows
"42\n47\n")
示例15: extract_docstrings_from_str
def extract_docstrings_from_str(self, module_content):
""" utility: return all msgids extracted from module_content """
filename = 'test_docstrings.py'
with temp_cwd(None) as cwd:
with open(filename, 'w') as fp:
fp.write(module_content)
assert_python_ok(self.script, '-D', filename)
with open('messages.pot') as fp:
data = fp.read()
return self.get_msgids(data)