اختبار كامل
tests/error_test.rs
use litesvm::LiteSVM;use solana_sdk::{signature::{Keypair, Signer},system_instruction,transaction::Transaction,};use solana_transaction_error::TransactionError;#[test]fn test_insufficient_funds_error() {let mut svm = LiteSVM::new();let alice = Keypair::new();let bob = Keypair::new();// Give Alice only 0.5 SOLsvm.airdrop(&alice.pubkey(), 500_000_000).unwrap();// Try to transfer 1 SOL (should fail)let transfer_ix = system_instruction::transfer(&alice.pubkey(),&bob.pubkey(),1_000_000_000, // More than Alice has);let tx = Transaction::new_signed_with_payer(&[transfer_ix],Some(&alice.pubkey()),&[&alice],svm.latest_blockhash(),);// Verify it fails with expected errorlet result = svm.send_transaction(tx);assert!(result.is_err());let err = result.unwrap_err();match err.err {TransactionError::InstructionError(0, _) => {println!("Got expected error: InstructionError (insufficient funds)");}_ => panic!("Got unexpected error: {:?}", err.err),}// Verify no funds were transferredassert_eq!(svm.get_balance(&bob.pubkey()).unwrap_or(0), 0);}
اختبار أنواع الأخطاء المختلفة
حساب غير صالح
#[test]fn test_account_not_found() {let mut svm = LiteSVM::new();let non_existent = Pubkey::new_unique();// This should return Noneassert!(svm.get_account(&non_existent).is_none());}
أخطاء البرنامج المخصصة
#[test]fn test_custom_program_error() {let mut svm = LiteSVM::new();// Deploy program and trigger custom errorlet result = svm.send_transaction(tx);if let Err(e) = result {match e.err {TransactionError::InstructionError(_, InstructionError::Custom(code)) => {assert_eq!(code, YOUR_ERROR_CODE);}_ => panic!("Expected custom error"),}}}
النقاط الرئيسية
- تأكيدات الأخطاء: استخدم
assert!(result.is_err())للتحقق من حدوث الأخطاء - مطابقة الأخطاء: المطابقة على أنواع أخطاء محددة لضمان معالجة الأخطاء بشكل صحيح
- التحقق من الحالة: تحقق من أن الحالة لم تتغير عند حدوث الأخطاء
- الأخطاء المخصصة: اختبر رموز الأخطاء المخصصة في برنامجك
- الحالات الحدية: اختبر الشروط الحدية والمدخلات غير الصالحة
Is this page helpful?