diff --git a/src/c/ffi_obj.c b/src/c/ffi_obj.c index fbba2894..3262b9c9 100644 --- a/src/c/ffi_obj.c +++ b/src/c/ffi_obj.c @@ -447,17 +447,17 @@ static PyObject *ffi_cast(FFIObject *self, PyObject *args) } PyDoc_STRVAR(ffi_string_doc, -"Return a Python string (or unicode string) from the 'cdata'. If\n" +"Return a Python string from the 'cdata'. If\n" "'cdata' is a pointer or array of characters or bytes, returns the\n" "null-terminated string. The returned string extends until the first\n" "null character, or at most 'maxlen' characters. If 'cdata' is an\n" "array then 'maxlen' defaults to its length.\n" "\n" -"If 'cdata' is a pointer or array of wchar_t, returns a unicode string\n" +"If 'cdata' is a pointer or array of wchar_t, returns a string\n" "following the same rules.\n" "\n" "If 'cdata' is a single character or byte or a wchar_t, returns it as a\n" -"string or unicode string.\n" +"string.\n" "\n" "If 'cdata' is an enum, returns the value of the enumerator as a\n" "string, or 'NUMBER' if the value is out of range."); @@ -467,13 +467,13 @@ PyDoc_STRVAR(ffi_string_doc, PyDoc_STRVAR(ffi_unpack_doc, "Unpack an array of C data of the given length,\n" -"returning a Python string/unicode/list.\n" +"returning a Python string/list.\n" "\n" "If 'cdata' is a pointer to 'char', returns a byte string.\n" "It does not stop at the first null. This is equivalent to:\n" "ffi.buffer(cdata, length)[:]\n" "\n" -"If 'cdata' is a pointer to 'wchar_t', returns a unicode string.\n" +"If 'cdata' is a pointer to 'wchar_t', returns a string.\n" "'length' is measured in wchar_t's; it is not the size in bytes.\n" "\n" "If 'cdata' is a pointer to anything else, returns a list of\n" @@ -662,7 +662,7 @@ static PyObject *ffi_getctype(FFIObject *self, PyObject *args, PyObject *kwds) if (add_paren) p[replace_with_len] = ')'; - /* bytes -> unicode string */ + /* bytes -> string */ u = PyUnicode_DecodeLatin1(PyBytes_AS_STRING(res), PyBytes_GET_SIZE(res), NULL); @@ -696,7 +696,7 @@ PyDoc_STRVAR(ffi_from_handle_doc, PyDoc_STRVAR(ffi_from_buffer_doc, "Return a that points to the data of the given Python\n" "object, which must support the buffer interface. Note that this is\n" -"not meant to be used on the built-in types str or unicode\n" +"not meant to be used on the built-in types str or bytes\n" "(you can build 'char[]' arrays explicitly) but only on objects\n" "containing large quantities of raw data in some other format, like\n" "'array.array' or numpy arrays."); diff --git a/src/c/lib_obj.c b/src/c/lib_obj.c index c25a78a7..9c55d801 100644 --- a/src/c/lib_obj.c +++ b/src/c/lib_obj.c @@ -695,8 +695,7 @@ static PyObject *address_of_global_var(PyObject *args) if (!PyArg_ParseTuple(args, "O!s", &Lib_Type, &lib, &varname)) return NULL; - /* rebuild a string from 'varname', to do typechecks and to force - a unicode back to a plain string (on python 2) */ + /* rebuild a string from 'varname', to do typechecks */ o_varname = PyUnicode_FromString(varname); if (o_varname == NULL) return NULL; diff --git a/src/c/test_c.py b/src/c/test_c.py index 8d2228c1..4916d993 100644 --- a/src/c/test_c.py +++ b/src/c/test_c.py @@ -69,31 +69,7 @@ def _capture_unraisable_hook(ur_args): assert __version__ == "2.0.1.dev0", ("This test_c.py file is for testing a version" " of cffi that differs from the one that we" " get from 'import _cffi_backend'") -if sys.version_info < (3,): - type_or_class = "type" - mandatory_b_prefix = '' - mandatory_u_prefix = 'u' - bytechr = chr - bitem2bchr = lambda x: x - class U: - def __add__(self, other): - return eval('u'+repr(other).replace(r'\\u', r'\u') - .replace(r'\\U', r'\U')) - u = U() - str2bytes = str - strict_compare = False -else: - type_or_class = "class" - long = int - unicode = str - unichr = chr - mandatory_b_prefix = 'b' - mandatory_u_prefix = '' - bytechr = lambda n: bytes([n]) - bitem2bchr = bytechr - u = "" - str2bytes = lambda s: bytes(s, "ascii") - strict_compare = True +bytechr = lambda n: bytes([n]) def size_of_int(): BInt = new_primitive_type("int") @@ -166,7 +142,7 @@ def test_cast_to_signed_char(): p = new_primitive_type("signed char") x = cast(p, -65 + 17*256) assert repr(x) == "" - assert repr(type(x)) == "<%s '_cffi_backend._CDataBase'>" % type_or_class + assert repr(type(x)) == "" assert int(x) == -65 x = cast(p, -66 + (1<<199)*256) assert repr(x) == "" @@ -193,9 +169,9 @@ def test_integer_types(): assert int(cast(p, min - 1)) == max assert int(cast(p, max + 1)) == min pytest.raises(TypeError, cast, p, None) - assert long(cast(p, min - 1)) == max + assert int(cast(p, min - 1)) == max assert int(cast(p, b'\x08')) == 8 - assert int(cast(p, u+'\x08')) == 8 + assert int(cast(p, '\x08')) == 8 for name in ['char', 'short', 'int', 'long', 'long long']: p = new_primitive_type('unsigned ' + name) size = sizeof(p) @@ -204,9 +180,9 @@ def test_integer_types(): assert int(cast(p, max)) == max assert int(cast(p, -1)) == max assert int(cast(p, max + 1)) == 0 - assert long(cast(p, -1)) == max + assert int(cast(p, -1)) == max assert int(cast(p, b'\xFE')) == 254 - assert int(cast(p, u+'\xFE')) == 254 + assert int(cast(p, '\xFE')) == 254 def test_no_float_on_int_types(): p = new_primitive_type('long') @@ -226,11 +202,9 @@ def test_float_types(): assert bool(cast(p, float("nan"))) assert int(cast(p, -150)) == -150 assert int(cast(p, 61.91)) == 61 - assert long(cast(p, 61.91)) == 61 + assert int(cast(p, 61.91)) == 61 assert type(int(cast(p, 61.91))) is int - assert type(int(cast(p, 1E22))) is long - assert type(long(cast(p, 61.91))) is long - assert type(long(cast(p, 1E22))) is long + assert type(int(cast(p, 1E22))) is int pytest.raises(OverflowError, int, cast(p, INF)) pytest.raises(OverflowError, int, cast(p, -INF)) assert float(cast(p, 1.25)) == 1.25 @@ -243,7 +217,7 @@ def test_float_types(): assert cast(p, -1.1) == cast(p, -1.1) assert repr(float(cast(p, -0.0))) == '-0.0' assert float(cast(p, b'\x09')) == 9.0 - assert float(cast(p, u+'\x09')) == 9.0 + assert float(cast(p, '\x09')) == 9.0 assert float(cast(p, True)) == 1.0 pytest.raises(TypeError, cast, p, None) @@ -259,7 +233,6 @@ def test_complex_types(): assert bool(cast(p, -INF*1j)) # "can't convert complex to float", like CPython's "float(0j)" pytest.raises(TypeError, int, cast(p, -150)) - pytest.raises(TypeError, long, cast(p, -150)) pytest.raises(TypeError, float, cast(p, -150)) assert complex(cast(p, 1.25)) == 1.25 assert complex(cast(p, 1.25j)) == 1.25j @@ -274,7 +247,7 @@ def test_complex_types(): assert repr(complex(cast(p, -0.0)).real) == '-0.0' #assert repr(complex(cast(p, -0j))) == '-0j' # http://bugs.python.org/issue29602 assert complex(cast(p, b'\x09')) == 9.0 + 0j - assert complex(cast(p, u+'\x09')) == 9.0 + 0j + assert complex(cast(p, '\x09')) == 9.0 + 0j assert complex(cast(p, True)) == 1.0 + 0j pytest.raises(TypeError, cast, p, None) # @@ -305,13 +278,11 @@ def test_character_type(): assert bool(cast(p, '\x00')) is False # since 1.7 assert cast(p, '\x00') == cast(p, -17*256) assert int(cast(p, 'A')) == 65 - assert long(cast(p, 'A')) == 65 assert type(int(cast(p, 'A'))) is int - assert type(long(cast(p, 'A'))) is long assert str(cast(p, 'A')) == repr(cast(p, 'A')) - assert repr(cast(p, 'A')) == "" % mandatory_b_prefix - assert repr(cast(p, 255)) == r"" % mandatory_b_prefix - assert repr(cast(p, 0)) == r"" % mandatory_b_prefix + assert repr(cast(p, 'A')) == "" + assert repr(cast(p, 255)) == r"" + assert repr(cast(p, 0)) == r"" def test_pointer_type(): p = new_primitive_type("int") @@ -438,12 +409,12 @@ def test_reading_pointer_to_char(): assert p[0] == b'A' pytest.raises(TypeError, newp, BPtr, 65) pytest.raises(TypeError, newp, BPtr, b"foo") - pytest.raises(TypeError, newp, BPtr, u+"foo") + pytest.raises(TypeError, newp, BPtr, "foo") c = cast(BChar, b'A') assert str(c) == repr(c) assert int(c) == ord(b'A') pytest.raises(TypeError, cast, BChar, b'foo') - pytest.raises(TypeError, cast, BChar, u+'foo') + pytest.raises(TypeError, cast, BChar, 'foo') e = pytest.raises(TypeError, newp, new_array_type(BPtr, None), 12.3) assert str(e.value) == ( "expected new array length or list/tuple/str, not float") @@ -519,14 +490,6 @@ def test_default_str(): x = newp(BArray, None) assert str(x) == repr(x) -def test_default_unicode(): - BInt = new_primitive_type("int") - x = cast(BInt, 42) - assert unicode(x) == unicode(repr(x)) - BArray = new_array_type(new_pointer_type(BInt), 10) - x = newp(BArray, None) - assert unicode(x) == unicode(repr(x)) - def test_cast_from_cdataint(): BInt = new_primitive_type("int") x = cast(BInt, 0) @@ -1123,7 +1086,7 @@ def test_call_function_6(): # pytest.raises(TypeError, f, 123456) pytest.raises(TypeError, f, "foo") - pytest.raises(TypeError, f, u+"bar") + pytest.raises(TypeError, f, "bar") def test_call_function_7(): BChar = new_primitive_type("char") @@ -1687,10 +1650,6 @@ def test_enum_in_struct(): "expected integer, got NoneType object" in msg) # newer PyPys with pytest.raises(TypeError): p.a1 = "def" - if sys.version_info < (3,): - BEnum2 = new_enum_type(unicode("foo"), (unicode('abc'),), (5,), BInt) - assert string(cast(BEnum2, 5)) == 'abc' - assert type(string(cast(BEnum2, 5))) is str def test_enum_overflow(): max_uint = 2 ** (size_of_int()*8) - 1 @@ -1753,14 +1712,14 @@ def test_callback_returning_char(): BInt = new_primitive_type("int") BChar = new_primitive_type("char") def cb(n): - return bytechr(n) + return bytes([n]) BFunc = new_function_type((BInt,), BChar) f = callback(BFunc, cb) assert f(0) == b'\x00' assert f(255) == b'\xFF' def _hacked_pypy_uni4(): - pyuni4 = {1: True, 2: False}[len(u+'\U00012345')] + pyuni4 = {1: True, 2: False}[len('\U00012345')] return 'PY_DOT_PY' in globals() and not pyuni4 @pytest.mark.skipif(is_ios, reason="Cannot allocate executable memory on iOS") @@ -1769,18 +1728,18 @@ def test_callback_returning_wchar_t(): BWChar = new_primitive_type("wchar_t") def cb(n): if n == -1: - return u+'\U00012345' + return '\U00012345' if n == -2: raise ValueError - return unichr(n) + return chr(n) BFunc = new_function_type((BInt,), BWChar) f = callback(BFunc, cb) - assert f(0) == unichr(0) - assert f(255) == unichr(255) - assert f(0x1234) == u+'\u1234' + assert f(0) == chr(0) + assert f(255) == chr(255) + assert f(0x1234) == '\u1234' if sizeof(BWChar) == 4 and not _hacked_pypy_uni4(): - assert f(-1) == u+'\U00012345' - assert f(-2) == u+'\x00' # and an exception printed to stderr + assert f(-1) == '\U00012345' + assert f(-2) == '\x00' # and an exception printed to stderr def test_struct_with_bitfields(): BLong = new_primitive_type("long") @@ -2033,16 +1992,16 @@ def test_string_wchar(): def _test_string_wchar_variant(typename): BWChar = new_primitive_type(typename) - assert string(cast(BWChar, 42)) == u+'*' - assert string(cast(BWChar, 0x4253)) == u+'\u4253' - assert string(cast(BWChar, 0)) == u+'\x00' + assert string(cast(BWChar, 42)) == '*' + assert string(cast(BWChar, 0x4253)) == '\u4253' + assert string(cast(BWChar, 0)) == '\x00' BArray = new_array_type(new_pointer_type(BWChar), None) - a = newp(BArray, [u+'A', u+'B', u+'C']) - assert type(string(a)) is unicode and string(a) == u+'ABC' + a = newp(BArray, ['A', 'B', 'C']) + assert type(string(a)) is str and string(a) == 'ABC' if 'PY_DOT_PY' not in globals() and sys.version_info < (3,): try: # may contain additional garbage - assert string(a, 8).startswith(u+'ABC') + assert string(a, 8).startswith('ABC') except ValueError: # garbage contains values > 0x10FFFF assert sizeof(BWChar) == 4 @@ -2099,7 +2058,7 @@ def test_struct_return_in_func(): f = cast(BFunc10, _testfunc(10)) s = f(40) assert repr(s) == "" - assert s.a1 == bytechr(40) + assert s.a1 == bytes([40]) assert s.a2 == 40 * 40 # BStruct11 = new_struct_type("struct test11") @@ -2216,22 +2175,18 @@ def test_char32(): def _test_wchar_variant(typename): BWChar = new_primitive_type(typename) BInt = new_primitive_type("int") - pyuni4 = {1: True, 2: False}[len(u+'\U00012345')] + pyuni4 = {1: True, 2: False}[len('\U00012345')] wchar4 = {2: False, 4: True}[sizeof(BWChar)] - assert str(cast(BWChar, 0x45)) == "" % ( - typename, mandatory_u_prefix) - assert str(cast(BWChar, 0x1234)) == "" % ( - typename, mandatory_u_prefix) + assert str(cast(BWChar, 0x45)) == "" % typename + assert str(cast(BWChar, 0x1234)) == "" % typename if not _hacked_pypy_uni4(): if wchar4: x = cast(BWChar, 0x12345) - assert str(x) == "" % ( - typename, mandatory_u_prefix) + assert str(x) == "" % typename assert int(x) == 0x12345 else: x = cast(BWChar, 0x18345) - assert str(x) == "" % ( - typename, mandatory_u_prefix) + assert str(x) == "" % typename assert int(x) == 0x8345 # BWCharP = new_pointer_type(BWChar) @@ -2240,47 +2195,47 @@ def _test_wchar_variant(typename): complete_struct_or_union(BStruct, [('a1', BWChar, -1), ('a2', BWCharP, -1)]) s = newp(BStructPtr) - s.a1 = u+'\x00' - assert s.a1 == u+'\x00' + s.a1 = '\x00' + assert s.a1 == '\x00' with pytest.raises(TypeError): s.a1 = b'a' with pytest.raises(TypeError): - s.a1 = bytechr(0xFF) - s.a1 = u+'\u1234' - assert s.a1 == u+'\u1234' + s.a1 = bytes([0xFF]) + s.a1 = '\u1234' + assert s.a1 == '\u1234' if pyuni4: if wchar4: - s.a1 = u+'\U00012345' - assert s.a1 == u+'\U00012345' + s.a1 = '\U00012345' + assert s.a1 == '\U00012345' elif wchar4: if not _hacked_pypy_uni4(): s.a1 = cast(BWChar, 0x12345) - assert s.a1 == u+'\ud808\udf45' - s.a1 = u+'\ud807\udf44' - assert s.a1 == u+'\U00011f44' + assert s.a1 == '\ud808\udf45' + s.a1 = '\ud807\udf44' + assert s.a1 == '\U00011f44' else: with pytest.raises(TypeError): - s.a1 = u+'\U00012345' + s.a1 = '\U00012345' # BWCharArray = new_array_type(BWCharP, None) - a = newp(BWCharArray, u+'hello \u1234 world') + a = newp(BWCharArray, 'hello \u1234 world') assert len(a) == 14 # including the final null - assert string(a) == u+'hello \u1234 world' - a[13] = u+'!' - assert string(a) == u+'hello \u1234 world!' + assert string(a) == 'hello \u1234 world' + a[13] = '!' + assert string(a) == 'hello \u1234 world!' assert str(a) == repr(a) - assert a[6] == u+'\u1234' - a[6] = u+'-' - assert string(a) == u+'hello - world!' + assert a[6] == '\u1234' + a[6] = '-' + assert string(a) == 'hello - world!' assert str(a) == repr(a) # if wchar4 and not _hacked_pypy_uni4(): - u1 = u+'\U00012345\U00012346\U00012347' + u1 = '\U00012345\U00012346\U00012347' a = newp(BWCharArray, u1) assert len(a) == 4 assert string(a) == u1 assert len(list(a)) == 4 - expected = [u+'\U00012345', u+'\U00012346', u+'\U00012347', unichr(0)] + expected = ['\U00012345', '\U00012346', '\U00012347', chr(0)] assert list(a) == expected got = [a[i] for i in range(4)] assert got == expected @@ -2288,46 +2243,45 @@ def _test_wchar_variant(typename): a[4] # w = cast(BWChar, 'a') - assert repr(w) == "" % (typename, mandatory_u_prefix) + assert repr(w) == "" % typename assert str(w) == repr(w) - assert string(w) == u+'a' + assert string(w) == 'a' assert int(w) == ord('a') w = cast(BWChar, 0x1234) - assert repr(w) == "" % (typename, mandatory_u_prefix) + assert repr(w) == "" % typename assert str(w) == repr(w) - assert string(w) == u+'\u1234' + assert string(w) == '\u1234' assert int(w) == 0x1234 - w = cast(BWChar, u+'\u8234') - assert repr(w) == "" % (typename, mandatory_u_prefix) + w = cast(BWChar, '\u8234') + assert repr(w) == "" % typename assert str(w) == repr(w) - assert string(w) == u+'\u8234' + assert string(w) == '\u8234' assert int(w) == 0x8234 - w = cast(BInt, u+'\u1234') + w = cast(BInt, '\u1234') assert repr(w) == "" if wchar4 and not _hacked_pypy_uni4(): - w = cast(BWChar, u+'\U00012345') - assert repr(w) == "" % ( - typename, mandatory_u_prefix) + w = cast(BWChar, '\U00012345') + assert repr(w) == "" % typename assert str(w) == repr(w) - assert string(w) == u+'\U00012345' + assert string(w) == '\U00012345' assert int(w) == 0x12345 - w = cast(BInt, u+'\U00012345') + w = cast(BInt, '\U00012345') assert repr(w) == "" - pytest.raises(TypeError, cast, BInt, u+'') - pytest.raises(TypeError, cast, BInt, u+'XX') - assert int(cast(BInt, u+'a')) == ord('a') + pytest.raises(TypeError, cast, BInt, '') + pytest.raises(TypeError, cast, BInt, 'XX') + assert int(cast(BInt, 'a')) == ord('a') # - a = newp(BWCharArray, u+'hello - world') + a = newp(BWCharArray, 'hello - world') p = cast(BWCharP, a) - assert string(p) == u+'hello - world' - p[6] = u+'\u2345' - assert string(p) == u+'hello \u2345 world' + assert string(p) == 'hello - world' + p[6] = '\u2345' + assert string(p) == 'hello \u2345 world' # - s = newp(BStructPtr, [u+'\u1234', p]) - assert s.a1 == u+'\u1234' + s = newp(BStructPtr, ['\u1234', p]) + assert s.a1 == '\u1234' assert s.a2 == p assert str(s.a2) == repr(s.a2) - assert string(s.a2) == u+'hello \u2345 world' + assert string(s.a2) == 'hello \u2345 world' # q = cast(BWCharP, 0) assert str(q) == repr(q) @@ -2340,7 +2294,7 @@ def cb(p): return len(string(p)) BFunc = new_function_type((BWCharP,), BInt, False) f = callback(BFunc, cb, -42) - assert f(u+'a\u1234b') == 3 + assert f('a\u1234b') == 3 # if wchar4 and not pyuni4 and not _hacked_pypy_uni4(): # try out-of-range wchar_t values @@ -2365,10 +2319,10 @@ def test_wchar_variants_mix(): x = cast(BChar16, 'A') pytest.raises(TypeError, newp, BChar32A, [x]) # - a = newp(BChar16A, u+'\U00012345') + a = newp(BChar16A, '\U00012345') assert len(a) == 3 - a = newp(BChar32A, u+'\U00012345') - assert len(a) == 2 # even if the Python unicode string above is 2 chars + a = newp(BChar32A, '\U00012345') + assert len(a) == 2 # even if the Python string above is 2 chars def test_keepalive_struct(): # exception to the no-keepalive rule: p=newp(BStructPtr) returns a @@ -2445,13 +2399,12 @@ def test_cmp(): assert (p != q) is True assert (q == p) is False assert (q != p) is True - if strict_compare: - with pytest.raises(TypeError): p < q - with pytest.raises(TypeError): p <= q - with pytest.raises(TypeError): q < p - with pytest.raises(TypeError): q <= p - with pytest.raises(TypeError): p > q - with pytest.raises(TypeError): p >= q + with pytest.raises(TypeError): p < q + with pytest.raises(TypeError): p <= q + with pytest.raises(TypeError): q < p + with pytest.raises(TypeError): q <= p + with pytest.raises(TypeError): p > q + with pytest.raises(TypeError): p >= q r = cast(BVoidP, p) assert (p < r) is False assert (p <= r) is True @@ -2467,10 +2420,7 @@ def test_cmp(): assert (p < s) ^ (p > s) def test_buffer(): - try: - import __builtin__ - except ImportError: - import builtins as __builtin__ + import builtins BShort = new_primitive_type("short") s = newp(new_pointer_type(BShort), 100) assert sizeof(s) == size_of_ptr() @@ -2485,11 +2435,7 @@ def test_buffer(): assert repr(buf).startswith('<_cffi_backend.buffer object at 0x') assert bytes(buf) == b"hi there\x00" assert type(buf) is buffer - if sys.version_info < (3,): - assert str(buf) == "hi there\x00" - assert unicode(buf) == u+"hi there\x00" - else: - assert str(buf) == repr(buf) + assert str(buf) == repr(buf) # --mb_length-- assert len(buf) == len(b"hi there\x00") # --mb_item-- @@ -2500,7 +2446,7 @@ def test_buffer(): with pytest.raises(IndexError): buf[i] else: - assert buf[i] == bitem2bchr(expected) + assert buf[i] == bytes([expected]) # --mb_slice-- assert buf[:] == b"hi there\x00" for i in range(-12, 12): @@ -2509,30 +2455,21 @@ def test_buffer(): for j in range(-12, 12): assert buf[i:j] == b"hi there\x00"[i:j] # --misc-- - assert list(buf) == list(map(bitem2bchr, b"hi there\x00")) - # --mb_as_buffer-- - if hasattr(__builtin__, 'buffer'): # Python <= 2.7 - pytest.raises(TypeError, __builtin__.buffer, c) - bf1 = __builtin__.buffer(buf) - assert len(bf1) == len(buf) and bf1[3] == "t" - if hasattr(__builtin__, 'memoryview'): # Python >= 2.7 - pytest.raises(TypeError, memoryview, c) - mv1 = memoryview(buf) - assert len(mv1) == len(buf) and mv1[3] in (b"t", ord(b"t")) + assert list(buf) == [bytes([c]) for c in b"hi there\x00"] # --mb_ass_item-- - expected = list(map(bitem2bchr, b"hi there\x00")) + expected = list(map(bytechr, b"hi there\x00")) for i in range(-12, 12): try: - expected[i] = bytechr(i & 0xff) + expected[i] = bytes([i & 0xff]) except IndexError: with pytest.raises(IndexError): - buf[i] = bytechr(i & 0xff) + buf[i] = bytes([i & 0xff]) else: - buf[i] = bytechr(i & 0xff) + buf[i] = bytes([i & 0xff]) assert list(buf) == expected # --mb_ass_slice-- buf[:] = b"hi there\x00" - assert list(buf) == list(c) == list(map(bitem2bchr, b"hi there\x00")) + assert list(buf) == list(c) == list(map(bytechr, b"hi there\x00")) with pytest.raises(ValueError): buf[:] = b"shorter" with pytest.raises(ValueError): @@ -2542,7 +2479,7 @@ def test_buffer(): buf[:2] = b"HI" assert buf[:] == b"HI there\x00" buf[:2] = b"hi" - expected = list(map(bitem2bchr, b"hi there\x00")) + expected = list(map(bytechr, b"hi there\x00")) x = 0 for i in range(-12, 12): for j in range(-12, 12): @@ -2550,10 +2487,10 @@ def test_buffer(): stop = j if j >= 0 else j + len(buf) start = max(0, min(len(buf), start)) stop = max(0, min(len(buf), stop)) - sample = bytechr(x & 0xff) * (stop - start) + sample = bytes([x & 0xff]) * (stop - start) x += 1 buf[i:j] = sample - expected[i:j] = map(bitem2bchr, sample) + expected[i:j] = map(bytechr, sample) assert list(buf) == expected def test_getcname(): @@ -2854,8 +2791,7 @@ def test_bool(): assert bool(cast(BBool, False)) is False # since 1.7 assert bool(cast(BBool, True)) is True assert int(cast(BBool, 3)) == 1 - assert int(cast(BBool, long(3))) == 1 - assert int(cast(BBool, long(10)**4000)) == 1 + assert int(cast(BBool, 10**4000)) == 1 assert int(cast(BBool, -0.1)) == 1 assert int(cast(BBool, -0.0)) == 0 assert int(cast(BBool, '\x00')) == 0 @@ -2917,7 +2853,7 @@ def test_typeoffsetof(): assert typeoffsetof(BStructPtr, 'a2') == (BChar, 1) assert typeoffsetof(BStruct, 'a3') == (BChar, 2) assert typeoffsetof(BStructPtr, 'a2', 0) == (BChar, 1) - assert typeoffsetof(BStruct, u+'a3') == (BChar, 2) + assert typeoffsetof(BStruct, 'a3') == (BChar, 2) pytest.raises(TypeError, typeoffsetof, BStructPtr, 'a2', 1) pytest.raises(KeyError, typeoffsetof, BStructPtr, 'a4') pytest.raises(KeyError, typeoffsetof, BStruct, 'a5') @@ -3015,12 +2951,11 @@ def test_string_assignment_to_byte_array(): assert list(p) == [ord("X"), ord("Y"), ord("Z"), 0, 0] # XXX hack -if sys.version_info >= (3,): - try: - import posix - posix.fdopen = open - except ImportError: - pass # win32 +try: + import posix + posix.fdopen = open +except ImportError: + pass # win32 @pytest.mark.skipif( is_ios, @@ -3169,19 +3104,19 @@ def test_nonstandard_integer_types(): def test_cannot_convert_unicode_to_charp(): BCharP = new_pointer_type(new_primitive_type("char")) BCharArray = new_array_type(BCharP, None) - pytest.raises(TypeError, newp, BCharArray, u+'foobar') + pytest.raises(TypeError, newp, BCharArray, 'foobar') def test_buffer_keepalive(): BCharP = new_pointer_type(new_primitive_type("char")) BCharArray = new_array_type(BCharP, None) buflist = [] for i in range(20): - c = newp(BCharArray, str2bytes("hi there %d" % i)) + c = newp(BCharArray, bytes("hi there %d" % i, "ascii")) buflist.append(buffer(c)) import gc; gc.collect() for i in range(20): buf = buflist[i] - assert buf[:] == str2bytes("hi there %d\x00" % i) + assert buf[:] == bytes("hi there %d\x00" % i, "ascii") def test_slice(): BIntP = new_pointer_type(new_primitive_type("int")) @@ -3662,17 +3597,17 @@ def test_ass_slice(): p[1:3] = b"XY" assert list(p) == [b"f", b"X", b"Y", b"Z", b"T", b"r", b"\x00"] with pytest.raises(TypeError): - p[1:5] = u+'XYZT' + p[1:5] = 'XYZT' with pytest.raises(TypeError): p[1:5] = [1, 2, 3, 4] # for typename in ["wchar_t", "char16_t", "char32_t"]: BUniChar = new_primitive_type(typename) BArray = new_array_type(new_pointer_type(BUniChar), None) - p = newp(BArray, u+"foobar") - p[2:5] = [u+"*", u+"Z", u+"T"] - p[1:3] = u+"XY" - assert list(p) == [u+"f", u+"X", u+"Y", u+"Z", u+"T", u+"r", u+"\x00"] + p = newp(BArray, "foobar") + p[2:5] = ["*", "Z", "T"] + p[1:3] = "XY" + assert list(p) == ["f", "X", "Y", "Z", "T", "r", "\x00"] with pytest.raises(TypeError): p[1:5] = b'XYZT' with pytest.raises(TypeError): @@ -3785,31 +3720,12 @@ def test_from_buffer_not_str_unicode(): assert p1 == from_buffer(BCharA, b"foo") import gc; gc.collect() assert p1 == from_buffer(BCharA, b"foo") - pytest.raises(TypeError, from_buffer, BCharA, u+"foo") - try: - from __builtin__ import buffer - except ImportError: - pass - else: - # Python 2 only - contents = from_buffer(BCharA, buffer(b"foo")) - assert len(contents) == len(p1) - for i in range(len(contents)): - assert contents[i] == p1[i] - p4 = buffer(u+"foo") - contents = from_buffer(BCharA, buffer(u+"foo")) - assert len(contents) == len(p4) - for i in range(len(contents)): - assert contents[i] == p4[i] - try: - from __builtin__ import memoryview - except ImportError: - pass - else: - contents = from_buffer(BCharA, memoryview(b"foo")) - assert len(contents) == len(p1) - for i in range(len(contents)): - assert contents[i] == p1[i] + pytest.raises(TypeError, from_buffer, BCharA, "foo") + from builtins import memoryview + contents = from_buffer(BCharA, memoryview(b"foo")) + assert len(contents) == len(p1) + for i in range(len(contents)): + assert contents[i] == p1[i] def test_from_buffer_bytearray(): @@ -3839,23 +3755,21 @@ def test_from_buffer_more_cases(): def check1(bufobj, expected): c = from_buffer(BCharA, bufobj) assert typeof(c) is BCharA - if sys.version_info >= (3,): - expected = [bytes(c, "ascii") for c in expected] + expected = [bytes(c, "ascii") for c in expected] assert list(c) == list(expected) # def check(methods, expected, expected_for_memoryview=None): - if sys.version_info >= (3,): - if methods <= 7: - return - if expected_for_memoryview is not None: - expected = expected_for_memoryview + if methods <= 7: + return + if expected_for_memoryview is not None: + expected = expected_for_memoryview class X: pass _testbuff(X, methods) bufobj = X() check1(bufobj, expected) try: - from __builtin__ import buffer + from builtins import buffer bufobjb = buffer(bufobj) except (TypeError, ImportError): pass @@ -4320,19 +4234,14 @@ def assert_ne(a, b): assert (b == a) is False assert (a != b) is True assert (b != a) is True - if strict_compare: - with pytest.raises(TypeError): a < b - with pytest.raises(TypeError): a <= b - with pytest.raises(TypeError): a > b - with pytest.raises(TypeError): a >= b - with pytest.raises(TypeError): b < a - with pytest.raises(TypeError): b <= a - with pytest.raises(TypeError): b > a - with pytest.raises(TypeError): b >= a - elif a < b: - assert_lt(a, b) - else: - assert_lt(b, a) + with pytest.raises(TypeError): a < b + with pytest.raises(TypeError): a <= b + with pytest.raises(TypeError): a > b + with pytest.raises(TypeError): a >= b + with pytest.raises(TypeError): b < a + with pytest.raises(TypeError): b <= a + with pytest.raises(TypeError): b > a + with pytest.raises(TypeError): b >= a assert_eq(5, 5) assert_lt(3, 5) assert_ne('5', 5) @@ -4491,8 +4400,6 @@ def test_int_doesnt_give_bool(): BBool = new_primitive_type("_Bool") x = int(cast(BBool, 42)) assert type(x) is int and x == 1 - x = long(cast(BBool, 42)) - assert type(x) is long and x == 1 with pytest.raises(TypeError): float(cast(BBool, 42)) with pytest.raises(TypeError): diff --git a/src/cffi/api.py b/src/cffi/api.py index ec8ee7df..d68cc832 100644 --- a/src/cffi/api.py +++ b/src/cffi/api.py @@ -3,12 +3,6 @@ from .error import CDefError from . import model -try: - basestring -except NameError: - # Python 3.x - basestring = str - _unspecified = object() @@ -111,7 +105,7 @@ def embedding_api(self, csource, packed=False, pack=None): def _cdef(self, csource, override=False, **options): if not isinstance(csource, str): # unicode, on Python 2 - if not isinstance(csource, basestring): + if not isinstance(csource, str): raise TypeError("cdef() argument must be a string") csource = csource.encode('ascii') with self._lock: @@ -134,7 +128,7 @@ def dlopen(self, name, flags=0): linked to a particular library, just like C headers; in the library we only look for the actual (untyped) symbols. """ - if not (isinstance(name, basestring) or + if not (isinstance(name, str) or name is None or isinstance(name, self.CData)): raise TypeError("dlopen(name): name must be a file name, None, " @@ -189,7 +183,7 @@ def typeof(self, cdecl): corresponding object. It can also be used on 'cdata' instance to get its C type. """ - if isinstance(cdecl, basestring): + if isinstance(cdecl, str): return self._typeof(cdecl) if isinstance(cdecl, self.CData): return self._backend.typeof(cdecl) @@ -207,7 +201,7 @@ def sizeof(self, cdecl): """Return the size in bytes of the argument. It can be a string naming a C type, or a 'cdata' instance. """ - if isinstance(cdecl, basestring): + if isinstance(cdecl, str): BType = self._typeof(cdecl) return self._backend.sizeof(BType) else: @@ -217,7 +211,7 @@ def alignof(self, cdecl): """Return the natural alignment size in bytes of the C type given as a string. """ - if isinstance(cdecl, basestring): + if isinstance(cdecl, str): cdecl = self._typeof(cdecl) return self._backend.alignof(cdecl) @@ -228,7 +222,7 @@ def offsetof(self, cdecl, *fields_or_indexes): You can also give numeric values which correspond to array items, in case of an array type. """ - if isinstance(cdecl, basestring): + if isinstance(cdecl, str): cdecl = self._typeof(cdecl) return self._typeoffsetof(cdecl, *fields_or_indexes)[1] @@ -255,7 +249,7 @@ def new(self, cdecl, init=None): about that when copying the pointer to the memory somewhere else, e.g. into another structure. """ - if isinstance(cdecl, basestring): + if isinstance(cdecl, str): cdecl = self._typeof(cdecl) return self._backend.newp(cdecl, init) @@ -278,7 +272,7 @@ def new_allocator(self, alloc=None, free=None, allocator = compiled_ffi.new_allocator(alloc, free, should_clear_after_alloc) def allocate(cdecl, init=None): - if isinstance(cdecl, basestring): + if isinstance(cdecl, str): cdecl = self._typeof(cdecl) return allocator(cdecl, init) return allocate @@ -288,7 +282,7 @@ def cast(self, cdecl, source): type initialized with the given 'source'. The source is casted between integers or pointers of any type. """ - if isinstance(cdecl, basestring): + if isinstance(cdecl, str): cdecl = self._typeof(cdecl) return self._backend.cast(cdecl, source) @@ -353,7 +347,7 @@ def from_buffer(self, cdecl, python_buffer=_unspecified, """ if python_buffer is _unspecified: cdecl, python_buffer = self.BCharA, cdecl - elif isinstance(cdecl, basestring): + elif isinstance(cdecl, str): cdecl = self._typeof(cdecl) return self._backend.from_buffer(cdecl, python_buffer, require_writable) @@ -388,7 +382,7 @@ def callback_decorator_wrap(python_callable): "is not callable") return self._backend.callback(cdecl, python_callable, error, onerror) - if isinstance(cdecl, basestring): + if isinstance(cdecl, str): cdecl = self._typeof(cdecl, consider_function_as_funcptr=True) if python_callable is None: return callback_decorator_wrap # decorator mode @@ -401,7 +395,7 @@ def getctype(self, cdecl, replace_with=''): extra text to append (or insert for more complicated C types), like a variable name, or '*' to get actually the C type 'pointer-to-cdecl'. """ - if isinstance(cdecl, basestring): + if isinstance(cdecl, str): cdecl = self._typeof(cdecl) replace_with = replace_with.strip() if (replace_with.startswith('*') @@ -596,10 +590,7 @@ def ensure(key, value): # we need 'libpypy-c.{so,dylib}', which should be by # default located in 'sys.prefix/bin' for installed # systems. - if sys.version_info < (3,): - pythonlib = "pypy-c" - else: - pythonlib = "pypy3-c" + pythonlib = "pypy3-c" if hasattr(sys, 'prefix'): ensure('library_dirs', os.path.join(sys.prefix, 'bin')) # On uninstalled pypy's, the libpypy-c is typically found in @@ -632,7 +623,7 @@ def set_source(self, module_name, source, source_extension='.c', **kwds): if hasattr(self, '_assigned_source'): raise ValueError("set_source() cannot be called several times " "per ffi object") - if not isinstance(module_name, basestring): + if not isinstance(module_name, str): raise TypeError("'module_name' must be a string") if os.sep in module_name or (os.altsep and os.altsep in module_name): raise ValueError("'module_name' must not contain '/': use a dotted " @@ -798,7 +789,7 @@ def list_types(self): def _load_backend_lib(backend, name, flags): import os - if not isinstance(name, basestring): + if not isinstance(name, str): if sys.platform != "win32" or name is not None: return backend.load_library(name, flags) name = "c" # Windows: load_library(None) fails, but this works @@ -934,7 +925,7 @@ def __cffi_close__(self): backendlib.close_lib() self.__dict__.clear() # - if isinstance(libname, basestring): + if isinstance(libname, str): try: if not isinstance(libname, str): # unicode, on Python 2 libname = libname.encode('utf-8') diff --git a/src/cffi/backend_ctypes.py b/src/cffi/backend_ctypes.py index 0801fc8e..f9bf117d 100644 --- a/src/cffi/backend_ctypes.py +++ b/src/cffi/backend_ctypes.py @@ -1,14 +1,6 @@ import ctypes, ctypes.util, operator, sys from . import model -if sys.version_info < (3,): - bytechr = chr -else: - unicode = str - long = int - xrange = range - bytechr = lambda num: bytes([num]) - class CTypesType(type): pass @@ -161,7 +153,7 @@ def _newp(cls, init): return cls(init) def __iter__(self): - for i in xrange(len(self)): + for i in range(len(self)): yield self[i] def _get_own_repr(self): @@ -183,7 +175,7 @@ def _cast_from(cls, source): address = 0 elif isinstance(source, CTypesData): address = source._cast_to_integer() - elif isinstance(source, (int, long)): + elif isinstance(source, int): address = source else: raise TypeError("bad type for cast to %r: %r" % @@ -358,7 +350,7 @@ def new_primitive_type(self, name): is_signed = (ctype(-1).value == -1) # def _cast_source_to_int(source): - if isinstance(source, (int, long, float)): + if isinstance(source, (int, float)): source = int(source) elif isinstance(source, CTypesData): source = source._cast_to_integer() @@ -399,7 +391,7 @@ def __int__(self): if kind == 'bool': @classmethod def _cast_from(cls, source): - if not isinstance(source, (int, long, float)): + if not isinstance(source, (int, float)): source = _cast_source_to_int(source) return cls(bool(source)) def __int__(self): @@ -409,7 +401,7 @@ def __int__(self): @classmethod def _cast_from(cls, source): source = _cast_source_to_int(source) - source = bytechr(source & 0xFF) + source = bytes([source & 0xFF]) return cls(source) def __int__(self): return ord(self._value) @@ -438,7 +430,7 @@ def __float__(self): if kind == 'int' or kind == 'byte' or kind == 'bool': @staticmethod def _to_ctypes(x): - if not isinstance(x, (int, long)): + if not isinstance(x, int): if isinstance(x, CTypesData): x = int(x) else: @@ -471,7 +463,7 @@ def __nonzero__(self): if kind == 'float': @staticmethod def _to_ctypes(x): - if not isinstance(x, (int, long, float, CTypesData)): + if not isinstance(x, (int, float, CTypesData)): raise TypeError("float expected, got %s" % type(x).__name__) return ctype(x).value @@ -535,14 +527,14 @@ def __init__(self, init): self._own = True def __add__(self, other): - if isinstance(other, (int, long)): + if isinstance(other, int): return self._new_pointer_at(self._address + other * self._bitem_size) else: return NotImplemented def __sub__(self, other): - if isinstance(other, (int, long)): + if isinstance(other, int): return self._new_pointer_at(self._address - other * self._bitem_size) elif type(self) is type(other): @@ -617,7 +609,7 @@ class CTypesArray(CTypesGenericArray): def __init__(self, init): if length is None: - if isinstance(init, (int, long)): + if isinstance(init, int): len1 = init init = None elif kind == 'char' and isinstance(init, bytes): @@ -696,7 +688,7 @@ def _arg_to_ctypes(value): return CTypesPtr._arg_to_ctypes(value) def __add__(self, other): - if isinstance(other, (int, long)): + if isinstance(other, int): return CTypesPtr._new_pointer_at( ctypes.addressof(self._blob) + other * ctypes.sizeof(BItem._ctype)) @@ -776,7 +768,7 @@ def initialize(blob, init): "only one supported (use a dict if needed)" % (len(init),)) if not isinstance(init, dict): - if isinstance(init, (bytes, unicode)): + if isinstance(init, (bytes, str)): raise TypeError("union initializer: got a str") init = tuple(init) if len(init) > len(fnames): @@ -1061,7 +1053,7 @@ def typeoffsetof(self, BType, fieldname, num=0): if BField is Ellipsis: raise TypeError("not supported for bitfields") return (BField, BType._offsetof(fieldname)) - elif isinstance(fieldname, (int, long)): + elif isinstance(fieldname, int): if issubclass(BType, CTypesGenericArray): BType = BType._CTPtr if not issubclass(BType, CTypesGenericPtr): diff --git a/src/cffi/cparser.py b/src/cffi/cparser.py index 2d78fc4b..3b777803 100644 --- a/src/cffi/cparser.py +++ b/src/cffi/cparser.py @@ -8,10 +8,7 @@ import weakref, re, sys try: - if sys.version_info < (3,): - import thread as _thread - else: - import _thread + import _thread lock = _thread.allocate_lock() except ImportError: lock = None diff --git a/src/cffi/ffiplatform.py b/src/cffi/ffiplatform.py index adca28f1..d438580f 100644 --- a/src/cffi/ffiplatform.py +++ b/src/cffi/ffiplatform.py @@ -1,3 +1,4 @@ +import io import sys, os from .error import VerificationError @@ -81,13 +82,6 @@ def maybe_relative_path(path): # ____________________________________________________________ -try: - int_or_long = (int, long) - import cStringIO -except NameError: - int_or_long = int # Python 3 - import io as cStringIO - def _flatten(x, f): if isinstance(x, str): f.write('%ds%s' % (len(x), x)) @@ -101,13 +95,13 @@ def _flatten(x, f): f.write('%dl' % len(x)) for value in x: _flatten(value, f) - elif isinstance(x, int_or_long): + elif isinstance(x, int): f.write('%di' % (x,)) else: raise TypeError( "the keywords to verify() contains unsupported object %r" % (x,)) def flatten(x): - f = cStringIO.StringIO() + f = io.StringIO() _flatten(x, f) return f.getvalue() diff --git a/src/cffi/lock.py b/src/cffi/lock.py index db91b715..f44f3e56 100644 --- a/src/cffi/lock.py +++ b/src/cffi/lock.py @@ -1,15 +1,9 @@ import sys -if sys.version_info < (3,): - try: - from thread import allocate_lock - except ImportError: - from dummy_thread import allocate_lock -else: - try: - from _thread import allocate_lock - except ImportError: - from _dummy_thread import allocate_lock +try: + from _thread import allocate_lock +except ImportError: + from _dummy_thread import allocate_lock ##import sys diff --git a/src/cffi/recompiler.py b/src/cffi/recompiler.py index 495b897a..df6643cd 100644 --- a/src/cffi/recompiler.py +++ b/src/cffi/recompiler.py @@ -1300,12 +1300,8 @@ def _print_string_literal_in_array(self, s): else: s.decode('utf-8') # got bytes, check for valid utf-8 for line in s.splitlines(True): - comment = line - if type('//') is bytes: # python2 - line = map(ord, line) # make a list of integers - else: # python3 - # type(line) is bytes, which enumerates like a list of integers - comment = ascii(comment)[1:-1] + # type(line) is bytes, which enumerates like a list of integers + comment = ascii(line)[1:-1] prnt(('// ' + comment).rstrip()) printed_line = '' for c in line: @@ -1390,15 +1386,6 @@ def _emit_bytecode_EnumType(self, tp, index): self.cffi_types[index] = CffiOp(OP_ENUM, enum_index) -if sys.version_info >= (3,): - NativeIO = io.StringIO -else: - class NativeIO(io.BytesIO): - def write(self, s): - if isinstance(s, unicode): - s = s.encode('ascii') - super().write(s) - def _is_file_like(maybefile): # compare to xml.etree.ElementTree._get_writer return hasattr(maybefile, 'write') @@ -1413,7 +1400,7 @@ def _make_c_or_py_source(ffi, module_name, preamble, target_file, verbose): if _is_file_like(target_file): recompiler.write_source_to_f(target_file, preamble) return True - f = NativeIO() + f = io.StringIO() recompiler.write_source_to_f(f, preamble) output = f.getvalue() try: diff --git a/src/cffi/vengine_gen.py b/src/cffi/vengine_gen.py index 0209c794..1f9b76ab 100644 --- a/src/cffi/vengine_gen.py +++ b/src/cffi/vengine_gen.py @@ -55,12 +55,8 @@ def write_source_to_f(self): # 'export_symbols', so instead of fighting it, just give up and # give it one if sys.platform == 'win32': - if sys.version_info >= (3,): - prefix = 'PyInit_' - else: - prefix = 'init' modname = self.verifier.get_module_name() - prnt("void %s%s(void) { }\n" % (prefix, modname)) + prnt(f"void PyInit_{modname}(void) {{ }}\n") def load_library(self, flags=0): # import it with the CFFI backend @@ -496,10 +492,7 @@ def _load_known_int_constant(self, module, funcname): function = module.load_function(BFunc, funcname) p = self.ffi.new(BType, 256) if function(p) < 0: - error = self.ffi.string(p) - if sys.version_info >= (3,): - error = str(error, 'utf-8') - raise VerificationError(error) + raise VerificationError(self.ffi.string(p)) def _enum_funcname(self, prefix, name): # "$enum_$1" => "___D_enum____D_1" diff --git a/src/cffi/verifier.py b/src/cffi/verifier.py index 5ad0105e..3423dcb7 100644 --- a/src/cffi/verifier.py +++ b/src/cffi/verifier.py @@ -6,25 +6,9 @@ from . import ffiplatform from .error import VerificationError -if sys.version_info >= (3, 3): - import importlib.machinery - def _extension_suffixes(): - return importlib.machinery.EXTENSION_SUFFIXES[:] -else: - import imp - def _extension_suffixes(): - return [suffix for suffix, _, type in imp.get_suffixes() - if type == imp.C_EXTENSION] - - -if sys.version_info >= (3,): - NativeIO = io.StringIO -else: - class NativeIO(io.BytesIO): - def write(self, s): - if isinstance(s, unicode): - s = s.encode('ascii') - super().write(s) +import importlib.machinery +def _extension_suffixes(): + return importlib.machinery.EXTENSION_SUFFIXES[:] class Verifier: @@ -54,8 +38,7 @@ def __init__(self, ffi, preamble, tmpdir=None, modulename=None, __version_verifier_modules__, preamble, flattened_kwds] + ffi._cdefsources) - if sys.version_info >= (3,): - key = key.encode('utf-8') + key = key.encode('utf-8') k1 = hex(binascii.crc32(key[0::2]) & 0xffffffff) k1 = k1.lstrip('0x').rstrip('L') k2 = hex(binascii.crc32(key[1::2]) & 0xffffffff) @@ -175,7 +158,7 @@ def _write_source(self, file=None): self._write_source_to(file) else: # Write our source file to an in memory file. - f = NativeIO() + f = io.StringIO() self._write_source_to(f) source_data = f.getvalue() diff --git a/testing/cffi0/backend_tests.py b/testing/cffi0/backend_tests.py index 99b30316..4197ab30 100644 --- a/testing/cffi0/backend_tests.py +++ b/testing/cffi0/backend_tests.py @@ -311,7 +311,7 @@ def test_char(self): assert bool(ffi.cast("char", 1)) assert bool(ffi.cast("char", 255)) pytest.raises(TypeError, ffi.new, "char*", 32) - pytest.raises(TypeError, ffi.new, "char*", u+"x") + pytest.raises(TypeError, ffi.new, "char*", "x") pytest.raises(TypeError, ffi.new, "char*", b"foo") # p = ffi.new("char[]", [b'a', b'b', b'\x9c']) @@ -342,13 +342,13 @@ def check_wchar_t(self, ffi): def test_wchar_t(self): ffi = FFI(backend=self.Backend()) self.check_wchar_t(ffi) - assert ffi.new("wchar_t*", u+'x')[0] == u+'x' - assert ffi.new("wchar_t*", u+'\u1234')[0] == u+'\u1234' + assert ffi.new("wchar_t*", 'x')[0] == 'x' + assert ffi.new("wchar_t*", '\u1234')[0] == '\u1234' if SIZE_OF_WCHAR > 2: - assert ffi.new("wchar_t*", u+'\U00012345')[0] == u+'\U00012345' + assert ffi.new("wchar_t*", '\U00012345')[0] == '\U00012345' else: - pytest.raises(TypeError, ffi.new, "wchar_t*", u+'\U00012345') - assert ffi.new("wchar_t*")[0] == u+'\x00' + pytest.raises(TypeError, ffi.new, "wchar_t*", '\U00012345') + assert ffi.new("wchar_t*")[0] == '\x00' assert int(ffi.cast("wchar_t", 300)) == 300 assert not bool(ffi.cast("wchar_t", 0)) assert bool(ffi.cast("wchar_t", 1)) @@ -358,40 +358,40 @@ def test_wchar_t(self): pytest.raises(TypeError, ffi.new, "wchar_t*", 32) pytest.raises(TypeError, ffi.new, "wchar_t*", "foo") # - p = ffi.new("wchar_t[]", [u+'a', u+'b', u+'\u1234']) + p = ffi.new("wchar_t[]", ['a', 'b', '\u1234']) assert len(p) == 3 - assert p[0] == u+'a' - assert p[1] == u+'b' and type(p[1]) is unicode - assert p[2] == u+'\u1234' - p[0] = u+'x' - assert p[0] == u+'x' and type(p[0]) is unicode - p[1] = u+'\u1357' - assert p[1] == u+'\u1357' - p = ffi.new("wchar_t[]", u+"abcd") + assert p[0] == 'a' + assert p[1] == 'b' and type(p[1]) is str + assert p[2] == '\u1234' + p[0] = 'x' + assert p[0] == 'x' and type(p[0]) is str + p[1] = '\u1357' + assert p[1] == '\u1357' + p = ffi.new("wchar_t[]", "abcd") assert len(p) == 5 - assert p[4] == u+'\x00' - p = ffi.new("wchar_t[]", u+"a\u1234b") + assert p[4] == '\x00' + p = ffi.new("wchar_t[]", "a\u1234b") assert len(p) == 4 - assert p[1] == u+'\u1234' + assert p[1] == '\u1234' # - p = ffi.new("wchar_t[]", u+'\U00023456') + p = ffi.new("wchar_t[]", '\U00023456') if SIZE_OF_WCHAR == 2: assert len(p) == 3 - assert p[0] == u+'\ud84d' - assert p[1] == u+'\udc56' - assert p[2] == u+'\x00' + assert p[0] == '\ud84d' + assert p[1] == '\udc56' + assert p[2] == '\x00' else: assert len(p) == 2 - assert p[0] == u+'\U00023456' - assert p[1] == u+'\x00' + assert p[0] == '\U00023456' + assert p[1] == '\x00' # - p = ffi.new("wchar_t[4]", u+"ab") + p = ffi.new("wchar_t[4]", "ab") assert len(p) == 4 - assert [p[i] for i in range(4)] == [u+'a', u+'b', u+'\x00', u+'\x00'] - p = ffi.new("wchar_t[2]", u+"ab") + assert [p[i] for i in range(4)] == ['a', 'b', '\x00', '\x00'] + p = ffi.new("wchar_t[2]", "ab") assert len(p) == 2 - assert [p[i] for i in range(2)] == [u+'a', u+'b'] - pytest.raises(IndexError, ffi.new, "wchar_t[2]", u+"abc") + assert [p[i] for i in range(2)] == ['a', 'b'] + pytest.raises(IndexError, ffi.new, "wchar_t[2]", "abc") def test_none_as_null_doesnt_work(self): ffi = FFI(backend=self.Backend()) @@ -596,15 +596,15 @@ def test_string_from_char_pointer(self): assert str(x) == repr(x) assert ffi.string(x) == b"x" assert ffi.string(ffi.new("char*", b"\x00")) == b"" - pytest.raises(TypeError, ffi.new, "char*", unicode("foo")) + pytest.raises(TypeError, ffi.new, "char*", "foo") def test_unicode_from_wchar_pointer(self): ffi = FFI(backend=self.Backend()) self.check_wchar_t(ffi) - x = ffi.new("wchar_t*", u+"x") - assert unicode(x) == unicode(repr(x)) - assert ffi.string(x) == u+"x" - assert ffi.string(ffi.new("wchar_t*", u+"\x00")) == u+"" + x = ffi.new("wchar_t*", "x") + assert str(x) == repr(x) + assert ffi.string(x) == "x" + assert ffi.string(ffi.new("wchar_t*", "\x00")) == "" def test_string_from_char_array(self): ffi = FFI(backend=self.Backend()) @@ -627,30 +627,30 @@ def test_string_from_char_array(self): def test_string_from_wchar_array(self): ffi = FFI(backend=self.Backend()) self.check_wchar_t(ffi) - assert ffi.string(ffi.cast("wchar_t", "x")) == u+"x" - assert ffi.string(ffi.cast("wchar_t", u+"x")) == u+"x" + assert ffi.string(ffi.cast("wchar_t", "x")) == "x" + assert ffi.string(ffi.cast("wchar_t", "x")) == "x" x = ffi.cast("wchar_t", "x") assert str(x) == repr(x) - assert ffi.string(x) == u+"x" + assert ffi.string(x) == "x" # - p = ffi.new("wchar_t[]", u+"hello.") - p[5] = u+'!' - assert ffi.string(p) == u+"hello!" - p[6] = u+'\u04d2' - assert ffi.string(p) == u+"hello!\u04d2" - p[3] = u+'\x00' - assert ffi.string(p) == u+"hel" - assert ffi.string(p, 123) == u+"hel" + p = ffi.new("wchar_t[]", "hello.") + p[5] = '!' + assert ffi.string(p) == "hello!" + p[6] = '\u04d2' + assert ffi.string(p) == "hello!\u04d2" + p[3] = '\x00' + assert ffi.string(p) == "hel" + assert ffi.string(p, 123) == "hel" with pytest.raises(IndexError): - p[7] = u+'X' + p[7] = 'X' # - a = ffi.new("wchar_t[]", u+"hello\x00world") + a = ffi.new("wchar_t[]", "hello\x00world") assert len(a) == 12 p = ffi.cast("wchar_t *", a) - assert ffi.string(p) == u+'hello' - assert ffi.string(p, 123) == u+'hello' - assert ffi.string(p, 5) == u+'hello' - assert ffi.string(p, 2) == u+'he' + assert ffi.string(p) == 'hello' + assert ffi.string(p, 123) == 'hello' + assert ffi.string(p, 5) == 'hello' + assert ffi.string(p, 2) == 'he' def test_fetch_const_char_p_field(self): # 'const' is ignored so far @@ -658,7 +658,7 @@ def test_fetch_const_char_p_field(self): ffi.cdef("struct foo { const char *name; };") t = ffi.new("const char[]", b"testing") s = ffi.new("struct foo*", [t]) - assert type(s.name) not in (bytes, str, unicode) + assert type(s.name) not in (bytes, str) assert ffi.string(s.name) == b"testing" with pytest.raises(TypeError): s.name = None @@ -670,10 +670,10 @@ def test_fetch_const_wchar_p_field(self): ffi = FFI(backend=self.Backend()) self.check_wchar_t(ffi) ffi.cdef("struct foo { const wchar_t *name; };") - t = ffi.new("const wchar_t[]", u+"testing") + t = ffi.new("const wchar_t[]", "testing") s = ffi.new("struct foo*", [t]) - assert type(s.name) not in (bytes, str, unicode) - assert ffi.string(s.name) == u+"testing" + assert type(s.name) not in (bytes, str) + assert ffi.string(s.name) == "testing" s.name = ffi.NULL assert s.name == ffi.NULL @@ -793,7 +793,7 @@ def test_char_cast(self): def test_wchar_cast(self): ffi = FFI(backend=self.Backend()) self.check_wchar_t(ffi) - p = ffi.cast("int", ffi.cast("wchar_t", u+'\u1234')) + p = ffi.cast("int", ffi.cast("wchar_t", '\u1234')) assert int(p) == 0x1234 p = ffi.cast("long long", ffi.cast("wchar_t", -1)) if SIZE_OF_WCHAR == 2: # 2 bytes, unsigned @@ -803,7 +803,7 @@ def test_wchar_cast(self): assert int(p) == -1 else: # in general, it can be either signed or not assert int(p) in [-1, 0xffffffff] # e.g. on arm, both cases occur - p = ffi.cast("int", u+'\u1234') + p = ffi.cast("int", '\u1234') assert int(p) == 0x1234 def test_cast_array_to_charp(self): @@ -1279,8 +1279,7 @@ def test_ffi_buffer_with_io(self): def test_ffi_buffer_comparisons(self): ffi = FFI(backend=self.Backend()) ba = bytearray(range(100, 110)) - if sys.version_info >= (2, 7): - assert ba == memoryview(ba) # justification for the following + assert ba == memoryview(ba) # justification for the following a = ffi.new("uint8_t[]", list(ba)) c = ffi.new("uint8_t[]", [99] + list(ba)) try: @@ -1968,10 +1967,7 @@ def do_init(): def test_init_once_multithread(self): import sys, time - if sys.version_info < (3,): - import thread - else: - import _thread as thread + import _thread as thread # def do_init(): seen.append('init!') diff --git a/testing/cffi0/test_ctypes.py b/testing/cffi0/test_ctypes.py index f3a50a12..6a8537a0 100644 --- a/testing/cffi0/test_ctypes.py +++ b/testing/cffi0/test_ctypes.py @@ -41,8 +41,3 @@ def test_nested_anonymous_union(self): def test_nested_anonymous_struct_2(self): pytest.skip("ctypes backend: not supported: nested anonymous union") - - def test_CData_CType_2(self): - if sys.version_info >= (3,): - pytest.skip("ctypes backend: not supported in Python 3: CType") - backend_tests.BackendTests.test_CData_CType_2(self) diff --git a/testing/cffi0/test_ffi_backend.py b/testing/cffi0/test_ffi_backend.py index 986f7081..cade60b4 100644 --- a/testing/cffi0/test_ffi_backend.py +++ b/testing/cffi0/test_ffi_backend.py @@ -1,7 +1,6 @@ import sys, platform import pytest from testing.cffi0 import backend_tests, test_function, test_ownlib -from testing.support import u from cffi import FFI import _cffi_backend @@ -613,32 +612,32 @@ def test_char16_t(self): ffi = FFI() x = ffi.new("char16_t[]", 5) assert len(x) == 5 and ffi.sizeof(x) == 10 - x[2] = u+'\u1324' - assert x[2] == u+'\u1324' - y = ffi.new("char16_t[]", u+'\u1234\u5678') + x[2] = '\u1324' + assert x[2] == '\u1324' + y = ffi.new("char16_t[]", '\u1234\u5678') assert len(y) == 3 - assert list(y) == [u+'\u1234', u+'\u5678', u+'\x00'] - assert ffi.string(y) == u+'\u1234\u5678' - z = ffi.new("char16_t[]", u+'\U00012345') + assert list(y) == ['\u1234', '\u5678', '\x00'] + assert ffi.string(y) == '\u1234\u5678' + z = ffi.new("char16_t[]", '\U00012345') assert len(z) == 3 - assert list(z) == [u+'\ud808', u+'\udf45', u+'\x00'] - assert ffi.string(z) == u+'\U00012345' + assert list(z) == ['\ud808', '\udf45', '\x00'] + assert ffi.string(z) == '\U00012345' def test_char32_t(self): ffi = FFI() x = ffi.new("char32_t[]", 5) assert len(x) == 5 and ffi.sizeof(x) == 20 - x[3] = u+'\U00013245' - assert x[3] == u+'\U00013245' - y = ffi.new("char32_t[]", u+'\u1234\u5678') + x[3] = '\U00013245' + assert x[3] == '\U00013245' + y = ffi.new("char32_t[]", '\u1234\u5678') assert len(y) == 3 - assert list(y) == [u+'\u1234', u+'\u5678', u+'\x00'] - py_uni = u+'\U00012345' + assert list(y) == ['\u1234', '\u5678', '\x00'] + py_uni = '\U00012345' z = ffi.new("char32_t[]", py_uni) assert len(z) == 2 - assert list(z) == [py_uni, u+'\x00'] # maybe a 2-unichars string + assert list(z) == [py_uni, '\x00'] # maybe a 2-unichars string assert ffi.string(z) == py_uni if len(py_uni) == 1: # 4-bytes unicodes in Python - s = ffi.new("char32_t[]", u+'\ud808\udf00') + s = ffi.new("char32_t[]", '\ud808\udf00') assert len(s) == 3 - assert list(s) == [u+'\ud808', u+'\udf00', u+'\x00'] + assert list(s) == ['\ud808', '\udf00', '\x00'] diff --git a/testing/cffi0/test_ownlib.py b/testing/cffi0/test_ownlib.py index af52f766..488327b0 100644 --- a/testing/cffi0/test_ownlib.py +++ b/testing/cffi0/test_ownlib.py @@ -3,7 +3,7 @@ import pytest from cffi import FFI from cffi.backend_ctypes import CTypesBackend -from testing.support import u, is_musl +from testing.support import is_musl SOURCE = """\ @@ -165,14 +165,13 @@ def setup_class(cls): encoded = None if cls.Backend is not CTypesBackend: try: - unicode_name = u+'testownlibcaf\xe9' + unicode_name = 'testownlibcaf\xe9' encoded = unicode_name.encode(sys.getfilesystemencoding()) - if sys.version_info >= (3,): - encoded = str(unicode_name) + encoded = str(unicode_name) except UnicodeEncodeError: pass if encoded is None: - unicode_name = u+'testownlib' + unicode_name = 'testownlib' encoded = str(unicode_name) subprocess.check_call( "cc testownlib.c -shared -fPIC -o '%s.so'" % (encoded,), @@ -359,9 +358,9 @@ def test_char16_char32_t(self): char32_t foo_4bytes(char32_t); """) lib = ffi.dlopen(self.module) - assert lib.foo_2bytes(u+'\u1234') == u+'\u125e' - assert lib.foo_4bytes(u+'\u1234') == u+'\u125e' - assert lib.foo_4bytes(u+'\U00012345') == u+'\U0001236f' + assert lib.foo_2bytes('\u1234') == '\u125e' + assert lib.foo_4bytes('\u1234') == '\u125e' + assert lib.foo_4bytes('\U00012345') == '\U0001236f' def test_modify_struct_value(self): if self.module is None: diff --git a/testing/cffi0/test_verify.py b/testing/cffi0/test_verify.py index f7a9c881..bcc459f8 100644 --- a/testing/cffi0/test_verify.py +++ b/testing/cffi0/test_verify.py @@ -391,11 +391,11 @@ def test_char_type(): def test_wchar_type(): ffi = FFI() if ffi.sizeof('wchar_t') == 2: - uniexample1 = u+'\u1234' - uniexample2 = u+'\u1235' + uniexample1 = '\u1234' + uniexample2 = '\u1235' else: - uniexample1 = u+'\U00012345' - uniexample2 = u+'\U00012346' + uniexample1 = '\U00012345' + uniexample2 = '\U00012346' # ffi.cdef("wchar_t foo(wchar_t);") lib = ffi.verify("wchar_t foo(wchar_t x) { return x+1; }") diff --git a/testing/cffi0/test_zintegration.py b/testing/cffi0/test_zintegration.py index 69c3d01f..a8dac861 100644 --- a/testing/cffi0/test_zintegration.py +++ b/testing/cffi0/test_zintegration.py @@ -8,10 +8,6 @@ if sys.platform == 'win32': pytestmark = pytest.mark.skip('snippets do not run on win32') -if sys.version_info < (2, 7): - pytestmark = pytest.mark.skip( - 'fails e.g. on a Debian/Ubuntu which patches virtualenv' - ' in a non-2.6-friendly way') def create_venv(name): tmpdir = udir / name diff --git a/testing/cffi1/test_dlopen_unicode_literals.py b/testing/cffi1/test_dlopen_unicode_literals.py deleted file mode 100644 index dc955a57..00000000 --- a/testing/cffi1/test_dlopen_unicode_literals.py +++ /dev/null @@ -1,9 +0,0 @@ -import os - -s = """from __future__ import unicode_literals -""" - -with open(os.path.join(os.path.dirname(__file__), 'test_dlopen.py')) as f: - s += f.read() - -exec(compile(s, filename='test_dlopen.py', mode='exec')) diff --git a/testing/cffi1/test_ffi_obj.py b/testing/cffi1/test_ffi_obj.py index 0914ead5..da8268a5 100644 --- a/testing/cffi1/test_ffi_obj.py +++ b/testing/cffi1/test_ffi_obj.py @@ -467,10 +467,7 @@ def do_init(): assert seen == [1, 1] def test_init_once_multithread(): - if sys.version_info < (3,): - import thread - else: - import _thread as thread + import _thread as thread import time # def do_init(): @@ -501,10 +498,7 @@ def do_init(): assert seen == [1] * (i + 1) def test_init_once_multithread_failure(): - if sys.version_info < (3,): - import thread - else: - import _thread as thread + import _thread as thread import time def do_init(): seen.append('init!') diff --git a/testing/cffi1/test_new_ffi_1.py b/testing/cffi1/test_new_ffi_1.py index 676d235d..5bb58f89 100644 --- a/testing/cffi1/test_new_ffi_1.py +++ b/testing/cffi1/test_new_ffi_1.py @@ -1,10 +1,11 @@ import pytest import platform +import io import sys, os, ctypes import cffi from testing.udir import udir from testing.support import * -from cffi.recompiler import recompile, NativeIO +from cffi.recompiler import recompile from cffi.cffi_opcode import PRIMITIVE_TO_INDEX SIZE_OF_INT = ctypes.sizeof(ctypes.c_int) @@ -362,7 +363,7 @@ def test_char(self): assert bool(ffi.cast("char", 1)) assert bool(ffi.cast("char", 255)) pytest.raises(TypeError, ffi.new, "char*", 32) - pytest.raises(TypeError, ffi.new, "char*", u+"x") + pytest.raises(TypeError, ffi.new, "char*", "x") pytest.raises(TypeError, ffi.new, "char*", b"foo") # p = ffi.new("char[]", [b'a', b'b', b'\x9c']) @@ -392,13 +393,13 @@ def check_wchar_t(self, ffi): def test_wchar_t(self): self.check_wchar_t(ffi) - assert ffi.new("wchar_t*", u+'x')[0] == u+'x' - assert ffi.new("wchar_t*", u+'\u1234')[0] == u+'\u1234' + assert ffi.new("wchar_t*", 'x')[0] == 'x' + assert ffi.new("wchar_t*", '\u1234')[0] == '\u1234' if SIZE_OF_WCHAR > 2: - assert ffi.new("wchar_t*", u+'\U00012345')[0] == u+'\U00012345' + assert ffi.new("wchar_t*", '\U00012345')[0] == '\U00012345' else: - pytest.raises(TypeError, ffi.new, "wchar_t*", u+'\U00012345') - assert ffi.new("wchar_t*")[0] == u+'\x00' + pytest.raises(TypeError, ffi.new, "wchar_t*", '\U00012345') + assert ffi.new("wchar_t*")[0] == '\x00' assert int(ffi.cast("wchar_t", 300)) == 300 assert not bool(ffi.cast("wchar_t", 0)) assert bool(ffi.cast("wchar_t", 1)) @@ -408,40 +409,40 @@ def test_wchar_t(self): pytest.raises(TypeError, ffi.new, "wchar_t*", 32) pytest.raises(TypeError, ffi.new, "wchar_t*", "foo") # - p = ffi.new("wchar_t[]", [u+'a', u+'b', u+'\u1234']) + p = ffi.new("wchar_t[]", ['a', 'b', '\u1234']) assert len(p) == 3 - assert p[0] == u+'a' - assert p[1] == u+'b' and type(p[1]) is unicode - assert p[2] == u+'\u1234' - p[0] = u+'x' - assert p[0] == u+'x' and type(p[0]) is unicode - p[1] = u+'\u1357' - assert p[1] == u+'\u1357' - p = ffi.new("wchar_t[]", u+"abcd") + assert p[0] == 'a' + assert p[1] == 'b' and type(p[1]) is str + assert p[2] == '\u1234' + p[0] = 'x' + assert p[0] == 'x' and type(p[0]) is str + p[1] = '\u1357' + assert p[1] == '\u1357' + p = ffi.new("wchar_t[]", "abcd") assert len(p) == 5 - assert p[4] == u+'\x00' - p = ffi.new("wchar_t[]", u+"a\u1234b") + assert p[4] == '\x00' + p = ffi.new("wchar_t[]", "a\u1234b") assert len(p) == 4 - assert p[1] == u+'\u1234' + assert p[1] == '\u1234' # - p = ffi.new("wchar_t[]", u+'\U00023456') + p = ffi.new("wchar_t[]", '\U00023456') if SIZE_OF_WCHAR == 2: assert len(p) == 3 - assert p[0] == u+'\ud84d' - assert p[1] == u+'\udc56' - assert p[2] == u+'\x00' + assert p[0] == '\ud84d' + assert p[1] == '\udc56' + assert p[2] == '\x00' else: assert len(p) == 2 - assert p[0] == u+'\U00023456' - assert p[1] == u+'\x00' + assert p[0] == '\U00023456' + assert p[1] == '\x00' # - p = ffi.new("wchar_t[4]", u+"ab") + p = ffi.new("wchar_t[4]", "ab") assert len(p) == 4 - assert [p[i] for i in range(4)] == [u+'a', u+'b', u+'\x00', u+'\x00'] - p = ffi.new("wchar_t[2]", u+"ab") + assert [p[i] for i in range(4)] == ['a', 'b', '\x00', '\x00'] + p = ffi.new("wchar_t[2]", "ab") assert len(p) == 2 - assert [p[i] for i in range(2)] == [u+'a', u+'b'] - pytest.raises(IndexError, ffi.new, "wchar_t[2]", u+"abc") + assert [p[i] for i in range(2)] == ['a', 'b'] + pytest.raises(IndexError, ffi.new, "wchar_t[2]", "abc") def test_none_as_null_doesnt_work(self): p = ffi.new("int*[1]") @@ -622,14 +623,14 @@ def test_string_from_char_pointer(self): assert str(x) == repr(x) assert ffi.string(x) == b"x" assert ffi.string(ffi.new("char*", b"\x00")) == b"" - pytest.raises(TypeError, ffi.new, "char*", unicode("foo")) + pytest.raises(TypeError, ffi.new, "char*", "foo") def test_unicode_from_wchar_pointer(self): self.check_wchar_t(ffi) - x = ffi.new("wchar_t*", u+"x") - assert unicode(x) == unicode(repr(x)) - assert ffi.string(x) == u+"x" - assert ffi.string(ffi.new("wchar_t*", u+"\x00")) == u+"" + x = ffi.new("wchar_t*", "x") + assert str(x) == repr(x) + assert ffi.string(x) == "x" + assert ffi.string(ffi.new("wchar_t*", "\x00")) == "" def test_string_from_char_array(self): p = ffi.new("char[]", b"hello.") @@ -650,36 +651,35 @@ def test_string_from_char_array(self): def test_string_from_wchar_array(self): self.check_wchar_t(ffi) - assert ffi.string(ffi.cast("wchar_t", "x")) == u+"x" - assert ffi.string(ffi.cast("wchar_t", u+"x")) == u+"x" + assert ffi.string(ffi.cast("wchar_t", "x")) == "x" x = ffi.cast("wchar_t", "x") assert str(x) == repr(x) - assert ffi.string(x) == u+"x" + assert ffi.string(x) == "x" # - p = ffi.new("wchar_t[]", u+"hello.") - p[5] = u+'!' - assert ffi.string(p) == u+"hello!" - p[6] = u+'\u04d2' - assert ffi.string(p) == u+"hello!\u04d2" - p[3] = u+'\x00' - assert ffi.string(p) == u+"hel" - assert ffi.string(p, 123) == u+"hel" + p = ffi.new("wchar_t[]", "hello.") + p[5] = '!' + assert ffi.string(p) == "hello!" + p[6] = '\u04d2' + assert ffi.string(p) == "hello!\u04d2" + p[3] = '\x00' + assert ffi.string(p) == "hel" + assert ffi.string(p, 123) == "hel" with pytest.raises(IndexError): - p[7] = u+'X' + p[7] = 'X' # - a = ffi.new("wchar_t[]", u+"hello\x00world") + a = ffi.new("wchar_t[]", "hello\x00world") assert len(a) == 12 p = ffi.cast("wchar_t *", a) - assert ffi.string(p) == u+'hello' - assert ffi.string(p, 123) == u+'hello' - assert ffi.string(p, 5) == u+'hello' - assert ffi.string(p, 2) == u+'he' + assert ffi.string(p) == 'hello' + assert ffi.string(p, 123) == 'hello' + assert ffi.string(p, 5) == 'hello' + assert ffi.string(p, 2) == 'he' def test_fetch_const_char_p_field(self): # 'const' is ignored so far, in the declaration of 'struct string' t = ffi.new("const char[]", b"testing") s = ffi.new("struct string*", [t]) - assert type(s.name) not in (bytes, str, unicode) + assert type(s.name) not in (bytes, str) assert ffi.string(s.name) == b"testing" with pytest.raises(TypeError): s.name = None @@ -689,10 +689,10 @@ def test_fetch_const_char_p_field(self): def test_fetch_const_wchar_p_field(self): # 'const' is ignored so far self.check_wchar_t(ffi) - t = ffi.new("const wchar_t[]", u+"testing") + t = ffi.new("const wchar_t[]", "testing") s = ffi.new("struct ustring*", [t]) - assert type(s.name) not in (bytes, str, unicode) - assert ffi.string(s.name) == u+"testing" + assert type(s.name) not in (bytes, str) + assert ffi.string(s.name) == "testing" s.name = ffi.NULL assert s.name == ffi.NULL @@ -803,7 +803,7 @@ def test_char_cast(self): def test_wchar_cast(self): self.check_wchar_t(ffi) - p = ffi.cast("int", ffi.cast("wchar_t", u+'\u1234')) + p = ffi.cast("int", ffi.cast("wchar_t", '\u1234')) assert int(p) == 0x1234 p = ffi.cast("long long", ffi.cast("wchar_t", -1)) if SIZE_OF_WCHAR == 2: # 2 bytes, unsigned @@ -813,7 +813,7 @@ def test_wchar_cast(self): assert int(p) == -1 else: # in general, it can be either signed or not assert int(p) in [-1, 0xffffffff] # e.g. on arm, both cases occur - p = ffi.cast("int", u+'\u1234') + p = ffi.cast("int", '\u1234') assert int(p) == 0x1234 def test_cast_array_to_charp(self): @@ -1783,7 +1783,7 @@ def test_emit_c_code(self): def test_emit_c_code_to_file_obj(self): ffi = cffi.FFI() ffi.set_source("foobar", "??") - fileobj = NativeIO() + fileobj = io.StringIO() ffi.emit_c_code(fileobj) assert 'foobar' in fileobj.getvalue() @@ -1817,26 +1817,26 @@ def test_import_from_lib(self): def test_char16_t(self): x = ffi.new("char16_t[]", 5) assert len(x) == 5 and ffi.sizeof(x) == 10 - x[2] = u+'\u1324' - assert x[2] == u+'\u1324' - y = ffi.new("char16_t[]", u+'\u1234\u5678') + x[2] = '\u1324' + assert x[2] == '\u1324' + y = ffi.new("char16_t[]", '\u1234\u5678') assert len(y) == 3 - assert list(y) == [u+'\u1234', u+'\u5678', u+'\x00'] - assert ffi.string(y) == u+'\u1234\u5678' - z = ffi.new("char16_t[]", u+'\U00012345') + assert list(y) == ['\u1234', '\u5678', '\x00'] + assert ffi.string(y) == '\u1234\u5678' + z = ffi.new("char16_t[]", '\U00012345') assert len(z) == 3 - assert list(z) == [u+'\ud808', u+'\udf45', u+'\x00'] - assert ffi.string(z) == u+'\U00012345' + assert list(z) == ['\ud808', '\udf45', '\x00'] + assert ffi.string(z) == '\U00012345' def test_char32_t(self): x = ffi.new("char32_t[]", 5) assert len(x) == 5 and ffi.sizeof(x) == 20 - x[3] = u+'\U00013245' - assert x[3] == u+'\U00013245' - y = ffi.new("char32_t[]", u+'\u1234\u5678') + x[3] = '\U00013245' + assert x[3] == '\U00013245' + y = ffi.new("char32_t[]", '\u1234\u5678') assert len(y) == 3 - assert list(y) == [u+'\u1234', u+'\u5678', u+'\x00'] - z = ffi.new("char32_t[]", u+'\U00012345') + assert list(y) == ['\u1234', '\u5678', '\x00'] + z = ffi.new("char32_t[]", '\U00012345') assert len(z) == 2 - assert list(z) == [u+'\U00012345', u+'\x00'] # maybe a 2-unichars string - assert ffi.string(z) == u+'\U00012345' + assert list(z) == ['\U00012345', '\x00'] # maybe a 2-unichars string + assert ffi.string(z) == '\U00012345' diff --git a/testing/cffi1/test_pkgconfig.py b/testing/cffi1/test_pkgconfig.py index 3dfed136..30032fb0 100644 --- a/testing/cffi1/test_pkgconfig.py +++ b/testing/cffi1/test_pkgconfig.py @@ -84,13 +84,12 @@ def test_call(): result = pkgconfig.call("libfoo", "--cflags") assert result == "abc def\n" - if sys.version_info >= (3,): - mock_subprocess.RESULT = b"\xff\n", "", 0 - e = pytest.raises(PkgConfigError, pkgconfig.call, - "libfoo", "--cflags", encoding="utf-8") - assert str(e.value) == ( - "pkg-config --cflags libfoo returned bytes that cannot be " - "decoded with encoding 'utf-8':\nb'\\xff\\n'") + mock_subprocess.RESULT = b"\xff\n", "", 0 + e = pytest.raises(PkgConfigError, pkgconfig.call, + "libfoo", "--cflags", encoding="utf-8") + assert str(e.value) == ( + "pkg-config --cflags libfoo returned bytes that cannot be " + "decoded with encoding 'utf-8':\nb'\\xff\\n'") finally: pkgconfig.subprocess = saved diff --git a/testing/cffi1/test_re_python.py b/testing/cffi1/test_re_python.py index fbca325e..4f0a60f9 100644 --- a/testing/cffi1/test_re_python.py +++ b/testing/cffi1/test_re_python.py @@ -3,7 +3,7 @@ from cffi import FFI from cffi import recompiler, ffiplatform, VerificationMissing from testing.udir import udir -from testing.support import u, is_musl +from testing.support import is_musl def setup_module(mod): @@ -40,9 +40,9 @@ def setup_module(mod): # test with a non-ascii char ofn, oext = os.path.splitext(outputfilename) if sys.platform == "win32": - unicode_name = ofn + (u+'\u03be') + oext + unicode_name = ofn + ('\u03be') + oext else: - unicode_name = ofn + (u+'\xe9') + oext + unicode_name = ofn + ('\xe9') + oext try: unicode_name.encode(sys.getfilesystemencoding()) except UnicodeEncodeError: @@ -132,13 +132,8 @@ def test_dlclose(): from re_python_pysrc import ffi lib = ffi.dlopen(extmod) ffi.dlclose(lib) - if type(extmod) is not str: # unicode, on python 2 - str_extmod = extmod.encode('utf-8') - else: - str_extmod = extmod e = pytest.raises(ffi.error, getattr, lib, 'add42') - assert str(e.value) == ( - "library '%s' has been closed" % (str_extmod,)) + assert str(e.value) == "library '%s' has been closed" % (extmod,) ffi.dlclose(lib) # does not raise @pytest.mark.thread_unsafe( @@ -178,9 +173,8 @@ def test_include_1(): sub_ffi.set_source('re_python_pysrc', None) sub_ffi.emit_python_code(str(tmpdir / '_re_include_1.py')) # - if sys.version_info[:2] >= (3, 3): - import importlib - importlib.invalidate_caches() # issue 197 (but can't reproduce myself) + import importlib + importlib.invalidate_caches() # issue 197 (but can't reproduce myself) # from _re_include_1 import ffi assert ffi.integer_const('FOOBAR') == -42 @@ -312,9 +306,8 @@ def test_rec_structs_1(): ffi.set_source('test_rec_structs_1', None) ffi.emit_python_code(str(tmpdir / '_rec_structs_1.py')) # - if sys.version_info[:2] >= (3, 3): - import importlib - importlib.invalidate_caches() # issue 197, maybe + import importlib + importlib.invalidate_caches() # issue 197, maybe # from _rec_structs_1 import ffi # the following line used to raise TypeError @@ -329,9 +322,8 @@ def test_rec_structs_2(): ffi.set_source('test_rec_structs_2', None) ffi.emit_python_code(tmpdir / '_rec_structs_2.py') # - if sys.version_info[:2] >= (3, 3): - import importlib - importlib.invalidate_caches() # issue 197, maybe + import importlib + importlib.invalidate_caches() # issue 197, maybe # from _rec_structs_2 import ffi sz = ffi.sizeof("struct C") diff --git a/testing/cffi1/test_recompiler.py b/testing/cffi1/test_recompiler.py index d37335c1..c1dd13fe 100644 --- a/testing/cffi1/test_recompiler.py +++ b/testing/cffi1/test_recompiler.py @@ -4,7 +4,7 @@ from cffi import FFI, VerificationError, FFIError, CDefError from cffi import recompiler from testing.udir import udir -from testing.support import u, long +from testing.support import long from testing.support import FdWriteCapture, StdErrCapture, _verify pytestmark = [ @@ -343,7 +343,7 @@ def test_verify_struct(): # assert ffi.offsetof("struct foo_s", "a") == 0 assert ffi.offsetof("struct foo_s", "b") == 4 - assert ffi.offsetof(u+"struct foo_s", u+"b") == 4 + assert ffi.offsetof("struct foo_s", "b") == 4 # pytest.raises(TypeError, ffi.addressof, p) assert ffi.addressof(p[0]) == p @@ -747,25 +747,6 @@ def test_include_8(): "the ffi doing the include (workaround: don't use ffi.include() but" " duplicate the declarations of everything using struct foo_s)") -def test_unicode_libraries(): - try: - unicode - except NameError: - pytest.skip("for python 2.x") - # - import math - lib_m = "m" - if sys.platform == 'win32': - #there is a small chance this fails on Mingw via environ $CC - import distutils.ccompiler - if distutils.ccompiler.get_default_compiler() == 'msvc': - lib_m = 'msvcrt' - ffi = FFI() - ffi.cdef(unicode("float sin(double); double cos(double);")) - lib = verify(ffi, 'test_math_sin_unicode', unicode('#include '), - libraries=[unicode(lib_m)], ignore_warnings=True) - assert lib.cos(1.43) == math.cos(1.43) - def test_incomplete_struct_as_arg(): ffi = FFI() ffi.cdef("struct foo_s { int x; ...; }; int f(int, struct foo_s);") @@ -2394,10 +2375,10 @@ def test_char16_char32_type(no_cpp=False): char16_t foo_2bytes(char16_t a) { return (char16_t)(a + 42); } char32_t foo_4bytes(char32_t a) { return (char32_t)(a + 42); } """, no_cpp=no_cpp) - assert lib.foo_2bytes(u+'\u1234') == u+'\u125e' - assert lib.foo_4bytes(u+'\u1234') == u+'\u125e' - assert lib.foo_4bytes(u+'\U00012345') == u+'\U0001236f' - pytest.raises(TypeError, lib.foo_2bytes, u+'\U00012345') + assert lib.foo_2bytes('\u1234') == '\u125e' + assert lib.foo_4bytes('\u1234') == '\u125e' + assert lib.foo_4bytes('\U00012345') == '\U0001236f' + pytest.raises(TypeError, lib.foo_2bytes, '\U00012345') pytest.raises(TypeError, lib.foo_2bytes, 1234) pytest.raises(TypeError, lib.foo_4bytes, 1234) @@ -2407,12 +2388,8 @@ def test_char16_char32_plain_c(): def test_loader_spec(): ffi = FFI() lib = verify(ffi, "test_loader_spec", "") - if sys.version_info < (3,): - assert not hasattr(lib, '__loader__') - assert not hasattr(lib, '__spec__') - else: - assert lib.__loader__ is None - assert lib.__spec__ is None + assert lib.__loader__ is None + assert lib.__spec__ is None def test_realize_struct_error(): ffi = FFI() diff --git a/testing/cffi1/test_verify1.py b/testing/cffi1/test_verify1.py index e8ffabd3..761e5c07 100644 --- a/testing/cffi1/test_verify1.py +++ b/testing/cffi1/test_verify1.py @@ -372,11 +372,11 @@ def test_char_type(): def test_wchar_type(): ffi = FFI() if ffi.sizeof('wchar_t') == 2: - uniexample1 = u+'\u1234' - uniexample2 = u+'\u1235' + uniexample1 = '\u1234' + uniexample2 = '\u1235' else: - uniexample1 = u+'\U00012345' - uniexample2 = u+'\U00012346' + uniexample1 = '\U00012345' + uniexample2 = '\U00012346' # ffi.cdef("wchar_t foo(wchar_t);") lib = ffi.verify("wchar_t foo(wchar_t x) { return x+1; }") diff --git a/testing/embedding/withunicode.py b/testing/embedding/withunicode.py index be86a21d..3e39a286 100644 --- a/testing/embedding/withunicode.py +++ b/testing/embedding/withunicode.py @@ -1,9 +1,4 @@ import sys, cffi -if sys.version_info < (3,): - u_prefix = "u" -else: - u_prefix = "" - unichr = chr ffi = cffi.FFI() @@ -12,12 +7,12 @@ int add1(int, int); """) -ffi.embedding_init_code((""" +ffi.embedding_init_code(""" import sys, time - for c in %s'""" + unichr(0x00ff) + unichr(0x1234) + unichr(0xfedc) + """': + for c in '""" + chr(0x00ff) + chr(0x1234) + chr(0xfedc) + """': sys.stdout.write(str(ord(c)) + '\\n') sys.stdout.flush() -""") % u_prefix) +""") ffi.set_source("_withunicode_cffi", """ """) diff --git a/testing/support.py b/testing/support.py index 382102ab..32634c74 100644 --- a/testing/support.py +++ b/testing/support.py @@ -1,28 +1,10 @@ import sys, os from cffi._imp_emulation import load_dynamic -if sys.version_info < (3,): - __all__ = ['u', 'arraytostring', 'load_dynamic'] - - class U: - def __add__(self, other): - return eval('u'+repr(other).replace(r'\\u', r'\u') - .replace(r'\\U', r'\U')) - u = U() - long = long # for further "from testing.support import long" - assert u+'a\x00b' == eval(r"u'a\x00b'") - assert u+'a\u1234b' == eval(r"u'a\u1234b'") - assert u+'a\U00012345b' == eval(r"u'a\U00012345b'") - def arraytostring(a): - return a.tostring() - -else: - __all__ = ['u', 'unicode', 'long', 'arraytostring', 'load_dynamic'] - u = "" - unicode = str - long = int - def arraytostring(a): - return a.tobytes() +__all__ = ['long', 'arraytostring', 'load_dynamic'] +long = int +def arraytostring(a): + return a.tobytes() class StdErrCapture: