Debian Codegraph @

common/types/timestamp_test.go

raw
1 // Copyright 2018 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package types
16
17 import (
18 "errors"
19 "math"
20 "reflect"
21 "testing"
22 "time"
23
24 "github.com/google/cel-go/common/overloads"
25 "github.com/google/cel-go/common/types/ref"
26
27 "google.golang.org/protobuf/proto"
28
29 anypb "google.golang.org/protobuf/types/known/anypb"
30 structpb "google.golang.org/protobuf/types/known/structpb"
31 tpb "google.golang.org/protobuf/types/known/timestamppb"
32 )
33
34 func TestTimestampConvertToType(t *testing.T) {
35 ts := Timestamp{Time: time.Unix(7654, 321).UTC()}
36 if ts.ConvertToType(TypeType) != TimestampType {
37 t.Errorf("ConvertToType(type) failed to return timestamp type: %v", ts.ConvertToType(TypeType))
38 }
39 if ts.ConvertToType(IntType) != Int(7654) {
40 t.Errorf("ConvertToType(int) failed to truncate a timestamp to a unix epoch: %v", ts.ConvertToType(IntType))
41 }
42 if ts.ConvertToType(StringType) != String("1970-01-01T02:07:34.000000321Z") {
43 t.Errorf("ConvertToType(string) failed to convert to a human readable timestamp. "+
44 "got %v, wanted: 1970-01-01T02:07:34.000000321Z",
45 ts.ConvertToType(StringType))
46 }
47 if ts.ConvertToType(TimestampType) != ts {
48 t.Error("ConvertToType(timestamp) failed an identity conversion")
49 }
50 if !IsError(ts.ConvertToType(DurationType)) {
51 t.Error("ConvertToType(duration) failed to error")
52 }
53 }
54
55 func TestTimestampOperators(t *testing.T) {
56 unixTimestamp := func(epoch int64) Timestamp {
57 return timestampOf(time.Unix(epoch, 0).UTC())
58 }
59 tests := []struct {
60 name string
61 op func() ref.Val
62 out any
63 }{
64 // Addition tests.
65 {
66 name: "DateAddOneHourMinusOneMilli",
67 op: func() ref.Val {
68 return unixTimestamp(3506).Add(durationOf(time.Hour - time.Millisecond))
69 },
70 out: time.Unix(7106, 0).Add(-time.Millisecond).UTC(),
71 },
72 {
73 name: "DateAddOneHourOneNano",
74 op: func() ref.Val {
75 return unixTimestamp(3506).Add(durationOf(time.Hour + time.Nanosecond))
76 },
77 out: time.Unix(7106, 1).UTC(),
78 },
79 {
80 name: "IntMaxAddOneSecond",
81 op: func() ref.Val {
82 return unixTimestamp(math.MaxInt64).Add(durationOf(time.Second))
83 },
84 out: errIntOverflow,
85 },
86 {
87 name: "MaxTimestampAddOneSecond",
88 op: func() ref.Val {
89 return unixTimestamp(maxUnixTime).Add(durationOf(time.Second))
90 },
91 out: errTimestampOverflow,
92 },
93 {
94 name: "MaxIntAddOneViaNanos",
95 op: func() ref.Val {
96 return timestampOf(time.Unix(math.MaxInt64, 999_999_999).UTC()).Add(durationOf(time.Nanosecond))
97 },
98 out: errIntOverflow,
99 },
100 {
101 name: "SecondsWithNanosNegative",
102 op: func() ref.Val {
103 ts1 := unixTimestamp(1).Add(durationOf(time.Nanosecond)).(Timestamp)
104 return ts1.Add(durationOf(-999_999_999))
105 },
106 out: time.Unix(0, 2).UTC(),
107 },
108 {
109 name: "SecondsWithNanosPositive",
110 op: func() ref.Val {
111 ts1 := unixTimestamp(1).Add(durationOf(999_999_999 * time.Nanosecond)).(Timestamp)
112 return ts1.Add(durationOf(999_999_999))
113 },
114 out: time.Unix(2, 999_999_998).UTC(),
115 },
116 {
117 name: "DateAddDateError",
118 op: func() ref.Val {
119 return unixTimestamp(1).Add(unixTimestamp(1))
120 },
121 out: errors.New("no such overload"),
122 },
123
124 // Comparison tests.
125 {
126 name: "DateCompareEqual",
127 op: func() ref.Val {
128 return unixTimestamp(1).Compare(unixTimestamp(1))
129 },
130 out: int64(0),
131 },
132 {
133 name: "DateCompareBefore",
134 op: func() ref.Val {
135 return unixTimestamp(1).Compare(unixTimestamp(200))
136 },
137 out: int64(-1),
138 },
139 {
140 name: "DateCompareAfter",
141 op: func() ref.Val {
142 return unixTimestamp(1000).Compare(unixTimestamp(200))
143 },
144 out: int64(1),
145 },
146 {
147 name: "DateCompareError",
148 op: func() ref.Val {
149 return unixTimestamp(1000).Compare(durationOf(1000))
150 },
151 out: errors.New("no such overload"),
152 },
153
154 // Time subtraction tests.
155 {
156 name: "TimeSubOneSecond",
157 op: func() ref.Val {
158 return unixTimestamp(100).Subtract(unixTimestamp(1))
159 },
160 out: 99 * time.Second,
161 },
162 {
163 name: "DateSubOneHour",
164 op: func() ref.Val {
165 return unixTimestamp(3506).Subtract(durationOf(time.Hour))
166 },
167 out: time.Unix(-94, 0).UTC(),
168 },
169 {
170 name: "MinTimestampSubOneSecond",
171 op: func() ref.Val {
172 return unixTimestamp(-62135596800).Subtract(durationOf(time.Second))
173 },
174 out: errTimestampOverflow,
175 },
176 {
177 name: "MinTimestampSubMinusOneViaNanos",
178 op: func() ref.Val {
179 return timestampOf(time.Unix(-62135596800, 2).UTC()).Subtract(durationOf(-999_999_999 * time.Nanosecond))
180 },
181 out: time.Unix(-62135596799, 1).UTC(),
182 },
183 {
184 name: "MinIntSubOneViaNanosOverflow",
185 op: func() ref.Val {
186 return timestampOf(time.Unix(math.MinInt64, 0).UTC()).Subtract(durationOf(time.Nanosecond))
187 },
188 out: errIntOverflow,
189 },
190 {
191 name: "TimeWithNanosPositive",
192 op: func() ref.Val {
193 return timestampOf(time.Unix(2, 1)).Subtract(timestampOf(time.Unix(0, 999_999_999)))
194 },
195 out: time.Second + 2*time.Nanosecond,
196 },
197 {
198 name: "TimeWithNanosNegative",
199 op: func() ref.Val {
200 return timestampOf(time.Unix(1, 1)).Subtract(timestampOf(time.Unix(2, 999_999_999)))
201 },
202 out: -2*time.Second + 2*time.Nanosecond,
203 },
204 {
205 name: "MinTimestampMinusOne",
206 op: func() ref.Val {
207 return unixTimestamp(math.MinInt64).Subtract(unixTimestamp(1))
208 },
209 out: errIntOverflow,
210 },
211 {
212 name: "DateMinusDateDurationOverflow",
213 op: func() ref.Val {
214 return unixTimestamp(maxUnixTime).Subtract(unixTimestamp(minUnixTime))
215 },
216 out: errIntOverflow,
217 },
218 {
219 name: "MinTimestampMinusOneViaNanosScaleOverflow",
220 op: func() ref.Val {
221 return timestampOf(time.Unix(math.MinInt64, 1)).Subtract(timestampOf(time.Unix(0, -999_999_999)))
222 },
223 out: errIntOverflow,
224 },
225 {
226 name: "DateSubMinDuration",
227 op: func() ref.Val {
228 return unixTimestamp(1).Subtract(durationOf(math.MinInt64))
229 },
230 out: errIntOverflow,
231 },
232 }
233 for _, tst := range tests {
234 got := tst.op()
235 switch v := got.Value().(type) {
236 case time.Time:
237 if want, ok := tst.out.(time.Time); !ok || !v.Equal(want) {
238 t.Errorf("%s: got %v, wanted %v", tst.name, v, tst.out)
239 }
240 case error:
241 if want, ok := tst.out.(error); !ok || v.Error() != want.Error() {
242 t.Errorf("%s: got %v, wanted %v", tst.name, v, tst.out)
243 }
244 default:
245 if !reflect.DeepEqual(v, tst.out) {
246 t.Errorf("%s: got %v, wanted %v", tst.name, v, tst.out)
247 }
248 }
249 }
250 }
251
252 func TestTimestampConvertToNative_Any(t *testing.T) {
253 // 1970-01-01T02:05:06Z
254 ts := Timestamp{Time: time.Unix(7506, 0)}
255 val, err := ts.ConvertToNative(anyValueType)
256 if err != nil {
257 t.Error(err)
258 }
259 want, err := anypb.New(tpb.New(ts.Time))
260 if err != nil {
261 t.Error(err)
262 }
263 if !proto.Equal(val.(proto.Message), want) {
264 t.Errorf("Got '%v', expected '%v'", val, want)
265 }
266 }
267
268 func TestTimestampConvertToNative(t *testing.T) {
269 // 1970-01-01T02:05:06Z
270 ts := Timestamp{Time: time.Unix(7506, 0).UTC()}
271 val, err := ts.ConvertToNative(timestampValueType)
272 if err != nil {
273 t.Error(err)
274 }
275 var want any
276 want = tpb.New(ts.Time)
277 if !proto.Equal(val.(proto.Message), want.(proto.Message)) {
278 t.Errorf("Got '%v', expected '%v'", val, want)
279 }
280 val, err = ts.ConvertToNative(JSONValueType)
281 if err != nil {
282 t.Error(err)
283 }
284 want = structpb.NewStringValue("1970-01-01T02:05:06Z")
285 if !proto.Equal(val.(proto.Message), want.(proto.Message)) {
286 t.Errorf("Got '%v', expected '%v'", val, want)
287 }
288 val, err = ts.ConvertToNative(anyValueType)
289 if err != nil {
290 t.Error(err)
291 }
292 want, err = anypb.New(tpb.New(ts.Time))
293 if err != nil {
294 t.Error(err)
295 }
296 if !proto.Equal(val.(proto.Message), want.(proto.Message)) {
297 t.Errorf("Got '%v', expected '%v'", val, want)
298 }
299 val, err = ts.ConvertToNative(reflect.TypeOf(Timestamp{}))
300 if err != nil {
301 t.Error(err)
302 }
303 if !reflect.DeepEqual(val, ts) {
304 t.Errorf("got %v wanted %v", val, ts)
305 }
306 val, err = ts.ConvertToNative(reflect.TypeOf(time.Now()))
307 if err != nil {
308 t.Error(err)
309 }
310 want = time.Unix(7506, 0).UTC()
311 if !reflect.DeepEqual(val, want) {
312 t.Errorf("got %v wanted %v", val, want)
313 }
314 }
315
316 func TestTimestampIsZeroValue(t *testing.T) {
317 if (Timestamp{Time: time.Now()}).IsZeroValue() {
318 t.Error("Timestamp(Now()).IsZeroValue() returned true, wanted false.")
319 }
320 if (Timestamp{Time: time.Unix(0, 0)}).IsZeroValue() {
321 t.Error("Timestamp(0).IsZeroValue() returned true, wanted false.")
322 }
323 }
324
325 func TestTimestampGetDayOfMonth(t *testing.T) {
326 // 1970-01-01T02:05:06Z
327 ts := timestampOf(time.Unix(7506, 0).UTC())
328 mon := ts.Receive(overloads.TimeGetDayOfMonth, overloads.TimestampToDayOfMonthZeroBased, []ref.Val{})
329 if !mon.Equal(Int(0)).(Bool) {
330 t.Errorf("ts.getDayOfMonth() got %v, wanted 0", mon)
331 }
332 // 1969-12-31T19:05:06Z
333 monTz := ts.Receive(overloads.TimeGetDayOfMonth, overloads.TimestampToDayOfMonthZeroBasedWithTz,
334 []ref.Val{String("America/Phoenix")})
335 if !monTz.Equal(Int(30)).(Bool) {
336 t.Errorf("ts.getDayOfMonth() got %v, wanted 30", mon)
337 }
338 // 1969-12-31T19:05:06Z
339 monTz = ts.Receive(overloads.TimeGetDayOfMonth, overloads.TimestampToDayOfMonthZeroBasedWithTz,
340 []ref.Val{String("-07:00")})
341 if !monTz.Equal(Int(30)).(Bool) {
342 t.Errorf("ts.getDayOfMonth() got %v, wanted 30", mon)
343 }
344
345 // 1970-01-01T02:05:06Z
346 mon = ts.Receive(overloads.TimeGetDate, overloads.TimestampToDayOfMonthOneBased, []ref.Val{})
347 if !mon.Equal(Int(1)).(Bool) {
348 t.Errorf("ts.getDate() got %v, wanted 1", mon)
349 }
350 // 1969-12-31T19:05:06Z
351 monTz = ts.Receive(overloads.TimeGetDate, overloads.TimestampToDayOfMonthOneBasedWithTz,
352 []ref.Val{String("America/Phoenix")})
353 if !monTz.Equal(Int(31)).(Bool) {
354 t.Errorf("ts.getDate() got %v, wanted 31", mon)
355 }
356 // 1970-01-02T01:05:06Z
357 monTz = ts.Receive(overloads.TimeGetDate, overloads.TimestampToDayOfMonthOneBasedWithTz,
358 []ref.Val{String("+23:00")})
359 if !monTz.Equal(Int(2)).(Bool) {
360 t.Errorf("ts.getDate() got %v, wanted 2", mon)
361 }
362 }
363
364 func TestTimestampGetDayOfYear(t *testing.T) {
365 // 1970-01-01T02:05:06Z
366 ts := timestampOf(time.Unix(7506, 0).UTC())
367 hr := ts.Receive(overloads.TimeGetDayOfYear, overloads.TimestampToDayOfYear, []ref.Val{})
368 if !hr.Equal(Int(0)).(Bool) {
369 t.Error("Expected 0, got", hr)
370 }
371 // 1969-12-31T19:05:06Z
372 hrTz := ts.Receive(overloads.TimeGetDayOfYear, overloads.TimestampToDayOfYearWithTz,
373 []ref.Val{String("America/Phoenix")})
374 if !hrTz.Equal(Int(364)).(Bool) {
375 t.Error("Expected 364, got", hrTz)
376 }
377 hrTz = ts.Receive(overloads.TimeGetDayOfYear, overloads.TimestampToDayOfYearWithTz,
378 []ref.Val{String("-07:00")})
379 if !hrTz.Equal(Int(364)).(Bool) {
380 t.Error("Expected 364, got", hrTz)
381 }
382 }
383
384 func TestTimestampGetFullYear(t *testing.T) {
385 // 1970-01-01T02:05:06Z
386 ts := Timestamp{Time: time.Unix(7506, 0).UTC()}
387 year := ts.Receive(overloads.TimeGetFullYear, overloads.TimestampToYear, []ref.Val{})
388 if !year.Equal(Int(1970)).(Bool) {
389 t.Errorf("ts.getFullYear() got %v, wanted 1970", year)
390 }
391 // 1969-12-31T19:05:06Z
392 yearTz := ts.Receive(overloads.TimeGetFullYear, overloads.TimestampToYearWithTz,
393 []ref.Val{String("America/Phoenix")})
394 if !yearTz.Equal(Int(1969)).(Bool) {
395 t.Errorf("ts.getFullYear('America/Phoenix') got %v, wanted 1969", yearTz)
396 }
397 }
398
399 func TestTimestampGetMonth(t *testing.T) {
400 // 1970-01-01T02:05:06Z
401 ts := Timestamp{Time: time.Unix(7506, 0).UTC()}
402 hr := ts.Receive(overloads.TimeGetMonth, overloads.TimestampToMonth, []ref.Val{})
403 if !hr.Equal(Int(0)).(Bool) {
404 t.Errorf("ts.getMonth() got %v, wanted 0", hr)
405 }
406 // 1969-12-31T19:05:06Z
407 hrTz := ts.Receive(overloads.TimeGetMonth, overloads.TimestampToMonthWithTz,
408 []ref.Val{String("America/Phoenix")})
409 if !hrTz.Equal(Int(11)).(Bool) {
410 t.Errorf("ts.getMonth('America/Phoenix') got %v, wanted 11", hrTz)
411 }
412 }
413
414 func TestTimestampGetDayOfWeek(t *testing.T) {
415 // 1970-01-01T02:05:06Z
416 ts := Timestamp{Time: time.Unix(7506, 0).UTC()}
417 day := ts.Receive(overloads.TimeGetDayOfWeek, overloads.TimestampToDayOfWeek, []ref.Val{})
418 if !day.Equal(Int(4)).(Bool) {
419 t.Errorf("ts.getDayOfWeek() got %v, wanted 4", day)
420 }
421 // 1969-12-31T19:05:06Z
422 dayTz := ts.Receive(overloads.TimeGetDayOfWeek, overloads.TimestampToDayOfWeekWithTz,
423 []ref.Val{String("America/Phoenix")})
424 if !dayTz.Equal(Int(3)).(Bool) {
425 t.Errorf("ts.getDayOfWeek('America/Phoenix') got %v, wanted 3", dayTz)
426 }
427 }
428
429 func TestTimestampGetHours(t *testing.T) {
430 // 1970-01-01T02:05:06Z
431 ts := Timestamp{Time: time.Unix(7506, 0).UTC()}
432 hr := ts.Receive(overloads.TimeGetHours, overloads.TimestampToHours, []ref.Val{})
433 if !hr.Equal(Int(2)).(Bool) {
434 t.Errorf("ts.getHours() got %v, wanted 2", hr)
435 }
436 // 1969-12-31T19:05:06Z
437 hrTz := ts.Receive(overloads.TimeGetHours, overloads.TimestampToHoursWithTz,
438 []ref.Val{String("America/Phoenix")})
439 if !hrTz.Equal(Int(19)).(Bool) {
440 t.Errorf("ts.getHours('America/Phoenix') got %v, wanted 19 hours", hrTz)
441 }
442 }
443
444 func TestTimestampGetMinutes(t *testing.T) {
445 // 1970-01-01T02:05:06Z
446 ts := Timestamp{Time: time.Unix(7506, 0).UTC()}
447 min := ts.Receive(overloads.TimeGetMinutes, overloads.TimestampToMinutes, []ref.Val{})
448 if !min.Equal(Int(5)).(Bool) {
449 t.Errorf("ts.getMinutes() got %v, wanted 5 minutes", min)
450 }
451 // 1969-12-31T19:05:06Z
452 minTz := ts.Receive(overloads.TimeGetMinutes, overloads.TimestampToMinutesWithTz,
453 []ref.Val{String("America/Phoenix")})
454 if !minTz.Equal(Int(5)).(Bool) {
455 t.Errorf("ts.getMinutes('America/Phoenix') got %v, wanted 5 minutes", min)
456 }
457 }
458
459 func TestTimestampGetSeconds(t *testing.T) {
460 // 1970-01-01T02:05:06Z
461 ts := Timestamp{Time: time.Unix(7506, 0).UTC()}
462 sec := ts.Receive(overloads.TimeGetSeconds, overloads.TimestampToSeconds, []ref.Val{})
463 if !sec.Equal(Int(6)).(Bool) {
464 t.Errorf("ts.getSeconds() got %v, wanted 6 seconds", sec)
465 }
466 // 1969-12-31T19:05:06Z
467 secTz := ts.Receive(overloads.TimeGetSeconds, overloads.TimestampToSecondsWithTz,
468 []ref.Val{String("America/Phoenix")})
469 if !secTz.Equal(Int(6)).(Bool) {
470 t.Errorf("ts.getSeconds('America/Phoenix') got %v, wanted 6 seconds", secTz)
471 }
472 }
473
474 func TestTimestampGetMilliseconds(t *testing.T) {
475 // 1970-01-01T02:05:06Z
476 ts := Timestamp{Time: time.Unix(7506, 1000000).UTC()}
477 ms := ts.Receive(overloads.TimeGetMilliseconds, overloads.TimestampToMilliseconds, []ref.Val{})
478 if !ms.Equal(Int(1)).(Bool) {
479 t.Errorf("ts.getMilliseconds() got %v, wanted 1 ms", ms)
480 }
481 // 1969-12-31T19:05:06Z
482 msTz := ts.Receive(overloads.TimeGetMilliseconds, overloads.TimestampToMillisecondsWithTz,
483 []ref.Val{String("America/Phoenix")})
484 if !msTz.Equal(Int(1)).(Bool) {
485 t.Errorf("ts.getMilliseconds('America/Phoenix') got %v, wanted 1 ms", msTz)
486 }
487 }