protocol_tests.rs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  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. struct ClientState;
  40. impl Client for ClientState {
  41. type SendMsgFut = Ready<Result<End>>;
  42. fn send_msg(self, _msg: Msg) -> Self::SendMsgFut {
  43. ready(Ok(End))
  44. }
  45. }
  46. }
  47. #[test]
  48. fn reply() {
  49. protocol! {
  50. named ReplyTest;
  51. let server = [Listening];
  52. let client = [Client, Waiting];
  53. Client -> Waiting, >service(Listening)!Ping;
  54. Listening?Ping -> Listening, >Waiting!Ping::Reply;
  55. Waiting?Ping::Reply -> End;
  56. }
  57. let msg: Option<ReplyTestMsgs> = None;
  58. match msg {
  59. Some(ReplyTestMsgs::Ping(ping)) => assert_type!(ping, Ping),
  60. Some(ReplyTestMsgs::PingReply(reply)) => assert_type!(reply, <Ping as CallMsg>::Reply),
  61. None => (),
  62. }
  63. struct ListeningState;
  64. impl Listening for ListeningState {
  65. type HandlePingListening = Self;
  66. type HandlePingFut = Ready<Result<(Self, <Ping as CallMsg>::Reply)>>;
  67. fn handle_ping(self, _msg: Ping) -> Self::HandlePingFut {
  68. ready(Ok((self, ())))
  69. }
  70. }
  71. struct ClientState;
  72. impl Client for ClientState {
  73. type SendPingWaiting = WaitingState;
  74. type SendPingFut = Ready<Result<(WaitingState, <Ping as CallMsg>::Reply)>>;
  75. fn send_ping(self, _ping: Ping) -> Self::SendPingFut {
  76. ready(Ok((WaitingState, ())))
  77. }
  78. }
  79. struct WaitingState;
  80. // TODO: This state should not be generated, as it is never observed.
  81. impl Waiting for WaitingState {
  82. type HandlePingReplyFut = Ready<Result<End>>;
  83. fn handle_ping_reply(self, _msg: ()) -> Self::HandlePingReplyFut {
  84. ready(Ok(End))
  85. }
  86. }
  87. }