123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262 |
- use cucumber::{given, then, when, World};
- use futures::future::BoxFuture;
- use std::{
- collections::HashMap,
- path::{Path, PathBuf},
- sync::Arc,
- };
- use tokio::{fs, io};
- use verax::{storage::SQLite, AccountId, Amount, Asset, RevId, TokenPayload};
- #[derive(Debug, Clone)]
- pub enum Variable {
- RevId(RevId),
- RevIdResult(Result<RevId, String>),
- }
- impl From<RevId> for Variable {
- fn from(rev_id: RevId) -> Self {
- Variable::RevId(rev_id)
- }
- }
- impl From<Result<RevId, verax::Error>> for Variable {
- fn from(rev_id: Result<RevId, verax::Error>) -> Self {
- Variable::RevIdResult(rev_id.map_err(|e| e.to_string()))
- }
- }
- #[derive(Debug, World)]
- pub struct LedgerWorld {
- ledger: Arc<verax::Ledger<SQLite>>,
- variables: HashMap<String, Variable>,
- spend: Option<Vec<(AccountId, Amount)>>,
- tokens: Vec<TokenPayload>,
- receive: Option<Vec<(AccountId, Amount)>>,
- }
- impl Default for LedgerWorld {
- fn default() -> Self {
- futures::executor::block_on(async move {
- let settings = "sqlite://:memory:"
- .parse::<verax::storage::sqlite::SqliteConnectOptions>()
- .expect("valid settings")
- .journal_mode(verax::storage::sqlite::SqliteJournalMode::Wal)
- .create_if_missing(true);
- let pool = verax::storage::sqlite::SqlitePoolOptions::new()
- .connect_with(settings)
- .await
- .expect("pool");
- let db = SQLite::new(pool);
- db.setup().await.expect("setup");
- Self {
- ledger: verax::Ledger::new(db.into()),
- variables: HashMap::new(),
- tokens: vec![],
- spend: None,
- receive: None,
- }
- })
- }
- }
- impl LedgerWorld {
- pub fn get(&self, name: &str) -> &Variable {
- self.variables.get(name).as_ref().expect("variable")
- }
- }
- #[given("a new transaction")]
- fn new_transaction(world: &mut LedgerWorld) {
- world.spend = Some(vec![]);
- world.receive = Some(vec![]);
- }
- #[given(expr = "spend {word} {word} from {word}")]
- fn spend(world: &mut LedgerWorld, amount: String, asset: String, account: String) {
- let asset = asset.parse::<Asset>().expect("valid asset");
- let amount = asset.from_human(&amount).expect("valid amount");
- world
- .spend
- .as_mut()
- .expect("has spend")
- .push((account.parse().expect("valid account"), amount));
- }
- #[then(expr = "withdraw from {word} {word} {word}")]
- async fn withdraw(world: &mut LedgerWorld, account: String, amount: String, asset: String) {
- let asset = asset.parse::<Asset>().expect("valid asset");
- let amount = asset.from_human(&amount).expect("valid amount");
- let account = account.parse().expect("valid account");
- world.variables.insert(
- "latest".to_owned(),
- world
- .ledger
- .withdrawal(&account, amount, "settled".into(), "test".to_owned(), None)
- .await
- .map(|x| x.revision_id)
- .into(),
- );
- }
- #[then("it fails")]
- async fn it_fails(world: &mut LedgerWorld) {
- match world.variables.get("latest").expect("latest") {
- Variable::RevIdResult(Err(_)) => {}
- latest => panic!("expected error found: {:?}", latest),
- }
- }
- #[given(expr = "receive {word} {word} in {word}")]
- fn receive(world: &mut LedgerWorld, amount: String, asset: String, account: String) {
- let asset = asset.parse::<Asset>().expect("valid asset");
- let amount = asset.from_human(&amount).expect("valid amount");
- world
- .receive
- .as_mut()
- .expect("has receive")
- .push((account.parse().expect("valid account"), amount));
- }
- #[when(expr = "commit transaction {word} as {word}")]
- async fn commit_transaction(world: &mut LedgerWorld, name: String, status: String) {
- let status = status.parse::<verax::Status>().expect("valid status");
- let spend = world.spend.take().expect("has spend");
- let receive = world.receive.take().expect("has receive");
- world.variables.insert(
- name,
- world
- .ledger
- .new_transaction("Transaction".to_owned(), status, spend, receive, None)
- .await
- .map(|x| x.revision_id)
- .into(),
- );
- }
- #[given(expr = "a {word} deposit {word} of {word} {word} for {word}")]
- async fn deposit_funds(
- world: &mut LedgerWorld,
- status: String,
- name: String,
- amount: String,
- asset: String,
- account: String,
- ) {
- let asset = asset.parse::<Asset>().expect("valid asset");
- world.variables.insert(
- name,
- world
- .ledger
- .deposit(
- &account.parse().expect("valid account"),
- asset.from_human(&amount).expect("valid amount"),
- status.parse().expect("valid status"),
- vec![],
- "Initial deposit".to_owned(),
- None,
- )
- .await
- .map(|x| x.revision_id)
- .into(),
- );
- }
- #[given(expr = "update {word} set status to {word}")]
- async fn update_status_from_last_tx(world: &mut LedgerWorld, tx: String, new_status: String) {
- let revision = match world.get(&tx) {
- Variable::RevId(rev_id) => rev_id.clone(),
- Variable::RevIdResult(Ok(rev_id)) => rev_id.clone(),
- _ => panic!("{} is not a RevId", tx),
- };
- let status = new_status.parse().expect("valid status");
- let update_token = world.tokens.pop();
- world.variables.insert(
- tx,
- world
- .ledger
- .change_status(revision, status, "update status".to_owned(), update_token)
- .await
- .map(|x| x.revision_id)
- .into(),
- );
- }
- #[then(expr = "{word} has failed")]
- fn has_failed(world: &mut LedgerWorld, tx: String) {
- assert!(matches!(
- world.get(&tx).clone(),
- Variable::RevIdResult(Err(_))
- ));
- }
- #[then(expr = "{word} has no balance")]
- async fn check_balance_empty(world: &mut LedgerWorld, account: String) {
- let balance = world
- .ledger
- .get_balance(&account.parse().expect("valid account"))
- .await
- .expect("balance")
- .into_iter()
- .filter(|b| b.cents() != 0)
- .collect::<Vec<_>>();
- assert_eq!(0, balance.len())
- }
- #[then(expr = "{word} has balance of {word} {word}")]
- async fn check_balance(world: &mut LedgerWorld, account: String, amount: String, asset: String) {
- let asset = asset.parse::<Asset>().expect("valid asset");
- let amount = asset.from_human(&amount).expect("valid amount");
- let balances = world
- .ledger
- .get_balance(&account.parse().expect("valid account"))
- .await
- .expect("balance")
- .into_iter()
- .filter(|b| b.asset() == &asset)
- .collect::<Vec<_>>();
- assert_eq!(1, balances.len(), "{} is found", asset);
- assert_eq!(balances.first(), Some(&amount));
- }
- fn find_features<A: AsRef<Path> + Send + Sync>(
- dir_path: &A,
- ) -> BoxFuture<'_, io::Result<Vec<PathBuf>>> {
- Box::pin(async move {
- let mut entries = fs::read_dir(dir_path).await?;
- let mut paths = vec![];
- while let Ok(Some(entry)) = entries.next_entry().await {
- let path = entry.path();
- if path.is_dir() {
- paths.extend(find_features(&path).await?);
- } else if let Some(extension) = path.extension() {
- if extension == "feature" {
- paths.push(path);
- }
- }
- }
- Ok(paths)
- })
- }
- #[tokio::main]
- async fn main() {
- for file in find_features(&".").await.expect("files") {
- LedgerWorld::run(file).await;
- }
- }
|