protocol_tests.rs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. use std::future::{ready, Ready};
  2. use btlib::Result;
  3. use btproto::protocol;
  4. use btrun::{CallMsg, End};
  5. use serde::{Deserialize, Serialize};
  6. #[derive(Serialize, Deserialize)]
  7. pub struct Ping;
  8. impl CallMsg for Ping {
  9. type Reply = ();
  10. }
  11. /// Tests that the given variable is of the given type.
  12. macro_rules! assert_type {
  13. ($var:expr, $ty:ty) => {{
  14. let _: $ty = $var;
  15. }};
  16. }
  17. #[test]
  18. fn minimal_syntax() {
  19. pub struct Msg;
  20. protocol! {
  21. named MinimalTest;
  22. let states = [Server];
  23. let client = [Client];
  24. Client -> End, >service(Server)!Msg;
  25. Server?Msg -> End;
  26. }
  27. let msg: Option<MinimalTestMsgs> = None;
  28. match msg {
  29. Some(MinimalTestMsgs::Msg(act)) => assert_type!(act, Msg),
  30. None => (),
  31. }
  32. struct ServerState;
  33. impl Server for ServerState {
  34. type HandleMsgFut = Ready<Result<End>>;
  35. fn handle_msg(self, _msg: Msg) -> Self::HandleMsgFut {
  36. ready(Ok(End))
  37. }
  38. }
  39. }
  40. #[test]
  41. fn reply() {
  42. protocol! {
  43. named ReplyTest;
  44. let server = [Listening];
  45. let client = [Client, Waiting];
  46. Client -> Waiting, >service(Listening)!Ping;
  47. Listening?Ping -> Listening, >Waiting!Ping::Reply;
  48. Waiting?Ping::Reply -> End;
  49. }
  50. let msg: Option<ReplyTestMsgs> = None;
  51. match msg {
  52. Some(ReplyTestMsgs::Ping(ping)) => assert_type!(ping, Ping),
  53. Some(ReplyTestMsgs::PingReply(reply)) => assert_type!(reply, <Ping as CallMsg>::Reply),
  54. None => (),
  55. }
  56. struct ListeningState;
  57. impl Listening for ListeningState {
  58. type HandlePingListening = Self;
  59. type HandlePingFut = Ready<Result<Self>>;
  60. fn handle_ping(self, _msg: Ping) -> Self::HandlePingFut {
  61. ready(Ok(self))
  62. }
  63. }
  64. struct ClientState;
  65. impl Client for ClientState {
  66. type SendPingWaiting = WaitingState;
  67. type SendPingFut = Ready<Result<WaitingState>>;
  68. fn send_ping(self) -> Self::SendPingFut {
  69. ready(Ok(WaitingState))
  70. }
  71. }
  72. struct WaitingState;
  73. impl Waiting for WaitingState {
  74. type HandlePingReplyFut = Ready<Result<End>>;
  75. fn handle_ping_reply(self, _msg: Ping) -> Self::HandlePingReplyFut {
  76. ready(Ok(End))
  77. }
  78. }
  79. }