@@ -91,11 +91,10 @@ pub fn value_to_otlp_array(values: Vec<Value>) -> OtlpArray {
91
91
pub fn value_to_system_time ( value : & Value ) -> SystemTime {
92
92
match value {
93
93
Value :: Timestamp ( time) => {
94
- let now = SystemTime :: now ( )
95
- . duration_since ( SystemTime :: UNIX_EPOCH )
96
- . unwrap ( ) ;
94
+ let mut now = SystemTime :: now ( ) ;
95
+ let now_unix = now. duration_since ( SystemTime :: UNIX_EPOCH ) . unwrap ( ) ;
97
96
98
- let diff = now
97
+ let diff = now_unix
99
98
- Duration :: from_nanos (
100
99
time. to_owned ( )
101
100
. timestamp_nanos_opt ( )
@@ -104,18 +103,15 @@ pub fn value_to_system_time(value: &Value) -> SystemTime {
104
103
. unwrap ( ) ,
105
104
) ;
106
105
107
- let mut ts = SystemTime :: now ( ) ;
108
- ts. sub_assign ( diff) ;
109
- ts
106
+ now. sub_assign ( diff) ;
107
+ now
110
108
}
111
109
Value :: Integer ( time) => {
112
- let now = SystemTime :: now ( )
113
- . duration_since ( SystemTime :: UNIX_EPOCH )
114
- . unwrap ( ) ;
115
- let diff = now - Duration :: from_millis ( ( * time) . try_into ( ) . unwrap ( ) ) ;
116
- let mut ts = SystemTime :: now ( ) ;
117
- ts. sub_assign ( diff) ;
118
- ts
110
+ let mut now = SystemTime :: now ( ) ;
111
+ let now_unix = now. duration_since ( SystemTime :: UNIX_EPOCH ) . unwrap ( ) ;
112
+ let diff = now_unix - Duration :: from_millis ( ( * time) . try_into ( ) . unwrap ( ) ) ;
113
+ now. sub_assign ( diff) ;
114
+ now
119
115
}
120
116
_ => SystemTime :: now ( ) ,
121
117
}
@@ -230,3 +226,39 @@ pub trait OpentelemetryModelMatch {
230
226
where
231
227
Self : Sized ;
232
228
}
229
+
230
+ #[ cfg( test) ]
231
+ mod test {
232
+
233
+ use super :: * ;
234
+ use chrono:: { NaiveDateTime , TimeZone , Utc } ;
235
+
236
+ #[ test]
237
+ fn test_value_to_system_time_timestamp ( ) {
238
+ let value = Value :: Timestamp (
239
+ Utc . from_utc_datetime (
240
+ & NaiveDateTime :: from_timestamp_opt ( 1_579_134_612_i64 , 11_u32 )
241
+ . expect ( "timestamp should be a valid timestamp" ) ,
242
+ ) ,
243
+ ) ;
244
+
245
+ let expected =
246
+ SystemTime :: UNIX_EPOCH + std:: time:: Duration :: from_nanos ( 1_579_134_612_000_000_011 ) ;
247
+ assert_eq ! ( value_to_system_time( & value) , expected) ;
248
+ }
249
+
250
+ #[ test]
251
+ fn test_value_to_system_time_int ( ) {
252
+ let value = Value :: Integer ( 1_579_134_612 ) ;
253
+
254
+ let expected = SystemTime :: UNIX_EPOCH + std:: time:: Duration :: from_millis ( 1_579_134_612 ) ;
255
+ assert_eq ! ( value_to_system_time( & value) , expected) ;
256
+ }
257
+
258
+ #[ test]
259
+ fn test_value_to_system_time_invalid_default_now ( ) {
260
+ let value = Value :: from ( "invalid" . to_string ( ) ) ;
261
+
262
+ assert ! ( matches!( value_to_system_time( & value) , SystemTime { .. } ) ) ;
263
+ }
264
+ }
0 commit comments