File: test_getargs.py

package info (click to toggle)
pypy3 7.0.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 111,848 kB
  • sloc: python: 1,291,746; ansic: 74,281; asm: 5,187; cpp: 3,017; sh: 2,533; makefile: 544; xml: 243; lisp: 45; csh: 21; awk: 4
file content (215 lines) | stat: -rw-r--r-- 7,018 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215

from pypy.module.cpyext.test.test_api import BaseApiTest
from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase

class AppTestGetargs(AppTestCpythonExtensionBase):
    def w_import_parser(self, implementation, argstyle='METH_VARARGS',
                        PY_SSIZE_T_CLEAN=False):
        mod = self.import_extension(
            'modname', [('funcname', argstyle, implementation)],
            PY_SSIZE_T_CLEAN=PY_SSIZE_T_CLEAN)
        return mod.funcname

    def test_pyarg_parse_int(self):
        """
        The `i` format specifier can be used to parse an integer.
        """
        oneargint = self.import_parser(
            '''
            int l;
            if (!PyArg_ParseTuple(args, "i", &l)) {
                return NULL;
            }
            return PyLong_FromLong(l);
            ''')
        assert oneargint(1) == 1
        raises(TypeError, oneargint, None)
        raises(TypeError, oneargint)


    def test_pyarg_parse_fromname(self):
        """
        The name of the function parsing the arguments can be given after a `:`
        in the argument format string.
        """
        oneargandform = self.import_parser(
            '''
            int l;
            if (!PyArg_ParseTuple(args, "i:oneargandstuff", &l)) {
                return NULL;
            }
            return PyLong_FromLong(l);
            ''')
        assert oneargandform(1) == 1


    def test_pyarg_parse_object(self):
        """
        The `O` format specifier can be used to parse an arbitrary object.
        """
        oneargobject = self.import_parser(
            '''
            PyObject *obj;
            if (!PyArg_ParseTuple(args, "O", &obj)) {
                return NULL;
            }
            Py_INCREF(obj);
            return obj;
            ''')
        sentinel = object()
        res = oneargobject(sentinel)
        assert res is sentinel

    def test_pyarg_parse_restricted_object_type(self):
        """
        The `O!` format specifier can be used to parse an object of a particular
        type.
        """
        oneargobjectandlisttype = self.import_parser(
            '''
            PyObject *obj;
            if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &obj)) {
                return NULL;
            }
            Py_INCREF(obj);
            return obj;
            ''')
        sentinel = object()
        raises(TypeError, "oneargobjectandlisttype(sentinel)")
        sentinel = []
        res = oneargobjectandlisttype(sentinel)
        assert res is sentinel


    def test_pyarg_parse_one_optional(self):
        """
        An object corresponding to a format specifier after a `|` in the
        argument format string is optional and may be passed or not.
        """
        twoopt = self.import_parser(
            '''
            PyObject *a;
            PyObject *b = NULL;
            if (!PyArg_ParseTuple(args, "O|O", &a, &b)) {
                return NULL;
            }
            if (b)
                Py_INCREF(b);
            else
                b = PyLong_FromLong(42);
            /* return an owned reference */
            return b;
            ''')
        assert twoopt(1) == 42
        assert twoopt(1, 2) == 2
        raises(TypeError, twoopt, 1, 2, 3)


    def test_pyarg_parse_string_py_buffer(self):
        """
        The `s*` format specifier can be used to parse a str into a Py_buffer
        structure containing a pointer to the string data and the length of the
        string data.
        """
        pybuffer = self.import_parser(
            '''
            Py_buffer buf;
            PyObject *result;
            if (!PyArg_ParseTuple(args, "s*", &buf)) {
                return NULL;
            }
            result = PyBytes_FromStringAndSize(buf.buf, buf.len);
            PyBuffer_Release(&buf);
            return result;
            ''')
        assert b'foo\0bar\0baz' == pybuffer(b'foo\0bar\0baz')
        #return  # XXX?
        assert b'foo\0bar\0baz' == pybuffer(bytearray(b'foo\0bar\0baz'))


    def test_pyarg_parse_string_fails(self):
        """
        Test the failing case of PyArg_ParseTuple(): it must not keep
        a reference on the PyObject passed in.
        """
        pybuffer = self.import_parser(
            '''
            Py_buffer buf1, buf2, buf3;
            if (!PyArg_ParseTuple(args, "s*s*s*", &buf1, &buf2, &buf3)) {
                return NULL;
            }
            Py_FatalError("should not get there");
            return NULL;
            ''')
        freed = []
        class freestring(bytes):
            def __del__(self):
                freed.append('x')
        raises(TypeError, pybuffer,
               freestring(b"string"), freestring(b"other string"), 42)
        self.debug_collect()    # gc.collect() is not enough in this test:
                                # we need to check and free the PyObject
                                # linked to the freestring object as well
        assert freed == ['x', 'x']


    def test_pyarg_parse_charbuf_and_length(self):
        """
        The `s#` format specifier can be used to parse a read-only 8-bit
        character buffer into a char* and int giving its length in bytes.
        """
        charbuf = self.import_parser(
            '''
            char *buf;
            int len;
            if (!PyArg_ParseTuple(args, "s#", &buf, &len)) {
                return NULL;
            }
            return PyBytes_FromStringAndSize(buf, len);
            ''')
        raises(TypeError, "charbuf(10)")
        assert b'foo\0bar\0baz' == charbuf(b'foo\0bar\0baz')

    def test_pyarg_parse_without_py_ssize_t(self):
        import sys
        charbuf = self.import_parser(
            '''
            char *buf;
            Py_ssize_t y = -1;
            if (!PyArg_ParseTuple(args, "s#", &buf, &y)) {
                return NULL;
            }
            return PyLong_FromSsize_t(y);
            ''')
        if sys.maxsize < 2**32:
            expected = 5
        elif sys.byteorder == 'little':
            expected = -0xfffffffb
        else:
            expected = 0x5ffffffff
        assert charbuf(b'12345') == expected

    def test_pyarg_parse_with_py_ssize_t(self):
        charbuf = self.import_parser(
            '''
            char *buf;
            Py_ssize_t y = -1;
            if (!PyArg_ParseTuple(args, "s#", &buf, &y)) {
                return NULL;
            }
            return PyLong_FromSsize_t(y);
            ''', PY_SSIZE_T_CLEAN=True)
        assert charbuf(b'12345') == 5

    def test_pyarg_parse_with_py_ssize_t_bytes(self):
        charbuf = self.import_parser(
            '''
            char *buf;
            Py_ssize_t len = -1;
            if (!PyArg_ParseTuple(args, "y#", &buf, &len)) {
                return NULL;
            }
            return PyBytes_FromStringAndSize(buf, len);
            ''', PY_SSIZE_T_CLEAN=True)
        assert type(charbuf(b'12345')) is bytes
        assert charbuf(b'12345') == b'12345'