use anyhow::Result;
use rogue_runtime::prelude::*;
rpc! {
struct BankAccount {
id: InstanceId,
balance: i64,
}
impl Identity for BankAccount {
fn id(&self) -> &InstanceId {
&self.id
}
}
impl BankAccount {
pub async fn new(initial: i64) -> Self {
Self {
id: InstanceId::new(),
balance: initial,
}
}
pub async fn balance(&self) -> i64 {
self.balance
}
pub async fn deposit(&mut self, amount: i64) {
self.balance += amount;
}
pub async fn withdraw(&mut self, amount: i64) -> bool {
if self.balance >= amount {
self.balance -= amount;
true
} else {
false
}
}
}
}
#[tokio::test]
async fn test_bank_account_runtime() -> Result<()> {
let runtime = Runtime::create("instance_test".to_string()).await?;
runtime
.execute_local(async move {
let mut acct = BankAccount::new(100).await;
assert_eq!(acct.balance().await, 100);
acct.deposit(50).await;
assert_eq!(acct.balance().await, 150);
assert!(acct.withdraw(70).await);
assert_eq!(acct.balance().await, 80);
assert!(!acct.withdraw(200).await);
assert_eq!(acct.balance().await, 80);
acct.deposit(20).await;
assert_eq!(acct.balance().await, 100);
Ok(())
})
.await?;
Ok(())
}