在测试程序之前,请确保您已完成以下步骤:
- 构建程序以生成
.so 文件
- 在
Cargo.toml 文件中将 litesvm 添加为开发依赖项
- 添加可能需要的其他开发依赖项,例如
solana-sdk@4 和
litesvm-token
- 在
tests 目录中创建测试文件
基本程序测试结构
以下是在 Solana 程序中调用并执行指令所需的全部基本步骤。
use litesvm::LiteSVM;
use solana_sdk::{
instruction::{AccountMeta, Instruction},
pubkey::Pubkey,
signature::{Keypair, Signer},
transaction::Transaction,
};
use my_program;
#[test]
fn test_my_program() {
// Initialize the test environment
let mut svm = LiteSVM::new();
// Deploy your program to the test environment. If your program uses an
// older solana-program (such as 2.2), its ID is a different Pubkey type,
// so convert it through its bytes.
let program_id = Pubkey::new_from_array(my_program::ID.to_bytes());
let program_bytes = include_bytes!("../../../target/deploy/my_program.so");
svm.add_program(program_id, program_bytes).unwrap();
// Create and fund test accounts
let payer = Keypair::new();
svm.airdrop(&payer.pubkey(), 10_000_000_000).unwrap();
// Create your instruction
let instruction = Instruction {
program_id,
accounts: vec![
AccountMeta::new(payer.pubkey(), true),
],
data: vec![],
};
// Build transaction
let tx = Transaction::new_signed_with_payer(
&[instruction],
Some(&payer.pubkey()),
&[&payer],
svm.latest_blockhash(),
);
// Send transaction
let result = svm.send_transaction(tx).unwrap();
// Check transaction succeeded
println!("Transaction logs: {:?}", result.logs);
println!("Program executed successfully!");
}
通过 LiteSVM::new() 生成的默认测试环境会启用当前 mainnet-beta 上已激活的运行时功能、默认 sysvar、spl 程序、sigverify 以及所有内置程序,例如 system program。
当启用 litesvm 的 precompiles 功能时,还会包含预编译程序(ed25519、secp256k1、secp256r1)。
如果要基于其他功能集(例如 agave-feature-set crate 中的
FeatureSet::all_enabled())构建整个环境,请从
LiteSVM::default() 开始,这样 sysvar 和功能账户才能与之匹配:
use agave_feature_set::FeatureSet;
use litesvm::LiteSVM;
use solana_sdk::native_token::LAMPORTS_PER_SOL;
let mut svm = LiteSVM::default()
.with_feature_set(FeatureSet::all_enabled())
.with_builtins()
.with_lamports(1_000_000 * LAMPORTS_PER_SOL)
.with_sysvars()
.with_feature_accounts()
.with_default_programs()
.with_sigverify(true)
.with_blockhash_check(true);
在 LiteSVM::new() 后链式调用 with_feature_set 只会替换功能集:
Rent sysvar 和功能账户仍保持 new() 为主网功能所设置的状态。
如果您想与默认测试环境中未包含的任何程序交互,则必须先将该程序部署到测试环境中。
后续步骤
在下一节中,我们将全面了解如何将程序部署到 litesvm 测试环境。