Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,10 @@ jobs:

- run: cargo test

- name: Run Rust tests inside the BEAM
run: cargo test -p beam_test_demo
if: "startsWith(matrix.os, 'ubuntu')"

- name: Test rustler_mix
working-directory: rustler_mix
run: |
Expand Down
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ members = [
"rustler",
"rustler/otp_headers/codegen",
"rustler_codegen",
"rustler_beam_test",
"rustler_beam_test/macros",
"rustler_beam_test/runner",
"rustler_tests/native/beam_test_demo",
"rustler_tests/native/binary_example",
"rustler_tests/native/rustler_test",
"rustler_tests/native/rustler_bigint_test",
Expand Down
3 changes: 3 additions & 0 deletions rustler/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ default = ["nif_version_2_17"]
derive = []
allocator = []
serde = ["dep:serde"]
# Lets a tool learn the module and the NIFs of a library before it loads the
# library: see `codegen_runtime::write_manifest`. For test builds only.
nif_manifest = []
# for nif versions and their changes see
# https://github.com/erlang/otp/blob/master/erts/emulator/beam/erl_nif.h
nif_version_2_14 = []
Expand Down
35 changes: 35 additions & 0 deletions rustler/src/codegen_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,41 @@ pub use crate::sys::{
ErlNifFunc, ErlNifTerm,
};

/// Writes the module of a library and its NIFs to a new file at the path that
/// the environment variable `RUSTLER_NIF_MANIFEST` names: the module on the
/// first line, then one line `<arity> <name>` for each NIF. When a file or a
/// link is at that path already, it writes nothing.
///
/// `erlang:load_nif/2` accepts a library only from the module that the library
/// names, and only when that module defines each NIF. The BEAM asks the library
/// for both before it checks them, so a tool that knows neither can call
/// `erlang:load_nif/2` from any module, read this file, and then load the
/// library from a module that fits. The first call fails, as it must.
///
/// Without the `nif_manifest` feature this does nothing.
///
/// # Safety
///
/// The name of each NIF is a C string.
pub unsafe fn write_manifest(module: &str, nifs: &[ErlNifFunc]) {
#[cfg(feature = "nif_manifest")]
if let Some(path) = std::env::var_os("RUSTLER_NIF_MANIFEST") {
let mut manifest = format!("{module}\n");
for nif in nifs {
let name = std::ffi::CStr::from_ptr(nif.name).to_string_lossy();
manifest.push_str(&format!("{} {name}\n", nif.arity));
}
// A tool that finds no file reports that.
let _ = std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(path)
.and_then(|mut file| std::io::Write::write_all(&mut file, manifest.as_bytes()));
}
#[cfg(not(feature = "nif_manifest"))]
let _ = (module, nifs);
}

pub unsafe trait NifReturnable {
unsafe fn into_returned(self, env: Env) -> NifReturned;
}
Expand Down
15 changes: 15 additions & 0 deletions rustler_beam_test/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
[package]
name = "rustler_beam_test"
description = "Write the tests of a Rustler NIF library in Rust and run them inside a real BEAM"
repository = "https://github.com/rusterlium/rustler"
version = "0.39.0"
license = "MIT/Apache-2.0"
readme = "README.md"
edition = "2021"
rust-version = "1.91"

[dependencies]
# The library picks its NIF version, and 2.15 is the lowest that rustler builds
# with.
rustler = { path = "../rustler", version = "0.39.0", default-features = false, features = ["nif_manifest", "nif_version_2_15"] }
rustler_beam_test_macros = { path = "macros", version = "0.39.0" }
114 changes: 114 additions & 0 deletions rustler_beam_test/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# rustler_beam_test

Write the tests of a Rustler NIF library in Rust, and run them inside a real
BEAM with `cargo test`.

A test binary has no BEAM, so a test that calls into the NIF API cannot run in
it. `#[rustler_beam_test::test]` compiles the test into the NIF library
instead. A test target then builds the library, loads it into an `erl` node,
and runs each test there as a NIF. `cargo test` lists, filters, and reports
them like any other test.

```rust,ignore
#[cfg(feature = "beam_test")]
mod tests {
use rustler::{Encoder, Env};
use rustler_beam_test::{receive, Receive};

#[rustler_beam_test::test]
fn an_integer_round_trips(env: Env) {
assert_eq!(42.encode(env).decode::<i64>().unwrap(), 42);
}

#[rustler_beam_test::test]
fn a_message_to_self_arrives(env: Env) -> Receive {
env.send(&env.pid(), "hello").unwrap();
receive(|_env, message| assert_eq!(message.decode::<&str>().unwrap(), "hello"))
}
}
```

## Setup

It works on Linux so far, and needs `erl` on the `PATH`.

```toml
[lib]
crate-type = ["cdylib"]
# Without a BEAM, the test binary of a NIF library does not link on Linux.
test = false

[[test]]
name = "beam"
harness = false

[features]
beam_test = ["dep:rustler_beam_test"]

[dependencies]
rustler = "..."
rustler_beam_test = { version = "...", optional = true }

[dev-dependencies]
rustler_beam_test_runner = "..."
```

The feature must have the name `beam_test`. The test target is one line, in
`tests/beam.rs`:

```rust,ignore
rustler_beam_test_runner::main!();
```

## Tests

A test takes no argument or a `rustler::Env`. It fails when it panics, or when
it returns an `Err`. `#[ignore]` and `#[should_panic]` work as on a `#[test]`.

Each test runs as one NIF call in a new process, on a normal scheduler, so
the `Env` is bound to a process, as in a NIF. The tests share the node and run
in parallel.

A NIF cannot read the mailbox of its process. To check a message, a test
returns `receive(...)`: the process then takes its next message and passes it
to the closure, in a second NIF call. The test fails when no message arrives
within 5 seconds.

`#[rustler::nif]` hides the function that it wraps, so a test cannot call it.
Test the function that the NIF calls.

## How it works

The attribute registers the test as one more NIF of the library, like
`#[rustler::nif]` does, behind the `beam_test` feature. The test target is
free of Rustler, so it links without a BEAM. It:

1. builds the library with `cargo build --lib --features beam_test`, in the
profile of the test target, into a directory of its own in the target
directory,
2. starts `erl` with a small driver, which connects back to the test target
on the loopback interface and proves with a random token that it is the
node that the test target started,
3. has the driver load the library and send back the names of its NIFs,
among them the tests, and then run each test that `cargo test` selects.

`erlang:load_nif/2` accepts a library only from the module that
`rustler::init!` names, and only when that module defines every NIF. The
driver knows neither. `rustler_beam_test` turns on the `nif_manifest` feature
of Rustler, with which the library writes both to a file when the BEAM asks it
for them. The BEAM does that before it checks them, so the driver calls
`erlang:load_nif/2` once from its own module, which the BEAM refuses, reads
the file, compiles the right module with a stub for each NIF, and loads the
library from it. So the library loads as it does in production, with all its
NIFs, its `load` function, and its resource types.

A failed test reports the panic message and its location. Set
`RUST_BACKTRACE=1` to get the backtrace too.

When a test kills the node, for example with a segmentation fault, that test
fails with the exit status of the node, and the next test starts a new node.
When several tests were running at that moment, each of them runs again
alone, so that only the one that kills the node fails.

Output that a test prints inside the node goes to the terminal directly.
`cargo test` does not capture it.
14 changes: 14 additions & 0 deletions rustler_beam_test/macros/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "rustler_beam_test_macros"
description = "The `#[rustler_beam_test::test]` attribute"
repository = "https://github.com/rusterlium/rustler"
version = "0.39.0"
license = "MIT/Apache-2.0"
edition = "2021"

[lib]
proc-macro = true

[dependencies]
syn = { version = "3.0", features = ["full"] }
quote = "1.0"
120 changes: 120 additions & 0 deletions rustler_beam_test/macros/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::spanned::Spanned;

/// Marks a function as a test that runs inside a BEAM.
///
/// The function takes no argument or a `rustler::Env`, and returns a
/// `rustler_beam_test::Outcome`. See the documentation of `rustler_beam_test`.
#[proc_macro_attribute]
pub fn test(attr: TokenStream, item: TokenStream) -> TokenStream {
syn::parse_macro_input!(attr as syn::parse::Nothing);
let mut function = syn::parse_macro_input!(item as syn::ItemFn);

// The compiler knows these two only on a `#[test]` function, so the test
// itself carries what they say.
let mut ignore = false;
let mut should_panic = quote!(::core::option::Option::None);
let mut error = None;
function.attrs.retain(|attr| {
if attr.path().is_ident("ignore") {
ignore = true;
} else if attr.path().is_ident("should_panic") {
match expected_message(attr) {
Ok(expected) => should_panic = quote!(::core::option::Option::Some(#expected)),
Err(invalid) => error = Some(invalid),
}
} else {
return true;
}
false
});
if let Some(error) = error {
return error.into_compile_error().into();
}

let name = &function.sig.ident;
let run = match function.sig.inputs.len() {
0 => quote!(|_| #name()),
1 => quote!(#name),
_ => {
return syn::Error::new(
function.sig.inputs.span(),
"a test takes no argument or a `rustler::Env`",
)
.into_compile_error()
.into()
}
};

// The runner knows a test, and whether it is ignored, by the prefix of its
// NIF name.
let prefix = if ignore {
"rustler_beam_test ignored "
} else {
"rustler_beam_test "
};
// The BEAM looks a NIF up by an atom of at most 255 Latin-1 characters.
let too_long = format!(
"the path of a test must be ASCII and at most {} bytes long",
255 - prefix.len()
);

// The NIF that runs the test calls it by its name, so none of the names
// that the NIF brings in can be the name of the test.
let nif = quote::format_ident!("{name}_nif");
let site = proc_macro::Span::mixed_site().into();
let (env, argv) = (syn::Ident::new("env", site), syn::Ident::new("argv", site));

// The test registers as a NIF with one argument, as `#[rustler::nif]`
// registers a function.
quote! {
#[cfg(feature = "beam_test")]
const _: () = {
#function
rustler::codegen_runtime::inventory::submit!(rustler::Nif {
// In a block of its own, so that the test sees its own items
// by these names.
name: {
const NAME: &str =
concat!(#prefix, module_path!(), "::", stringify!(#name), "\0");
const _: () = assert!(NAME.is_ascii() && NAME.len() <= 256, #too_long);
NAME.as_ptr() as *const rustler::codegen_runtime::c_char
},
arity: 1,
flags: 0,
raw_func: {
unsafe extern "C" fn #nif(
#env: *mut rustler::codegen_runtime::ErlNifEnv,
_: rustler::codegen_runtime::c_int,
#argv: *const rustler::codegen_runtime::ErlNifTerm,
) -> rustler::codegen_runtime::ErlNifTerm {
unsafe { ::rustler_beam_test::step(#env, #argv, #should_panic, #run) }
}
#nif
},
});
};
}
.into()
}

/// The text of `#[should_panic = "..."]` or `#[should_panic(expected = "...")]`,
/// or an empty one, which every panic message contains.
fn expected_message(attr: &syn::Attribute) -> syn::Result<String> {
let mut expected = String::new();
match &attr.meta {
syn::Meta::Path(_) => {}
syn::Meta::NameValue(pair) => {
expected = syn::parse2::<syn::LitStr>(pair.value.to_token_stream())?.value();
}
syn::Meta::List(_) => attr.parse_nested_meta(|meta| {
if !meta.path.is_ident("expected") {
return Err(meta.error("the only argument is `expected = \"...\"`"));
}
expected = meta.value()?.parse::<syn::LitStr>()?.value();
Ok(())
})?,
}
Ok(expected)
}
13 changes: 13 additions & 0 deletions rustler_beam_test/runner/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
[package]
name = "rustler_beam_test_runner"
description = "The test harness of rustler_beam_test: runs the tests of a NIF library in an erl node"
repository = "https://github.com/rusterlium/rustler"
version = "0.39.0"
license = "MIT/Apache-2.0"
readme = "../README.md"
edition = "2021"
rust-version = "1.91"

[dependencies]
libtest-mimic = "0.8"
serde_json = "1"
Loading
Loading