Пример #1
0
    def test_check_environ_getpwuid(self):
        util._environ_checked = 0
        os.environ.pop('HOME', None)

        import pwd

        # only set pw_dir field, other fields are not used
        def mock_getpwuid(uid):
            return pwd.struct_passwd(
                (None, None, None, None, None, '/home/distutils', None))

        with swap_attr(pwd, 'getpwuid', mock_getpwuid):
            check_environ()
            self.assertEqual(os.environ['HOME'], '/home/distutils')

        util._environ_checked = 0
        os.environ.pop('HOME', None)

        # bpo-10496: Catch pwd.getpwuid() error
        def getpwuid_err(uid):
            raise KeyError

        with swap_attr(pwd, 'getpwuid', getpwuid_err):
            check_environ()
            self.assertNotIn('HOME', os.environ)
Пример #2
0
    def test_expanduser_pwd(self):
        pwd = support.import_module('pwd')

        self.assertIsInstance(posixpath.expanduser("~/"), str)

        # if home directory == root directory, this test makes no sense
        if posixpath.expanduser("~") != '/':
            self.assertEqual(
                posixpath.expanduser("~") + "/", posixpath.expanduser("~/"))
        self.assertIsInstance(posixpath.expanduser("~root/"), str)
        self.assertIsInstance(posixpath.expanduser("~foo/"), str)

        with support.EnvironmentVarGuard() as env:
            # expanduser should fall back to using the password database
            del env['HOME']

            home = pwd.getpwuid(os.getuid()).pw_dir
            # $HOME can end with a trailing /, so strip it (see #17809)
            home = home.rstrip("/") or '/'
            self.assertEqual(posixpath.expanduser("~"), home)

            # bpo-10496: If the HOME environment variable is not set and the
            # user (current identifier or name in the path) doesn't exist in
            # the password database (pwd.getuid() or pwd.getpwnam() fail),
            # expanduser() must return the path unchanged.
            def raise_keyerror(*args):
                raise KeyError

            with support.swap_attr(pwd, 'getpwuid', raise_keyerror), \
                 support.swap_attr(pwd, 'getpwnam', raise_keyerror):
                for path in ('~', '~/.local', '~vstinner/'):
                    self.assertEqual(posixpath.expanduser(path), path)
Пример #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()
Пример #4
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()
Пример #5
0
    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)
Пример #6
0
def _inside_empty_temp_dir():
    dir = tempfile.mkdtemp()
    try:
        with support.swap_attr(tempfile, 'tempdir', dir):
            yield
    finally:
        support.rmtree(dir)
Пример #7
0
 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(OSError) as cm:
                 self.make_temp()
             self.assertEqual(cm.exception.errno, errno.ENOENT)
Пример #8
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.BytesIO(data)

        path = os.environ.get("PATH", os.defpath).split(os.pathsep)
        path.extend(('/sbin', '/usr/sbin'))
        for dir in path:
            executable = os.path.join(dir, 'ifconfig')
            if (os.path.exists(executable)
                    and os.access(executable, os.F_OK | os.X_OK)
                    and not os.path.isdir(executable)):
                break
        else:
            self.skipTest('requires ifconfig')

        with test_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)
Пример #9
0
def _inside_empty_temp_dir():
    dir = tempfile.mkdtemp()
    try:
        with support.swap_attr(tempfile, 'tempdir', dir):
            yield
    finally:
        support.rmtree(dir)
Пример #10
0
    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)
Пример #11
0
 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(OSError) as cm:
                 self.make_temp()
             self.assertEqual(cm.exception.errno, errno.ENOENT)
Пример #12
0
    def run_script(self, input="", args=("-",), substfile="xx yy\n"):
        substfilename = test_support.TESTFN + ".subst"
        with open(substfilename, "w") as file:
            file.write(substfile)
        self.addCleanup(test_support.unlink, substfilename)

        argv = ["fixcid.py", "-s", substfilename] + list(args)
        script = os.path.join(scriptsdir, "fixcid.py")
        with test_support.swap_attr(sys, "argv", argv), \
                test_support.swap_attr(sys, "stdin", StringIO(input)), \
                test_support.captured_stdout() as output:
            try:
                runpy.run_path(script, run_name="__main__")
            except SystemExit as exit:
                self.assertEqual(exit.code, 0)
        return output.getvalue()
Пример #13
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.BytesIO(data)

        path = os.environ.get("PATH", os.defpath).split(os.pathsep)
        path.extend(('/sbin', '/usr/sbin'))
        for dir in path:
            executable = os.path.join(dir, 'ifconfig')
            if (os.path.exists(executable) and
                os.access(executable, os.F_OK | os.X_OK) and
                not os.path.isdir(executable)):
                break
        else:
            self.skipTest('requires ifconfig')

        with test_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)
Пример #14
0
 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(OSError) as cm:
                 self.make_temp()
             self.assertIn(cm.exception.errno, (errno.ENOTDIR, errno.ENOENT))
Пример #15
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))
Пример #16
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))
Пример #17
0
    def test_modify_builtins(self):
        # Modify the __builtin__ module directly.
        def foo():
            return len([1, 2, 3])
        self.configure_func(foo)

        self.assertEqual(foo(), 3)
        with swap_attr(__builtin__, "len", lambda x: 7):
            self.assertEqual(foo(), 7)
Пример #18
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')
Пример #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 test_support.swap_attr(wmod, 'onceregistry', None):
             with self.assertRaises(TypeError):
                 wmod.warn_explicit('foo', Warning, 'bar', 1, registry=None)
Пример #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')
Пример #21
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 test_support.swap_attr(wmod, 'onceregistry', None):
             with self.assertRaises(TypeError):
                 wmod.warn_explicit('foo', Warning, 'bar', 1, registry=None)
Пример #22
0
    def test_modify_builtins(self):
        # Modify the __builtin__ module directly.
        def foo():
            return len([1, 2, 3])

        self.configure_func(foo)

        self.assertEqual(foo(), 3)
        with swap_attr(__builtin__, "len", lambda x: 7):
            self.assertEqual(foo(), 7)
Пример #23
0
    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(g.next(), 3)
        with swap_attr(__builtin__, "len", lambda x: 7):
            self.assertEqual(g.next(), 7)
Пример #24
0
    def test_linetoolong(self):
        maxline = 10

        class TooLongHandler(SimpleIMAPHandler):
            def handle(self):
                # Send a very long response line
                self.wfile.write('* OK ' + maxline * 'x' + '\r\n')

        with self.reaped_server(TooLongHandler) as server, \
                 support.swap_attr(imaplib, '_MAXLINE', maxline):
            with self.assertRaisesRegexp(imaplib.IMAP4.error,
                                         'got more than 10 bytes'):
                self.imap_class(*server.server_address)
Пример #25
0
    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(g.next(), 3)
        with swap_attr(__builtin__, "len", lambda x: 7):
            self.assertEqual(g.next(), 7)
Пример #26
0
    def test_no_files_left_behind(self):
        # use a private empty directory
        our_temp_directory = tempfile.mkdtemp()
        try:
            # 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(-1)

                with support.swap_attr(io, "open", raise_OSError):
                    # test again with failing io.open()
                    with self.assertRaises(IOError) as cm:
                        tempfile._get_default_tempdir()
                    self.assertEqual(cm.exception.errno, errno.ENOENT)
                    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(IOError) as cm:
                        tempfile._get_default_tempdir()
                    self.assertEqual(cm.exception.errno, errno.ENOENT)
                    self.assertEqual(os.listdir(our_temp_directory), [])
        finally:
            shutil.rmtree(our_temp_directory)
Пример #27
0
    def test_no_files_left_behind(self):
        # use a private empty directory
        our_temp_directory = tempfile.mkdtemp()
        try:
            # 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(-1)

                with support.swap_attr(io, "open", raise_OSError):
                    # test again with failing io.open()
                    with self.assertRaises(IOError) as cm:
                        tempfile._get_default_tempdir()
                    self.assertEqual(cm.exception.errno, errno.ENOENT)
                    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(IOError) as cm:
                        tempfile._get_default_tempdir()
                    self.assertEqual(cm.exception.errno, errno.ENOENT)
                    self.assertEqual(os.listdir(our_temp_directory), [])
        finally:
            shutil.rmtree(our_temp_directory)
Пример #28
0
    def test_parse_close_source(self):
        builtin_open = open
        non_local = {'fileobj': None}

        def mock_open(*args):
            fileobj = builtin_open(*args)
            non_local['fileobj'] = fileobj
            return fileobj

        with support.swap_attr(saxutils, 'open', mock_open):
            make_xml_file(self.data, 'iso-8859-1', None)
            with self.assertRaises(SAXException):
                self.check_parse(TESTFN)
            self.assertTrue(non_local['fileobj'].closed)
Пример #29
0
    def test_parse_close_source(self):
        builtin_open = open
        non_local = {'fileobj': None}

        def mock_open(*args):
            fileobj = builtin_open(*args)
            non_local['fileobj'] = fileobj
            return fileobj

        with support.swap_attr(saxutils, 'open', mock_open):
            make_xml_file(self.data, 'iso-8859-1', None)
            with self.assertRaises(SAXException):
                self.check_parse(TESTFN)
            self.assertTrue(non_local['fileobj'].closed)
Пример #30
0
    def test_modify_builtins_from_leaf_function(self):
        # Verify that modifications made by leaf functions percolate up the
        # callstack.
        with swap_attr(__builtin__, "len", len):
            def bar():
                __builtin__.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])
Пример #31
0
    def test_override_builtin(self):
        # Test that overriding __builtin__.__import__ can bypass sys.modules.
        import os

        def foo():
            import os
            return os
        self.assertEqual(foo(), os)  # Quick sanity check.

        with test_support.swap_attr(__builtin__, "__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 test_support.swap_item(globals(), "__import__", lambda *x: 5):
            self.assertEqual(foo(), os)
Пример #32
0
    def test_windows_colon(self):
        import SimpleHTTPServer
        with test_support.swap_attr(SimpleHTTPServer.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)
Пример #33
0
    def test_modify_builtins_from_leaf_function(self):
        # Verify that modifications made by leaf functions percolate up the
        # callstack.
        with swap_attr(__builtin__, "len", len):

            def bar():
                __builtin__.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])
Пример #34
0
    def test_windows_colon(self):
        import SimpleHTTPServer
        with test_support.swap_attr(SimpleHTTPServer.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)
Пример #35
0
    def test_override_builtin(self):
        # Test that overriding __builtin__.__import__ can bypass sys.modules.
        import os

        def foo():
            import os
            return os

        self.assertEqual(foo(), os)  # Quick sanity check.

        with test_support.swap_attr(__builtin__, "__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 test_support.swap_item(globals(), "__import__", lambda *x: 5):
            self.assertEqual(foo(), os)
Пример #36
0
def _mock_candidate_names(*names):
    return support.swap_attr(tempfile, '_get_candidate_names',
                             lambda: iter(names))
Пример #37
0
def _mock_candidate_names(*names):
    return support.swap_attr(tempfile,
                             '_get_candidate_names',
                             lambda: iter(names))