NFC Add test for pyo3 catching rust panics (#3905)

This adds a test PyO3 module which intentionally panics and checks that it
gets properly caught and converted to a Python exception. I think this test
is failing on the wasm-exceptions branch, but in any case it is good to have
explicit test coverage for this.
This commit is contained in:
Hood Chatham 2023-06-05 19:23:14 -07:00 committed by GitHub
parent 51c56ba645
commit 31e937ea2d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 80 additions and 0 deletions

View File

@ -0,0 +1,9 @@
package:
name: rust-panic-test
version: "1.0"
source:
path: src
build:
script: |
rustup toolchain install ${RUST_TOOLCHAIN} && rustup default ${RUST_TOOLCHAIN}
rustup target add wasm32-unknown-emscripten --toolchain ${RUST_TOOLCHAIN}

7
packages/rust-panic-test/src/Cargo.lock generated Normal file
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "hello-world"
version = "0.1.0"

View File

@ -0,0 +1,19 @@
[package]
name = "rust-panic-test"
version = "0.1.0"
edition = "2018"
publish = false
[dependencies]
pyo3 = { version = "0.15.2" }
[features]
extension-module = ["pyo3/extension-module"]
default = ["extension-module"]
[lib]
crate-type = ["cdylib"]
[profile.release]
lto = "thin"
overflow-checks = true

View File

@ -0,0 +1,3 @@
[build-system]
requires = ["setuptools", "wheel", "setuptools-rust"]
build-backend = "setuptools.build_meta"

View File

@ -0,0 +1,12 @@
from setuptools import setup
from setuptools_rust import Binding, RustExtension
setup(
name="rust_panic_test",
version="1.0",
rust_extensions=[
RustExtension("rust_panic_test", "Cargo.toml", binding=Binding.PyO3)
],
# rust extensions are not zip safe, just like C-extensions.
zip_safe=False,
)

View File

@ -0,0 +1,18 @@
#[pyo3::prelude::pyfunction]
fn panic_test(data: &[u8]) -> bool {
if data[0] < 6 {
panic!("this is a {} {message:?}", "fancy", message = data);
}
data[0] < 20
}
#[pyo3::prelude::pymodule]
fn rust_panic_test(py: pyo3::Python<'_>, m: &pyo3::types::PyModule) -> pyo3::PyResult<()> {
m.add_function(pyo3::wrap_pyfunction!(panic_test, m)?)?;
m.add("PanicException", py.get_type::<pyo3::panic::PanicException>())?;
Ok(())
}

View File

@ -0,0 +1,12 @@
from pytest_pyodide import run_in_pyodide
@run_in_pyodide(packages=["rust-panic-test"])
def test_rust_panic(selenium):
from pytest import raises
from rust_panic_test import PanicException, panic_test
assert not panic_test(bytes([20]))
assert panic_test(bytes([10]))
with raises(PanicException):
panic_test(bytes([1]))