Esempio n. 1
0
 def test_options_no_site_import(self):
     with test_support.temp_cwd() as temp_cwd:
         self.assertEqual(
             subprocess.check_output(
                 [sys.executable, "-S", "-c",
                  "import sys; print sorted(sys.modules.keys())"]).strip(),
             "['__builtin__', '__main__', 'exceptions', 'sys']")
Esempio n. 2
0
 def test_readlink_nonexistent(self):
     with test_support.temp_cwd() as new_cwd:
         nonexistent_file = os.path.join(new_cwd, "nonexistent-file")
         with self.assertRaises(OSError) as cm:
             os.readlink(nonexistent_file)
         self.assertEqual(cm.exception.errno, errno.ENOENT)
         self.assertEqual(cm.exception.filename, nonexistent_file)
Esempio n. 3
0
 def test_getcwd(self):
     with test_support.temp_cwd(name=u"tempcwd-中文") as temp_cwd:
         p = subprocess.Popen([sys.executable, "-c",
                               'import sys,os;' \
                               'sys.stdout.write(os.getcwd().encode("utf-8"))'],
                              stdout=subprocess.PIPE)
         self.assertEqual(p.stdout.read().decode("utf-8"), temp_cwd)
Esempio n. 4
0
 def test_getcwd(self):
     with test_support.temp_cwd(name=u"tempcwd-中文") as temp_cwd:
         p = subprocess.Popen([sys.executable, "-c",
                               'import sys,os;' \
                               'sys.stdout.write(os.getcwd().encode("utf-8"))'],
                              stdout=subprocess.PIPE)
         self.assertEqual(p.stdout.read().decode("utf-8"), temp_cwd)
Esempio n. 5
0
 def test_relpath(self):
     tester('ntpath.relpath("a")', 'a')
     tester('ntpath.relpath(os.path.abspath("a"))', 'a')
     tester('ntpath.relpath("a/b")', 'a\\b')
     tester('ntpath.relpath("../a/b")', '..\\a\\b')
     with test_support.temp_cwd(test_support.TESTFN) as cwd_dir:
         currentdir = os.path.basename(cwd_dir)
         tester('ntpath.relpath("a", "../b")', '..\\' + currentdir + '\\a')
         tester('ntpath.relpath("a/b", "../c")',
                '..\\' + currentdir + '\\a\\b')
     tester('ntpath.relpath("a", "b/c")', '..\\..\\a')
     tester(
         'ntpath.relpath("//conky/mountpoint/a", "//conky/mountpoint/b/c")',
         '..\\..\\a')
     tester('ntpath.relpath("a", "a")', '.')
     tester('ntpath.relpath("/foo/bar/bat", "/x/y/z")',
            '..\\..\\..\\foo\\bar\\bat')
     tester('ntpath.relpath("/foo/bar/bat", "/foo/bar")', 'bat')
     tester('ntpath.relpath("/foo/bar/bat", "/")', 'foo\\bar\\bat')
     tester('ntpath.relpath("/", "/foo/bar/bat")', '..\\..\\..')
     tester('ntpath.relpath("/foo/bar/bat", "/x")', '..\\foo\\bar\\bat')
     tester('ntpath.relpath("/x", "/foo/bar/bat")', '..\\..\\..\\x')
     tester('ntpath.relpath("/", "/")', '.')
     tester('ntpath.relpath("/a", "/a")', '.')
     tester('ntpath.relpath("/a/b", "/a/b")', '.')
     tester('ntpath.relpath("c:/foo", "C:/FOO")', '.')
Esempio n. 6
0
 def test_readlink_nonexistent(self):
     with test_support.temp_cwd() as new_cwd:
         nonexistent_file = os.path.join(new_cwd, "nonexistent-file")
         with self.assertRaises(OSError) as cm:
             os.readlink(nonexistent_file)
         self.assertEqual(cm.exception.errno, errno.ENOENT)
         self.assertEqual(cm.exception.filename, nonexistent_file)
    def test_compileall(self):
        with temp_cwd():
            PACKAGE = os.path.realpath("./greetings")
            PYC_GREETER = os.path.join(PACKAGE, "greeter.pyc")
            PYCLASS_GREETER = os.path.join(PACKAGE, "greeter$py.class")
            PYCLASS_TEST = os.path.join(PACKAGE, "test$py.class")            

            os.mkdir(PACKAGE)
            self.write_code(
                PACKAGE, "greeter.py",
                """
                def greet():
                    print 'Hello world!'
                """)
            self.write_code(
                PACKAGE, "test.py",
                """
                from greeter import greet
                greet()
                """)

            # pretend we have a Python bytecode compiler by touching this file
            open(PYC_GREETER, "a").close()
            
            compileall.compile_dir(PACKAGE, quiet=True)
            self.assertTrue(os.path.exists(PYC_GREETER))     # still exists
            self.assertTrue(os.path.exists(PYCLASS_TEST))    # along with these new compiled files
            self.assertTrue(os.path.exists(PYCLASS_GREETER))

            # verify we can work with just compiled files
            os.unlink(os.path.join(PACKAGE, "greeter.py"))
            self.assertEqual(
                subprocess.check_output([sys.executable, os.path.join(PACKAGE, "test.py")]).rstrip(),
                "Hello world!")
Esempio n. 8
0
    def test_compileall(self):
        with temp_cwd():
            PACKAGE = os.path.realpath("./greetings")
            PYC_GREETER = os.path.join(PACKAGE, "greeter.pyc")
            PYCLASS_GREETER = os.path.join(PACKAGE, "greeter$py.class")
            PYCLASS_TEST = os.path.join(PACKAGE, "test$py.class")

            os.mkdir(PACKAGE)
            self.write_code(
                PACKAGE, "greeter.py", """
                def greet():
                    print 'Hello world!'
                """)
            self.write_code(
                PACKAGE, "test.py", """
                from greeter import greet
                greet()
                """)

            # pretend we have a Python bytecode compiler by touching this file
            open(PYC_GREETER, "a").close()

            compileall.compile_dir(PACKAGE, quiet=True)
            self.assertTrue(os.path.exists(PYC_GREETER))  # still exists
            self.assertTrue(os.path.exists(
                PYCLASS_TEST))  # along with these new compiled files
            self.assertTrue(os.path.exists(PYCLASS_GREETER))

            # verify we can work with just compiled files
            os.unlink(os.path.join(PACKAGE, "greeter.py"))
            self.assertEqual(
                subprocess.check_output(
                    [sys.executable,
                     os.path.join(PACKAGE, "test.py")]).rstrip(),
                "Hello world!")
Esempio n. 9
0
 def test_property_no_site_import(self):
     # only the minimal set of modules are imported
     with test_support.temp_cwd() as temp_cwd:
         self.assertEqual(
             subprocess.check_output(
                 [sys.executable, "-Dpython.import.site=false", "-c",
                  "import sys; print sorted(sys.modules.keys())"]).strip(),
             "['__builtin__', '__main__', 'exceptions', 'sys']")
Esempio n. 10
0
 def test_directory(self):
     dirname = os.path.join(test_support.TESTFN,
                            u'Gr\xfc\xdf-\u66e8\u66e9\u66eb')
     filename = u'\xdf-\u66e8\u66e9\u66eb'
     with test_support.temp_cwd(dirname):
         with open(filename, 'w') as f:
             f.write((filename + '\n').encode("utf-8"))
         os.access(filename,os.R_OK)
         os.remove(filename)
Esempio n. 11
0
 def test_link(self):
     with test_support.temp_cwd() as new_cwd:
         target = os.path.join(new_cwd, "target")
         with open(target, "w") as f:
             f.write("TARGET")
         source = os.path.join(new_cwd, "source")
         os.link(target, source)
         with open(source, "r") as f:
             self.assertEqual(f.read(), "TARGET")
Esempio n. 12
0
 def test_link(self):
     with test_support.temp_cwd() as new_cwd:
         target = os.path.join(new_cwd, "target")
         with open(target, "w") as f:
             f.write("TARGET")
         source = os.path.join(new_cwd, "source")
         os.link(target, source)
         with open(source, "r") as f:
             self.assertEqual(f.read(), "TARGET")
Esempio n. 13
0
 def test_bad_symlink(self):
     with test_support.temp_cwd() as new_cwd:
         target = os.path.join(new_cwd, "target")
         with open(target, "w") as f:
             f.write("TARGET")
         source = os.path.join(new_cwd, "source")
         with self.assertRaises(OSError) as cm:
             os.symlink(source, target)  # reversed args!
         self.assertEqual(cm.exception.errno, errno.EEXIST)
Esempio n. 14
0
 def test_directory(self):
     dirname = os.path.join(test_support.TESTFN,
                            u'Gr\xfc\xdf-\u66e8\u66e9\u66eb')
     filename = u'\xdf-\u66e8\u66e9\u66eb'
     with test_support.temp_cwd(dirname):
         with open(filename, 'w') as f:
             f.write((filename + '\n').encode("utf-8"))
         os.access(filename, os.R_OK)
         os.remove(filename)
Esempio n. 15
0
 def test_bad_symlink(self):
     with test_support.temp_cwd() as new_cwd:
         target = os.path.join(new_cwd, "target")
         with open(target, "w") as f:
             f.write("TARGET")
         source = os.path.join(new_cwd, "source")
         with self.assertRaises(OSError) as cm:
             os.symlink(source, target)  # reversed args!
         self.assertEqual(cm.exception.errno, errno.EEXIST)
Esempio n. 16
0
 def test_readlink(self):
     with test_support.temp_cwd() as new_cwd:
         target = os.path.join(new_cwd, "target")
         with open(target, "w") as f:
             f.write("TARGET")
         source = os.path.join(new_cwd, "source")
         os.symlink(target, source)
         self.assertEqual(os.readlink(source), target)
         self.assertEqual(os.readlink(unicode(source)), unicode(target))
         self.assertIsInstance(os.readlink(unicode(source)), unicode)
Esempio n. 17
0
 def test_getcwd(self):
     with test_support.temp_cwd(name=u"tempcwd-中文") as temp_cwd:
         # os.getcwd reports the working directory as an FS-encoded str,
         # which is also the encoding used in subprocess communication.
         p = subprocess.Popen([
                 sys.executable, "-c",
                 'import sys,os;' \
                 'sys.stdout.write(os.getcwd())'],
             stdout=subprocess.PIPE)
         self.assertEqual(p.stdout.read(), temp_cwd)
Esempio n. 18
0
 def test_empty_python_home(self):
     # http://bugs.jython.org/issue2283
     with test_support.temp_cwd() as temp_cwd:
         # using a new directory ensures no Lib/ directory is available
         self.assertEqual(
             subprocess.check_output(
                 [sys.executable, "-Dpython.home=", "-c",
                  "import os; os.system('echo 42'); os.system('echo 47')"])\
             .replace("\r", ""),  # in case of running on Windows
             "42\n47\n")
Esempio n. 19
0
 def test_readlink(self):
     with test_support.temp_cwd() as new_cwd:
         target = os.path.join(new_cwd, "target")
         with open(target, "w") as f:
             f.write("TARGET")
         source = os.path.join(new_cwd, "source")
         os.symlink(target, source)
         self.assertEqual(os.readlink(source), target)
         self.assertEqual(os.readlink(unicode(source)), unicode(target))
         self.assertIsInstance(os.readlink(unicode(source)), unicode)
Esempio n. 20
0
 def test_env(self):
     with test_support.temp_cwd(name=u"tempcwd-中文"):
         newenv = os.environ.copy()
         newenv["TEST_HOME"] = u"首页"
         p = subprocess.Popen([sys.executable, "-c",
                               'import sys,os;' \
                               'sys.stdout.write(os.getenv("TEST_HOME").encode("utf-8"))'],
                              stdout=subprocess.PIPE,
                              env=newenv)
         self.assertEqual(p.stdout.read().decode("utf-8"), u"首页")
Esempio n. 21
0
 def test_getcwd(self):
     with test_support.temp_cwd(name=u"tempcwd-中文") as temp_cwd:
         # os.getcwd reports the working directory as an FS-encoded str,
         # which is also the encoding used in subprocess communication.
         p = subprocess.Popen([
                 sys.executable, "-c",
                 'import sys,os;' \
                 'sys.stdout.write(os.getcwd())'],
             stdout=subprocess.PIPE)
         self.assertEqual(p.stdout.read(), temp_cwd)
Esempio n. 22
0
 def test_getcwdu(self):
     with test_support.temp_cwd(name=u"tempcwd-中文") as temp_cwd:
         # os.getcwdu reports the working directory as unicode,
         # which must be encoded for subprocess communication.
         p = subprocess.Popen([
                 sys.executable, "-c",
                 'import sys,os;' \
                 'sys.stdout.write(os.getcwdu().encode(sys.getfilesystemencoding()))'],
             stdout=subprocess.PIPE)
         self.assertEqual(p.stdout.read(), temp_cwd)
Esempio n. 23
0
 def test_getcwdu(self):
     with test_support.temp_cwd(name=u"tempcwd-中文") as temp_cwd:
         # os.getcwdu reports the working directory as unicode,
         # which must be encoded for subprocess communication.
         p = subprocess.Popen([
                 sys.executable, "-c",
                 'import sys,os;' \
                 'sys.stdout.write(os.getcwdu().encode(sys.getfilesystemencoding()))'],
             stdout=subprocess.PIPE)
         self.assertEqual(p.stdout.read(), temp_cwd)
Esempio n. 24
0
 def test_env(self):
     with test_support.temp_cwd(name=u"tempcwd-中文"):
         newenv = os.environ.copy()
         newenv["TEST_HOME"] = u"首页"
         p = subprocess.Popen([sys.executable, "-c",
                               'import sys,os;' \
                               'sys.stdout.write(os.getenv("TEST_HOME").encode("utf-8"))'],
                              stdout=subprocess.PIPE,
                              env=newenv)
         self.assertEqual(p.stdout.read().decode("utf-8"), u"首页")
Esempio n. 25
0
 def test_unicode_argv(self):
     # Unicode roundtrips successfully through sys.argv arguments
     zhongwen = u'\u4e2d\u6587'
     with test_support.temp_cwd(name=u"tempcwd-%s" % zhongwen):
         p = subprocess.Popen(
             [sys.executable, '-c',
              'import sys;' \
              'sys.stdout.write(sys.argv[1].encode("utf-8"))',
              zhongwen],
             stdout=subprocess.PIPE)
         self.assertEqual(p.stdout.read().decode("utf-8"), zhongwen)
Esempio n. 26
0
 def test_readlink_non_symlink(self):
     """os.readlink of a non symbolic link should raise an error"""
     # test for http://bugs.jython.org/issue2292
     with test_support.temp_cwd() as new_cwd:
         target = os.path.join(new_cwd, "target")
         with open(target, "w") as f:
             f.write("TARGET")
         with self.assertRaises(OSError) as cm:
             os.readlink(target)
         self.assertEqual(cm.exception.errno, errno.EINVAL)
         self.assertEqual(cm.exception.filename, target)
Esempio n. 27
0
 def test_readlink_non_symlink(self):
     """os.readlink of a non symbolic link should raise an error"""
     # test for http://bugs.jython.org/issue2292
     with test_support.temp_cwd() as new_cwd:
         target = os.path.join(new_cwd, "target")
         with open(target, "w") as f:
             f.write("TARGET")
         with self.assertRaises(OSError) as cm:
             os.readlink(target)
         self.assertEqual(cm.exception.errno, errno.EINVAL)
         self.assertEqual(cm.exception.filename, target)
Esempio n. 28
0
 def test_bad_python_home(self):
     # http://bugs.jython.org/issue2283
     with test_support.temp_cwd() as temp_cwd:
         os.makedirs(os.path.join(temp_cwd, "Lib"))
         with self.assertRaises(subprocess.CalledProcessError) as cm:
             subprocess.check_output(
                 [sys.executable, "-Dpython.home=%s" % temp_cwd, "-c",
                  "print 42"],
                 stderr=subprocess.STDOUT)
         self.assertIn(
             'Exception in thread "main" ImportError: Cannot import site module and its dependencies: No module named site',
             cm.exception.output)
Esempio n. 29
0
    def test_listdir(self):
        # It is hard to avoid Unicode paths on systems like OS X. Use
        # relative paths from a temp CWD to work around this
        with test_support.temp_cwd() as new_cwd:
            unicode_path = os.path.join(".", "unicode")
            self.assertIs(type(unicode_path), str)
            chinese_path = os.path.join(unicode_path, u"中文")
            self.assertIs(type(chinese_path), unicode)
            home_path = os.path.join(chinese_path, u"首页")
            os.makedirs(home_path)
            
            with open(os.path.join(home_path, "test.txt"), "w") as test_file:
                test_file.write("42\n")

            # Verify works with str paths, returning Unicode as necessary
            entries = os.listdir(unicode_path)
            self.assertIn(u"中文", entries)

            # Verify works with Unicode paths
            entries = os.listdir(chinese_path)
            self.assertIn(u"首页", entries)
           
            # glob.glob builds on os.listdir; note that we don't use
            # Unicode paths in the arg to glob
            self.assertEqual(
                glob.glob(os.path.join("unicode", "*")),
                [os.path.join(u"unicode", u"中文")])
            self.assertEqual(
                glob.glob(os.path.join("unicode", "*", "*")),
                [os.path.join(u"unicode", u"中文", u"首页")])
            self.assertEqual(
                glob.glob(os.path.join("unicode", "*", "*", "*")),
                [os.path.join(u"unicode", u"中文", u"首页", "test.txt")])

            # Now use a Unicode path as well as in the glob arg
            self.assertEqual(
                glob.glob(os.path.join(u"unicode", "*")),
                [os.path.join(u"unicode", u"中文")])
            self.assertEqual(
                glob.glob(os.path.join(u"unicode", "*", "*")),
                [os.path.join(u"unicode", u"中文", u"首页")])
            self.assertEqual(
                glob.glob(os.path.join(u"unicode", "*", "*", "*")),
                [os.path.join(u"unicode", u"中文", u"首页", "test.txt")])
 
            # Verify Java integration. But we will need to construct
            # an absolute path since chdir doesn't work with Java
            # (except for subprocesses, like below in test_env)
            for entry in entries:
                entry_path = os.path.join(new_cwd, chinese_path, entry)
                f = File(entry_path)
                self.assertTrue(f.exists(), "File %r (%r) should be testable for existence" % (
                    f, entry_path))
Esempio n. 30
0
    def test_listdir(self):
        # It is hard to avoid Unicode paths on systems like OS X. Use
        # relative paths from a temp CWD to work around this
        with test_support.temp_cwd() as new_cwd:
            unicode_path = os.path.join(".", "unicode")
            self.assertIs(type(unicode_path), str)
            chinese_path = os.path.join(unicode_path, u"中文")
            self.assertIs(type(chinese_path), unicode)
            home_path = os.path.join(chinese_path, u"首页")
            os.makedirs(home_path)

            with open(os.path.join(home_path, "test.txt"), "w") as test_file:
                test_file.write("42\n")

            # Verify works with str paths, returning Unicode as necessary
            entries = os.listdir(unicode_path)
            self.assertIn(u"中文", entries)

            # Verify works with Unicode paths
            entries = os.listdir(chinese_path)
            self.assertIn(u"首页", entries)

            # glob.glob builds on os.listdir; note that we don't use
            # Unicode paths in the arg to glob
            self.assertEqual(
                glob.glob(os.path.join("unicode", "*")),
                [os.path.join(u"unicode", u"中文")])
            self.assertEqual(
                glob.glob(os.path.join("unicode", "*", "*")),
                [os.path.join(u"unicode", u"中文", u"首页")])
            self.assertEqual(
                glob.glob(os.path.join("unicode", "*", "*", "*")),
                [os.path.join(u"unicode", u"中文", u"首页", "test.txt")])

            # Now use a Unicode path as well as in the glob arg
            self.assertEqual(
                glob.glob(os.path.join(u"unicode", "*")),
                [os.path.join(u"unicode", u"中文")])
            self.assertEqual(
                glob.glob(os.path.join(u"unicode", "*", "*")),
                [os.path.join(u"unicode", u"中文", u"首页")])
            self.assertEqual(
                glob.glob(os.path.join(u"unicode", "*", "*", "*")),
                [os.path.join(u"unicode", u"中文", u"首页", "test.txt")])

            # Verify Java integration. But we will need to construct
            # an absolute path since chdir doesn't work with Java
            # (except for subprocesses, like below in test_env)
            for entry in entries:
                entry_path = os.path.join(new_cwd, chinese_path, entry)
                f = File(entry_path)
                self.assertTrue(f.exists(), "File %r (%r) should be testable for existence" % (
                    f, entry_path))
Esempio n. 31
0
    def test_bad_link(self):
        with test_support.temp_cwd() as new_cwd:
            target = os.path.join(new_cwd, "target")
            with open(target, "w") as f:
                f.write("TARGET")
            source = os.path.join(new_cwd, "source")
            with self.assertRaises(OSError) as cm:
                os.link(target, target)
            self.assertEqual(cm.exception.errno, errno.EEXIST)

            with self.assertRaises(OSError) as cm:
                os.link("nonexistent-file", source)
            self.assertEqual(cm.exception.errno, errno.ENOENT)
Esempio n. 32
0
    def test_bad_link(self):
        with test_support.temp_cwd() as new_cwd:
            target = os.path.join(new_cwd, "target")
            with open(target, "w") as f:
                f.write("TARGET")
            source = os.path.join(new_cwd, "source")
            with self.assertRaises(OSError) as cm:
                os.link(target, target)
            self.assertEqual(cm.exception.errno, errno.EEXIST)

            with self.assertRaises(OSError) as cm:
                os.link("nonexistent-file", source)
            self.assertEqual(cm.exception.errno, errno.ENOENT)
Esempio n. 33
0
 def test_env_naively(self):
     with test_support.temp_cwd(name=u"tempcwd-中文"):
         # os.environ is constructed with FS-encoded values (as in CPython),
         # but it will accept unicode additions.
         newenv = os.environ.copy()
         newenv["TEST_HOME"] = expected = u"首页"
         # Environment passed as UTF-16 String[] by Java, arrives FS-encoded.
         # However, emit TEST_HOME without thinking about the encoding.
         p = subprocess.Popen(
                 [sys.executable, "-c",
                         'import sys, os;' \
                         'sys.stdout.write(os.getenv("TEST_HOME"))'],
                 stdout=subprocess.PIPE,
                 env=newenv)
         # Decode with FS encoding used by subprocess communication
         self.assertEqual(p.stdout.read().decode('utf-8'), expected)
Esempio n. 34
0
 def test_env_naively(self):
     with test_support.temp_cwd(name=u"tempcwd-中文"):
         # os.environ is constructed with FS-encoded values (as in CPython),
         # but it will accept unicode additions.
         newenv = os.environ.copy()
         newenv["TEST_HOME"] = expected = u"首页"
         # Environment passed as UTF-16 String[] by Java, arrives FS-encoded.
         # However, emit TEST_HOME without thinking about the encoding.
         p = subprocess.Popen(
                 [sys.executable, "-c",
                         'import sys, os;' \
                         'sys.stdout.write(os.getenv("TEST_HOME"))'],
                 stdout=subprocess.PIPE,
                 env=newenv)
         # Decode with FS encoding used by subprocess communication
         self.assertEqual(p.stdout.read().decode('utf-8'), expected)
Esempio n. 35
0
 def test_system_no_site_import(self):
     # If not importing site (-S), importing traceback previously
     # would fail with an import error due to creating a circular
     # import chain. This root cause is because the os module
     # imports the subprocess module for the system function; but
     # the subprocess module imports from os. Verifies that this is
     # managed by making the import late; also verify the
     # monkeypatching optimization is successful by calling
     # os.system twice.
     with test_support.temp_cwd() as temp_cwd:
         self.assertEqual(
             subprocess.check_output(
                 [sys.executable, "-S", "-c",
                  "import traceback; import os; os.system('echo 42'); os.system('echo 47')"])\
             .replace("\r", ""),  # in case of running on Windows
             "42\n47\n")
Esempio n. 36
0
 def test_system_uses_os_environ(self):
     """Writing to os.environ is made available as env vars in os.system subprocesses"""
     # This test likely requires additional customization for
     # environments like AS/400, but I do not have current access.
     # Verifies fix for http://bugs.jython.org/issue2416
     if os._name == "nt":
         echo_command = 'echo %TEST_ENVVAR%'
     else:
         echo_command = 'echo $TEST_ENVVAR'
     with test_support.temp_cwd() as temp_cwd:
         self.assertEqual(
             subprocess.check_output(
                 [sys.executable, "-c",
                  "import os; os.environ['TEST_ENVVAR'] = 'works on 2.7.1+'; os.system('%s')" % echo_command])\
             .replace("\r", ""),  # in case of running on Windows
             "works on 2.7.1+\n")
Esempio n. 37
0
 def test_system_no_site_import(self):
     # If not importing site (-S), importing traceback previously
     # would fail with an import error due to creating a circular
     # import chain. This root cause is because the os module
     # imports the subprocess module for the system function; but
     # the subprocess module imports from os. Verifies that this is
     # managed by making the import late; also verify the
     # monkeypatching optimization is successful by calling
     # os.system twice.
     with test_support.temp_cwd() as temp_cwd:
         self.assertEqual(
             subprocess.check_output(
                 [sys.executable, "-S", "-c",
                  "import traceback; import os; os.system('echo 42'); os.system('echo 47')"])\
             .replace("\r", ""),  # in case of running on Windows
             "42\n47\n")
Esempio n. 38
0
 def test_system_uses_os_environ(self):
     """Writing to os.environ is made available as env vars in os.system subprocesses"""
     # This test likely requires additional customization for
     # environments like AS/400, but I do not have current access.
     # Verifies fix for http://bugs.jython.org/issue2416
     if os._name == "nt":
         echo_command = 'echo %TEST_ENVVAR%'
     else:
         echo_command = 'echo $TEST_ENVVAR'
     with test_support.temp_cwd() as temp_cwd:
         self.assertEqual(
             subprocess.check_output(
                 [sys.executable, "-c",
                  "import os; os.environ['TEST_ENVVAR'] = 'works on 2.7.1+'; os.system('%s')" % echo_command])\
             .replace("\r", ""),  # in case of running on Windows
             "works on 2.7.1+\n")
Esempio n. 39
0
    def test_abspath_issue3426(self):
        # Check that abspath returns unicode when the arg is unicode
        # with both ASCII and non-ASCII cwds.
        abspath = self.pathmodule.abspath
        for path in (u'', u'fuu', u'f\xf9\xf9', u'/fuu', u'U:\\'):
            self.assertIsInstance(abspath(path), unicode)

        unicwd = u'\xe7w\xf0'
        try:
            fsencoding = test_support.TESTFN_ENCODING or "ascii"
            unicwd.encode(fsencoding)
        except (AttributeError, UnicodeEncodeError):
            # FS encoding is probably ASCII
            pass
        else:
            with test_support.temp_cwd(unicwd):
                for path in (u'', u'fuu', u'f\xf9\xf9', u'/fuu', u'U:\\'):
                    self.assertIsInstance(abspath(path), unicode)
Esempio n. 40
0
    def test_abspath_issue3426(self):
        # Check that abspath returns unicode when the arg is unicode
        # with both ASCII and non-ASCII cwds.
        abspath = self.pathmodule.abspath
        for path in (u'', u'fuu', u'f\xf9\xf9', u'/fuu', u'U:\\'):
            self.assertIsInstance(abspath(path), unicode)

        unicwd = u'\xe7w\xf0'
        try:
            fsencoding = test_support.TESTFN_ENCODING or "ascii"
            unicwd.encode(fsencoding)
        except (AttributeError, UnicodeEncodeError):
            # FS encoding is probably ASCII
            pass
        else:
            with test_support.temp_cwd(unicwd):
                for path in (u'', u'fuu', u'f\xf9\xf9', u'/fuu', u'U:\\'):
                    self.assertIsInstance(abspath(path), unicode)
Esempio n. 41
0
 def test_env(self):
     with test_support.temp_cwd(name=u"tempcwd-中文"):
         # os.environ is constructed with FS-encoded values (as in CPython),
         # but it will accept unicode additions.
         newenv = os.environ.copy()
         newenv["TEST_HOME"] = expected = u"首页"
         # Environment passed as UTF-16 String[] by Java, arrives FS-encoded.
         for encoding in ('utf-8', 'gbk'):
             # Emit the value of TEST_HOME explicitly encoded.
             p = subprocess.Popen(
                     [sys.executable, "-c",
                             'import sys, os;' \
                             'sys.stdout.write(os.getenv("TEST_HOME")' \
                             '.decode(sys.getfilesystemencoding())' \
                             '.encode("%s"))' \
                             % encoding],
                     stdout=subprocess.PIPE,
                     env=newenv)
             # Decode with chosen encoding 
             self.assertEqual(p.stdout.read().decode(encoding), u"首页")
Esempio n. 42
0
 def test_env(self):
     with test_support.temp_cwd(name=u"tempcwd-中文"):
         # os.environ is constructed with FS-encoded values (as in CPython),
         # but it will accept unicode additions.
         newenv = os.environ.copy()
         newenv["TEST_HOME"] = expected = u"首页"
         # Environment passed as UTF-16 String[] by Java, arrives FS-encoded.
         for encoding in ('utf-8', 'gbk'):
             # Emit the value of TEST_HOME explicitly encoded.
             p = subprocess.Popen(
                     [sys.executable, "-c",
                             'import sys, os;' \
                             'sys.stdout.write(os.getenv("TEST_HOME")' \
                             '.decode(sys.getfilesystemencoding())' \
                             '.encode("%s"))' \
                             % encoding],
                     stdout=subprocess.PIPE,
                     env=newenv)
             # Decode with chosen encoding
             self.assertEqual(p.stdout.read().decode(encoding), u"首页")
 def test_relpath(self):
     tester('ntpath.relpath("a")', 'a')
     tester('ntpath.relpath(os.path.abspath("a"))', 'a')
     tester('ntpath.relpath("a/b")', 'a\\b')
     tester('ntpath.relpath("../a/b")', '..\\a\\b')
     with test_support.temp_cwd(test_support.TESTFN) as cwd_dir:
         currentdir = os.path.basename(cwd_dir)
         tester('ntpath.relpath("a", "../b")', '..\\'+currentdir+'\\a')
         tester('ntpath.relpath("a/b", "../c")', '..\\'+currentdir+'\\a\\b')
     tester('ntpath.relpath("a", "b/c")', '..\\..\\a')
     tester('ntpath.relpath("//conky/mountpoint/a", "//conky/mountpoint/b/c")', '..\\..\\a')
     tester('ntpath.relpath("a", "a")', '.')
     tester('ntpath.relpath("/foo/bar/bat", "/x/y/z")', '..\\..\\..\\foo\\bar\\bat')
     tester('ntpath.relpath("/foo/bar/bat", "/foo/bar")', 'bat')
     tester('ntpath.relpath("/foo/bar/bat", "/")', 'foo\\bar\\bat')
     tester('ntpath.relpath("/", "/foo/bar/bat")', '..\\..\\..')
     tester('ntpath.relpath("/foo/bar/bat", "/x")', '..\\foo\\bar\\bat')
     tester('ntpath.relpath("/x", "/foo/bar/bat")', '..\\..\\..\\x')
     tester('ntpath.relpath("/", "/")', '.')
     tester('ntpath.relpath("/a", "/a")', '.')
     tester('ntpath.relpath("/a/b", "/a/b")', '.')
     tester('ntpath.relpath("c:/foo", "C:/FOO")', '.')
Esempio n. 44
0
    def test_abspath_issue3426(self):
        # Check that abspath returns unicode when the arg is unicode
        # with both ASCII and non-ASCII cwds.
        abspath = self.pathmodule.abspath
        for path in (u'', u'fuu', u'f\xf9\xf9', u'/fuu', u'U:\\'):
            self.assertIsInstance(abspath(path), unicode)

        unicwd = u'\xe7w\xf0'
        try:
            fsencoding = test_support.TESTFN_ENCODING or "ascii"
            asciival = unicwd.encode(fsencoding)
            if fsencoding == "mbcs":
                # http://bugs.python.org/issue850997
                v = asciival.find('?')
                if v >= 0:
                    raise UnicodeEncodeError(fsencoding, unicwd, v, v, asciival)
        except (AttributeError, UnicodeEncodeError):
            # FS encoding is probably ASCII or windows and codepage is non-Latin1
            pass
        else:
            with test_support.temp_cwd(unicwd):
                for path in (u'', u'fuu', u'f\xf9\xf9', u'/fuu', u'U:\\'):
                    self.assertIsInstance(abspath(path), unicode)
Esempio n. 45
0
    def test_abspath_issue3426(self):
        # Check that abspath returns unicode when the arg is unicode
        # with both ASCII and non-ASCII cwds.
        abspath = self.pathmodule.abspath
        for path in (u'', u'fuu', u'f\xf9\xf9', u'/fuu', u'U:\\'):
            self.assertIsInstance(abspath(path), unicode)

        unicwd = u'\xe7w\xf0'
        try:
            fsencoding = test_support.TESTFN_ENCODING or "ascii"
            asciival = unicwd.encode(fsencoding)
            if fsencoding == "mbcs":
                # http://bugs.python.org/issue850997
                v = asciival.find('?')
                if v >= 0:
                    raise UnicodeEncodeError(fsencoding, unicwd, v, v, asciival)
        except (AttributeError, UnicodeEncodeError):
            # FS encoding is probably ASCII or windows and codepage is non-Latin1
            pass
        else:
            with test_support.temp_cwd(unicwd):
                for path in (u'', u'fuu', u'f\xf9\xf9', u'/fuu', u'U:\\'):
                    self.assertIsInstance(abspath(path), unicode)
 def test_nonascii_abspath(self):
     # Test non-ASCII, non-UTF8 bytes in the path.
     with test_support.temp_cwd('\xe7w\xf0'):
         self.test_abspath()
Esempio n. 47
0
 def test_nonascii_abspath(self):
     # Test non-ASCII, non-UTF8 bytes in the path.
     with test_support.temp_cwd('\xe7w\xf0'):
         self.test_abspath()
        assert self.isvalid()
        return self.expected

if __name__ == '__main__':
    # Simplification for findtestdir().
    assert __file__ == os.path.abspath(sys.argv[0])

    # When tests are run from the Python build directory, it is best practice
    # to keep the test files in a subfolder.  It eases the cleanup of leftover
    # files using command "make distclean".
    if sysconfig.is_python_build():
        TEMPDIR = os.path.join(sysconfig.get_config_var('srcdir'), 'build')
        TEMPDIR = os.path.abspath(TEMPDIR)
        if not os.path.exists(TEMPDIR):
            os.mkdir(TEMPDIR)

    # Define a writable temp dir that will be used as cwd while running
    # the tests. The name of the dir includes the pid to allow parallel
    # testing (see the -j option).
    TESTCWD = 'test_python_{}'.format(os.getpid())

    TESTCWD = os.path.join(TEMPDIR, TESTCWD)

    # Run the tests in a context manager that temporary changes the CWD to a
    # temporary and writable directory. If it's not possible to create or
    # change the CWD, the original CWD will be used. The original CWD is
    # available from test_support.SAVEDCWD.
    with test_support.temp_cwd(TESTCWD, quiet=True):
        main()
Esempio n. 49
0
    def test_listdir(self):
        # It is hard to avoid Unicode paths on systems like OS X. Use relative
        # paths from a temp CWD to work around this. But when you don't,
        # it behaves like this ...
        with test_support.temp_cwd() as new_cwd:

            basedir = os.path.join(".", "unicode")
            self.assertIs(type(basedir), bytes)
            chinese_path = os.path.join(basedir, u"中文")
            self.assertIs(type(chinese_path), unicode)
            home_path = os.path.join(chinese_path, u"首页")
            os.makedirs(home_path)

            FS = sys.getfilesystemencoding()

            with open(os.path.join(home_path, "test.txt"), "w") as test_file:
                test_file.write("42\n")

            # listdir(bytes) includes encoded form of 中文
            entries = os.listdir(basedir)
            self.assertIn(u"中文".encode(FS), entries)
            for entry in entries:
                self.assertIs(type(entry), bytes)

            # listdir(unicode) includes unicode form of 首页
            entries = os.listdir(chinese_path)
            self.assertIn(u"首页", entries)
            for entry in entries:
                self.assertIs(type(entry), unicode)

            # glob.glob builds on os.listdir; note that we don't use
            # Unicode paths in the arg to glob so the result is bytes
            self.assertEqual(
                glob.glob(os.path.join("unicode", "*")),
                [os.path.join(u"unicode", u"中文").encode(FS)])
            self.assertEqual(
                glob.glob(os.path.join("unicode", "*", "*")),
                [os.path.join(u"unicode", u"中文", u"首页").encode(FS)])
            self.assertEqual(
                glob.glob(os.path.join("unicode", "*", "*", "*")),
                [os.path.join(u"unicode", u"中文", u"首页", "test.txt").encode(FS)])

            # Now use a Unicode path as well as in the glob arg
            self.assertEqual(
                glob.glob(os.path.join(u"unicode", "*")),
                [os.path.join(u"unicode", u"中文")])
            self.assertEqual(
                glob.glob(os.path.join(u"unicode", "*", "*")),
                [os.path.join(u"unicode", u"中文", u"首页")])
            self.assertEqual(
                glob.glob(os.path.join(u"unicode", "*", "*", "*")),
                [os.path.join(u"unicode", u"中文", u"首页", "test.txt")])

            # Verify Java integration. But we will need to construct
            # an absolute path since chdir doesn't work with Java
            # (except for subprocesses, like below in test_env)
            for entry in entries: # list(unicode)
                # new_cwd is bytes while chinese_path is unicode.
                # But new_cwd is not guaranteed to be just ascii, so decode it.
                new_cwd = new_cwd.decode(FS)
                entry_path = os.path.join(new_cwd, chinese_path, entry)
                f = File(entry_path)
                self.assertTrue(f.exists(),
                    "File %r (%r) should be testable for existence" %
                    (f, entry_path))
Esempio n. 50
0
    def test_listdir(self):
        # It is hard to avoid Unicode paths on systems like OS X. Use relative
        # paths from a temp CWD to work around this. But when you don't,
        # it behaves like this ...
        with test_support.temp_cwd() as new_cwd:

            basedir = os.path.join(".", "unicode")
            self.assertIs(type(basedir), bytes)
            chinese_path = os.path.join(basedir, u"中文")
            self.assertIs(type(chinese_path), unicode)
            home_path = os.path.join(chinese_path, u"首页")
            os.makedirs(home_path)

            FS = sys.getfilesystemencoding()

            with open(os.path.join(home_path, "test.txt"), "w") as test_file:
                test_file.write("42\n")

            # listdir(bytes) includes encoded form of 中文
            entries = os.listdir(basedir)
            self.assertIn(u"中文".encode(FS), entries)
            for entry in entries:
                self.assertIs(type(entry), bytes)

            # listdir(unicode) includes unicode form of 首页
            entries = os.listdir(chinese_path)
            self.assertIn(u"首页", entries)
            for entry in entries:
                self.assertIs(type(entry), unicode)

            # glob.glob builds on os.listdir; note that we don't use
            # Unicode paths in the arg to glob so the result is bytes
            self.assertEqual(glob.glob(os.path.join("unicode", "*")),
                             [os.path.join(u"unicode", u"中文").encode(FS)])
            self.assertEqual(
                glob.glob(os.path.join("unicode", "*", "*")),
                [os.path.join(u"unicode", u"中文", u"首页").encode(FS)])
            self.assertEqual(glob.glob(os.path.join("unicode", "*", "*", "*")),
                             [
                                 os.path.join(u"unicode", u"中文", u"首页",
                                              "test.txt").encode(FS)
                             ])

            # Now use a Unicode path as well as in the glob arg
            self.assertEqual(glob.glob(os.path.join(u"unicode", "*")),
                             [os.path.join(u"unicode", u"中文")])
            self.assertEqual(glob.glob(os.path.join(u"unicode", "*", "*")),
                             [os.path.join(u"unicode", u"中文", u"首页")])
            self.assertEqual(
                glob.glob(os.path.join(u"unicode", "*", "*", "*")),
                [os.path.join(u"unicode", u"中文", u"首页", "test.txt")])

            # Verify Java integration. But we will need to construct
            # an absolute path since chdir doesn't work with Java
            # (except for subprocesses, like below in test_env)
            for entry in entries:  # list(unicode)
                # new_cwd is bytes while chinese_path is unicode.
                # But new_cwd is not guaranteed to be just ascii, so decode it.
                new_cwd = new_cwd.decode(FS)
                entry_path = os.path.join(new_cwd, chinese_path, entry)
                f = File(entry_path)
                self.assertTrue(
                    f.exists(),
                    "File %r (%r) should be testable for existence" %
                    (f, entry_path))