Rust的Holochain WASM测试工具库holochain_wasm_test_utils使用指南,简化WASM智能合约单元测试开发
Rust的Holochain WASM测试工具库holochain_wasm_test_utils使用指南,简化WASM智能合约单元测试开发
Wasm测试工具
这个crate包含:
- 几个编译成Wasm的小crate,用作测试值
enum TestWasm
枚举所有这些crateimpl From<TestWasm> for DnaWasm
获取这些crate的编译后Wasm工件- 一个
build.rs
文件,在编译时将所有这些crate构建并包含到库中
这些Wasm crate直接测试Holochain的主机/访客实现,而不通过HDK或其他便利接口。这样做是为了确保不使用hdk
和holochain_wasmer_*
crate时也能相对容易地与Holochain交互。
运行这些Wasm的测试通常位于核心的ribosome.rs
模块中。这是必要的,因为Wasm crate依赖于核心定义的某些全局函数,需要注入。
安装方法
在项目目录中运行以下Cargo命令:
cargo add holochain_wasm_test_utils
或者在Cargo.toml中添加以下行:
holochain_wasm_test_utils = "0.5.4"
完整示例代码
use holochain_wasm_test_utils::TestWasm;
use holochain_zome_types::DnaWasm;
// 获取测试Wasm的路径
let test_wasm = TestWasm::Foo; // 使用Foo作为示例测试Wasm
let wasm_path: DnaWasm = test_wasm.into();
// 在测试中使用Wasm
#[test]
fn test_wasm_execution() {
// 初始化测试环境
let mut conductor = Conductor::builder().build();
// 创建包含测试Wasm的DNA
let dna = DnaFile::new(
DnaDef::unique(),
vec![wasm_path]
).unwrap();
// 安装DNA到导体
let cell_id = conductor.install_dna(dna).unwrap();
// 调用Wasm函数进行测试
let result: SerializedBytes = conductor.call(
&cell_id,
"zome_name",
"function_name",
None,
&() // 传入参数
).unwrap();
// 断言结果
assert!(result.is_valid());
}
示例说明
- 首先导入必要的类型:
TestWasm
枚举和DnaWasm
类型 - 选择一个测试Wasm(这里使用
Foo
作为示例) - 将
TestWasm
转换为DnaWasm
获取路径 - 在测试函数中:
- 创建导体(Conductor)实例
- 构建包含测试Wasm的DNA定义
- 将DNA安装到导体中
- 调用Wasm函数进行测试
- 验证结果
这个示例展示了如何使用holochain_wasm_test_utils
来简化Wasm智能合约的单元测试开发,通过预构建的测试Wasm来验证核心功能。
元数据
- 版本: 0.5.4
- 发布时间: 28天前
- 许可证: Apache-2.0
- 大小: 7.48 KiB
扩展完整示例
use holochain_wasm_test_utils::TestWasm;
use holochain_zome_types::{DnaWasm, DnaDef, DnaFile};
use holochain_conductor_api::{Conductor, ConductorHandle};
use holochain_types::prelude::{SerializedBytes, InstallAppPayload};
// 测试多个Wasm模块的示例
#[tokio::test]
async fn test_multiple_wasm_modules() {
// 初始化导体
let conductor = Conductor::builder().build().await.unwrap();
// 准备多个测试Wasm
let wasms = vec![
TestWasm::Foo.into(),
TestWasm::Bar.into(),
TestWasm::Baz.into()
];
// 创建DNA定义
let dna = DnaFile::new(
DnaDef::unique().with_wasms(wasms),
Default::default()
).unwrap();
// 安装应用
let payload = InstallAppPayload {
installed_app_id: "test_app".to_string(),
dna: dna.clone(),
agent_key: conductor.keystore().new_sign_keypair_random().unwrap(),
membrane_proofs: Default::default(),
};
let cell_id = conductor.install_app(payload).await.unwrap();
// 测试Foo模块
let foo_result: SerializedBytes = conductor.call(
&cell_id,
"foo_zome",
"foo_fn",
None,
&()
).await.unwrap();
// 测试Bar模块
let bar_result: SerializedBytes = conductor.call(
&cell_id,
"bar_zome",
"bar_fn",
None,
&()
).await.unwrap();
// 断言结果
assert!(foo_result.is_valid());
assert!(bar_result.is_valid());
}
扩展示例说明
- 这个扩展示例展示了如何测试多个Wasm模块
- 使用
TestWasm
枚举的不同变体(Foo, Bar, Baz) - 创建包含多个Wasm的DNA
- 安装应用到导体
- 分别测试不同Wasm模块的功能
- 使用异步测试(Tokio运行时)
- 包含更完整的错误处理和类型转换
这个示例演示了如何在更复杂的场景下使用holochain_wasm_test_utils
进行集成测试。
1 回复