本文整理汇总了Python中test.support.swap_attr函数的典型用法代码示例。如果您正苦于以下问题:Python swap_attr函数的具体用法?Python swap_attr怎么用?Python swap_attr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了swap_attr函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_no_files_left_behind
def test_no_files_left_behind(self):
# use a private empty directory
with tempfile.TemporaryDirectory() as our_temp_directory:
# force _get_default_tempdir() to consider our empty directory
def our_candidate_list():
return [our_temp_directory]
with support.swap_attr(tempfile, "_candidate_tempdir_list", our_candidate_list):
# verify our directory is empty after _get_default_tempdir()
tempfile._get_default_tempdir()
self.assertEqual(os.listdir(our_temp_directory), [])
def raise_OSError(*args, **kwargs):
raise OSError()
with support.swap_attr(io, "open", raise_OSError):
# test again with failing io.open()
with self.assertRaises(FileNotFoundError):
tempfile._get_default_tempdir()
self.assertEqual(os.listdir(our_temp_directory), [])
open = io.open
def bad_writer(*args, **kwargs):
fp = open(*args, **kwargs)
fp.write = raise_OSError
return fp
with support.swap_attr(io, "open", bad_writer):
# test again with failing write()
with self.assertRaises(FileNotFoundError):
tempfile._get_default_tempdir()
self.assertEqual(os.listdir(our_temp_directory), [])
示例2: test_non_ascii
def test_non_ascii(self):
# Issues #8663, #34421: test that non-encodable text is escaped with
# backslashreplace error handler and encodable non-ASCII text is
# output as is.
for errors in ('strict', 'backslashreplace', 'surrogateescape',
'replace', 'ignore'):
with self.subTest(errors=errors):
stdout = io.TextIOWrapper(io.BytesIO(),
encoding='cp437', errors=errors)
stderr = io.TextIOWrapper(io.BytesIO(),
encoding='cp437', errors=errors)
old_threshold = log.set_threshold(log.DEBUG)
try:
with swap_attr(sys, 'stdout', stdout), \
swap_attr(sys, 'stderr', stderr):
log.debug('Dεbug\tMėssãge')
log.fatal('Fαtal\tÈrrōr')
finally:
log.set_threshold(old_threshold)
stdout.seek(0)
self.assertEqual(stdout.read().rstrip(),
'Dεbug\tM?ss?ge' if errors == 'replace' else
'Dεbug\tMssge' if errors == 'ignore' else
'Dεbug\tM\\u0117ss\\xe3ge')
stderr.seek(0)
self.assertEqual(stderr.read().rstrip(),
'Fαtal\t?rr?r' if errors == 'replace' else
'Fαtal\trrr' if errors == 'ignore' else
'Fαtal\t\\xc8rr\\u014dr')
示例3: test_initialization_no_master
def test_initialization_no_master(self):
# no master passing
with swap_attr(tkinter, '_default_root', None), \
swap_attr(tkinter, '_support_default_root', True):
try:
x = ttk.LabeledScale()
self.assertIsNotNone(tkinter._default_root)
self.assertEqual(x.master, tkinter._default_root)
self.assertEqual(x.tk, tkinter._default_root.tk)
x.destroy()
finally:
destroy_default_root()
示例4: test_memoryerror
def test_memoryerror(self):
lines = linecache.getlines(FILENAME)
self.assertTrue(lines)
def raise_memoryerror(*args, **kwargs):
raise MemoryError
with support.swap_attr(linecache, 'updatecache', raise_memoryerror):
lines2 = linecache.getlines(FILENAME)
self.assertEqual(lines2, lines)
linecache.clearcache()
with support.swap_attr(linecache, 'updatecache', raise_memoryerror):
lines3 = linecache.getlines(FILENAME)
self.assertEqual(lines3, [])
self.assertEqual(linecache.getlines(FILENAME), lines)
示例5: test_home_not_set
def test_home_not_set(self):
fake_home = support.TESTFN
os.mkdir(fake_home)
self.addCleanup(support.rmtree, fake_home)
fake_netrc_path = os.path.join(fake_home, '.netrc')
with open(fake_netrc_path, 'w') as f:
f.write('machine foo.domain.com login bar password pass')
os.chmod(fake_netrc_path, 0o600)
orig_expanduser = os.path.expanduser
called = []
def fake_expanduser(s):
called.append(s)
with support.EnvironmentVarGuard() as environ:
environ.set('HOME', fake_home)
result = orig_expanduser(s)
return result
with support.swap_attr(os.path, 'expanduser', fake_expanduser):
nrc = netrc.netrc()
login, account, password = nrc.authenticators('foo.domain.com')
self.assertEqual(login, 'bar')
self.assertTrue(called)
示例6: test_format_exception
def test_format_exception(self):
try:
self.last_raises5()
except Exception:
exc_type, exc_value, tb = sys.exc_info()
# [1:-1] to exclude "Traceback (...)" header and
# exception type and value
def extract(**kwargs):
return traceback.format_exception(exc_type, exc_value, tb, **kwargs)[1:-1]
with support.swap_attr(sys, 'tracebacklimit', 1000):
nolim = extract()
self.assertEqual(len(nolim), 5+1)
self.assertEqual(extract(limit=2), nolim[:2])
self.assertEqual(extract(limit=10), nolim)
self.assertEqual(extract(limit=-2), nolim[-2:])
self.assertEqual(extract(limit=-10), nolim)
self.assertEqual(extract(limit=0), [])
del sys.tracebacklimit
self.assertEqual(extract(), nolim)
sys.tracebacklimit = 2
self.assertEqual(extract(), nolim[:2])
self.assertEqual(extract(limit=3), nolim[:3])
self.assertEqual(extract(limit=-3), nolim[-3:])
sys.tracebacklimit = 0
self.assertEqual(extract(), [])
sys.tracebacklimit = -1
self.assertEqual(extract(), [])
示例7: test_collision_with_existing_directory
def test_collision_with_existing_directory(self):
# _mkstemp_inner tries another name when a directory with
# the chosen name already exists
container_dir = tempfile.mkdtemp()
try:
def mock_get_candidate_names():
return iter(['aaa', 'aaa', 'bbb'])
with support.swap_attr(tempfile,
'_get_candidate_names',
mock_get_candidate_names):
dir = tempfile.mkdtemp(dir=container_dir)
self.assertTrue(dir.endswith('aaa'))
flags = tempfile._bin_openflags
(fd, name) = tempfile._mkstemp_inner(container_dir,
tempfile.template,
'',
flags)
try:
self.assertTrue(name.endswith('bbb'))
finally:
os.close(fd)
os.unlink(name)
finally:
support.rmtree(container_dir)
示例8: test_extract_stack
def test_extract_stack(self):
frame = self.last_returns_frame5()
def extract(**kwargs):
return traceback.extract_stack(frame, **kwargs)
def assertEqualExcept(actual, expected, ignore):
self.assertEqual(actual[:ignore], expected[:ignore])
self.assertEqual(actual[ignore+1:], expected[ignore+1:])
self.assertEqual(len(actual), len(expected))
with support.swap_attr(sys, 'tracebacklimit', 1000):
nolim = extract()
self.assertGreater(len(nolim), 5)
self.assertEqual(extract(limit=2), nolim[-2:])
assertEqualExcept(extract(limit=100), nolim[-100:], -5-1)
self.assertEqual(extract(limit=-2), nolim[:2])
assertEqualExcept(extract(limit=-100), nolim[:100], len(nolim)-5-1)
self.assertEqual(extract(limit=0), [])
del sys.tracebacklimit
assertEqualExcept(extract(), nolim, -5-1)
sys.tracebacklimit = 2
self.assertEqual(extract(), nolim[-2:])
self.assertEqual(extract(limit=3), nolim[-3:])
self.assertEqual(extract(limit=-3), nolim[:3])
sys.tracebacklimit = 0
self.assertEqual(extract(), [])
sys.tracebacklimit = -1
self.assertEqual(extract(), [])
示例9: test_no_home_directory
def test_no_home_directory(self):
# bpo-10496: getuserbase() and getusersitepackages() must not fail if
# the current user has no home directory (if expanduser() returns the
# path unchanged).
site.USER_SITE = None
site.USER_BASE = None
with EnvironmentVarGuard() as environ, \
mock.patch('os.path.expanduser', lambda path: path):
del environ['PYTHONUSERBASE']
del environ['APPDATA']
user_base = site.getuserbase()
self.assertTrue(user_base.startswith('~' + os.sep),
user_base)
user_site = site.getusersitepackages()
self.assertTrue(user_site.startswith(user_base), user_site)
with mock.patch('os.path.isdir', return_value=False) as mock_isdir, \
mock.patch.object(site, 'addsitedir') as mock_addsitedir, \
support.swap_attr(site, 'ENABLE_USER_SITE', True):
# addusersitepackages() must not add user_site to sys.path
# if it is not an existing directory
known_paths = set()
site.addusersitepackages(known_paths)
mock_isdir.assert_called_once_with(user_site)
mock_addsitedir.assert_not_called()
self.assertFalse(known_paths)
示例10: test_swap_attr
def test_swap_attr(self):
class Obj:
pass
obj = Obj()
obj.x = 1
with support.swap_attr(obj, "x", 5) as x:
self.assertEqual(obj.x, 5)
self.assertEqual(x, 1)
self.assertEqual(obj.x, 1)
with support.swap_attr(obj, "y", 5) as y:
self.assertEqual(obj.y, 5)
self.assertIsNone(y)
self.assertFalse(hasattr(obj, 'y'))
with support.swap_attr(obj, "y", 5):
del obj.y
self.assertFalse(hasattr(obj, 'y'))
示例11: test_non_directory
def test_non_directory(self):
with _inside_empty_temp_dir():
tempdir = os.path.join(tempfile.tempdir, 'file')
open(tempdir, 'wb').close()
with support.swap_attr(tempfile, 'tempdir', tempdir):
with self.assertRaises((NotADirectoryError, FileNotFoundError)):
self.make_temp()
示例12: test_swap_attr
def test_swap_attr(self):
class Obj:
x = 1
obj = Obj()
with support.swap_attr(obj, "x", 5):
self.assertEqual(obj.x, 5)
self.assertEqual(obj.x, 1)
示例13: _inside_empty_temp_dir
def _inside_empty_temp_dir():
dir = tempfile.mkdtemp()
try:
with support.swap_attr(tempfile, "tempdir", dir):
yield
finally:
support.rmtree(dir)
示例14: test_extract_tb
def test_extract_tb(self):
try:
self.last_raises5()
except Exception:
exc_type, exc_value, tb = sys.exc_info()
def extract(**kwargs):
return traceback.extract_tb(tb, **kwargs)
with support.swap_attr(sys, 'tracebacklimit', 1000):
nolim = extract()
self.assertEqual(len(nolim), 5+1)
self.assertEqual(extract(limit=2), nolim[:2])
self.assertEqual(extract(limit=10), nolim)
self.assertEqual(extract(limit=-2), nolim[-2:])
self.assertEqual(extract(limit=-10), nolim)
self.assertEqual(extract(limit=0), [])
del sys.tracebacklimit
self.assertEqual(extract(), nolim)
sys.tracebacklimit = 2
self.assertEqual(extract(), nolim[:2])
self.assertEqual(extract(limit=3), nolim[:3])
self.assertEqual(extract(limit=-3), nolim[-3:])
sys.tracebacklimit = 0
self.assertEqual(extract(), [])
sys.tracebacklimit = -1
self.assertEqual(extract(), [])
示例15: test_bad_timezone
def test_bad_timezone(self):
# Explicitly test possibility of bad timezone;
# when time.tzname[0] == time.tzname[1] and time.daylight
tz_name = time.tzname[0]
if tz_name.upper() in ("UTC", "GMT"):
self.skipTest('need non-UTC/GMT timezone')
with support.swap_attr(time, 'tzname', (tz_name, tz_name)), \
support.swap_attr(time, 'daylight', 1), \
support.swap_attr(time, 'tzset', lambda: None):
time.tzname = (tz_name, tz_name)
time.daylight = 1
tz_value = _strptime._strptime_time(tz_name, "%Z")[8]
self.assertEqual(tz_value, -1,
"%s lead to a timezone value of %s instead of -1 when "
"time.daylight set to %s and passing in %s" %
(time.tzname, tz_value, time.daylight, tz_name))