def make_class(cls):
        # XXX: this is (mostly) wrong: .compile() compiles the code object
        # using the host python compiler, but then in the tests we load it
        # with py.py. It works (mostly by chance) because the two functions
        # are very simple and the bytecodes are compatible enough.
        co = py.code.Source(
            """
        def get_name():
            return __name__
        def get_file():
            return __file__
        """
        ).compile()

        if cls.compression == ZIP_DEFLATED:
            space = gettestobjspace(usemodules=["zipimport", "zlib", "rctime", "struct"])
        else:
            space = gettestobjspace(usemodules=["zipimport", "rctime", "struct"])

        cls.space = space
        tmpdir = udir.ensure("zipimport_%s" % cls.__name__, dir=1)
        now = time.time()
        cls.w_now = space.wrap(now)
        test_pyc = cls.make_pyc(space, co, now)
        cls.w_test_pyc = space.wrap(test_pyc)
        cls.w_compression = space.wrap(cls.compression)
        cls.w_pathsep = space.wrap(cls.pathsep)
        # ziptestmodule = tmpdir.ensure('ziptestmodule.zip').write(
        ziptestmodule = tmpdir.join("somezip.zip")
        cls.w_tmpzip = space.wrap(str(ziptestmodule))
        cls.w_co = space.wrap(co)
        cls.tmpdir = tmpdir
Esempio n. 2
0
    def test_hash_against_normal_tuple(self):
        N_space = gettestobjspace(**{"objspace.std.withspecialisedtuple": False})
        S_space = gettestobjspace(**{"objspace.std.withspecialisedtuple": True})
        
        def hash_test(values, must_be_specialized=True):
            N_values_w = [N_space.wrap(value) for value in values]
            S_values_w = [S_space.wrap(value) for value in values]
            N_w_tuple = N_space.newtuple(N_values_w)
            S_w_tuple = S_space.newtuple(S_values_w)

            if must_be_specialized:
                assert isinstance(S_w_tuple, W_SpecialisedTupleObject)
            assert isinstance(N_w_tuple, W_TupleObject)
            assert S_space.is_true(S_space.eq(N_w_tuple, S_w_tuple))
            assert S_space.is_true(S_space.eq(N_space.hash(N_w_tuple), S_space.hash(S_w_tuple)))

        hash_test([1,2])
        hash_test([1.5,2.8])
        hash_test([1.0,2.0])
        hash_test(['arbitrary','strings'])
        hash_test([1,(1,2,3,4)])
        hash_test([1,(1,2)])
        hash_test([1,('a',2)])
        hash_test([1,()])
        hash_test([1,2,3], must_be_specialized=False)
Esempio n. 3
0
 def setup_class(cls):
     # This imports support_test_sre as the global "s"
     try:
         cls.space = gettestobjspace(usemodules=('_locale', ))
     except py.test.skip.Exception:
         cls.space = gettestobjspace(usemodules=('_rawffi', ))
     init_globals_hack(cls.space)
Esempio n. 4
0
 def setup_class(cls):
     # This imports support_test_sre as the global "s"
     try:
         cls.space = gettestobjspace(usemodules=('_locale',))
     except py.test.skip.Exception:
         cls.space = gettestobjspace(usemodules=('_rawffi',))
     init_globals_hack(cls.space)
Esempio n. 5
0
def setup_module(mod):
    if os.name != 'nt':
        mod.space = gettestobjspace(usemodules=['posix', 'fcntl', 'struct'])
    else:
        # On windows, os.popen uses the subprocess module
        mod.space = gettestobjspace(
            usemodules=['posix', '_rawffi', 'thread', 'struct'])
    mod.path = udir.join('posixtestfile.txt')
    mod.path.write("this is a test")
    mod.path2 = udir.join('test_posix2-')
    pdir = udir.ensure('posixtestdir', dir=True)
    pdir.join('file1').write("test1")
    os.chmod(str(pdir.join('file1')), 0600)
    pdir.join('file2').write("test2")
    pdir.join('another_longer_file_name').write("test3")
    mod.pdir = pdir
    unicode_dir = udir.ensure('fi\xc5\x9fier.txt', dir=True)
    unicode_dir.join('somefile').write('who cares?')
    unicode_dir.join('caf\xe9').write('who knows?')
    mod.unicode_dir = unicode_dir

    # in applevel tests, os.stat uses the CPython os.stat.
    # Be sure to return times with full precision
    # even when running on top of CPython 2.4.
    os.stat_float_times(True)

    # Initialize sys.filesystemencoding
    space.call_method(space.getbuiltinmodule('sys'), 'getfilesystemencoding')
Esempio n. 6
0
def setup_module(mod):
    if os.name != 'nt':
        mod.space = gettestobjspace(usemodules=['posix', 'fcntl'])
    else:
        # On windows, os.popen uses the subprocess module
        mod.space = gettestobjspace(usemodules=['posix', '_rawffi', 'thread'])
    mod.path = udir.join('posixtestfile.txt')
    mod.path.write("this is a test")
    mod.path2 = udir.join('test_posix2-')
    pdir = udir.ensure('posixtestdir', dir=True)
    pdir.join('file1').write("test1")
    os.chmod(str(pdir.join('file1')), 0600)
    pdir.join('file2').write("test2")
    pdir.join('another_longer_file_name').write("test3")
    mod.pdir = pdir
    unicode_dir = udir.ensure('fi\xc5\x9fier.txt', dir=True)
    unicode_dir.join('somefile').write('who cares?')
    mod.unicode_dir = unicode_dir

    # in applevel tests, os.stat uses the CPython os.stat.
    # Be sure to return times with full precision
    # even when running on top of CPython 2.4.
    os.stat_float_times(True)

    # Initialize sys.filesystemencoding
    space.call_method(space.getbuiltinmodule('sys'), 'getfilesystemencoding')
Esempio n. 7
0
    def make_class(cls):
        # XXX: this is (mostly) wrong: .compile() compiles the code object
        # using the host python compiler, but then in the tests we load it
        # with py.py. It works (mostly by chance) because the two functions
        # are very simple and the bytecodes are compatible enough.
        co = py.code.Source("""
        def get_name():
            return __name__
        def get_file():
            return __file__
        """).compile()

        if cls.compression == ZIP_DEFLATED:
            space = gettestobjspace(
                usemodules=['zipimport', 'zlib', 'rctime', 'struct'])
        else:
            space = gettestobjspace(
                usemodules=['zipimport', 'rctime', 'struct'])

        cls.space = space
        tmpdir = udir.ensure('zipimport_%s' % cls.__name__, dir=1)
        now = time.time()
        cls.w_now = space.wrap(now)
        test_pyc = cls.make_pyc(space, co, now)
        cls.w_test_pyc = space.wrap(test_pyc)
        cls.w_compression = space.wrap(cls.compression)
        cls.w_pathsep = space.wrap(cls.pathsep)
        #ziptestmodule = tmpdir.ensure('ziptestmodule.zip').write(
        ziptestmodule = tmpdir.join("somezip.zip")
        cls.w_tmpzip = space.wrap(str(ziptestmodule))
        cls.w_co = space.wrap(co)
        cls.tmpdir = tmpdir
 def setup_class(cls):
     try:
         cls.space = gettestobjspace(usemodules=('_locale',))
     except Skipped:
         cls.space = gettestobjspace(usemodules=('_rawffi',))
     # This imports support_test_sre as the global "s"
     init_globals_hack(cls.space)
Esempio n. 9
0
 def setup_class(cls):
     try:
         cls.space = gettestobjspace(usemodules=('_locale', ))
     except Skipped:
         cls.space = gettestobjspace(usemodules=('_rawffi', ))
     # This imports support_test_sre as the global "s"
     init_globals_hack(cls.space)
Esempio n. 10
0
 def test_abi_tag(self):
     space1 = gettestobjspace(soabi='TEST')
     space2 = gettestobjspace(soabi='')
     if sys.platform == 'win32':
         assert importing.get_so_extension(space1) == '.TESTi.pyd'
         assert importing.get_so_extension(space2) == '.pyd'
     else:
         assert importing.get_so_extension(space1) == '.TESTi.so'
         assert importing.get_so_extension(space2) == '.so'
Esempio n. 11
0
 def test_abi_tag(self):
     space1 = gettestobjspace(soabi='TEST')
     space2 = gettestobjspace(soabi='')
     if sys.platform == 'win32':
         assert importing.get_so_extension(space1) == '.TESTi.pyd'
         assert importing.get_so_extension(space2) == '.pyd'
     else:
         assert importing.get_so_extension(space1) == '.TESTi.so'
         assert importing.get_so_extension(space2) == '.so'
Esempio n. 12
0
    def test_hash_agains_normal_tuple(self):
        normalspace = gettestobjspace(**{"objspace.std.withsmalltuple": False})
        w_tuple = normalspace.newtuple([self.space.wrap(1), self.space.wrap(2)])

        smallspace = gettestobjspace(**{"objspace.std.withsmalltuple": True})
        w_smalltuple = smallspace.newtuple([self.space.wrap(1), self.space.wrap(2)])

        assert isinstance(w_smalltuple, W_SmallTupleObject)
        assert isinstance(w_tuple, W_TupleObject)
        assert not normalspace.is_true(normalspace.eq(w_tuple, w_smalltuple))
        assert smallspace.is_true(smallspace.eq(w_tuple, w_smalltuple))
        assert smallspace.is_true(smallspace.eq(normalspace.hash(w_tuple), smallspace.hash(w_smalltuple)))
Esempio n. 13
0
 def setup_class(cls):
     cls.space = gettestobjspace(usemodules=['cpyext', 'thread', '_rawffi'])
     cls.space.getbuiltinmodule("cpyext")
     from pypy.module.imp.importing import importhook
     importhook(cls.space, "os")  # warm up reference counts
     state = cls.space.fromcache(RefcountState)
     state.non_heaptypes_w[:] = []
Esempio n. 14
0
 def setup_class(cls):
     space = gettestobjspace()
     cls.space = space
     if py.test.config.option.runappdirect:
         cls.w_file = space.wrap(__file__[:-1])
     else:
         cls.w_file = space.wrap("None<%s" % gateway.__file__[:-1])
Esempio n. 15
0
 def setup_class(cls):
     cls.space = gettestobjspace(**{"objspace.std.withmapdict": True})
     if option.runappdirect:
         py.test.skip("can only be run on py.py")
     def has_mapdict(space, w_inst):
         return space.wrap(w_inst._get_mapdict_map() is not None)
     cls.w_has_mapdict = cls.space.wrap(gateway.interp2app(has_mapdict))
Esempio n. 16
0
 def setup_class(cls):
     space = gettestobjspace(usemodules=('_continuation', '_socket'))
     cls.space = space
     if option.runappdirect:
         cls.w_lev = space.wrap(14)
     else:
         cls.w_lev = space.wrap(2)
    def setup_class(cls):
        space = gettestobjspace(usemodules=("_stackless",), **cls.OPTIONS)
        cls.space = space

        from pypy.rlib import rstack

        cls.old_resume_state_create = rstack.resume_state_create

        def tr(prevstate, label, *args):
            if prevstate is None:
                prevstate = []
            return prevstate + [(label, args)]

        rstack.resume_state_create = tr

        w_opmap = space.appexec(
            [],
            """():
        import opcode

        return opcode.opmap
        """,
        )

        opmap = space.unwrap(w_opmap)
        cls.CALL_FUNCTION = opmap["CALL_FUNCTION"]
        cls.CALL_FUNCTION_VAR = opmap["CALL_FUNCTION_VAR"]
        cls.CALL_METHOD = opmap["CALL_METHOD"]

        cls.callmethod = getattr(cls, cls.callmethod_label)
Esempio n. 18
0
 def setup_class(cls):
     space = gettestobjspace(usemodules=('_rawffi', 'struct'))
     cls.space = space
     cls.w_sizes_and_alignments = space.wrap(
         dict([(k, (v.c_size, v.c_alignment))
               for k, v in TYPEMAP.iteritems()]))
     Tracker.DO_TRACING = True
Esempio n. 19
0
    def setup_class(cls):
        space = gettestobjspace(usemodules=("thread", "time"))
        cls.space = space

        if option.runappdirect:

            def plain_waitfor(condition, delay=1):
                adaptivedelay = 0.04
                limit = time.time() + NORMAL_TIMEOUT * delay
                while time.time() <= limit:
                    time.sleep(adaptivedelay)
                    gc.collect()
                    if condition():
                        return
                    adaptivedelay *= 1.05
                print "*** timed out ***"

            cls.w_waitfor = plain_waitfor
        else:
            cls.w_waitfor = space.wrap(interp2app_temp(waitfor))
        cls.w_busywait = space.appexec(
            [],
            """():
            import time
            return time.sleep
        """,
        )
Esempio n. 20
0
    def setup_class(cls):
        cls.space = space = gettestobjspace(usemodules=['_locale'])
        if sys.platform != 'win32':
            cls.w_language_en = cls.space.wrap("en_US")
            cls.w_language_utf8 = cls.space.wrap("en_US.UTF-8")
            cls.w_language_pl = cls.space.wrap("pl_PL.UTF-8")
            cls.w_encoding_pl = cls.space.wrap("utf-8")
        else:
            cls.w_language_en = cls.space.wrap("English_US")
            cls.w_language_utf8 = cls.space.wrap("English_US.65001")
            cls.w_language_pl = cls.space.wrap("Polish_Poland.1257")
            cls.w_encoding_pl = cls.space.wrap("cp1257")
        import _locale
        # check whether used locales are installed, otherwise the tests will
        # fail
        current = _locale.setlocale(_locale.LC_ALL)
        try:
            try:
                _locale.setlocale(_locale.LC_ALL,
                                  space.str_w(cls.w_language_en))
                _locale.setlocale(_locale.LC_ALL,
                                  space.str_w(cls.w_language_pl))
            except _locale.Error:
                py.test.skip("necessary locales not installed")

            # Windows forbids the UTF-8 character set since Windows XP.
            try:
                _locale.setlocale(_locale.LC_ALL,
                                  space.str_w(cls.w_language_utf8))
            except _locale.Error:
                del cls.w_language_utf8
        finally:
            _locale.setlocale(_locale.LC_ALL, current)
Esempio n. 21
0
    def setup_class(cls):
        if sys.platform == 'win32':
            py.test.skip("select() doesn't work with pipes on win32")
        space = gettestobjspace(usemodules=('select', ))
        cls.space = space

        # Wraps a file descriptor in an socket-like object
        space.exec_(
            '''if 1:
        import os
        class FileAsSocket:
            def __init__(self, fd):
                self.fd = fd
            def fileno(self):
                return self.fd
            def send(self, data):
                return os.write(self.fd, data)
            def recv(self, length):
                return os.read(self.fd, length)
            def close(self):
                return os.close(self.fd)
        def getpair():
            s1, s2 = os.pipe()
            return FileAsSocket(s1), FileAsSocket(s2)''', space.builtin.w_dict,
            space.builtin.w_dict)
Esempio n. 22
0
 def setup_class(cls):
     cls.space = gettestobjspace(usemodules=['cpyext', 'thread', '_rawffi'])
     cls.space.getbuiltinmodule("cpyext")
     from pypy.module.imp.importing import importhook
     importhook(cls.space, "os") # warm up reference counts
     state = cls.space.fromcache(RefcountState)
     state.non_heaptypes_w[:] = []
Esempio n. 23
0
 def setup_class(cls):
     cls.space = gettestobjspace(
         **{
             "objspace.std.withrope": True,
             "objspace.std.withprebuiltchar": False,
             "objspace.std.sharesmallstr": False
         })
Esempio n. 24
0
 def setup_class(cls):
     if not option.runappdirect:
         py.test.skip("likely to deadlock when interpreted by py.py")
     cls.space = gettestobjspace(usemodules=("_file", "thread"))
     cls.w_temppath = cls.space.wrap(
         str(py.test.ensuretemp("fileimpl").join("concurrency.txt")))
     cls.w_file = getfile(cls.space)
Esempio n. 25
0
    def setup_class(cls):
        if sys.platform == "win32":
            py.test.skip("select() doesn't work with pipes on win32")
        space = gettestobjspace(usemodules=("select",))
        cls.space = space

        # Wraps a file descriptor in an socket-like object
        cls.w_getpair = space.appexec(
            [],
            """():
        import os
        class FileAsSocket:
            def __init__(self, fd):
                self.fd = fd
            def fileno(self):
                return self.fd
            def send(self, data):
                return os.write(self.fd, data)
            def recv(self, length):
                return os.read(self.fd, length)
            def close(self):
                return os.close(self.fd)
        def getpair():
            s1, s2 = os.pipe()
            return FileAsSocket(s1), FileAsSocket(s2)
        return getpair""",
        )
Esempio n. 26
0
 def setup_class(cls):
     cls.space = gettestobjspace(
         **{
             "objspace.std.withmethodcachecounter": True,
             "objspace.std.withmapdict": True,
             "objspace.opcodes.CALL_METHOD": True
         })
Esempio n. 27
0
    def test_hash_agains_normal_tuple(self):
        normalspace = gettestobjspace(**{"objspace.std.withsmalltuple": False})
        w_tuple = normalspace.newtuple(
            [self.space.wrap(1), self.space.wrap(2)])

        smallspace = gettestobjspace(**{"objspace.std.withsmalltuple": True})
        w_smalltuple = smallspace.newtuple(
            [self.space.wrap(1), self.space.wrap(2)])

        assert isinstance(w_smalltuple, W_SmallTupleObject)
        assert isinstance(w_tuple, W_TupleObject)
        assert not normalspace.is_true(normalspace.eq(w_tuple, w_smalltuple))
        assert smallspace.is_true(smallspace.eq(w_tuple, w_smalltuple))
        assert smallspace.is_true(
            smallspace.eq(normalspace.hash(w_tuple),
                          smallspace.hash(w_smalltuple)))
Esempio n. 28
0
 def setup_class(cls):
     space = gettestobjspace(usemodules=('_continuation', '_socket'))
     cls.space = space
     if option.runappdirect:
         cls.w_lev = space.wrap(14)
     else:
         cls.w_lev = space.wrap(2)
Esempio n. 29
0
 def setup_class(cls):
     space = gettestobjspace(usemodules=('_rawffi', 'struct'))
     cls.space = space
     cls.w_lib_name = space.wrap(cls.prepare_c_example())
     cls.w_sizes_and_alignments = space.wrap(
         dict([(k, (v.c_size, v.c_alignment))
               for k, v in TYPEMAP.iteritems()]))
Esempio n. 30
0
    def setup_class(cls):
        cls.space = space = gettestobjspace(usemodules=['_locale'])
        if sys.platform != 'win32':
            cls.w_language_en = cls.space.wrap("en_US")
            cls.w_language_utf8 = cls.space.wrap("en_US.UTF-8")
            cls.w_language_pl = cls.space.wrap("pl_PL.UTF-8")
            cls.w_encoding_pl = cls.space.wrap("utf-8")
        else:
            cls.w_language_en = cls.space.wrap("English_US")
            cls.w_language_utf8 = cls.space.wrap("English_US.65001")
            cls.w_language_pl = cls.space.wrap("Polish_Poland.1257")
            cls.w_encoding_pl = cls.space.wrap("cp1257")
        import _locale
        # check whether used locales are installed, otherwise the tests will
        # fail
        current = _locale.setlocale(_locale.LC_ALL)
        try:
            try:
                _locale.setlocale(_locale.LC_ALL,
                                  space.str_w(cls.w_language_en))
                _locale.setlocale(_locale.LC_ALL,
                                  space.str_w(cls.w_language_pl))
            except _locale.Error:
                py.test.skip("necessary locales not installed")

            # Windows forbids the UTF-8 character set since Windows XP.
            try:
                _locale.setlocale(_locale.LC_ALL,
                                  space.str_w(cls.w_language_utf8))
            except _locale.Error:
                del cls.w_language_utf8
        finally:
            _locale.setlocale(_locale.LC_ALL, current)
 def setup_class(cls):
     space = gettestobjspace(usemodules=('bz2',))
     cls.space = space
     cls.w_TEXT = space.wrap(TEXT)
     cls.w_DATA = space.wrap(DATA)
     cls.w_decompress = space.wrap(decompress)
     cls.w_HUGE_OK = space.wrap(HUGE_OK)
Esempio n. 32
0
    def setup_class(cls):
        if option.runappdirect:
            py.test.skip("Can't run this test with -A")
        space = gettestobjspace(usemodules=('pypyjit',))
        cls.space = space
        w_f = space.appexec([], """():
        def f():
            pass
        return f
        """)
        ll_code = cast_instance_to_base_ptr(w_f.code)
        logger = Logger(MockSD())

        oplist = parse("""
        [i1, i2]
        i3 = int_add(i1, i2)
        guard_true(i3) []
        """, namespace={'ptr0': 3}).operations

        def interp_on_compile():
            pypyjitdriver.on_compile(logger, LoopToken(), oplist, 'loop',
                                     0, False, ll_code)

        def interp_on_compile_bridge():
            pypyjitdriver.on_compile_bridge(logger, LoopToken(), oplist, 0)
        
        cls.w_on_compile = space.wrap(interp2app(interp_on_compile))
        cls.w_on_compile_bridge = space.wrap(interp2app(interp_on_compile_bridge))
Esempio n. 33
0
 def setup_class(cls):
     cls.space = gettestobjspace(**{"objspace.std.withcelldict": True})
     cls.w_impl_used = cls.space.appexec([], """():
         import __pypy__
         def impl_used(obj):
             assert "ModuleDictImplementation" in __pypy__.internal_repr(obj)
         return impl_used
     """)
     def is_in_cache(space, w_code, w_globals, w_name):
         name = space.str_w(w_name)
         cache = get_global_cache(space, w_code, w_globals)
         index = [space.str_w(w_n) for w_n in w_code.co_names_w].index(name)
         return space.wrap(cache[index].w_value is not None)
     is_in_cache = gateway.interp2app(is_in_cache)
     cls.w_is_in_cache = cls.space.wrap(is_in_cache) 
     stored_builtins = []
     def rescue_builtins(space):
         w_dict = space.builtin.getdict()
         content = {}
         for key, cell in w_dict.implementation.content.iteritems():
             newcell = ModuleCell()
             newcell.w_value = cell.w_value
             content[key] = newcell
         stored_builtins.append(content)
     rescue_builtins = gateway.interp2app(rescue_builtins)
     cls.w_rescue_builtins = cls.space.wrap(rescue_builtins) 
     def restore_builtins(space):
         w_dict = space.builtin.getdict()
         if not isinstance(w_dict.implementation, ModuleDictImplementation):
             w_dict.implementation = ModuleDictImplementation(space)
         w_dict.implementation.content = stored_builtins.pop()
     restore_builtins = gateway.interp2app(restore_builtins)
     cls.w_restore_builtins = cls.space.wrap(restore_builtins) 
Esempio n. 34
0
    def setup_class(cls):
        space = gettestobjspace(usemodules=('_multiprocessing', 'thread',
                                            'signal'))
        cls.space = space
        cls.w_connections = space.newlist([])

        def socketpair(space):
            "A socket.socketpair() that works on Windows"
            import socket, errno
            serverSocket = socket.socket()
            serverSocket.bind(('127.0.0.1', 0))
            serverSocket.listen(1)

            client = socket.socket()
            client.setblocking(False)
            try:
                client.connect(('127.0.0.1', serverSocket.getsockname()[1]))
            except socket.error, e:
                assert e.args[0] in (errno.EINPROGRESS, errno.EWOULDBLOCK)
            server, addr = serverSocket.accept()

            # keep sockets alive during the test
            space.call_method(cls.w_connections, "append", space.wrap(server))
            space.call_method(cls.w_connections, "append", space.wrap(client))

            return space.wrap((server.fileno(), client.fileno()))
Esempio n. 35
0
 def setup_class(cls):
     cls.space = gettestobjspace(usemodules=['itertools'])
     if cls.space.is_true(
             cls.space.appexec([], """():
         import sys; return sys.version_info < (2, 7)
         """)):
         py.test.skip("Requires Python 2.7")
Esempio n. 36
0
    def setup_class(cls):
        space = gettestobjspace(usemodules=('_stackless', ), **cls.OPTIONS)
        cls.space = space

        from pypy.rlib import rstack
        cls.old_resume_state_create = rstack.resume_state_create

        def tr(prevstate, label, *args):
            if prevstate is None:
                prevstate = []
            return prevstate + [(label, args)]

        rstack.resume_state_create = tr

        w_opmap = space.appexec([], """():
        import opcode

        return opcode.opmap
        """)

        opmap = space.unwrap(w_opmap)
        cls.CALL_FUNCTION = opmap['CALL_FUNCTION']
        cls.CALL_FUNCTION_VAR = opmap['CALL_FUNCTION_VAR']
        cls.CALL_METHOD = opmap['CALL_METHOD']

        cls.callmethod = getattr(cls, cls.callmethod_label)
Esempio n. 37
0
 def setup_class(cls):
     from pypy.interpreter import gateway
     cls.space = gettestobjspace(
         **{"objspace.std.withmapdict": True,
            "objspace.std.withmethodcachecounter": True,
            "objspace.opcodes.CALL_METHOD": True})
     #
     def check(space, w_func, name):
         w_code = space.getattr(w_func, space.wrap('func_code'))
         nameindex = map(space.str_w, w_code.co_names_w).index(name)
         entry = w_code._mapdict_caches[nameindex]
         entry.failure_counter = 0
         entry.success_counter = 0
         INVALID_CACHE_ENTRY.failure_counter = 0
         #
         w_res = space.call_function(w_func)
         assert space.eq_w(w_res, space.wrap(42))
         #
         entry = w_code._mapdict_caches[nameindex]
         if entry is INVALID_CACHE_ENTRY:
             failures = successes = 0
         else:
             failures = entry.failure_counter
             successes = entry.success_counter
         globalfailures = INVALID_CACHE_ENTRY.failure_counter
         return space.wrap((failures, successes, globalfailures))
     check.unwrap_spec = [gateway.ObjSpace, gateway.W_Root, str]
     cls.w_check = cls.space.wrap(gateway.interp2app(check))
Esempio n. 38
0
    def setup_class(cls):
        space = gettestobjspace(usemodules=('thread', 'time', 'signal'))
        cls.space = space

        if option.runappdirect:

            def plain_waitfor(self, condition, delay=1):
                adaptivedelay = 0.04
                limit = time.time() + NORMAL_TIMEOUT * delay
                while time.time() <= limit:
                    time.sleep(adaptivedelay)
                    gc.collect()
                    if condition():
                        return
                    adaptivedelay *= 1.05
                print '*** timed out ***'

            cls.w_waitfor = plain_waitfor
        else:
            cls.w_waitfor = space.wrap(lambda self, condition, delay=1:
                                       waitfor(space, condition, delay))
        cls.w_busywait = space.appexec([], """():
            import time
            return time.sleep
        """)

        cls.w_timeout_killer = space.wrap(
            lambda self, *args, **kwargs: timeout_killer(*args, **kwargs))
Esempio n. 39
0
    def setup_class(cls):
        space = gettestobjspace(usemodules=('_multiprocessing', 'thread', 'signal',
                                            'struct', 'array'))
        cls.space = space
        cls.w_connections = space.newlist([])

        def socketpair(space):
            "A socket.socketpair() that works on Windows"
            import socket, errno
            serverSocket = socket.socket()
            serverSocket.bind(('127.0.0.1', 0))
            serverSocket.listen(1)

            client = socket.socket()
            client.setblocking(False)
            try:
                client.connect(('127.0.0.1', serverSocket.getsockname()[1]))
            except socket.error, e:
                assert e.args[0] in (errno.EINPROGRESS, errno.EWOULDBLOCK)
            server, addr = serverSocket.accept()

            # keep sockets alive during the test
            space.call_method(cls.w_connections, "append", space.wrap(server))
            space.call_method(cls.w_connections, "append", space.wrap(client))

            return space.wrap((server.fileno(), client.fileno()))
Esempio n. 40
0
 def setup_class(cls):
     if not option.runappdirect:
         py.test.skip("likely to deadlock when interpreted by py.py")
     cls.space = gettestobjspace(usemodules=("_file", "thread"))
     cls.w_temppath = cls.space.wrap(
         str(py.test.ensuretemp("fileimpl").join("concurrency.txt")))
     cls.w_file = getfile(cls.space)
Esempio n. 41
0
def test_direct():
    space = gettestobjspace(**{"objspace.std.withsmalllong": True})
    w5 = space.wrap(r_longlong(5))
    assert isinstance(w5, W_SmallLongObject)
    wlarge = space.wrap(r_longlong(0x123456789ABCDEFL))
    #
    assert space.int_w(w5) == 5
    if sys.maxint < 0x123456789ABCDEFL:
        py.test.raises(OperationError, space.int_w, wlarge)
    else:
        assert space.int_w(wlarge) == 0x123456789ABCDEF
    #
    assert space.pos(w5) is w5
    assert space.abs(w5) is w5
    wm5 = space.wrap(r_longlong(-5))
    assert space.int_w(space.abs(wm5)) == 5
    assert space.int_w(space.neg(w5)) == -5
    assert space.is_true(w5) is True
    assert space.is_true(wm5) is True
    w0 = space.wrap(r_longlong(0))
    assert space.is_true(w0) is False
    #
    w14000000000000 = space.wrap(r_longlong(0x14000000000000L))
    assert space.is_true(space.eq(
        space.lshift(w5, space.wrap(49)), w14000000000000)) is False
    assert space.is_true(space.eq(
        space.lshift(w5, space.wrap(50)), w14000000000000)) is True
    #
    w_huge = space.sub(space.lshift(w5, space.wrap(150)), space.wrap(1))
    wx = space.and_(w14000000000000, w_huge)
    assert space.is_true(space.eq(wx, w14000000000000))
Esempio n. 42
0
    def setup_class(cls):
        from pypy.interpreter import gateway
        cls.space = gettestobjspace(
            **{
                "objspace.std.withmapdict": True,
                "objspace.std.withmethodcachecounter": True,
                "objspace.opcodes.CALL_METHOD": True
            })

        #
        def check(space, w_func, name):
            w_code = space.getattr(w_func, space.wrap('func_code'))
            nameindex = map(space.str_w, w_code.co_names_w).index(name)
            entry = w_code._mapdict_caches[nameindex]
            entry.failure_counter = 0
            entry.success_counter = 0
            INVALID_CACHE_ENTRY.failure_counter = 0
            #
            w_res = space.call_function(w_func)
            assert space.eq_w(w_res, space.wrap(42))
            #
            entry = w_code._mapdict_caches[nameindex]
            if entry is INVALID_CACHE_ENTRY:
                failures = successes = 0
            else:
                failures = entry.failure_counter
                successes = entry.success_counter
            globalfailures = INVALID_CACHE_ENTRY.failure_counter
            return space.wrap((failures, successes, globalfailures))

        check.unwrap_spec = [gateway.ObjSpace, gateway.W_Root, str]
        cls.w_check = cls.space.wrap(gateway.interp2app(check))
Esempio n. 43
0
    def setup_class(cls):
        if not option.runappdirect:
            py.test.skip("Cannot run this on top of py.py because of PopenGateway")
        cls.space = gettestobjspace(**{"objspace.std.withtproxy": True,
                                       "usemodules":("_stackless",)})
        cls.w_remote_side_code = cls.space.appexec([], """():
        import sys
        sys.path.insert(0, '%s')
        remote_side_code = '''
class A:
   def __init__(self, x):
       self.x = x
            
   def __len__(self):
       return self.x + 8

   def raising(self):
       1/0

   def method(self, x):
       return x() + self.x

a = A(3)

def count():
    x = 10
    # naive counting :)
    result = 1
    for i in range(x):
        result += 1
    return result
'''
        return remote_side_code
        """ % str(py.path.local(__file__).dirpath().dirpath().dirpath().dirpath()))
Esempio n. 44
0
    def setup_class(cls):
        space = gettestobjspace(usemodules=('thread', 'time', 'signal'))
        cls.space = space

        if option.runappdirect:
            def plain_waitfor(self, condition, delay=1):
                adaptivedelay = 0.04
                limit = time.time() + NORMAL_TIMEOUT * delay
                while time.time() <= limit:
                    time.sleep(adaptivedelay)
                    gc.collect()
                    if condition():
                        return
                    adaptivedelay *= 1.05
                print '*** timed out ***'
                
            cls.w_waitfor = plain_waitfor
        else:
            cls.w_waitfor = space.wrap(lambda self, condition, delay=1: waitfor(space, condition, delay))
        cls.w_busywait = space.appexec([], """():
            import time
            return time.sleep
        """)
        
        cls.w_timeout_killer = space.wrap(lambda self, *args, **kwargs: timeout_killer(*args, **kwargs))
Esempio n. 45
0
 def setup_class(cls):
     space = gettestobjspace(usemodules=('bz2', ))
     cls.space = space
     cls.w_TEXT = space.wrap(TEXT)
     cls.w_DATA = space.wrap(DATA)
     cls.w_decompress = space.wrap(decompress)
     cls.w_HUGE_OK = space.wrap(HUGE_OK)
Esempio n. 46
0
    def setup_class(cls):
        cls.space = gettestobjspace(**{"objspace.std.withstrslice": True})

        def not_forced(space, w_s):
            return space.wrap(isinstance(w_s, W_StringSliceObject) and (w_s.start != 0 or w_s.stop != len(w_s.str)))

        cls.w_not_forced = cls.space.wrap(gateway.interp2app(not_forced))
Esempio n. 47
0
    def _prepare(self): 
        if hasattr(self, 'name2item'): 
            return
        self.name2item = {}
        space = gettestobjspace(usemodules=self.regrtest.usemodules)
        if self.regrtest.dumbtest or self.regrtest.getoutputpath(): 
            self.name2item['output'] = SimpleRunItem('output', self) 
            return 

        tup = start_intercept(space) 
        self.regrtest.run_file(space)
        w_namemethods, w_doctestlist = collect_intercept(space, *tup) 

        # setup {name -> wrapped testcase method}
        for w_item in space.unpackiterable(w_namemethods): 
            w_name, w_method = space.unpacktuple(w_item) 
            name = space.str_w(w_name) 
            testitem = AppTestCaseMethod(name, parent=self, w_method=w_method) 
            self.name2item[name] = testitem

        # setup {name -> wrapped doctest module}
        for w_item in space.unpackiterable(w_doctestlist): 
            w_name, w_module = space.unpacktuple(w_item) 
            name = space.str_w(w_name) 
            testitem = AppDocTestModule(name, parent=self, w_module=w_module)
            self.name2item[name] = testitem 
Esempio n. 48
0
 def setup_class(cls):
     if option.runappdirect:
         if '__pypy__' not in sys.builtin_module_names:
             import numpy
             sys.modules['numpypy'] = numpy
             sys.modules['_numpypy'] = numpy
     cls.space = gettestobjspace(usemodules=['micronumpy'])
Esempio n. 49
0
 def test_pyc_magic_changes(self):
     # test that the pyc files produced by a space are not reimportable
     # from another, if they differ in what opcodes they support
     allspaces = [self.space]
     for opcodename in self.space.config.objspace.opcodes.getpaths():
         key = 'objspace.opcodes.' + opcodename
         space2 = gettestobjspace(**{key: True})
         allspaces.append(space2)
     for space1 in allspaces:
         for space2 in allspaces:
             if space1 is space2:
                 continue
             pathname = "whatever"
             mtime = 12345
             co = compile('x = 42', '?', 'exec')
             cpathname = _testfile(importing.get_pyc_magic(space1),
                                   mtime, co)
             w_modulename = space2.wrap('somemodule')
             stream = streamio.open_file_as_stream(cpathname, "rb")
             try:
                 w_mod = space2.wrap(Module(space2, w_modulename))
                 magic = importing._r_long(stream)
                 timestamp = importing._r_long(stream)
                 space2.raises_w(space2.w_ImportError,
                                 importing.load_compiled_module,
                                 space2,
                                 w_modulename,
                                 w_mod,
                                 cpathname,
                                 magic,
                                 timestamp,
                                 stream.readall())
             finally:
                 stream.close()
Esempio n. 50
0
    def setup_class(cls):
        if option.runappdirect:
            py.test.skip("Can't run this test with -A")
        space = gettestobjspace(usemodules=('pypyjit',))
        cls.space = space
        w_f = space.appexec([], """():
        def function():
            pass
        return function
        """)
        cls.w_f = w_f
        ll_code = cast_instance_to_base_ptr(w_f.code)
        code_gcref = lltype.cast_opaque_ptr(llmemory.GCREF, ll_code)
        logger = Logger(MockSD())

        oplist = parse("""
        [i1, i2, p2]
        i3 = int_add(i1, i2)
        debug_merge_point(0, 0, 0, 0, 0, ConstPtr(ptr0))
        guard_nonnull(p2) []
        guard_true(i3) []
        """, namespace={'ptr0': code_gcref}).operations
        greenkey = [ConstInt(0), ConstInt(0), ConstPtr(code_gcref)]
        offset = {}
        for i, op in enumerate(oplist):
            if i != 1:
               offset[op] = i

        di_loop = JitDebugInfo(MockJitDriverSD, logger, JitCellToken(),
                               oplist, 'loop', greenkey)
        di_loop_optimize = JitDebugInfo(MockJitDriverSD, logger, JitCellToken(),
                                        oplist, 'loop', greenkey)
        di_loop.asminfo = AsmInfo(offset, 0, 0)
        di_bridge = JitDebugInfo(MockJitDriverSD, logger, JitCellToken(),
                                 oplist, 'bridge', fail_descr_no=0)
        di_bridge.asminfo = AsmInfo(offset, 0, 0)

        def interp_on_compile():
            di_loop.oplist = cls.oplist
            pypy_hooks.after_compile(di_loop)

        def interp_on_compile_bridge():
            pypy_hooks.after_compile_bridge(di_bridge)

        def interp_on_optimize():
            di_loop_optimize.oplist = cls.oplist
            pypy_hooks.before_compile(di_loop_optimize)

        def interp_on_abort():
            pypy_hooks.on_abort(ABORT_TOO_LONG, pypyjitdriver, greenkey,
                                'blah')

        cls.w_on_compile = space.wrap(interp2app(interp_on_compile))
        cls.w_on_compile_bridge = space.wrap(interp2app(interp_on_compile_bridge))
        cls.w_on_abort = space.wrap(interp2app(interp_on_abort))
        cls.w_int_add_num = space.wrap(rop.INT_ADD)
        cls.w_dmp_num = space.wrap(rop.DEBUG_MERGE_POINT)
        cls.w_on_optimize = space.wrap(interp2app(interp_on_optimize))
        cls.orig_oplist = oplist
Esempio n. 51
0
 def setup_class(cls):
     cls.space = gettestobjspace(**{"objspace.std.withcelldict": True})
     cls.w_impl_used = cls.space.appexec([], """():
         import __pypy__
         def impl_used(obj):
             assert "ModuleDictImplementation" in __pypy__.internal_repr(obj)
         return impl_used
     """)
Esempio n. 52
0
 def setup_class(cls):
     if not option.runappdirect:
         py.test.skip("meant only for pypy-c")
     cls.space = gettestobjspace(usemodules=['pypyjit'])
     cls.tmpdir = udir.join('pypy-jit')
     cls.tmpdir.ensure(dir=1)
     cls.counter = 0
     cls.pypy_c = sys.executable
Esempio n. 53
0
 def test_trylock(self):
     space = gettestobjspace(usemodules=["thread"])
     lock = interp_bufferedio.TryLock(space)
     with lock:
         pass
     with lock:
         exc = py.test.raises(OperationError, "with lock: pass")
     assert exc.value.match(space, space.w_RuntimeError)
Esempio n. 54
0
 def setup_class(cls):
     cls.space = gettestobjspace(**{
         "objspace.usepycfiles": cls.usepycfiles,
         "objspace.lonepycfiles": cls.lonepycfiles,
         })
     cls.w_usepycfiles = cls.space.wrap(cls.usepycfiles)
     cls.w_lonepycfiles = cls.space.wrap(cls.lonepycfiles)
     cls.saved_modules = _setup(cls.space)
Esempio n. 55
0
 def setup_class(cls):
     cls.space = gettestobjspace(**{"objspace.std.withsmalltuple": True})
     cls.w_issmall = cls.space.appexec([], """():
         import __pypy__
         def issmall(obj):
             assert "SmallTuple" in __pypy__.internal_repr(obj)
         return issmall
     """)