1 /*
2     tests/test_pytypes.cpp -- Python type casters
3 
4     Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
5 
6     All rights reserved. Use of this source code is governed by a
7     BSD-style license that can be found in the LICENSE file.
8 */
9 
10 #include <utility>
11 
12 #include "pybind11_tests.h"
13 
14 
TEST_SUBMODULE(pytypes,m)15 TEST_SUBMODULE(pytypes, m) {
16     // test_int
17     m.def("get_int", []{return py::int_(0);});
18     // test_iterator
19     m.def("get_iterator", []{return py::iterator();});
20     // test_iterable
21     m.def("get_iterable", []{return py::iterable();});
22     // test_list
23     m.def("get_list", []() {
24         py::list list;
25         list.append("value");
26         py::print("Entry at position 0:", list[0]);
27         list[0] = py::str("overwritten");
28         list.insert(0, "inserted-0");
29         list.insert(2, "inserted-2");
30         return list;
31     });
32     m.def("print_list", [](const py::list &list) {
33         int index = 0;
34         for (auto item : list)
35             py::print("list item {}: {}"_s.format(index++, item));
36     });
37     // test_none
38     m.def("get_none", []{return py::none();});
39     m.def("print_none", [](const py::none &none) { py::print("none: {}"_s.format(none)); });
40 
41     // test_set
42     m.def("get_set", []() {
43         py::set set;
44         set.add(py::str("key1"));
45         set.add("key2");
46         set.add(std::string("key3"));
47         return set;
48     });
49     m.def("print_set", [](const py::set &set) {
50         for (auto item : set)
51             py::print("key:", item);
52     });
53     m.def("set_contains",
54           [](const py::set &set, const py::object &key) { return set.contains(key); });
55     m.def("set_contains", [](const py::set &set, const char *key) { return set.contains(key); });
56 
57     // test_dict
58     m.def("get_dict", []() { return py::dict("key"_a="value"); });
59     m.def("print_dict", [](const py::dict &dict) {
60         for (auto item : dict)
61             py::print("key: {}, value={}"_s.format(item.first, item.second));
62     });
63     m.def("dict_keyword_constructor", []() {
64         auto d1 = py::dict("x"_a=1, "y"_a=2);
65         auto d2 = py::dict("z"_a=3, **d1);
66         return d2;
67     });
68     m.def("dict_contains",
69           [](const py::dict &dict, py::object val) { return dict.contains(val); });
70     m.def("dict_contains",
71           [](const py::dict &dict, const char *val) { return dict.contains(val); });
72 
73     // test_str
74     m.def("str_from_string", []() { return py::str(std::string("baz")); });
75     m.def("str_from_bytes", []() { return py::str(py::bytes("boo", 3)); });
76     m.def("str_from_object", [](const py::object& obj) { return py::str(obj); });
77     m.def("repr_from_object", [](const py::object& obj) { return py::repr(obj); });
78     m.def("str_from_handle", [](py::handle h) { return py::str(h); });
79     m.def("str_from_string_from_str", [](const py::str& obj) {
80         return py::str(static_cast<std::string>(obj));
81     });
82 
83     m.def("str_format", []() {
84         auto s1 = "{} + {} = {}"_s.format(1, 2, 3);
85         auto s2 = "{a} + {b} = {c}"_s.format("a"_a=1, "b"_a=2, "c"_a=3);
86         return py::make_tuple(s1, s2);
87     });
88 
89     // test_bytes
90     m.def("bytes_from_string", []() { return py::bytes(std::string("foo")); });
91     m.def("bytes_from_str", []() { return py::bytes(py::str("bar", 3)); });
92 
93     // test bytearray
94     m.def("bytearray_from_string", []() { return py::bytearray(std::string("foo")); });
95     m.def("bytearray_size", []() { return py::bytearray("foo").size(); });
96 
97     // test_capsule
98     m.def("return_capsule_with_destructor", []() {
99         py::print("creating capsule");
100         return py::capsule([]() {
101             py::print("destructing capsule");
102         });
103     });
104 
105     m.def("return_capsule_with_destructor_2", []() {
106         py::print("creating capsule");
107         return py::capsule((void *) 1234, [](void *ptr) {
108             py::print("destructing capsule: {}"_s.format((size_t) ptr));
109         });
110     });
111 
112     m.def("return_capsule_with_name_and_destructor", []() {
113         auto capsule = py::capsule((void *) 12345, "pointer type description", [](PyObject *ptr) {
114             if (ptr) {
115                 auto name = PyCapsule_GetName(ptr);
116                 py::print("destructing capsule ({}, '{}')"_s.format(
117                     (size_t) PyCapsule_GetPointer(ptr, name), name
118                 ));
119             }
120         });
121 
122         capsule.set_pointer((void *) 1234);
123 
124         // Using get_pointer<T>()
125         void* contents1 = static_cast<void*>(capsule);
126         void* contents2 = capsule.get_pointer();
127         void* contents3 = capsule.get_pointer<void>();
128 
129         auto result1 = reinterpret_cast<size_t>(contents1);
130         auto result2 = reinterpret_cast<size_t>(contents2);
131         auto result3 = reinterpret_cast<size_t>(contents3);
132 
133         py::print("created capsule ({}, '{}')"_s.format(result1 & result2 & result3, capsule.name()));
134         return capsule;
135     });
136 
137     // test_accessors
138     m.def("accessor_api", [](const py::object &o) {
139         auto d = py::dict();
140 
141         d["basic_attr"] = o.attr("basic_attr");
142 
143         auto l = py::list();
144         for (auto item : o.attr("begin_end")) {
145             l.append(item);
146         }
147         d["begin_end"] = l;
148 
149         d["operator[object]"] = o.attr("d")["operator[object]"_s];
150         d["operator[char *]"] = o.attr("d")["operator[char *]"];
151 
152         d["attr(object)"] = o.attr("sub").attr("attr_obj");
153         d["attr(char *)"] = o.attr("sub").attr("attr_char");
154         try {
155             o.attr("sub").attr("missing").ptr();
156         } catch (const py::error_already_set &) {
157             d["missing_attr_ptr"] = "raised"_s;
158         }
159         try {
160             o.attr("missing").attr("doesn't matter");
161         } catch (const py::error_already_set &) {
162             d["missing_attr_chain"] = "raised"_s;
163         }
164 
165         d["is_none"] = o.attr("basic_attr").is_none();
166 
167         d["operator()"] = o.attr("func")(1);
168         d["operator*"] = o.attr("func")(*o.attr("begin_end"));
169 
170         // Test implicit conversion
171         py::list implicit_list = o.attr("begin_end");
172         d["implicit_list"] = implicit_list;
173         py::dict implicit_dict = o.attr("__dict__");
174         d["implicit_dict"] = implicit_dict;
175 
176         return d;
177     });
178 
179     m.def("tuple_accessor", [](const py::tuple &existing_t) {
180         try {
181             existing_t[0] = 1;
182         } catch (const py::error_already_set &) {
183             // --> Python system error
184             // Only new tuples (refcount == 1) are mutable
185             auto new_t = py::tuple(3);
186             for (size_t i = 0; i < new_t.size(); ++i) {
187                 new_t[i] = i;
188             }
189             return new_t;
190         }
191         return py::tuple();
192     });
193 
194     m.def("accessor_assignment", []() {
195         auto l = py::list(1);
196         l[0] = 0;
197 
198         auto d = py::dict();
199         d["get"] = l[0];
200         auto var = l[0];
201         d["deferred_get"] = var;
202         l[0] = 1;
203         d["set"] = l[0];
204         var = 99; // this assignment should not overwrite l[0]
205         d["deferred_set"] = l[0];
206         d["var"] = var;
207 
208         return d;
209     });
210 
211     // test_constructors
212     m.def("default_constructors", []() {
213         return py::dict(
214             "bytes"_a=py::bytes(),
215             "bytearray"_a=py::bytearray(),
216             "str"_a=py::str(),
217             "bool"_a=py::bool_(),
218             "int"_a=py::int_(),
219             "float"_a=py::float_(),
220             "tuple"_a=py::tuple(),
221             "list"_a=py::list(),
222             "dict"_a=py::dict(),
223             "set"_a=py::set()
224         );
225     });
226 
227     m.def("converting_constructors", [](const py::dict &d) {
228         return py::dict(
229             "bytes"_a=py::bytes(d["bytes"]),
230             "bytearray"_a=py::bytearray(d["bytearray"]),
231             "str"_a=py::str(d["str"]),
232             "bool"_a=py::bool_(d["bool"]),
233             "int"_a=py::int_(d["int"]),
234             "float"_a=py::float_(d["float"]),
235             "tuple"_a=py::tuple(d["tuple"]),
236             "list"_a=py::list(d["list"]),
237             "dict"_a=py::dict(d["dict"]),
238             "set"_a=py::set(d["set"]),
239             "memoryview"_a=py::memoryview(d["memoryview"])
240         );
241     });
242 
243     m.def("cast_functions", [](const py::dict &d) {
244         // When converting between Python types, obj.cast<T>() should be the same as T(obj)
245         return py::dict(
246             "bytes"_a=d["bytes"].cast<py::bytes>(),
247             "bytearray"_a=d["bytearray"].cast<py::bytearray>(),
248             "str"_a=d["str"].cast<py::str>(),
249             "bool"_a=d["bool"].cast<py::bool_>(),
250             "int"_a=d["int"].cast<py::int_>(),
251             "float"_a=d["float"].cast<py::float_>(),
252             "tuple"_a=d["tuple"].cast<py::tuple>(),
253             "list"_a=d["list"].cast<py::list>(),
254             "dict"_a=d["dict"].cast<py::dict>(),
255             "set"_a=d["set"].cast<py::set>(),
256             "memoryview"_a=d["memoryview"].cast<py::memoryview>()
257         );
258     });
259 
260     m.def("convert_to_pybind11_str", [](const py::object &o) { return py::str(o); });
261 
262     m.def("nonconverting_constructor",
263           [](const std::string &type, py::object value, bool move) -> py::object {
264               if (type == "bytes") {
265                   return move ? py::bytes(std::move(value)) : py::bytes(value);
266               }
267               if (type == "none") {
268                   return move ? py::none(std::move(value)) : py::none(value);
269               }
270               if (type == "ellipsis") {
271                   return move ? py::ellipsis(std::move(value)) : py::ellipsis(value);
272               }
273               if (type == "type") {
274                   return move ? py::type(std::move(value)) : py::type(value);
275               }
276               throw std::runtime_error("Invalid type");
277           });
278 
279     m.def("get_implicit_casting", []() {
280         py::dict d;
281         d["char*_i1"] = "abc";
282         const char *c2 = "abc";
283         d["char*_i2"] = c2;
284         d["char*_e"] = py::cast(c2);
285         d["char*_p"] = py::str(c2);
286 
287         d["int_i1"] = 42;
288         int i = 42;
289         d["int_i2"] = i;
290         i++;
291         d["int_e"] = py::cast(i);
292         i++;
293         d["int_p"] = py::int_(i);
294 
295         d["str_i1"] = std::string("str");
296         std::string s2("str1");
297         d["str_i2"] = s2;
298         s2[3] = '2';
299         d["str_e"] = py::cast(s2);
300         s2[3] = '3';
301         d["str_p"] = py::str(s2);
302 
303         py::list l(2);
304         l[0] = 3;
305         l[1] = py::cast(6);
306         l.append(9);
307         l.append(py::cast(12));
308         l.append(py::int_(15));
309 
310         return py::dict(
311             "d"_a=d,
312             "l"_a=l
313         );
314     });
315 
316     // test_print
317     m.def("print_function", []() {
318         py::print("Hello, World!");
319         py::print(1, 2.0, "three", true, std::string("-- multiple args"));
320         auto args = py::make_tuple("and", "a", "custom", "separator");
321         py::print("*args", *args, "sep"_a="-");
322         py::print("no new line here", "end"_a=" -- ");
323         py::print("next print");
324 
325         auto py_stderr = py::module_::import("sys").attr("stderr");
326         py::print("this goes to stderr", "file"_a=py_stderr);
327 
328         py::print("flush", "flush"_a=true);
329 
330         py::print("{a} + {b} = {c}"_s.format("a"_a="py::print", "b"_a="str.format", "c"_a="this"));
331     });
332 
333     m.def("print_failure", []() { py::print(42, UnregisteredType()); });
334 
335     m.def("hash_function", [](py::object obj) { return py::hash(std::move(obj)); });
336 
337     m.def("test_number_protocol", [](const py::object &a, const py::object &b) {
338         py::list l;
339         l.append(a.equal(b));
340         l.append(a.not_equal(b));
341         l.append(a < b);
342         l.append(a <= b);
343         l.append(a > b);
344         l.append(a >= b);
345         l.append(a + b);
346         l.append(a - b);
347         l.append(a * b);
348         l.append(a / b);
349         l.append(a | b);
350         l.append(a & b);
351         l.append(a ^ b);
352         l.append(a >> b);
353         l.append(a << b);
354         return l;
355     });
356 
357     m.def("test_list_slicing", [](const py::list &a) { return a[py::slice(0, -1, 2)]; });
358 
359     // See #2361
360     m.def("issue2361_str_implicit_copy_none", []() {
361         py::str is_this_none = py::none();
362         return is_this_none;
363     });
364     m.def("issue2361_dict_implicit_copy_none", []() {
365         py::dict is_this_none = py::none();
366         return is_this_none;
367     });
368 
369     m.def("test_memoryview_object", [](const py::buffer &b) { return py::memoryview(b); });
370 
371     m.def("test_memoryview_buffer_info",
372           [](const py::buffer &b) { return py::memoryview(b.request()); });
373 
374     m.def("test_memoryview_from_buffer", [](bool is_unsigned) {
375         static const int16_t si16[] = { 3, 1, 4, 1, 5 };
376         static const uint16_t ui16[] = { 2, 7, 1, 8 };
377         if (is_unsigned)
378             return py::memoryview::from_buffer(
379                 ui16, { 4 }, { sizeof(uint16_t) });
380         return py::memoryview::from_buffer(si16, {5}, {sizeof(int16_t)});
381     });
382 
383     m.def("test_memoryview_from_buffer_nativeformat", []() {
384         static const char* format = "@i";
385         static const int32_t arr[] = { 4, 7, 5 };
386         return py::memoryview::from_buffer(
387             arr, sizeof(int32_t), format, { 3 }, { sizeof(int32_t) });
388     });
389 
390     m.def("test_memoryview_from_buffer_empty_shape", []() {
391         static const char* buf = "";
392         return py::memoryview::from_buffer(buf, 1, "B", { }, { });
393     });
394 
395     m.def("test_memoryview_from_buffer_invalid_strides", []() {
396         static const char* buf = "\x02\x03\x04";
397         return py::memoryview::from_buffer(buf, 1, "B", { 3 }, { });
398     });
399 
400     m.def("test_memoryview_from_buffer_nullptr", []() {
401         return py::memoryview::from_buffer(
402             static_cast<void*>(nullptr), 1, "B", { }, { });
403     });
404 
405 #if PY_MAJOR_VERSION >= 3
406     m.def("test_memoryview_from_memory", []() {
407         const char* buf = "\xff\xe1\xab\x37";
408         return py::memoryview::from_memory(
409             buf, static_cast<py::ssize_t>(strlen(buf)));
410     });
411 #endif
412 
413     // test_builtin_functions
414     m.def("get_len", [](py::handle h) { return py::len(h); });
415 
416 #ifdef PYBIND11_STR_LEGACY_PERMISSIVE
417     m.attr("PYBIND11_STR_LEGACY_PERMISSIVE") = true;
418 #endif
419 
420     m.def("isinstance_pybind11_bytes",
421           [](py::object o) { return py::isinstance<py::bytes>(std::move(o)); });
422     m.def("isinstance_pybind11_str",
423           [](py::object o) { return py::isinstance<py::str>(std::move(o)); });
424 
425     m.def("pass_to_pybind11_bytes", [](py::bytes b) { return py::len(std::move(b)); });
426     m.def("pass_to_pybind11_str", [](py::str s) { return py::len(std::move(s)); });
427     m.def("pass_to_std_string", [](const std::string &s) { return s.size(); });
428 
429     // test_weakref
430     m.def("weakref_from_handle",
431           [](py::handle h) { return py::weakref(h); });
432     m.def("weakref_from_handle_and_function",
433           [](py::handle h, py::function f) { return py::weakref(h, std::move(f)); });
434     m.def("weakref_from_object", [](const py::object &o) { return py::weakref(o); });
435     m.def("weakref_from_object_and_function",
436           [](py::object o, py::function f) { return py::weakref(std::move(o), std::move(f)); });
437 }
438