Example #1
0
    def test_issue_8766(self):
        # "import encodings" emits a warning whereas the warnings is not loaded
        # or not completely loaded (warnings imports indirectly encodings by
        # importing linecache) yet
        with support.temp_cwd() as cwd, support.temp_cwd('encodings'):
            # encodings loaded by initfsencoding()
            assert_python_ok('-c', 'pass', PYTHONPATH=cwd)

            # Use -W to load warnings module at startup
            assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd)
Example #2
0
    def test_issue_8766(self):
        # "import encodings" emits a warning whereas the warnings is not loaded
        # or not completely loaded (warnings imports indirectly encodings by
        # importing linecache) yet
        with support.temp_cwd() as cwd, support.temp_cwd("encodings"):
            env = os.environ.copy()
            env["PYTHONPATH"] = cwd

            # encodings loaded by initfsencoding()
            retcode = subprocess.call([sys.executable, "-c", "pass"], env=env)
            self.assertEqual(retcode, 0)

            # Use -W to load warnings module at startup
            retcode = subprocess.call([sys.executable, "-c", "pass", "-W", "always"], env=env)
            self.assertEqual(retcode, 0)
Example #3
0
 def test_empty(self):
     # Switch to an existing, but safe, working directory to let the
     # cleanup code do its thing without permission errors.
     with support.temp_cwd(path=path.dirname(sys.executable)):
         empty = path.join(path.dirname(__file__), "empty.vbs")
         startfile(empty)
         startfile(empty, "open")
Example #4
0
    def main(self, tests=None, **kwargs):
        self.parse_args(kwargs)

        self.set_temp_dir()

        if self.ns.cleanup:
            self.cleanup()
            sys.exit(0)

        test_cwd = self.create_temp_dir()

        try:
            # Run the tests in a context manager that temporarily 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 support.SAVEDCWD.
            with support.temp_cwd(test_cwd, quiet=True):
                # When using multiprocessing, worker processes will use test_cwd
                # as their parent temporary directory. So when the main process
                # exit, it removes also subdirectories of worker processes.
                self.ns.tempdir = test_cwd

                self._main(tests, kwargs)
        except SystemExit as exc:
            # bpo-38203: Python can hang at exit in Py_Finalize(), especially
            # on threading._shutdown() call: put a timeout
            faulthandler.dump_traceback_later(EXIT_TIMEOUT, exit=True)

            sys.exit(exc.code)
Example #5
0
    def _test_soft_switchable_extension(self):
        with temp_cwd(self.id()) as tmpdir:
            args = [sys.executable]
            args.extend(args_from_interpreter_flags())
            args.extend(["setup.py", "build", "-b", tmpdir, "install_lib", "-d", tmpdir, "--no-compile"])
            try:
                output = subprocess.check_output(args, stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT, cwd=self.demo_dir)
            except subprocess.CalledProcessError as e:
                if e.stdout:
                    sys.stdout.buffer.write(e.stdout)
                if e.stderr:
                    sys.stderr.buffer.write(e.stderr)
                raise
            if self.verbose:
                sys.stdout.buffer.write(output)
            py = glob.glob("*.py")
            self.assertEqual(len(py), 1)
            py = py[0]

            args = [sys.executable]
            args.extend(args_from_interpreter_flags())
            args.extend([py, '-v'])
            try:
                output = subprocess.check_output(args, stdin=subprocess.DEVNULL, stderr=subprocess.STDOUT)
            except subprocess.CalledProcessError as e:
                if e.stdout:
                    sys.stdout.buffer.write(e.stdout)
                if e.stderr:
                    sys.stderr.buffer.write(e.stderr)
                raise
            if self.verbose:
                sys.stdout.buffer.write(output)
Example #6
0
 def test_set_pycache_prefix(self):
     # sys.pycache_prefix can be set from either -X pycache_prefix or
     # PYTHONPYCACHEPREFIX env var, with the former taking precedence.
     NO_VALUE = object()  # `-X pycache_prefix` with no `=PATH`
     cases = [
         # (PYTHONPYCACHEPREFIX, -X pycache_prefix, sys.pycache_prefix)
         (None, None, None),
         ('foo', None, 'foo'),
         (None, 'bar', 'bar'),
         ('foo', 'bar', 'bar'),
         ('foo', '', None),
         ('foo', NO_VALUE, None),
     ]
     for envval, opt, expected in cases:
         exp_clause = "is None" if expected is None else f'== "{expected}"'
         code = f"import sys; sys.exit(not sys.pycache_prefix {exp_clause})"
         args = ['-c', code]
         env = {} if envval is None else {'PYTHONPYCACHEPREFIX': envval}
         if opt is NO_VALUE:
             args[:0] = ['-X', 'pycache_prefix']
         elif opt is not None:
             args[:0] = ['-X', f'pycache_prefix={opt}']
         with self.subTest(envval=envval, opt=opt):
             with support.temp_cwd():
                 assert_python_ok(*args, **env)
Example #7
0
 def test_readlink_nonexistent(self):
     with 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)
Example #8
0
 def test_set_pycache_prefix(self):
     # sys.pycache_prefix can be set from either -X pycache_prefix or
     # PYTHONPYCACHEPREFIX env var, with the former taking precedence.
     NO_VALUE = object()  # `-X pycache_prefix` with no `=PATH`
     cases = [
         # (PYTHONPYCACHEPREFIX, -X pycache_prefix, sys.pycache_prefix)
         (None, None, None),
         ('foo', None, 'foo'),
         (None, 'bar', 'bar'),
         ('foo', 'bar', 'bar'),
         ('foo', '', None),
         ('foo', NO_VALUE, None),
     ]
     for envval, opt, expected in cases:
         exp_clause = "is None" if expected is None else f'== "{expected}"'
         code = f"import sys; sys.exit(not sys.pycache_prefix {exp_clause})"
         args = ['-c', code]
         env = {} if envval is None else {'PYTHONPYCACHEPREFIX': envval}
         if opt is NO_VALUE:
             args[:0] = ['-X', 'pycache_prefix']
         elif opt is not None:
             args[:0] = ['-X', f'pycache_prefix={opt}']
         with self.subTest(envval=envval, opt=opt):
             with support.temp_cwd():
                 assert_python_ok(*args, **env)
Example #9
0
 def test_empty(self):
     # Switch to an existing, but safe, working directory to let the
     # cleanup code do its thing without permission errors.
     with support.temp_cwd(path=path.dirname(sys.executable)):
         empty = path.join(path.dirname(__file__), "empty.vbs")
         startfile(empty)
         startfile(empty, "open")
Example #10
0
    def test_readrc_kwarg(self):
        script = textwrap.dedent("""
            import pdb; pdb.Pdb(readrc=False).set_trace()

            print('hello')
        """)

        save_home = os.environ.pop('HOME', None)
        try:
            with support.temp_cwd():
                with open('.pdbrc', 'w') as f:
                    f.write("invalid\n")

                with open('main.py', 'w') as f:
                    f.write(script)

                cmd = [sys.executable, 'main.py']
                proc = subprocess.Popen(
                    cmd,
                    stdout=subprocess.PIPE,
                    stdin=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                )
                with proc:
                    stdout, stderr = proc.communicate(b'q\n')
                    self.assertNotIn("NameError: name 'invalid' is not defined",
                                  stdout.decode())

        finally:
            if save_home is not None:
                os.environ['HOME'] = save_home
Example #11
0
 def test_options_no_site_import(self):
     with 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']")
Example #12
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 support.temp_cwd(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("c:/foo/bar/bat", "c:/x/y")',
            '..\\..\\foo\\bar\\bat')
     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")', '.')
Example #13
0
 def test_isolatedmode(self):
     self.verify_valid_flag('-I')
     self.verify_valid_flag('-IEs')
     rc, out, err = assert_python_ok(
         '-I',
         '-c',
         'from sys import flags as f; '
         'print(f.no_user_site, f.ignore_environment, f.isolated)',
         # dummyvar to prevent extraneous -E
         dummyvar="")
     self.assertEqual(out.strip(), b'1 1 1')
     with support.temp_cwd() as tmpdir:
         fake = os.path.join(tmpdir, "uuid.py")
         main = os.path.join(tmpdir, "main.py")
         with open(fake, "w") as f:
             f.write("raise RuntimeError('isolated mode test')\n")
         with open(main, "w") as f:
             f.write("import uuid\n")
             f.write("print('ok')\n")
         self.assertRaises(subprocess.CalledProcessError,
                           subprocess.check_output, [sys.executable, main],
                           cwd=tmpdir,
                           stderr=subprocess.DEVNULL)
         out = subprocess.check_output([sys.executable, "-I", main],
                                       cwd=tmpdir)
         self.assertEqual(out.strip(), b"ok")
Example #14
0
    def test_readrc_kwarg(self):
        script = textwrap.dedent("""
            import pdb; pdb.Pdb(readrc=False).set_trace()

            print('hello')
        """)

        save_home = os.environ.pop('HOME', None)
        try:
            with support.temp_cwd():
                with open('.pdbrc', 'w') as f:
                    f.write("invalid\n")

                with open('main.py', 'w') as f:
                    f.write(script)

                cmd = [sys.executable, 'main.py']
                proc = subprocess.Popen(
                    cmd,
                    stdout=subprocess.PIPE,
                    stdin=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                )
                with proc:
                    stdout, stderr = proc.communicate(b'q\n')
                    self.assertNotIn(
                        "NameError: name 'invalid' is not defined",
                        stdout.decode())

        finally:
            if save_home is not None:
                os.environ['HOME'] = save_home
Example #15
0
 def test_getcwd(self):
     with support.temp_cwd(name="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)
Example #16
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!")
Example #17
0
    def test_issue_8766(self):
        # "import encodings" emits a warning whereas the warnings is not loaded
        # or not completely loaded (warnings imports indirectly encodings by
        # importing linecache) yet
        with support.temp_cwd() as cwd, support.temp_cwd('encodings'):
            env = os.environ.copy()
            env['PYTHONPATH'] = cwd

            # encodings loaded by initfsencoding()
            retcode = subprocess.call([sys.executable, '-c', 'pass'], env=env)
            self.assertEqual(retcode, 0)

            # Use -W to load warnings module at startup
            retcode = subprocess.call(
                [sys.executable, '-c', 'pass', '-W', 'always'], env=env)
            self.assertEqual(retcode, 0)
    def test_reload_namespace_changed(self):
        name = 'spam'
        with support.temp_cwd(None) as cwd:
            with test_util.uncache('spam'):
                with support.DirsOnSysPath(cwd):
                    # Start as a namespace package.
                    self.init.invalidate_caches()
                    bad_path = os.path.join(cwd, name, '__init.py')
                    cached = self.util.cache_from_source(bad_path)
                    expected = {
                        '__name__': name,
                        '__package__': name,
                        '__doc__': None,
                        '__file__': None,
                    }
                    os.mkdir(name)
                    with open(bad_path, 'w') as init_file:
                        init_file.write('eggs = None')
                    module = self.init.import_module(name)
                    ns = vars(module).copy()
                    loader = ns.pop('__loader__')
                    path = ns.pop('__path__')
                    spec = ns.pop('__spec__')
                    ns.pop('__builtins__', None)  # An implementation detail.
                    self.assertEqual(spec.name, name)
                    self.assertIsNotNone(spec.loader)
                    self.assertIsNotNone(loader)
                    self.assertEqual(spec.loader, loader)
                    self.assertEqual(set(path),
                                     set([os.path.dirname(bad_path)]))
                    with self.assertRaises(AttributeError):
                        # a NamespaceLoader
                        loader.path
                    self.assertEqual(ns, expected)

                    # Change to a regular package.
                    self.init.invalidate_caches()
                    init_path = os.path.join(cwd, name, '__init__.py')
                    cached = self.util.cache_from_source(init_path)
                    expected = {
                        '__name__': name,
                        '__package__': name,
                        '__file__': init_path,
                        '__cached__': cached,
                        '__path__': [os.path.dirname(init_path)],
                        '__doc__': None,
                        'eggs': None,
                    }
                    os.rename(bad_path, init_path)
                    reloaded = self.init.reload(module)
                    ns = vars(reloaded).copy()
                    loader = ns.pop('__loader__')
                    spec = ns.pop('__spec__')
                    ns.pop('__builtins__', None)  # An implementation detail.
                    self.assertEqual(spec.name, name)
                    self.assertEqual(spec.loader, loader)
                    self.assertIs(reloaded, module)
                    self.assertEqual(loader.path, init_path)
                    self.assertEqual(ns, expected)
Example #19
0
 def test_property_no_site_import(self):
     # only the minimal set of modules are imported
     with 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']")
Example #20
0
 def test_abspath(self):
     tester('ntpath.abspath("C:\\")', "C:\\")
     with support.temp_cwd(support.TESTFN) as cwd_dir: # bpo-31047
         tester('ntpath.abspath("")', cwd_dir)
         tester('ntpath.abspath(" ")', cwd_dir + "\\ ")
         tester('ntpath.abspath("?")', cwd_dir + "\\?")
         drive, _ = ntpath.splitdrive(cwd_dir)
         tester('ntpath.abspath("/abc/")', drive + "\\abc")
Example #21
0
 def test_temp_cwd__chdir_warning(self):
     """Check the warning message when os.chdir() fails."""
     path = TESTFN + '_does_not_exist'
     with support.check_warnings() as recorder:
         with support.temp_cwd(path=path, quiet=True):
             pass
         messages = [str(w.message) for w in recorder.warnings]
     self.assertEqual(messages, ['tests may fail, unable to change the CWD to ' + path])
Example #22
0
 def test_temp_cwd__name_none(self):
     """Test passing None to temp_cwd()."""
     original_cwd = os.getcwd()
     with support.temp_cwd(name=None) as new_cwd:
         self.assertNotEqual(new_cwd, original_cwd)
         self.assertTrue(os.path.isdir(new_cwd))
         self.assertEqual(os.getcwd(), new_cwd)
     self.assertEqual(os.getcwd(), original_cwd)
Example #23
0
 def test_filename_in_syntaxerror(self):
     # see issue 38964
     with temp_cwd() as cwd:
         file_path = os.path.join(cwd, 't.py')
         with open(file_path, 'w') as f:
             f.write('f"{a b}"')  # This generates a SyntaxError
         _, _, stderr = assert_python_failure(file_path)
     self.assertIn(file_path, stderr.decode('utf-8'))
Example #24
0
 def test_property_no_site_import(self):
     # only the minimal set of modules are imported
     with 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']")
Example #25
0
 def test_directory(self):
     dirname = os.path.join(support.TESTFN, 'Gr\xfc\xdf-\u66e8\u66e9\u66eb')
     filename = '\xdf-\u66e8\u66e9\u66eb'
     with support.temp_cwd(dirname):
         with open(filename, 'wb') as f:
             f.write((filename + '\n').encode("utf-8"))
         os.access(filename,os.R_OK)
         os.remove(filename)
Example #26
0
 def test_abspath(self):
     tester('ntpath.abspath("C:\\")', "C:\\")
     with support.temp_cwd(support.TESTFN) as cwd_dir: # bpo-31047
         tester('ntpath.abspath("")', cwd_dir)
         tester('ntpath.abspath(" ")', cwd_dir + "\\ ")
         tester('ntpath.abspath("?")', cwd_dir + "\\?")
         drive, _ = ntpath.splitdrive(cwd_dir)
         tester('ntpath.abspath("/abc/")', drive + "\\abc")
 def test_directory(self):
     dirname = os.path.join(support.TESTFN, 'Gr\xfc\xdf-\u66e8\u66e9\u66eb')
     filename = '\xdf-\u66e8\u66e9\u66eb'
     with support.temp_cwd(dirname):
         with open(filename, 'wb') as f:
             f.write((filename + '\n').encode("utf-8"))
         os.access(filename,os.R_OK)
         os.remove(filename)
Example #28
0
def test_load_conf():
    """Test the configuration loading
    """
    with temp_cwd():
        with pytest.raises(SystemExit):
            kisee.load_conf("settings.toml")
    config = kisee.load_conf("tests/test_settings.toml")
    assert config["server"]["host"] == "0.0.0.0"
Example #29
0
 def test_temp_cwd__name_none(self):
     """Test passing None to temp_cwd()."""
     original_cwd = os.getcwd()
     with support.temp_cwd(name=None) as new_cwd:
         self.assertNotEqual(new_cwd, original_cwd)
         self.assertTrue(os.path.isdir(new_cwd))
         self.assertEqual(os.getcwd(), new_cwd)
     self.assertEqual(os.getcwd(), original_cwd)
 def test_directory(self):
     dirname = os.path.join(support.TESTFN, 'Grüß-曨曩曫')
     filename = 'ß-曨曩曫'
     with support.temp_cwd(dirname):
         with open(filename, 'wb') as f:
             f.write((filename + '\n').encode('utf-8'))
         os.access(filename, os.R_OK)
         os.remove(filename)
Example #31
0
 def test_bad_symlink(self):
     with 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)
Example #32
0
    def test_reload_namespace_changed(self):
        name = 'spam'
        with support.temp_cwd(None) as cwd:
            with test_util.uncache('spam'):
                with support.DirsOnSysPath(cwd):
                    # Start as a namespace package.
                    self.init.invalidate_caches()
                    bad_path = os.path.join(cwd, name, '__init.py')
                    cached = self.util.cache_from_source(bad_path)
                    expected = {'__name__': name,
                                '__package__': name,
                                '__doc__': None,
                                '__file__': None,
                                }
                    os.mkdir(name)
                    with open(bad_path, 'w') as init_file:
                        init_file.write('eggs = None')
                    module = self.init.import_module(name)
                    ns = vars(module).copy()
                    loader = ns.pop('__loader__')
                    path = ns.pop('__path__')
                    spec = ns.pop('__spec__')
                    ns.pop('__builtins__', None)  # An implementation detail.
                    self.assertEqual(spec.name, name)
                    self.assertIsNotNone(spec.loader)
                    self.assertIsNotNone(loader)
                    self.assertEqual(spec.loader, loader)
                    self.assertEqual(set(path),
                                     set([os.path.dirname(bad_path)]))
                    with self.assertRaises(AttributeError):
                        # a NamespaceLoader
                        loader.path
                    self.assertEqual(ns, expected)

                    # Change to a regular package.
                    self.init.invalidate_caches()
                    init_path = os.path.join(cwd, name, '__init__.py')
                    cached = self.util.cache_from_source(init_path)
                    expected = {'__name__': name,
                                '__package__': name,
                                '__file__': init_path,
                                '__cached__': cached,
                                '__path__': [os.path.dirname(init_path)],
                                '__doc__': None,
                                'eggs': None,
                                }
                    os.rename(bad_path, init_path)
                    reloaded = self.init.reload(module)
                    ns = vars(reloaded).copy()
                    loader = ns.pop('__loader__')
                    spec = ns.pop('__spec__')
                    ns.pop('__builtins__', None)  # An implementation detail.
                    self.assertEqual(spec.name, name)
                    self.assertEqual(spec.loader, loader)
                    self.assertIs(reloaded, module)
                    self.assertEqual(loader.path, init_path)
                    self.assertEqual(ns, expected)
Example #33
0
 def test_link(self):
     with 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")
Example #34
0
 def test_filename_in_syntaxerror(self):
     # see issue 38964
     with temp_cwd() as cwd:
         file_path = os.path.join(cwd, 't.py')
         with open(file_path, 'w') as f:
             f.write('f"{a b}"')  # This generates a SyntaxError
         _, _, stderr = assert_python_failure(file_path,
                                              PYTHONIOENCODING='ascii')
     self.assertIn(file_path.encode('ascii', 'backslashreplace'), stderr)
Example #35
0
 def test_empty_python_home(self):
     # http://bugs.jython.org/issue2283
     with 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")
Example #36
0
 def test_empty_python_home(self):
     # http://bugs.jython.org/issue2283
     with 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")
Example #37
0
 def extract_docstrings_from_str(self, module_content):
     """ utility: return all msgids extracted from module_content """
     filename = 'test_docstrings.py'
     with temp_cwd(None) as cwd:
         with open(filename, 'w') as fp:
             fp.write(module_content)
         assert_python_ok(self.script, '-D', filename)
         with open('messages.pot') as fp:
             data = fp.read()
     return self.get_msgids(data)
Example #38
0
 def test_env(self):
     with support.temp_cwd(name="tempcwd-中文"):
         newenv = os.environ.copy()
         newenv["TEST_HOME"] = "首页"
         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"), "首页")
Example #39
0
 def test_readlink(self):
     with 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(str(source)), str(target))
         self.assertIsInstance(os.readlink(str(source)), str)
Example #40
0
def test_quickstart(monkeypatch: MonkeyPatch) -> None:
    monkeypatch.setattr("sys.stdin", io.StringIO("\n" * 1000))
    with temp_cwd():
        quickstart.main()
        with open("settings.toml") as first_settings_file:
            first_settings = first_settings_file.read()
        quickstart.main()
        with open("settings.toml") as second_settings_file:
            second_settings = second_settings_file.read()
        assert first_settings != second_settings
Example #41
0
    def test_script_abspath(self):
        # pass the script using the relative path, expect the absolute path
        # in __file__ and sys.argv[0]
        with support.temp_cwd() as script_dir:
            self.assertTrue(os.path.isabs(script_dir), script_dir)

            script_name = _make_test_script(script_dir, 'script')
            self._check_script(os.path.basename(script_name), script_name, script_name,
                               script_dir, None,
                               importlib.machinery.SourceFileLoader)
 def extract_docstrings_from_str(self, module_content):
     """ utility: return all msgids extracted from module_content """
     filename = 'test_docstrings.py'
     with temp_cwd(None) as cwd:
         with open(filename, 'w') as fp:
             fp.write(module_content)
         assert_python_ok(self.script, '-D', filename)
         with open('messages.pot') as fp:
             data = fp.read()
     return self.get_msgids(data)
Example #43
0
 def test_unicode_argv(self):
     """Unicode roundtrips successfully through sys.argv arguments"""
     zhongwen = u'\u4e2d\u6587'
     with 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)
Example #44
0
 def test_unicode_argv(self):
     """Unicode roundtrips successfully through sys.argv arguments"""
     zhongwen = u'\u4e2d\u6587'
     with 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)
Example #45
0
 def test_issue8202_dash_m_file_ignored(self):
     # Make sure a "-m" file in the current directory
     # does not alter the value of sys.path[0]
     with temp_dir() as script_dir:
         script_name = _make_test_script(script_dir, 'other')
         with support.temp_cwd(path=script_dir):
             with open("-m", "w") as f:
                 f.write("data")
                 rc, out, err = assert_python_ok('-m', 'other', *example_args)
                 self._check_output(script_name, rc, out,
                                   script_name, script_name, '', '')
Example #46
0
 def main(self, tests=None, **kwargs):
     global TEMPDIR
     if sysconfig.is_python_build():
         try:
             os.mkdir(TEMPDIR)
         except FileExistsError:
             pass
     test_cwd = 'test_python_{}'.format(os.getpid())
     test_cwd = os.path.join(TEMPDIR, test_cwd)
     with support.temp_cwd(test_cwd, quiet=True):
         self._main(tests, kwargs)
 def test_issue8202_dash_c_file_ignored(self):
     # Make sure a "-c" file in the current directory
     # does not alter the value of sys.path[0]
     with temp_dir() as script_dir:
         with support.temp_cwd(path=script_dir):
             with open("-c", "w") as f:
                 f.write("data")
                 rc, out, err = assert_python_ok("-c", 'import sys; print("sys.path[0]==%r" % sys.path[0])')
                 if verbose > 1:
                     print(out)
                 expected = "sys.path[0]==%r" % ""
                 self.assertIn(expected.encode("utf-8"), out)
Example #48
0
 def test_bad_python_home(self):
     # http://bugs.jython.org/issue2283
     with 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)
    def test_take_snapshot(self):
        def callback(snapshot):
            snapshot.add_metric('callback', 5, 'size')

        with support.temp_cwd():
            task = tracemalloctext.TakeSnapshotTask(callback=callback)
            for index in range(1, 4):
                snapshot, filename = task.take_snapshot()
                self.assertEqual(snapshot.get_metric('callback'), 5)
                self.assertEqual(filename,
                                 'tracemalloc-%04d.pickle' % index)
                self.assertTrue(os.path.exists(filename))
Example #50
0
    def test_reload_location_changed(self):
        name = "spam"
        with support.temp_cwd(None) as cwd:
            with test_util.uncache("spam"):
                with support.DirsOnSysPath(cwd):
                    # Start as a plain module.
                    self.init.invalidate_caches()
                    path = os.path.join(cwd, name + ".py")
                    cached = self.util.cache_from_source(path)
                    expected = {
                        "__name__": name,
                        "__package__": "",
                        "__file__": path,
                        "__cached__": cached,
                        "__doc__": None,
                    }
                    support.create_empty_file(path)
                    module = self.init.import_module(name)
                    ns = vars(module).copy()
                    loader = ns.pop("__loader__")
                    spec = ns.pop("__spec__")
                    ns.pop("__builtins__", None)  # An implementation detail.
                    self.assertEqual(spec.name, name)
                    self.assertEqual(spec.loader, loader)
                    self.assertEqual(loader.path, path)
                    self.assertEqual(ns, expected)

                    # Change to a package.
                    self.init.invalidate_caches()
                    init_path = os.path.join(cwd, name, "__init__.py")
                    cached = self.util.cache_from_source(init_path)
                    expected = {
                        "__name__": name,
                        "__package__": name,
                        "__file__": init_path,
                        "__cached__": cached,
                        "__path__": [os.path.dirname(init_path)],
                        "__doc__": None,
                    }
                    os.mkdir(name)
                    os.rename(path, init_path)
                    reloaded = self.init.reload(module)
                    ns = vars(reloaded).copy()
                    loader = ns.pop("__loader__")
                    spec = ns.pop("__spec__")
                    ns.pop("__builtins__", None)  # An implementation detail.
                    self.assertEqual(spec.name, name)
                    self.assertEqual(spec.loader, loader)
                    self.assertIs(reloaded, module)
                    self.assertEqual(loader.path, init_path)
                    self.maxDiff = None
                    self.assertEqual(ns, expected)
Example #51
0
 def test_find_and_load_checked_pyc(self):
     # issue 34056
     with support.temp_cwd():
         with open('mymod.py', 'wb') as fp:
             fp.write(b'x = 42\n')
         py_compile.compile(
             'mymod.py',
             doraise=True,
             invalidation_mode=py_compile.PycInvalidationMode.CHECKED_HASH,
         )
         file, path, description = imp.find_module('mymod', path=['.'])
         mod = imp.load_module('mymod', file, path, description)
     self.assertEqual(mod.x, 42)
 def test_dash_m_error_code_is_one(self):
     # If a module is invoked with the -m command line flag
     # and results in an error that the return code to the
     # shell is '1'
     with temp_dir() as script_dir:
         with support.temp_cwd(path=script_dir):
             pkg_dir = os.path.join(script_dir, "test_pkg")
             make_pkg(pkg_dir)
             script_name = _make_test_script(pkg_dir, "other", "if __name__ == '__main__': raise ValueError")
             rc, out, err = assert_python_failure("-m", "test_pkg.other", *example_args)
             if verbose > 1:
                 print(out)
             self.assertEqual(rc, 1)
Example #53
0
    def test_reload_location_changed(self):
        name = 'spam'
        with support.temp_cwd(None) as cwd:
            with util.uncache('spam'):
                with support.DirsOnSysPath(cwd):
                    # Start as a plain module.
                    self.init.invalidate_caches()
                    path = os.path.join(cwd, name + '.py')
                    cached = self.util.cache_from_source(path)
                    expected = {'__name__': name,
                                '__package__': '',
                                '__file__': path,
                                '__cached__': cached,
                                '__doc__': None,
                                '__builtins__': __builtins__,
                                }
                    support.create_empty_file(path)
                    module = self.init.import_module(name)
                    ns = vars(module)
                    loader = ns.pop('__loader__')
                    spec = ns.pop('__spec__')
                    self.assertEqual(spec.name, name)
                    self.assertEqual(spec.loader, loader)
                    self.assertEqual(loader.path, path)
                    self.assertEqual(ns, expected)

                    # Change to a package.
                    self.init.invalidate_caches()
                    init_path = os.path.join(cwd, name, '__init__.py')
                    cached = self.util.cache_from_source(init_path)
                    expected = {'__name__': name,
                                '__package__': name,
                                '__file__': init_path,
                                '__cached__': cached,
                                '__path__': [os.path.dirname(init_path)],
                                '__doc__': None,
                                '__builtins__': __builtins__,
                                }
                    os.mkdir(name)
                    os.rename(path, init_path)
                    reloaded = self.init.reload(module)
                    ns = vars(reloaded)
                    loader = ns.pop('__loader__')
                    spec = ns.pop('__spec__')
                    self.assertEqual(spec.name, name)
                    self.assertEqual(spec.loader, loader)
                    self.assertIs(reloaded, module)
                    self.assertEqual(loader.path, init_path)
                    self.maxDiff = None
                    self.assertEqual(ns, expected)
 def test_issue8202(self):
     # Make sure package __init__ modules see "-m" in sys.argv0 while
     # searching for the module to execute
     with temp_dir() as script_dir:
         with support.temp_cwd(path=script_dir):
             pkg_dir = os.path.join(script_dir, 'test_pkg')
             make_pkg(pkg_dir, "import sys; print('init_argv0==%r' % sys.argv[0])")
             script_name = _make_test_script(pkg_dir, 'script')
             rc, out, err = assert_python_ok('-m', 'test_pkg.script', *example_args)
             if verbose > 1:
                 print(out)
             expected = "init_argv0==%r" % '-m'
             self.assertIn(expected.encode('utf-8'), out)
             self._check_output(script_name, rc, out,
                                script_name, script_name, '', 'test_pkg')
Example #55
0
    def test_nonascii_abspath(self):
        if (support.TESTFN_UNDECODABLE
        # Mac OS X denies the creation of a directory with an invalid
        # UTF-8 name. Windows allows to create a directory with an
        # arbitrary bytes name, but fails to enter this directory
        # (when the bytes name is used).
        and sys.platform not in ('win32', 'darwin')):
            name = support.TESTFN_UNDECODABLE
        elif support.TESTFN_NONASCII:
            name = support.TESTFN_NONASCII
        else:
            self.skipTest("need support.TESTFN_NONASCII")

        with support.temp_cwd(name):
            self.test_abspath()
Example #56
0
    def test_nonascii_abspath(self):
        name = b'\xe7w\xf0'
        if sys.platform == 'win32':
            try:
                os.fsdecode(name)
            except UnicodeDecodeError:
                self.skipTest("the filename %a is not decodable "
                              "from the ANSI code page %s"
                              % (name, sys.getfilesystemencoding()))

        # Test non-ASCII, non-UTF8 bytes in the path.
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", DeprecationWarning)
            with support.temp_cwd(name):
                self.test_abspath()
Example #57
0
    def test_POT_Creation_Date(self):
        """ Match the date format from xgettext for POT-Creation-Date """
        from datetime import datetime
        with temp_cwd(None) as cwd:
            assert_python_ok(self.script)
            with open('messages.pot') as fp:
                data = fp.read()
            header = self.get_header(data)
            creationDate = header['POT-Creation-Date']

            # peel off the escaped newline at the end of string
            if creationDate.endswith('\\n'):
                creationDate = creationDate[:-len('\\n')]

            # This will raise if the date format does not exactly match.
            datetime.strptime(creationDate, '%Y-%m-%d %H:%M%z')
 def test_issue8202(self):
     # Make sure package __init__ modules see "-m" in sys.argv0 while
     # searching for the module to execute
     with temp_dir() as script_dir:
         with support.temp_cwd(path=script_dir):
             pkg_dir = os.path.join(script_dir, "test_pkg")
             make_pkg(pkg_dir, "import sys; print('init_argv0==%r' % sys.argv[0])")
             script_name = _make_test_script(pkg_dir, "script")
             rc, out, err = assert_python_ok("-m", "test_pkg.script", *example_args)
             if verbose > 1:
                 print(out)
             expected = "init_argv0==%r" % "-m"
             self.assertIn(expected.encode("utf-8"), out)
             self._check_output(
                 script_name, rc, out, script_name, script_name, "", "test_pkg", importlib.machinery.SourceFileLoader
             )
Example #59
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 ('', 'fuu', 'f\xf9\xf9', '/fuu', 'U:\\'):
            self.assertIsInstance(abspath(path), str)

        unicwd = '\xe7w\xf0'
        try:
            os.fsencode(unicwd)
        except (AttributeError, UnicodeEncodeError):
            # FS encoding is probably ASCII
            pass
        else:
            with support.temp_cwd(unicwd):
                for path in ('', 'fuu', 'f\xf9\xf9', '/fuu', 'U:\\'):
                    self.assertIsInstance(abspath(path), str)