Skip to content

Commit edc9993

Browse files
Junha Yangjunha1
Junha Yang
authored andcommitted
Write a simple test as an example
1 parent 1cd212d commit edc9993

File tree

2 files changed

+68
-0
lines changed

2 files changed

+68
-0
lines changed

remote-trait-object-tests/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ extern crate log;
1919

2020
#[cfg(test)]
2121
mod ping;
22+
mod simple;
2223
mod test_store;
2324
pub mod transport;
2425

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
//! This is a working version of the example in the crate-level documentation of `remote-trait-object`
2+
3+
use remote_trait_object::*;
4+
5+
#[service]
6+
pub trait CreditCard: Service {
7+
fn pay(&mut self, ammount: u64) -> Result<(), ()>;
8+
}
9+
struct SomeCreditCard {
10+
money: u64,
11+
}
12+
impl Service for SomeCreditCard {}
13+
impl CreditCard for SomeCreditCard {
14+
fn pay(&mut self, ammount: u64) -> Result<(), ()> {
15+
if ammount <= self.money {
16+
self.money -= ammount;
17+
Ok(())
18+
} else {
19+
Err(())
20+
}
21+
}
22+
}
23+
24+
#[service]
25+
pub trait PizzaStore: Service {
26+
fn order_pizza(&self, credit_card: ServiceRef<dyn CreditCard>) -> Result<String, ()>;
27+
}
28+
struct SomePizzaStore;
29+
impl Service for SomePizzaStore {}
30+
impl PizzaStore for SomePizzaStore {
31+
fn order_pizza(&self, credit_card: ServiceRef<dyn CreditCard>) -> Result<String, ()> {
32+
let mut credit_card_proxy: Box<dyn CreditCard> = credit_card.unwrap_import().into_proxy();
33+
credit_card_proxy.pay(10)?;
34+
Ok("Tasty Pizza".to_owned())
35+
}
36+
}
37+
38+
#[test]
39+
fn test() {
40+
let crate::transport::TransportEnds {
41+
recv1,
42+
send1,
43+
recv2,
44+
send2,
45+
} = crate::transport::create();
46+
47+
let _context_pizza_town = Context::with_initial_service_export(
48+
Config::default_setup(),
49+
send1,
50+
recv1,
51+
ServiceToExport::new(Box::new(SomePizzaStore) as Box<dyn PizzaStore>),
52+
);
53+
54+
let (_context_customer, pizza_store): (_, ServiceToImport<dyn PizzaStore>) =
55+
Context::with_initial_service_import(Config::default_setup(), send2, recv2);
56+
let pizza_store_proxy: Box<dyn PizzaStore> = pizza_store.into_proxy();
57+
58+
let my_credit_card = Box::new(SomeCreditCard {
59+
money: 11,
60+
}) as Box<dyn CreditCard>;
61+
assert_eq!(pizza_store_proxy.order_pizza(ServiceRef::create_export(my_credit_card)).unwrap(), "Tasty Pizza");
62+
63+
let my_credit_card = Box::new(SomeCreditCard {
64+
money: 9,
65+
}) as Box<dyn CreditCard>;
66+
assert!(pizza_store_proxy.order_pizza(ServiceRef::create_export(my_credit_card)).is_err());
67+
}

0 commit comments

Comments
 (0)