本文整理汇总了Python中test.support.EnvironmentVarGuard方法的典型用法代码示例。如果您正苦于以下问题:Python support.EnvironmentVarGuard方法的具体用法?Python support.EnvironmentVarGuard怎么用?Python support.EnvironmentVarGuard使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类test.support
的用法示例。
在下文中一共展示了support.EnvironmentVarGuard方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_uname_win32_ARCHITEW6432
# 需要导入模块: from test import support [as 别名]
# 或者: from test.support import EnvironmentVarGuard [as 别名]
def test_uname_win32_ARCHITEW6432(self):
# Issue 7860: make sure we get architecture from the correct variable
# on 64 bit Windows: if PROCESSOR_ARCHITEW6432 exists we should be
# using it, per
# http://blogs.msdn.com/david.wang/archive/2006/03/26/HOWTO-Detect-Process-Bitness.aspx
try:
with support.EnvironmentVarGuard() as environ:
if 'PROCESSOR_ARCHITEW6432' in environ:
del environ['PROCESSOR_ARCHITEW6432']
environ['PROCESSOR_ARCHITECTURE'] = 'foo'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'foo')
environ['PROCESSOR_ARCHITEW6432'] = 'bar'
platform._uname_cache = None
system, node, release, version, machine, processor = platform.uname()
self.assertEqual(machine, 'bar')
finally:
platform._uname_cache = None
示例2: test_security
# 需要导入模块: from test import support [as 别名]
# 或者: from test.support import EnvironmentVarGuard [as 别名]
def test_security(self):
# This test is incomplete since we are normally not run as root and
# therefore can't test the file ownership being wrong.
d = support.TESTFN
os.mkdir(d)
self.addCleanup(support.rmtree, d)
fn = os.path.join(d, '.netrc')
with open(fn, 'wt') as f:
f.write("""\
machine foo.domain.com login bar password pass
default login foo password pass
""")
with support.EnvironmentVarGuard() as environ:
environ.set('HOME', d)
os.chmod(fn, 0o600)
nrc = netrc.netrc()
self.assertEqual(nrc.hosts['foo.domain.com'],
('bar', None, 'pass'))
os.chmod(fn, 0o622)
self.assertRaises(netrc.NetrcParseError, netrc.netrc)
示例3: testLoadWithUNC
# 需要导入模块: from test import support [as 别名]
# 或者: from test.support import EnvironmentVarGuard [as 别名]
def testLoadWithUNC(self):
# Build a UNC path from the regular path.
# Something like
# \\%COMPUTERNAME%\c$\python27\python.exe
fullname = os.path.abspath(sys.executable)
if fullname[1] != ':':
raise unittest.SkipTest('Absolute path should have drive part')
unc_name = r'\\%s\%s$\%s' % (os.environ['COMPUTERNAME'],
fullname[0],
fullname[3:])
if not os.path.exists(unc_name):
raise unittest.SkipTest('Cannot connect to UNC Path')
with support.EnvironmentVarGuard() as env:
env.unset("TCL_LIBRARY")
stdout = subprocess.check_output(
[unc_name, '-c', 'import tkinter; print(tkinter)'])
self.assertIn(b'tkinter', stdout)
示例4: test_expandvars
# 需要导入模块: from test import support [as 别名]
# 或者: from test.support import EnvironmentVarGuard [as 别名]
def test_expandvars(self):
with support.EnvironmentVarGuard() as env:
env.clear()
env["foo"] = "bar"
env["{foo"] = "baz1"
env["{foo}"] = "baz2"
tester('ntpath.expandvars("foo")', "foo")
tester('ntpath.expandvars("$foo bar")', "bar bar")
tester('ntpath.expandvars("${foo}bar")', "barbar")
tester('ntpath.expandvars("$[foo]bar")', "$[foo]bar")
tester('ntpath.expandvars("$bar bar")', "$bar bar")
tester('ntpath.expandvars("$?bar")', "$?bar")
tester('ntpath.expandvars("$foo}bar")', "bar}bar")
tester('ntpath.expandvars("${foo")', "${foo")
tester('ntpath.expandvars("${{foo}}")', "baz1}")
tester('ntpath.expandvars("$foo$foo")', "barbar")
tester('ntpath.expandvars("$bar$bar")', "$bar$bar")
tester('ntpath.expandvars("%foo% bar")', "bar bar")
tester('ntpath.expandvars("%foo%bar")', "barbar")
tester('ntpath.expandvars("%foo%%foo%")', "barbar")
tester('ntpath.expandvars("%%foo%%foo%foo%")', "%foo%foobar")
tester('ntpath.expandvars("%?bar%")', "%?bar%")
tester('ntpath.expandvars("%foo%%bar")', "bar%bar")
tester('ntpath.expandvars("\'%foo%\'%bar")', "\'%foo%\'%bar")
tester('ntpath.expandvars("bar\'%foo%")', "bar\'%foo%")
示例5: test_expandvars_nonascii
# 需要导入模块: from test import support [as 别名]
# 或者: from test.support import EnvironmentVarGuard [as 别名]
def test_expandvars_nonascii(self):
def check(value, expected):
tester('ntpath.expandvars(%r)' % value, expected)
with support.EnvironmentVarGuard() as env:
env.clear()
nonascii = support.FS_NONASCII
env['spam'] = nonascii
env[nonascii] = 'ham' + nonascii
check('$spam bar', '%s bar' % nonascii)
check('$%s bar' % nonascii, '$%s bar' % nonascii)
check('${spam}bar', '%sbar' % nonascii)
check('${%s}bar' % nonascii, 'ham%sbar' % nonascii)
check('$spam}bar', '%s}bar' % nonascii)
check('$%s}bar' % nonascii, '$%s}bar' % nonascii)
check('%spam% bar', '%s bar' % nonascii)
check('%{}% bar'.format(nonascii), 'ham%s bar' % nonascii)
check('%spam%bar', '%sbar' % nonascii)
check('%{}%bar'.format(nonascii), 'ham%sbar' % nonascii)
示例6: test_load_from_source
# 需要导入模块: from test import support [as 别名]
# 或者: from test.support import EnvironmentVarGuard [as 别名]
def test_load_from_source(self):
# Verify that the imp module can correctly load and find .py files
# XXX (ncoghlan): It would be nice to use support.CleanImport
# here, but that breaks because the os module registers some
# handlers in copy_reg on import. Since CleanImport doesn't
# revert that registration, the module is left in a broken
# state after reversion. Reinitialising the module contents
# and just reverting os.environ to its previous state is an OK
# workaround
orig_path = os.path
orig_getenv = os.getenv
with support.EnvironmentVarGuard():
x = imp.find_module("os")
self.addCleanup(x[0].close)
new_os = imp.load_module("os", *x)
self.assertIs(os, new_os)
self.assertIs(orig_path, new_os.path)
self.assertIsNot(orig_getenv, new_os.getenv)
示例7: test_stty_match
# 需要导入模块: from test import support [as 别名]
# 或者: from test.support import EnvironmentVarGuard [as 别名]
def test_stty_match(self):
"""Check if stty returns the same results ignoring env
This test will fail if stdin and stdout are connected to
different terminals with different sizes. Nevertheless, such
situations should be pretty rare.
"""
try:
size = subprocess.check_output(['stty', 'size']).decode().split()
except (FileNotFoundError, subprocess.CalledProcessError):
self.skipTest("stty invocation failed")
expected = (int(size[1]), int(size[0])) # reversed order
with support.EnvironmentVarGuard() as env:
del env['LINES']
del env['COLUMNS']
actual = shutil.get_terminal_size()
self.assertEqual(expected, actual)
示例8: setUp
# 需要导入模块: from test import support [as 别名]
# 或者: from test.support import EnvironmentVarGuard [as 别名]
def setUp(self):
if not os.path.isdir(LOCALEDIR):
os.makedirs(LOCALEDIR)
with open(MOFILE, 'wb') as fp:
fp.write(base64.decodebytes(GNU_MO_DATA))
with open(MOFILE_BAD_MAJOR_VERSION, 'wb') as fp:
fp.write(base64.decodebytes(GNU_MO_DATA_BAD_MAJOR_VERSION))
with open(MOFILE_BAD_MINOR_VERSION, 'wb') as fp:
fp.write(base64.decodebytes(GNU_MO_DATA_BAD_MINOR_VERSION))
with open(UMOFILE, 'wb') as fp:
fp.write(base64.decodebytes(UMO_DATA))
with open(MMOFILE, 'wb') as fp:
fp.write(base64.decodebytes(MMO_DATA))
self.env = support.EnvironmentVarGuard()
self.env['LANGUAGE'] = 'xx'
gettext._translations.clear()
示例9: make_parser
# 需要导入模块: from test import support [as 别名]
# 或者: from test.support import EnvironmentVarGuard [as 别名]
def make_parser(self, columns):
options = [
make_option("-a", type="string", dest='a',
metavar="APPLE", help="throw APPLEs at basket"),
make_option("-b", "--boo", type="int", dest='boo',
metavar="NUM",
help=
"shout \"boo!\" NUM times (in order to frighten away "
"all the evil spirits that cause trouble and mayhem)"),
make_option("--foo", action="append", type="string", dest='foo',
help="store FOO in the foo list for later fooing"),
]
# We need to set COLUMNS for the OptionParser constructor, but
# we must restore its original value -- otherwise, this test
# screws things up for other tests when it's part of the Python
# test suite.
with support.EnvironmentVarGuard() as env:
env['COLUMNS'] = str(columns)
return InterceptingOptionParser(option_list=options)
示例10: test_cgi_get
# 需要导入模块: from test import support [as 别名]
# 或者: from test.support import EnvironmentVarGuard [as 别名]
def test_cgi_get(self):
with support.EnvironmentVarGuard() as env:
env['REQUEST_METHOD'] = 'GET'
# if the method is GET and no request_text is given, it runs handle_get
# get sysout output
with captured_stdout(encoding=self.cgi.encoding) as data_out:
self.cgi.handle_request()
# parse Status header
data_out.seek(0)
handle = data_out.read()
status = handle.split()[1]
message = ' '.join(handle.split()[2:4])
self.assertEqual(status, '400')
self.assertEqual(message, 'Bad Request')
示例11: test_getuserbase
# 需要导入模块: from test import support [as 别名]
# 或者: from test.support import EnvironmentVarGuard [as 别名]
def test_getuserbase(self):
site.USER_BASE = None
user_base = site.getuserbase()
# the call sets site.USER_BASE
self.assertEqual(site.USER_BASE, user_base)
# let's set PYTHONUSERBASE and see if it uses it
site.USER_BASE = None
import sysconfig
sysconfig._CONFIG_VARS = None
with EnvironmentVarGuard() as environ:
environ['PYTHONUSERBASE'] = 'xoxo'
self.assertTrue(site.getuserbase().startswith('xoxo'),
site.getuserbase())
示例12: test_run_not_fail_on_debug
# 需要导入模块: from test import support [as 别名]
# 或者: from test.support import EnvironmentVarGuard [as 别名]
def test_run_not_fail_on_debug(self, mock_requests):
"""
do a run with DEIS_DEBUG on - https://github.com/deis/controller/issues/583
"""
env = EnvironmentVarGuard()
env['DEIS_DEBUG'] = 'true'
app_id = self.create_app()
app = App.objects.get(id=app_id)
# dockerfile + procfile worflow
build = Build.objects.create(
owner=self.user,
app=app,
image="qwerty",
procfile={
'web': 'node server.js',
'worker': 'node worker.js'
},
dockerfile='foo',
sha='somereallylongsha'
)
# create an initial release
Release.objects.create(
version=2,
owner=self.user,
app=app,
config=app.config_set.latest(),
build=build
)
# create a run pod
url = "/v2/apps/{app_id}/run".format(**locals())
body = {'command': 'echo hi'}
response = self.client.post(url, body)
self.assertEqual(response.status_code, 200, response.data)
app = App.objects.get(id=app_id)
self.assertEqual(app._get_entrypoint('web'), ['/bin/bash', '-c'])
示例13: test_find_executable
# 需要导入模块: from test import support [as 别名]
# 或者: from test.support import EnvironmentVarGuard [as 别名]
def test_find_executable(self):
with test_support.temp_dir() as tmp_dir:
# use TESTFN to get a pseudo-unique filename
program_noeext = test_support.TESTFN
# Give the temporary program an ".exe" suffix for all.
# It's needed on Windows and not harmful on other platforms.
program = program_noeext + ".exe"
filename = os.path.join(tmp_dir, program)
with open(filename, "wb"):
pass
os.chmod(filename, stat.S_IXUSR)
# test path parameter
rv = find_executable(program, path=tmp_dir)
self.assertEqual(rv, filename)
if sys.platform == 'win32':
# test without ".exe" extension
rv = find_executable(program_noeext, path=tmp_dir)
self.assertEqual(rv, filename)
# test find in the current directory
with test_support.change_cwd(tmp_dir):
rv = find_executable(program)
self.assertEqual(rv, program)
# test non-existent program
dont_exist_program = "dontexist_" + program
rv = find_executable(dont_exist_program , path=tmp_dir)
self.assertIsNone(rv)
# test os.defpath: missing PATH environment variable
with test_support.EnvironmentVarGuard() as env:
from distutils import spawn
with test_support.swap_attr(spawn.os, 'defpath', tmp_dir):
env.pop('PATH')
rv = find_executable(program)
self.assertEqual(rv, filename)
示例14: _test_client
# 需要导入模块: from test import support [as 别名]
# 或者: from test.support import EnvironmentVarGuard [as 别名]
def _test_client(self, client_func, expected_path, expected_body, secret=None, success=True):
_request = {}
class AccessTokenHandler(UserSecretsHTTPHandler):
def set_request(self):
_request['path'] = self.path
content_len = int(self.headers.get('Content-Length'))
_request['body'] = json.loads(self.rfile.read(content_len))
_request['headers'] = self.headers
def get_response(self):
if success:
return {'result': {'secret': secret, 'secretType': 'refreshToken', 'secretProvider': 'google', 'expiresInSeconds': 3600}, 'wasSuccessful': "true"}
else:
return {'wasSuccessful': "false", 'errors': ['No user secrets exist for kernel']}
env = EnvironmentVarGuard()
env.set(_KAGGLE_USER_SECRETS_TOKEN_ENV_VAR_NAME, _TEST_JWT)
with env:
with HTTPServer((self.SERVER_ADDRESS.hostname, self.SERVER_ADDRESS.port), AccessTokenHandler) as httpd:
threading.Thread(target=httpd.serve_forever).start()
try:
client_func()
finally:
httpd.shutdown()
path, headers, body = _request['path'], _request['headers'], _request['body']
self.assertEqual(
path,
expected_path,
msg="Fake server did not receive the right request from the UserSecrets client.")
self.assertEqual(
body,
expected_body,
msg="Fake server did not receive the right body from the UserSecrets client.")
示例15: test_no_token_fails
# 需要导入模块: from test import support [as 别名]
# 或者: from test.support import EnvironmentVarGuard [as 别名]
def test_no_token_fails(self):
env = EnvironmentVarGuard()
env.unset(_KAGGLE_USER_SECRETS_TOKEN_ENV_VAR_NAME)
with env:
with self.assertRaises(CredentialError):
client = UserSecretsClient()