File: mod.rs

package info (click to toggle)
rust-pyo3-async-runtimes 0.25.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 448 kB
  • sloc: makefile: 2
file content (65 lines) | stat: -rw-r--r-- 1,725 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
use std::ffi::CString;
use std::{thread, time::Duration};

use pyo3::prelude::*;
use pyo3_async_runtimes::TaskLocals;

pub(super) const TEST_MOD: &str = r#"
import asyncio

async def py_sleep(duration):
    await asyncio.sleep(duration)

async def sleep_for_1s(sleep_for):
    await sleep_for(1)
"#;

pub(super) async fn test_into_future(event_loop: PyObject) -> PyResult<()> {
    let fut = Python::with_gil(|py| {
        let test_mod = PyModule::from_code(
            py,
            &CString::new(TEST_MOD).unwrap(),
            &CString::new("test_rust_coroutine/test_mod.py").unwrap(),
            &CString::new("test_mod").unwrap(),
        )?;

        pyo3_async_runtimes::into_future_with_locals(
            &TaskLocals::new(event_loop.into_bound(py)),
            test_mod.call_method1("py_sleep", (1.into_pyobject(py).unwrap(),))?,
        )
    })?;

    fut.await?;

    Ok(())
}

pub(super) fn test_blocking_sleep() -> PyResult<()> {
    thread::sleep(Duration::from_secs(1));
    Ok(())
}

pub(super) async fn test_other_awaitables(event_loop: PyObject) -> PyResult<()> {
    let fut = Python::with_gil(|py| {
        let functools = py.import("functools")?;
        let time = py.import("time")?;

        // spawn a blocking sleep in the threadpool executor - returns a task, not a coroutine
        let task = event_loop.bind(py).call_method1(
            "run_in_executor",
            (
                py.None(),
                functools.call_method1("partial", (time.getattr("sleep")?, 1))?,
            ),
        )?;

        pyo3_async_runtimes::into_future_with_locals(
            &TaskLocals::new(event_loop.into_bound(py)),
            task,
        )
    })?;

    fut.await?;

    Ok(())
}