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), [])
Beispiel #2
0
    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')
Beispiel #3
0
 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)
Beispiel #5
0
    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)
def _inside_empty_temp_dir():
    dir = tempfile.mkdtemp()
    try:
        with support.swap_attr(tempfile, "tempdir", dir):
            yield
    finally:
        support.rmtree(dir)
    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(), [])
Beispiel #8
0
 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_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()
    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(), [])
Beispiel #11
0
    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)
Beispiel #12
0
 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)
Beispiel #13
0
    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)
    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(), [])
Beispiel #15
0
 def test_issue31592(self):
     # There shouldn't be an assertion failure in case of a bad
     # unicodedata.normalize().
     import unicodedata
     def bad_normalize(*args):
         return None
     with support.swap_attr(unicodedata, 'normalize', bad_normalize):
         self.assertRaises(TypeError, ast.parse, '\u03D5')
Beispiel #16
0
    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()
Beispiel #17
0
    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 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)
Beispiel #19
0
 def test_issue31411(self):
     # warn_explicit() shouldn't raise a SystemError in case
     # warnings.onceregistry isn't a dictionary.
     wmod = self.module
     with original_warnings.catch_warnings(module=wmod):
         wmod.filterwarnings('once')
         with support.swap_attr(wmod, 'onceregistry', None):
             with self.assertRaises(TypeError):
                 wmod.warn_explicit('foo', Warning, 'bar', 1, registry=None)
Beispiel #20
0
 def test_apop_REDOS(self):
     # Replace welcome with very long evil welcome.
     # NB The upper bound on welcome length is currently 2048.
     # At this length, evil input makes each apop call take
     # on the order of milliseconds instead of microseconds.
     evil_welcome = b'+OK' + (b'<' * 1000000)
     with test_support.swap_attr(self.client, 'welcome', evil_welcome):
         # The evil welcome is invalid, so apop should throw.
         self.assertRaises(poplib.error_proto, self.client.apop, 'a', 'kb')
Beispiel #21
0
    def test_match_test(self):
        class Test:
            def __init__(self, test_id):
                self.test_id = test_id

            def id(self):
                return self.test_id

        test_access = Test('test.test_os.FileTests.test_access')
        test_chdir = Test('test.test_os.Win32ErrorTests.test_chdir')

        with support.swap_attr(support, '_match_test_func', None):
            # match all
            support.set_match_tests([])
            self.assertTrue(support.match_test(test_access))
            self.assertTrue(support.match_test(test_chdir))

            # match all using None
            support.set_match_tests(None)
            self.assertTrue(support.match_test(test_access))
            self.assertTrue(support.match_test(test_chdir))

            # match the full test identifier
            support.set_match_tests([test_access.id()])
            self.assertTrue(support.match_test(test_access))
            self.assertFalse(support.match_test(test_chdir))

            # match the module name
            support.set_match_tests(['test_os'])
            self.assertTrue(support.match_test(test_access))
            self.assertTrue(support.match_test(test_chdir))

            # Test '*' pattern
            support.set_match_tests(['test_*'])
            self.assertTrue(support.match_test(test_access))
            self.assertTrue(support.match_test(test_chdir))

            # Test case sensitivity
            support.set_match_tests(['filetests'])
            self.assertFalse(support.match_test(test_access))
            support.set_match_tests(['FileTests'])
            self.assertTrue(support.match_test(test_access))

            # Test pattern containing '.' and a '*' metacharacter
            support.set_match_tests(['*test_os.*.test_*'])
            self.assertTrue(support.match_test(test_access))
            self.assertTrue(support.match_test(test_chdir))

            # Multiple patterns
            support.set_match_tests([test_access.id(), test_chdir.id()])
            self.assertTrue(support.match_test(test_access))
            self.assertTrue(support.match_test(test_chdir))

            support.set_match_tests(['test_access', 'DONTMATCH'])
            self.assertTrue(support.match_test(test_access))
            self.assertFalse(support.match_test(test_chdir))
Beispiel #22
0
    def test_issue31492(self):
        # There shouldn't be an assertion failure in case of failing to import
        # from a module with a bad __name__ attribute, or in case of failing
        # to access an attribute of such a module.
        with swap_attr(os, '__name__', None):
            with self.assertRaises(ImportError):
                from os import does_not_exist

            with self.assertRaises(AttributeError):
                os.does_not_exist
Beispiel #23
0
 def test_issue31602(self):
     # There shouldn't be an assertion failure in zipimporter.get_source()
     # in case of a bad zlib.decompress().
     def bad_decompress(*args):
         return None
     with ZipFile(TEMP_ZIP, 'w') as zip_file:
         self.addCleanup(support.unlink, TEMP_ZIP)
         zip_file.writestr('bar.py', b'print("hello world")', ZIP_DEFLATED)
     zi = zipimport.zipimporter(TEMP_ZIP)
     with support.swap_attr(zlib, 'decompress', bad_decompress):
         self.assertRaises(TypeError, zi.get_source, 'bar')
    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)
Beispiel #25
0
    def test_issue31416(self):
        # warn_explicit() shouldn't cause an assertion failure in case of a
        # bad warnings.filters or warnings.defaultaction.
        wmod = self.module
        with original_warnings.catch_warnings(module=wmod):
            wmod.filters = [(None, None, Warning, None, 0)]
            with self.assertRaises(TypeError):
                wmod.warn_explicit('foo', Warning, 'bar', 1)

            wmod.filters = []
            with support.swap_attr(wmod, 'defaultaction', None), \
                 self.assertRaises(TypeError):
                wmod.warn_explicit('foo', Warning, 'bar', 1)
Beispiel #26
0
    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_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])
Beispiel #28
0
    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)
Beispiel #29
0
    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)
Beispiel #30
0
    def test_windows_colon(self):
        with support.swap_attr(server.os, 'path', ntpath):
            path = self.handler.translate_path('c:c:c:foo/filename')
            path = path.replace(ntpath.sep, os.sep)
            self.assertEqual(path, self.translated)

            path = self.handler.translate_path('\\c:../filename')
            path = path.replace(ntpath.sep, os.sep)
            self.assertEqual(path, self.translated)

            path = self.handler.translate_path('c:\\c:..\\foo/filename')
            path = path.replace(ntpath.sep, os.sep)
            self.assertEqual(path, self.translated)

            path = self.handler.translate_path('c:c:foo\\c:c:bar/filename')
            path = path.replace(ntpath.sep, os.sep)
            self.assertEqual(path, self.translated)
    def test_windows_colon(self):
        with support.swap_attr(server.os, 'path', ntpath):
            path = self.handler.translate_path('c:c:c:foo/filename')
            path = path.replace(ntpath.sep, os.sep)
            self.assertEqual(path, self.translated)

            path = self.handler.translate_path('\\c:../filename')
            path = path.replace(ntpath.sep, os.sep)
            self.assertEqual(path, self.translated)

            path = self.handler.translate_path('c:\\c:..\\foo/filename')
            path = path.replace(ntpath.sep, os.sep)
            self.assertEqual(path, self.translated)

            path = self.handler.translate_path('c:c:foo\\c:c:bar/filename')
            path = path.replace(ntpath.sep, os.sep)
            self.assertEqual(path, self.translated)
Beispiel #32
0
    def test_find_mac(self):
        data = '''\

fake hwaddr
cscotun0  Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
eth0      Link encap:Ethernet  HWaddr 12:34:56:78:90:ab
'''
        def mock_popen(cmd):
            return io.StringIO(data)

        with support.swap_attr(os, 'popen', mock_popen):
            mac = uuid._find_mac(
                command='ifconfig',
                args='',
                hw_identifiers=['hwaddr'],
                get_index=lambda x: x + 1,
            )
            self.assertEqual(mac, 0x1234567890ab)
Beispiel #33
0
    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])
Beispiel #34
0
    def test_reap_children(self):
        # Make sure that there is no other pending child process
        support.reap_children()

        # Create a child process
        pid = os.fork()
        if pid == 0:
            # child process: do nothing, just exit
            os._exit(0)

        t0 = time.monotonic()
        deadline = time.monotonic() + support.SHORT_TIMEOUT

        was_altered = support.environment_altered
        try:
            support.environment_altered = False
            stderr = io.StringIO()

            while True:
                if time.monotonic() > deadline:
                    self.fail("timeout")

                with support.swap_attr(support.print_warning, 'orig_stderr',
                                       stderr):
                    support.reap_children()

                # Use environment_altered to check if reap_children() found
                # the child process
                if support.environment_altered:
                    break

                # loop until the child process completed
                time.sleep(0.100)

            msg = "Warning -- reap_children() reaped child process %s" % pid
            self.assertIn(msg, stderr.getvalue())
            self.assertTrue(support.environment_altered)
        finally:
            support.environment_altered = was_altered

        # Just in case, check again that there is no other
        # pending child process
        support.reap_children()
Beispiel #35
0
    def test_find_mac(self):
        data = '''\

fake hwaddr
cscotun0  Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
eth0      Link encap:Ethernet  HWaddr 12:34:56:78:90:ab
'''

        def mock_popen(cmd):
            return io.StringIO(data)

        with support.swap_attr(os, 'popen', mock_popen):
            mac = uuid._find_mac(
                command='ifconfig',
                args='',
                hw_identifiers=['hwaddr'],
                get_index=lambda x: x + 1,
            )
            self.assertEqual(mac, 0x1234567890ab)
    def test_showinfo(self):
        def test_callback(dialog, master):
            nonlocal ismapped
            master.update()
            ismapped = master.winfo_ismapped()
            raise ZeroDivisionError

        with swap_attr(Dialog, '_test_callback', test_callback):
            ismapped = None
            self.assertRaises(ZeroDivisionError, showinfo, "Spam", "Egg Information")
            self.assertEqual(ismapped, False)

            root = tkinter.Tk()
            ismapped = None
            self.assertRaises(ZeroDivisionError, showinfo, "Spam", "Egg Information")
            self.assertEqual(ismapped, True)
            root.destroy()

            tkinter.NoDefaultRoot()
            self.assertRaises(RuntimeError, showinfo, "Spam", "Egg Information")
Beispiel #37
0
    def test_custom_excepthook(self):
        args = None

        def hook(hook_args):
            nonlocal args
            args = hook_args

        try:
            with support.swap_attr(threading, 'excepthook', hook):
                thread = ThreadRunFail()
                thread.start()
                thread.join()

            self.assertEqual(args.exc_type, ValueError)
            self.assertEqual(str(args.exc_value), 'run failed')
            self.assertEqual(args.exc_traceback, args.exc_value.__traceback__)
            self.assertIs(args.thread, thread)
        finally:
            # Break reference cycle
            args = None
Beispiel #38
0
    def test_askinteger(self):
        @staticmethod
        def mock_wait_window(w):
            nonlocal ismapped
            ismapped = w.master.winfo_ismapped()
            w.destroy()

        with swap_attr(Dialog, 'wait_window', mock_wait_window):
            ismapped = None
            askinteger("Go To Line", "Line number")
            self.assertEqual(ismapped, False)

            root = tkinter.Tk()
            ismapped = None
            askinteger("Go To Line", "Line number")
            self.assertEqual(ismapped, True)
            root.destroy()

            tkinter.NoDefaultRoot()
            self.assertRaises(RuntimeError, askinteger, "Go To Line", "Line number")
Beispiel #39
0
    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)
Beispiel #40
0
    def test_record_override_showwarning_before(self):
        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)

        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, [])
Beispiel #41
0
    def test_find_mac(self):
        data = '''\

fake hwaddr
cscotun0  Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
eth0      Link encap:Ethernet  HWaddr 12:34:56:78:90:ab
'''
        def mock_popen(cmd):
            return io.StringIO(data)

        if shutil.which('ifconfig') is None:
            path = os.pathsep.join(('/sbin', '/usr/sbin'))
            if shutil.which('ifconfig', path=path) is None:
                self.skipTest('requires ifconfig')

        with support.swap_attr(os, 'popen', mock_popen):
            mac = uuid._find_mac(
                command='ifconfig',
                args='',
                hw_identifiers=['hwaddr'],
                get_index=lambda x: x + 1,
            )
            self.assertEqual(mac, 0x1234567890ab)
Beispiel #42
0
    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, [])
Beispiel #43
0
    def test_home_not_set(self):
        with os_helper.temp_cwd(None) as 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 os_helper.EnvironmentVarGuard() as environ:
                    environ.set('HOME', fake_home)
                    environ.set('USERPROFILE', 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)
Beispiel #44
0
    def test_read_mime_types(self):
        eq = self.assertEqual

        # Unreadable file returns None
        self.assertIsNone(mimetypes.read_mime_types("non-existent"))

        with os_helper.temp_dir() as directory:
            data = "x-application/x-unittest pyunit\n"
            file = pathlib.Path(directory, "sample.mimetype")
            file.write_text(data)
            mime_dict = mimetypes.read_mime_types(file)
            eq(mime_dict[".pyunit"], "x-application/x-unittest")

        # bpo-41048: read_mime_types should read the rule file with 'utf-8' encoding.
        # Not with locale encoding. _bootlocale has been imported because io.open(...)
        # uses it.
        with os_helper.temp_dir() as directory:
            data = "application/no-mans-land  Fran\u00E7ais"
            file = pathlib.Path(directory, "sample.mimetype")
            file.write_text(data, encoding='utf-8')
            import _bootlocale
            with support.swap_attr(_bootlocale, 'getpreferredencoding', lambda do_setlocale=True: 'ASCII'):
                mime_dict = mimetypes.read_mime_types(file)
            eq(mime_dict[".Français"], "application/no-mans-land")
Beispiel #45
0
 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)
Beispiel #46
0
 def test_very_long_wrapped_line(self):
     with swap_attr(self.shell, 'squeezer', None):
         self.do_input('x = ' + '1'*10_000 + '\n')
         yield
         self.assertEqual(self.get_sidebar_lines(), ['>>>'])
Beispiel #47
0
 def testRecursiveRepr(self):
     # Issue #25455
     with swap_attr(self.f, 'name', self.f):
         with self.assertRaises(RuntimeError):
             repr(self.f)  # Should not crash
Beispiel #48
0
            mime_dict = mimetypes.read_mime_types(file)
            eq(mime_dict[".pyunit"], "x-application/x-unittest")

        # bpo-41048: read_mime_types should read the rule file with 'utf-8' encoding.
        # Not with locale encoding. _bootlocale has been imported because io.open(...)
        # uses it.
<<<<<<< HEAD
        with os_helper.temp_dir() as directory:
=======
        with support.temp_dir() as directory:
>>>>>>> 3.9
            data = "application/no-mans-land  Fran\u00E7ais"
            file = pathlib.Path(directory, "sample.mimetype")
            file.write_text(data, encoding='utf-8')
            import _bootlocale
            with support.swap_attr(_bootlocale, 'getpreferredencoding', lambda do_setlocale=True: 'ASCII'):
                mime_dict = mimetypes.read_mime_types(file)
            eq(mime_dict[".Français"], "application/no-mans-land")

    def test_non_standard_types(self):
        eq = self.assertEqual
        # First try strict
        eq(self.db.guess_type('foo.xul', strict=True), (None, None))
        eq(self.db.guess_extension('image/jpg', strict=True), None)
        # And then non-strict
        eq(self.db.guess_type('foo.xul', strict=False), ('text/xul', None))
        eq(self.db.guess_type('foo.XUL', strict=False), ('text/xul', None))
        eq(self.db.guess_type('foo.invalid', strict=False), (None, None))
        eq(self.db.guess_extension('image/jpg', strict=False), '.jpg')
        eq(self.db.guess_extension('image/JPG', strict=False), '.jpg')
Beispiel #49
0
 def testRecursiveRepr(self):
     with swap_attr(self.f, 'name', self.f):
         with self.assertRaises(RuntimeError):
             repr(self.f)
 def test_nonexisting_directory(self):
     with _inside_empty_temp_dir():
         tempdir = os.path.join(tempfile.tempdir, 'nonexistent')
         with support.swap_attr(tempfile, 'tempdir', tempdir):
             with self.assertRaises(FileNotFoundError):
                 self.make_temp()
Beispiel #51
0
 def test_log_invalid_level_with_raise(self):
     with swap_attr(logging, 'raiseExceptions', True):
         self.assertRaises(TypeError, self.logger.log, '10', 'test message')
Beispiel #52
0
 def test_log_invalid_level_no_raise(self):
     with swap_attr(logging, 'raiseExceptions', False):
         self.logger.log('10', 'test message')  # no exception happens
Beispiel #53
0
    def test_match_test(self):
        class Test:
            def __init__(self, test_id):
                self.test_id = test_id

            def id(self):
                return self.test_id

        test_access = Test('test.test_os.FileTests.test_access')
        test_chdir = Test('test.test_os.Win32ErrorTests.test_chdir')

        # Test acceptance
        with support.swap_attr(support, '_match_test_func', None):
            # match all
            support.set_match_tests([])
            self.assertTrue(support.match_test(test_access))
            self.assertTrue(support.match_test(test_chdir))

            # match all using None
            support.set_match_tests(None, None)
            self.assertTrue(support.match_test(test_access))
            self.assertTrue(support.match_test(test_chdir))

            # match the full test identifier
            support.set_match_tests([test_access.id()], None)
            self.assertTrue(support.match_test(test_access))
            self.assertFalse(support.match_test(test_chdir))

            # match the module name
            support.set_match_tests(['test_os'], None)
            self.assertTrue(support.match_test(test_access))
            self.assertTrue(support.match_test(test_chdir))

            # Test '*' pattern
            support.set_match_tests(['test_*'], None)
            self.assertTrue(support.match_test(test_access))
            self.assertTrue(support.match_test(test_chdir))

            # Test case sensitivity
            support.set_match_tests(['filetests'], None)
            self.assertFalse(support.match_test(test_access))
            support.set_match_tests(['FileTests'], None)
            self.assertTrue(support.match_test(test_access))

            # Test pattern containing '.' and a '*' metacharacter
            support.set_match_tests(['*test_os.*.test_*'], None)
            self.assertTrue(support.match_test(test_access))
            self.assertTrue(support.match_test(test_chdir))

            # Multiple patterns
            support.set_match_tests([test_access.id(), test_chdir.id()], None)
            self.assertTrue(support.match_test(test_access))
            self.assertTrue(support.match_test(test_chdir))

            support.set_match_tests(['test_access', 'DONTMATCH'], None)
            self.assertTrue(support.match_test(test_access))
            self.assertFalse(support.match_test(test_chdir))

        # Test rejection
        with support.swap_attr(support, '_match_test_func', None):
            # match all
            support.set_match_tests(ignore_patterns=[])
            self.assertTrue(support.match_test(test_access))
            self.assertTrue(support.match_test(test_chdir))

            # match all using None
            support.set_match_tests(None, None)
            self.assertTrue(support.match_test(test_access))
            self.assertTrue(support.match_test(test_chdir))

            # match the full test identifier
            support.set_match_tests(None, [test_access.id()])
            self.assertFalse(support.match_test(test_access))
            self.assertTrue(support.match_test(test_chdir))

            # match the module name
            support.set_match_tests(None, ['test_os'])
            self.assertFalse(support.match_test(test_access))
            self.assertFalse(support.match_test(test_chdir))

            # Test '*' pattern
            support.set_match_tests(None, ['test_*'])
            self.assertFalse(support.match_test(test_access))
            self.assertFalse(support.match_test(test_chdir))

            # Test case sensitivity
            support.set_match_tests(None, ['filetests'])
            self.assertTrue(support.match_test(test_access))
            support.set_match_tests(None, ['FileTests'])
            self.assertFalse(support.match_test(test_access))

            # Test pattern containing '.' and a '*' metacharacter
            support.set_match_tests(None, ['*test_os.*.test_*'])
            self.assertFalse(support.match_test(test_access))
            self.assertFalse(support.match_test(test_chdir))

            # Multiple patterns
            support.set_match_tests(None, [test_access.id(), test_chdir.id()])
            self.assertFalse(support.match_test(test_access))
            self.assertFalse(support.match_test(test_chdir))

            support.set_match_tests(None, ['test_access', 'DONTMATCH'])
            self.assertFalse(support.match_test(test_access))
            self.assertTrue(support.match_test(test_chdir))
Beispiel #54
0
 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')
Beispiel #55
0
 def check_print_warning(self, msg, expected):
     stderr = io.StringIO()
     with support.swap_attr(support.print_warning, 'orig_stderr', stderr):
         support.print_warning(msg)
     self.assertEqual(stderr.getvalue(), expected)
Beispiel #56
0
def _mock_candidate_names(*names):
    return support.swap_attr(tempfile,
                             '_get_candidate_names',
                             lambda: iter(names))