File: test_pyfunction.rs

package info (click to toggle)
rust-pyo3 0.22.6-3
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 3,420 kB
  • sloc: makefile: 58; python: 39; sh: 1
file content (614 lines) | stat: -rw-r--r-- 17,421 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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
#![cfg(feature = "macros")]

use std::collections::HashMap;

#[cfg(not(Py_LIMITED_API))]
use pyo3::buffer::PyBuffer;
use pyo3::ffi::c_str;
use pyo3::prelude::*;
#[cfg(not(Py_LIMITED_API))]
use pyo3::types::PyDateTime;
#[cfg(not(any(Py_LIMITED_API, PyPy)))]
use pyo3::types::PyFunction;
use pyo3::types::{self, PyCFunction};

#[path = "../src/tests/common.rs"]
mod common;

#[pyfunction(name = "struct")]
fn struct_function() {}

#[test]
fn test_rust_keyword_name() {
    Python::with_gil(|py| {
        let f = wrap_pyfunction_bound!(struct_function)(py).unwrap();

        py_assert!(py, f, "f.__name__ == 'struct'");
    });
}

#[pyfunction(signature = (arg = true))]
fn optional_bool(arg: Option<bool>) -> String {
    format!("{:?}", arg)
}

#[test]
fn test_optional_bool() {
    // Regression test for issue #932
    Python::with_gil(|py| {
        let f = wrap_pyfunction_bound!(optional_bool)(py).unwrap();

        py_assert!(py, f, "f() == 'Some(true)'");
        py_assert!(py, f, "f(True) == 'Some(true)'");
        py_assert!(py, f, "f(False) == 'Some(false)'");
        py_assert!(py, f, "f(None) == 'None'");
    });
}

#[cfg(not(Py_LIMITED_API))]
#[pyfunction]
fn buffer_inplace_add(py: Python<'_>, x: PyBuffer<i32>, y: PyBuffer<i32>) {
    let x = x.as_mut_slice(py).unwrap();
    let y = y.as_slice(py).unwrap();
    for (xi, yi) in x.iter().zip(y) {
        let xi_plus_yi = xi.get() + yi.get();
        xi.set(xi_plus_yi);
    }
}

#[cfg(not(Py_LIMITED_API))]
#[test]
fn test_buffer_add() {
    Python::with_gil(|py| {
        let f = wrap_pyfunction_bound!(buffer_inplace_add)(py).unwrap();

        py_expect_exception!(
            py,
            f,
            r#"
import array
a = array.array("i", [0, 1, 2, 3])
b = array.array("I", [0, 1, 2, 3])
f(a, b)
"#,
            PyBufferError
        );

        pyo3::py_run!(
            py,
            f,
            r#"
import array
a = array.array("i", [0, 1, 2, 3])
b = array.array("i", [2, 3, 4, 5])
f(a, b)
assert a, array.array("i", [2, 4, 6, 8])
"#
        );
    });
}

#[cfg(not(any(Py_LIMITED_API, PyPy)))]
#[pyfunction]
fn function_with_pyfunction_arg<'py>(fun: &Bound<'py, PyFunction>) -> PyResult<Bound<'py, PyAny>> {
    fun.call((), None)
}

#[pyfunction]
fn function_with_pycfunction_arg<'py>(
    fun: &Bound<'py, PyCFunction>,
) -> PyResult<Bound<'py, PyAny>> {
    fun.call((), None)
}

#[test]
fn test_functions_with_function_args() {
    Python::with_gil(|py| {
        let py_cfunc_arg = wrap_pyfunction_bound!(function_with_pycfunction_arg)(py).unwrap();
        let bool_to_string = wrap_pyfunction_bound!(optional_bool)(py).unwrap();

        pyo3::py_run!(
            py,
            py_cfunc_arg
            bool_to_string,
            r#"
        assert py_cfunc_arg(bool_to_string) == "Some(true)"
        "#
        );

        #[cfg(not(any(Py_LIMITED_API, PyPy)))]
        {
            let py_func_arg = wrap_pyfunction_bound!(function_with_pyfunction_arg)(py).unwrap();

            pyo3::py_run!(
                py,
                py_func_arg,
                r#"
            def foo(): return "bar"
            assert py_func_arg(foo) == "bar"
            "#
            );
        }
    });
}

#[cfg(not(Py_LIMITED_API))]
fn datetime_to_timestamp(dt: &Bound<'_, PyAny>) -> PyResult<i64> {
    let dt = dt.downcast::<PyDateTime>()?;
    let ts: f64 = dt.call_method0("timestamp")?.extract()?;

    Ok(ts as i64)
}

#[cfg(not(Py_LIMITED_API))]
#[pyfunction]
fn function_with_custom_conversion(
    #[pyo3(from_py_with = "datetime_to_timestamp")] timestamp: i64,
) -> i64 {
    timestamp
}

#[cfg(not(Py_LIMITED_API))]
#[test]
fn test_function_with_custom_conversion() {
    Python::with_gil(|py| {
        let custom_conv_func = wrap_pyfunction_bound!(function_with_custom_conversion)(py).unwrap();

        pyo3::py_run!(
            py,
            custom_conv_func,
            r#"
        import datetime

        dt = datetime.datetime.fromtimestamp(1612040400)
        assert custom_conv_func(dt) == 1612040400
        "#
        )
    });
}

#[cfg(not(Py_LIMITED_API))]
#[test]
fn test_function_with_custom_conversion_error() {
    Python::with_gil(|py| {
        let custom_conv_func = wrap_pyfunction_bound!(function_with_custom_conversion)(py).unwrap();

        py_expect_exception!(
            py,
            custom_conv_func,
            "custom_conv_func(['a'])",
            PyTypeError,
            "argument 'timestamp': 'list' object cannot be converted to 'PyDateTime'"
        );
    });
}

#[test]
fn test_from_py_with_defaults() {
    fn optional_int(x: &Bound<'_, PyAny>) -> PyResult<Option<i32>> {
        if x.is_none() {
            Ok(None)
        } else {
            Some(x.extract()).transpose()
        }
    }

    // issue 2280 combination of from_py_with and Option<T> did not compile
    #[pyfunction]
    #[pyo3(signature = (int=None))]
    fn from_py_with_option(#[pyo3(from_py_with = "optional_int")] int: Option<i32>) -> i32 {
        int.unwrap_or(0)
    }

    #[pyfunction(signature = (len=0))]
    fn from_py_with_default(
        #[pyo3(from_py_with = "<Bound<'_, _> as PyAnyMethods>::len")] len: usize,
    ) -> usize {
        len
    }

    Python::with_gil(|py| {
        let f = wrap_pyfunction_bound!(from_py_with_option)(py).unwrap();

        assert_eq!(f.call0().unwrap().extract::<i32>().unwrap(), 0);
        assert_eq!(f.call1((123,)).unwrap().extract::<i32>().unwrap(), 123);
        assert_eq!(f.call1((999,)).unwrap().extract::<i32>().unwrap(), 999);

        let f2 = wrap_pyfunction_bound!(from_py_with_default)(py).unwrap();

        assert_eq!(f2.call0().unwrap().extract::<usize>().unwrap(), 0);
        assert_eq!(f2.call1(("123",)).unwrap().extract::<usize>().unwrap(), 3);
        assert_eq!(f2.call1(("1234",)).unwrap().extract::<usize>().unwrap(), 4);
    });
}

#[pyclass]
#[derive(Debug, FromPyObject)]
struct ValueClass {
    #[pyo3(get)]
    value: usize,
}

#[pyfunction]
#[pyo3(signature=(str_arg, int_arg, tuple_arg, option_arg = None, struct_arg = None))]
fn conversion_error(
    str_arg: &str,
    int_arg: i64,
    tuple_arg: (String, f64),
    option_arg: Option<i64>,
    struct_arg: Option<ValueClass>,
) {
    println!(
        "{:?} {:?} {:?} {:?} {:?}",
        str_arg, int_arg, tuple_arg, option_arg, struct_arg
    );
}

#[test]
fn test_conversion_error() {
    Python::with_gil(|py| {
        let conversion_error = wrap_pyfunction_bound!(conversion_error)(py).unwrap();
        py_expect_exception!(
            py,
            conversion_error,
            "conversion_error(None, None, None, None, None)",
            PyTypeError,
            "argument 'str_arg': 'NoneType' object cannot be converted to 'PyString'"
        );
        py_expect_exception!(
            py,
            conversion_error,
            "conversion_error(100, None, None, None, None)",
            PyTypeError,
            "argument 'str_arg': 'int' object cannot be converted to 'PyString'"
        );
        py_expect_exception!(
            py,
            conversion_error,
            "conversion_error('string1', 'string2', None, None, None)",
            PyTypeError,
            "argument 'int_arg': 'str' object cannot be interpreted as an integer"
        );
        py_expect_exception!(
            py,
            conversion_error,
            "conversion_error('string1', -100, 'string2', None, None)",
            PyTypeError,
            "argument 'tuple_arg': 'str' object cannot be converted to 'PyTuple'"
        );
        py_expect_exception!(
            py,
            conversion_error,
            "conversion_error('string1', -100, ('string2', 10.), 'string3', None)",
            PyTypeError,
            "argument 'option_arg': 'str' object cannot be interpreted as an integer"
        );
        let exception = py_expect_exception!(
            py,
            conversion_error,
            "
class ValueClass:
    def __init__(self, value):
        self.value = value
conversion_error('string1', -100, ('string2', 10.), None, ValueClass(\"no_expected_type\"))",
            PyTypeError
        );
        assert_eq!(
            extract_traceback(py, exception),
            "TypeError: argument 'struct_arg': failed to \
    extract field ValueClass.value: TypeError: 'str' object cannot be interpreted as an integer"
        );

        let exception = py_expect_exception!(
            py,
            conversion_error,
            "
class ValueClass:
    def __init__(self, value):
        self.value = value
conversion_error('string1', -100, ('string2', 10.), None, ValueClass(-5))",
            PyTypeError
        );
        assert_eq!(
            extract_traceback(py, exception),
            "TypeError: argument 'struct_arg': failed to \
    extract field ValueClass.value: OverflowError: can't convert negative int to unsigned"
        );
    });
}

/// Helper function that concatenates the error message from
/// each error in the traceback into a single string that can
/// be tested.
fn extract_traceback(py: Python<'_>, mut error: PyErr) -> String {
    let mut error_msg = error.to_string();
    while let Some(cause) = error.cause(py) {
        error_msg.push_str(": ");
        error_msg.push_str(&cause.to_string());
        error = cause
    }
    error_msg
}

#[test]
fn test_pycfunction_new() {
    use pyo3::ffi;

    Python::with_gil(|py| {
        unsafe extern "C" fn c_fn(
            _self: *mut ffi::PyObject,
            _args: *mut ffi::PyObject,
        ) -> *mut ffi::PyObject {
            ffi::PyLong_FromLong(4200)
        }

        let py_fn = PyCFunction::new_bound(
            py,
            c_fn,
            c_str!("py_fn"),
            c_str!("py_fn for test (this is the docstring)"),
            None,
        )
        .unwrap();

        py_assert!(py, py_fn, "py_fn() == 4200");
        py_assert!(
            py,
            py_fn,
            "py_fn.__doc__ == 'py_fn for test (this is the docstring)'"
        );
    });
}

#[test]
fn test_pycfunction_new_with_keywords() {
    use pyo3::ffi;
    use std::os::raw::c_long;
    use std::ptr;

    Python::with_gil(|py| {
        unsafe extern "C" fn c_fn(
            _self: *mut ffi::PyObject,
            args: *mut ffi::PyObject,
            kwds: *mut ffi::PyObject,
        ) -> *mut ffi::PyObject {
            let mut foo: c_long = 0;
            let mut bar: c_long = 0;

            #[cfg(not(Py_3_13))]
            let foo_name = std::ffi::CString::new("foo").unwrap();
            #[cfg(not(Py_3_13))]
            let kw_bar_name = std::ffi::CString::new("kw_bar").unwrap();
            #[cfg(not(Py_3_13))]
            let mut args_names = [foo_name.into_raw(), kw_bar_name.into_raw(), ptr::null_mut()];

            #[cfg(Py_3_13)]
            let args_names = [
                c_str!("foo").as_ptr(),
                c_str!("kw_bar").as_ptr(),
                ptr::null_mut(),
            ];

            ffi::PyArg_ParseTupleAndKeywords(
                args,
                kwds,
                c_str!("l|l").as_ptr(),
                #[cfg(Py_3_13)]
                args_names.as_ptr(),
                #[cfg(not(Py_3_13))]
                args_names.as_mut_ptr(),
                &mut foo,
                &mut bar,
            );

            #[cfg(not(Py_3_13))]
            drop(std::ffi::CString::from_raw(args_names[0]));
            #[cfg(not(Py_3_13))]
            drop(std::ffi::CString::from_raw(args_names[1]));

            ffi::PyLong_FromLong(foo * bar)
        }

        let py_fn = PyCFunction::new_with_keywords_bound(
            py,
            c_fn,
            c_str!("py_fn"),
            c_str!("py_fn for test (this is the docstring)"),
            None,
        )
        .unwrap();

        py_assert!(py, py_fn, "py_fn(42, kw_bar=100) == 4200");
        py_assert!(py, py_fn, "py_fn(foo=42, kw_bar=100) == 4200");
        py_assert!(
            py,
            py_fn,
            "py_fn.__doc__ == 'py_fn for test (this is the docstring)'"
        );
    });
}

#[test]
fn test_closure() {
    Python::with_gil(|py| {
        let f = |args: &Bound<'_, types::PyTuple>,
                 _kwargs: Option<&Bound<'_, types::PyDict>>|
         -> PyResult<_> {
            Python::with_gil(|py| {
                let res: Vec<_> = args
                    .iter()
                    .map(|elem| {
                        if let Ok(i) = elem.extract::<i64>() {
                            (i + 1).into_py(py)
                        } else if let Ok(f) = elem.extract::<f64>() {
                            (2. * f).into_py(py)
                        } else if let Ok(mut s) = elem.extract::<String>() {
                            s.push_str("-py");
                            s.into_py(py)
                        } else {
                            panic!("unexpected argument type for {:?}", elem)
                        }
                    })
                    .collect();
                Ok(res)
            })
        };
        let closure_py = PyCFunction::new_closure_bound(
            py,
            Some(c_str!("test_fn")),
            Some(c_str!("test_fn doc")),
            f,
        )
        .unwrap();

        py_assert!(py, closure_py, "closure_py(42) == [43]");
        py_assert!(py, closure_py, "closure_py.__name__ == 'test_fn'");
        py_assert!(py, closure_py, "closure_py.__doc__ == 'test_fn doc'");
        py_assert!(
            py,
            closure_py,
            "closure_py(42, 3.14, 'foo') == [43, 6.28, 'foo-py']"
        );
    });
}

#[test]
fn test_closure_counter() {
    Python::with_gil(|py| {
        let counter = std::cell::RefCell::new(0);
        let counter_fn = move |_args: &Bound<'_, types::PyTuple>,
                               _kwargs: Option<&Bound<'_, types::PyDict>>|
              -> PyResult<i32> {
            let mut counter = counter.borrow_mut();
            *counter += 1;
            Ok(*counter)
        };
        let counter_py = PyCFunction::new_closure_bound(py, None, None, counter_fn).unwrap();

        py_assert!(py, counter_py, "counter_py() == 1");
        py_assert!(py, counter_py, "counter_py() == 2");
        py_assert!(py, counter_py, "counter_py() == 3");
    });
}

#[test]
fn use_pyfunction() {
    mod function_in_module {
        use pyo3::prelude::*;

        #[pyfunction]
        pub fn foo(x: i32) -> i32 {
            x
        }
    }

    Python::with_gil(|py| {
        use function_in_module::foo;

        // check imported name can be wrapped
        let f = wrap_pyfunction_bound!(foo, py).unwrap();
        assert_eq!(f.call1((5,)).unwrap().extract::<i32>().unwrap(), 5);
        assert_eq!(f.call1((42,)).unwrap().extract::<i32>().unwrap(), 42);

        // check path import can be wrapped
        let f2 = wrap_pyfunction_bound!(function_in_module::foo, py).unwrap();
        assert_eq!(f2.call1((5,)).unwrap().extract::<i32>().unwrap(), 5);
        assert_eq!(f2.call1((42,)).unwrap().extract::<i32>().unwrap(), 42);
    })
}

#[pyclass]
struct Key(String);

#[pyclass]
struct Value(i32);

#[pyfunction]
fn return_value_borrows_from_arguments<'py>(
    py: Python<'py>,
    key: &'py Key,
    value: &'py Value,
) -> HashMap<&'py str, i32> {
    py.allow_threads(move || {
        let mut map = HashMap::new();
        map.insert(key.0.as_str(), value.0);
        map
    })
}

#[test]
fn test_return_value_borrows_from_arguments() {
    Python::with_gil(|py| {
        let function = wrap_pyfunction_bound!(return_value_borrows_from_arguments, py).unwrap();

        let key = Py::new(py, Key("key".to_owned())).unwrap();
        let value = Py::new(py, Value(42)).unwrap();

        py_assert!(py, function key value, "function(key, value) == { \"key\": 42 }");
    });
}

#[test]
fn test_some_wrap_arguments() {
    // https://github.com/PyO3/pyo3/issues/3460
    const NONE: Option<u8> = None;
    #[pyfunction(signature = (a = 1, b = Some(2), c = None, d = NONE))]
    fn some_wrap_arguments(
        a: Option<u8>,
        b: Option<u8>,
        c: Option<u8>,
        d: Option<u8>,
    ) -> [Option<u8>; 4] {
        [a, b, c, d]
    }

    Python::with_gil(|py| {
        let function = wrap_pyfunction_bound!(some_wrap_arguments, py).unwrap();
        py_assert!(py, function, "function() == [1, 2, None, None]");
    })
}

#[test]
fn test_reference_to_bound_arguments() {
    #[pyfunction]
    #[pyo3(signature = (x, y = None))]
    fn reference_args<'py>(
        x: &Bound<'py, PyAny>,
        y: Option<&Bound<'py, PyAny>>,
    ) -> PyResult<Bound<'py, PyAny>> {
        y.map_or_else(|| Ok(x.clone()), |y| y.add(x))
    }

    Python::with_gil(|py| {
        let function = wrap_pyfunction_bound!(reference_args, py).unwrap();
        py_assert!(py, function, "function(1) == 1");
        py_assert!(py, function, "function(1, 2) == 3");
    })
}

#[test]
fn test_pyfunction_raw_ident() {
    #[pyfunction]
    fn r#struct() -> bool {
        true
    }

    #[pyfunction]
    #[pyo3(name = "r#enum")]
    fn raw_ident() -> bool {
        true
    }

    #[pymodule]
    fn m(m: &Bound<'_, PyModule>) -> PyResult<()> {
        m.add_function(wrap_pyfunction!(r#struct, m)?)?;
        m.add_function(wrap_pyfunction!(raw_ident, m)?)?;
        Ok(())
    }

    Python::with_gil(|py| {
        let m = pyo3::wrap_pymodule!(m)(py);
        py_assert!(py, m, "m.struct()");
        py_assert!(py, m, "m.enum()");
    })
}