Exemplo n.º 1
0
class StringlikeHashRandomizationTests(HashRandomizationTests):
    if check_impl_detail(pypy=True):
        EMPTY_STRING_HASH = -1
    else:
        EMPTY_STRING_HASH = 0

    def test_null_hash(self):
        # PYTHONHASHSEED=0 disables the randomized hash
        if IS_64BIT:
            known_hash_of_obj = 1453079729188098211
        else:
            known_hash_of_obj = -1600925533

        # Randomization is disabled by default:
        self.assertEqual(self.get_hash(self.repr_), known_hash_of_obj)

        # It can also be disabled by setting the seed to 0:
        self.assertEqual(self.get_hash(self.repr_, seed=0), known_hash_of_obj)

    def test_fixed_hash(self):
        # test a fixed seed for the randomized hash
        # Note that all types share the same values:
        if IS_64BIT:
            if sys.byteorder == 'little':
                h = -4410911502303878509
            else:
                h = -3570150969479994130
        else:
            if sys.byteorder == 'little':
                h = -206076799
            else:
                h = -1024014457
        self.assertEqual(self.get_hash(self.repr_, seed=42), h)
Exemplo n.º 2
0
 def test_getbuffer(self):
     memio = self.ioclass(b"1234567890")
     buf = memio.getbuffer()
     self.assertEqual(bytes(buf), b"1234567890")
     memio.seek(5)
     buf = memio.getbuffer()
     self.assertEqual(bytes(buf), b"1234567890")
     # Trying to change the size of the BytesIO while a buffer is exported
     # raises a BufferError.
     if support.check_impl_detail(pypy=False):
         # PyPy export buffers differently, and allows reallocation
         # of the underlying object.
         self.assertRaises(BufferError, memio.write, b'x' * 100)
         self.assertRaises(BufferError, memio.truncate)
         self.assertRaises(BufferError, memio.close)
         self.assertFalse(memio.closed)
     # Mutating the buffer updates the BytesIO
     buf[3:6] = b"abc"
     self.assertEqual(bytes(buf), b"123abc7890")
     self.assertEqual(memio.getvalue(), b"123abc7890")
     # After the buffer gets released, we can resize and close the BytesIO
     # again
     del buf
     support.gc_collect()
     memio.truncate()
     memio.close()
     self.assertRaises(ValueError, memio.getbuffer)
 def check_resurrecting_chain(self, classes):
     if support.check_impl_detail(pypy=True):
         self.skipTest("in CPython, in a cycle of objects with __del__(), "
                       "all the __del__() are called even if some of them "
                       "resurrect.  In PyPy the recurrection will stop "
                       "the other objects from being considered as dead.")
     N = len(classes)
     with SimpleBase.test():
         nodes = self.build_chain(classes)
         N = len(nodes)
         ids = [id(s) for s in nodes]
         survivor_ids = [
             id(s) for s in nodes if isinstance(s, SimpleResurrector)
         ]
         wrs = [weakref.ref(s) for s in nodes]
         del nodes
         gc.collect()
         self.assert_del_calls(ids)
         self.assert_survivors(survivor_ids)
         # XXX desirable?
         self.assertEqual([wr() for wr in wrs], [None] * N)
         self.clear_survivors()
         gc.collect()
         self.assert_del_calls(ids)
         self.assert_survivors([])
Exemplo n.º 4
0
 def test_basic_script(self):
     with temp_dir() as script_dir:
         script_name = _make_test_script(script_dir, 'script')
         package = '' if support.check_impl_detail(pypy=True) else None
         self._check_script(script_name, script_name, script_name,
                            script_dir, package,
                            importlib.machinery.SourceFileLoader)
Exemplo n.º 5
0
 def interactive_python(self, separate_stderr=False):
     if separate_stderr:
         p = spawn_python('-i', bufsize=1, stderr=subprocess.PIPE)
         stderr = p.stderr
     else:
         p = spawn_python('-i', bufsize=1, stderr=subprocess.STDOUT)
         stderr = p.stdout
     try:
         # Drain stderr until prompt
         if support.check_impl_detail(pypy=True):
             ps1 = b">>>> "
             # PyPy: the prompt is still printed to stdout, like it
             # is in CPython 2.7.  This messes up the logic below
             # if stdout and stderr are different.  Skip for now.
             if separate_stderr:
                 self.skipTest("the prompt is still written to "
                               "stdout in pypy")
         else:
             ps1 = b">>> "
         # logic fixed to support the case of lines that are shorter
         # than len(ps1) characters
         got = b""
         while not got.endswith(ps1):
             got += stderr.read(1)
         yield p
     finally:
         kill_python(p)
         stderr.close()
Exemplo n.º 6
0
 def test_excluding_predicates(self):
     self.istest(inspect.isbuiltin, 'sys.exit')
     if check_impl_detail():
         self.istest(inspect.isbuiltin, '[].append')
     self.istest(inspect.iscode, 'mod.spam.func_code')
     self.istest(inspect.isframe, 'tb.tb_frame')
     self.istest(inspect.isfunction, 'mod.spam')
     self.istest(inspect.ismethod, 'mod.StupidGit.abuse')
     self.istest(inspect.ismethod, 'git.argue')
     self.istest(inspect.ismodule, 'mod')
     self.istest(inspect.istraceback, 'tb')
     self.istest(inspect.isdatadescriptor, '__builtin__.file.closed')
     self.istest(inspect.isdatadescriptor, '__builtin__.file.softspace')
     self.istest(inspect.isgenerator, '(x for x in xrange(2))')
     self.istest(inspect.isgeneratorfunction, 'generator_function_example')
     if hasattr(types, 'GetSetDescriptorType'):
         self.istest(inspect.isgetsetdescriptor,
                     'type(tb.tb_frame).f_locals')
     else:
         self.assertFalse(
             inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
     if hasattr(types, 'MemberDescriptorType'):
         # App-level slots are member descriptors on both PyPy and
         # CPython, but the various built-in attributes are all
         # getsetdescriptors on PyPy.  So check ismemberdescriptor()
         # with an app-level slot.
         self.istest(inspect.ismemberdescriptor,
                     'ExampleClassWithSlot.myslot')
     else:
         self.assertFalse(
             inspect.ismemberdescriptor(datetime.timedelta.days))
Exemplo n.º 7
0
    def test_getsitepackages(self):
        site.PREFIXES = ['xoxo']
        dirs = site.getsitepackages()

        if check_impl_detail(pypy=True):
            self.assertEqual(len(dirs), 1)
            wanted = os.path.join('xoxo', 'site-packages')
            self.assertEqual(dirs[0], wanted)
        elif (sys.platform == "darwin" and
            sysconfig.get_config_var("PYTHONFRAMEWORK")):
            # OS X framework builds
            site.PREFIXES = ['Python.framework']
            dirs = site.getsitepackages()
            self.assertEqual(len(dirs), 2)
            wanted = os.path.join('/Library',
                                  sysconfig.get_config_var("PYTHONFRAMEWORK"),
                                  '%d.%d' % sys.version_info[:2],
                                  'site-packages')
            self.assertEqual(dirs[1], wanted)
        elif os.sep == '/':
            # OS X non-framework builds, Linux, FreeBSD, etc
            self.assertEqual(len(dirs), 1)
            wanted = os.path.join('xoxo', 'lib',
                                  'python%d.%d' % sys.version_info[:2],
                                  'site-packages')
            self.assertEqual(dirs[0], wanted)
        else:
            # other platforms
            self.assertEqual(len(dirs), 2)
            self.assertEqual(dirs[0], 'xoxo')
            wanted = os.path.join('xoxo', 'lib', 'site-packages')
            self.assertEqual(dirs[1], wanted)
Exemplo n.º 8
0
 def test_no_len_for_infinite_repeat(self):
     # The repeat() object can also be infinite
     if support.check_impl_detail(pypy=True):
         # 3.4 (PEP 424) behavior
         self.assertEqual(len(repeat(None)), NotImplemented)
     else:
         self.assertRaises(TypeError, len, repeat(None))
Exemplo n.º 9
0
def test_main(verbose=None):
    from test import test_code
    run_doctest(test_code, verbose)
    tests = [CodeTest, CodeConstsTest, CodeWeakRefTest]
    if check_impl_detail(cpython=True) and ctypes is not None:
        tests.append(CoExtra)
    run_unittest(*tests)
Exemplo n.º 10
0
    def test_popitem(self):
        # dict.popitem()
        for copymode in -1, +1:
            # -1: b has same structure as a
            # +1: b is a.copy()
            for log2size in range(12):
                size = 2**log2size
                a = {}
                b = {}
                for i in range(size):
                    a[repr(i)] = i
                    if copymode < 0:
                        b[repr(i)] = i
                if copymode > 0:
                    b = a.copy()
                for i in range(size):
                    ka, va = ta = a.popitem()
                    self.assertEqual(va, int(ka))
                    kb, vb = tb = b.popitem()
                    self.assertEqual(vb, int(kb))
                    if support.check_impl_detail():
                        self.assertFalse(copymode < 0 and ta != tb)
                self.assertFalse(a)
                self.assertFalse(b)

        d = {}
        self.assertRaises(KeyError, d.popitem)
Exemplo n.º 11
0
 def test_excluding_predicates(self):
     self.istest(inspect.isbuiltin, 'sys.exit')
     if check_impl_detail():
         self.istest(inspect.isbuiltin, '[].append')
     self.istest(inspect.iscode, 'mod.spam.__code__')
     self.istest(inspect.isframe, 'tb.tb_frame')
     self.istest(inspect.isfunction, 'mod.spam')
     self.istest(inspect.isfunction, 'mod.StupidGit.abuse')
     self.istest(inspect.ismethod, 'git.argue')
     self.istest(inspect.ismodule, 'mod')
     self.istest(inspect.istraceback, 'tb')
     self.istest(inspect.isdatadescriptor,
                 'collections.defaultdict.default_factory')
     self.istest(inspect.isgenerator, '(x for x in range(2))')
     self.istest(inspect.isgeneratorfunction, 'generator_function_example')
     if hasattr(types, 'GetSetDescriptorType'):
         self.istest(inspect.isgetsetdescriptor,
                     'type(tb.tb_frame).f_locals')
     else:
         self.assertFalse(
             inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
     if hasattr(types, 'MemberDescriptorType'):
         self.istest(inspect.ismemberdescriptor,
                     'type(lambda: None).__globals__')
     else:
         self.assertFalse(
             inspect.ismemberdescriptor(datetime.timedelta.days))
Exemplo n.º 12
0
 def test_invalid_identitifer(self):
     m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))])
     ast.fix_missing_locations(m)
     with self.assertRaises(TypeError) as cm:
         compile(m, "<test>", "exec")
     if support.check_impl_detail():
         self.assertIn("identifier must be of type str", str(cm.exception))
Exemplo n.º 13
0
    def test_popitem(self):
        # dict.popitem()
        for copymode in -1, +1:
            # -1: b has same structure as a
            # +1: b is a.copy()
            for log2size in range(12):
                size = 2**log2size
                a = {}
                b = {}
                for i in range(size):
                    a[repr(i)] = i
                    if copymode < 0:
                        b[repr(i)] = i
                if copymode > 0:
                    b = a.copy()
                for i in range(size):
                    ka, va = ta = a.popitem()
                    self.assertEqual(va, int(ka))
                    kb, vb = tb = b.popitem()
                    self.assertEqual(vb, int(kb))
                    if support.check_impl_detail():
                        self.assertFalse(copymode < 0 and ta != tb)
                self.assertFalse(a)
                self.assertFalse(b)

        d = {}
        self.assertRaises(KeyError, d.popitem)
Exemplo n.º 14
0
 def test_invalid_string(self):
     m = ast.Module([ast.Expr(ast.Str(42))])
     ast.fix_missing_locations(m)
     with self.assertRaises(TypeError) as cm:
         compile(m, "<test>", "exec")
     if support.check_impl_detail():
         self.assertIn("string must be of type str or uni", str(cm.exception))
Exemplo n.º 15
0
 def test_basic_script(self):
     with support.temp_dir() as script_dir:
         script_name = _make_test_script(script_dir, 'script')
         package = '' if support.check_impl_detail(pypy=True) else None
         self._check_script(script_name, script_name, script_name,
                            script_dir, package,
                            importlib.machinery.SourceFileLoader)
Exemplo n.º 16
0
 def test_no_len_for_infinite_repeat(self):
     # The repeat() object can also be infinite
     if support.check_impl_detail(pypy=True):
         # 3.4 (PEP 424) behavior
         self.assertEqual(len(repeat(None)), NotImplemented)
     else:
         self.assertRaises(TypeError, len, repeat(None))
Exemplo n.º 17
0
 def test_unhandled(self):
     # Check for sensible reporting of unhandled exceptions
     for exc_type in (ValueError, BrokenStrException):
         with self.subTest(exc_type):
             try:
                 exc = exc_type("test message")
                 # The following line is included in the traceback report:
                 raise exc
             except exc_type:
                 with captured_stderr() as stderr:
                     sys.__excepthook__(*sys.exc_info())
             report = stderr.getvalue()
             self.assertIn("test_exceptions.py", report)
             self.assertIn("raise exc", report)
             self.assertIn(exc_type.__name__, report)
             if exc_type is BrokenStrException:
                 if check_impl_detail(pypy=False):
                     self.assertIn("<exception str() failed>", report)
                 else:
                     # pypy: this is what lib-python's traceback.py gives
                     self.assertIn(
                         "<unprintable BrokenStrException object>", report)
             else:
                 self.assertIn("test message", report)
             self.assertTrue(report.endswith("\n"))
Exemplo n.º 18
0
 def test_former_statements_refer_to_builtins(self):
     keywords = "print", "exec"
     # Cases where we want the custom error
     cases = [
         "{} foo",
         "{} {{1:foo}}",
         "if 1: {} foo",
         "if 1: {} {{1:foo}}",
         "if 1:\n    {} foo",
         "if 1:\n    {} {{1:foo}}",
     ]
     for keyword in keywords:
         custom_msg = "call to '{}'".format(keyword)
         for case in cases:
             source = case.format(keyword)
             with self.subTest(source=source):
                 with self.assertRaisesRegex(SyntaxError, custom_msg):
                     exec(source)
             source = source.replace("foo", "(foo.)")
             # PyPy's parser also detects the same "Missing parentheses"
             # if there are some parentheses later in the line
             # (above, the cases that contain '{1:').
             # CPython gives up in this case.
             if check_impl_detail(pypy=True) and '{1:' in source:
                 expected = custom_msg
             else:
                 expected = "invalid syntax"
             with self.subTest(source=source):
                 with self.assertRaisesRegex(SyntaxError, expected):
                     exec(source)
Exemplo n.º 19
0
def test_main(verbose=None):
    from test import test_code
    run_doctest(test_code, verbose)
    tests = [CodeTest, CodeConstsTest, CodeWeakRefTest]
    if check_impl_detail(cpython=True) and ctypes is not None:
        tests.append(CoExtra)
    run_unittest(*tests)
Exemplo n.º 20
0
 def test_invalid_sum(self):
     pos = dict(lineno=2, col_offset=3)
     m = ast.Module([ast.Expr(ast.expr(**pos), **pos)])
     with self.assertRaises(TypeError) as cm:
         compile(m, "<test>", "exec")
     if support.check_impl_detail():
         self.assertIn("but got <_ast.expr", str(cm.exception))
 def test_invalid_identitifer(self):
     m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))])
     ast.fix_missing_locations(m)
     with self.assertRaises(TypeError) as cm:
         compile(m, "<test>", "exec")
     if support.check_impl_detail():
         self.assertIn("identifier must be of type str", str(cm.exception))
 def test_invalid_string(self):
     m = ast.Module([ast.Expr(ast.Str(42))])
     ast.fix_missing_locations(m)
     with self.assertRaises(TypeError) as cm:
         compile(m, "<test>", "exec")
     if support.check_impl_detail():
         self.assertIn("string must be of type str or uni", str(cm.exception))
 def test_invalid_sum(self):
     pos = dict(lineno=2, col_offset=3)
     m = ast.Module([ast.Expr(ast.expr(**pos), **pos)])
     with self.assertRaises(TypeError) as cm:
         compile(m, "<test>", "exec")
     if support.check_impl_detail():
         self.assertIn("but got <_ast.expr", str(cm.exception))
Exemplo n.º 24
0
 def testModule(self):
     with open(__file__, "rb") as f:
         code = f.read()
     if __file__.endswith(".py"):
         code = compile(code, __file__, "exec")
     self.helper(code)
     self.helper3(code, check_sharing=support.check_impl_detail())
Exemplo n.º 25
0
def test_one(n):
    global mutate, dict1, dict2, dict1keys, dict2keys

    # Fill the dicts without mutating them.
    mutate = 0
    dict1keys = fill_dict(dict1, range(n), n)
    dict2keys = fill_dict(dict2, range(n), n)

    # Enable mutation, then compare the dicts so long as they have the
    # same size.
    mutate = 1
    if verbose:
        print("trying w/ lengths", len(dict1), len(dict2), end=' ')
    while dict1 and len(dict1) == len(dict2):
        if verbose:
            print(".", end=' ')
        try:
            c = dict1 == dict2
        except RuntimeError:
            # CPython never raises RuntimeError here, but other implementations
            # might, and it's fine.
            if check_impl_detail(cpython=True):
                raise
    if verbose:
        print()
Exemplo n.º 26
0
 def test_builtin_function(self):
     eq = self.assertEqual
     # Functions
     eq(repr(hash), "<built-in function hash>")
     # Methods
     if check_impl_detail(pypy=False):
         self.assertTrue(repr("".split).startswith("<built-in method split of str object at 0x"))
Exemplo n.º 27
0
    def test_c_buffer_raw(self):
        buf = c_buffer(32)

        buf.raw = memoryview(b"Hello, World")
        self.assertEqual(buf.value, b"Hello, World")
        if support.check_impl_detail():
            self.assertRaises(TypeError, setattr, buf, "value", memoryview(b"abc"))
        self.assertRaises(ValueError, setattr, buf, "raw", memoryview(b"x" * 100))
Exemplo n.º 28
0
    def test_c_buffer_raw(self):
        buf = c_buffer(32)

        buf.raw = memoryview(b"Hello, World")
        self.assertEqual(buf.value, b"Hello, World")
        if support.check_impl_detail():
            self.assertRaises(TypeError, setattr, buf, "value", memoryview(b"abc"))
        self.assertRaises(ValueError, setattr, buf, "raw", memoryview(b"x" * 100))
 def test_builtin_function(self):
     eq = self.assertEqual
     # Functions
     eq(repr(hash), '<built-in function hash>')
     # Methods
     if check_impl_detail(pypy=False):
         self.assertTrue(repr(''.split).startswith(
             '<built-in method split of str object at 0x'))
Exemplo n.º 30
0
 def test_select_mutated(self):
     a = []
     class F:
         def fileno(self):
             del a[-1]
             return sys.__stdout__.fileno()
     a[:] = [F()] * 10
     result = select.select([], a, [])
     # CPython: 'a' ends up with 5 items, because each fileno()
     # removes an item and at the middle the iteration stops.
     # PyPy: 'a' ends up empty, because the iteration is done on
     # a copy of the original list: fileno() is called 10 times.
     if support.check_impl_detail(cpython=True):
         self.assertEqual(len(result[1]), 5)
         self.assertEqual(len(a), 5)
     if support.check_impl_detail(pypy=True):
         self.assertEqual(len(result[1]), 10)
         self.assertEqual(len(a), 0)
Exemplo n.º 31
0
 def test_bad_indentation(self):
     err = self.get_exception_format(self.syntax_error_bad_indentation,
                                     IndentationError)
     self.assertEqual(len(err), 4)
     self.assertEqual(err[1].strip(), "print(2)")
     if check_impl_detail():
         # on CPython, there is a "^" at the end of the line on PyPy,
         # there is a "^" too, but at the start, more logically
         self.assertIn("^", err[2])
         self.assertEqual(err[1].find(")"), err[2].find("^"))
Exemplo n.º 32
0
 def test_bad_indentation(self):
     err = self.get_exception_format(self.syntax_error_bad_indentation,
                                     IndentationError)
     self.assertEqual(len(err), 4)
     self.assertEqual(err[1].strip(), "print(2)")
     if check_impl_detail():
         # on CPython, there is a "^" at the end of the line on PyPy,
         # there is a "^" too, but at the start, more logically
         self.assertIn("^", err[2])
         self.assertEqual(err[1].find(")"), err[2].find("^"))
Exemplo n.º 33
0
 def testOpenDel(self):
     # "Test opening and deleting a file many times"
     self.createTempFile()
     for i in range(10000):
         if support.check_impl_detail(pypy=True):
             with BZ2File(self.filename) as o:
                 pass
         else:
             o = BZ2File(self.filename)
             del o
Exemplo n.º 34
0
 def test_script_compiled(self):
     with support.temp_dir() as script_dir:
         script_name = _make_test_script(script_dir, 'script')
         py_compile.compile(script_name, doraise=True)
         os.remove(script_name)
         pyc_file = support.make_legacy_pyc(script_name)
         package = '' if support.check_impl_detail(pypy=True) else None
         self._check_script(pyc_file, pyc_file, pyc_file, script_dir,
                            package,
                            importlib.machinery.SourcelessFileLoader)
Exemplo n.º 35
0
 def test_script_compiled(self):
     with temp_dir() as script_dir:
         script_name = _make_test_script(script_dir, 'script')
         py_compile.compile(script_name, doraise=True)
         os.remove(script_name)
         pyc_file = support.make_legacy_pyc(script_name)
         package = '' if support.check_impl_detail(pypy=True) else None
         self._check_script(pyc_file, pyc_file,
                            pyc_file, script_dir, package,
                            importlib.machinery.SourcelessFileLoader)
Exemplo n.º 36
0
 def test_bad_integer(self):
     # issue13436: Bad error message with invalid numeric values
     body = [ast.ImportFrom(module='time',
                            names=[ast.alias(name='sleep')],
                            level=None,
                            lineno=None, col_offset=None)]
     mod = ast.Module(body)
     with self.assertRaises((TypeError, ValueError)) as cm:
         compile(mod, 'test', 'exec')
     if support.check_impl_detail():
         self.assertIn("invalid integer value: None", str(cm.exception))
 def test_bad_integer(self):
     # issue13436: Bad error message with invalid numeric values
     body = [ast.ImportFrom(module='time',
                            names=[ast.alias(name='sleep')],
                            level=None,
                            lineno=None, col_offset=None)]
     mod = ast.Module(body)
     with self.assertRaises((TypeError, ValueError)) as cm:
         compile(mod, 'test', 'exec')
     if support.check_impl_detail():
         self.assertIn("invalid integer value: None", str(cm.exception))
Exemplo n.º 38
0
 def test_issue9319(self):
     path = os.path.dirname(__file__)
     try:
         imp.find_module("badsyntax_pep3120", [path])
     except SyntaxError:
         pass
     else:
         # PyPy's find_module won't raise a SyntaxError when checking
         # the file's magic encoding comment, the point of the test
         # is to ensure no seg fault anyway
         self.assertTrue(support.check_impl_detail(cpython=False))
Exemplo n.º 39
0
 def test_issue9319(self):
     path = os.path.dirname(__file__)
     try:
         imp.find_module("badsyntax_pep3120", [path])
     except SyntaxError:
         pass
     else:
         # PyPy's find_module won't raise a SyntaxError when checking
         # the file's magic encoding comment, the point of the test
         # is to ensure no seg fault anyway
         self.assertTrue(support.check_impl_detail(cpython=False))
Exemplo n.º 40
0
 def test_bad_single_statement(self):
     self.assertInvalidSingle('1\n2')
     if check_impl_detail():
         # it's a single statment in PyPy
         self.assertInvalidSingle('def f(): pass')
     self.assertInvalidSingle('a = 13\nb = 187')
     self.assertInvalidSingle('del x\ndel y')
     self.assertInvalidSingle('f()\ng()')
     self.assertInvalidSingle('f()\n# blah\nblah()')
     self.assertInvalidSingle('f()\nxy # blah\nblah()')
     self.assertInvalidSingle('x = 5 # comment\nx = 6\n')
Exemplo n.º 41
0
 def test_bad_single_statement(self):
     self.assertInvalidSingle('1\n2')
     if check_impl_detail():
         # it's a single statment in PyPy
         self.assertInvalidSingle('def f(): pass')
     self.assertInvalidSingle('a = 13\nb = 187')
     self.assertInvalidSingle('del x\ndel y')
     self.assertInvalidSingle('f()\ng()')
     self.assertInvalidSingle('f()\n# blah\nblah()')
     self.assertInvalidSingle('f()\nxy # blah\nblah()')
     self.assertInvalidSingle('x = 5 # comment\nx = 6\n')
Exemplo n.º 42
0
    def test_abs_paths(self):
        # Make sure all imported modules have their __file__ and __cached__
        # attributes as absolute paths.  Arranging to put the Lib directory on
        # PYTHONPATH would cause the os module to have a relative path for
        # __file__ if abs_paths() does not get run.  sys and builtins (the
        # only other modules imported before site.py runs) do not have
        # __file__ or __cached__ because they are built-in.
        try:
            parent = os.path.relpath(os.path.dirname(os.__file__))
            cwd = os.getcwd()
        except ValueError:
            # Failure to get relpath probably means we need to chdir
            # to the same drive.
            cwd, parent = os.path.split(os.path.dirname(os.__file__))
        with change_cwd(cwd):
            env = os.environ.copy()
            env['PYTHONPATH'] = parent
            code = (
                'import os, sys',
                # use ASCII to avoid locale issues with non-ASCII directories
                'os_file = os.__file__.encode("ascii", "backslashreplace")',
                r'sys.stdout.buffer.write(os_file + b"\n")',
                'os_cached = os.__cached__.encode("ascii", "backslashreplace")',
                r'sys.stdout.buffer.write(os_cached + b"\n")')
            command = '\n'.join(code)
            # First, prove that with -S (no 'import site'), the paths are
            # relative.
            proc = subprocess.Popen([sys.executable, '-S', '-c', command],
                                    env=env,
                                    stdout=subprocess.PIPE)
            stdout, stderr = proc.communicate()

            self.assertEqual(proc.returncode, 0)
            os__file__, os__cached__ = stdout.splitlines()[:2]
            if check_impl_detail(cpython=True):
                # XXX: should probably match cpython
                self.assertFalse(os.path.isabs(os__file__))
                self.assertFalse(os.path.isabs(os__cached__))
            # Now, with 'import site', it works.
            proc = subprocess.Popen([sys.executable, '-c', command],
                                    env=env,
                                    stdout=subprocess.PIPE)
            stdout, stderr = proc.communicate()
            self.assertEqual(proc.returncode, 0)
            os__file__, os__cached__ = stdout.splitlines()[:2]
            self.assertTrue(
                os.path.isabs(os__file__),
                "expected absolute path, got {}".format(
                    os__file__.decode('ascii')))
            self.assertTrue(
                os.path.isabs(os__cached__),
                "expected absolute path, got {}".format(
                    os__cached__.decode('ascii')))
Exemplo n.º 43
0
    def testSetattrWrapperNameIntern(self):
        # Issue #25794: __setattr__ should intern the attribute name
        class A:
            pass

        def add(self, other):
            return 'summa'

        name = str(b'__add__', 'ascii')  # shouldn't be optimized
        if support.check_impl_detail():
            self.assertIsNot(name, '__add__')  # not interned
        type.__setattr__(A, name, add)
        self.assertEqual(A() + 1, 'summa')

        name2 = str(b'__add__', 'ascii')
        if support.check_impl_detail():
            self.assertIsNot(name2, '__add__')
            self.assertIsNot(name2, name)
        type.__delattr__(A, name2)
        with self.assertRaises(TypeError):
            A() + 1
    def test_setitem_writable(self):
        if not self.rw_type:
            self.skipTest("no writable type to test")
        tp = self.rw_type
        b = self.rw_type(self._source)
        oldrefcount = getrefcount(b)
        m = self._view(b)
        m[0] = ord(b'1')
        self._check_contents(tp, b, b"1bcdef")
        m[0:1] = tp(b"0")
        self._check_contents(tp, b, b"0bcdef")
        m[1:3] = tp(b"12")
        self._check_contents(tp, b, b"012def")
        m[1:1] = tp(b"")
        self._check_contents(tp, b, b"012def")
        m[:] = tp(b"abcdef")
        self._check_contents(tp, b, b"abcdef")

        # Overlapping copies of a view into itself
        m[0:3] = m[2:5]
        self._check_contents(tp, b, b"cdedef")
        m[:] = tp(b"abcdef")
        m[2:5] = m[0:3]
        self._check_contents(tp, b, b"ababcf")

        def setitem(key, value):
            m[key] = tp(value)

        # Bounds checking
        self.assertRaises(IndexError, setitem, 6, b"a")
        self.assertRaises(IndexError, setitem, -7, b"a")
        self.assertRaises(IndexError, setitem, sys.maxsize, b"a")
        self.assertRaises(IndexError, setitem, -sys.maxsize, b"a")
        # Wrong index/slice types
        self.assertRaises(TypeError, setitem, 0.0, b"a")
        if check_impl_detail():
            self.assertRaises(TypeError, setitem, (0, ), b"a")
            self.assertRaises(TypeError, setitem, (slice(0, 1, 1), 0), b"a")
            self.assertRaises(TypeError, setitem, (0, slice(0, 1, 1)), b"a")
            self.assertRaises(TypeError, setitem, (0, ), b"a")
        self.assertRaises(TypeError, setitem, "a", b"a")
        # Not implemented: multidimensional slices
        slices = (slice(0, 1, 1), slice(0, 1, 2))
        self.assertRaises(NotImplementedError, setitem, slices, b"a")
        # Trying to resize the memory object
        exc = ValueError if m.format == 'c' else TypeError
        self.assertRaises(exc, setitem, 0, b"")
        self.assertRaises(exc, setitem, 0, b"ab")
        self.assertRaises(ValueError, setitem, slice(1, 1), b"a")
        self.assertRaises(ValueError, setitem, slice(0, 2), b"a")

        m = None
        self.assertEqual(getrefcount(b), oldrefcount)
Exemplo n.º 45
0
 def test_method_lookup(self):
     f = self.do_create()
     wr = weakref.ref(f)
     write = f.write
     write2 = f.write
     del f
     write(b'foo')
     del write
     write2(b'bar')
     del write2
     if support.check_impl_detail(cpython=True):
         self.assertIsNone(wr())
Exemplo n.º 46
0
    def test_setitem_writable(self):
        if not self.rw_type:
            self.skipTest("no writable type to test")
        tp = self.rw_type
        b = self.rw_type(self._source)
        oldrefcount = getrefcount(b)
        m = self._view(b)
        m[0] = ord(b'1')
        self._check_contents(tp, b, b"1bcdef")
        m[0:1] = tp(b"0")
        self._check_contents(tp, b, b"0bcdef")
        m[1:3] = tp(b"12")
        self._check_contents(tp, b, b"012def")
        m[1:1] = tp(b"")
        self._check_contents(tp, b, b"012def")
        m[:] = tp(b"abcdef")
        self._check_contents(tp, b, b"abcdef")

        # Overlapping copies of a view into itself
        m[0:3] = m[2:5]
        self._check_contents(tp, b, b"cdedef")
        m[:] = tp(b"abcdef")
        m[2:5] = m[0:3]
        self._check_contents(tp, b, b"ababcf")

        def setitem(key, value):
            m[key] = tp(value)
        # Bounds checking
        self.assertRaises(IndexError, setitem, 6, b"a")
        self.assertRaises(IndexError, setitem, -7, b"a")
        self.assertRaises(IndexError, setitem, sys.maxsize, b"a")
        self.assertRaises(IndexError, setitem, -sys.maxsize, b"a")
        # Wrong index/slice types
        self.assertRaises(TypeError, setitem, 0.0, b"a")
        if check_impl_detail():
            self.assertRaises(TypeError, setitem, (0,), b"a")
            self.assertRaises(TypeError, setitem, (slice(0,1,1), 0), b"a")
            self.assertRaises(TypeError, setitem, (0, slice(0,1,1)), b"a")
            self.assertRaises(TypeError, setitem, (0,), b"a")
        self.assertRaises(TypeError, setitem, "a", b"a")
        # Not implemented: multidimensional slices
        slices = (slice(0,1,1), slice(0,1,2))
        self.assertRaises(NotImplementedError, setitem, slices, b"a")
        # Trying to resize the memory object
        exc = ValueError if m.format == 'c' else TypeError
        self.assertRaises(exc, setitem, 0, b"")
        self.assertRaises(exc, setitem, 0, b"ab")
        self.assertRaises(ValueError, setitem, slice(1,1), b"a")
        self.assertRaises(ValueError, setitem, slice(0,2), b"a")

        m = None
        self.assertEqual(getrefcount(b), oldrefcount)
Exemplo n.º 47
0
    def testSyntaxErrorOffset(self):
        def check(src, lineno, offset):
            with self.assertRaises(SyntaxError) as cm:
                compile(src, '<fragment>', 'exec')
            self.assertEqual(cm.exception.lineno, lineno)
            self.assertEqual(cm.exception.offset, offset)

        is_pypy = check_impl_detail(pypy=True)
        check('def fact(x):\n\treturn x!\n', 2, 10)
        check('1 +\n', 1, 4 - is_pypy)
        check('def spam():\n  print(1)\n print(2)', 3, 0 if is_pypy else 10)
        check('Python = "Python" +', 1, 20 - is_pypy)
        check('Python = "\u1e54\xfd\u0163\u0125\xf2\xf1" +', 1, 20 - is_pypy)
Exemplo n.º 48
0
    def test_AST_objects(self):
        if not support.check_impl_detail():
            # PyPy also provides a __dict__ to the ast.AST base class.
            return

        x = ast.AST()
        self.assertEqual(x._fields, ())

        with self.assertRaises(AttributeError):
            x.vararg

        with self.assertRaises(TypeError):
            # "_ast.AST constructor takes 0 positional arguments"
            ast.AST(2)
Exemplo n.º 49
0
 def test_uninitialized(self):
     # An uninitialized module has no __dict__ or __name__,
     # and __doc__ is None
     foo = ModuleType.__new__(ModuleType)
     self.assertFalse(foo.__dict__)
     if check_impl_detail():
         self.assertTrue(foo.__dict__ is None)
         self.assertRaises(SystemError, dir, foo)
     try:
         s = foo.__name__
         self.fail("__name__ = %s" % repr(s))
     except AttributeError:
         pass
     self.assertEqual(foo.__doc__, ModuleType.__doc__)
Exemplo n.º 50
0
def blowstack(fxn, arg, compare_to):
    # Make sure that calling isinstance with a deeply nested tuple for its
    # argument will raise RuntimeError eventually.
    tuple_arg = (compare_to,)

    if support.check_impl_detail(cpython=True):
        RECURSION_LIMIT = sys.getrecursionlimit()
    else:
        # on non-CPython implementations, the maximum actual recursion
        # limit might be higher, but probably not higher than 99999
        RECURSION_LIMIT = 99999

    for cnt in range(RECURSION_LIMIT + 5):
        tuple_arg = (tuple_arg,)
        fxn(arg, tuple_arg)
Exemplo n.º 51
0
 def test_method_lookup(self):
     # Issue #18879: Looking up a temporary file method should keep it
     # alive long enough.
     f = self.do_create()
     wr = weakref.ref(f)
     write = f.write
     write2 = f.write
     del f
     write(b"foo")
     del write
     write2(b"bar")
     del write2
     if support.check_impl_detail(cpython=True):
         # No reference cycle was created.
         self.assertIsNone(wr())
Exemplo n.º 52
0
 def test_keep_buffer(self):
     # See bug 14212
     b = bytearray(b'x')
     it = re.finditer(b'a', b)
     if check_impl_detail(pypy=False):
         # PyPy export buffers differently, and allows reallocation
         # of the underlying object.
         with self.assertRaises(BufferError):
             b.extend(b'x'*400)
     else:
         b.extend(b'x'*400)
     list(it)
     del it
     gc_collect()
     b.extend(b'x'*400)
Exemplo n.º 53
0
    def test_int_subclass_with_index(self):
        # __index__ should be used when computing indices, even for int
        # subclasses.  See issue #17576.
        class MyInt(int):
            def __index__(self):
                return int(self) + 1

        my_int = MyInt(7)
        direct_index = my_int.__index__()
        operator_index = operator.index(my_int)
        self.assertEqual(direct_index, 8)
        if support.check_impl_detail():
            self.assertEqual(operator_index, 7)
        else:
            self.assertEqual(operator_index, 8)
        # Both results should be of exact type int.
        self.assertIs(type(direct_index), int)
Exemplo n.º 54
0
    def test_binary_subscr_on_unicode(self):
        if check_impl_detail(pypy=False):
            # valid code get optimized
            asm = dis_single('"foo"[0]')
            self.assertIn("('f')", asm)
            self.assertNotIn('BINARY_SUBSCR', asm)
            asm = dis_single('"\u0061\uffff"[1]')
            self.assertIn("('\\uffff')", asm)
            self.assertNotIn('BINARY_SUBSCR', asm)

        # invalid code doesn't get optimized
        # out of range
        asm = dis_single('"fuu"[10]')
        self.assertIn('BINARY_SUBSCR', asm)
        # non-BMP char (see #5057)
        asm = dis_single('"\U00012345"[0]')
        self.assertIn('BINARY_SUBSCR', asm)
Exemplo n.º 55
0
    def test_descriptors(self):
        eq = self.assertEqual
        # method descriptors
        if check_impl_detail(pypy=False):
            eq(repr(dict.items), "<method 'items' of 'dict' objects>")
        # XXX member descriptors
        # XXX attribute descriptors
        # XXX slot descriptors
        # static and class methods
        class C:
            def foo(cls):
                pass

        x = staticmethod(C.foo)
        self.assertTrue(repr(x).startswith("<staticmethod object at 0x"))
        x = classmethod(C.foo)
        self.assertTrue(repr(x).startswith("<classmethod object at 0x"))
Exemplo n.º 56
0
    def test_hash_randomization(self):
        # Verify that -R enables hash randomization:
        self.verify_valid_flag('-R')
        hashes = []
        for i in range(2):
            code = 'print(hash("spam"))'
            rc, out, err = assert_python_ok('-R', '-c', code)
            self.assertEqual(rc, 0)
            hashes.append(out)
        if check_impl_detail(pypy=False):  # PyPy does not really implement it!
            self.assertNotEqual(hashes[0], hashes[1])

        # Verify that sys.flags contains hash_randomization
        code = 'import sys; print("random is", sys.flags.hash_randomization)'
        rc, out, err = assert_python_ok('-R', '-c', code)
        self.assertEqual(rc, 0)
        self.assertIn(b'random is 1', out)
Exemplo n.º 57
0
 def test_tofromstring(self):
     nb_warnings = 4
     with warnings.catch_warnings(record=True) as r:
         warnings.filterwarnings("always", message=r"(to|from)string\(\) is deprecated", category=DeprecationWarning)
         a = array.array(self.typecode, 2 * self.example)
         b = array.array(self.typecode)
         self.assertRaises(TypeError, a.tostring, 42)
         self.assertRaises(TypeError, b.fromstring)
         self.assertRaises(TypeError, b.fromstring, 42)
         b.fromstring(a.tostring())
         self.assertEqual(a, b)
         if a.itemsize > 1:
             self.assertRaises(ValueError, b.fromstring, "x")
             nb_warnings += 1
     if support.check_impl_detail():
         # PyPy's multimethod dispatch is different from CPython's
         # on CPython the warning is emitted before checking the arguments
         self.assertEqual(len(r), nb_warnings)
Exemplo n.º 58
0
    def test_send_error(self):
        # Use a subprocess to have only one thread.
        if os.name == 'nt':
            action = 'send'
        else:
            action = 'write'
        code = """if 1:
        import errno
        import signal
        import socket
        import sys
        import time
        import _testcapi
        from test.support import captured_stderr

        signum = signal.SIGINT

        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())

        # Close sockets: send() will fail
        read.close()
        write.close()

        with captured_stderr() as err:
            _testcapi.raise_signal(signum)

        err = err.getvalue()
        if ('Exception ignored when trying to {action} to the signal wakeup fd'
            not in err) and {cpython_only}:
            raise AssertionError(err)
        """.format(action=action, cpython_only=support.check_impl_detail())
        # note that PyPy produces the same error message, but sent to
        # the real stderr instead of to sys.stderr.
        assert_python_ok('-c', code)