当前位置: 首页>>代码示例>>Python>>正文


Python script_helper.assert_python_ok函数代码示例

本文整理汇总了Python中test.support.script_helper.assert_python_ok函数的典型用法代码示例。如果您正苦于以下问题:Python assert_python_ok函数的具体用法?Python assert_python_ok怎么用?Python assert_python_ok使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了assert_python_ok函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_temp_dir__forked_child

    def test_temp_dir__forked_child(self):
        """Test that a forked child process does not remove the directory."""
        # See bpo-30028 for details.
        # Run the test as an external script, because it uses fork.
        script_helper.assert_python_ok("-c", textwrap.dedent("""
            import os
            from test import support
            with support.temp_cwd() as temp_path:
                pid = os.fork()
                if pid != 0:
                    # parent process (child has pid == 0)

                    # wait for the child to terminate
                    (pid, status) = os.waitpid(pid, 0)
                    if status != 0:
                        raise AssertionError(f"Child process failed with exit "
                                             f"status indication 0x{status:x}.")

                    # Make sure that temp_path is still present. When the child
                    # process leaves the 'temp_cwd'-context, the __exit__()-
                    # method of the context must not remove the temporary
                    # directory.
                    if not os.path.isdir(temp_path):
                        raise AssertionError("Child removed temp_path.")
        """))
开发者ID:CCNITSilchar,项目名称:cpython,代码行数:25,代码来源:test_support.py

示例2: test_sigpending

    def test_sigpending(self):
        code = """if 1:
            import os
            import signal

            def handler(signum, frame):
                1/0

            signum = signal.SIGUSR1
            signal.signal(signum, handler)

            signal.pthread_sigmask(signal.SIG_BLOCK, [signum])
            os.kill(os.getpid(), signum)
            pending = signal.sigpending()
            for sig in pending:
                assert isinstance(sig, signal.Signals), repr(pending)
            if pending != {signum}:
                raise Exception('%s != {%s}' % (pending, signum))
            try:
                signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum])
            except ZeroDivisionError:
                pass
            else:
                raise Exception("ZeroDivisionError not raised")
        """
        assert_python_ok('-c', code)
开发者ID:Eyepea,项目名称:cpython,代码行数:26,代码来源:test_signal.py

示例3: test_pthread_kill

    def test_pthread_kill(self):
        code = """if 1:
            import signal
            import threading
            import sys

            signum = signal.SIGUSR1

            def handler(signum, frame):
                1/0

            signal.signal(signum, handler)

            if sys.platform == 'freebsd6':
                # Issue #12392 and #12469: send a signal to the main thread
                # doesn't work before the creation of the first thread on
                # FreeBSD 6
                def noop():
                    pass
                thread = threading.Thread(target=noop)
                thread.start()
                thread.join()

            tid = threading.get_ident()
            try:
                signal.pthread_kill(tid, signum)
            except ZeroDivisionError:
                pass
            else:
                raise Exception("ZeroDivisionError not raised")
        """
        assert_python_ok('-c', code)
开发者ID:gevent,项目名称:gevent,代码行数:32,代码来源:test_signal.py

示例4: test_assert_python_ok_raises

 def test_assert_python_ok_raises(self):
     # I didn't import the sys module so this child will fail.
     with self.assertRaises(AssertionError) as error_context:
         script_helper.assert_python_ok('-c', 'sys.exit(0)')
     error_msg = str(error_context.exception)
     self.assertIn('command line:', error_msg)
     self.assertIn('sys.exit(0)', error_msg, msg='unexpected command line')
开发者ID:Apoorvadabhere,项目名称:cpython,代码行数:7,代码来源:test_script_helper.py

示例5: test_socket

    def test_socket(self):
        # use a subprocess to have only one thread
        code = """if 1:
        import signal
        import socket
        import struct
        import _testcapi

        signum = signal.SIGINT
        signals = (signum,)

        def handler(signum, frame):
            pass

        signal.signal(signum, handler)

        read, write = socket.socketpair()
        write.setblocking(False)
        signal.set_wakeup_fd(write.fileno())

        signal.raise_signal(signum)

        data = read.recv(1)
        if not data:
            raise Exception("no signum written")
        raised = struct.unpack('B', data)
        if raised != signals:
            raise Exception("%r != %r" % (raised, signals))

        read.close()
        write.close()
        """

        assert_python_ok('-c', code)
开发者ID:Eyepea,项目名称:cpython,代码行数:34,代码来源:test_signal.py

示例6: test_set_pycache_prefix

 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)
开发者ID:CCNITSilchar,项目名称:cpython,代码行数:25,代码来源:test_cmd_line.py

示例7: test_sigwait_thread

    def test_sigwait_thread(self):
        # Check that calling sigwait() from a thread doesn't suspend the whole
        # process. A new interpreter is spawned to avoid problems when mixing
        # threads and fork(): only async-safe functions are allowed between
        # fork() and exec().
        assert_python_ok("-c", """if True:
            import os, threading, sys, time, signal

            # the default handler terminates the process
            signum = signal.SIGUSR1

            def kill_later():
                # wait until the main thread is waiting in sigwait()
                time.sleep(1)
                os.kill(os.getpid(), signum)

            # the signal must be blocked by all the threads
            signal.pthread_sigmask(signal.SIG_BLOCK, [signum])
            killer = threading.Thread(target=kill_later)
            killer.start()
            received = signal.sigwait([signum])
            if received != signum:
                print("sigwait() received %s, not %s" % (received, signum),
                      file=sys.stderr)
                sys.exit(1)
            killer.join()
            # unblock the signal, which should have been cleared by sigwait()
            signal.pthread_sigmask(signal.SIG_UNBLOCK, [signum])
        """)
开发者ID:Eyepea,项目名称:cpython,代码行数:29,代码来源:test_signal.py

示例8: test_unencodable_filename

 def test_unencodable_filename(self):
     # Issue #11619: The Python parser and the import machinery must not
     # encode filenames, especially on Windows
     pyname = script_helper.make_script("", TESTFN_UNENCODABLE, "pass")
     self.addCleanup(unlink, pyname)
     name = pyname[:-3]
     script_helper.assert_python_ok("-c", "mod = __import__(%a)" % name, __isolated=False)
开发者ID:francois-wellenreiter,项目名称:cpython,代码行数:7,代码来源:__init__.py

示例9: test_doctest_main_issue4197

    def test_doctest_main_issue4197(self):
        test_src = textwrap.dedent("""\
                    class Test:
                        ">>> 'line 2'"
                        pass

                    import doctest
                    doctest.testmod()
                    """)
        pattern = 'File "%s", line 2, in %s'
        with test.support.temp_dir() as d:
            script_name = make_script(d, 'script', test_src)
            rc, out, err = assert_python_ok(script_name)
            expected = pattern % (script_name, "__main__.Test")
            if verbose:
                print ("Expected line", expected)
                print ("Got stdout:")
                print (ascii(out))
            self.assertIn(expected.encode('utf-8'), out)
            zip_name, run_name = make_zip_script(d, "test_zip",
                                                script_name, '__main__.py')
            rc, out, err = assert_python_ok(zip_name)
            expected = pattern % (run_name, "__main__.Test")
            if verbose:
                print ("Expected line", expected)
                print ("Got stdout:")
                print (ascii(out))
            self.assertIn(expected.encode('utf-8'), out)
开发者ID:10sr,项目名称:cpython,代码行数:28,代码来源:test_zipimport_support.py

示例10: test_hash_randomization

    def test_hash_randomization(self):
        # Verify that -R enables hash randomization:
        self.verify_valid_flag('-R')
        hashes = []
        if os.environ.get('PYTHONHASHSEED', 'random') != 'random':
            env = dict(os.environ)  # copy
            # We need to test that it is enabled by default without
            # the environment variable enabling it for us.
            del env['PYTHONHASHSEED']
            env['__cleanenv'] = '1'  # consumed by assert_python_ok()
        else:
            env = {}
        for i in range(3):
            code = 'print(hash("spam"))'
            rc, out, err = assert_python_ok('-c', code, **env)
            self.assertEqual(rc, 0)
            hashes.append(out)
        hashes = sorted(set(hashes))  # uniq
        # Rare chance of failure due to 3 random seeds honestly being equal.
        self.assertGreater(len(hashes), 1,
                           msg='3 runs produced an identical random hash '
                               ' for "spam": {}'.format(hashes))

        # Verify that sys.flags contains hash_randomization
        code = 'import sys; print("random is", sys.flags.hash_randomization)'
        rc, out, err = assert_python_ok('-c', code)
        self.assertEqual(rc, 0)
        self.assertIn(b'random is 1', out)
开发者ID:cherish3620,项目名称:cpython,代码行数:28,代码来源:test_cmd_line.py

示例11: test_verbose

 def test_verbose(self):
     # -v causes imports to write to stderr.  If the write to
     # stderr itself causes an import to happen (for the output
     # codec), a recursion loop can occur.
     rc, out, err = assert_python_ok('-v')
     self.assertNotIn(b'stack overflow', err)
     rc, out, err = assert_python_ok('-vv')
     self.assertNotIn(b'stack overflow', err)
开发者ID:cherish3620,项目名称:cpython,代码行数:8,代码来源:test_cmd_line.py

示例12: test_run_code

 def test_run_code(self):
     # Test expected operation of the '-c' switch
     # Switch needs an argument
     assert_python_failure('-c')
     # Check we get an error for an uncaught exception
     assert_python_failure('-c', 'raise Exception')
     # All good if execution is successful
     assert_python_ok('-c', 'pass')
开发者ID:cherish3620,项目名称:cpython,代码行数:8,代码来源:test_cmd_line.py

示例13: test_sys_argv_list

    def test_sys_argv_list(self):
        with open(TESTFN, 'w') as fd:
            self.addCleanup(unlink, TESTFN)
            fd.write("import sys\n")
            fd.write("print(type(sys.argv))\n")

        status, direct_stdout, stderr = assert_python_ok(TESTFN)
        status, trace_stdout, stderr = assert_python_ok('-m', 'trace', '-l', TESTFN)
        self.assertIn(direct_stdout.strip(), trace_stdout)
开发者ID:DinoV,项目名称:cpython,代码行数:9,代码来源:test_trace.py

示例14: test_import_in_del_does_not_crash

 def test_import_in_del_does_not_crash(self):
     # Issue 4236
     testfn = script_helper.make_script('', TESTFN, textwrap.dedent("""\
         import sys
         class C:
            def __del__(self):
               import importlib
         sys.argv.insert(0, C())
         """))
     script_helper.assert_python_ok(testfn)
开发者ID:FRidh,项目名称:cpython,代码行数:10,代码来源:__init__.py

示例15: f

 def f(self, ext=ext, switch=switch):
     script_helper.assert_python_ok(*(switch + ["-m", "compileall", "-q", self.pkgdir]))
     # Verify the __pycache__ directory contents.
     self.assertTrue(os.path.exists(self.pkgdir_cachedir))
     expected = sorted(
         base.format(sys.implementation.cache_tag, ext) for base in ("__init__.{}.{}", "bar.{}.{}")
     )
     self.assertEqual(sorted(os.listdir(self.pkgdir_cachedir)), expected)
     # Make sure there are no .pyc files in the source directory.
     self.assertFalse([fn for fn in os.listdir(self.pkgdir) if fn.endswith(ext)])
开发者ID:rayeya,项目名称:cpython,代码行数:10,代码来源:test_compileall.py


注:本文中的test.support.script_helper.assert_python_ok函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。