protocol_tests.rs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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];
  53. Client -> Client, >service(Listening)!Ping;
  54. Listening?Ping -> Listening, >Client!Ping::Reply;
  55. }
  56. let msg: Option<ReplyTestMsgs> = None;
  57. match msg {
  58. Some(ReplyTestMsgs::Ping(ping)) => assert_type!(ping, Ping),
  59. Some(ReplyTestMsgs::PingReply(reply)) => assert_type!(reply, <Ping as CallMsg>::Reply),
  60. None => (),
  61. }
  62. struct ListeningState;
  63. impl Listening for ListeningState {
  64. type HandlePingListening = Self;
  65. type HandlePingFut = Ready<Result<(Self, <Ping as CallMsg>::Reply)>>;
  66. fn handle_ping(self, _msg: Ping) -> Self::HandlePingFut {
  67. ready(Ok((self, ())))
  68. }
  69. }
  70. struct ClientState;
  71. impl Client for ClientState {
  72. type SendPingClient = Self;
  73. type SendPingFut = Ready<Result<(Self, <Ping as CallMsg>::Reply)>>;
  74. fn send_ping(self, _ping: Ping) -> Self::SendPingFut {
  75. ready(Ok((self, ())))
  76. }
  77. }
  78. }