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()
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)
def test_record_override_showwarning_before(self): # Issue #28835: If warnings.showwarning() was overriden, make sure # that catch_warnings(record=True) overrides it again. text = "This is a warning" wmod = self.module my_log = [] def my_logger(message, category, filename, lineno, file=None, line=None): nonlocal my_log my_log.append(message) # Override warnings.showwarning() before calling catch_warnings() with support.swap_attr(wmod, 'showwarning', my_logger): with wmod.catch_warnings(module=wmod, record=True) as log: self.assertIsNot(wmod.showwarning, my_logger) wmod.simplefilter("always") wmod.warn(text) self.assertIs(wmod.showwarning, my_logger) self.assertEqual(len(log), 1, log) self.assertEqual(log[0].message.args[0], text) self.assertEqual(my_log, [])
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(), [])
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(), [])
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(), [])
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'))
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))
def run_script(self, input="", *, args=("-", ), substfile="xx yy\n"): substfilename = support.TESTFN + ".subst" with open(substfilename, "w") as file: file.write(substfile) self.addCleanup(support.unlink, substfilename) argv = ["fixcid.py", "-s", substfilename] + list(args) script = os.path.join(scriptsdir, "fixcid.py") with support.swap_attr(sys, "argv", argv), \ support.swap_attr(sys, "stdin", StringIO(input)), \ support.captured_stdout() as output, \ support.captured_stderr(): try: runpy.run_path(script, run_name="__main__") except SystemExit as exit: self.assertEqual(exit.code, 0) return output.getvalue()
def test_modify_builtins(self): # Modify the builtins module directly. def foo(): return len([1, 2, 3]) self.configure_func(foo) self.assertEqual(foo(), 3) with swap_attr(builtins, "len", lambda x: 7): self.assertEqual(foo(), 7)
def test_modify_builtins_while_generator_active(self): # Modify the builtins out from under a live generator. def foo(): x = range(3) yield len(x) yield len(x) self.configure_func(foo) g = foo() self.assertEqual(next(g), 3) with swap_attr(builtins, "len", lambda x: 7): self.assertEqual(next(g), 7)
def test_rmtree(self): dirpath = support.TESTFN + 'd' subdirpath = os.path.join(dirpath, 'subdir') os.mkdir(dirpath) os.mkdir(subdirpath) support.rmtree(dirpath) self.assertFalse(os.path.exists(dirpath)) with support.swap_attr(support, 'verbose', 0): support.rmtree(dirpath) os.mkdir(dirpath) os.mkdir(subdirpath) os.chmod(dirpath, stat.S_IRUSR|stat.S_IXUSR) with support.swap_attr(support, 'verbose', 0): support.rmtree(dirpath) self.assertFalse(os.path.exists(dirpath)) os.mkdir(dirpath) os.mkdir(subdirpath) os.chmod(dirpath, 0) with support.swap_attr(support, 'verbose', 0): support.rmtree(dirpath) self.assertFalse(os.path.exists(dirpath))
def test_override_builtin(self): # Test that overriding builtins.__import__ can bypass sys.modules. import os def foo(): import os return os self.assertEqual(foo(), os) # Quick sanity check. with swap_attr(builtins, "__import__", lambda *x: 5): self.assertEqual(foo(), 5) # Test what happens when we shadow __import__ in globals(); this # currently does not impact the import process, but if this changes, # other code will need to change, so keep this test as a tripwire. with swap_item(globals(), "__import__", lambda *x: 5): self.assertEqual(foo(), os)
def test_modify_builtins_from_leaf_function(self): # Verify that modifications made by leaf functions percolate up the # callstack. with swap_attr(builtins, "len", len): def bar(): builtins.len = lambda x: 4 def foo(modifier): l = [] l.append(len(range(7))) modifier() l.append(len(range(7))) return l self.configure_func(foo, lambda: None) self.assertEqual(foo(bar), [7, 4])
def test_cache_from_source_no_cache_tag(self): # No cache tag means NotImplementedError. with support.swap_attr(sys.implementation, 'cache_tag', None): with self.assertRaises(NotImplementedError): self.util.cache_from_source('whatever.py')
def test_source_from_cache_no_cache_tag(self): # If sys.implementation.cache_tag is None, raise NotImplementedError. path = os.path.join('blah', '__pycache__', 'whatever.pyc') with support.swap_attr(sys.implementation, 'cache_tag', None): with self.assertRaises(NotImplementedError): self.util.source_from_cache(path)
def testRecursiveRepr(self): # Issue #25455 with swap_attr(self.f, 'name', self.f): with self.assertRaises(RuntimeError): repr(self.f) # Should not crash