Debian Codegraph @

pypy/module/cpyext/test/test_bytesobject.py

raw symbols SCIP
1 # encoding: utf-8
2 import pytest
3 from rpython.rtyper.lltypesystem import rffi, lltype
4 from pypy.interpreter.error import OperationError
5 from pypy.module.cpyext.test.test_api import BaseApiTest, raises_w
6 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
7 from pypy.module.cpyext.bytesobject import (
8 new_empty_str, PyBytesObject, _PyBytes_Resize, PyBytes_Concat,
9 _PyBytes_Eq, PyBytes_ConcatAndDel, _PyBytes_Join)
10 from pypy.module.cpyext.api import (PyObjectP, PyObject, Py_ssize_tP,
11 Py_buffer, Py_bufferP, generic_cpy_call, PyVarObject)
12 from pypy.module.cpyext.pyobject import decref, from_ref, make_ref
13 from pypy.module.cpyext.buffer import PyObject_AsCharBuffer
14 from pypy.module.cpyext.unicodeobject import (PyUnicode_AsEncodedObject,
15 PyUnicode_InternFromString, PyUnicode_Format)
16
17
18 class AppTestBytesObject(AppTestCpythonExtensionBase):
19 def test_bytesobject(self):
20 module = self.import_extension('foo', [
21 ("get_hello1", "METH_NOARGS",
22 """
23 return PyBytes_FromStringAndSize(
24 "Hello world<should not be included>", 11);
25 """),
26 ("get_hello2", "METH_NOARGS",
27 """
28 return PyBytes_FromString("Hello world");
29 """),
30 ("test_Size", "METH_NOARGS",
31 """
32 PyObject* s = PyBytes_FromString("Hello world");
33 int result = PyBytes_Size(s);
34
35 Py_DECREF(s);
36 return PyLong_FromLong(result);
37 """),
38 ("test_Size_exception", "METH_NOARGS",
39 """
40 PyObject* f = PyFloat_FromDouble(1.0);
41 PyBytes_Size(f);
42
43 Py_DECREF(f);
44 return NULL;
45 """),
46 ("test_is_bytes", "METH_VARARGS",
47 """
48 return PyBool_FromLong(PyBytes_Check(PyTuple_GetItem(args, 0)));
49 """)], prologue='#include <stdlib.h>')
50 assert module.get_hello1() == b'Hello world'
51 assert module.get_hello2() == b'Hello world'
52 assert module.test_Size()
53 raises(TypeError, module.test_Size_exception)
54
55 assert module.test_is_bytes(b"")
56 assert not module.test_is_bytes(())
57
58 def test_bytes_buffer_init(self):
59 module = self.import_extension('foo', [
60 ("getbytes", "METH_NOARGS",
61 """
62 PyObject *s, *t;
63 char* c;
64
65 s = PyBytes_FromStringAndSize(NULL, 4);
66 if (s == NULL)
67 return NULL;
68 t = PyBytes_FromStringAndSize(NULL, 3);
69 if (t == NULL)
70 return NULL;
71 Py_DECREF(t);
72 c = PyBytes_AS_STRING(s);
73 c[0] = 'a';
74 c[1] = 'b';
75 c[2] = 0;
76 c[3] = 'c';
77 return s;
78 """),
79 ])
80 s = module.getbytes()
81 assert len(s) == 4
82 assert s == b'ab\x00c'
83
84 def test_bytes_tp_alloc(self):
85 module = self.import_extension('foo', [
86 ("tpalloc", "METH_NOARGS",
87 """
88 PyObject *base;
89 PyTypeObject * type;
90 PyObject *obj;
91 base = PyBytes_FromString("test");
92 if (PyBytes_GET_SIZE(base) != 4)
93 return PyLong_FromLong(-PyBytes_GET_SIZE(base));
94 type = base->ob_type;
95 if (type->tp_itemsize != 1)
96 return PyLong_FromLong(type->tp_itemsize);
97 obj = type->tp_alloc(type, 10);
98 if (PyBytes_GET_SIZE(obj) != 10)
99 return PyLong_FromLong(PyBytes_GET_SIZE(obj));
100 /* cannot work, there is only RO access
101 memcpy(PyBytes_AS_STRING(obj), "works", 6); */
102 Py_INCREF(obj);
103 return obj;
104 """),
105 ('alloc_rw', "METH_NOARGS",
106 '''
107 PyObject *obj = (PyObject*)_PyObject_NewVar(&PyBytes_Type, 10);
108 memcpy(PyBytes_AS_STRING(obj), "works", 6);
109 return (PyObject*)obj;
110 '''),
111 ])
112 s = module.alloc_rw()
113 assert s[:6] == b'works\0' # s[6:10] contains random garbage
114 s = module.tpalloc()
115 assert s == b'\x00' * 10
116
117 def test_AsString(self):
118 module = self.import_extension('foo', [
119 ("getbytes", "METH_NOARGS",
120 """
121 char *c;
122 PyObject* s2, *s1 = PyBytes_FromStringAndSize("test", 4);
123 c = PyBytes_AsString(s1);
124 s2 = PyBytes_FromStringAndSize(c, 4);
125 Py_DECREF(s1);
126 return s2;
127 """),
128 ])
129 s = module.getbytes()
130 assert s == b'test'
131
132 def test_manipulations(self):
133 module = self.import_extension('foo', [
134 ("bytes_as_string", "METH_VARARGS",
135 '''
136 return PyBytes_FromStringAndSize(PyBytes_AsString(
137 PyTuple_GetItem(args, 0)), 4);
138 '''
139 ),
140 ("concat", "METH_VARARGS",
141 """
142 PyObject ** v;
143 PyObject * left = PyTuple_GetItem(args, 0);
144 Py_INCREF(left); /* the reference will be stolen! */
145 v = &left;
146 PyBytes_Concat(v, PyTuple_GetItem(args, 1));
147 return *v;
148 """)])
149 assert module.bytes_as_string(b"huheduwe") == b"huhe"
150 ret = module.concat(b'abc', b'def')
151 assert ret == b'abcdef'
152
153 def test_py_bytes_as_string_None(self):
154 module = self.import_extension('foo', [
155 ("string_None", "METH_VARARGS",
156 '''
157 if (PyBytes_AsString(Py_None)) {
158 Py_RETURN_NONE;
159 }
160 return NULL;
161 '''
162 )])
163 raises(TypeError, module.string_None)
164
165 def test_AsStringAndSize(self):
166 module = self.import_extension('foo', [
167 ("getbytes", "METH_NOARGS",
168 """
169 PyObject* s1 = PyBytes_FromStringAndSize("te\\0st", 5);
170 char *buf;
171 Py_ssize_t len;
172 if (PyBytes_AsStringAndSize(s1, &buf, &len) < 0)
173 return NULL;
174 if (len != 5) {
175 PyErr_SetString(PyExc_AssertionError, "Bad Length");
176 return NULL;
177 }
178 if (PyBytes_AsStringAndSize(s1, &buf, NULL) >= 0) {
179 PyErr_SetString(PyExc_AssertionError, "Should Have failed");
180 return NULL;
181 }
182 PyErr_Clear();
183 Py_DECREF(s1);
184 Py_INCREF(Py_None);
185 return Py_None;
186 """),
187 ("c_only", "METH_NOARGS",
188 """
189 int ret;
190 char * buf2;
191 PyObject * obj = PyBytes_FromStringAndSize(NULL, 1024);
192 if (!obj)
193 return NULL;
194 buf2 = PyBytes_AsString(obj);
195 if (!buf2)
196 return NULL;
197 /* buf should not have been forced, issue #2395 */
198 ret = _PyBytes_Resize(&obj, 512);
199 if (ret < 0)
200 return NULL;
201 Py_DECREF(obj);
202 Py_INCREF(Py_None);
203 return Py_None;
204 """),
205 ])
206 module.getbytes()
207 module.c_only()
208
209 def test_FromFormat(self):
210 module = self.import_extension('foo', [
211 ("fmt", "METH_VARARGS",
212 """
213 PyObject* fmt = PyTuple_GetItem(args, 0);
214 int n = PyLong_AsLong(PyTuple_GetItem(args, 1));
215 PyObject* result = PyBytes_FromFormat(PyBytes_AsString(fmt), n);
216 return result;
217 """),
218 ])
219 print(module.fmt(b'd:%d', 10))
220 assert module.fmt(b'd:%d', 10) == b'd:10'
221
222 def test_suboffsets(self):
223 module = self.import_extension('foo', [
224 ("check_suboffsets", "METH_O",
225 """
226 Py_buffer view;
227 PyObject_GetBuffer(args, &view, 0);
228 return PyLong_FromLong(view.suboffsets == NULL);
229 """)])
230 assert module.check_suboffsets(b'1234') == 1
231
232 class TestBytes(BaseApiTest):
233 def test_eq(self, space):
234 assert 1 == _PyBytes_Eq(space, space.newbytes("hello"), space.newbytes("hello"))
235 assert 0 == _PyBytes_Eq(space, space.newbytes("hello"), space.newbytes("world"))
236
237 def test_join(self, space):
238 w_sep = space.newbytes('<sep>')
239 w_seq = space.newtuple([space.newbytes('a'), space.newbytes('b')])
240 w_joined = _PyBytes_Join(space, w_sep, w_seq)
241 assert space.bytes_w(w_joined) == 'a<sep>b'
242
243 def test_FromObject(self, space, api):
244 w_obj = space.newbytes("test")
245 assert space.eq_w(w_obj, api.PyBytes_FromObject(w_obj))
246 w_obj = space.call_function(space.w_bytearray, w_obj)
247 assert space.eq_w(w_obj, api.PyBytes_FromObject(w_obj))
248 w_obj = space.wrap(u"test")
249 with raises_w(space, TypeError):
250 api.PyBytes_FromObject(w_obj)
251
252 def test_bytes_resize(self, space):
253 py_str = new_empty_str(space, 10)
254 ar = lltype.malloc(PyObjectP.TO, 1, flavor='raw')
255 py_str.c_ob_sval[0] = 'a'
256 py_str.c_ob_sval[1] = 'b'
257 py_str.c_ob_sval[2] = 'c'
258 ar[0] = rffi.cast(PyObject, py_str)
259 _PyBytes_Resize(space, ar, 3)
260 py_str = rffi.cast(PyBytesObject, ar[0])
261 py_obj = rffi.cast(PyVarObject, ar[0])
262 assert py_obj.c_ob_size == 3
263 assert py_str.c_ob_sval[1] == 'b'
264 assert py_str.c_ob_sval[3] == '\x00'
265 # the same for growing
266 ar[0] = rffi.cast(PyObject, py_str)
267 _PyBytes_Resize(space, ar, 10)
268 py_str = rffi.cast(PyBytesObject, ar[0])
269 py_obj = rffi.cast(PyVarObject, ar[0])
270 assert py_obj.c_ob_size == 10
271 assert py_str.c_ob_sval[1] == 'b'
272 assert py_str.c_ob_sval[10] == '\x00'
273 decref(space, ar[0])
274 lltype.free(ar, flavor='raw')
275
276 def test_string_buffer(self, space):
277 py_str = new_empty_str(space, 10)
278 py_obj = rffi.cast(PyObject, py_str)
279 c_buf = py_obj.c_ob_type.c_tp_as_buffer
280 assert c_buf
281 size = rffi.sizeof(Py_buffer)
282 ref = lltype.malloc(rffi.VOIDP.TO, size, flavor='raw', zero=True)
283 ref = rffi.cast(Py_bufferP, ref)
284 assert generic_cpy_call(space, c_buf.c_bf_getbuffer,
285 py_obj, ref, rffi.cast(rffi.INT_real, 0)) == 0
286 lltype.free(ref, flavor='raw')
287 decref(space, py_obj)
288
289 def test_Concat(self, space):
290 ref = make_ref(space, space.newbytes('abc'))
291 ptr = lltype.malloc(PyObjectP.TO, 1, flavor='raw')
292 ptr[0] = ref
293 prev_refcnt = ref.c_ob_refcnt
294 PyBytes_Concat(space, ptr, space.newbytes('def'))
295 assert ref.c_ob_refcnt == prev_refcnt - 1
296 assert space.bytes_w(from_ref(space, ptr[0])) == b'abcdef'
297 with pytest.raises(OperationError):
298 PyBytes_Concat(space, ptr, space.w_None)
299 assert not ptr[0]
300 ptr[0] = lltype.nullptr(PyObject.TO)
301 PyBytes_Concat(space, ptr, space.wrap('def')) # should not crash
302 lltype.free(ptr, flavor='raw')
303
304 def test_ConcatAndDel2(self, space):
305 ref1 = make_ref(space, space.newbytes('abc'))
306 ref2 = make_ref(space, space.newbytes('def'))
307 ptr = lltype.malloc(PyObjectP.TO, 1, flavor='raw')
308 ptr[0] = ref1
309 prev_refcnf = ref2.c_ob_refcnt
310 PyBytes_ConcatAndDel(space, ptr, ref2)
311 assert space.bytes_w(from_ref(space, ptr[0])) == b'abcdef'
312 assert ref2.c_ob_refcnt == prev_refcnf - 1
313 decref(space, ptr[0])
314 ptr[0] = lltype.nullptr(PyObject.TO)
315 ref2 = make_ref(space, space.wrap('foo'))
316 prev_refcnf = ref2.c_ob_refcnt
317 PyBytes_ConcatAndDel(space, ptr, ref2) # should not crash
318 assert ref2.c_ob_refcnt == prev_refcnf - 1
319 lltype.free(ptr, flavor='raw')
320
321 def test_format(self, space):
322 # XXX move to test_unicodeobject
323 assert "1 2" == space.unwrap(
324 PyUnicode_Format(space, space.wrap('%s %d'), space.wrap((1, 2))))
325
326 def test_asbuffer(self, space):
327 bufp = lltype.malloc(rffi.CCHARPP.TO, 1, flavor='raw')
328 lenp = lltype.malloc(Py_ssize_tP.TO, 1, flavor='raw')
329
330 w_bytes = space.newbytes("text")
331 ref = make_ref(space, w_bytes)
332 prev_refcnt = ref.c_ob_refcnt
333 assert PyObject_AsCharBuffer(space, ref, bufp, lenp) == 0
334 assert ref.c_ob_refcnt == prev_refcnt
335 assert lenp[0] == 4
336 assert rffi.charp2str(bufp[0]) == 'text'
337 lltype.free(bufp, flavor='raw')
338 lltype.free(lenp, flavor='raw')
339 decref(space, ref)
340
341 def test_intern(self, space):
342 # XXX move to test_unicodeobject
343 buf = rffi.str2charp("test")
344 w_s1 = PyUnicode_InternFromString(space, buf)
345 w_s2 = PyUnicode_InternFromString(space, buf)
346 rffi.free_charp(buf)
347 assert w_s1 is w_s2
348
349 def test_AsEncodedObject(self, space):
350 # XXX move to test_unicodeobject
351 ptr = space.wrap('abc')
352
353 errors = rffi.str2charp("strict")
354
355 encoding = rffi.str2charp("ascii")
356 res = PyUnicode_AsEncodedObject(space, ptr, encoding, errors)
357 assert space.unwrap(res) == "abc"
358
359 res = PyUnicode_AsEncodedObject(space,
360 ptr, encoding, lltype.nullptr(rffi.CCHARP.TO))
361 assert space.unwrap(res) == "abc"
362 rffi.free_charp(encoding)
363
364 encoding = rffi.str2charp("unknown_encoding")
365 with raises_w(space, LookupError):
366 PyUnicode_AsEncodedObject(space, ptr, encoding, errors)
367 rffi.free_charp(encoding)
368
369 rffi.free_charp(errors)
370
371 NULL = lltype.nullptr(rffi.CCHARP.TO)
372 res = PyUnicode_AsEncodedObject(space, ptr, NULL, NULL)
373 assert space.unwrap(res) == "abc"
374 with raises_w(space, TypeError):
375 PyUnicode_AsEncodedObject(space, space.wrap(2), NULL, NULL)
376
377 def test_eq(self, space):
378 assert 1 == _PyBytes_Eq(
379 space, space.wrap("hello"), space.wrap("hello"))
380 assert 0 == _PyBytes_Eq(
381 space, space.wrap("hello"), space.wrap("world"))
382
383 def test_join(self, space):
384 w_sep = space.wrap('<sep>')
385 w_seq = space.wrap(['a', 'b'])
386 w_joined = _PyBytes_Join(space, w_sep, w_seq)
387 assert space.unwrap(w_joined) == 'a<sep>b'