@dashevo/dapi-grpc 1.0.0-dev.4 → 1.0.0-dev.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/lib.rs CHANGED
@@ -22,3 +22,9 @@ pub mod platform {
22
22
  #[cfg(feature = "serde")]
23
23
  // Serde deserialization logic
24
24
  pub mod deserialization;
25
+
26
+ // We need mock module even if the feature is disabled
27
+ pub mod mock;
28
+
29
+ // Re-export tonic to ensure everyone uses the same version
30
+ pub use tonic;
package/src/mock.rs ADDED
@@ -0,0 +1,68 @@
1
+ //! Mocking support for messages.
2
+ //!
3
+ //! Contains [Mockable] trait that should be implemented by any object that can be used in the DAPI.
4
+ //!
5
+ //! Note that this trait is defined even if mocks are not supported, but it should always return `None` on serialization.
6
+ use tonic::Streaming;
7
+
8
+ /// Mocking support for messages.
9
+ ///
10
+ /// This trait should be implemented by any object that can be used in the DAPI.
11
+ ///
12
+ /// We use serde_json to serialize/deserialize messages.
13
+ // TODO: Move to a different crate where it can be easily shared by dapi-grpc, dash-platform-sdk, and rs-dapi-client.
14
+ pub trait Mockable
15
+ where
16
+ Self: std::marker::Sized,
17
+ {
18
+ /// Serialize the message to bytes for mocking purposes.
19
+ ///
20
+ /// Returns None if the message is not serializable or mocking is disabled.
21
+ ///
22
+ /// # Panics
23
+ ///
24
+ /// Panics on any error.
25
+ fn mock_serialize(&self) -> Option<Vec<u8>> {
26
+ None
27
+ }
28
+ /// Deserialize the message serialized with [mock_serialize()].
29
+ ///
30
+ /// Returns None if the message is not serializable or mocking is disabled.
31
+ ///
32
+ /// # Panics
33
+ ///
34
+ /// Panics on any error.
35
+ fn mock_deserialize(_data: &[u8]) -> Option<Self> {
36
+ None
37
+ }
38
+ }
39
+
40
+ impl<T: Mockable> Mockable for Option<T> {
41
+ #[cfg(feature = "mocks")]
42
+ fn mock_serialize(&self) -> Option<Vec<u8>> {
43
+ self.as_ref().and_then(|value| value.mock_serialize())
44
+ }
45
+
46
+ #[cfg(feature = "mocks")]
47
+ fn mock_deserialize(data: &[u8]) -> Option<Self> {
48
+ T::mock_deserialize(data).map(Some)
49
+ }
50
+ }
51
+
52
+ impl Mockable for Vec<u8> {
53
+ #[cfg(feature = "mocks")]
54
+ fn mock_serialize(&self) -> Option<Vec<u8>> {
55
+ serde_json::to_vec(self).ok()
56
+ }
57
+
58
+ #[cfg(feature = "mocks")]
59
+ fn mock_deserialize(data: &[u8]) -> Option<Self> {
60
+ serde_json::from_slice(data).ok()
61
+ }
62
+ }
63
+
64
+ /// Mocking of gRPC streaming responses is not supported.
65
+ ///
66
+ /// This will return `None` on serialization,
67
+ /// effectively disabling mocking of streaming responses.
68
+ impl<T: Mockable> Mockable for Streaming<T> {}