protocol_tests.rs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. use std::future::{ready, Ready};
  2. use btlib::Result;
  3. use btproto::protocol;
  4. use btrun::{Activate, 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. protocol! {
  20. named MinimalTest;
  21. let states = [Init];
  22. Init?Activate -> End;
  23. }
  24. let msg: Option<MinimalTestMsgs> = None;
  25. match msg {
  26. Some(MinimalTestMsgs::Activate(act)) => assert_type!(act, Activate),
  27. None => (),
  28. }
  29. struct InitState;
  30. impl Init for InitState {
  31. type HandleActivateFut = Ready<Result<End>>;
  32. fn handle_activate(self, _msg: btrun::Activate) -> Self::HandleActivateFut {
  33. ready(Ok(End))
  34. }
  35. }
  36. }
  37. #[test]
  38. fn reply() {
  39. protocol! {
  40. named ReplyTest;
  41. let states = [
  42. ServerInit, Listening,
  43. Client, Waiting,
  44. ];
  45. ServerInit?Activate -> Listening;
  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::Activate(act)) => assert_type!(act, Activate),
  53. Some(ReplyTestMsgs::Ping(ping)) => assert_type!(ping, Ping),
  54. Some(ReplyTestMsgs::PingReply(reply)) => assert_type!(reply, <Ping as CallMsg>::Reply),
  55. None => (),
  56. }
  57. struct ServerInitState;
  58. impl ServerInit for ServerInitState {
  59. type HandleActivateListening = ListeningState;
  60. type HandleActivateFut = Ready<Result<ListeningState>>;
  61. fn handle_activate(self, _msg: btrun::Activate) -> Self::HandleActivateFut {
  62. ready(Ok(ListeningState))
  63. }
  64. }
  65. struct ListeningState;
  66. impl Listening for ListeningState {
  67. type HandlePingListening = Self;
  68. type HandlePingFut = Ready<Result<Self>>;
  69. fn handle_ping(self, _msg: Ping) -> Self::HandlePingFut {
  70. ready(Ok(self))
  71. }
  72. }
  73. struct ClientState;
  74. impl Client for ClientState {
  75. type SendPingWaiting = WaitingState;
  76. type SendPingFut = Ready<Result<WaitingState>>;
  77. fn send_ping(self) -> Self::SendPingFut {
  78. ready(Ok(WaitingState))
  79. }
  80. }
  81. struct WaitingState;
  82. impl Waiting for WaitingState {
  83. type HandlePingReplyFut = Ready<Result<End>>;
  84. fn handle_ping_reply(self, _msg: Ping) -> Self::HandlePingReplyFut {
  85. ready(Ok(End))
  86. }
  87. }
  88. }