• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python script_helper.assert_python_ok函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: test_env_var

    def test_env_var(self):
        # not tracing by default
        code = 'import tracemalloc; print(tracemalloc.is_tracing())'
        ok, stdout, stderr = assert_python_ok('-c', code)
        stdout = stdout.rstrip()
        self.assertEqual(stdout, b'False')

        # PYTHON* environment variables must be ignored when -E option is
        # present
        code = 'import tracemalloc; print(tracemalloc.is_tracing())'
        ok, stdout, stderr = assert_python_ok('-E', '-c', code, PYTHONTRACEMALLOC='1')
        stdout = stdout.rstrip()
        self.assertEqual(stdout, b'False')

        # tracing at startup
        code = 'import tracemalloc; print(tracemalloc.is_tracing())'
        ok, stdout, stderr = assert_python_ok('-c', code, PYTHONTRACEMALLOC='1')
        stdout = stdout.rstrip()
        self.assertEqual(stdout, b'True')

        # start and set the number of frames
        code = 'import tracemalloc; print(tracemalloc.get_traceback_limit())'
        ok, stdout, stderr = assert_python_ok('-c', code, PYTHONTRACEMALLOC='10')
        stdout = stdout.rstrip()
        self.assertEqual(stdout, b'10')
开发者ID:AlexHorlenko,项目名称:ironpython3,代码行数:25,代码来源:test_tracemalloc.py


示例2: 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')
     name = pyname[:-3]
     script_helper.assert_python_ok("-c", "mod = __import__(%a)" % name,
                                    __isolated=False)
开发者ID:0jpq0,项目名称:kbengine,代码行数:7,代码来源:test_import.py


示例3: check_wakeup

    def check_wakeup(self, test_body):
        # use a subprocess to have only one thread and to not change signal
        # handling of the parent process
        code = """if 1:
        import fcntl
        import os
        import signal

        def handler(signum, frame):
            pass

        {}

        signal.signal(signal.SIGALRM, handler)
        read, write = os.pipe()
        flags = fcntl.fcntl(write, fcntl.F_GETFL, 0)
        flags = flags | os.O_NONBLOCK
        fcntl.fcntl(write, fcntl.F_SETFL, flags)
        signal.set_wakeup_fd(write)

        test()

        os.close(read)
        os.close(write)
        """.format(test_body)

        assert_python_ok('-c', code)
开发者ID:7modelsan,项目名称:kbengine,代码行数:27,代码来源:test_signal.py


示例4: test_build_ext

    def test_build_ext(self):
        support.copy_xxmodule_c(self.tmp_dir)
        xx_c = os.path.join(self.tmp_dir, 'xxmodule.c')
        xx_ext = Extension('xx', [xx_c])
        dist = Distribution({'name': 'xx', 'ext_modules': [xx_ext]})
        dist.package_dir = self.tmp_dir
        cmd = build_ext(dist)
        support.fixup_build_ext(cmd)
        cmd.build_lib = self.tmp_dir
        cmd.build_temp = self.tmp_dir
        cmd.ensure_finalized()
        cmd.run()

        code = textwrap.dedent("""\
            import sys
            sys.path.insert(0, %r)

            import xx

            for attr in ('error', 'foo', 'new', 'roj'):
                assert hasattr(xx, attr)

            assert xx.foo(2, 5) == 7
            assert xx.foo(13, 15) == 28
            assert xx.new().demo() is None
            doc = 'This is a template module just for instruction.'
            assert xx.__doc__ == doc
            assert isinstance(xx.Null(), xx.Null)
            assert isinstance(xx.Str(), xx.Str)
            """)
        code = code % self.tmp_dir
        assert_python_ok('-c', code)
开发者ID:Naddiseo,项目名称:cpython,代码行数:32,代码来源:test_command_build_ext.py


示例5: 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 was:', error_msg)
     self.assertIn('sys.exit(0)', error_msg, msg='unexpected command line')
开发者ID:chidea,项目名称:GoPythonDLLWrapper,代码行数:7,代码来源:test_script_helper.py


示例6: 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()
        read.setblocking(False)
        write.setblocking(False)
        signal.set_wakeup_fd(write.fileno())

        _testcapi.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:kwatch,项目名称:cpython,代码行数:35,代码来源:test_signal.py


示例7: 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:kwatch,项目名称:cpython,代码行数:26,代码来源:test_signal.py


示例8: 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:BrythonServer,项目名称:brython,代码行数:29,代码来源:test_signal.py


示例9: 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:BrythonServer,项目名称:brython,代码行数:32,代码来源:test_signal.py


示例10: test_finalize_with_trace

    def test_finalize_with_trace(self):
        # Issue1733757
        # Avoid a deadlock when sys.settrace steps into threading._shutdown
        assert_python_ok(
            "-c",
            """if 1:
            import sys, threading

            # A deadlock-killer, to prevent the
            # testsuite to hang forever
            def killer():
                import os, time
                time.sleep(2)
                print('program blocked; aborting')
                os._exit(2)
            t = threading.Thread(target=killer)
            t.daemon = True
            t.start()

            # This is the trace function
            def func(frame, event, arg):
                threading.current_thread()
                return func

            sys.settrace(func)
            """,
        )
开发者ID:pykomke,项目名称:Kurz_Python_KE,代码行数:27,代码来源:test_threading.py


示例11: 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:dougmassay,项目名称:cpython3.4.4,代码行数:28,代码来源:test_cmd_line.py


示例12: test_non_ascii

 def test_non_ascii(self):
     # Test handling of non-ascii data
     if test.support.verbose:
         import locale
         print('locale encoding = %s, filesystem encoding = %s'
               % (locale.getpreferredencoding(), sys.getfilesystemencoding()))
     command = "assert(ord('\xe9') == 0xe9)"
     assert_python_ok('-c', command)
开发者ID:469306621,项目名称:Languages,代码行数:8,代码来源:test_cmd_line.py


示例13: test_xoptions

 def test_xoptions(self):
     rc, out, err = assert_python_ok('-c', 'import sys; print(sys._xoptions)')
     opts = eval(out.splitlines()[0])
     self.assertEqual(opts, {})
     rc, out, err = assert_python_ok(
         '-Xa', '-Xb=c,d=e', '-c', 'import sys; print(sys._xoptions)')
     opts = eval(out.splitlines()[0])
     self.assertEqual(opts, {'a': True, 'b': 'c,d=e'})
开发者ID:7modelsan,项目名称:kbengine,代码行数:8,代码来源:test_cmd_line.py


示例14: 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:7modelsan,项目名称:kbengine,代码行数:8,代码来源:test_cmd_line.py


示例15: 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:7modelsan,项目名称:kbengine,代码行数:8,代码来源:test_cmd_line.py


示例16: 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 imp
         sys.argv.insert(0, C())
         """))
     script_helper.assert_python_ok(testfn)
开发者ID:MichaelBlume,项目名称:pypy,代码行数:10,代码来源:test_import.py


示例17: test_issue_8766

    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)
开发者ID:chidea,项目名称:GoPythonDLLWrapper,代码行数:10,代码来源:test_warnings.py


示例18: 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:Orav,项目名称:kbengine,代码行数:10,代码来源:test_compileall.py


示例19: test_del___main__

 def test_del___main__(self):
     # Issue #15001: PyRun_SimpleFileExFlags() did crash because it kept a
     # borrowed reference to the dict of __main__ module and later modify
     # the dict whereas the module was destroyed
     filename = test.support.TESTFN
     self.addCleanup(test.support.unlink, filename)
     with open(filename, "w") as script:
         print("import sys", file=script)
         print("del sys.modules['__main__']", file=script)
     assert_python_ok(filename)
开发者ID:7modelsan,项目名称:kbengine,代码行数:10,代码来源:test_cmd_line.py


示例20: 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(imp.get_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:alfonsodiecko,项目名称:PYTHON_DIST,代码行数:11,代码来源:test_compileall.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python script_helper.compile_script函数代码示例发布时间:2022-05-27
下一篇:
Python script_helper.assert_python_failure函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap